Sub topic 4
Checking results with plain assert
This chapter assumes you can write Python functions, run pytest from a terminal, and have a test file that pytest discovers. It uses the cart.py module from earlier in the tutorial.
Why plain assert works
A test passes if it finishes without raising an exception. The assert statement raises AssertionError when its expression is false. So a test is a function that calls your code and asserts something about the result.
Other frameworks, such as unittest, ask you to learn a method for each comparison: assertEqual, assertTrue, assertIn, and so on. In pytest you write the Python expression you mean.
# test_cart.py
from cart import total
def test_total_without_tax():
assert total([10, 20]) == 30
def test_total_of_empty_cart_is_zero():
assert total([]) == 0Assertion introspection
Python's own assert only tells you that something was false. Pytest rewrites the assert statements in your test modules when it imports them. When one fails, the report includes the values of the sub-expressions.
Change the expected value to 31 and run the test:
> assert total([10, 20]) == 31
E assert 30 == 31
E + where 30 = total([10, 20])You see the actual value, the expected value, and the call that produced the actual value. You did not write a failure message.
For lists, dictionaries, sets, and strings, pytest also shows what differs, such as the first index where two lists disagree.
Common assertion forms
| You want to check | Write |
|---|---|
| Equality | `assert result == expected` |
| Inequality | `assert result != other` |
| Membership | `assert "ada" in names` |
| Truthiness | `assert items` or `assert not items` |
| Identity with `None` | `assert value is None` |
| Type | `assert isinstance(result, float)` |
Compare against None with is, not ==. Compare booleans by truthiness: assert flag reads better than assert flag == True.
Adding a message
You can attach text to an assertion. It appears next to pytest's own detail.
from cart import total
def test_total_is_never_negative():
prices = [5, 10]
assert total(prices) >= 0, f"unexpected negative total for {prices}"Use messages only when the failure would otherwise be unclear. Pytest's default output is usually enough.
Common errors
- Asserting a tuple.
assert (x == 1, "message")is always true, because a non-empty tuple is truthy. Writeassert x == 1, "message". - Several checks in one test. The first failing assert stops the test, so later checks never run. Keep one behavior per test.
- Asserting on floats.
0.1 + 0.2 == 0.3is false in Python. The next chapters coverpytest.approxfor this. - Running Python with
-O. This flag removes assert statements, and the tests then pass without checking anything. Don't run tests with it.
What assert does not cover
Plain assert checks values. It cannot check that a function raised an exception, because the exception stops the test first. That needs pytest.raises, which comes next.
Exercise
A teammate writes assert (total([1, 2]) == 4, "wrong total"). The correct total is 3. Does the test fail? Why, and how do you fix it?
Show answer
It passes, which is a bug. The parentheses create a two-item tuple, and a non-empty tuple is always truthy, so the assertion never evaluates to false. Remove the parentheses: assert total([1, 2]) == 4, "wrong total". The test then fails as intended, because 3 is not 4.