Debian Codegraph @

Lib/test/test_launcher.py

raw
1 import contextlib
2 import itertools
3 import os
4 import re
5 import shutil
6 import subprocess
7 import sys
8 import sysconfig
9 import tempfile
10 import unittest
11 from pathlib import Path
12 from test import support
13
14 if sys.platform != "win32":
15 raise unittest.SkipTest("test only applies to Windows")
16
17 # Get winreg after the platform check
18 import winreg
19
20
21 PY_EXE = "py.exe"
22 DEBUG_BUILD = False
23 if sys.executable.casefold().endswith("_d.exe".casefold()):
24 PY_EXE = "py_d.exe"
25 DEBUG_BUILD = True
26
27 # Registry data to create. On removal, everything beneath top-level names will
28 # be deleted.
29 TEST_DATA = {
30 "PythonTestSuite": {
31 "DisplayName": "Python Test Suite",
32 "SupportUrl": "https://www.python.org/",
33 "3.100": {
34 "DisplayName": "X.Y version",
35 "InstallPath": {
36 None: sys.prefix,
37 "ExecutablePath": "X.Y.exe",
38 }
39 },
40 "3.100-32": {
41 "DisplayName": "X.Y-32 version",
42 "InstallPath": {
43 None: sys.prefix,
44 "ExecutablePath": "X.Y-32.exe",
45 }
46 },
47 "3.100-arm64": {
48 "DisplayName": "X.Y-arm64 version",
49 "InstallPath": {
50 None: sys.prefix,
51 "ExecutablePath": "X.Y-arm64.exe",
52 "ExecutableArguments": "-X fake_arg_for_test",
53 }
54 },
55 "ignored": {
56 "DisplayName": "Ignored because no ExecutablePath",
57 "InstallPath": {
58 None: sys.prefix,
59 }
60 },
61 },
62 "PythonTestSuite1": {
63 "DisplayName": "Python Test Suite Single",
64 "3.100": {
65 "DisplayName": "Single Interpreter",
66 "InstallPath": {
67 None: sys.prefix,
68 "ExecutablePath": sys.executable,
69 }
70 }
71 },
72 }
73
74
75 TEST_PY_ENV = dict(
76 PY_PYTHON="PythonTestSuite/3.100",
77 PY_PYTHON2="PythonTestSuite/3.100-32",
78 PY_PYTHON3="PythonTestSuite/3.100-arm64",
79 )
80
81
82 TEST_PY_DEFAULTS = "\n".join([
83 "[defaults]",
84 *[f"{k[3:].lower()}={v}" for k, v in TEST_PY_ENV.items()],
85 ])
86
87
88 TEST_PY_COMMANDS = "\n".join([
89 "[commands]",
90 "test-command=TEST_EXE.exe",
91 ])
92
93
94 def quote(s):
95 s = str(s)
96 return f'"{s}"' if " " in s else s
97
98
99 def create_registry_data(root, data):
100 def _create_registry_data(root, key, value):
101 if isinstance(value, dict):
102 # For a dict, we recursively create keys
103 with winreg.CreateKeyEx(root, key) as hkey:
104 for k, v in value.items():
105 _create_registry_data(hkey, k, v)
106 elif isinstance(value, str):
107 # For strings, we set values. 'key' may be None in this case
108 winreg.SetValueEx(root, key, None, winreg.REG_SZ, value)
109 else:
110 raise TypeError("don't know how to create data for '{}'".format(value))
111
112 for k, v in data.items():
113 _create_registry_data(root, k, v)
114
115
116 def enum_keys(root):
117 for i in itertools.count():
118 try:
119 yield winreg.EnumKey(root, i)
120 except OSError as ex:
121 if ex.winerror == 259:
122 break
123 raise
124
125
126 def delete_registry_data(root, keys):
127 ACCESS = winreg.KEY_WRITE | winreg.KEY_ENUMERATE_SUB_KEYS
128 for key in list(keys):
129 with winreg.OpenKey(root, key, access=ACCESS) as hkey:
130 delete_registry_data(hkey, enum_keys(hkey))
131 winreg.DeleteKey(root, key)
132
133
134 def is_installed(tag):
135 key = rf"Software\Python\PythonCore\{tag}\InstallPath"
136 for root, flag in [
137 (winreg.HKEY_CURRENT_USER, 0),
138 (winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_64KEY),
139 (winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_32KEY),
140 ]:
141 try:
142 winreg.CloseKey(winreg.OpenKey(root, key, access=winreg.KEY_READ | flag))
143 return True
144 except OSError:
145 pass
146 return False
147
148
149 class PreservePyIni:
150 def __init__(self, path, content):
151 self.path = Path(path)
152 self.content = content
153 self._preserved = None
154
155 def __enter__(self):
156 try:
157 self._preserved = self.path.read_bytes()
158 except FileNotFoundError:
159 self._preserved = None
160 self.path.write_text(self.content, encoding="utf-16")
161
162 def __exit__(self, *exc_info):
163 if self._preserved is None:
164 self.path.unlink()
165 else:
166 self.path.write_bytes(self._preserved)
167
168
169 class RunPyMixin:
170 py_exe = None
171
172 @classmethod
173 def find_py(cls):
174 py_exe = None
175 if sysconfig.is_python_build():
176 py_exe = Path(sys.executable).parent / PY_EXE
177 else:
178 for p in os.getenv("PATH").split(";"):
179 if p:
180 py_exe = Path(p) / PY_EXE
181 if py_exe.is_file():
182 break
183 else:
184 py_exe = None
185
186 # Test launch and check version, to exclude installs of older
187 # releases when running outside of a source tree
188 if py_exe:
189 try:
190 with subprocess.Popen(
191 [py_exe, "-h"],
192 stdin=subprocess.PIPE,
193 stdout=subprocess.PIPE,
194 stderr=subprocess.PIPE,
195 encoding="ascii",
196 errors="ignore",
197 ) as p:
198 p.stdin.close()
199 version = next(p.stdout, "\n").splitlines()[0].rpartition(" ")[2]
200 p.stdout.read()
201 p.wait(10)
202 if not sys.version.startswith(version):
203 py_exe = None
204 except OSError:
205 py_exe = None
206
207 if not py_exe:
208 raise unittest.SkipTest(
209 "cannot locate '{}' for test".format(PY_EXE)
210 )
211 return py_exe
212
213 def get_py_exe(self):
214 if not self.py_exe:
215 self.py_exe = self.find_py()
216 return self.py_exe
217
218 def run_py(self, args, env=None, allow_fail=False, expect_returncode=0, argv=None):
219 if not self.py_exe:
220 self.py_exe = self.find_py()
221
222 ignore = {"VIRTUAL_ENV", "PY_PYTHON", "PY_PYTHON2", "PY_PYTHON3"}
223 env = {
224 **{k.upper(): v for k, v in os.environ.items() if k.upper() not in ignore},
225 "PYLAUNCHER_DEBUG": "1",
226 "PYLAUNCHER_DRYRUN": "1",
227 "PYLAUNCHER_LIMIT_TO_COMPANY": "",
228 **{k.upper(): v for k, v in (env or {}).items()},
229 }
230 if ini_dir := getattr(self, '_ini_dir', None):
231 env.setdefault("_PYLAUNCHER_INIDIR", ini_dir)
232 if not argv:
233 argv = [self.py_exe, *args]
234 with subprocess.Popen(
235 argv,
236 env=env,
237 executable=self.py_exe,
238 stdin=subprocess.PIPE,
239 stdout=subprocess.PIPE,
240 stderr=subprocess.PIPE,
241 ) as p:
242 p.stdin.close()
243 p.wait(10)
244 out = p.stdout.read().decode("utf-8", "replace")
245 err = p.stderr.read().decode("ascii", "replace").replace("\uFFFD", "?")
246 if p.returncode != expect_returncode and support.verbose and not allow_fail:
247 print("++ COMMAND ++")
248 print([self.py_exe, *args])
249 print("++ STDOUT ++")
250 print(out)
251 print("++ STDERR ++")
252 print(err)
253 if allow_fail and p.returncode != expect_returncode:
254 raise subprocess.CalledProcessError(p.returncode, [self.py_exe, *args], out, err)
255 else:
256 self.assertEqual(expect_returncode, p.returncode)
257 data = {
258 s.partition(":")[0]: s.partition(":")[2].lstrip()
259 for s in err.splitlines()
260 if not s.startswith("#") and ":" in s
261 }
262 data["stdout"] = out
263 data["stderr"] = err
264 return data
265
266 def py_ini(self, content):
267 ini_dir = getattr(self, '_ini_dir', None)
268 if not ini_dir:
269 local_appdata = os.environ.get("LOCALAPPDATA")
270 if not local_appdata:
271 raise unittest.SkipTest("LOCALAPPDATA environment variable is "
272 "missing or empty")
273 ini_dir = local_appdata
274 return PreservePyIni(Path(ini_dir) / "py.ini", content)
275
276 @contextlib.contextmanager
277 def script(self, content, encoding="utf-8"):
278 file = Path(tempfile.mktemp(dir=os.getcwd()) + ".py")
279 if isinstance(content, bytes):
280 file.write_bytes(content)
281 else:
282 file.write_text(content, encoding=encoding)
283 try:
284 yield file
285 finally:
286 file.unlink()
287
288 @contextlib.contextmanager
289 def fake_venv(self):
290 venv = Path.cwd() / "Scripts"
291 venv.mkdir(exist_ok=True, parents=True)
292 venv_exe = (venv / ("python_d.exe" if DEBUG_BUILD else "python.exe"))
293 venv_exe.touch()
294 try:
295 yield venv_exe, {"VIRTUAL_ENV": str(venv.parent)}
296 finally:
297 shutil.rmtree(venv)
298
299
300 class TestLauncher(unittest.TestCase, RunPyMixin):
301 @classmethod
302 def setUpClass(cls):
303 with winreg.CreateKey(winreg.HKEY_CURRENT_USER, rf"Software\Python") as key:
304 create_registry_data(key, TEST_DATA)
305
306 if support.verbose:
307 p = subprocess.check_output("reg query HKCU\\Software\\Python /s")
308 #print(p.decode('mbcs'))
309
310 cls._ini_dir = tempfile.mkdtemp()
311 cls.addClassCleanup(shutil.rmtree, cls._ini_dir, ignore_errors=True)
312
313 @classmethod
314 def tearDownClass(cls):
315 with winreg.OpenKey(winreg.HKEY_CURRENT_USER, rf"Software\Python", access=winreg.KEY_WRITE | winreg.KEY_ENUMERATE_SUB_KEYS) as key:
316 delete_registry_data(key, TEST_DATA)
317
318
319 def test_version(self):
320 data = self.run_py(["-0"])
321 self.assertEqual(self.py_exe, Path(data["argv0"]))
322 self.assertEqual(sys.version.partition(" ")[0], data["version"])
323
324 def test_help_option(self):
325 data = self.run_py(["-h"])
326 self.assertEqual("True", data["SearchInfo.help"])
327
328 def test_list_option(self):
329 for opt, v1, v2 in [
330 ("-0", "True", "False"),
331 ("-0p", "False", "True"),
332 ("--list", "True", "False"),
333 ("--list-paths", "False", "True"),
334 ]:
335 with self.subTest(opt):
336 data = self.run_py([opt])
337 self.assertEqual(v1, data["SearchInfo.list"])
338 self.assertEqual(v2, data["SearchInfo.listPaths"])
339
340 def test_list(self):
341 data = self.run_py(["--list"])
342 found = {}
343 expect = {}
344 for line in data["stdout"].splitlines():
345 m = re.match(r"\s*(.+?)\s+?(\*\s+)?(.+)$", line)
346 if m:
347 found[m.group(1)] = m.group(3)
348 for company in TEST_DATA:
349 company_data = TEST_DATA[company]
350 tags = [t for t in company_data if isinstance(company_data[t], dict)]
351 for tag in tags:
352 arg = f"-V:{company}/{tag}"
353 expect[arg] = company_data[tag]["DisplayName"]
354 expect.pop(f"-V:{company}/ignored", None)
355
356 actual = {k: v for k, v in found.items() if k in expect}
357 try:
358 self.assertDictEqual(expect, actual)
359 except:
360 if support.verbose:
361 print("*** STDOUT ***")
362 print(data["stdout"])
363 raise
364
365 def test_list_paths(self):
366 data = self.run_py(["--list-paths"])
367 found = {}
368 expect = {}
369 for line in data["stdout"].splitlines():
370 m = re.match(r"\s*(.+?)\s+?(\*\s+)?(.+)$", line)
371 if m:
372 found[m.group(1)] = m.group(3)
373 for company in TEST_DATA:
374 company_data = TEST_DATA[company]
375 tags = [t for t in company_data if isinstance(company_data[t], dict)]
376 for tag in tags:
377 arg = f"-V:{company}/{tag}"
378 install = company_data[tag]["InstallPath"]
379 try:
380 expect[arg] = install["ExecutablePath"]
381 try:
382 expect[arg] += " " + install["ExecutableArguments"]
383 except KeyError:
384 pass
385 except KeyError:
386 expect[arg] = str(Path(install[None]) / Path(sys.executable).name)
387
388 expect.pop(f"-V:{company}/ignored", None)
389
390 actual = {k: v for k, v in found.items() if k in expect}
391 try:
392 self.assertDictEqual(expect, actual)
393 except:
394 if support.verbose:
395 print("*** STDOUT ***")
396 print(data["stdout"])
397 raise
398
399 def test_filter_to_company(self):
400 company = "PythonTestSuite"
401 data = self.run_py([f"-V:{company}/"])
402 self.assertEqual("X.Y.exe", data["LaunchCommand"])
403 self.assertEqual(company, data["env.company"])
404 self.assertEqual("3.100", data["env.tag"])
405
406 def test_filter_to_company_with_default(self):
407 company = "PythonTestSuite"
408 data = self.run_py([f"-V:{company}/"], env=dict(PY_PYTHON="3.0"))
409 self.assertEqual("X.Y.exe", data["LaunchCommand"])
410 self.assertEqual(company, data["env.company"])
411 self.assertEqual("3.100", data["env.tag"])
412
413 def test_filter_to_tag(self):
414 company = "PythonTestSuite"
415 data = self.run_py(["-V:3.100"])
416 self.assertEqual("X.Y.exe", data["LaunchCommand"])
417 self.assertEqual(company, data["env.company"])
418 self.assertEqual("3.100", data["env.tag"])
419
420 data = self.run_py(["-V:3.100-32"])
421 self.assertEqual("X.Y-32.exe", data["LaunchCommand"])
422 self.assertEqual(company, data["env.company"])
423 self.assertEqual("3.100-32", data["env.tag"])
424
425 data = self.run_py(["-V:3.100-arm64"])
426 self.assertEqual("X.Y-arm64.exe -X fake_arg_for_test", data["LaunchCommand"])
427 self.assertEqual(company, data["env.company"])
428 self.assertEqual("3.100-arm64", data["env.tag"])
429
430 def test_filter_to_company_and_tag(self):
431 company = "PythonTestSuite"
432 data = self.run_py([f"-V:{company}/3.1"], expect_returncode=103)
433
434 data = self.run_py([f"-V:{company}/3.100"])
435 self.assertEqual("X.Y.exe", data["LaunchCommand"])
436 self.assertEqual(company, data["env.company"])
437 self.assertEqual("3.100", data["env.tag"])
438
439 def test_filter_with_single_install(self):
440 company = "PythonTestSuite1"
441 data = self.run_py(
442 ["-V:Nonexistent"],
443 env={"PYLAUNCHER_LIMIT_TO_COMPANY": company},
444 expect_returncode=103,
445 )
446
447 def test_search_major_3(self):
448 try:
449 data = self.run_py(["-3"], allow_fail=True)
450 except subprocess.CalledProcessError:
451 raise unittest.SkipTest("requires at least one Python 3.x install")
452 self.assertEqual("PythonCore", data["env.company"])
453 self.assertStartsWith(data["env.tag"], "3.")
454
455 def test_search_major_3_32(self):
456 try:
457 data = self.run_py(["-3-32"], allow_fail=True)
458 except subprocess.CalledProcessError:
459 if not any(is_installed(f"3.{i}-32") for i in range(5, 11)):
460 raise unittest.SkipTest("requires at least one 32-bit Python 3.x install")
461 raise
462 self.assertEqual("PythonCore", data["env.company"])
463 self.assertStartsWith(data["env.tag"], "3.")
464 self.assertEndsWith(data["env.tag"], "-32")
465
466 def test_search_major_2(self):
467 try:
468 data = self.run_py(["-2"], allow_fail=True)
469 except subprocess.CalledProcessError:
470 if not is_installed("2.7"):
471 raise unittest.SkipTest("requires at least one Python 2.x install")
472 self.assertEqual("PythonCore", data["env.company"])
473 self.assertStartsWith(data["env.tag"], "2.")
474
475 def test_py_default(self):
476 with self.py_ini(TEST_PY_DEFAULTS):
477 data = self.run_py(["-arg"])
478 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
479 self.assertEqual("3.100", data["SearchInfo.tag"])
480 self.assertEqual("X.Y.exe -arg", data["stdout"].strip())
481
482 def test_py2_default(self):
483 with self.py_ini(TEST_PY_DEFAULTS):
484 data = self.run_py(["-2", "-arg"])
485 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
486 self.assertEqual("3.100-32", data["SearchInfo.tag"])
487 self.assertEqual("X.Y-32.exe -arg", data["stdout"].strip())
488
489 def test_py3_default(self):
490 with self.py_ini(TEST_PY_DEFAULTS):
491 data = self.run_py(["-3", "-arg"])
492 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
493 self.assertEqual("3.100-arm64", data["SearchInfo.tag"])
494 self.assertEqual("X.Y-arm64.exe -X fake_arg_for_test -arg", data["stdout"].strip())
495
496 def test_py_default_env(self):
497 data = self.run_py(["-arg"], env=TEST_PY_ENV)
498 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
499 self.assertEqual("3.100", data["SearchInfo.tag"])
500 self.assertEqual("X.Y.exe -arg", data["stdout"].strip())
501
502 def test_py2_default_env(self):
503 data = self.run_py(["-2", "-arg"], env=TEST_PY_ENV)
504 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
505 self.assertEqual("3.100-32", data["SearchInfo.tag"])
506 self.assertEqual("X.Y-32.exe -arg", data["stdout"].strip())
507
508 def test_py3_default_env(self):
509 data = self.run_py(["-3", "-arg"], env=TEST_PY_ENV)
510 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
511 self.assertEqual("3.100-arm64", data["SearchInfo.tag"])
512 self.assertEqual("X.Y-arm64.exe -X fake_arg_for_test -arg", data["stdout"].strip())
513
514 def test_py_default_short_argv0(self):
515 with self.py_ini(TEST_PY_DEFAULTS):
516 for argv0 in ['"py.exe"', 'py.exe', '"py"', 'py']:
517 with self.subTest(argv0):
518 data = self.run_py(["--version"], argv=f'{argv0} --version')
519 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
520 self.assertEqual("3.100", data["SearchInfo.tag"])
521 self.assertEqual("X.Y.exe --version", data["stdout"].strip())
522
523 def test_py_default_in_list(self):
524 data = self.run_py(["-0"], env=TEST_PY_ENV)
525 default = None
526 for line in data["stdout"].splitlines():
527 m = re.match(r"\s*-V:(.+?)\s+?\*\s+(.+)$", line)
528 if m:
529 default = m.group(1)
530 break
531 self.assertEqual("PythonTestSuite/3.100", default)
532
533 def test_virtualenv_in_list(self):
534 with self.fake_venv() as (venv_exe, env):
535 data = self.run_py(["-0p"], env=env)
536 for line in data["stdout"].splitlines():
537 m = re.match(r"\s*\*\s+(.+)$", line)
538 if m:
539 self.assertEqual(str(venv_exe), m.group(1))
540 break
541 else:
542 if support.verbose:
543 print(data["stdout"])
544 print(data["stderr"])
545 self.fail("did not find active venv path")
546
547 data = self.run_py(["-0"], env=env)
548 for line in data["stdout"].splitlines():
549 m = re.match(r"\s*\*\s+(.+)$", line)
550 if m:
551 self.assertEqual("Active venv", m.group(1))
552 break
553 else:
554 self.fail("did not find active venv entry")
555
556 def test_virtualenv_with_env(self):
557 with self.fake_venv() as (venv_exe, env):
558 data1 = self.run_py([], env={**env, "PY_PYTHON": "PythonTestSuite/3"})
559 data2 = self.run_py(["-V:PythonTestSuite/3"], env={**env, "PY_PYTHON": "PythonTestSuite/3"})
560 # Compare stdout, because stderr goes via ascii
561 self.assertEqual(data1["stdout"].strip(), quote(venv_exe))
562 self.assertEqual(data1["SearchInfo.lowPriorityTag"], "True")
563 # Ensure passing the argument doesn't trigger the same behaviour
564 self.assertNotEqual(data2["stdout"].strip(), quote(venv_exe))
565 self.assertNotEqual(data2["SearchInfo.lowPriorityTag"], "True")
566
567 def test_py_shebang(self):
568 with self.py_ini(TEST_PY_DEFAULTS):
569 with self.script("#! /usr/bin/python -prearg") as script:
570 data = self.run_py([script, "-postarg"])
571 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
572 self.assertEqual("3.100", data["SearchInfo.tag"])
573 self.assertEqual(f"X.Y.exe -prearg {quote(script)} -postarg", data["stdout"].strip())
574
575 def test_python_shebang(self):
576 with self.py_ini(TEST_PY_DEFAULTS):
577 with self.script("#! python -prearg") as script:
578 data = self.run_py([script, "-postarg"])
579 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
580 self.assertEqual("3.100", data["SearchInfo.tag"])
581 self.assertEqual(f"X.Y.exe -prearg {quote(script)} -postarg", data["stdout"].strip())
582
583 def test_py2_shebang(self):
584 with self.py_ini(TEST_PY_DEFAULTS):
585 with self.script("#! /usr/bin/python2 -prearg") as script:
586 data = self.run_py([script, "-postarg"])
587 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
588 self.assertEqual("3.100-32", data["SearchInfo.tag"])
589 self.assertEqual(f"X.Y-32.exe -prearg {quote(script)} -postarg",
590 data["stdout"].strip())
591
592 def test_py3_shebang(self):
593 with self.py_ini(TEST_PY_DEFAULTS):
594 with self.script("#! /usr/bin/python3 -prearg") as script:
595 data = self.run_py([script, "-postarg"])
596 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
597 self.assertEqual("3.100-arm64", data["SearchInfo.tag"])
598 self.assertEqual(f"X.Y-arm64.exe -X fake_arg_for_test -prearg {quote(script)} -postarg",
599 data["stdout"].strip())
600
601 def test_py_shebang_nl(self):
602 with self.py_ini(TEST_PY_DEFAULTS):
603 with self.script("#! /usr/bin/python -prearg\n") as script:
604 data = self.run_py([script, "-postarg"])
605 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
606 self.assertEqual("3.100", data["SearchInfo.tag"])
607 self.assertEqual(f"X.Y.exe -prearg {quote(script)} -postarg",
608 data["stdout"].strip())
609
610 def test_py2_shebang_nl(self):
611 with self.py_ini(TEST_PY_DEFAULTS):
612 with self.script("#! /usr/bin/python2 -prearg\n") as script:
613 data = self.run_py([script, "-postarg"])
614 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
615 self.assertEqual("3.100-32", data["SearchInfo.tag"])
616 self.assertEqual(f"X.Y-32.exe -prearg {quote(script)} -postarg",
617 data["stdout"].strip())
618
619 def test_py3_shebang_nl(self):
620 with self.py_ini(TEST_PY_DEFAULTS):
621 with self.script("#! /usr/bin/python3 -prearg\n") as script:
622 data = self.run_py([script, "-postarg"])
623 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
624 self.assertEqual("3.100-arm64", data["SearchInfo.tag"])
625 self.assertEqual(f"X.Y-arm64.exe -X fake_arg_for_test -prearg {quote(script)} -postarg",
626 data["stdout"].strip())
627
628 def test_py_shebang_short_argv0(self):
629 with self.py_ini(TEST_PY_DEFAULTS):
630 with self.script("#! /usr/bin/python -prearg") as script:
631 # Override argv to only pass "py.exe" as the command
632 data = self.run_py([script, "-postarg"], argv=f'"py.exe" "{script}" -postarg')
633 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
634 self.assertEqual("3.100", data["SearchInfo.tag"])
635 self.assertEqual(f'X.Y.exe -prearg "{script}" -postarg', data["stdout"].strip())
636
637 def test_py_shebang_valid_bom(self):
638 with self.py_ini(TEST_PY_DEFAULTS):
639 content = "#! /usr/bin/python -prearg".encode("utf-8")
640 with self.script(b"\xEF\xBB\xBF" + content) as script:
641 data = self.run_py([script, "-postarg"])
642 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
643 self.assertEqual("3.100", data["SearchInfo.tag"])
644 self.assertEqual(f"X.Y.exe -prearg {quote(script)} -postarg", data["stdout"].strip())
645
646 def test_py_shebang_invalid_bom(self):
647 with self.py_ini(TEST_PY_DEFAULTS):
648 content = "#! /usr/bin/python3 -prearg".encode("utf-8")
649 with self.script(b"\xEF\xAA\xBF" + content) as script:
650 data = self.run_py([script, "-postarg"])
651 self.assertIn("Invalid BOM", data["stderr"])
652 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
653 self.assertEqual("3.100", data["SearchInfo.tag"])
654 self.assertEqual(f"X.Y.exe {quote(script)} -postarg", data["stdout"].strip())
655
656 def test_py_handle_64_in_ini(self):
657 with self.py_ini("\n".join(["[defaults]", "python=3.999-64"])):
658 # Expect this to fail, but should get oldStyleTag flipped on
659 data = self.run_py([], allow_fail=True, expect_returncode=103)
660 self.assertEqual("3.999-64", data["SearchInfo.tag"])
661 self.assertEqual("True", data["SearchInfo.oldStyleTag"])
662
663 def test_search_path(self):
664 exe = Path("arbitrary-exe-name.exe").absolute()
665 exe.touch()
666 self.addCleanup(exe.unlink)
667 with self.py_ini(TEST_PY_DEFAULTS):
668 with self.script(f"#! /usr/bin/env {exe.stem} -prearg") as script:
669 data = self.run_py(
670 [script, "-postarg"],
671 env={"PATH": f"{exe.parent};{os.getenv('PATH')}"},
672 )
673 self.assertEqual(f"{quote(exe)} -prearg {quote(script)} -postarg",
674 data["stdout"].strip())
675
676 def test_search_path_exe(self):
677 # Leave the .exe on the name to ensure we don't add it a second time
678 exe = Path("arbitrary-exe-name.exe").absolute()
679 exe.touch()
680 self.addCleanup(exe.unlink)
681 with self.py_ini(TEST_PY_DEFAULTS):
682 with self.script(f"#! /usr/bin/env {exe.name} -prearg") as script:
683 data = self.run_py(
684 [script, "-postarg"],
685 env={"PATH": f"{exe.parent};{os.getenv('PATH')}"},
686 )
687 self.assertEqual(f"{quote(exe)} -prearg {quote(script)} -postarg",
688 data["stdout"].strip())
689
690 def test_recursive_search_path(self):
691 stem = self.get_py_exe().stem
692 with self.py_ini(TEST_PY_DEFAULTS):
693 with self.script(f"#! /usr/bin/env {stem}") as script:
694 data = self.run_py(
695 [script],
696 env={"PATH": f"{self.get_py_exe().parent};{os.getenv('PATH')}"},
697 )
698 # The recursive search is ignored and we get normal "py" behavior
699 self.assertEqual(f"X.Y.exe {quote(script)}", data["stdout"].strip())
700
701 def test_install(self):
702 data = self.run_py(["-V:3.10"], env={"PYLAUNCHER_ALWAYS_INSTALL": "1"}, expect_returncode=111)
703 cmd = data["stdout"].strip()
704 # If winget is runnable, we should find it. Otherwise, we'll be trying
705 # to open the Store.
706 try:
707 subprocess.check_call(["winget.exe", "--version"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
708 except FileNotFoundError:
709 self.assertIn("ms-windows-store://", cmd)
710 else:
711 self.assertIn("winget.exe", cmd)
712 # Both command lines include the store ID
713 self.assertIn("9PJPW5LDXLZ5", cmd)
714
715 def test_literal_shebang_absolute(self):
716 with self.script("#! C:/some_random_app -witharg") as script:
717 data = self.run_py([script])
718 self.assertEqual(
719 f"C:\\some_random_app -witharg {quote(script)}",
720 data["stdout"].strip(),
721 )
722
723 def test_literal_shebang_relative(self):
724 with self.script("#! ..\\some_random_app -witharg") as script:
725 data = self.run_py([script])
726 self.assertEqual(
727 f"{quote(script.parent.parent / 'some_random_app')} -witharg {quote(script)}",
728 data["stdout"].strip(),
729 )
730
731 def test_literal_shebang_quoted(self):
732 with self.script('#! "some random app" -witharg') as script:
733 data = self.run_py([script])
734 self.assertEqual(
735 f"{quote(script.parent / 'some random app')} -witharg {quote(script)}",
736 data["stdout"].strip(),
737 )
738
739 with self.script('#! some" random "app -witharg') as script:
740 data = self.run_py([script])
741 self.assertEqual(
742 f"{quote(script.parent / 'some random app')} -witharg {quote(script)}",
743 data["stdout"].strip(),
744 )
745
746 def test_literal_shebang_quoted_escape(self):
747 with self.script('#! some\\" random "app -witharg') as script:
748 data = self.run_py([script])
749 self.assertEqual(
750 f"{quote(script.parent / 'some/ random app')} -witharg {quote(script)}",
751 data["stdout"].strip(),
752 )
753
754 def test_literal_shebang_command(self):
755 with self.py_ini(TEST_PY_COMMANDS):
756 with self.script('#! test-command arg1') as script:
757 data = self.run_py([script])
758 self.assertEqual(
759 f"TEST_EXE.exe arg1 {quote(script)}",
760 data["stdout"].strip(),
761 )
762
763 def test_literal_shebang_invalid_template(self):
764 with self.script('#! /usr/bin/not-python arg1') as script:
765 data = self.run_py([script])
766 expect = script.parent / "/usr/bin/not-python"
767 self.assertEqual(
768 f"{quote(expect)} arg1 {quote(script)}",
769 data["stdout"].strip(),
770 )
771
772 def test_shebang_command_in_venv(self):
773 stem = "python-that-is-not-on-path"
774
775 # First ensure that our test name doesn't exist, and the launcher does
776 # not match any installed env
777 with self.script(f'#! /usr/bin/env {stem} arg1') as script:
778 data = self.run_py([script], expect_returncode=103)
779
780 with self.fake_venv() as (venv_exe, env):
781 # Put a "normal" Python on PATH as a distraction.
782 # The active VIRTUAL_ENV should be preferred when the name isn't an
783 # exact match.
784 exe = Path(Path(venv_exe).name).absolute()
785 exe.touch()
786 self.addCleanup(exe.unlink)
787 env["PATH"] = f"{exe.parent};{os.environ['PATH']}"
788
789 with self.script(f'#! /usr/bin/env {stem} arg1') as script:
790 data = self.run_py([script], env=env)
791 self.assertEqual(data["stdout"].strip(), f"{quote(venv_exe)} arg1 {quote(script)}")
792
793 with self.script(f'#! /usr/bin/env {exe.stem} arg1') as script:
794 data = self.run_py([script], env=env)
795 self.assertEqual(data["stdout"].strip(), f"{quote(exe)} arg1 {quote(script)}")
796
797 def test_shebang_executable_extension(self):
798 with self.script('#! /usr/bin/env python3.99') as script:
799 data = self.run_py([script], expect_returncode=103)
800 expect = "# Search PATH for python3.99.exe"
801 actual = [line.strip() for line in data["stderr"].splitlines()
802 if line.startswith("# Search PATH")]
803 self.assertEqual([expect], actual)