Sub topic 2
Writing your first tests and how pytest finds them
This chapter assumes you can write Python functions, import modules, use a terminal with a virtual environment and pip, and read a basic traceback. By the end you will know how to write a test pytest picks up, which naming rules decide what it collects, and which discovery mistakes cause tests to go missing.
What a test looks like
A pytest test is an ordinary Python function whose name starts with test. It runs some code and checks the result with assert. If the function returns without an exception, the test passes. If an assert fails or any other exception escapes, the test fails.
Here is a small function 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)Here is a first test file for it:
# test_cart.py
from cart import total
def test_total_without_tax():
assert total([10, 20]) == 30
def test_total_of_empty_cart_is_zero():
assert total([]) == 0Put both files in the same directory and run pytest. Each function becomes one test. The test body has three parts: arrange the inputs, act by calling the code, and assert on the outcome. These tests are short enough that all three fit on one line, but the structure stays the same as tests grow.
How discovery works
pytest does not need a list of tests. When you run it, it performs collection: it walks the directory tree, imports the test modules it finds, and gathers the test items inside them. The default rules are:
| What | Default rule |
|---|---|
| Test files | Names matching `test_*.py` or `*_test.py` |
| Test functions | Module-level functions whose names start with `test` |
| Test classes | Classes whose names start with `Test` and that have no `__init__` method |
| Test methods | Methods inside such a class whose names start with `test` |
| Directories | Searched recursively, except those matching `norecursedirs` (such as `.git`, `venv`, `node_modules`, and `build`) |
Anything that does not match is ignored. A file called checks.py is never collected, and neither is a function called check_total. This is the most common reason a beginner's test "passes" with no output: it was never found.
Grouping tests in classes
Classes are optional. They help you group related tests, and they do not need to inherit from anything.
# test_cart_classes.py
import pytest
from cart import total
class TestTotal:
def test_sums_prices(self):
assert total([1, 2, 3]) == 6
def test_applies_tax(self):
assert total([100], tax_rate=0.5) == 150
def test_rejects_negative_tax(self):
with pytest.raises(ValueError):
total([1], tax_rate=-1)pytest creates a new instance of the class for every test method. State you set on self in one test is therefore not visible in another. This differs from unittest.TestCase, where setup patterns share more ceremony. Do not rely on instance attributes to pass data between tests.
Seeing what pytest collected
You can ask pytest to list what it found without running anything:
pytest --collect-only -qThe output is a list of node IDs. A node ID names a test precisely:
test_cart.py::test_total_without_tax
test_cart.py::test_total_of_empty_cart_is_zero
test_cart_classes.py::TestTotal::test_sums_pricesThe format is file::function or file::Class::method. You can pass a node ID back to pytest to run exactly one test:
pytest test_cart.py::test_total_without_tax
pytest test_cart_classes.py::TestTotalWhen a test is missing from a run, --collect-only is the first diagnostic to try. If the test is not in that list, the problem is naming or location. If it is in the list but does not run, the problem is something else, such as a deselection option.
Collection as a pipeline
It helps to picture collection as stages that a name must pass through.
The import step matters. Collection imports your test modules, so any code at module level runs at that point, before a single test executes. A syntax error, a missing dependency, or a failing import produces a collection error, and by default pytest reports it and stops the run without executing any tests.
Import errors and the project layout
The most frequent first-week problem is ModuleNotFoundError: No module named 'cart'. It happens because pytest must be able to import both your test and the code under test, and where it looks depends on layout.
With the default prepend import mode, pytest finds the first directory upward from a test file that has no __init__.py, and inserts it at the front of sys.path. For the flat layout used above, with cart.py and test_cart.py side by side, this works without any configuration.
Once code lives in a package and tests in a separate folder, the layout needs more care. A common arrangement is:
project/
├── pyproject.toml
├── src/
│ └── shop/
│ ├── __init__.py
│ └── cart.py
└── tests/
└── test_cart.pyIn this layout the test imports from shop.cart import total. That import only works if shop is installed in your environment. The reliable approach is an editable install from the project root:
python -m pip install -e .This needs a build configuration in pyproject.toml, and it keeps your tests honest: they exercise the package the way a user would import it, not whatever happens to be on the path.
Duplicate test file names
Under the default import mode, two test files with the same base name in different directories can collide. If tests/a/test_utils.py and tests/b/test_utils.py both lack __init__.py files, pytest reports an "import file mismatch" error. There are two fixes. You can give each test file a unique name, or you can add an __init__.py to each test directory so the files become part of distinct packages. A third option is --import-mode=importlib, which avoids the sys.path changes altogether.
Common discovery mistakes
These are the errors that cost the most time, roughly in the order you will meet them.
- Wrong file name.
cart_test.pyis collected, buttests_cart.pyandtestcart.pyare not. Onlytest_*.pyand*_test.pymatch. - Wrong function name.
def total_test()anddef check_total()are never run. The prefix must betest. - Test class with
__init__. pytest skips the class and emits a warning, because it cannot construct it without arguments. - Duplicate function names. If a module defines
test_totaltwice, the second definition replaces the first, and only one runs. Linters flag this as a redefinition. - Tests that return a value. A test that ends with
return x == 3instead ofassert x == 3always passes. Recent pytest versions warn about non-Nonereturn values, but do not depend on the warning. - Running from the wrong directory. Paths and
testpathssettings are relative to where you invoke pytest or where it finds its configuration. Check therootdirline in the header of the output.
Controlling what gets collected
You do not have to run everything. Passing a path restricts collection to that path:
pytest tests/
pytest tests/test_cart.py
pytest tests/test_cart.py::TestTotal::test_applies_taxThe -k option selects by a keyword expression matched against test names:
pytest -k "total and not tax"Collection settings can also live in pyproject.toml, so a bare pytest behaves the same for everyone on the team:
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
python_functions = ["test_*"]The python_files, python_functions, and python_classes options change the naming rules. Leave them at the defaults unless you inherit a codebase with a different convention. Matching the standard rules makes your project easier for other developers to read.
Putting it together
Create a fresh directory with cart.py and test_cart.py from the start of this chapter. Then follow these steps:
- Run
pytest --collect-only -qand confirm that both tests are listed. - Run
pytest -vand confirm both pass. - Change
assert total([10, 20]) == 30to== 31and run again. Read the failure output, which shows the compared values. - Rename
test_cart.pytocart_checks.pyand runpytest. Notice that pytest reports that no tests were collected. - Restore the name, then add a function named
check_totaland confirm it is not collected.
Doing the failure and rename steps yourself builds the habit of distrusting a green run until you have seen the test fail.
Exercise
You add a new file tests/cart_tests.py containing def test_discount(): assert total([100]) == 90. Running pytest reports 4 passed, and test_discount is not among them. Why, and what are two ways to fix it?
Show answer
The file name cart_tests.py matches neither test_*.py nor *_test.py, so pytest never imports it. Fix it by renaming the file to test_cart.py or cart_test.py, or by adding python_files = ["test_*.py", "*_test.py", "*_tests.py"] to the pytest configuration. Renaming is preferred because it follows the default convention. You can confirm the result with pytest --collect-only -q.
Exercise
A test class is written as class TestOrder: with an __init__(self) method that sets self.items = [], and its test methods are never run. What does pytest do, and how should the shared setup be written instead?
Show answer
pytest will not collect a class that defines __init__, and it emits a warning saying so. Remove __init__ and create the data inside each test, or put it in a fixture, which later chapters cover. pytest builds a new instance per test, so instance attributes would not be shared between tests anyway.