Framework structure: pyproject, fixtures, parametrize and markers at scale

Study time
≈ 3 h (estimate)
Needs
L1-M06-L05
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M07 · Duration: ~165 min (estimate, including the independent exercise) · Previous: L1-M06-L05 · Next: L02 - Configuration, secrets and provider abstraction

1. Introduction

Over six modules you have written tests in six separate labs. Each lab has its own fixtures, configuration and way of running. In a real project, all tests live in one repository and run with one command, on every machine and on CI. That is a test framework.

This module builds that framework. It is also the starting point of the Level 1 capstone (L1-M08). The first lesson takes care of the skeleton: the pytest configuration in pyproject.toml, the directory layout, shared fixtures, and markers to pick the right group of tests at the right time (offline runs on every commit, UI runs, live runs that cost money).

2. Learning objectives

  1. Explain the src/ + tests/ layout and the role of pyproject.toml.
  2. Configure pytest: testpaths, pythonpath, addopts, registered markers and --strict-markers.
  3. Use fixtures at the right scope and put shared fixtures in conftest.py.
  4. Select a group of tests with -m (for example -m "not ui").
  5. Register a new marker and use it on several tests.

3. Prerequisites and tools

  • L1-M03 to L1-M06: pytest, fixtures, parametrize, monkeypatch.
  • The code lab code-labs/l1-m07, installed as described in its README (including python -m playwright install chromium).

4. Concepts

4.1 Layout

l1-m07/
├── pyproject.toml          cấu hình dự án và pytest
├── requirements.txt        phiên bản cố định của mọi thư viện
├── src/aiqa/               code của framework (config, client, report, app thử)
├── tests/unit/             test nhanh, offline
├── tests/ui/               test trình duyệt (Playwright)
└── ci/                     workflow CI

In English: pyproject.toml holds the project and pytest configuration; requirements.txt the pinned version of every library; src/aiqa/ the framework code (config, client, report, a trial app); tests/unit/ fast offline tests; tests/ui/ browser tests (Playwright); ci/ the CI workflow.

The pytest documentation says: "Generally, but especially if you use the default import mode prepend, it is strongly suggested to use a src layout" [R1]. When the code lives in src/, tests can import it only through the configured path, so you do not accidentally test a file that happens to sit in the current directory. ("Import mode prepend" is the default mode: pytest puts the folder of the test file at the front of the import path, so a file with the same name lying in that folder can be imported instead of the real code.)

Everyday example. A coffee shop puts the goods for sale (cakes, packed coffee beans) on a shelf, while whatever the barista is still trying out stays in the kitchen. Customers can only buy what is on the shelf. src/ is that shelf: tests can only "buy" the code placed on it through pythonpath, so they never pick up a draft lying in the kitchen.

Good vs bad.

Weak layout Good layout
config.py, test_config.py and config_old.py side by side at the repository root src/aiqa/config.py; tests in tests/unit/; the import path declared once with pythonpath = ["src"]

Why: in the weak layout it is hard to know which file a test imports, and the result can change with the folder you run the command from. In the good layout, code reaches the tests by one road only.

4.2 Configuring pytest in pyproject.toml

The pytest documentation: "Use [tool.pytest.ini_options] for INI-style configuration (supported since pytest 6.0)", and "Use [tool.pytest] to leverage native TOML types (supported since pytest 9.0)" [R2]. The lab uses the first form:

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-ra --strict-markers"
xfail_strict = true
markers = ["live: calls the real Claude API ...", "ui: drives a browser with Playwright"]
Setting Effect
testpaths python -m pytest without arguments looks for tests only in tests/
pythonpath Adds src/ to the import path while tests run
-ra At the end of every run, lists the reasons for skipped, xfailed and failed tests
--strict-markers An unregistered marker is an error, not a warning

