Testing with pytest: Fixtures, Mocks and Coverage
assert, pytest.raises, a first parametrize) came in Type Hints, Testing & Code Quality. Fixtures are built from decorators and yield, so this lesson follows Decorators and Generators & Context Managers.After this lesson, you will be able to:
- Write a parametrized test with readable ids and explain why each case is reported on its own
- Build fixtures with `yield` teardown, choose a scope, and share them through conftest.py
- Test file-reading and file-writing code with tmp_path, replace environment variables with monkeypatch, and check printed output and log lines with capsys and caplog
- Mock an HTTP call made with requests so a test checks your code without any network
- Select tests with markers, skip or xfail them, and read a pytest-cov report without over-trusting it
Before you start
#A bug one test would have caught
labelkit that the rest of the lesson builds on.# labelkit/cleaning.py
def clean_rows(rows):
"""Keep only the rows that have a label."""
return [row for row in rows if row.get("label")]clean_rows is called with rows labelled 1, 0 and None (unlabelled), with ids 1, 2 and 3. Which ids come back?
test_, and it uses a plain assert.# tests/test_cleaning.py
from labelkit.cleaning import clean_rows
def test_clean_rows_keeps_zero_labels():
rows = [
{"id": 1, "label": 1},
{"id": 2, "label": 0},
{"id": 3, "label": None},
]
kept = clean_rows(rows)
assert [row["id"] for row in kept] == [1, 2]pytest in the project folder prints this (the session header lines are left out; timings differ on every machine).$ pytest
collected 1 item
tests/test_cleaning.py F [100%]
=================================== FAILURES ===================================
______________________ test_clean_rows_keeps_zero_labels _______________________
def test_clean_rows_keeps_zero_labels():
rows = [
{"id": 1, "label": 1},
{"id": 2, "label": 0},
{"id": 3, "label": None},
]
kept = clean_rows(rows)
> assert [row["id"] for row in kept] == [1, 2]
E assert [1] == [1, 2]
E
E Right contains one more item: 2
E Use -v to get more diff
tests/test_cleaning.py:11: AssertionError
=========================== short test summary info ============================
FAILED tests/test_cleaning.py::test_clean_rows_keeps_zero_labels - assert [1]...
============================== 1 failed in 0.02s ===============================
assert so a failure shows both sides, which is why you see [1] == [1, 2] and not just AssertionError. The fix is one phrase, if row.get("label") is not None, and the test goes green. The rest of the lesson is the machinery that keeps tests like this cheap to write.#What pytest does when you run it
test_*, calls each one, and records whether it raised. This runnable cell is a runner with the same job, small enough to read in one go.def clean_rows(rows):
return [row for row in rows if row.get("label")]
def test_keeps_positive_rows():
rows = [{"id": 1, "label": 1}]
assert [row["id"] for row in clean_rows(rows)] == [1]
def test_keeps_zero_labels():
rows = [{"id": 1, "label": 1}, {"id": 2, "label": 0}, {"id": 3, "label": None}]
assert [row["id"] for row in clean_rows(rows)] == [1, 2]
def run_tests(*tests):
for test in tests:
try:
test()
except AssertionError:
print("FAILED", test.__name__)
else:
print("passed", test.__name__)
run_tests(test_keeps_positive_rows, test_keeps_zero_labels)is not None and run it again. Real pytest adds three things to this loop, and they are what the rest of the lesson is about.| Idea | What pytest adds to the loop |
|---|---|
| Discovery | Finds test_*.py files and test_* functions without a list |
| Injection | Reads each test's parameter names and passes in a fixture of the same name |
| Reporting | Rewrites assert to show values, and reports every case, not only the first failure |
def test_x(rows): is not called with arguments you supplied. pytest sees the name rows, finds a fixture called rows, runs it and passes the result in.#Parametrize with ids
accuracy(predictions, labels) lives in its own module, labelkit/metrics.py, and returns the fraction of matching pairs. Each interesting input is a row in a table.# labelkit/metrics.py
def accuracy(predictions, labels):
"""Fraction of predictions that match their label."""
hits = sum(1 for p, y in zip(predictions, labels) if p == y)
return hits / len(labels)# tests/test_metrics.py
import pytest
from labelkit.metrics import accuracy
@pytest.mark.parametrize(
"predictions, labels, expected",
[
([1, 0, 1, 1], [1, 0, 1, 1], 1.0),
([1, 0, 1, 0], [1, 1, 1, 1], 0.5),
([0, 0, 0], [1, 1, 0], 1 / 3),
(["cat", "dog"], ["cat", "cat"], 0.5),
],
ids=["all-correct", "half-right", "one-third", "string-labels"],
)
def test_accuracy(predictions, labels, expected):
assert accuracy(predictions, labels) == pytest.approx(expected)pytest generates one test per row, so a failure names the case.
$ pytest -v tests/test_metrics.py
tests/test_metrics.py::test_accuracy[all-correct] PASSED [ 25%]
tests/test_metrics.py::test_accuracy[half-right] PASSED [ 50%]
tests/test_metrics.py::test_accuracy[one-third] PASSED [ 75%]
tests/test_metrics.py::test_accuracy[string-labels] PASSED [100%]
============================== 4 passed in 0.01s ===============================
ids, pytest builds names from the values, which turns into [predictions2-labels2-0.3333333333333333] after a few cases. A name like one-third is readable in a CI log. This runnable cell shows what generating a test per case buys over one loop inside one test: a bad case does not stop the others.import math
def accuracy(predictions, labels):
hits = sum(1 for p, y in zip(predictions, labels) if p == y)
return hits / len(labels)
cases = [
("all-correct", [1, 0, 1, 1], [1, 0, 1, 1], 1.0),
("half-right", [1, 0, 1, 0], [1, 1, 1, 1], 0.5),
("one-third", [0, 0, 0], [1, 1, 0], 1 / 3),
("typo-in-case", [1, 1], [1, 0], 1.0),
]
for case_id, predictions, labels, expected in cases:
got = accuracy(predictions, labels)
verdict = "PASSED" if math.isclose(got, expected) else "FAILED"
print(f"test_accuracy[{case_id}] {verdict}")
print(1 / 3 == 0.3333333333333333, 0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))pytest.approx(expected) and not ==. Floating-point results are close, not always identical, so compare them with a tolerance. pytest.approx is that tolerance for tests, and math.isclose is the same idea in plain Python.#Fixtures: setup a test asks for by name
@pytest.fixture, and any test that lists its name as a parameter receives the result.# tests/conftest.py
import pytest
@pytest.fixture
def rows():
"""Three labelled rows: a positive, a negative, and one unlabelled."""
return [
{"id": 1, "label": 1},
{"id": 2, "label": 0},
{"id": 3, "label": None},
]
@pytest.fixture
def audit_log(tmp_path):
"""An open log file for the test, closed afterwards even if the test fails."""
handle = (tmp_path / "audit.log").open("w")
yield handle
handle.close()def test_clean_rows_keeps_zero_labels(rows): and drop its own setup. The second fixture shows teardown. Everything before yield is setup, the yielded value is what the test receives, and everything after yield runs when the test ends, pass or fail. That is the generator pattern from the earlier lesson: pytest calls next() to set up and again to tear down. This runnable cell does the same by hand.def audit_log():
print("setup: open the log")
log = []
yield log
print("teardown: close the log, saw", log)
def run_with_fixture(fixture, test):
generator = fixture()
value = next(generator)
try:
test(value)
print("test passed")
except AssertionError:
print("test FAILED")
finally:
next(generator, None)
def test_logs_one_event(log):
log.append("loaded 3 rows")
assert len(log) == 2
run_with_fixture(audit_log, test_logs_one_event)yield and not at the bottom of the test body.#Scope: how long a fixture lives
function). scope="module" builds it once per file, and scope="session" once per run. A wider scope saves time for expensive things and costs isolation.A scope='session' fixture returns an empty list. test_a appends 7 to it and passes. test_b, which runs later, asserts the list is empty. What happens?
--setup-show flag shows scopes. This small file has one session fixture, label_names, one function fixture, rows, and two tests that use both.# demo/test_demo_scope.py
import pytest
@pytest.fixture(scope="session")
def label_names():
return ["negative", "positive"]
@pytest.fixture
def rows():
return [{"id": 1, "label": 1}]
def test_first(label_names, rows):
assert len(label_names) == 2
def test_second(label_names, rows):
assert label_names[1] == "positive"S marks session scope and F function scope in the output.$ pytest --setup-show demo/test_demo_scope.py
demo/test_demo_scope.py
SETUP S label_names
SETUP F rows
demo/test_demo_scope.py::test_first (fixtures used: label_names, rows) .
TEARDOWN F rows
SETUP F rows
demo/test_demo_scope.py::test_second (fixtures used: label_names, rows) .
TEARDOWN F rows
TEARDOWN S label_names
labelkit project the autouse no_network fixture from conftest.py, shown in the layout section, would add its own lines to this output. The demo file sits outside tests/ so those lines do not appear.)#Testing code that reads and writes files
tmp_path fixture solves this. It gives each test a fresh, empty folder as a pathlib.Path, under your system's temp directory.tempfile, the module tmp_path is built on.import json
import tempfile
from pathlib import Path
def save_rows(path, rows):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as handle:
for row in rows:
handle.write(json.dumps(row) + "\n")
def load_rows(path):
path = Path(path)
if not path.exists():
return []
with path.open(encoding="utf-8") as handle:
return [json.loads(line) for line in handle if line.strip()]
rows = [{"id": 1, "label": 1}, {"id": 2, "label": 0}]
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "data" / "rows.jsonl"
save_rows(path, rows)
print(path.read_text().splitlines())
print(load_rows(path) == rows)
print(load_rows(Path(folder) / "missing.jsonl"))
print(path.exists())False: the folder and everything in it are gone once the block ends. In pytest you skip the with and ask for tmp_path, which hands each test its own fresh folder.# tests/test_storage.py
from labelkit.storage import load_rows, save_rows
def test_round_trip(tmp_path, rows):
path = tmp_path / "data" / "rows.jsonl"
save_rows(path, rows)
assert load_rows(path) == rows
def test_missing_file_gives_empty_list(tmp_path):
assert load_rows(tmp_path / "nope.jsonl") == []
def test_one_json_object_per_line(tmp_path, rows):
path = tmp_path / "rows.jsonl"
save_rows(path, rows)
lines = path.read_text().splitlines()
assert len(lines) == 3
assert lines[0] == '{"id": 1, "label": 1}'data subfolder is deliberate, because it checks that save_rows creates missing parent folders. Two tests can both write rows.jsonl without seeing each other's file, since each gets its own tmp_path. pytest also keeps the folders from the last few runs, so after a failure you can open the folder and look at what the code wrote.#monkeypatch: change something for one test
monkeypatch fixture changes such things for the length of one test and puts every original back afterwards.# labelkit/client.py (the first half)
import os
def base_url():
"""Where the service lives. Override with LABELKIT_API_URL."""
return os.environ.get("LABELKIT_API_URL", "https://api.example.com")
# tests/test_client.py
def test_base_url_from_environment(monkeypatch):
monkeypatch.setenv("LABELKIT_API_URL", "https://staging.example.com")
assert base_url() == "https://staging.example.com"
def test_base_url_default(monkeypatch):
monkeypatch.delenv("LABELKIT_API_URL", raising=False)
assert base_url() == "https://api.example.com"delenv on purpose. If your own shell has LABELKIT_API_URL set, the default-value test would otherwise pass or fail depending on whose machine it runs on. raising=False means "fine if it was never set". The same fixture has setattr for replacing a function or attribute and setitem for a dictionary entry, and all of them are undone when the test ends. This cell shows the restore behaviour with the standard library's patch.dict, which does the same job for os.environ.import os
from unittest.mock import patch
def base_url():
return os.environ.get("LABELKIT_API_URL", "https://api.example.com")
print(base_url())
with patch.dict(os.environ, {"LABELKIT_API_URL": "https://staging.example.com"}):
print(base_url())
print(base_url())os.environ["LABELKIT_API_URL"] = ... directly in a test is the version that leaks: the value stays set for every later test in the process. That is the whole reason monkeypatch exists.#Checking printed output and log lines
main(argv) prints a summary and may log a warning, and a test needs to see both. Two more built-in fixtures do that. capsys collects what the code printed, and caplog collects its log records. Here is labelkit/cli.py, which reads a rows file, cleans it and reports.# labelkit/cli.py
import logging
from labelkit.cleaning import clean_rows
from labelkit.storage import load_rows
logger = logging.getLogger("labelkit")
def main(argv):
"""Print how many rows survive cleaning and return an exit code."""
rows = load_rows(argv[0])
kept = clean_rows(rows)
dropped = len(rows) - len(kept)
if dropped:
logger.warning("dropped %d unlabelled rows", dropped)
print(f"kept {len(kept)} of {len(rows)} rows")
return 0# tests/test_cli.py
import logging
from labelkit.cli import main
from labelkit.storage import save_rows
def test_main_prints_a_summary(tmp_path, rows, capsys):
path = tmp_path / "rows.jsonl"
save_rows(path, rows)
assert main([str(path)]) == 0
assert capsys.readouterr().out == "kept 2 of 3 rows\n"
def test_main_warns_about_unlabelled_rows(tmp_path, rows, caplog):
path = tmp_path / "rows.jsonl"
save_rows(path, rows)
with caplog.at_level(logging.WARNING):
main([str(path)])
assert "dropped 1 unlabelled rows" in caplog.textcapsys.readouterr() returns what was printed so far, split into .out and .err. caplog.at_level makes sure records at that level are kept, and caplog.text holds them as text. The test checks the exit code and the printed line, so a change to either one is noticed.#Mocking an HTTP call
A test for code that calls a web service has two problems. The service may be slow, down or rate limited, and a test that fails because of that tells you nothing about your code. And you cannot make the real service return a timeout or a 500 on demand. The fix is a mock: a stand-in object that records how it was called and returns whatever you tell it to.
requests and returns the label.# labelkit/client.py (the second half)
import requests
def predict(features, timeout=5):
"""Send one feature row to the service and return its predicted label."""
response = requests.post(
f"{base_url()}/v1/predict",
json={"features": features},
timeout=timeout,
)
response.raise_for_status()
return response.json()["label"]Mock accepts any call and any attribute. You set what its calls return with return_value, and what they raise with side_effect. You check how it was used with assert_called_once_with.from unittest.mock import Mock
response = Mock()
response.json.return_value = {"label": 1}
response.status_code = 200
post = Mock(return_value=response)
result = post("https://api.example.com/v1/predict", json={"features": [0.2, 0.7]}, timeout=5)
print(result.json()["label"])
print(post.call_count)
post.assert_called_once_with(
"https://api.example.com/v1/predict", json={"features": [0.2, 0.7]}, timeout=5
)
flaky = Mock(side_effect=TimeoutError("slow"))
try:
flaky()
except TimeoutError as error:
print("raised:", error)
try:
post.assert_called_once_with("https://api.example.com/v2/predict")
except AssertionError:
print("wrong URL detected")patch does: it swaps a name for a mock while the test runs and swaps it back afterwards. With the pytest-mock plugin (pip install pytest-mock) it arrives as the mocker fixture, which undoes every patch at the end of the test for you.# tests/test_client.py
from unittest.mock import Mock
import pytest
import requests
from labelkit.client import predict
def fake_response(payload):
response = Mock()
response.json.return_value = payload
return response
def test_predict_returns_label(mocker):
post = mocker.patch(
"labelkit.client.requests.post",
return_value=fake_response({"label": 1}),
)
assert predict([0.2, 0.7]) == 1
post.assert_called_once_with(
"https://api.example.com/v1/predict",
json={"features": [0.2, 0.7]},
timeout=5,
)
def test_predict_raises_on_timeout(mocker):
mocker.patch("labelkit.client.requests.post", side_effect=requests.Timeout("slow"))
with pytest.raises(requests.Timeout):
predict([0.2])
def test_predict_raises_on_server_error(mocker):
response = fake_response({})
response.raise_for_status.side_effect = requests.HTTPError("500 Server Error")
mocker.patch("labelkit.client.requests.post", return_value=response)
with pytest.raises(requests.HTTPError):
predict([0.2])"labelkit.client.requests.post" means "in the labelkit.client module, look up requests, then replace its post". The rule for choosing a target is to patch the name where your code looks it up, which is not always where it was defined.A module does from random import random as draw and calls draw(). A test runs with patch('random.random', return_value=0.9): and then calls the module's function. Does the function see 0.9?
import random
from random import random as draw
from unittest.mock import patch
def noisy_label():
return 1 if draw() > 0.5 else 0
def noisy_label_via_module():
return 1 if random.random() > 0.5 else 0
with patch("random.random", return_value=0.9):
print(noisy_label_via_module())
print(draw is random.random)False: draw is not the patched object, so noisy_label() would still return random labels. labelkit.client uses requests.post through the requests module, which is why patching labelkit.client.requests.post reaches it.create_autospec(function) or Mock(spec=...) copies the real signature, so a call the real function would reject raises TypeError on the mock too.requests.post runs, the test hits the network or hangs. An autouse fixture in conftest.py makes that fail loudly (the layout section shows it in place). Here is what a test that forgot its mock reports.$ pytest tests/test_forgot.py
def test_predict_without_a_mock():
> predict([0.2])
...
def blocked(*args, **kwargs):
> raise RuntimeError("a test tried to use the network")
E RuntimeError: a test tried to use the network
tests/conftest.py:28: RuntimeError
FAILED tests/test_forgot.py::test_predict_without_a_mock - RuntimeError: a te...
... stands for the middle of the traceback through labelkit/client.py and the requests library, which is left out.#Markers and skipping
A marker is a label you attach to a test with a decorator. pytest uses some labels itself and lets you invent your own.
# tests/test_markers.py
import sys
import pytest
from labelkit.cleaning import accuracy, clean_rows
@pytest.mark.slow
def test_accuracy_on_a_million_rows():
labels = [1, 0] * 500_000
assert accuracy(labels, labels) == 1.0
@pytest.mark.skipif(sys.platform == "win32", reason="checks POSIX file modes")
def test_saved_file_is_not_executable(tmp_path):
path = tmp_path / "rows.jsonl"
path.write_text("")
assert not path.stat().st_mode & 0o111
@pytest.mark.xfail(reason="empty-string labels are not dropped yet", strict=True)
def test_clean_rows_drops_empty_string_labels():
assert clean_rows([{"id": 1, "label": ""}]) == []skip and skipif do not run the test and say why. xfail means "expected to fail": the test runs, a failure is reported as xfail and does not break the run, and a surprise pass is a problem when strict=True, because the bug you wrote down has been fixed and the marker should go. A custom marker such as slow is only a label until you filter on it. Register it in pyproject.toml, and add --strict-markers so a typo like @pytest.mark.slwo stops collection and does not pass silently.[tool.pytest.ini_options]
addopts = "--strict-markers"
markers = [
"slow: takes more than a second; deselect with -m 'not slow'",
]
$ pytest -q -rsx
..........x....... [100%]
=========================== short test summary info ============================
XFAIL tests/test_markers.py::test_clean_rows_drops_empty_string_labels - empty-string labels are not dropped yet
17 passed, 1 xfailed in 0.17s
$ pytest -q -m "not slow"
.........x....... [100%]
16 passed, 1 deselected, 1 xfailed in 0.09s
slow test. -m "not slow" selects by marker and -k "accuracy" selects by a substring of the test name. -rsx adds a summary line for each skipped (s) or xfailed (x) test with its reason. A skip without a reason is a test nobody will ever turn back on.#Coverage: what it tells you and what it does not
pytest-cov plugin (pip install pytest-cov) wraps coverage.py. You point --cov at the package you are testing, not at the tests.$ pytest -q --cov=labelkit --cov-report=term-missing --ignore=tests/test_client.py
Name Stmts Miss Cover Missing
----------------------------------------------------
labelkit/__init__.py 0 0 100%
labelkit/cleaning.py 2 0 100%
labelkit/cli.py 12 0 100%
labelkit/client.py 8 8 0% 1-19
labelkit/metrics.py 3 0 100%
labelkit/storage.py 14 0 100%
----------------------------------------------------
TOTAL 39 8 79%
Missing column points at lines 1 to 19 of client.py: nothing tests it. That is what coverage is good at, finding code no test has run. Add --cov-fail-under=80 to fail the run below a threshold. Add --cov-branch to also track whether both sides of each if ran. With every test included, the plain line report says 100%, and the branch report finds something the line report could not.$ pytest -q --cov=labelkit --cov-branch --cov-report=term-missing
Name Stmts Miss Branch BrPart Cover Missing
------------------------------------------------------------------
labelkit/__init__.py 0 0 0 0 100%
labelkit/cleaning.py 2 0 0 0 100%
labelkit/cli.py 12 0 2 1 93% 14->16
labelkit/client.py 8 0 0 0 100%
labelkit/metrics.py 3 0 0 0 100%
labelkit/storage.py 14 0 4 0 100%
------------------------------------------------------------------
TOTAL 39 0 6 1 98%
14->16 means: the jump from line 14, if dropped:, to line 16 never happened. Every test has at least one unlabelled row, so the if was never false.labelkit/cleaning.py (if row.get("label") without the is not None) and add a test that calls clean_rows and asserts nothing.# tests/test_no_assert.py
from labelkit.cleaning import clean_rows
def test_clean_rows_runs():
clean_rows([{"id": 1, "label": 1}, {"id": 2, "label": 0}])$ pytest -q --cov=labelkit.cleaning --cov-report=term-missing tests/test_no_assert.py
. [100%]
Name Stmts Miss Cover Missing
----------------------------------------------------
labelkit/cleaning.py 2 0 100%
----------------------------------------------------
TOTAL 2 0 100%
1 passed in 0.03s
def line and the return, and the test ran both. The run passes with 100% coverage and the bug is still there, because the test never looks at what clean_rows returned. Read a coverage report as a list of code that has never run under test. A low number is information. A high number says the lines executed, and nothing more.#A small project layout with conftest.py
conftest.py, holds the fixtures that several test files share. (The small demo files from earlier, demo/test_demo_scope.py, tests/test_forgot.py and tests/test_no_assert.py, are left out of the tree: they exist only to show one output each.)labelkit/
pyproject.toml
labelkit/
__init__.py
cleaning.py
metrics.py
storage.py
client.py
cli.py
tests/
conftest.py
test_cleaning.py
test_metrics.py
test_storage.py
test_client.py
test_cli.py
test_markers.py
conftest.py by itself, and every fixture in it is available to all tests in that folder and below, with no import. A second conftest.py in a subfolder, say tests/integration/, adds fixtures for that subtree only, and a fixture with the same name there overrides the outer one. Fixtures used by one file belong in that file.# tests/conftest.py (the rows and audit_log fixtures from earlier live here too)
import pytest
import requests
@pytest.fixture(autouse=True)
def no_network(monkeypatch):
"""Make any real HTTP request fail loudly instead of reaching a server."""
def blocked(*args, **kwargs):
raise RuntimeError("a test tried to use the network")
monkeypatch.setattr(requests.sessions.Session, "request", blocked)autouse=True applies a fixture to every test without being named, which suits a safety net like this one. The last piece is configuration, so pytest works from the project root and can import labelkit.# pyproject.toml
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
addopts = "--strict-markers"
markers = [
"slow: takes more than a second; deselect with -m 'not slow'",
]
pythonpath = ["."] puts the project root on the import path. Installing the package in editable mode with pip install -e . is the alternative once you have a build configuration. The full suite then runs like this. The numbers are from pytest 9 on Python 3.12 and 3.13, and the timings will differ on your machine.$ pytest -q
..........x....... [100%]
17 passed, 1 xfailed in 0.17s
#Common mistakes
Four mistakes cause most of the confusing test failures.
Mocking where the name was defined, not where it is used
labelkit/client.py said from requests import post, then mocker.patch("requests.post") would miss it and the real call would go out. Patch labelkit.client.post, the name the code under test looks up.A mock that returns a truthy Mock
Mock. In the test below the response is meant to be a failure, but code that checks response.ok sees a truthy object and carries on.label_from should raise RuntimeError for a failed response. The test builds a failing response, but it reports that no error was raised. Make the fake response really look like a failure so the output is 'raised: service error'.
raised: service error
Sharing a mutable fixture across a wide scope
A test passes alone and fails in the full run, as the session-scoped list showed. Keep fixtures at function scope unless the value is expensive and read-only.
Tests that assert nothing
def test_nothing(): clean_rows(rows) passes, and coverage counts it. Break the function by hand once and see which tests go red. A test that stays green is not testing it.#Try it
precision answers: of the rows the model predicted positive, what fraction really are? The function below has a bug. Write three tests as plain functions: one where every positive prediction is right, one with exactly one false alarm, and one where the model predicts no positives at all. Run them, watch the false-alarm test fail, fix precision, and run again.Tests: With the buggy precision, test_one_false_alarm prints FAILED (1 / 3 is not 0.5). After dividing by len(predicted_positive), all three print passed.
precision in a file, write the three tests, turn them into one @pytest.mark.parametrize with ids, and run pytest -v.#Going further
async code is covered in the next lesson, Async/Await & Concurrency, in its section on testing async code. A FastAPI service is tested with the same fixtures plus a test client, which FastAPI Basics covers. pytest.approx also compares lists and NumPy arrays. The playground below lets you switch a bug on and watch which cases fail.Interactive Lab
Watch pytest collect and run tests, toggle a bug on, and see which cases fail and which lines are covered
#Recap
ids makes each case readable in a report. A fixture is setup a test asks for by naming it, yield puts teardown next to setup, and scope sets how long the object lives, with function scope the safe default.tmp_path gives each test its own folder, so file code can be tested without leaving files behind. monkeypatch changes an environment variable or attribute for one test and restores it. capsys and caplog capture what the code printed and logged. A mock replaces an HTTP call so a test checks your logic and never touches the network, and the target to patch is the name your code looks up. Markers select, skip and flag tests, and coverage reports which lines ran, not whether they were checked.#Check yourself
A function calls `requests.post` inside `labelkit/client.py`, which does `import requests`. Which test setup stops it from using the network and lets you control the reply?