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 not argv:
231 argv = [self.py_exe, *args]
232 with subprocess.Popen(
233 argv,
234 env=env,
235 executable=self.py_exe,
236 stdin=subprocess.PIPE,
237 stdout=subprocess.PIPE,
238 stderr=subprocess.PIPE,
239 ) as p:
240 p.stdin.close()
241 p.wait(10)
242 out = p.stdout.read().decode("utf-8", "replace")
243 err = p.stderr.read().decode("ascii", "replace").replace("\uFFFD", "?")
244 if p.returncode != expect_returncode and support.verbose and not allow_fail:
245 print("++ COMMAND ++")
246 print([self.py_exe, *args])
247 print("++ STDOUT ++")
248 print(out)
249 print("++ STDERR ++")
250 print(err)
251 if allow_fail and p.returncode != expect_returncode:
252 raise subprocess.CalledProcessError(p.returncode, [self.py_exe, *args], out, err)
253 else:
254 self.assertEqual(expect_returncode, p.returncode)
255 data = {
256 s.partition(":")[0]: s.partition(":")[2].lstrip()
257 for s in err.splitlines()
258 if not s.startswith("#") and ":" in s
259 }
260 data["stdout"] = out
261 data["stderr"] = err
262 return data
263
264 def py_ini(self, content):
265 local_appdata = os.environ.get("LOCALAPPDATA")
266 if not local_appdata:
267 raise unittest.SkipTest("LOCALAPPDATA environment variable is "
268 "missing or empty")
269 return PreservePyIni(Path(local_appdata) / "py.ini", content)
270
271 @contextlib.contextmanager
272 def script(self, content, encoding="utf-8"):
273 file = Path(tempfile.mktemp(dir=os.getcwd()) + ".py")
274 if isinstance(content, bytes):
275 file.write_bytes(content)
276 else:
277 file.write_text(content, encoding=encoding)
278 try:
279 yield file
280 finally:
281 file.unlink()
282
283 @contextlib.contextmanager
284 def fake_venv(self):
285 venv = Path.cwd() / "Scripts"
286 venv.mkdir(exist_ok=True, parents=True)
287 venv_exe = (venv / ("python_d.exe" if DEBUG_BUILD else "python.exe"))
288 venv_exe.touch()
289 try:
290 yield venv_exe, {"VIRTUAL_ENV": str(venv.parent)}
291 finally:
292 shutil.rmtree(venv)
293
294
295 class TestLauncher(unittest.TestCase, RunPyMixin):
296 @classmethod
297 def setUpClass(cls):
298 with winreg.CreateKey(winreg.HKEY_CURRENT_USER, rf"Software\Python") as key:
299 create_registry_data(key, TEST_DATA)
300
301 if support.verbose:
302 p = subprocess.check_output("reg query HKCU\\Software\\Python /s")
303 #print(p.decode('mbcs'))
304
305
306 @classmethod
307 def tearDownClass(cls):
308 with winreg.OpenKey(winreg.HKEY_CURRENT_USER, rf"Software\Python", access=winreg.KEY_WRITE | winreg.KEY_ENUMERATE_SUB_KEYS) as key:
309 delete_registry_data(key, TEST_DATA)
310
311
312 def test_version(self):
313 data = self.run_py(["-0"])
314 self.assertEqual(self.py_exe, Path(data["argv0"]))
315 self.assertEqual(sys.version.partition(" ")[0], data["version"])
316
317 def test_help_option(self):
318 data = self.run_py(["-h"])
319 self.assertEqual("True", data["SearchInfo.help"])
320
321 def test_list_option(self):
322 for opt, v1, v2 in [
323 ("-0", "True", "False"),
324 ("-0p", "False", "True"),
325 ("--list", "True", "False"),
326 ("--list-paths", "False", "True"),
327 ]:
328 with self.subTest(opt):
329 data = self.run_py([opt])
330 self.assertEqual(v1, data["SearchInfo.list"])
331 self.assertEqual(v2, data["SearchInfo.listPaths"])
332
333 def test_list(self):
334 data = self.run_py(["--list"])
335 found = {}
336 expect = {}
337 for line in data["stdout"].splitlines():
338 m = re.match(r"\s*(.+?)\s+?(\*\s+)?(.+)$", line)
339 if m:
340 found[m.group(1)] = m.group(3)
341 for company in TEST_DATA:
342 company_data = TEST_DATA[company]
343 tags = [t for t in company_data if isinstance(company_data[t], dict)]
344 for tag in tags:
345 arg = f"-V:{company}/{tag}"
346 expect[arg] = company_data[tag]["DisplayName"]
347 expect.pop(f"-V:{company}/ignored", None)
348
349 actual = {k: v for k, v in found.items() if k in expect}
350 try:
351 self.assertDictEqual(expect, actual)
352 except:
353 if support.verbose:
354 print("*** STDOUT ***")
355 print(data["stdout"])
356 raise
357
358 def test_list_paths(self):
359 data = self.run_py(["--list-paths"])
360 found = {}
361 expect = {}
362 for line in data["stdout"].splitlines():
363 m = re.match(r"\s*(.+?)\s+?(\*\s+)?(.+)$", line)
364 if m:
365 found[m.group(1)] = m.group(3)
366 for company in TEST_DATA:
367 company_data = TEST_DATA[company]
368 tags = [t for t in company_data if isinstance(company_data[t], dict)]
369 for tag in tags:
370 arg = f"-V:{company}/{tag}"
371 install = company_data[tag]["InstallPath"]
372 try:
373 expect[arg] = install["ExecutablePath"]
374 try:
375 expect[arg] += " " + install["ExecutableArguments"]
376 except KeyError:
377 pass
378 except KeyError:
379 expect[arg] = str(Path(install[None]) / Path(sys.executable).name)
380
381 expect.pop(f"-V:{company}/ignored", None)
382
383 actual = {k: v for k, v in found.items() if k in expect}
384 try:
385 self.assertDictEqual(expect, actual)
386 except:
387 if support.verbose:
388 print("*** STDOUT ***")
389 print(data["stdout"])
390 raise
391
392 def test_filter_to_company(self):
393 company = "PythonTestSuite"
394 data = self.run_py([f"-V:{company}/"])
395 self.assertEqual("X.Y.exe", data["LaunchCommand"])
396 self.assertEqual(company, data["env.company"])
397 self.assertEqual("3.100", data["env.tag"])
398
399 def test_filter_to_company_with_default(self):
400 company = "PythonTestSuite"
401 data = self.run_py([f"-V:{company}/"], env=dict(PY_PYTHON="3.0"))
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_tag(self):
407 company = "PythonTestSuite"
408 data = self.run_py(["-V:3.100"])
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 data = self.run_py(["-V:3.100-32"])
414 self.assertEqual("X.Y-32.exe", data["LaunchCommand"])
415 self.assertEqual(company, data["env.company"])
416 self.assertEqual("3.100-32", data["env.tag"])
417
418 data = self.run_py(["-V:3.100-arm64"])
419 self.assertEqual("X.Y-arm64.exe -X fake_arg_for_test", data["LaunchCommand"])
420 self.assertEqual(company, data["env.company"])
421 self.assertEqual("3.100-arm64", data["env.tag"])
422
423 def test_filter_to_company_and_tag(self):
424 company = "PythonTestSuite"
425 data = self.run_py([f"-V:{company}/3.1"], expect_returncode=103)
426
427 data = self.run_py([f"-V:{company}/3.100"])
428 self.assertEqual("X.Y.exe", data["LaunchCommand"])
429 self.assertEqual(company, data["env.company"])
430 self.assertEqual("3.100", data["env.tag"])
431
432 def test_filter_with_single_install(self):
433 company = "PythonTestSuite1"
434 data = self.run_py(
435 ["-V:Nonexistent"],
436 env={"PYLAUNCHER_LIMIT_TO_COMPANY": company},
437 expect_returncode=103,
438 )
439
440 def test_search_major_3(self):
441 try:
442 data = self.run_py(["-3"], allow_fail=True)
443 except subprocess.CalledProcessError:
444 raise unittest.SkipTest("requires at least one Python 3.x install")
445 self.assertEqual("PythonCore", data["env.company"])
446 self.assertTrue(data["env.tag"].startswith("3."), data["env.tag"])
447
448 def test_search_major_3_32(self):
449 try:
450 data = self.run_py(["-3-32"], allow_fail=True)
451 except subprocess.CalledProcessError:
452 if not any(is_installed(f"3.{i}-32") for i in range(5, 11)):
453 raise unittest.SkipTest("requires at least one 32-bit Python 3.x install")
454 raise
455 self.assertEqual("PythonCore", data["env.company"])
456 self.assertTrue(data["env.tag"].startswith("3."), data["env.tag"])
457 self.assertTrue(data["env.tag"].endswith("-32"), data["env.tag"])
458
459 def test_search_major_2(self):
460 try:
461 data = self.run_py(["-2"], allow_fail=True)
462 except subprocess.CalledProcessError:
463 if not is_installed("2.7"):
464 raise unittest.SkipTest("requires at least one Python 2.x install")
465 self.assertEqual("PythonCore", data["env.company"])
466 self.assertTrue(data["env.tag"].startswith("2."), data["env.tag"])
467
468 def test_py_default(self):
469 with self.py_ini(TEST_PY_DEFAULTS):
470 data = self.run_py(["-arg"])
471 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
472 self.assertEqual("3.100", data["SearchInfo.tag"])
473 self.assertEqual("X.Y.exe -arg", data["stdout"].strip())
474
475 def test_py2_default(self):
476 with self.py_ini(TEST_PY_DEFAULTS):
477 data = self.run_py(["-2", "-arg"])
478 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
479 self.assertEqual("3.100-32", data["SearchInfo.tag"])
480 self.assertEqual("X.Y-32.exe -arg", data["stdout"].strip())
481
482 def test_py3_default(self):
483 with self.py_ini(TEST_PY_DEFAULTS):
484 data = self.run_py(["-3", "-arg"])
485 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
486 self.assertEqual("3.100-arm64", data["SearchInfo.tag"])
487 self.assertEqual("X.Y-arm64.exe -X fake_arg_for_test -arg", data["stdout"].strip())
488
489 def test_py_default_env(self):
490 data = self.run_py(["-arg"], env=TEST_PY_ENV)
491 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
492 self.assertEqual("3.100", data["SearchInfo.tag"])
493 self.assertEqual("X.Y.exe -arg", data["stdout"].strip())
494
495 def test_py2_default_env(self):
496 data = self.run_py(["-2", "-arg"], env=TEST_PY_ENV)
497 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
498 self.assertEqual("3.100-32", data["SearchInfo.tag"])
499 self.assertEqual("X.Y-32.exe -arg", data["stdout"].strip())
500
501 def test_py3_default_env(self):
502 data = self.run_py(["-3", "-arg"], env=TEST_PY_ENV)
503 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
504 self.assertEqual("3.100-arm64", data["SearchInfo.tag"])
505 self.assertEqual("X.Y-arm64.exe -X fake_arg_for_test -arg", data["stdout"].strip())
506
507 def test_py_default_short_argv0(self):
508 with self.py_ini(TEST_PY_DEFAULTS):
509 for argv0 in ['"py.exe"', 'py.exe', '"py"', 'py']:
510 with self.subTest(argv0):
511 data = self.run_py(["--version"], argv=f'{argv0} --version')
512 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
513 self.assertEqual("3.100", data["SearchInfo.tag"])
514 self.assertEqual("X.Y.exe --version", data["stdout"].strip())
515
516 def test_py_default_in_list(self):
517 data = self.run_py(["-0"], env=TEST_PY_ENV)
518 default = None
519 for line in data["stdout"].splitlines():
520 m = re.match(r"\s*-V:(.+?)\s+?\*\s+(.+)$", line)
521 if m:
522 default = m.group(1)
523 break
524 self.assertEqual("PythonTestSuite/3.100", default)
525
526 def test_virtualenv_in_list(self):
527 with self.fake_venv() as (venv_exe, env):
528 data = self.run_py(["-0p"], env=env)
529 for line in data["stdout"].splitlines():
530 m = re.match(r"\s*\*\s+(.+)$", line)
531 if m:
532 self.assertEqual(str(venv_exe), m.group(1))
533 break
534 else:
535 if support.verbose:
536 print(data["stdout"])
537 print(data["stderr"])
538 self.fail("did not find active venv path")
539
540 data = self.run_py(["-0"], env=env)
541 for line in data["stdout"].splitlines():
542 m = re.match(r"\s*\*\s+(.+)$", line)
543 if m:
544 self.assertEqual("Active venv", m.group(1))
545 break
546 else:
547 self.fail("did not find active venv entry")
548
549 def test_virtualenv_with_env(self):
550 with self.fake_venv() as (venv_exe, env):
551 data1 = self.run_py([], env={**env, "PY_PYTHON": "PythonTestSuite/3"})
552 data2 = self.run_py(["-V:PythonTestSuite/3"], env={**env, "PY_PYTHON": "PythonTestSuite/3"})
553 # Compare stdout, because stderr goes via ascii
554 self.assertEqual(data1["stdout"].strip(), quote(venv_exe))
555 self.assertEqual(data1["SearchInfo.lowPriorityTag"], "True")
556 # Ensure passing the argument doesn't trigger the same behaviour
557 self.assertNotEqual(data2["stdout"].strip(), quote(venv_exe))
558 self.assertNotEqual(data2["SearchInfo.lowPriorityTag"], "True")
559
560 def test_py_shebang(self):
561 with self.py_ini(TEST_PY_DEFAULTS):
562 with self.script("#! /usr/bin/python -prearg") as script:
563 data = self.run_py([script, "-postarg"])
564 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
565 self.assertEqual("3.100", data["SearchInfo.tag"])
566 self.assertEqual(f"X.Y.exe -prearg {quote(script)} -postarg", data["stdout"].strip())
567
568 def test_python_shebang(self):
569 with self.py_ini(TEST_PY_DEFAULTS):
570 with self.script("#! python -prearg") as script:
571 data = self.run_py([script, "-postarg"])
572 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
573 self.assertEqual("3.100", data["SearchInfo.tag"])
574 self.assertEqual(f"X.Y.exe -prearg {quote(script)} -postarg", data["stdout"].strip())
575
576 def test_py2_shebang(self):
577 with self.py_ini(TEST_PY_DEFAULTS):
578 with self.script("#! /usr/bin/python2 -prearg") as script:
579 data = self.run_py([script, "-postarg"])
580 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
581 self.assertEqual("3.100-32", data["SearchInfo.tag"])
582 self.assertEqual(f"X.Y-32.exe -prearg {quote(script)} -postarg",
583 data["stdout"].strip())
584
585 def test_py3_shebang(self):
586 with self.py_ini(TEST_PY_DEFAULTS):
587 with self.script("#! /usr/bin/python3 -prearg") as script:
588 data = self.run_py([script, "-postarg"])
589 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
590 self.assertEqual("3.100-arm64", data["SearchInfo.tag"])
591 self.assertEqual(f"X.Y-arm64.exe -X fake_arg_for_test -prearg {quote(script)} -postarg",
592 data["stdout"].strip())
593
594 def test_py_shebang_nl(self):
595 with self.py_ini(TEST_PY_DEFAULTS):
596 with self.script("#! /usr/bin/python -prearg\n") as script:
597 data = self.run_py([script, "-postarg"])
598 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
599 self.assertEqual("3.100", data["SearchInfo.tag"])
600 self.assertEqual(f"X.Y.exe -prearg {quote(script)} -postarg",
601 data["stdout"].strip())
602
603 def test_py2_shebang_nl(self):
604 with self.py_ini(TEST_PY_DEFAULTS):
605 with self.script("#! /usr/bin/python2 -prearg\n") as script:
606 data = self.run_py([script, "-postarg"])
607 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
608 self.assertEqual("3.100-32", data["SearchInfo.tag"])
609 self.assertEqual(f"X.Y-32.exe -prearg {quote(script)} -postarg",
610 data["stdout"].strip())
611
612 def test_py3_shebang_nl(self):
613 with self.py_ini(TEST_PY_DEFAULTS):
614 with self.script("#! /usr/bin/python3 -prearg\n") as script:
615 data = self.run_py([script, "-postarg"])
616 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
617 self.assertEqual("3.100-arm64", data["SearchInfo.tag"])
618 self.assertEqual(f"X.Y-arm64.exe -X fake_arg_for_test -prearg {quote(script)} -postarg",
619 data["stdout"].strip())
620
621 def test_py_shebang_short_argv0(self):
622 with self.py_ini(TEST_PY_DEFAULTS):
623 with self.script("#! /usr/bin/python -prearg") as script:
624 # Override argv to only pass "py.exe" as the command
625 data = self.run_py([script, "-postarg"], argv=f'"py.exe" "{script}" -postarg')
626 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
627 self.assertEqual("3.100", data["SearchInfo.tag"])
628 self.assertEqual(f'X.Y.exe -prearg "{script}" -postarg', data["stdout"].strip())
629
630 def test_py_shebang_valid_bom(self):
631 with self.py_ini(TEST_PY_DEFAULTS):
632 content = "#! /usr/bin/python -prearg".encode("utf-8")
633 with self.script(b"\xEF\xBB\xBF" + content) as script:
634 data = self.run_py([script, "-postarg"])
635 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
636 self.assertEqual("3.100", data["SearchInfo.tag"])
637 self.assertEqual(f"X.Y.exe -prearg {quote(script)} -postarg", data["stdout"].strip())
638
639 def test_py_shebang_invalid_bom(self):
640 with self.py_ini(TEST_PY_DEFAULTS):
641 content = "#! /usr/bin/python3 -prearg".encode("utf-8")
642 with self.script(b"\xEF\xAA\xBF" + content) as script:
643 data = self.run_py([script, "-postarg"])
644 self.assertIn("Invalid BOM", data["stderr"])
645 self.assertEqual("PythonTestSuite", data["SearchInfo.company"])
646 self.assertEqual("3.100", data["SearchInfo.tag"])
647 self.assertEqual(f"X.Y.exe {quote(script)} -postarg", data["stdout"].strip())
648
649 def test_py_handle_64_in_ini(self):
650 with self.py_ini("\n".join(["[defaults]", "python=3.999-64"])):
651 # Expect this to fail, but should get oldStyleTag flipped on
652 data = self.run_py([], allow_fail=True, expect_returncode=103)
653 self.assertEqual("3.999-64", data["SearchInfo.tag"])
654 self.assertEqual("True", data["SearchInfo.oldStyleTag"])
655
656 def test_search_path(self):
657 exe = Path("arbitrary-exe-name.exe").absolute()
658 exe.touch()
659 self.addCleanup(exe.unlink)
660 with self.py_ini(TEST_PY_DEFAULTS):
661 with self.script(f"#! /usr/bin/env {exe.stem} -prearg") as script:
662 data = self.run_py(
663 [script, "-postarg"],
664 env={"PATH": f"{exe.parent};{os.getenv('PATH')}"},
665 )
666 self.assertEqual(f"{quote(exe)} -prearg {quote(script)} -postarg",
667 data["stdout"].strip())
668
669 def test_search_path_exe(self):
670 # Leave the .exe on the name to ensure we don't add it a second time
671 exe = Path("arbitrary-exe-name.exe").absolute()
672 exe.touch()
673 self.addCleanup(exe.unlink)
674 with self.py_ini(TEST_PY_DEFAULTS):
675 with self.script(f"#! /usr/bin/env {exe.name} -prearg") as script:
676 data = self.run_py(
677 [script, "-postarg"],
678 env={"PATH": f"{exe.parent};{os.getenv('PATH')}"},
679 )
680 self.assertEqual(f"{quote(exe)} -prearg {quote(script)} -postarg",
681 data["stdout"].strip())
682
683 def test_recursive_search_path(self):
684 stem = self.get_py_exe().stem
685 with self.py_ini(TEST_PY_DEFAULTS):
686 with self.script(f"#! /usr/bin/env {stem}") as script:
687 data = self.run_py(
688 [script],
689 env={"PATH": f"{self.get_py_exe().parent};{os.getenv('PATH')}"},
690 )
691 # The recursive search is ignored and we get normal "py" behavior
692 self.assertEqual(f"X.Y.exe {quote(script)}", data["stdout"].strip())
693
694 def test_install(self):
695 data = self.run_py(["-V:3.10"], env={"PYLAUNCHER_ALWAYS_INSTALL": "1"}, expect_returncode=111)
696 cmd = data["stdout"].strip()
697 # If winget is runnable, we should find it. Otherwise, we'll be trying
698 # to open the Store.
699 try:
700 subprocess.check_call(["winget.exe", "--version"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
701 except FileNotFoundError:
702 self.assertIn("ms-windows-store://", cmd)
703 else:
704 self.assertIn("winget.exe", cmd)
705 # Both command lines include the store ID
706 self.assertIn("9PJPW5LDXLZ5", cmd)
707
708 def test_literal_shebang_absolute(self):
709 with self.script("#! C:/some_random_app -witharg") as script:
710 data = self.run_py([script])
711 self.assertEqual(
712 f"C:\\some_random_app -witharg {quote(script)}",
713 data["stdout"].strip(),
714 )
715
716 def test_literal_shebang_relative(self):
717 with self.script("#! ..\\some_random_app -witharg") as script:
718 data = self.run_py([script])
719 self.assertEqual(
720 f"{quote(script.parent.parent / 'some_random_app')} -witharg {quote(script)}",
721 data["stdout"].strip(),
722 )
723
724 def test_literal_shebang_quoted(self):
725 with self.script('#! "some random app" -witharg') as script:
726 data = self.run_py([script])
727 self.assertEqual(
728 f"{quote(script.parent / 'some random app')} -witharg {quote(script)}",
729 data["stdout"].strip(),
730 )
731
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 def test_literal_shebang_quoted_escape(self):
740 with self.script('#! some\\" random "app -witharg') as script:
741 data = self.run_py([script])
742 self.assertEqual(
743 f"{quote(script.parent / 'some/ random app')} -witharg {quote(script)}",
744 data["stdout"].strip(),
745 )
746
747 def test_literal_shebang_command(self):
748 with self.py_ini(TEST_PY_COMMANDS):
749 with self.script('#! test-command arg1') as script:
750 data = self.run_py([script])
751 self.assertEqual(
752 f"TEST_EXE.exe arg1 {quote(script)}",
753 data["stdout"].strip(),
754 )
755
756 def test_literal_shebang_invalid_template(self):
757 with self.script('#! /usr/bin/not-python arg1') as script:
758 data = self.run_py([script])
759 expect = script.parent / "/usr/bin/not-python"
760 self.assertEqual(
761 f"{quote(expect)} arg1 {quote(script)}",
762 data["stdout"].strip(),
763 )
764
765 def test_shebang_command_in_venv(self):
766 stem = "python-that-is-not-on-path"
767
768 # First ensure that our test name doesn't exist, and the launcher does
769 # not match any installed env
770 with self.script(f'#! /usr/bin/env {stem} arg1') as script:
771 data = self.run_py([script], expect_returncode=103)
772
773 with self.fake_venv() as (venv_exe, env):
774 # Put a "normal" Python on PATH as a distraction.
775 # The active VIRTUAL_ENV should be preferred when the name isn't an
776 # exact match.
777 exe = Path(Path(venv_exe).name).absolute()
778 exe.touch()
779 self.addCleanup(exe.unlink)
780 env["PATH"] = f"{exe.parent};{os.environ['PATH']}"
781
782 with self.script(f'#! /usr/bin/env {stem} arg1') as script:
783 data = self.run_py([script], env=env)
784 self.assertEqual(data["stdout"].strip(), f"{quote(venv_exe)} arg1 {quote(script)}")
785
786 with self.script(f'#! /usr/bin/env {exe.stem} arg1') as script:
787 data = self.run_py([script], env=env)
788 self.assertEqual(data["stdout"].strip(), f"{quote(exe)} arg1 {quote(script)}")
789
790 def test_shebang_executable_extension(self):
791 with self.script('#! /usr/bin/env python3.99') as script:
792 data = self.run_py([script], expect_returncode=103)
793 expect = "# Search PATH for python3.99.exe"
794 actual = [line.strip() for line in data["stderr"].splitlines()
795 if line.startswith("# Search PATH")]
796 self.assertEqual([expect], actual)