liveBook · Manning

Assertion

As explained in Practices of the Python Pro

A software assertion is an executable check of an expected condition or property that signals failure when the check does not hold.

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

How Practices of the Python Pro covers it

How deep it goes
Explains Boolean conditions, silent success, AssertionError failure, and testing-tool usage without descending into implementation internals.
Examples
Demonstrates calculate_mean checks, Product SKU tests, ShoppingCart outcomes, dictionary comparisons, and pytest test-run output.
What it assumes
Assumes basic Python expressions and function calls while teaching expected-versus-actual comparison through testing examples.
What you can do after
Apply raw assertions in Python tests and migrate unittest comparisons to concise pytest expressions.
How it connects
Connects assertions with functional testing, unittest, pytest, AssertionError, and expected-versus-actual comparison.

Also explained in

Compare how 15 books explain assertion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.