Python · Advanced level

Advanced level · Module 2: Testing and Code Quality · Lesson 3 of 4

Fixtures, Parametrised Tests and Coverage

Write shorter, stronger test suites with fixtures and parametrisation, and see which code is untested.

In this lesson you will

  • Share set-up code between tests with fixtures
  • Test many inputs with one parametrised test
  • Read a coverage report and add missing tests

Key concepts

fixtureparametrizetest coverageedge case

The lesson

When several tests need the same starting point — a fresh database or an account with 1,000 SSP — a pytest fixture creates it once in a function decorated with @pytest.fixture, and each test receives it as an argument.

@pytest.mark.parametrize runs the same test with a list of inputs and expected results. One parametrised test can check ten phone numbers, which makes it easy to add edge cases as you discover them.

Coverage tools show which lines your tests never run. High coverage does not prove the code is correct, but uncovered lines are certainly untested — usually error handling.

Step by step

  1. Move repeated set-up into a fixture.
  2. Rewrite three similar tests as one parametrised test.
  3. Install pytest-cov and run pytest --cov.
  4. Add tests for the most important uncovered lines.

Practice activity

Refactor your BankAccount tests to use a fixture and a parametrised test, then raise coverage of the account module above 90%.

Expected result: A shorter test file with the same or more checks and a coverage report above 90% for the module.

Check your understanding

  1. Does 100% coverage prove the code has no bugs?

    Show answer

    No. It shows every line ran during tests, not that the results were checked correctly or that all cases were considered.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.