you could use Python built-in capability to show custom exception message:

assert response.status_code == 200, f"My custom msg: actual status code {response.status_code}"

Or you can built a helper assert functions:

def assert_status(response, status=200):  # you can assert other status codes too
    assert response.status_code == status, \
        f"Expected {status}. Actual status {response.status_code}. Response text {response.text}"

# here is how you'd use it
def test_api_call(self, client):
    response = client.get(reverse('api:my_api_call'))
    assert_status(response)

also checkout: https://wiki.python.org/moin/UsingAssertionsEffectively

Answer from Dmitry Tokarev on Stack Overflow
🌐
Real Python
realpython.com › python-assert-statement
Python's assert: Debug and Test Your Code Like a Pro – Real Python
January 12, 2025 - In this tutorial, you'll learn how to use Python's assert statement to document, debug, and test code in development. You'll learn how assertions might be disabled in production code, so you shouldn't use them to validate data. You'll also learn about a few common pitfalls of assertions in Python.
🌐
W3Schools
w3schools.com › python › ref_keyword_assert.asp
Python assert Keyword
x = "welcome" #if condition returns False, AssertionError is raised: assert x != "welcome", "x should not be 'welcome'" Try it Yourself » ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-assert-keyword
Python assert keyword - GeeksforGeeks
July 11, 2025 - This code is trying to demonstrate the use of assert in Python by checking whether the value of b is 0 before performing a division operation. a is initialized to the value 4, and b is initialized to the value 0. The program prints the message "The value of a / b is: ".The assert statement checks whether b is not equal to 0. Since b is 0, the assert statement fails and raises an AssertionError with the message "Zero Division Error".
🌐
Python
wiki.python.org › moin › UsingAssertionsEffectively
UsingAssertionsEffectively - Python Wiki
Instead, you should raise an exception, or print an error message, or whatever is appropriate. One important reason why assertions should only be used for self-tests of the program is that assertions can be disabled at compile time. If Python is started with the -O option, then assertions will be stripped out and not evaluated.
🌐
Programiz
programiz.com › python-programming › assert-statement
Python Assert Statement
In Python we can use assert statement in two ways as mentioned above. assert statement has a condition and if the condition is not satisfied the program will stop and give AssertionError. assert statement can also have a condition and a optional error message.
🌐
Hyperskill
hyperskill.org › university › python › assert-statements-in-python
Assert Statements in Python
August 2, 2024 - If the condition x > 10 is false, an AssertionError is raised with the message "x should be greater than 10".
Find elsewhere
🌐
pytest
docs.pytest.org › en › 7.1.x › how-to › assert.html
How to write and report assertions in tests — pytest documentation
$ pytest test_assert1.py =========================== test session starts ============================ platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y rootdir: /home/sweet/project collected 1 item test_assert1.py F [100%] ================================= FAILURES ================================= ______________________________ test_function _______________________________ def test_function(): > assert f() == 4 E assert 3 == 4 E + where 3 = f() test_assert1.py:6: AssertionError ========================= short test summary info ========================== FAILED test_assert1.py::test_f
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › statements › assert.html
assert — Python Reference (The Right Way) 0.1 documentation
The value for the built-in variable is determined when the interpreter starts. >>> assert 2 + 2 == 4 >>> assert 2 + 2 == 3 Traceback (most recent call last): File "<interactive input>", line 1, in <module> AssertionError · >>> assert 1 == False, "That can't be right." Traceback (most recent call last): File "<interactive input>", line 1, in <module> AssertionError: That can't be right.
🌐
AskPython
askpython.com › home › 2 approaches to using assert to validate the type of variable
2 Approaches to Using Assert to Validate the Type of Variable - AskPython
April 10, 2025 - Then we use the assert keyword to determine if the type of the variable x is int or not. If the type is int, True is printed else, the error statement Variable is not of type int! is displayed on the screen.
🌐
Stack Abuse
stackabuse.com › the-python-assert-statement
The Python Assert Statement
July 9, 2020 - Here is an example of an assert statement with a more meaningful condition. Let's assume that we want to ensure that a flag variable input by the user has been set to one of several correct values. If not, we will terminate execution of the program. We can do that as follows: >>> flag = input("Enter a flag (y/n): ") Enter a flag (y/n): y >>> assert flag == "y" or flag == "n", "Invalid flag, must be 'y' or 'n'"
🌐
Towards Data Science
towardsdatascience.com › home › latest › python assert statement – everything you need to know explained in 5 minutes
Python Assert Statement - Everything You Need To Know Explained in 5 Minutes | Towards Data Science
January 16, 2025 - It must be followed by a condition, and you can optionally put a message that gets printed if the condition evaluates to false. ... Let’s leave Megan alone for now and focus on an even simpler example.
🌐
BrowserStack
browserstack.com › home › guide › assert in python: what is it and how to use it
Assert in Python: What is it and How to use it | BrowserStack
July 4, 2025 - In Python, the assert statement is a built-in construct that allows you to test assumptions about your code. It acts as a sanity check to ensure that certain conditions are met during the execution of a program.
Top answer
1 of 16
1769

