Skip to content
Tutorials Center
My learning

Topics

pytest Tutorial

Learn pytest step by step: 38 lessons in 9 chapters with examples, quizzes, diagrams and projects.

Start learning →

of lessons completed

Getting Started

  1. 1 What Is pytest? Learn what pytest is, why most Python projects choose it over unittest, how a test is shaped, and run real pytest sessions right in your browser.
  2. 2 Your First Test Write your first pytest test from scratch, split code and tests into separate files, run them, and learn the test-fix-rerun loop that drives everyday testing.
  3. 3 Running Tests Master the pytest command line: run one file, one test or a keyword match, stop at the first failure, control output and tracebacks, and read exit codes.
  4. 4 Test Discovery and Project Layout Learn how pytest discovers tests, the naming rules for files, classes and functions, the src layout, pytest.ini settings, and why a tests folder works.

Tests and Assertions

  1. 5 Assertions and Failure Reports Learn how pytest rewrites the plain assert statement to explain failures: comparing strings, lists, dicts and sets, custom messages, and the -vv option for full diffs.
  2. 6 Testing Exceptions Learn how to test that code raises the right exception with pytest.raises, check messages with match, inspect the exception object, and handle exception groups.
  3. 7 Comparing Floats with approx Understand why 0.1 + 0.2 is not 0.3, then use pytest.approx with relative and absolute tolerances to compare floats, lists, dicts, complex numbers and NumPy arrays.
  4. 8 Testing Warnings, Output and Logs Test that code emits the right warnings with pytest.warns, capture printed output with capsys, check log records with caplog, and turn warnings into errors.
  5. 9 Organizing Tests with Classes Learn when to group pytest tests in classes, how each test gets a fresh instance, how setup_method and teardown_method work, and why fixtures usually beat them.

Fixtures

  1. 10 Fixtures Basics Learn what pytest fixtures are and how @pytest.fixture provides test data by name, how fixtures use other fixtures, and why they beat copy-pasted setup code.
  2. 11 Fixture Scopes Learn how fixture scope controls how often setup runs: function, class, module, package and session, with --setup-show examples, scope rules and dynamic scope.
  3. 12 Yield Fixtures and Cleanup Use yield in pytest fixtures to run teardown code after a test, learn what happens when setup or a test fails, order of cleanup, and the addfinalizer alternative.
  4. 13 conftest.py and Sharing Fixtures Learn how conftest.py makes fixtures available to many test files without imports, how its folder scope and override rules work, and how to organize shared fixtures.
  5. 14 Built-in Fixtures Tour the fixtures that ship with pytest: tmp_path and tmp_path_factory for temporary files, request, pytestconfig, monkeypatch basics, recwarn, capsys and record_property.
  6. 15 Fixture Factories, Autouse and Parameters Build factory fixtures that create many objects on demand, apply setup to every test with autouse, add fixtures with usefixtures, and use getfixturevalue and params.

Parametrization and Marks

  1. 16 Parametrized Tests Learn @pytest.mark.parametrize to run one test function with many input and expected-output pairs, stack decorators for combinations, and read the generated test ids.
  2. 17 IDs, Indirect Parametrization and Parametrized Fixtures Give parametrized tests readable ids, use pytest.param to attach marks and ids to single cases, parametrize fixtures with params, and route values through fixtures with indirect.
  3. 18 Skip, skipif and xfail Learn when and how to skip tests, run them conditionally with skipif, mark known bugs with xfail and strict mode, and use importorskip and pytest.skip inside tests.
  4. 19 Custom Marks and Strict Markers Label tests with custom marks like slow or integration, register them in pytest.ini, select with the -m expression, enforce --strict-markers, and mark whole modules and classes.

Mocking and Monkeypatching

  1. 20 The monkeypatch Fixture Replace functions, attributes, dictionary items, environment variables and the working directory for one test with pytest's monkeypatch fixture, and get them restored automatically.
  2. 21 unittest.mock Basics Learn Mock, MagicMock, return_value, side_effect and call assertions from the standard library's unittest.mock, and use them in pytest tests to fake collaborators.
  3. 22 patch, Where to Patch and autospec Use unittest.mock.patch as a decorator or context manager in pytest, learn the golden rule of where to patch, and use autospec so mocks cannot drift from the real API.
  4. 23 The pytest-mock Plugin Use pytest-mock's mocker fixture to patch with automatic cleanup, spy on real functions, create stubs and mock properties, and see when it beats unittest.mock.patch.
  5. 24 Mocking Time, Files and the Network Make tests deterministic by faking the clock with monkeypatch and freezegun, using tmp_path for files, and replacing HTTP calls with fakes or the responses library.

Plugins and Coverage

  1. 25 Coverage with pytest-cov Measure which lines and branches your tests execute with pytest-cov and coverage.py, read the missing-lines report, exclude code sensibly and enforce a minimum in CI.
  2. 26 Property-Based Testing with Hypothesis Let the Hypothesis library generate hundreds of inputs for your pytest tests, state properties instead of examples, and watch failing cases shrink to the smallest counterexample.
  3. 27 conftest.py Hooks and Local Plugins Customize pytest with hook functions in conftest.py: add command-line options, skip slow tests by default, change test order, add report lines, and package the code as a plugin.
  4. 28 A Tour of Third-Party Plugins Meet the pytest plugins most teams rely on: random ordering to expose hidden dependencies, reruns for flaky tests, soft assertions, xdist for parallel runs, timeouts and more.

Testing Real Projects

  1. 29 Project Layout and Configuration Organize a real Python project for pytest: src layout, tests folders, conftest.py placement, import modes, and the pytest.ini or pyproject.toml settings every team should set.
  2. 30 Testing Command-Line Programs Test Python command-line tools with pytest: capture printed output with capsys, call main(argv), check exit codes and SystemExit, fake stdin, and assert on log messages with caplog.
  3. 31 Testing Database Code Test code that talks to a database using pytest fixtures: in-memory SQLite, schema setup, rollback per test, factory fixtures, and how to scale the same pattern to PostgreSQL and SQLAlchemy.
  4. 32 Testing Async Code Test asyncio code with pytest: how async tests are run, pytest-asyncio modes and fixtures, AsyncMock, timeouts and concurrency, with a runnable stand-in that shows what the plugin does.

CI and Best Practices

  1. 33 Continuous Integration with GitHub Actions Run your pytest suite on every push with GitHub Actions: Python version matrix, dependency caching, coverage gates, JUnit reports, tox or nox, and a test that lints the workflow file itself.
  2. 34 Faster Suites and Flaky Tests Find slow tests with --durations, run only what you need with -k, -m and --lf, share expensive setup with fixture scopes, and track down the real causes of flaky tests.
  3. 35 Test Design and Best Practices Write tests that stay valuable: Arrange-Act-Assert, one behavior per test, good names, testing behavior instead of implementation, the test pyramid, and common anti-patterns with fixes.

Projects and Practice

  1. 36 Project: Test-Driven Shopping Cart Build a shopping cart with test-driven development: write failing pytest tests first, make them pass, refactor, and finish with fixtures, parametrization, Decimal money and coupon rules.
  2. 37 Project: Testing an API Client Test an API client without a network: inject a fake transport and a fake clock, check retries with backoff, error mapping, rate limits and caching, and learn how to design code for testability.
  3. 38 Practice: Reading and Fixing Failing Tests Learn to read pytest failure reports, use -x, -vv, -l and --tb options, and fix a project with three planted bugs. Hands-on exercises with runnable editors and a debugging checklist.