Sub topic 1
What unit tests are and why use pytest
Prerequisites
This chapter assumes you can write Python functions and classes, import modules, use a terminal with a virtual environment and pip, and read a basic exception traceback. You don't need any testing experience.
What a unit test is
A unit test is a small program that runs one piece of your code, such as a function, with known input. It then checks that the result matches what you expect. A good unit test is fast, runs without a network or a real database, and fails for one clear reason.
Unit tests give you three things:
- Early detection of bugs, before they reach users.
- Safety when you change code. If the tests still pass after a refactor, you probably haven't broken anything.
- Executable examples of how a function is meant to behave.
Why pytest
Python ships with unittest, which needs test classes and special assertion methods such as assertEqual. pytest is a third-party test framework that keeps tests short:
- Tests are plain functions. No base class is required.
- You check results with the ordinary
assertstatement. On failure, pytest shows the values on both sides of the comparison. - Fixtures handle setup and teardown, and parametrization runs one test over many inputs.
- Plugins add features such as coverage. pytest can also run existing
unittesttests.
Install it in your virtual environment:
python -m pip install pytest
pytest --versionThe working model
pytest follows a simple cycle. It collects test functions from your files, runs each one in isolation, and reports a result for each. A test passes if it finishes without an exception. It fails if an assertion fails or any other exception escapes.
A first example
Here is a small function to test. Save it as cart.py.
# 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)A test for it needs only a function and an assert. Save it as test_cart.py in the same folder.
# test_cart.py
from cart import total
def test_total_without_tax():
assert total([10, 20]) == 30Run pytest from that folder. The output ends with a line like 1 passed. The later chapters explain how pytest finds tests and how to read its output in detail.
Common early mistakes
- Testing too much at once. If one test covers five behaviors, a failure doesn't tell you which one broke.
- Depending on outside state, such as a real network service or the current time. These tests fail at random.
- Running
pytestin an environment where it isn't installed. Check thatpytest --versionworks in the active virtual environment.
Exercise
Name two reasons pytest tests are usually shorter than unittest tests.
Show answer
Tests are plain functions with no required base class, and they use the built-in assert statement instead of special methods such as assertEqual. pytest also reports the compared values when an assert fails.
Exercise
Add a second test to test_cart.py that checks total([]) returns 0. What do you expect when you run pytest?
Show answer
Write def test_total_empty(): assert total([]) == 0. sum([]) is 0, and 0 * 1.0 equals 0, so pytest reports 2 passed.