Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.3 — Fixtures and Parametrised Tests
Python · Example 2 of 2

Fixture scopes and teardown order

A module-scope fixture opens once; a function-scope fixture wraps each test. The log shows the real order, including teardown.

A fixture is a function that prepares what a test needs (data, a temporary folder, a fake client) and cleans up afterwards. @pytest.mark.parametrize runs the same test body with many inputs, so one test function becomes a whole table of cases.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a fixture numbers that returns [3, 1, 2] and two tests that use it: one for sorted(numbers) and one showing that sorting a copy leaves the fixture's list unchanged. Run them with the pytest helper.

02

Parametrize a test for is_even(n) with at least five rows, including 0 and a negative number.

03

Write a test with tmp_path that saves a function's result into a text file and reads it back.

Explain it without notes

01

What is a pytest fixture, and how does a test use one?

02

What do fixture scopes mean, and what is the risk of a wide scope?

03

How does yield work in a fixture, and when does teardown run?

04

Why is @pytest.mark.parametrize better than a loop inside a test?

05

What are tmp_path, monkeypatch and capsys for?

Fixture scopes and teardown order
Sign in to run this example in your browser.

Expected output

open database (once per file)
  begin session
    test_one runs
  end session
  begin session
    test_two runs
  end session
close database