Fixtures, parametrize, tmp_path, capsys and monkeypatch
pytest runs here in your browser. The run_pytest helper is the same plumbing as before. The conftest.py fixture is used by test_fixtures.py without any import. Add a row to the parametrize list and run again.
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
test_fixtures.py::test_cart_total
test_fixtures.py::test_cart_is_fresh_each_time
test_fixtures.py::test_cart_again_is_fresh
test_fixtures.py::test_line_total[10-3-30]
test_fixtures.py::test_line_total[0-5-0]
test_fixtures.py::test_line_total[7-0-0]
test_fixtures.py::test_line_total[2.5-4-10.0]
test_fixtures.py::test_writes_a_file
test_fixtures.py::test_prints
test_fixtures.py::test_env
10 tests collected
.......... [100%]
10 passed