An assert states that an expression must be true. When the condition is false, Python fails loudly with an AssertionError; when it passes, it produces no output. section 5.3
Think of an assert as a checkpoint: it records an assumption and immediately alerts you when the assumption no longer holds. This makes it useful for comparing expected and actual results in tests. section 5.3
Use assertions to:
- Check a calculation against an expected value, such as the mean of a list. section 5.3
- Test different outcomes for application methods, including dictionary results and shopping-cart behavior. section 5.4.6
- Write concise pytest tests with direct comparisons instead of unittest assertion methods. section 5.5 section 5.5.2
A passing and failing check
>>> assert 10.0 == calculate_mean([0, 10, 20]) >>> assert 1.0 == calculate_mean([1000, 3500, 7_000_000]) Traceback (most recent call last): AssertionError The first assertion passes silently; the second exposes a mismatch between the expected and actual result. section 5.3
Listing 5.4. A test case in pytest
class TestProduct: #1
def test_transform_name_for_sku(self):
small_black_shoes = Product('shoes', 'S', 'black')
assert small_black_shoes.transform_name_for_sku() == 'SHOES' #2
def test_transform_color_for_sku(self):
small_black_shoes = Product('shoes', 'S', 'black')
assert small_black_shoes.transform_color_for_sku() == 'BLACK'
def test_generate_sku(self):
small_black_shoes = Product('shoes', 'S', 'black')
assert small_black_shoes.generate_sku() == 'SHOES-S-BLACK'
Compare short pytest tests that assert Product methods return the expected SKU components and complete SKU. section 5.5.2














