Skip to content

Commit 84909ef

Browse files
test: reach the loaded package conftest through one shared helper
test_readiness_scaling.py imported the package conftest by name at six sites to call the hooks under test. Under the workspace default --import-mode=importlib that executes packages/studyloop/tests/conftest.py a second time as a separate module (sys.modules['conftest'] beside the registered 'packages.studyloop.tests.conftest'), so the tests patched and called a copy nothing else runs; the pid markers only kept the re-run from re-pointing the sandbox (lane O, review 4, found-not-fixed #4). _loaded_package_conftest moves out of test_suite_isolation.py into tests/_conftest_access.py as loaded_package_conftest(config) and both modules use it. Two new isolation tests prove the property: an AST scan that no test module imports 'conftest' by name, and a runtime check that exactly one module object executed from the file is in sys.modules and it is the registered plugin (red on 137ccad under both the package rootdir and the workspace rootdir).
1 parent 361d729 commit 84909ef

3 files changed

Lines changed: 175 additions & 62 deletions

File tree

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
"""Reach the package conftest pytest actually loaded, without executing it again.
2+
3+
Under the workspace's ``--import-mode=importlib`` a test module's
4+
``from conftest import ...`` executes ``packages/studyloop/tests/conftest.py`` a
5+
second time as a separate module object: a second mkdtemp'd
6+
``_TMUX_TMPDIR_ROOT``, a second ``_SESSION_SCALE``, hook functions that are not
7+
the ones pytest calls. The pid markers inside that conftest keep the re-run from
8+
re-pointing the sandbox, but a test that patches or calls the copy is testing a
9+
module nothing else runs. :func:`loaded_package_conftest` returns the module
10+
pytest registered as a plugin, so tests of the conftest's hooks exercise the
11+
real ones -- and ``test_suite_isolation.py`` proves the conftest is loaded once.
12+
13+
Not a test module (leading underscore, per ``docs/contributor-conventions.md``).
14+
"""
15+
16+
from __future__ import annotations
17+
18+
import sys
19+
from pathlib import Path
20+
from types import ModuleType
21+
from typing import TYPE_CHECKING
22+
23+
if TYPE_CHECKING:
24+
import pytest
25+
26+
#: The one conftest this helper resolves; the workspace root has another.
27+
PACKAGE_CONFTEST = Path(__file__).resolve().parent / "conftest.py"
28+
29+
30+
def loaded_package_conftest(config: pytest.Config) -> ModuleType:
31+
"""Return the ``packages/studyloop/tests/conftest.py`` module whose hooks run."""
32+
for plugin in config.pluginmanager.get_plugins():
33+
location = getattr(plugin, "__file__", None)
34+
if (
35+
isinstance(plugin, ModuleType)
36+
and location
37+
and Path(location).resolve() == PACKAGE_CONFTEST
38+
):
39+
return plugin
40+
raise AssertionError(f"pytest did not load {PACKAGE_CONFTEST} as a plugin")
41+
42+
43+
def modules_loaded_from_package_conftest() -> list[str]:
44+
"""Names under which ``sys.modules`` holds a module executed from the package conftest.
45+
46+
Exactly one entry is expected: the plugin pytest registered. A second entry
47+
(``conftest``) means some test module imported the file by name and ran it
48+
again.
49+
"""
50+
return [
51+
name
52+
for name, module in list(sys.modules.items())
53+
if isinstance(module, ModuleType)
54+
and getattr(module, "__file__", None)
55+
and Path(str(module.__file__)).resolve() == PACKAGE_CONFTEST
56+
]

‎packages/studyloop/tests/test_readiness_scaling.py‎

Lines changed: 57 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from typing import Any, ClassVar
1212

1313
import pytest
14+
from _conftest_access import loaded_package_conftest
1415

1516

1617
class TestScalingContract:
@@ -127,7 +128,7 @@ class TestTheCollectionHook:
127128
"""One hook — and pytest calls only one function by that name."""
128129

129130
def test_e2e_items_still_get_their_per_test_timeout(
130-
self, monkeypatch: pytest.MonkeyPatch
131+
self, monkeypatch: pytest.MonkeyPatch, pytestconfig: pytest.Config
131132
) -> None:
132133
"""The readiness scale must not have displaced the e2e timeout marker.
133134
@@ -137,13 +138,9 @@ def test_e2e_items_still_get_their_per_test_timeout(
137138
marker, which would have turned a hanging e2e test from a 300s failure into
138139
a run that never ends. Nothing covered it, so nothing failed.
139140
"""
140-
141-
# from-import so the one suppression covers it; `conftest.X` would need
142-
# one at every use site.
143-
from conftest import (
144-
E2E_TIMEOUT_SECONDS, # pyright: ignore[reportAttributeAccessIssue]
145-
pytest_collection_modifyitems, # pyright: ignore[reportAttributeAccessIssue]
146-
)
141+
# The plugin pytest registered, not a bare-name import that would execute
142+
# the conftest a second time under --import-mode=importlib.
143+
conftest = loaded_package_conftest(pytestconfig)
147144

148145
applied: list[Any] = []
149146

@@ -162,17 +159,17 @@ def add_marker(self, marker) -> None:
162159
already_timed = FakeItem({"e2e", "timeout"})
163160

164161
monkeypatch.delenv("STUDYLOOP_E2E_TIMEOUT_SCALE", raising=False)
165-
pytest_collection_modifyitems([e2e_item, plain_item, already_timed])
162+
conftest.pytest_collection_modifyitems([e2e_item, plain_item, already_timed])
166163

167164
assert len(applied) == 1, (
168165
f"expected exactly one timeout marker (the bare e2e item), got {len(applied)}"
169166
)
170-
assert applied[0].args == (E2E_TIMEOUT_SECONDS,), (
171-
f"expected a {E2E_TIMEOUT_SECONDS}s budget, got {applied[0].args}"
167+
assert applied[0].args == (conftest.E2E_TIMEOUT_SECONDS,), (
168+
f"expected a {conftest.E2E_TIMEOUT_SECONDS}s budget, got {applied[0].args}"
172169
)
173170

174171
def test_the_hook_does_not_touch_the_readiness_scale(
175-
self, monkeypatch: pytest.MonkeyPatch
172+
self, monkeypatch: pytest.MonkeyPatch, pytestconfig: pytest.Config
176173
) -> None:
177174
"""Collection must not set the multiplier, however large the run.
178175
@@ -181,9 +178,7 @@ def test_the_hook_does_not_touch_the_readiness_scale(
181178
"""
182179
import _readiness
183180

184-
from conftest import (
185-
pytest_collection_modifyitems, # pyright: ignore[reportAttributeAccessIssue]
186-
)
181+
conftest = loaded_package_conftest(pytestconfig)
187182

188183
monkeypatch.delenv("STUDYLOOP_E2E_TIMEOUT_SCALE", raising=False)
189184
monkeypatch.setattr(_readiness, "_scale", 1.0, raising=False)
@@ -195,38 +190,38 @@ def get_closest_marker(self, name: str) -> None:
195190
def add_marker(self, marker) -> None: # pragma: no cover
196191
raise AssertionError("a non-e2e item should not be marked")
197192

198-
pytest_collection_modifyitems([FakeItem() for _ in range(3599)])
193+
conftest.pytest_collection_modifyitems([FakeItem() for _ in range(3599)])
199194

200195
assert _readiness.readiness_scale() == 1.0
201196

202-
def test_the_header_states_the_multiplier(self, monkeypatch: pytest.MonkeyPatch) -> None:
197+
def test_the_header_states_the_multiplier(
198+
self, monkeypatch: pytest.MonkeyPatch, pytestconfig: pytest.Config
199+
) -> None:
203200
"""Every run must say what sensitivity produced its pass count.
204201
205202
The report that started this work said "500 passed" without recording
206203
that budgets had been widened, so the number could not be interpreted.
207204
"""
208205
import _readiness
209206

210-
from conftest import (
211-
pytest_report_header, # pyright: ignore[reportAttributeAccessIssue]
212-
)
207+
conftest = loaded_package_conftest(pytestconfig)
213208

214209
# setattr, so monkeypatch restores the module global too. Only setenv-ing
215210
# left _scale at 3.0 after teardown, and the terminal-summary hook then
216211
# warned that an unscaled run was scaled.
217212
monkeypatch.setattr(_readiness, "_scale", 1.0, raising=False)
218213
monkeypatch.delenv("STUDYLOOP_E2E_TIMEOUT_SCALE", raising=False)
219-
unscaled = pytest_report_header()
214+
unscaled = conftest.pytest_report_header()
220215
assert "1.0x" in unscaled
221216
assert "release configuration" in unscaled
222217

223218
monkeypatch.setenv("STUDYLOOP_E2E_TIMEOUT_SCALE", "3")
224-
scaled = pytest_report_header()
219+
scaled = conftest.pytest_report_header()
225220
assert "3.0x" in scaled
226221
assert "NOT a release-pass configuration" in scaled
227222

228223
def test_the_summary_warning_tracks_the_session_not_the_global(
229-
self, monkeypatch: pytest.MonkeyPatch
224+
self, monkeypatch: pytest.MonkeyPatch, pytestconfig: pytest.Config
230225
) -> None:
231226
"""A test mutating the scale must not make an unscaled run look scaled.
232227
@@ -238,7 +233,7 @@ def test_the_summary_warning_tracks_the_session_not_the_global(
238233
"""
239234
import _readiness
240235

241-
import conftest
236+
conftest = loaded_package_conftest(pytestconfig)
242237

243238
monkeypatch.setattr(conftest, "_SESSION_SCALE", 1.0, raising=False)
244239
monkeypatch.setattr(_readiness, "_scale", 3.0, raising=False)
@@ -249,20 +244,15 @@ class FakeReporter:
249244
def write_sep(self, sep: str, text: str, **kwargs: object) -> None:
250245
written.append(text)
251246

252-
# Two conftest.py files exist in this repo, so the type checker cannot
253-
# tell which module this name resolves to -- the same reason sibling
254-
# imports here carry per-symbol ignores.
255-
conftest.pytest_terminal_summary( # pyright: ignore[reportAttributeAccessIssue]
256-
FakeReporter() # pyright: ignore[reportArgumentType]
257-
)
247+
conftest.pytest_terminal_summary(FakeReporter())
258248

259249
assert written == [], f"warned about scaling on an unscaled session: {written}"
260250

261251
def test_the_summary_warns_when_the_session_really_was_scaled(
262-
self, monkeypatch: pytest.MonkeyPatch
252+
self, monkeypatch: pytest.MonkeyPatch, pytestconfig: pytest.Config
263253
) -> None:
264254
"""And it must still fire when it matters, under -q as well."""
265-
import conftest
255+
conftest = loaded_package_conftest(pytestconfig)
266256

267257
monkeypatch.setattr(conftest, "_SESSION_SCALE", 3.0, raising=False)
268258

@@ -272,12 +262,7 @@ class FakeReporter:
272262
def write_sep(self, sep: str, text: str, **kwargs: object) -> None:
273263
written.append(text)
274264

275-
# Two conftest.py files exist in this repo, so the type checker cannot
276-
# tell which module this name resolves to -- the same reason sibling
277-
# imports here carry per-symbol ignores.
278-
conftest.pytest_terminal_summary( # pyright: ignore[reportAttributeAccessIssue]
279-
FakeReporter() # pyright: ignore[reportArgumentType]
280-
)
265+
conftest.pytest_terminal_summary(FakeReporter())
281266

282267
assert len(written) == 1
283268
assert "NOT a release result" in written[0]
@@ -342,8 +327,15 @@ class TestHollowRunGuard:
342327
"""
343328

344329
@staticmethod
345-
def _run(monkeypatch: pytest.MonkeyPatch, *, required: str | None, passed: int, skipped: int):
346-
import conftest
330+
def _run(
331+
monkeypatch: pytest.MonkeyPatch,
332+
config: pytest.Config,
333+
*,
334+
required: str | None,
335+
passed: int,
336+
skipped: int,
337+
):
338+
conftest = loaded_package_conftest(config)
347339

348340
if required is None:
349341
monkeypatch.delenv("STUDYLOOP_MIN_PASSED", raising=False)
@@ -373,40 +365,54 @@ class FakeSession:
373365
exitstatus = 0
374366

375367
session = FakeSession()
376-
conftest.pytest_sessionfinish(session, 0) # pyright: ignore[reportAttributeAccessIssue]
368+
conftest.pytest_sessionfinish(session, 0)
377369
return session, written
378370

379-
def test_a_hollow_run_fails(self, monkeypatch: pytest.MonkeyPatch) -> None:
371+
def test_a_hollow_run_fails(
372+
self, monkeypatch: pytest.MonkeyPatch, pytestconfig: pytest.Config
373+
) -> None:
380374
"""400 of 500 tests skipping because ttyd vanished must not read green."""
381-
session, written = self._run(monkeypatch, required="450", passed=100, skipped=400)
375+
session, written = self._run(
376+
monkeypatch, pytestconfig, required="450", passed=100, skipped=400
377+
)
382378

383379
assert session.exitstatus == 1
384380
assert "HOLLOW RUN" in written[0]
385381
assert "400 skipped" in written[0]
386382

387-
def test_a_full_run_passes(self, monkeypatch: pytest.MonkeyPatch) -> None:
388-
session, written = self._run(monkeypatch, required="450", passed=500, skipped=20)
383+
def test_a_full_run_passes(
384+
self, monkeypatch: pytest.MonkeyPatch, pytestconfig: pytest.Config
385+
) -> None:
386+
session, written = self._run(
387+
monkeypatch, pytestconfig, required="450", passed=500, skipped=20
388+
)
389389

390390
assert session.exitstatus == 0
391391
assert written == []
392392

393-
def test_exactly_the_minimum_is_enough(self, monkeypatch: pytest.MonkeyPatch) -> None:
394-
session, _ = self._run(monkeypatch, required="500", passed=500, skipped=0)
393+
def test_exactly_the_minimum_is_enough(
394+
self, monkeypatch: pytest.MonkeyPatch, pytestconfig: pytest.Config
395+
) -> None:
396+
session, _ = self._run(monkeypatch, pytestconfig, required="500", passed=500, skipped=0)
395397

396398
assert session.exitstatus == 0
397399

398-
def test_unset_leaves_local_runs_alone(self, monkeypatch: pytest.MonkeyPatch) -> None:
400+
def test_unset_leaves_local_runs_alone(
401+
self, monkeypatch: pytest.MonkeyPatch, pytestconfig: pytest.Config
402+
) -> None:
399403
"""Running one file must not trip a suite-sized threshold."""
400-
session, written = self._run(monkeypatch, required=None, passed=3, skipped=0)
404+
session, written = self._run(monkeypatch, pytestconfig, required=None, passed=3, skipped=0)
401405

402406
assert session.exitstatus == 0
403407
assert written == []
404408

405409
def test_a_garbage_threshold_is_ignored_rather_than_fatal(
406-
self, monkeypatch: pytest.MonkeyPatch
410+
self, monkeypatch: pytest.MonkeyPatch, pytestconfig: pytest.Config
407411
) -> None:
408412
"""A typo in CI config must not fail every run for the wrong reason."""
409-
session, written = self._run(monkeypatch, required="lots", passed=1, skipped=0)
413+
session, written = self._run(
414+
monkeypatch, pytestconfig, required="lots", passed=1, skipped=0
415+
)
410416

411417
assert session.exitstatus == 0
412418
assert written == []

0 commit comments

Comments
 (0)