Sub topic 4
Checking results with plain assert
This chapter assumes you can write Python functions, run pytest from a terminal inside a virtual environment, and read a basic traceback. You should also know that assert is a Python statement and that tests are functions named test_* in files named test_*.py. The earlier chapters on discovery and running cover those details.
One statement, no assertion API
Many testing libraries give you a family of methods such as assertEqual, assertIn and assertIsNone. pytest does not. You write the Python statement assert followed by an expression, and the test fails if the expression is falsy.
# cart.py
def total(prices, tax_rate=0.0):
if tax_rate < 0:
raise ValueError("tax_rate must be non-negative")
return sum(prices) * (1 + tax_rate)# test_cart.py
from cart import total
def test_total_without_tax():
assert total([10, 20]) == 30
def test_total_of_nothing_is_zero():
assert total([]) == 0A passing assertion produces no output. A failing one raises AssertionError, and pytest marks that test as failed. Other tests still run.
Why the failure messages are detailed
A bare assert in normal Python tells you almost nothing when it fails. It shows AssertionError and the line, but not the values involved. pytest fixes this with assertion rewriting. When it imports a test module, it rewrites the module's syntax tree. Each assert becomes code that saves the intermediate values of the expression, so a failure can print them.
# test_introspection.py
def double(n):
return n * 3 # deliberate bug
def test_double():
assert double(4) == 8Running pytest test_introspection.py prints something like this for the failure:
def test_double():
> assert double(4) == 8
E assert 12 == 8
E + where 12 = double(4)You see the actual value, the expected value, and the call that produced the actual value. You did not write a message or call a special method.
What the report shows for common types
pytest has specialized comparison output for several built-in types.
| Comparison | What the failure shows |
|---|---|
| Strings | The first differing position, and a line-by-line diff for multiline text |
| Lists and tuples | The first differing index, and a note when lengths differ |
| Dicts | Keys that differ, keys present on only one side, and values that differ |
| Sets | Items present on only one side |
| Dataclasses and attrs classes | The fields that differ |
Here is a dictionary comparison that fails:
# test_dicts.py
def build_user():
return {"name": "ada", "role": "admin", "active": False}
def test_build_user():
expected = {"name": "ada", "role": "admin", "active": True}
assert build_user() == expectedThe report names active as the differing key and prints both values. It leaves out the keys that matched.
pytest truncates long output by default. Run pytest -vv to see the full diff of large lists, dicts and strings.
Asserting more than equality
Any expression works, so you use the operator that states the intent.
# test_checks.py
def test_membership():
names = ["ada", "grace", "linus"]
assert "grace" in names
assert "bob" not in names
def test_identity_and_none():
result = {}.get("missing")
assert result is None
def test_type_and_truthiness():
items = [1, 2]
assert isinstance(items, list)
assert items # non-empty list is truthy
def test_string_properties():
message = "Order #42 shipped"
assert message.startswith("Order")
assert "42" in messageSome conventions keep failures easy to read:
- Put the computed value on the left and the expected value on the right. The report labels the sides, and consistency makes it faster to read.
- Use
is Noneandis not NoneforNone. Use==for values. - Write
assert xandassert not xinstead ofassert x == True. The longer form hides what you mean and fails with a less useful message. - Use
infor membership. When it fails on a long collection, pytest shows the collection.
Adding your own message
You can attach text after a comma:
def test_inventory_never_negative():
stock = {"apples": 3}
assert stock["apples"] >= 0, "stock must never go below zero"The message appears in the report next to the introspection output. Add one when the expression alone does not say why it matters. Do not add one that only repeats the expression. Putting the values into an f-string is rarely needed, because pytest already shows them.
Gotchas
A tuple is always truthy
def test_oops():
assert (1 == 2, "values differ") # always passesThe parentheses make this a non-empty tuple, and a non-empty tuple is truthy. Python emits a SyntaxWarning for this form. pytest also reports it as a warning. Write assert 1 == 2, "values differ" without parentheses.
Rewriting only covers certain modules
pytest rewrites test modules, conftest.py files and registered plugins. It does not rewrite ordinary helper modules that tests import. An assert inside a shared helpers.py therefore gives the plain Python failure with no introspection. If you keep assertion helpers in a separate module, register it before it is imported:
# conftest.py
import pytest
pytest.register_assert_rewrite("helpers")The first failure ends the test
When a test has several assert statements, the first failing one stops the test. Later checks do not run, so you may fix one failure and then meet the next. Either accept that, or split unrelated checks into separate tests. Parametrization, covered in a later chapter, is the usual way to do this for many inputs.
Side effects inside the assert
Never put work you depend on inside the assert expression. For example, assert queue.pop() == "a" is fine in a test, because the test needs the pop either way. But code that is only called from within an assert is lost if assertions are disabled. Python's -O flag removes assert statements from code that pytest does not rewrite. Keep production logic out of assertions, and store results in a variable first when the expression has side effects.
Floats and exceptions need other tools
assert 0.1 + 0.2 == 0.3 fails because of binary floating-point rounding. Use pytest.approx, covered in its own chapter. To check that code raises an error, use pytest.raises rather than try/except with assert.
Turning the output up or down
Two options change how much pytest tells you about an assertion:
pytest -vvincreases verbosity and shows full diffs.pytest --assert=plainturns rewriting off, which restores the bare Python behavior. You rarely want this. It is mostly useful when you suspect rewriting is interfering with something unusual, such as code that inspects its own bytecode.
Putting it together
A good assertion states one fact, uses the operator that names that fact, and fails with the values visible. When a test needs a message to be understood, that often means the test is checking too much, and splitting it gives better results than adding text.
Exercise
This test passes, but it should fail because total([1, 2]) returns 3, not 4. Why does it pass, and how do you fix it?
from cart import total
def test_total():
assert (total([1, 2]) == 4, "wrong total")
Show answer
The parentheses create a two-element tuple, and a non-empty tuple is always truthy, so the assertion never checks the comparison. pytest and Python only emit a warning. Remove the parentheses: assert total([1, 2]) == 4, "wrong total". The test then fails and reports that 3 does not equal 4.
Exercise
You move a function check_order(order) containing several assert statements into helpers.py. Failures from it now show only a bare AssertionError with no values. What is the cause and the fix?
Show answer
pytest rewrites asserts only in test modules, conftest.py files and registered plugins, not in ordinary helper modules. Call pytest.registerassertrewrite("helpers") in conftest.py, before helpers is imported, so that module's assert statements are rewritten and show the intermediate values.