Sub topic 2
Writing your first tests and how pytest finds them
This chapter assumes you can write Python functions and classes, import modules, and use a terminal with a virtual environment where pip install pytest has been run. You will write a first test file and learn the rules pytest uses to find tests. Most "my tests don't run" problems come from those rules.
A function to test
Create cart.py with one function:
# 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)Your first test file
Create test_cart.py in the same folder:
# 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([]) == 0A test is an ordinary function that uses assert. If every assertion passes and no exception escapes, the test passes. Nothing needs to be imported from pytest, and there is no base class to inherit from.
The discovery rules
Collection is pytest's name for finding tests. By default it follows these rules:
- It starts from the paths you give on the command line. With no paths, it uses
testpathsfrom the configuration file, or the current directory. - It walks directories recursively and imports files named
test_*.pyor*_test.py. - In those files it collects functions whose names start with
test. - It also collects classes whose names start with
Test, and inside them, methods whose names start withtest. Such a class must not define__init__.
# test_cart.py (continued)
class TestTaxedTotals:
def test_ten_percent_tax(self):
assert total([100], tax_rate=0.5) == 150
def helper(self): # not collected: name does not start with "test"
return 1Classes only group related tests. Each test method gets a fresh instance of the class, so state set on self in one test is not visible in another.
flowchart TD
A[Start path or testpaths] --> B[Walk directories]
B --> C{File name matches test_*.py or *_test.py?}
C -- no --> B
C -- yes --> D[Import the file]
D --> E{Name starts with test or Test?}
E -- function test_* --> F[Collect test]
E -- class Test* --> G[Collect test_* methods]To use the diagram, replace the opening fence with the diagram form below.
Checking what was found
The --collect-only flag lists the tests without running them:
pytest --collect-only -qtest_cart.py::test_total_without_tax
test_cart.py::test_total_of_empty_cart_is_zero
test_cart.py::TestTaxedTotals::test_ten_percent_tax
3 tests collected in 0.01sEach line is a node ID in the form file::function or file::Class::method. You can pass a node ID to pytest to run just that test.
Common errors
- A test silently never runs. A function named
check_totalortotals_testis not collected, and neither is a file namedcart_tests.py. Run--collect-onlyfirst. ModuleNotFoundErrorfor your own code. With the default import mode, pytest adds the test file's folder tosys.path.from cart import totalworks whencart.pysits beside the test, or when your package is installed withpip install -e ..- "import file mismatch". Two test files with the same name in different folders, such as
a/test_utils.pyandb/test_utils.py, collide unless each folder has an__init__.py.
Exercise
You add def check_discount(): with several asserts to test_cart.py, and pytest reports the same number of tests as before. Why, and what are two ways to fix it?
Show answer
Collection only picks up functions whose names start with test, so check_discount is ignored. Rename it to test_discount (or a name starting with test_). Running pytest --collect-only -q before and after confirms the change.