@@ -102,134 +102,17 @@ func pythonFileURI(path string) string {
102102 return (& url.URL {Scheme : "file" , Path : slashed }).String ()
103103}
104104
105- func hasPytestInstalled (ctx context.Context , pythonExec string , extraEnv map [string ]string ) bool {
106- if pythonExec == "" {
107- return false
108- }
109- cmd := exec .CommandContext (ctx , pythonExec , "-B" , "-c" , "import pytest" )
110- cmd .Env = os .Environ ()
111- for k , v := range extraEnv {
112- cmd .Env = append (cmd .Env , k + "=" + v )
113- }
114- return cmd .Run () == nil
115- }
116-
117- // resolvePytestToolForE2E returns a Python executable + optional environment that can run pytest,
118- // preferring systemPython, then local developer virtualenvs, and finally a tiny hermetic pytest module.
119105func resolvePytestToolForE2E (t * testing.T , ctx context.Context , systemPython string ) core.BuildTool {
120106 t .Helper ()
121- if hasPytestInstalled (ctx , systemPython , nil ) {
122- return core.BuildTool {Executable : systemPython }
123- }
124- if home , err := os .UserHomeDir (); err == nil {
125- entries , _ := os .ReadDir (home )
126- for _ , entry := range entries {
127- name := entry .Name ()
128- if strings .HasPrefix (name , ".venv" ) || strings .Contains (name , "conda" ) || strings .HasPrefix (name , "miniforge" ) {
129- cand := filepath .Join (home , name , "bin" , "python3" )
130- if runtime .GOOS == "windows" {
131- cand = filepath .Join (home , name , "Scripts" , "python.exe" )
132- }
133- if info , statErr := os .Stat (cand ); statErr == nil && ! info .IsDir () && hasPytestInstalled (ctx , cand , nil ) {
134- return core.BuildTool {Executable : cand }
135- }
136- }
137- }
138- }
139-
140- // Hermetic offline fallback so air-gapped hosts never require PyPI access.
141- shimDir := t .TempDir ()
142- pkgDir := filepath .Join (shimDir , "pytest" )
143- if err := os .MkdirAll (pkgDir , 0o755 ); err != nil {
144- t .Fatal (err )
145- }
146- shimInit := `import importlib.util, inspect, pathlib, sys, xml.etree.ElementTree as ET
147- class _Item:
148- def __init__(self, nodeid, path, name, fn):
149- self.nodeid, self.path, self.name, self.fn = nodeid, path, name, fn
150- class _Config:
151- def __init__(self, rootpath):
152- self.rootpath = rootpath
153- def _parametrize(argnames, argvalues):
154- names = [n.strip() for n in argnames.split(",")] if isinstance(argnames, str) else list(argnames)
155- def _deco(fn):
156- fn._parametrize = (names, list(argvalues))
157- return fn
158- return _deco
159- class _Mark:
160- parametrize = staticmethod(_parametrize)
161- mark = _Mark()
162- def _discover(root):
163- items = []
164- for p in sorted(root.rglob("test_*.py")):
165- rel = p.relative_to(root).as_posix()
166- spec = importlib.util.spec_from_file_location(rel.replace("/", "_").replace(".py", ""), p)
167- mod = importlib.util.module_from_spec(spec)
168- spec.loader.exec_module(mod)
169- for k, v in vars(mod).items():
170- if callable(v) and k.startswith("test_"):
171- prm = getattr(v, "_parametrize", None)
172- if prm:
173- pnames, pvals = prm
174- for row in pvals:
175- vals = row if isinstance(row, (tuple, list)) else (row,)
176- lbl = "-".join(str(x) for x in vals)
177- kw = dict(zip(pnames, vals))
178- items.append(_Item(f"{rel}::{k}[{lbl}]", p, f"{k}[{lbl}]", lambda fn=v, kw=kw: fn(**kw)))
179- else:
180- items.append(_Item(f"{rel}::{k}", p, k, v))
181- return items
182- def main(args=None, plugins=None):
183- argv = list(args or sys.argv[1:])
184- collect_only = "--collect-only" in argv
185- junit_xml = None
186- selectors = []
187- i = 0
188- while i < len(argv):
189- a = argv[i]
190- if a == "--":
191- selectors.extend(argv[i + 1:])
192- break
193- elif a.startswith("--junitxml="):
194- junit_xml = a.split("=", 1)[1]
195- elif a in ("-o", "-k"):
196- i += 1
197- elif not a.startswith("-"):
198- selectors.append(a)
199- i += 1
200- cwd = pathlib.Path.cwd().resolve()
201- items = _discover(cwd)
202- if selectors:
203- items = [it for it in items if any(it.nodeid == s or it.nodeid.startswith(s + "::") for s in selectors)]
204- cfg = _Config(cwd)
205- for plug in (plugins or []):
206- if hasattr(plug, "pytest_collection_modifyitems"):
207- plug.pytest_collection_modifyitems(None, cfg, items)
208- if not items:
209- return 5
210- if collect_only:
211- return 0
212- suite_el = ET.Element("testsuite", name="pytest", tests=str(len(items)), failures="0")
213- for it in items:
214- cname = it.path.relative_to(cwd).with_suffix("").as_posix().replace("/", ".")
215- ET.SubElement(suite_el, "testcase", classname=cname, name=it.name, time="0.001")
216- it.fn()
217- if junit_xml:
218- out_p = cwd / junit_xml
219- out_p.parent.mkdir(parents=True, exist_ok=True)
220- ET.ElementTree(suite_el).write(out_p, encoding="utf-8", xml_declaration=True)
221- return 0
222- `
223- if err := os .WriteFile (filepath .Join (pkgDir , "__init__.py" ), []byte (shimInit ), 0o644 ); err != nil {
224- t .Fatal (err )
225- }
226- if err := os .WriteFile (filepath .Join (pkgDir , "__main__.py" ), []byte ("import pytest, sys\n raise SystemExit(pytest.main(sys.argv[1:]))\n " ), 0o644 ); err != nil {
227- t .Fatal (err )
107+ executable := os .Getenv ("PYTEST_PYTHON" )
108+ if executable == "" {
109+ executable = systemPython
228110 }
229- return core. BuildTool {
230- Executable : systemPython ,
231- Environment : map [ string ] string { "PYTHONPATH" : shimDir },
111+ cmd := exec . CommandContext ( ctx , executable , "-B" , "-c" , "import pytest" )
112+ if err := cmd . Run (); err != nil {
113+ t . Fatalf ( "pytest is required for the host test; set PYTEST_PYTHON to an interpreter with pytest: %v" , err )
232114 }
115+ return core.BuildTool {Executable : executable }
233116}
234117
235118func TestPythonSupportPluginContractPlansInstallAndImmutability (t * testing.T ) {
@@ -715,16 +598,6 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
715598 t .Fatal (err )
716599 }
717600 testProviderParams ["tool" ] = map [string ]any {"executable" : pytestTool .Executable }
718- if len (pytestTool .Environment ) > 0 {
719- envObj , _ := testProviderParams ["environment" ].(map [string ]any )
720- if envObj == nil {
721- envObj = map [string ]any {}
722- }
723- for k , v := range pytestTool .Environment {
724- envObj [k ] = v
725- }
726- testProviderParams ["environment" ] = envObj
727- }
728601 enrichedTestParams , err := json .Marshal (testProviderParams )
729602 if err != nil {
730603 t .Fatal (err )
0 commit comments