1"""Sum each package's test time in a pytest run, for the runner to print.
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"""
25_sums: dict[str, dict[str, float]] = defaultdict(lambda: {"seconds": 0.0, "tests": 0})
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
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 )