Sub topic 1
What Unit Tests Are and Why Use pytest
Prerequisites
This chapter assumes that you can write Python functions, import modules, handle exceptions, and run commands inside a virtual environment.
A unit test checks one small behavior of a program, such as a function returning the right value for a given input. Tests turn expected behavior into executable documentation. They also catch regressions, which are bugs introduced when existing code changes.
pytest is a Python testing framework. It uses ordinary Python functions and the built-in assert statement, so tests stay compact. It also provides tools for exceptions, fixtures, parametrization, and test isolation.
Writing Your First Tests and How pytest Finds Them
Create a module containing the behavior under test:
# 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)Put tests in a file such as test_cart.py. By default, pytest looks for test_*.py and *_test.py. It collects functions whose names start with test_.
# test_cart.py
import pytest
from cart import total
def test_total_without_tax():
assert total([10, 20]) == 30
def test_negative_tax_rate_is_rejected():
with pytest.raises(ValueError, match="non-negative"):
total([1], tax_rate=-0.5)The diagram shows the path from source code to a test result.
Running pytest and Reading the Output
Install pytest in the active virtual environment, then run it from the project directory:
python -m pip install pytest
pytest -vThe -v option means verbose. A passing test is shown with PASSED; a failing test is shown with FAILED. For a failure, read the assertion comparison and the traceback. Pytest displays the actual and expected values, which often identifies the defect directly.
Checking Results with Plain `assert`
Python's assert statement checks that an expression is true. If it is false, pytest reports useful details:
def test_total_sums_prices():
result = total([1, 2, 3])
assert result == 6Keep one clear behavior in each test. Give tests names that describe the expected result.
Testing Expected Errors with `pytest.raises`
Use pytest.raises when invalid input should raise an exception. The match argument checks text in the exception message, making the test more precise.
Exercise
Which pytest naming rule allows the test function test_total_without_tax to be collected automatically?
Show answer
Its name starts with test_, and it is in a file matching pytest's default test-file patterns.