Sub topic 1
What Unit Tests Are and Why Use pytest
Prerequisites
This chapter assumes you can do the following:
- Write Python functions and classes.
- Import modules and packages.
- Use a terminal, create a virtual environment, and install packages with pip.
- Read a basic exception traceback and know what
raisedoes.
You do not need any testing experience. Later chapters cover each pytest feature in detail. This chapter explains what a unit test is, how a test is structured, and why pytest is a common choice for Python.
What a unit test is
A unit test is a small program that runs one piece of your code and checks that it behaves as expected. The "unit" is usually a single function, method, or class. The test supplies inputs, runs the unit, and compares the result with what you expect. If the result matches, the test passes. If it does not, the test fails and reports the difference.
A good unit test has these properties:
- Fast. It runs in milliseconds, so you can run hundreds of them after every edit.
- Isolated. It does not depend on the network, a shared database, or the order of other tests.
- Deterministic. The same code gives the same result every time.
- Specific. When it fails, the failure points to one behavior.
Tests that touch many parts of a system at once are called integration tests. They are valuable, but they are slower and harder to diagnose. This tutorial focuses on unit tests, and later chapters show how to isolate code from its dependencies so that tests stay unit-sized.
The shape of a test: arrange, act, assert
Most tests follow three steps:
- Arrange. Build the inputs and any objects the unit needs.
- Act. Call the code under test.
- Assert. Check the outcome.
Keeping these steps visible makes a test easy to read. A reader should be able to see what was set up, what was called, and what was expected.
Why write unit tests
Tests give you three concrete benefits.
- Safe changes. When you refactor or fix a bug, a passing suite tells you quickly whether existing behavior survived.
- Executable documentation. A test such as "an empty cart totals zero" states a rule in a form that cannot drift out of date without failing.
- Faster debugging. A failing test narrows a problem to one function, which is quicker than tracing a whole program by hand.
Tests also have costs. They take time to write and must be maintained as the code changes. Poorly designed tests that check implementation details break on harmless refactors and erode trust. The last chapter of this tutorial covers habits that keep that cost low.
Testing without a framework
You can test with nothing but Python. Consider this module, which is used throughout the tutorial.
# 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 hand-written check might look like this:
# check_cart.py
from cart import total
if total([10, 20]) != 30:
print("FAIL: total without tax")
else:
print("ok")This works for one case, but it scales poorly. You have to invent your own way to report failures, run many checks, continue after the first failure, and show what the actual value was. A test framework supplies all of that.
Where pytest fits
Python's standard library includes unittest, a framework modeled on the xUnit family of tools from other languages. pytest is a third-party framework that runs unittest tests as well as its own style. Most new Python projects choose pytest because it asks for less code and reports failures more clearly.
| Aspect | `unittest` | pytest |
|---|---|---|
| Installation | Built in | `pip install pytest` |
| Test form | Methods on a `TestCase` subclass | Plain functions (classes optional) |
| Assertions | Methods such as `assertEqual` | The plain `assert` statement |
| Setup and teardown | `setUp` and `tearDown` methods | Fixtures, injected by argument name |
| Many inputs, one test | `subTest` or hand-written loops | `pytest.mark.parametrize` |
| Failure output | Message from the assert method | Rewritten `assert` shows the values involved |
| Extensions | Limited | Large plugin ecosystem, such as `pytest-cov` |
pytest does not replace unittest.mock, which you will still use for test doubles in a later chapter. The two tools work together.
The same test in both styles
Here is one check written in unittest style.
# test_cart_unittest.py
import unittest
from cart import total
class TotalTests(unittest.TestCase):
def test_total_without_tax(self):
self.assertEqual(total([10, 20]), 30)
if __name__ == "__main__":
unittest.main()And here is the same check in pytest style.
# test_cart.py
from cart import total
def test_total_without_tax():
assert total([10, 20]) == 30The pytest version has no class, no import of a framework, and no special assertion method. A test is a function whose name starts with test_, and it fails if an assert fails or an exception escapes.
Setting up and running your first test
Create a project folder with a virtual environment, then install pytest.
python -m venv .venv
source .venv/bin/activate
pip install pytest
pytest --versionOn Windows, activate the environment with .venv\Scripts\activate instead of the source line.
Save cart.py and test_cart.py from above in the same folder, then run:
pytestpytest finds test_cart.py, runs test_total_without_tax, and prints a summary. A passing run ends with a line similar to 1 passed in 0.01s. The next chapter explains the discovery rules in detail, and the chapter after it explains how to read the full output.
What pytest does for a failing test
The clearest advantage appears when a test fails. Change the expected value to something wrong:
# test_cart.py
from cart import total
def test_total_without_tax():
assert total([10, 20]) == 31pytest reports the failing line and the values on each side of the comparison, along these lines:
def test_total_without_tax():
> assert total([10, 20]) == 31
E assert 30 == 31
E + where 30 = total([10, 20])Plain assert normally prints nothing but AssertionError. pytest rewrites assert statements when it imports test modules so that it can show the intermediate values. This feature is called assertion introspection, and a later chapter covers it.
How a test run works
When you run pytest, the tool performs a fixed sequence of steps.
The exit code matters when you automate. pytest exits with 0 when all tests pass and a non-zero code when any fail or no tests are collected. Continuous integration systems use that code to decide whether a build is healthy.
Common mistakes at this stage
- Wrong file or function name. A file named
cart_test_1.pyor a function namedcheck_totalis not collected under the default rules, so the test silently never runs. If your count of tests is lower than expected, check the names first. - Import errors. If
from cart import totalfails, the test module cannot be collected. Make sure the module is importable from where you run pytest, and that the virtual environment with pytest installed is active. - A test with no assertion. A test that calls code but never asserts passes as long as nothing raises. That proves less than it appears to.
- Testing too much at once. A test that checks ten behaviors fails for ten possible reasons. Prefer one behavior per test.
What comes next
The following chapters build up pytest in the order you would use it. You will learn the discovery rules and how to read run output, then assertions, exceptions, and floating-point comparison. After that come fixtures, parametrization, markers, built-in fixtures, mocking, configuration, coverage, and test organization. Each chapter reuses the cart.py module and small examples like it.
Exercise
Name the three steps of a typical unit test, and say which step a test is missing if it calls a function but never uses assert.
Show answer
The steps are arrange, act, and assert. A test that calls a function without asserting is missing the assert step. It passes unless the call raises an exception, so it proves very little.
Exercise
You create cart_checks.py containing def test_total(): assert total([1]) == 1 and run pytest in the folder. pytest reports that no tests ran. Why, and what are two ways to fix it?
Show answer
By default pytest collects files named test_*.py or *_test.py, and cart_checks.py matches neither pattern. Rename the file to test_cart.py (or cart_test.py), or pass the file path explicitly, as in pytest cart_checks.py. Passing the path works because pytest collects files given on the command line even when their names do not match the pattern.