Test Python code with pytest

8 steps · about 3 h 50 min · Intermediate

  1. Write and run the first test (tutorial, pytest documentation, 25 min)

    One small assertion establishes discovery, execution and failure output.

  2. Make failures explain the mismatch (guide, pytest documentation, 25 min)

    Useful assertions shorten the path from a failing test to the broken behaviour.

  3. Choose a maintainable test layout (guide, pytest documentation, 30 min)

    Import mode, package layout and naming decisions prevent fragile discovery problems.

  4. Set up repeatable test context with fixtures (guide, pytest documentation, 35 min)

    Fixtures make dependencies explicit and remove duplicated setup.

  5. Test several cases with parametrization (guide, pytest documentation, 30 min)

    A compact table of cases exposes boundaries without copying the test body.

  6. Control external state with monkeypatch (guide, pytest documentation, 35 min)

    Replacing environment, paths or calls keeps a unit test deterministic and local.

  7. Verify command output deliberately (guide, pytest documentation, 25 min)

    Captured streams let command-line behaviour be checked without manual inspection.

  8. Read and control failure behaviour (guide, pytest documentation, 25 min)

    Traceback and stop options help isolate the first useful signal in a larger suite.