Everyday example. A bakery pins its standard recipe in one place on the kitchen wall. New or experienced, morning or evening shift, every baker follows the same sheet. pyproject.toml is the recipe sheet of the test suite: whoever runs python -m pytest, on whatever machine, gets the same testpaths, pythonpath and addopts.

Good vs bad.

Weak Good
The README says "remember to type pytest -ra --strict-markers tests", and everyone has their own habit addopts and testpaths live in pyproject.toml; the command is just python -m pytest

Why: an option that lives only in someone's memory is forgotten on the very day it matters most, CI included.

4.3 Markers

A marker labels a test so that you can select a group when running. According to the documentation, when strict_markers is on, "any unknown marks applied with the @pytest.mark.name_of_the_mark decorator will trigger an error" [R3]. Without this option, a typo such as @pytest.mark.smok is only a warning, and -m smoke silently leaves that test out.

Everyday example. A school library puts coloured labels on book spines: green for reference books, red for books that cannot be borrowed. The librarian only has to "take every green book". A book with a wrongly coloured label silently ends up in no group at all. --strict-markers is a librarian who refuses to shelve a book with an unknown label.

Command What it runs When
python -m pytest -m "not ui and not live" Fast, offline tests Every time you save a file
python -m pytest -m ui Browser tests Every commit, on CI
python -m pytest -m live Calls the real API (costs money) Run by hand, with a budget (L04)

Worked example: a mistyped marker. Save this file as exercises/vd_l01_typo.py in the lab folder. It has one deliberate typo:

import pytest


@pytest.mark.ui
def test_reply_is_shown():
    pass


@pytest.mark.iu                      # typo: "iu" instead of "ui"
def test_enter_key_sends():
    pass

Run it twice. The first time, switch off the lab's addopts (and with it --strict-markers); the second time, keep the configuration as it is:

python -m pytest -q -o addopts="" -m ui exercises/vd_l01_typo.py
python -m pytest -q -m ui exercises/vd_l01_typo.py

Output (main lines only, run times and the path at the start of the warning line removed; the --- line separates the two runs; copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-06; both versions gave identical output):

PytestUnknownMarkWarning: Unknown pytest.mark.iu - is this a typo?
1 passed, 1 deselected, 1 warning
---
ERROR exercises/vd_l01_typo.py - Failed: 'iu' not found in `markers` configur...
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
1 error
  1. The first run is green. test_enter_key_sends is counted as "deselected": pytest thinks it is not in the ui group, so it does not run it. The only sign is one warning line, easily lost in a CI log.
  2. The second run stops at once during collection and names the wrong marker.
  3. This is the "40 tests vanished" scenario of §7, shrunk to one test. Delete vd_l01_typo.py when you are done.

One test, many items. The all 52 tests of the §8.1 demo counts items (one run of a test function with one set of parameters), not test functions: test_bad_configuration_fails_at_startup has 6 parameter sets, so it is 6 items. A marker can also be put on one parameter with pytest.param(..., marks=...). L02 does this for the live parameter of the contract tests, so -m live selects exactly the 2 [live] items and not the rest of those two tests.

4.4 Fixtures at scale

  • Scope. "Possible values for scope are: function, class, module, package or session"; the default is function, and the fixture "is destroyed at the end of the test" [R4]. Use a wider scope only when the fixture is expensive and the tests do not change it.
  • conftest.py. "Fixtures defined in a conftest.py can be used by any test in that package without needing to import them" [R5]. The lab has tests/conftest.py for every test and tests/ui/conftest.py for the UI tests.
  • Teardown with yield. "Any teardown code for that fixture is placed after the yield" [R4]. The chat fixture starts the server before yield and stops it after yield, even when the test fails.
  • autouse fixtures. offline_unless_live runs for every test: it forces mock mode and a fake API key, except for tests with the live marker. This is the framework's most important safeguard: nobody spends money by accident when running pytest.

