Pylerno
English

Pytest

Run independent tests against a real shared implementation.

On this page

The concept

pytest discovers test_*.py files and test_ functions. An assertion compares actual behavior with a requirement. Parametrization runs the same requirement for several inputs without duplicating test bodies. pytest.raises checks that an expected failure really occurs.

A fixture prepares a test resource. tmp_path gives each test an isolated temporary directory, preventing order-dependent file collisions. The helper module title_rules.py is imported by both the lesson and its tests: the test does not copy the implementation it intends to verify. lesson.py runs without pytest; the separate test file requires the development environment.

Worked example

Extract the example files. From the python_from_zero directory, run the following command in a terminal. On Windows, use py in place of python3.

sh
python3 08_professional_workflow/58_pytest/lesson.py
python
from title_rules import normalize_title

assert normalize_title("  Python  ") == "Python"
try:
    normalize_title("   ")
except ValueError:
    print("Empty input was rejected.")
else:
    raise AssertionError("empty title must fail")

Trace the result

  1. normalize_title is imported from title_rules, making the real implementation shared.
  2. The prepared title is trimmed and checked against its expected value.
  3. Empty input is required to fail. The separate test module adds several cases and an isolated UTF-8 file round trip.
text
Empty input was rejected.
Line-by-line walkthrough

Line 1: from title_rules import normalize_title

Import normalize_title from title_rules. This supplies the same title-normalization implementation used by the tests. The caller can now use the imported names directly.

Line 3: assert normalize_title(" Python ") == "Python"

Check normalize_title(' Python ') == 'Python' and raise AssertionError if it is false. This is a test/internal assumption; optimized Python may remove assertions, so it must not enforce untrusted-input rules.

Lines 4–9: try:

Run the protected body. A matching except handles its specified failure. An else suite runs after a successful try body, and finally runs when leaving the construct. This structure should handle expected failures without concealing unrelated bugs.

Line 5: normalize_title(" ")

Call normalize_title with the displayed arguments. This call may have an effect even when its return value is not assigned.

Alternative or completion suite: read the statements below as part of this branch.

Line 9: raise AssertionError("empty title must fail")

Raise AssertionError('empty title must fail'). Normal execution stops here unless an enclosing handler catches it. A from cause, when present, preserves the reason for a translated error.

Handler for ValueError: control reaches this suite only for a matching exception from the protected body.

Line 7: print("Empty input was rejected.")

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Common mistake

Tests should not require a particular execution order or share an unprotected real data file. Use isolated fixtures.

Run the tests

Install pytest into your project environment with python -m pip install pytest. From the extracted example root, run the following command with that same interpreter.

sh
python -m pytest 08_professional_workflow/58_pytest -q

Check your understanding

Which pytest fixture gives each test its own temporary directory?

Choose one answer

Search documentation

Share this page