The assert statement exists in almost every programming language. It has two main uses:

  1. It helps detect problems early in your program, where the cause is clear, rather than later when some other operation fails. A type error in Python, for example, can go through several layers of code before actually raising an Exception if not caught early on.

  2. It works as documentation for other developers reading the code, who see the assert and can confidently say that its condition holds from now on.

When you do...

assert condition

... you're telling the program to test that condition, and immediately trigger an error if the condition is false.

In Python, it's roughly equivalent to this:

if not condition:
    raise AssertionError()

Try it in the Python shell:

>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

Assertions can include an optional message, and you can disable them when running the interpreter.

To print a message if the assertion fails:

assert False, "Oh no! This assertion failed!"

Do not use parenthesis to call assert like a function. It is a statement. If you do assert(condition, message) you'll be running the assert with a (condition, message) tuple as first parameter.

As for disabling them, when running python in optimized mode, where __debug__ is False, assert statements will be ignored. Just pass the -O flag:

python -O script.py

See here for the relevant documentation.

2 of 16
632

Watch out for the parentheses. As has been pointed out in other answers, in Python 3, assert is still a statement, so by analogy with print(..), one may extrapolate the same to assert(..) or raise(..) but you shouldn't.

This is wrong:

assert(2 + 2 == 5, "Houston we've got a problem")

This is correct:

assert 2 + 2 == 5, "Houston we've got a problem"

The reason the first one will not work is that bool( (False, "Houston we've got a problem") ) evaluates to True.

In the statement assert(False), these are just redundant parentheses around False, which evaluate to their contents. But with assert(False,) the parentheses are now a tuple, and a non-empty tuple evaluates to True in a boolean context.

🌐
Tutorial Teacher
tutorialsteacher.com › python › python-assert
Python Assert Statement
In the above example, the division() function contains the assert statement to check whether the y parameter is zero or not. If the assert condition y!=0 evalutes to be True, then it will continue to execute the next statement without any error. If it is true then it will raise an AssertionError with the error message y cannot be zero.
🌐
pytest
docs.pytest.org › en › stable › how-to › assert.html
How to write and report assertions in tests - pytest documentation
$ pytest test_assert1.py =========================== test session starts ============================ platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y rootdir: /home/sweet/project collected 1 item test_assert1.py F [100%] ================================= FAILURES ================================= ______________________________ test_function _______________________________ def test_function(): > assert f() == 4 E assert 3 == 4 E + where 3 = f() test_assert1.py:6: AssertionError ========================= short test summary info ========================== FAILED test_assert1.py::test_f
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-assertion-error
Assertion Error - Python - GeeksforGeeks
July 12, 2025 - If y is zero, it raises an AssertionError with the message "Invalid Operation: Denominator cannot be 0". If the condition were true, the program would proceed to print the result of x / y. The default exception handler in python will print the error_message written by the programmer, or else will just handle the error without any message, both the ways are valid.
🌐
promptfoo
promptfoo.dev › assertions & metrics › python
Python assertions | Promptfoo
For an overview of all Python integrations (providers, assertions, test generators, prompts), see the Python integration guide. A variable named output is injected into the context. The function should return true if the output passes the assertion, ...