Everyday example. A coffee shop can serve water in two ways: a clean glass for each customer (function scope), or one shared jug for the whole day (session scope). The jug saves washing up, but once one customer drops a slice of lemon in it, every later customer drinks lemon water. Sharing is safe only when nobody changes the shared thing.

Worked example: a wide scope makes tests depend on each other. Save as exercises/vd_l01_scope.py:

import pytest


@pytest.fixture(scope="session")     # try "function" next
def call_log():
    log = []
    yield log
    print(f"\nteardown: log had {len(log)} call(s)")


def test_first_question(call_log):
    call_log.append("Đơn SE1001 đâu rồi?")
    assert len(call_log) == 1


def test_second_question(call_log):
    call_log.append("Hoàn tiền thế nào?")
    assert len(call_log) == 1

Run python -m pytest -q -s exercises/vd_l01_scope.py (-s shows the print line at teardown). Output (excerpt, run times removed; copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-06; identical):

.F
teardown: log had 2 call(s)
E       AssertionError: assert 2 == 1
FAILED exercises/vd_l01_scope.py::test_second_question - AssertionError: asse...
1 failed, 1 passed
  1. With session scope, both tests get the same list. The first test adds one question, the second adds another: the list has 2 items, so len(call_log) == 1 fails.
  2. The code after yield runs only once, at the end of the run, and sees 2 calls.
  3. Change it to scope="function" and run again: 2 passed, and the line teardown: log had 1 call(s) appears twice, once per test. This is why the lab's chat fixture has function scope (§5.1). Delete the file when you are done.

5. Technical deep dive

5.1 Why a new server for each UI test

The chat fixture has function scope: each UI test gets its own server with an empty api_calls log. A shared server (session scope) would be slightly faster, but the log of an earlier test would leak into the next one. An assertion such as len(chat.api_calls) == 1 would then depend on the run order, and the test would become flaky (L1-M06-L05).

5.2 The Python you need for this lesson

  • TOML is the format of pyproject.toml: [table], key = "value", lists ["a", "b"].
  • tomllib (Python 3.11+) reads TOML: tomllib.loads(text). The exercise uses it to check your configuration.

6. The QA perspective

  • One command, every machine. If a test suite needs five manual steps to run, it will not be run.
  • Safe by default. The default command does not call the real API and needs no API key.
  • What can go wrong: a mistyped marker makes tests vanish from a group; a wide fixture scope makes tests depend on each other; configuration is scattered across many files; library versions are not pinned, so results differ between machines.

7. Real-world scenarios

Scenario 1 (fictional): 40 tests "disappear". A team runs pytest -m regression every night. After a refactor, 40 tests are tagged @pytest.mark.regresion (one "s" missing). They are never run again, and nobody notices for three months. --strict-markers would have reported an error on the very first run.

Scenario 2 (fictional): tests that pass only when run together. A session fixture holds an object with a log. Test B passes only when test A runs first and writes to the log. When CI runs the tests in parallel, B fails at random. Changing the fixture back to function scope fixes the bug.

8. Hands-on tutorial

8.1 Running the demo

cd academy-content/code-labs/l1-m07
python demo.py l01

Output (copied from a real run, 2026-10-31):

testpaths: ['tests'] | pythonpath: ['src'] | addopts: -ra --strict-markers
marker live
marker ui
all        52 tests
not ui     44 tests
ui only    8 tests
live only  2 tests
typo marker -> 'smok' not found in `markers` configuration option

Reading the output:

  • The first three lines are the configuration read from pyproject.toml.
  • The next four lines count the tests per marker group: 52 tests, of which 8 are UI tests and 2 are live tests.
  • The last line: the demo creates a temporary test with the mistyped marker smok, and pytest refuses to run.

8.2 Running the tests

python -m pytest -m "not ui"
python -m pytest

The first run needs no browser. The second also runs the UI tests. The SKIPPED line at the end (thanks to -ra) states why the two live tests did not run.

8.3 Troubleshooting

