Coverage for packages/workshop/src/livery/workshop/_pytest_speed.py: 100%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop, packages/extensions/ty, packages/extensions/ruff, packages/extensions/python, packages/extensions/pytest, packages/extensions/pyrefly, packages/extensions/nanobind, packages/extensions/mypy, packages/extensions/mkdocstrings, packages/extensions/lfs, packages/extensions/docs, packages/extensions/cpp, packages/extensions/coverage, packages/extensions/conan, packages/extensions/cmake, packages/extensions/claude, packages/extensions/clang-tidy, packages/extensions/clang-format, packages/extensions/changelog, packages/extensions/basedpyright ran.

1"""Sum each package's test time in a pytest run, for the runner to print.
2
3Registered through livery-workshop's ``pytest11`` entry point, so every
4pytest this venv starts carries it. It acts only when the test runner
5names a file in [livery.workshop.SPEED_FILE_VARIABLE][],
6``WORKSHOP_SPEED_FILE``: every phase of every test adds its duration
7to the sum of its package, the one [livery.workshop.package_of][]
8names, and the session's end writes the sums as JSON to that file,
9from the controlling process alone under xdist. A pytest started
10without the variable, the nested runs the workshop's own tests spawn
11included, sums nothing and writes nothing.
12"""
13
14from __future__ import annotations(empty)
15
16import json(empty)
17import os(empty)
18from collections import defaultdict(empty)
19from pathlib import Path(empty)
20
21import pytest(empty)
22
23from livery.workshop import SPEED_FILE_VARIABLE, package_of(empty)
24
25_sums: dict[str, dict[str, float]] = defaultdict(lambda: {"seconds": 0.0, "tests": 0})
26
27
28def pytest_runtest_logreport(report: pytest.TestReport) -> None:(empty)
29 """Add the phase's duration to its package's sum."""
30 if not os.environ.get(SPEED_FILE_VARIABLE):
31 return
32 package = package_of(report.nodeid)
33 if not package:
34 return
35 _sums[package]["seconds"] += report.duration
36 if report.when == "call":
37 _sums[package]["tests"] += 1
38
39
40def pytest_sessionfinish((empty)
41 session: pytest.Session, exitstatus: int | pytest.ExitCode
42) -> None:
43 """Write the sums to the named file, from the controlling process."""
44 target = os.environ.get(SPEED_FILE_VARIABLE)
45 if not target or hasattr(session.config, "workerinput"):
46 return
47 Path(target).write_text(
48 json.dumps(
49 {
50 package: {
51 "seconds": round(data["seconds"], 1),
52 "tests": int(data["tests"]),
53 }
54 for package, data in sorted(_sums.items())
55 }
56 ),
57 encoding="utf-8",
58 )