99import sys
1010from importlib .machinery import SourceFileLoader
1111from pathlib import Path
12- from types import SimpleNamespace
12+ from types import ModuleType , SimpleNamespace
1313
1414import pytest
1515
1818PATH_POLICY_PATH = ROOT / ".github" / "scripts" / "_ci_paths.py"
1919VALIDATION_PLAN_PATH = ROOT / "benchmarks" / "tooling" / "validation_plan.py"
2020VALIDATOR_PATH = ROOT / ".github" / "scripts" / "validate-benchmark-plan"
21- _SPEC = importlib .util .spec_from_loader (
22- "benchmark_planner" , SourceFileLoader ("benchmark_planner" , str (PLANNER_PATH ))
23- )
24- assert _SPEC is not None and _SPEC .loader is not None
25- planner = importlib .util .module_from_spec (_SPEC )
26- sys .modules ["benchmark_planner" ] = planner
27- _SPEC .loader .exec_module (planner )
21+
22+
23+ def _load_script (module_name : str , path : Path ) -> ModuleType :
24+ spec = importlib .util .spec_from_loader (
25+ module_name , SourceFileLoader (module_name , str (path ))
26+ )
27+ assert spec is not None and spec .loader is not None
28+ module = importlib .util .module_from_spec (spec )
29+ with pytest .MonkeyPatch .context () as module_state :
30+ module_state .setitem (sys .modules , module_name , module )
31+ spec .loader .exec_module (module )
32+ return module
33+
34+
35+ planner = _load_script ("benchmark_planner" , PLANNER_PATH )
2836
2937
3038@pytest .fixture (autouse = True )
@@ -38,6 +46,34 @@ def stable_digests(monkeypatch: pytest.MonkeyPatch) -> None:
3846 )
3947
4048
49+ @pytest .mark .parametrize ("preserve_existing" , [False , True ])
50+ def test_load_script_scopes_sys_modules_registration (
51+ tmp_path : Path ,
52+ monkeypatch : pytest .MonkeyPatch ,
53+ * ,
54+ preserve_existing : bool ,
55+ ) -> None :
56+ module_name = "_benchmark_planner_module_probe"
57+ source = tmp_path / "module_probe.py"
58+ source .write_text (
59+ "import sys\n registered_while_loading = sys.modules[__name__]\n " ,
60+ encoding = "utf-8" ,
61+ )
62+ sentinel = ModuleType ("sentinel" )
63+ if preserve_existing :
64+ monkeypatch .setitem (sys .modules , module_name , sentinel )
65+ else :
66+ monkeypatch .delitem (sys .modules , module_name , raising = False )
67+
68+ loaded = _load_script (module_name , source )
69+
70+ assert vars (loaded )["registered_while_loading" ] is loaded
71+ if preserve_existing :
72+ assert sys .modules [module_name ] is sentinel
73+ else :
74+ assert module_name not in sys .modules
75+
76+
4177def _matrix (result : dict [str , str ]) -> list [dict [str , object ]]:
4278 return json .loads (result ["benchmark-oracle-matrix" ])
4379
0 commit comments