Symptom Cause Fix
'xyz' not found in markers configuration option The marker is not registered or is mistyped Fix the name, or register it in pyproject.toml
ModuleNotFoundError: No module named 'aiqa' Running python -m aiqa... without src on the path Use pytest, or the scripts in the root directory, or set PYTHONPATH=src
PytestRemovedIn10Warning about base_url Comes from the pytest-playwright 0.10.0 plugin Harmless with pytest 9 (see the lab README)

9. Independent exercise

9.1 Main exercise

Problem: The team wants a "smoke" group of tests that runs in under 10 seconds after every deploy.

Requirements:

  1. Register the smoke marker (with a description) in pyproject.toml.
  2. Put @pytest.mark.smoke on at least 3 tests in tests/ that you consider the most important. Write a one-sentence reason for each choice.
  3. Run python -m pytest exercises/test_l01_markers.py, then python -m pytest -m smoke.
  4. Try mistyping @pytest.mark.smok on one test and record the error message.

Deliverable: the changes to pyproject.toml and the tests, the reasons for your choices, the error message from step 4.

Acceptance criteria: the exercise test passes; the smoke group includes both configuration tests and at least one UI test.

Hint: a test can carry several markers: @pytest.mark.smoke sits next to pytestmark = pytest.mark.ui.

9.2 Extra exercise: check the markers before running (20-30 minutes)

Problem: --strict-markers reports an error only when you run the very file with the typo. The team wants a check that only reads files, finishes in a blink, and lists every marker used but not registered in the whole test folder.

