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.
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.
Parametrize a test for is_even(n) with at least five rows, including 0 and a negative number.
Write a test with tmp_path that saves a function's result into a text file and reads it back.
Explain it without notes
What is a pytest fixture, and how does a test use one?
What do fixture scopes mean, and what is the risk of a wide scope?
How does yield work in a fixture, and when does teardown run?
Why is @pytest.mark.parametrize better than a loop inside a test?
What are tmp_path, monkeypatch and capsys for?
Expected output
open database (once per file)
begin session
test_one runs
end session
begin session
test_two runs
end session
close database