Requirements: in exercises/test_l01_extra_marker_audit.py:

  1. TODO 1: write registered_markers(pyproject_text): read it with tomllib.loads and return the set of registered marker names. A name is the part before : (and before ( if there is one), without surrounding spaces.
  2. TODO 2: write used_markers(source): find every pytest.mark.<name> in the text of a test file, leaving out pytest's built-in markers (the BUILTIN set).
  3. Run the file again. The last test uses your two functions on the lab's own tests/ folder.

Run: python -m pytest exercises/test_l01_extra_marker_audit.py. Until you do the work, the tests fail with TODO 1 or TODO 2.

Acceptance criteria: 8 tests pass; the functions do not hard-code any of the lab's marker names.

Hint: the regular expression pytest\.mark\.([A-Za-z_]\w*) captures the name after pytest.mark.. The entry " regression : nightly run" in SAMPLE_PYPROJECT checks that you trim spaces.

9.3 Real-world scenario: taking over a bus-ticket chatbot's tests

Context (fictional): You have just taken over the tests of XeTot, a chatbot that sells long-distance bus tickets. Current state:

  • The pytest configuration lives in three places: pytest.ini, setup.cfg and a long command line in the README.
  • Tests sit next to the code in the app/ folder, for example app/booking.py beside app/test_booking.py.
  • The code uses 9 different markers, but only 4 are registered, and there is no --strict-markers.
  • A session-scoped fixture named fake_payment keeps a list of the transactions called; a few tests assert the length of that list.
  • Running pytest without arguments calls the real sandbox payment API, because there is no default mode.
  • The nightly job runs pytest -m regression, and the report has been green for weeks.

Your task: write a technical note (about one page) with: (a) the risks, ranked by severity, each with a concrete consequence for the team; (b) the folder layout and the [tool.pytest.ini_options] section you propose; (c) the order of work for the first week, and how you prove that each change loses no test.

A good answer has:

  • Every risk points to a section of the lesson (§4.1-§4.4, §6) and states its consequence with a concrete example, not just "not good".
  • The ranking has reasons: risks that cost money or touch a real system are weighed against tidiness risks.
  • The proposed configuration is valid TOML and gathers every option in one place.
  • There is a before-and-after measurement for each change, enough to prove that no test vanished.
  • There is at least one question for the previous team where you are unsure, instead of a guess.

10. Knowledge check

0/17 done · Results are kept in this browser only.

P02 · True or false

A session-scoped fixture is always better because it is faster.

P03 · Short answer

Why should a framework force mock mode in an autouse fixture?

P04 · Short answer

Give two benefits of the src/ layout.

P05 · Short answer

(Scenario) A colleague wants to put every fixture in each test file "so it is easier to read". How do you answer?

P06 · Match

According to §4.2, match each pytest setting of the lab with its effect.

P08 · Multiple choice

The demo in §8.1 prints all 52, not ui 44, ui only 8 and live only 2. How many tests does the command python -m pytest -m "not ui and not live" from the table in §4.3 select?

P09 · Spot the bug

The fixture below is copied from the lab's tests/conftest.py, with one line changed. Find the bug.

@pytest.fixture(autouse=True)
def offline_unless_live(request, monkeypatch):
    if not request.node.get_closest_marker("live"):
        return
    monkeypatch.setenv("AIQA_MODE", "mock")
    monkeypatch.setenv("ANTHROPIC_API_KEY", FAKE_KEY)
    for name in ("ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "AIQA_BASE_URL", "AIQA_MODEL"):
        monkeypatch.delenv(name, raising=False)

P10 · Recall

Lesson: L1-M06-L05

L1-M06-L05 §4.1: among the 161 commits analysed in Luo's study, the leading cause of flaky tests is:

P11 · True or false

python -m pytest without arguments also runs the files in exercises/.

P13 · True or false

In the worked example of §4.4, if you change the call_log fixture from session scope to function scope, both tests pass.

P14 · Multiple choice

Worked example of §4.3: vd_l01_typo.py has one test with @pytest.mark.ui and one with @pytest.mark.iu. You run python -m pytest -q -o addopts="" -m ui exercises/vd_l01_typo.py, that is, without --strict-markers. What is the summary line?

P15 · Apply now

In code-labs/l1-m07, do the extra exercise of §9.2: complete registered_markers() and used_markers() in exercises/test_l01_extra_marker_audit.py, then run python -m pytest exercises/test_l01_extra_marker_audit.py.

Checklist

P16 · Match

Match each incident with the framework mechanism (§4.2-§4.4) that prevents it.

P17 · True or false

test_bad_configuration_fails_at_startup contributes 6 items to the all 52 tests of the §8.1 demo.

11. Summary

  • Concepts: the src/ + tests/ layout; pytest configuration in pyproject.toml; markers and --strict-markers; fixture scope; conftest.py; yield for cleanup; autouse fixtures to keep safe defaults.
  • Skills: configuring pytest; selecting a group of tests with -m; adding a new marker.
  • Pitfalls: mistyped markers; a scope that is too wide; unpinned versions; a default command that costs money.
  • You can now: build the skeleton of an LLM test suite that anyone can run with one command.

12. References

ID Title Publisher URL Accessed Relevance
R1 Good Integration Practices pytest https://docs.pytest.org/en/stable/explanation/goodpractices.html 2026-10-31 The src layout
R2 Configuration pytest https://docs.pytest.org/en/stable/reference/customize.html 2026-10-31 [tool.pytest.ini_options] and [tool.pytest]
R3 How to mark test functions with attributes pytest https://docs.pytest.org/en/stable/how-to/mark.html 2026-10-31 Registering markers; strict_markers
R4 How to use fixtures pytest https://docs.pytest.org/en/stable/how-to/fixtures.html 2026-10-31 Scope; teardown after yield
R5 Fixtures reference pytest https://docs.pytest.org/en/stable/reference/fixtures.html 2026-10-31 Sharing fixtures through conftest.py

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Test framework Bộ khung test dùng chung
src layout Bố cục đặt code trong thư mục src/
Marker Nhãn để chọn nhóm test
Fixture scope Phạm vi sống của fixture
Teardown Dọn dẹp sau test
Smoke test Bộ test nhanh, kiểm tra những gì quan trọng nhất