Debian Codegraph @

Lib/test/test_embed.py

raw
1 # Run the tests in Programs/_testembed.c (tests for the CPython embedding APIs)
2 from test import support
3 from test.support import import_helper, os_helper, threading_helper, MS_WINDOWS
4 import unittest
5
6 from collections import namedtuple
7 import contextlib
8 import io
9 import json
10 import os
11 import os.path
12 import re
13 import shutil
14 import subprocess
15 import sys
16 import sysconfig
17 import tempfile
18 import textwrap
19
20 if not support.has_subprocess_support:
21 raise unittest.SkipTest("test module requires subprocess")
22
23
24 try:
25 import _testinternalcapi
26 except ImportError:
27 _testinternalcapi = None
28
29
30 MACOS = (sys.platform == 'darwin')
31 PYMEM_ALLOCATOR_NOT_SET = 0
32 PYMEM_ALLOCATOR_DEBUG = 2
33 PYMEM_ALLOCATOR_MALLOC = 3
34 PYMEM_ALLOCATOR_MIMALLOC = 7
35 if support.Py_GIL_DISABLED:
36 ALLOCATOR_FOR_CONFIG = PYMEM_ALLOCATOR_MIMALLOC
37 else:
38 ALLOCATOR_FOR_CONFIG = PYMEM_ALLOCATOR_MALLOC
39
40 Py_STATS = hasattr(sys, '_stats_on')
41
42 # _PyCoreConfig_InitCompatConfig()
43 API_COMPAT = 1
44 # _PyCoreConfig_InitPythonConfig()
45 API_PYTHON = 2
46 # _PyCoreConfig_InitIsolatedConfig()
47 API_ISOLATED = 3
48
49 INIT_LOOPS = 4
50 MAX_HASH_SEED = 4294967295
51
52 ABI_THREAD = 't' if sysconfig.get_config_var('Py_GIL_DISABLED') else ''
53
54
55 # If we are running from a build dir, but the stdlib has been installed,
56 # some tests need to expect different results.
57 STDLIB_INSTALL = os.path.join(sys.prefix, sys.platlibdir,
58 f'python{sys.version_info.major}.{sys.version_info.minor}')
59 if not os.path.isfile(os.path.join(STDLIB_INSTALL, 'os.py')):
60 STDLIB_INSTALL = None
61
62 def debug_build(program):
63 program = os.path.basename(program)
64 name = os.path.splitext(program)[0]
65 return name.casefold().endswith("_d".casefold())
66
67
68 def remove_python_envvars():
69 env = dict(os.environ)
70 # Remove PYTHON* environment variables to get deterministic environment
71 for key in list(env):
72 if key.startswith('PYTHON'):
73 del env[key]
74 return env
75
76
77 class EmbeddingTestsMixin:
78 def setUp(self):
79 exename = "_testembed"
80 builddir = os.path.dirname(sys.executable)
81 if MS_WINDOWS:
82 ext = ("_d" if debug_build(sys.executable) else "") + ".exe"
83 exename += ext
84 exepath = builddir
85 else:
86 exepath = os.path.join(builddir, 'Programs')
87 self.test_exe = exe = os.path.join(exepath, exename)
88 if not os.path.exists(exe):
89 self.skipTest("%r doesn't exist" % exe)
90 # This is needed otherwise we get a fatal error:
91 # "Py_Initialize: Unable to get the locale encoding
92 # LookupError: no codec search functions registered: can't find encoding"
93 self.oldcwd = os.getcwd()
94 os.chdir(builddir)
95
96 def tearDown(self):
97 os.chdir(self.oldcwd)
98
99 def run_embedded_interpreter(self, *args, env=None,
100 timeout=None, returncode=0, input=None,
101 cwd=None):
102 """Runs a test in the embedded interpreter"""
103 cmd = [self.test_exe]
104 cmd.extend(args)
105 if env is not None and MS_WINDOWS:
106 # Windows requires at least the SYSTEMROOT environment variable to
107 # start Python.
108 env = env.copy()
109 env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
110
111 p = subprocess.Popen(cmd,
112 stdout=subprocess.PIPE,
113 stderr=subprocess.PIPE,
114 universal_newlines=True,
115 env=env,
116 cwd=cwd)
117 try:
118 (out, err) = p.communicate(input=input, timeout=timeout)
119 except:
120 p.terminate()
121 p.wait()
122 raise
123 if p.returncode != returncode and support.verbose:
124 print(f"--- {cmd} failed ---")
125 print(f"stdout:\n{out}")
126 print(f"stderr:\n{err}")
127 print("------")
128
129 self.assertEqual(p.returncode, returncode,
130 "bad returncode %d, stderr is %r" %
131 (p.returncode, err))
132 return out, err
133
134 def run_repeated_init_and_subinterpreters(self):
135 out, err = self.run_embedded_interpreter("test_repeated_init_and_subinterpreters")
136 self.assertEqual(err, "")
137
138 # The output from _testembed looks like this:
139 # --- Pass 1 ---
140 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
141 # interp 1 <0x1d4f690>, thread state <0x1d35350>: id(modules) = 139650431165784
142 # interp 2 <0x1d5a690>, thread state <0x1d99ed0>: id(modules) = 139650413140368
143 # interp 3 <0x1d4f690>, thread state <0x1dc3340>: id(modules) = 139650412862200
144 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
145 # --- Pass 2 ---
146 # ...
147
148 interp_pat = (r"^interp (\d+) <(0x[\dA-F]+)>, "
149 r"thread state <(0x[\dA-F]+)>: "
150 r"id\(modules\) = ([\d]+)$")
151 Interp = namedtuple("Interp", "id interp tstate modules")
152
153 numloops = 1
154 current_run = []
155 for line in out.splitlines():
156 if line == "--- Pass {} ---".format(numloops):
157 self.assertEqual(len(current_run), 0)
158 if support.verbose > 1:
159 print(line)
160 numloops += 1
161 continue
162
163 self.assertLess(len(current_run), 5)
164 match = re.match(interp_pat, line)
165 if match is None:
166 self.assertRegex(line, interp_pat)
167
168 # Parse the line from the loop. The first line is the main
169 # interpreter and the 3 afterward are subinterpreters.
170 interp = Interp(*match.groups())
171 if support.verbose > 2:
172 # 5 lines per pass is super-spammy, so limit that to -vvv
173 print(interp)
174 self.assertTrue(interp.interp)
175 self.assertTrue(interp.tstate)
176 self.assertTrue(interp.modules)
177 current_run.append(interp)
178
179 # The last line in the loop should be the same as the first.
180 if len(current_run) == 5:
181 main = current_run[0]
182 self.assertEqual(interp, main)
183 yield current_run
184 current_run = []
185
186
187 class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase):
188 maxDiff = 100 * 50
189
190 def test_subinterps_main(self):
191 for run in self.run_repeated_init_and_subinterpreters():
192 main = run[0]
193
194 self.assertEqual(main.id, '0')
195
196 def test_subinterps_different_ids(self):
197 for run in self.run_repeated_init_and_subinterpreters():
198 main, *subs, _ = run
199
200 mainid = int(main.id)
201 for i, sub in enumerate(subs):
202 self.assertEqual(sub.id, str(mainid + i + 1))
203
204 def test_subinterps_distinct_state(self):
205 for run in self.run_repeated_init_and_subinterpreters():
206 main, *subs, _ = run
207
208 if '0x0' in main:
209 # XXX Fix on Windows (and other platforms): something
210 # is going on with the pointers in Programs/_testembed.c.
211 # interp.interp is 0x0 and interp.modules is the same
212 # between interpreters.
213 raise unittest.SkipTest('platform prints pointers as 0x0')
214
215 for sub in subs:
216 # A new subinterpreter may have the same
217 # PyInterpreterState pointer as a previous one if
218 # the earlier one has already been destroyed. So
219 # we compare with the main interpreter. The same
220 # applies to tstate.
221 self.assertNotEqual(sub.interp, main.interp)
222 self.assertNotEqual(sub.tstate, main.tstate)
223 self.assertNotEqual(sub.modules, main.modules)
224
225 def test_repeated_init_and_inittab(self):
226 out, err = self.run_embedded_interpreter("test_repeated_init_and_inittab")
227 self.assertEqual(err, "")
228
229 lines = [f"--- Pass {i} ---" for i in range(1, INIT_LOOPS+1)]
230 lines = "\n".join(lines) + "\n"
231 self.assertEqual(out, lines)
232
233 def test_inittab_submodule_multiphase(self):
234 out, err = self.run_embedded_interpreter("test_inittab_submodule_multiphase")
235 self.assertEqual(err, "")
236 self.assertEqual(out,
237 "<module 'mp_pkg.mp_submod' (built-in)>\n"
238 "<module 'mp_pkg.mp_submod' (built-in)>\n"
239 "Hello from sub-module\n"
240 "mp_pkg.mp_submod.mp_submod_exec_slot_ran='yes'\n"
241 "mp_pkg.mp_pkg_exec_slot_ran='yes'\n"
242 )
243
244 def test_inittab_submodule_singlephase(self):
245 out, err = self.run_embedded_interpreter("test_inittab_submodule_singlephase")
246 self.assertEqual(self._nogil_filtered_err(err, "sp_pkg"), "")
247 self.assertEqual(out,
248 "<module 'sp_pkg.sp_submod' (built-in)>\n"
249 "<module 'sp_pkg.sp_submod' (built-in)>\n"
250 "Hello from sub-module\n"
251 )
252
253 def test_forced_io_encoding(self):
254 # Checks forced configuration of embedded interpreter IO streams
255 env = dict(os.environ, PYTHONIOENCODING="utf-8:surrogateescape")
256 out, err = self.run_embedded_interpreter("test_forced_io_encoding", env=env)
257 if support.verbose > 1:
258 print()
259 print(out)
260 print(err)
261 expected_stream_encoding = "utf-8"
262 expected_errors = "surrogateescape"
263 expected_output = '\n'.join([
264 "--- Use defaults ---",
265 "Expected encoding: default",
266 "Expected errors: default",
267 "stdin: {in_encoding}:{errors}",
268 "stdout: {out_encoding}:{errors}",
269 "stderr: {out_encoding}:backslashreplace",
270 "--- Set errors only ---",
271 "Expected encoding: default",
272 "Expected errors: ignore",
273 "stdin: {in_encoding}:ignore",
274 "stdout: {out_encoding}:ignore",
275 "stderr: {out_encoding}:backslashreplace",
276 "--- Set encoding only ---",
277 "Expected encoding: iso8859-1",
278 "Expected errors: default",
279 "stdin: iso8859-1:{errors}",
280 "stdout: iso8859-1:{errors}",
281 "stderr: iso8859-1:backslashreplace",
282 "--- Set encoding and errors ---",
283 "Expected encoding: iso8859-1",
284 "Expected errors: replace",
285 "stdin: iso8859-1:replace",
286 "stdout: iso8859-1:replace",
287 "stderr: iso8859-1:backslashreplace"])
288 expected_output = expected_output.format(
289 in_encoding=expected_stream_encoding,
290 out_encoding=expected_stream_encoding,
291 errors=expected_errors)
292 # This is useful if we ever trip over odd platform behaviour
293 self.maxDiff = None
294 self.assertEqual(out.strip(), expected_output)
295
296 def test_pre_initialization_api(self):
297 """
298 Checks some key parts of the C-API that need to work before the runtime
299 is initialized (via Py_Initialize()).
300 """
301 env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path))
302 out, err = self.run_embedded_interpreter("test_pre_initialization_api", env=env)
303 if support.verbose > 1:
304 print()
305 print(out)
306 print(err)
307 if MS_WINDOWS:
308 expected_path = self.test_exe
309 else:
310 expected_path = os.path.join(os.getcwd(), "spam")
311 expected_output = f"sys.executable: {expected_path}\n"
312 self.assertIn(expected_output, out)
313 self.assertEqual(err, '')
314
315 def test_pre_initialization_sys_options(self):
316 """
317 Checks that sys.warnoptions and sys._xoptions can be set before the
318 runtime is initialized (otherwise they won't be effective).
319 """
320 env = remove_python_envvars()
321 env['PYTHONPATH'] = os.pathsep.join(sys.path)
322 out, err = self.run_embedded_interpreter(
323 "test_pre_initialization_sys_options", env=env)
324 if support.verbose > 1:
325 print()
326 print(out)
327 print(err)
328 expected_output = (
329 "sys.warnoptions: ['once', 'module', 'default']\n"
330 "sys._xoptions: {'not_an_option': '1', 'also_not_an_option': '2'}\n"
331 "warnings.filters[:3]: ['default', 'module', 'once']\n"
332 )
333 self.assertIn(expected_output, out)
334 self.assertEqual(err, '')
335
336 def test_bpo20891(self):
337 """
338 bpo-20891: Calling PyGILState_Ensure in a non-Python thread must not
339 crash.
340 """
341 out, err = self.run_embedded_interpreter("test_bpo20891")
342 self.assertEqual(out, '')
343 self.assertEqual(err, '')
344
345 def test_initialize_twice(self):
346 """
347 bpo-33932: Calling Py_Initialize() twice should do nothing (and not
348 crash!).
349 """
350 out, err = self.run_embedded_interpreter("test_initialize_twice")
351 self.assertEqual(out, '')
352 self.assertEqual(err, '')
353
354 def test_initialize_pymain(self):
355 """
356 bpo-34008: Calling Py_Main() after Py_Initialize() must not fail.
357 """
358 out, err = self.run_embedded_interpreter("test_initialize_pymain")
359 self.assertEqual(out.rstrip(), "Py_Main() after Py_Initialize: sys.argv=['-c', 'arg2']")
360 self.assertEqual(err, '')
361
362 def test_run_main(self):
363 out, err = self.run_embedded_interpreter("test_run_main")
364 self.assertEqual(out.rstrip(), "Py_RunMain(): sys.argv=['-c', 'arg2']")
365 self.assertEqual(err, '')
366
367 def test_run_main_loop(self):
368 # bpo-40413: Calling Py_InitializeFromConfig()+Py_RunMain() multiple
369 # times must not crash.
370 nloop = 5
371 out, err = self.run_embedded_interpreter("test_run_main_loop")
372 self.assertEqual(out, "Py_RunMain(): sys.argv=['-c', 'arg2']\n" * nloop)
373 self.assertEqual(err, '')
374
375 def test_finalize_structseq(self):
376 # bpo-46417: Py_Finalize() clears structseq static types. Check that
377 # sys attributes using struct types still work when
378 # Py_Finalize()/Py_Initialize() is called multiple times.
379 # print() calls type->tp_repr(instance) and so checks that the types
380 # are still working properly.
381 script = support.findfile('_test_embed_structseq.py')
382 with open(script, encoding="utf-8") as fp:
383 code = fp.read()
384 out, err = self.run_embedded_interpreter("test_repeated_init_exec", code)
385 self.assertEqual(out, 'Tests passed\n' * INIT_LOOPS)
386
387 def test_simple_initialization_api(self):
388 # _testembed now uses Py_InitializeFromConfig by default
389 # This case specifically checks Py_Initialize(Ex) still works
390 out, err = self.run_embedded_interpreter("test_repeated_simple_init")
391 self.assertEqual(out, 'Finalized\n' * INIT_LOOPS)
392
393 @support.requires_specialization
394 @unittest.skipUnless(support.TEST_MODULES_ENABLED, "requires test modules")
395 def test_specialized_static_code_gets_unspecialized_at_Py_FINALIZE(self):
396 # https://github.com/python/cpython/issues/92031
397
398 code = textwrap.dedent("""\
399 import dis
400 import importlib._bootstrap
401 import opcode
402 import test.test_dis
403
404 def is_specialized(f):
405 for instruction in dis.get_instructions(f, adaptive=True):
406 opname = instruction.opname
407 if (
408 opname in opcode._specialized_opmap
409 # Exclude superinstructions:
410 and "__" not in opname
411 ):
412 return True
413 return False
414
415 func = importlib._bootstrap._handle_fromlist
416
417 # "copy" the code to un-specialize it:
418 func.__code__ = func.__code__.replace()
419
420 assert not is_specialized(func), "specialized instructions found"
421
422 for i in range(test.test_dis.ADAPTIVE_WARMUP_DELAY):
423 func(importlib._bootstrap, ["x"], lambda *args: None)
424
425 assert is_specialized(func), "no specialized instructions found"
426
427 print("Tests passed")
428 """)
429 run = self.run_embedded_interpreter
430 out, err = run("test_repeated_init_exec", code)
431 self.assertEqual(out, 'Tests passed\n' * INIT_LOOPS)
432
433 def test_ucnhash_capi_reset(self):
434 # bpo-47182: unicodeobject.c:ucnhash_capi was not reset on shutdown.
435 code = "print('\\N{digit nine}')"
436 out, err = self.run_embedded_interpreter("test_repeated_init_exec", code)
437 self.assertEqual(out, '9\n' * INIT_LOOPS)
438
439 def test_datetime_reset_strptime(self):
440 code = (
441 "import datetime;"
442 "d = datetime.datetime.strptime('2000-01-01', '%Y-%m-%d');"
443 "print(d.strftime('%Y%m%d'))"
444 )
445 out, err = self.run_embedded_interpreter("test_repeated_init_exec", code)
446 self.assertEqual(out, '20000101\n' * INIT_LOOPS)
447
448 def test_static_types_inherited_slots(self):
449 script = textwrap.dedent("""
450 import test.support
451
452 results = {}
453 def add(cls, slot, own):
454 value = getattr(cls, slot)
455 try:
456 subresults = results[cls.__name__]
457 except KeyError:
458 subresults = results[cls.__name__] = {}
459 subresults[slot] = [repr(value), own]
460
461 for cls in test.support.iter_builtin_types():
462 for slot, own in test.support.iter_slot_wrappers(cls):
463 add(cls, slot, own)
464 """)
465
466 ns = {}
467 exec(script, ns, ns)
468 all_expected = ns['results']
469 del ns
470
471 script += textwrap.dedent("""
472 import json
473 import sys
474 text = json.dumps(results)
475 print(text, file=sys.stderr)
476 """)
477 out, err = self.run_embedded_interpreter(
478 "test_repeated_init_exec", script, script)
479 results = err.split('--- Loop #')[1:]
480 results = [res.rpartition(' ---\n')[-1] for res in results]
481
482 self.maxDiff = None
483 for i, text in enumerate(results, start=1):
484 result = json.loads(text)
485 for classname, expected in all_expected.items():
486 with self.subTest(loop=i, cls=classname):
487 slots = result.pop(classname)
488 self.assertEqual(slots, expected)
489 self.assertEqual(result, {})
490 self.assertEqual(out, '')
491
492 def test_getargs_reset_static_parser(self):
493 # Test _PyArg_Parser initializations via _PyArg_UnpackKeywords()
494 # https://github.com/python/cpython/issues/122334
495 code = textwrap.dedent("""
496 try:
497 import _ssl
498 except ModuleNotFoundError:
499 _ssl = None
500 if _ssl is not None:
501 _ssl.txt2obj(txt='1.3')
502 print('1')
503
504 import _queue
505 _queue.SimpleQueue().put_nowait(item=None)
506 print('2')
507
508 import _zoneinfo
509 _zoneinfo.ZoneInfo.clear_cache(only_keys=['Foo/Bar'])
510 print('3')
511 """)
512 out, err = self.run_embedded_interpreter("test_repeated_init_exec", code)
513 self.assertEqual(out, '1\n2\n3\n' * INIT_LOOPS)
514
515 @staticmethod
516 def _nogil_filtered_err(err: str, mod_name: str) -> str:
517 if not support.Py_GIL_DISABLED:
518 return err
519
520 # the test imports a singlephase init extension, so it emits a warning
521 # under the free-threaded build
522 expected_runtime_warning = (
523 "RuntimeWarning: The global interpreter lock (GIL)"
524 f" has been enabled to load module '{mod_name}'"
525 )
526 filtered_err_lines = [
527 line
528 for line in err.strip().splitlines()
529 if expected_runtime_warning not in line
530 ]
531 return "\n".join(filtered_err_lines)
532
533
534 @unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
535 class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
536 maxDiff = 4096
537 UTF8_MODE_ERRORS = ('surrogatepass' if MS_WINDOWS else 'surrogateescape')
538
539 # Marker to read the default configuration: get_default_config()
540 GET_DEFAULT_CONFIG = object()
541
542 # Marker to ignore a configuration parameter
543 IGNORE_CONFIG = object()
544
545 PRE_CONFIG_COMPAT = {
546 '_config_init': API_COMPAT,
547 'allocator': PYMEM_ALLOCATOR_NOT_SET,
548 'parse_argv': 0,
549 'configure_locale': 1,
550 'coerce_c_locale': 0,
551 'coerce_c_locale_warn': 0,
552 'utf8_mode': 0,
553 }
554 if MS_WINDOWS:
555 PRE_CONFIG_COMPAT.update({
556 'legacy_windows_fs_encoding': 0,
557 })
558 PRE_CONFIG_PYTHON = dict(PRE_CONFIG_COMPAT,
559 _config_init=API_PYTHON,
560 parse_argv=1,
561 coerce_c_locale=GET_DEFAULT_CONFIG,
562 utf8_mode=GET_DEFAULT_CONFIG,
563 )
564 PRE_CONFIG_ISOLATED = dict(PRE_CONFIG_COMPAT,
565 _config_init=API_ISOLATED,
566 configure_locale=0,
567 isolated=1,
568 use_environment=0,
569 utf8_mode=0,
570 dev_mode=0,
571 coerce_c_locale=0,
572 )
573
574 COPY_PRE_CONFIG = [
575 'dev_mode',
576 'isolated',
577 'use_environment',
578 ]
579
580 CONFIG_COMPAT = {
581 '_config_init': API_COMPAT,
582 'isolated': False,
583 'use_environment': True,
584 'dev_mode': False,
585
586 'install_signal_handlers': True,
587 'use_hash_seed': False,
588 'hash_seed': 0,
589 'int_max_str_digits': sys.int_info.default_max_str_digits,
590 'cpu_count': -1,
591 'faulthandler': False,
592 'tracemalloc': 0,
593 'perf_profiling': False,
594 'import_time': False,
595 'code_debug_ranges': True,
596 'show_ref_count': False,
597 'dump_refs': False,
598 'dump_refs_file': None,
599 'malloc_stats': False,
600
601 'filesystem_encoding': GET_DEFAULT_CONFIG,
602 'filesystem_errors': GET_DEFAULT_CONFIG,
603
604 'pycache_prefix': None,
605 'program_name': GET_DEFAULT_CONFIG,
606 'parse_argv': False,
607 'argv': [""],
608 'orig_argv': [],
609
610 'xoptions': [],
611 'warnoptions': [],
612
613 'pythonpath_env': None,
614 'home': None,
615 'executable': GET_DEFAULT_CONFIG,
616 'base_executable': GET_DEFAULT_CONFIG,
617
618 'prefix': GET_DEFAULT_CONFIG,
619 'base_prefix': GET_DEFAULT_CONFIG,
620 'exec_prefix': GET_DEFAULT_CONFIG,
621 'base_exec_prefix': GET_DEFAULT_CONFIG,
622 'module_search_paths': GET_DEFAULT_CONFIG,
623 'module_search_paths_set': True,
624 'platlibdir': sys.platlibdir,
625 'stdlib_dir': GET_DEFAULT_CONFIG,
626
627 'site_import': True,
628 'bytes_warning': 0,
629 'warn_default_encoding': False,
630 'inspect': False,
631 'interactive': False,
632 'optimization_level': 0,
633 'parser_debug': False,
634 'write_bytecode': True,
635 'verbose': 0,
636 'quiet': False,
637 'user_site_directory': True,
638 'configure_c_stdio': False,
639 'buffered_stdio': True,
640
641 'stdio_encoding': GET_DEFAULT_CONFIG,
642 'stdio_errors': GET_DEFAULT_CONFIG,
643
644 'skip_source_first_line': False,
645 'run_command': None,
646 'run_module': None,
647 'run_filename': None,
648 'sys_path_0': None,
649
650 '_install_importlib': True,
651 'check_hash_pycs_mode': 'default',
652 'pathconfig_warnings': True,
653 '_init_main': True,
654 'use_frozen_modules': not support.Py_DEBUG,
655 'safe_path': False,
656 '_is_python_build': IGNORE_CONFIG,
657 }
658 if Py_STATS:
659 CONFIG_COMPAT['_pystats'] = 0
660 if support.Py_DEBUG:
661 CONFIG_COMPAT['run_presite'] = None
662 if support.Py_GIL_DISABLED:
663 CONFIG_COMPAT['enable_gil'] = -1
664 if MS_WINDOWS:
665 CONFIG_COMPAT.update({
666 'legacy_windows_stdio': 0,
667 })
668
669 CONFIG_PYTHON = dict(CONFIG_COMPAT,
670 _config_init=API_PYTHON,
671 configure_c_stdio=True,
672 parse_argv=True,
673 )
674 CONFIG_ISOLATED = dict(CONFIG_COMPAT,
675 _config_init=API_ISOLATED,
676 isolated=True,
677 use_environment=False,
678 user_site_directory=False,
679 safe_path=True,
680 dev_mode=False,
681 install_signal_handlers=False,
682 use_hash_seed=False,
683 faulthandler=False,
684 tracemalloc=0,
685 perf_profiling=False,
686 pathconfig_warnings=False,
687 )
688 if MS_WINDOWS:
689 CONFIG_ISOLATED['legacy_windows_stdio'] = 0
690
691 # global config
692 DEFAULT_GLOBAL_CONFIG = {
693 'Py_HasFileSystemDefaultEncoding': 0,
694 'Py_HashRandomizationFlag': 1,
695 '_Py_HasFileSystemDefaultEncodeErrors': 0,
696 }
697 COPY_GLOBAL_PRE_CONFIG = [
698 ('Py_UTF8Mode', 'utf8_mode'),
699 ]
700 COPY_GLOBAL_CONFIG = [
701 # Copy core config to global config for expected values
702 # True means that the core config value is inverted (0 => 1 and 1 => 0)
703 ('Py_BytesWarningFlag', 'bytes_warning'),
704 ('Py_DebugFlag', 'parser_debug'),
705 ('Py_DontWriteBytecodeFlag', 'write_bytecode', True),
706 ('Py_FileSystemDefaultEncodeErrors', 'filesystem_errors'),
707 ('Py_FileSystemDefaultEncoding', 'filesystem_encoding'),
708 ('Py_FrozenFlag', 'pathconfig_warnings', True),
709 ('Py_IgnoreEnvironmentFlag', 'use_environment', True),
710 ('Py_InspectFlag', 'inspect'),
711 ('Py_InteractiveFlag', 'interactive'),
712 ('Py_IsolatedFlag', 'isolated'),
713 ('Py_NoSiteFlag', 'site_import', True),
714 ('Py_NoUserSiteDirectory', 'user_site_directory', True),
715 ('Py_OptimizeFlag', 'optimization_level'),
716 ('Py_QuietFlag', 'quiet'),
717 ('Py_UnbufferedStdioFlag', 'buffered_stdio', True),
718 ('Py_VerboseFlag', 'verbose'),
719 ]
720 if MS_WINDOWS:
721 COPY_GLOBAL_PRE_CONFIG.extend((
722 ('Py_LegacyWindowsFSEncodingFlag', 'legacy_windows_fs_encoding'),
723 ))
724 COPY_GLOBAL_CONFIG.extend((
725 ('Py_LegacyWindowsStdioFlag', 'legacy_windows_stdio'),
726 ))
727
728 EXPECTED_CONFIG = None
729
730 @classmethod
731 def tearDownClass(cls):
732 # clear cache
733 cls.EXPECTED_CONFIG = None
734
735 def main_xoptions(self, xoptions_list):
736 xoptions = {}
737 for opt in xoptions_list:
738 if '=' in opt:
739 key, value = opt.split('=', 1)
740 xoptions[key] = value
741 else:
742 xoptions[opt] = True
743 return xoptions
744
745 def _get_expected_config_impl(self):
746 env = remove_python_envvars()
747 code = textwrap.dedent('''
748 import json
749 import sys
750 import _testinternalcapi
751
752 configs = _testinternalcapi.get_configs()
753
754 data = json.dumps(configs)
755 data = data.encode('utf-8')
756 sys.stdout.buffer.write(data)
757 sys.stdout.buffer.flush()
758 ''')
759
760 # Use -S to not import the site module: get the proper configuration
761 # when test_embed is run from a venv (bpo-35313)
762 args = [sys.executable, '-S', '-c', code]
763 proc = subprocess.run(args, env=env,
764 stdout=subprocess.PIPE,
765 stderr=subprocess.PIPE)
766 if proc.returncode:
767 raise Exception(f"failed to get the default config: "
768 f"stdout={proc.stdout!r} stderr={proc.stderr!r}")
769 stdout = proc.stdout.decode('utf-8')
770 # ignore stderr
771 try:
772 return json.loads(stdout)
773 except json.JSONDecodeError:
774 self.fail(f"fail to decode stdout: {stdout!r}")
775
776 def _get_expected_config(self):
777 cls = InitConfigTests
778 if cls.EXPECTED_CONFIG is None:
779 cls.EXPECTED_CONFIG = self._get_expected_config_impl()
780
781 # get a copy
782 configs = {}
783 for config_key, config_value in cls.EXPECTED_CONFIG.items():
784 config = {}
785 for key, value in config_value.items():
786 if isinstance(value, list):
787 value = value.copy()
788 config[key] = value
789 configs[config_key] = config
790 return configs
791
792 def get_expected_config(self, expected_preconfig, expected,
793 env, api, modify_path_cb=None):
794 configs = self._get_expected_config()
795
796 pre_config = configs['pre_config']
797 for key, value in expected_preconfig.items():
798 if value is self.GET_DEFAULT_CONFIG:
799 expected_preconfig[key] = pre_config[key]
800
801 if not expected_preconfig['configure_locale'] or api == API_COMPAT:
802 # there is no easy way to get the locale encoding before
803 # setlocale(LC_CTYPE, "") is called: don't test encodings
804 for key in ('filesystem_encoding', 'filesystem_errors',
805 'stdio_encoding', 'stdio_errors'):
806 expected[key] = self.IGNORE_CONFIG
807
808 if not expected_preconfig['configure_locale']:
809 # UTF-8 Mode depends on the locale. There is no easy way
810 # to guess if UTF-8 Mode will be enabled or not if the locale
811 # is not configured.
812 expected_preconfig['utf8_mode'] = self.IGNORE_CONFIG
813
814 if expected_preconfig['utf8_mode'] == 1:
815 if expected['filesystem_encoding'] is self.GET_DEFAULT_CONFIG:
816 expected['filesystem_encoding'] = 'utf-8'
817 if expected['filesystem_errors'] is self.GET_DEFAULT_CONFIG:
818 expected['filesystem_errors'] = self.UTF8_MODE_ERRORS
819 if expected['stdio_encoding'] is self.GET_DEFAULT_CONFIG:
820 expected['stdio_encoding'] = 'utf-8'
821 if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG:
822 expected['stdio_errors'] = 'surrogateescape'
823
824 if MS_WINDOWS:
825 default_executable = self.test_exe
826 elif expected['program_name'] is not self.GET_DEFAULT_CONFIG:
827 default_executable = os.path.abspath(expected['program_name'])
828 else:
829 default_executable = os.path.join(os.getcwd(), '_testembed')
830 if expected['executable'] is self.GET_DEFAULT_CONFIG:
831 expected['executable'] = default_executable
832 if expected['base_executable'] is self.GET_DEFAULT_CONFIG:
833 expected['base_executable'] = default_executable
834 if expected['program_name'] is self.GET_DEFAULT_CONFIG:
835 expected['program_name'] = './_testembed'
836
837 config = configs['config']
838 for key, value in expected.items():
839 if value is self.GET_DEFAULT_CONFIG:
840 expected[key] = config[key]
841
842 if expected['module_search_paths'] is not self.IGNORE_CONFIG:
843 pythonpath_env = expected['pythonpath_env']
844 if pythonpath_env is not None:
845 paths = pythonpath_env.split(os.path.pathsep)
846 expected['module_search_paths'] = [*paths, *expected['module_search_paths']]
847 if modify_path_cb is not None:
848 expected['module_search_paths'] = expected['module_search_paths'].copy()
849 modify_path_cb(expected['module_search_paths'])
850
851 for key in self.COPY_PRE_CONFIG:
852 if key not in expected_preconfig:
853 expected_preconfig[key] = expected[key]
854
855 def check_pre_config(self, configs, expected):
856 pre_config = dict(configs['pre_config'])
857 for key, value in list(expected.items()):
858 if value is self.IGNORE_CONFIG:
859 pre_config.pop(key, None)
860 del expected[key]
861 self.assertEqual(pre_config, expected)
862
863 def check_config(self, configs, expected):
864 config = dict(configs['config'])
865 if MS_WINDOWS:
866 value = config.get(key := 'program_name')
867 if value and isinstance(value, str):
868 value = value[:len(value.lower().removesuffix('.exe'))]
869 if debug_build(sys.executable):
870 value = value[:len(value.lower().removesuffix('_d'))]
871 config[key] = value
872 for key, value in list(expected.items()):
873 if value is self.IGNORE_CONFIG:
874 config.pop(key, None)
875 del expected[key]
876 # Resolve bool/int mismatches to reduce noise in diffs
877 if isinstance(value, (bool, int)) and isinstance(config.get(key), (bool, int)):
878 expected[key] = type(config[key])(expected[key])
879 self.assertEqual(config, expected)
880
881 def check_global_config(self, configs):
882 pre_config = configs['pre_config']
883 config = configs['config']
884
885 expected = dict(self.DEFAULT_GLOBAL_CONFIG)
886 for item in self.COPY_GLOBAL_CONFIG:
887 if len(item) == 3:
888 global_key, core_key, opposite = item
889 expected[global_key] = 0 if config[core_key] else 1
890 else:
891 global_key, core_key = item
892 expected[global_key] = config[core_key]
893 for item in self.COPY_GLOBAL_PRE_CONFIG:
894 if len(item) == 3:
895 global_key, core_key, opposite = item
896 expected[global_key] = 0 if pre_config[core_key] else 1
897 else:
898 global_key, core_key = item
899 expected[global_key] = pre_config[core_key]
900
901 self.assertEqual(configs['global_config'], expected)
902
903 def check_all_configs(self, testname, expected_config=None,
904 expected_preconfig=None,
905 modify_path_cb=None,
906 stderr=None, *, api, preconfig_api=None,
907 env=None, ignore_stderr=False, cwd=None):
908 new_env = remove_python_envvars()
909 if env is not None:
910 new_env.update(env)
911 env = new_env
912
913 if preconfig_api is None:
914 preconfig_api = api
915 if preconfig_api == API_ISOLATED:
916 default_preconfig = self.PRE_CONFIG_ISOLATED
917 elif preconfig_api == API_PYTHON:
918 default_preconfig = self.PRE_CONFIG_PYTHON
919 else:
920 default_preconfig = self.PRE_CONFIG_COMPAT
921 if expected_preconfig is None:
922 expected_preconfig = {}
923 expected_preconfig = dict(default_preconfig, **expected_preconfig)
924
925 if expected_config is None:
926 expected_config = {}
927
928 if api == API_PYTHON:
929 default_config = self.CONFIG_PYTHON
930 elif api == API_ISOLATED:
931 default_config = self.CONFIG_ISOLATED
932 else:
933 default_config = self.CONFIG_COMPAT
934 expected_config = dict(default_config, **expected_config)
935
936 self.get_expected_config(expected_preconfig,
937 expected_config,
938 env,
939 api, modify_path_cb)
940
941 out, err = self.run_embedded_interpreter(testname,
942 env=env, cwd=cwd)
943 if stderr is None and not expected_config['verbose']:
944 stderr = ""
945 if stderr is not None and not ignore_stderr:
946 self.assertEqual(err.rstrip(), stderr)
947 try:
948 configs = json.loads(out)
949 except json.JSONDecodeError:
950 self.fail(f"fail to decode stdout: {out!r}")
951
952 self.check_pre_config(configs, expected_preconfig)
953 self.check_config(configs, expected_config)
954 self.check_global_config(configs)
955 return configs
956
957 def test_init_default_config(self):
958 self.check_all_configs("test_init_initialize_config", api=API_COMPAT)
959
960 def test_preinit_compat_config(self):
961 self.check_all_configs("test_preinit_compat_config", api=API_COMPAT)
962
963 def test_init_compat_config(self):
964 self.check_all_configs("test_init_compat_config", api=API_COMPAT)
965
966 def test_init_global_config(self):
967 preconfig = {
968 'utf8_mode': 1,
969 }
970 config = {
971 'program_name': './globalvar',
972 'site_import': 0,
973 'bytes_warning': 1,
974 'warnoptions': ['default::BytesWarning'],
975 'inspect': 1,
976 'interactive': 1,
977 'optimization_level': 2,
978 'write_bytecode': 0,
979 'verbose': 1,
980 'quiet': 1,
981 'buffered_stdio': 0,
982
983 'user_site_directory': 0,
984 'pathconfig_warnings': 0,
985 }
986 self.check_all_configs("test_init_global_config", config, preconfig,
987 api=API_COMPAT)
988
989 def test_init_from_config(self):
990 preconfig = {
991 'allocator': ALLOCATOR_FOR_CONFIG,
992 'utf8_mode': 1,
993 }
994 config = {
995 'install_signal_handlers': False,
996 'use_hash_seed': True,
997 'hash_seed': 123,
998 'tracemalloc': 2,
999 'perf_profiling': False,
1000 'import_time': True,
1001 'code_debug_ranges': False,
1002 'show_ref_count': True,
1003 'malloc_stats': True,
1004
1005 'stdio_encoding': 'iso8859-1',
1006 'stdio_errors': 'replace',
1007
1008 'pycache_prefix': 'conf_pycache_prefix',
1009 'program_name': './conf_program_name',
1010 'argv': ['-c', 'arg2'],
1011 'orig_argv': ['python3',
1012 '-W', 'cmdline_warnoption',
1013 '-X', 'cmdline_xoption',
1014 '-c', 'pass',
1015 'arg2'],
1016 'parse_argv': True,
1017 'xoptions': [
1018 'config_xoption1=3',
1019 'config_xoption2=',
1020 'config_xoption3',
1021 'cmdline_xoption',
1022 ],
1023 'warnoptions': [
1024 'cmdline_warnoption',
1025 'default::BytesWarning',
1026 'config_warnoption',
1027 ],
1028 'run_command': 'pass\n',
1029
1030 'site_import': False,
1031 'bytes_warning': 1,
1032 'inspect': True,
1033 'interactive': True,
1034 'optimization_level': 2,
1035 'write_bytecode': False,
1036 'verbose': 1,
1037 'quiet': True,
1038 'configure_c_stdio': True,
1039 'buffered_stdio': False,
1040 'user_site_directory': False,
1041 'faulthandler': True,
1042 'platlibdir': 'my_platlibdir',
1043 'module_search_paths': self.IGNORE_CONFIG,
1044 'safe_path': True,
1045 'int_max_str_digits': 31337,
1046 'cpu_count': 4321,
1047
1048 'check_hash_pycs_mode': 'always',
1049 'pathconfig_warnings': False,
1050 }
1051 if Py_STATS:
1052 config['_pystats'] = 1
1053 self.check_all_configs("test_init_from_config", config, preconfig,
1054 api=API_COMPAT)
1055
1056 def test_init_compat_env(self):
1057 preconfig = {
1058 'allocator': ALLOCATOR_FOR_CONFIG,
1059 }
1060 config = {
1061 'use_hash_seed': True,
1062 'hash_seed': 42,
1063 'tracemalloc': 2,
1064 'perf_profiling': False,
1065 'import_time': True,
1066 'code_debug_ranges': False,
1067 'malloc_stats': True,
1068 'inspect': True,
1069 'optimization_level': 2,
1070 'pythonpath_env': '/my/path',
1071 'pycache_prefix': 'env_pycache_prefix',
1072 'write_bytecode': False,
1073 'verbose': 1,
1074 'buffered_stdio': False,
1075 'stdio_encoding': 'iso8859-1',
1076 'stdio_errors': 'replace',
1077 'user_site_directory': False,
1078 'faulthandler': True,
1079 'warnoptions': ['EnvVar'],
1080 'platlibdir': 'env_platlibdir',
1081 'module_search_paths': self.IGNORE_CONFIG,
1082 'safe_path': True,
1083 'int_max_str_digits': 4567,
1084 }
1085 if Py_STATS:
1086 config['_pystats'] = 1
1087 self.check_all_configs("test_init_compat_env", config, preconfig,
1088 api=API_COMPAT)
1089
1090 def test_init_python_env(self):
1091 preconfig = {
1092 'allocator': ALLOCATOR_FOR_CONFIG,
1093 'utf8_mode': 1,
1094 }
1095 config = {
1096 'use_hash_seed': True,
1097 'hash_seed': 42,
1098 'tracemalloc': 2,
1099 'perf_profiling': False,
1100 'import_time': True,
1101 'code_debug_ranges': False,
1102 'malloc_stats': True,
1103 'inspect': True,
1104 'optimization_level': 2,
1105 'pythonpath_env': '/my/path',
1106 'pycache_prefix': 'env_pycache_prefix',
1107 'write_bytecode': False,
1108 'verbose': 1,
1109 'buffered_stdio': False,
1110 'stdio_encoding': 'iso8859-1',
1111 'stdio_errors': 'replace',
1112 'user_site_directory': False,
1113 'faulthandler': True,
1114 'warnoptions': ['EnvVar'],
1115 'platlibdir': 'env_platlibdir',
1116 'module_search_paths': self.IGNORE_CONFIG,
1117 'safe_path': True,
1118 'int_max_str_digits': 4567,
1119 }
1120 if Py_STATS:
1121 config['_pystats'] = True
1122 self.check_all_configs("test_init_python_env", config, preconfig,
1123 api=API_PYTHON)
1124
1125 def test_init_env_dev_mode(self):
1126 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
1127 config = dict(dev_mode=1,
1128 faulthandler=1,
1129 warnoptions=['default'])
1130 self.check_all_configs("test_init_env_dev_mode", config, preconfig,
1131 api=API_COMPAT)
1132
1133 def test_init_env_dev_mode_alloc(self):
1134 preconfig = dict(allocator=ALLOCATOR_FOR_CONFIG)
1135 config = dict(dev_mode=1,
1136 faulthandler=1,
1137 warnoptions=['default'])
1138 self.check_all_configs("test_init_env_dev_mode_alloc", config, preconfig,
1139 api=API_COMPAT)
1140
1141 def test_init_dev_mode(self):
1142 preconfig = {
1143 'allocator': PYMEM_ALLOCATOR_DEBUG,
1144 }
1145 config = {
1146 'faulthandler': True,
1147 'dev_mode': True,
1148 'warnoptions': ['default'],
1149 }
1150 self.check_all_configs("test_init_dev_mode", config, preconfig,
1151 api=API_PYTHON)
1152
1153 def test_preinit_parse_argv(self):
1154 # Pre-initialize implicitly using argv: make sure that -X dev
1155 # is used to configure the allocation in preinitialization
1156 preconfig = {
1157 'allocator': PYMEM_ALLOCATOR_DEBUG,
1158 }
1159 config = {
1160 'argv': ['script.py'],
1161 'orig_argv': ['python3', '-X', 'dev', '-P', 'script.py'],
1162 'run_filename': os.path.abspath('script.py'),
1163 'dev_mode': True,
1164 'faulthandler': True,
1165 'warnoptions': ['default'],
1166 'xoptions': ['dev'],
1167 'safe_path': True,
1168 }
1169 self.check_all_configs("test_preinit_parse_argv", config, preconfig,
1170 api=API_PYTHON)
1171
1172 def test_preinit_dont_parse_argv(self):
1173 # -X dev must be ignored by isolated preconfiguration
1174 preconfig = {
1175 'isolated': 0,
1176 }
1177 argv = ["python3",
1178 "-E", "-I", "-P",
1179 "-X", "dev",
1180 "-X", "utf8",
1181 "script.py"]
1182 config = {
1183 'argv': argv,
1184 'orig_argv': argv,
1185 'isolated': 0,
1186 }
1187 self.check_all_configs("test_preinit_dont_parse_argv", config, preconfig,
1188 api=API_ISOLATED)
1189
1190 def test_init_isolated_flag(self):
1191 config = {
1192 'isolated': True,
1193 'safe_path': True,
1194 'use_environment': False,
1195 'user_site_directory': False,
1196 }
1197 self.check_all_configs("test_init_isolated_flag", config, api=API_PYTHON)
1198
1199 def test_preinit_isolated1(self):
1200 # _PyPreConfig.isolated=1, _PyCoreConfig.isolated not set
1201 config = {
1202 'isolated': True,
1203 'safe_path': True,
1204 'use_environment': False,
1205 'user_site_directory': False,
1206 }
1207 self.check_all_configs("test_preinit_isolated1", config, api=API_COMPAT)
1208
1209 def test_preinit_isolated2(self):
1210 # _PyPreConfig.isolated=0, _PyCoreConfig.isolated=1
1211 config = {
1212 'isolated': True,
1213 'safe_path': True,
1214 'use_environment': False,
1215 'user_site_directory': False,
1216 }
1217 self.check_all_configs("test_preinit_isolated2", config, api=API_COMPAT)
1218
1219 def test_preinit_isolated_config(self):
1220 self.check_all_configs("test_preinit_isolated_config", api=API_ISOLATED)
1221
1222 def test_init_isolated_config(self):
1223 self.check_all_configs("test_init_isolated_config", api=API_ISOLATED)
1224
1225 def test_preinit_python_config(self):
1226 self.check_all_configs("test_preinit_python_config", api=API_PYTHON)
1227
1228 def test_init_python_config(self):
1229 self.check_all_configs("test_init_python_config", api=API_PYTHON)
1230
1231 def test_init_dont_configure_locale(self):
1232 # _PyPreConfig.configure_locale=0
1233 preconfig = {
1234 'configure_locale': 0,
1235 'coerce_c_locale': 0,
1236 }
1237 self.check_all_configs("test_init_dont_configure_locale", {}, preconfig,
1238 api=API_PYTHON)
1239
1240 @unittest.skip('as of 3.11 this test no longer works because '
1241 'path calculations do not occur on read')
1242 def test_init_read_set(self):
1243 config = {
1244 'program_name': './init_read_set',
1245 'executable': 'my_executable',
1246 'base_executable': 'my_executable',
1247 }
1248 def modify_path(path):
1249 path.insert(1, "test_path_insert1")
1250 path.append("test_path_append")
1251 self.check_all_configs("test_init_read_set", config,
1252 api=API_PYTHON,
1253 modify_path_cb=modify_path)
1254
1255 def test_init_sys_add(self):
1256 config = {
1257 'faulthandler': 1,
1258 'xoptions': [
1259 'config_xoption',
1260 'cmdline_xoption',
1261 'sysadd_xoption',
1262 'faulthandler',
1263 ],
1264 'warnoptions': [
1265 'ignore:::cmdline_warnoption',
1266 'ignore:::sysadd_warnoption',
1267 'ignore:::config_warnoption',
1268 ],
1269 'orig_argv': ['python3',
1270 '-W', 'ignore:::cmdline_warnoption',
1271 '-X', 'cmdline_xoption'],
1272 }
1273 self.check_all_configs("test_init_sys_add", config, api=API_PYTHON)
1274
1275 def test_init_run_main(self):
1276 code = ('import _testinternalcapi, json; '
1277 'print(json.dumps(_testinternalcapi.get_configs()))')
1278 config = {
1279 'argv': ['-c', 'arg2'],
1280 'orig_argv': ['python3', '-c', code, 'arg2'],
1281 'program_name': './python3',
1282 'run_command': code + '\n',
1283 'parse_argv': True,
1284 'sys_path_0': '',
1285 }
1286 self.check_all_configs("test_init_run_main", config, api=API_PYTHON)
1287
1288 def test_init_main(self):
1289 code = ('import _testinternalcapi, json; '
1290 'print(json.dumps(_testinternalcapi.get_configs()))')
1291 config = {
1292 'argv': ['-c', 'arg2'],
1293 'orig_argv': ['python3',
1294 '-c', code,
1295 'arg2'],
1296 'program_name': './python3',
1297 'run_command': code + '\n',
1298 'parse_argv': True,
1299 '_init_main': 0,
1300 'sys_path_0': '',
1301 }
1302 self.check_all_configs("test_init_main", config,
1303 api=API_PYTHON,
1304 stderr="Run Python code before _Py_InitializeMain")
1305
1306 def test_init_parse_argv(self):
1307 config = {
1308 'parse_argv': True,
1309 'argv': ['-c', 'arg1', '-v', 'arg3'],
1310 'orig_argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
1311 'program_name': './argv0',
1312 'run_command': 'pass\n',
1313 'use_environment': False,
1314 }
1315 self.check_all_configs("test_init_parse_argv", config, api=API_PYTHON)
1316
1317 def test_init_dont_parse_argv(self):
1318 pre_config = {
1319 'parse_argv': 0,
1320 }
1321 config = {
1322 'parse_argv': False,
1323 'argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
1324 'orig_argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
1325 'program_name': './argv0',
1326 }
1327 self.check_all_configs("test_init_dont_parse_argv", config, pre_config,
1328 api=API_PYTHON)
1329
1330 def default_program_name(self, config):
1331 if MS_WINDOWS:
1332 program_name = 'python'
1333 executable = self.test_exe
1334 else:
1335 program_name = 'python3'
1336 if MACOS:
1337 executable = self.test_exe
1338 else:
1339 executable = shutil.which(program_name) or ''
1340 config.update({
1341 'program_name': program_name,
1342 'base_executable': executable,
1343 'executable': executable,
1344 })
1345
1346 def test_init_setpath(self):
1347 # Test Py_SetPath()
1348 config = self._get_expected_config()
1349 paths = config['config']['module_search_paths']
1350
1351 config = {
1352 'module_search_paths': paths,
1353 'prefix': '',
1354 'base_prefix': '',
1355 'exec_prefix': '',
1356 'base_exec_prefix': '',
1357 # The current getpath.c doesn't determine the stdlib dir
1358 # in this case.
1359 'stdlib_dir': '',
1360 }
1361 self.default_program_name(config)
1362 env = {'TESTPATH': os.path.pathsep.join(paths)}
1363
1364 self.check_all_configs("test_init_setpath", config,
1365 api=API_COMPAT, env=env,
1366 ignore_stderr=True)
1367
1368 def test_init_setpath_config(self):
1369 # Test Py_SetPath() with PyConfig
1370 config = self._get_expected_config()
1371 paths = config['config']['module_search_paths']
1372
1373 config = {
1374 # set by Py_SetPath()
1375 'module_search_paths': paths,
1376 'prefix': '',
1377 'base_prefix': '',
1378 'exec_prefix': '',
1379 'base_exec_prefix': '',
1380 # The current getpath.c doesn't determine the stdlib dir
1381 # in this case.
1382 'stdlib_dir': '',
1383 'use_frozen_modules': not support.Py_DEBUG,
1384 # overridden by PyConfig
1385 'program_name': 'conf_program_name',
1386 'base_executable': 'conf_executable',
1387 'executable': 'conf_executable',
1388 }
1389 env = {'TESTPATH': os.path.pathsep.join(paths)}
1390 self.check_all_configs("test_init_setpath_config", config,
1391 api=API_PYTHON, env=env, ignore_stderr=True)
1392
1393 def module_search_paths(self, prefix=None, exec_prefix=None):
1394 config = self._get_expected_config()
1395 if prefix is None:
1396 prefix = config['config']['prefix']
1397 if exec_prefix is None:
1398 exec_prefix = config['config']['prefix']
1399 if MS_WINDOWS:
1400 return config['config']['module_search_paths']
1401 else:
1402 ver = sys.version_info
1403 return [
1404 os.path.join(prefix, sys.platlibdir,
1405 f'python{ver.major}{ver.minor}{ABI_THREAD}.zip'),
1406 os.path.join(prefix, sys.platlibdir,
1407 f'python{ver.major}.{ver.minor}{ABI_THREAD}'),
1408 os.path.join(exec_prefix, sys.platlibdir,
1409 f'python{ver.major}.{ver.minor}{ABI_THREAD}', 'lib-dynload'),
1410 ]
1411
1412 @contextlib.contextmanager
1413 def tmpdir_with_python(self, subdir=None):
1414 # Temporary directory with a copy of the Python program
1415 with tempfile.TemporaryDirectory() as tmpdir:
1416 # bpo-38234: On macOS and FreeBSD, the temporary directory
1417 # can be symbolic link. For example, /tmp can be a symbolic link
1418 # to /var/tmp. Call realpath() to resolve all symbolic links.
1419 tmpdir = os.path.realpath(tmpdir)
1420 if subdir:
1421 tmpdir = os.path.normpath(os.path.join(tmpdir, subdir))
1422 os.makedirs(tmpdir)
1423
1424 if MS_WINDOWS:
1425 # Copy pythonXY.dll (or pythonXY_d.dll)
1426 import fnmatch
1427 exedir = os.path.dirname(self.test_exe)
1428 for f in os.listdir(exedir):
1429 if fnmatch.fnmatch(f, '*.dll'):
1430 shutil.copyfile(os.path.join(exedir, f), os.path.join(tmpdir, f))
1431
1432 # Copy Python program
1433 exec_copy = os.path.join(tmpdir, os.path.basename(self.test_exe))
1434 shutil.copyfile(self.test_exe, exec_copy)
1435 shutil.copystat(self.test_exe, exec_copy)
1436 self.test_exe = exec_copy
1437
1438 yield tmpdir
1439
1440 def test_init_setpythonhome(self):
1441 # Test Py_SetPythonHome(home) with PYTHONPATH env var
1442 config = self._get_expected_config()
1443 paths = config['config']['module_search_paths']
1444 paths_str = os.path.pathsep.join(paths)
1445
1446 for path in paths:
1447 if not os.path.isdir(path):
1448 continue
1449 if os.path.exists(os.path.join(path, 'os.py')):
1450 home = os.path.dirname(path)
1451 break
1452 else:
1453 self.fail(f"Unable to find home in {paths!r}")
1454
1455 prefix = exec_prefix = home
1456 if MS_WINDOWS:
1457 stdlib = os.path.join(home, "Lib")
1458 # Because we are specifying 'home', module search paths
1459 # are fairly static
1460 expected_paths = [paths[0], os.path.join(home, 'DLLs'), stdlib]
1461 else:
1462 version = f'{sys.version_info.major}.{sys.version_info.minor}'
1463 stdlib = os.path.join(home, sys.platlibdir, f'python{version}{ABI_THREAD}')
1464 expected_paths = self.module_search_paths(prefix=home, exec_prefix=home)
1465
1466 config = {
1467 'home': home,
1468 'module_search_paths': expected_paths,
1469 'prefix': prefix,
1470 'base_prefix': prefix,
1471 'exec_prefix': exec_prefix,
1472 'base_exec_prefix': exec_prefix,
1473 'pythonpath_env': paths_str,
1474 'stdlib_dir': stdlib,
1475 }
1476 self.default_program_name(config)
1477 env = {'TESTHOME': home, 'PYTHONPATH': paths_str}
1478 self.check_all_configs("test_init_setpythonhome", config,
1479 api=API_COMPAT, env=env)
1480
1481 def test_init_is_python_build_with_home(self):
1482 # Test _Py_path_config._is_python_build configuration (gh-91985)
1483 config = self._get_expected_config()
1484 paths = config['config']['module_search_paths']
1485 paths_str = os.path.pathsep.join(paths)
1486
1487 for path in paths:
1488 if not os.path.isdir(path):
1489 continue
1490 if os.path.exists(os.path.join(path, 'os.py')):
1491 home = os.path.dirname(path)
1492 break
1493 else:
1494 self.fail(f"Unable to find home in {paths!r}")
1495
1496 prefix = exec_prefix = home
1497 if MS_WINDOWS:
1498 stdlib = os.path.join(home, "Lib")
1499 # Because we are specifying 'home', module search paths
1500 # are fairly static
1501 expected_paths = [paths[0], os.path.join(home, 'DLLs'), stdlib]
1502 else:
1503 version = f'{sys.version_info.major}.{sys.version_info.minor}'
1504 stdlib = os.path.join(home, sys.platlibdir, f'python{version}{ABI_THREAD}')
1505 expected_paths = self.module_search_paths(prefix=home, exec_prefix=home)
1506
1507 config = {
1508 'home': home,
1509 'module_search_paths': expected_paths,
1510 'prefix': prefix,
1511 'base_prefix': prefix,
1512 'exec_prefix': exec_prefix,
1513 'base_exec_prefix': exec_prefix,
1514 'pythonpath_env': paths_str,
1515 'stdlib_dir': stdlib,
1516 }
1517 # The code above is taken from test_init_setpythonhome()
1518 env = {'TESTHOME': home, 'PYTHONPATH': paths_str}
1519
1520 env['NEGATIVE_ISPYTHONBUILD'] = '1'
1521 config['_is_python_build'] = 0
1522 self.check_all_configs("test_init_is_python_build", config,
1523 api=API_COMPAT, env=env)
1524
1525 env['NEGATIVE_ISPYTHONBUILD'] = '0'
1526 config['_is_python_build'] = 1
1527 exedir = os.path.dirname(sys.executable)
1528 with open(os.path.join(exedir, 'pybuilddir.txt'), encoding='utf8') as f:
1529 expected_paths[1 if MS_WINDOWS else 2] = os.path.normpath(
1530 os.path.join(exedir, f'{f.read()}\n$'.splitlines()[0]))
1531 if not MS_WINDOWS:
1532 # PREFIX (default) is set when running in build directory
1533 prefix = exec_prefix = sys.prefix
1534 # stdlib calculation (/Lib) is not yet supported
1535 expected_paths[0] = self.module_search_paths(prefix=prefix)[0]
1536 config.update(prefix=prefix, base_prefix=prefix,
1537 exec_prefix=exec_prefix, base_exec_prefix=exec_prefix)
1538 self.check_all_configs("test_init_is_python_build", config,
1539 api=API_COMPAT, env=env)
1540
1541 def copy_paths_by_env(self, config):
1542 all_configs = self._get_expected_config()
1543 paths = all_configs['config']['module_search_paths']
1544 paths_str = os.path.pathsep.join(paths)
1545 config['pythonpath_env'] = paths_str
1546 env = {'PYTHONPATH': paths_str}
1547 return env
1548
1549 @unittest.skipIf(MS_WINDOWS, 'See test_init_pybuilddir_win32')
1550 def test_init_pybuilddir(self):
1551 # Test path configuration with pybuilddir.txt configuration file
1552
1553 with self.tmpdir_with_python() as tmpdir:
1554 # pybuilddir.txt is a sub-directory relative to the current
1555 # directory (tmpdir)
1556 vpath = sysconfig.get_config_var("VPATH") or ''
1557 subdir = 'libdir'
1558 libdir = os.path.join(tmpdir, subdir)
1559 # The stdlib dir is dirname(executable) + VPATH + 'Lib'
1560 stdlibdir = os.path.normpath(os.path.join(tmpdir, vpath, 'Lib'))
1561 os.mkdir(libdir)
1562
1563 filename = os.path.join(tmpdir, 'pybuilddir.txt')
1564 with open(filename, "w", encoding="utf8") as fp:
1565 fp.write(subdir)
1566
1567 module_search_paths = self.module_search_paths()
1568 module_search_paths[-2] = stdlibdir
1569 module_search_paths[-1] = libdir
1570
1571 executable = self.test_exe
1572 config = {
1573 'base_exec_prefix': sysconfig.get_config_var("exec_prefix"),
1574 'base_prefix': sysconfig.get_config_var("prefix"),
1575 'base_executable': executable,
1576 'executable': executable,
1577 'module_search_paths': module_search_paths,
1578 'stdlib_dir': stdlibdir,
1579 }
1580 env = self.copy_paths_by_env(config)
1581 self.check_all_configs("test_init_compat_config", config,
1582 api=API_COMPAT, env=env,
1583 ignore_stderr=True, cwd=tmpdir)
1584
1585 @unittest.skipUnless(MS_WINDOWS, 'See test_init_pybuilddir')
1586 def test_init_pybuilddir_win32(self):
1587 # Test path configuration with pybuilddir.txt configuration file
1588
1589 vpath = sysconfig.get_config_var("VPATH")
1590 subdir = r'PCbuild\arch'
1591 if os.path.normpath(vpath).count(os.sep) == 2:
1592 subdir = os.path.join(subdir, 'instrumented')
1593
1594 with self.tmpdir_with_python(subdir) as tmpdir:
1595 # The prefix is dirname(executable) + VPATH
1596 prefix = os.path.normpath(os.path.join(tmpdir, vpath))
1597 # The stdlib dir is dirname(executable) + VPATH + 'Lib'
1598 stdlibdir = os.path.normpath(os.path.join(tmpdir, vpath, 'Lib'))
1599
1600 filename = os.path.join(tmpdir, 'pybuilddir.txt')
1601 with open(filename, "w", encoding="utf8") as fp:
1602 fp.write(tmpdir)
1603
1604 module_search_paths = self.module_search_paths()
1605 module_search_paths[-3] = os.path.join(tmpdir, os.path.basename(module_search_paths[-3]))
1606 module_search_paths[-2] = tmpdir
1607 module_search_paths[-1] = stdlibdir
1608
1609 executable = self.test_exe
1610 config = {
1611 'base_exec_prefix': prefix,
1612 'base_prefix': prefix,
1613 'base_executable': executable,
1614 'executable': executable,
1615 'prefix': prefix,
1616 'exec_prefix': prefix,
1617 'module_search_paths': module_search_paths,
1618 'stdlib_dir': stdlibdir,
1619 }
1620 env = self.copy_paths_by_env(config)
1621 self.check_all_configs("test_init_compat_config", config,
1622 api=API_COMPAT, env=env,
1623 ignore_stderr=False, cwd=tmpdir)
1624
1625 def test_init_pyvenv_cfg(self):
1626 # Test path configuration with pyvenv.cfg configuration file
1627
1628 with self.tmpdir_with_python() as tmpdir, \
1629 tempfile.TemporaryDirectory() as pyvenv_home:
1630 ver = sys.version_info
1631
1632 if not MS_WINDOWS:
1633 lib_dynload = os.path.join(pyvenv_home,
1634 sys.platlibdir,
1635 f'python{ver.major}.{ver.minor}{ABI_THREAD}',
1636 'lib-dynload')
1637 os.makedirs(lib_dynload)
1638 else:
1639 lib_folder = os.path.join(pyvenv_home, 'Lib')
1640 os.makedirs(lib_folder)
1641 # getpath.py uses Lib\os.py as the LANDMARK
1642 shutil.copyfile(
1643 os.path.join(support.STDLIB_DIR, 'os.py'),
1644 os.path.join(lib_folder, 'os.py'),
1645 )
1646
1647 filename = os.path.join(tmpdir, 'pyvenv.cfg')
1648 with open(filename, "w", encoding="utf8") as fp:
1649 print("home = %s" % pyvenv_home, file=fp)
1650 print("include-system-site-packages = false", file=fp)
1651
1652 paths = self.module_search_paths()
1653 if not MS_WINDOWS:
1654 paths[-1] = lib_dynload
1655 else:
1656 paths = [
1657 os.path.join(tmpdir, os.path.basename(paths[0])),
1658 pyvenv_home,
1659 os.path.join(pyvenv_home, "Lib"),
1660 ]
1661
1662 executable = self.test_exe
1663 base_executable = os.path.join(pyvenv_home, os.path.basename(executable))
1664 exec_prefix = pyvenv_home
1665 config = {
1666 'base_prefix': sysconfig.get_config_var("prefix"),
1667 'base_exec_prefix': exec_prefix,
1668 'exec_prefix': exec_prefix,
1669 'base_executable': base_executable,
1670 'executable': executable,
1671 'module_search_paths': paths,
1672 }
1673 if MS_WINDOWS:
1674 config['base_prefix'] = pyvenv_home
1675 config['prefix'] = pyvenv_home
1676 config['stdlib_dir'] = os.path.join(pyvenv_home, 'Lib')
1677 config['use_frozen_modules'] = int(not support.Py_DEBUG)
1678 else:
1679 # cannot reliably assume stdlib_dir here because it
1680 # depends too much on our build. But it ought to be found
1681 config['stdlib_dir'] = self.IGNORE_CONFIG
1682 config['use_frozen_modules'] = int(not support.Py_DEBUG)
1683
1684 env = self.copy_paths_by_env(config)
1685 self.check_all_configs("test_init_compat_config", config,
1686 api=API_COMPAT, env=env,
1687 ignore_stderr=True, cwd=tmpdir)
1688
1689 @unittest.skipUnless(MS_WINDOWS, 'specific to Windows')
1690 def test_getpath_abspath_win32(self):
1691 # Check _Py_abspath() is passed a backslashed path not to fall back to
1692 # GetFullPathNameW() on startup, which (re-)normalizes the path overly.
1693 # Currently, _Py_normpath() doesn't trim trailing dots and spaces.
1694 CASES = [
1695 ("C:/a. . .", "C:\\a. . ."),
1696 ("C:\\a. . .", "C:\\a. . ."),
1697 ("\\\\?\\C:////a////b. . .", "\\\\?\\C:\\a\\b. . ."),
1698 ("//a/b/c. . .", "\\\\a\\b\\c. . ."),
1699 ("\\\\a\\b\\c. . .", "\\\\a\\b\\c. . ."),
1700 ("a. . .", f"{os.getcwd()}\\a"), # relpath gets fully normalized
1701 ]
1702 out, err = self.run_embedded_interpreter(
1703 "test_init_initialize_config",
1704 env={**remove_python_envvars(),
1705 "PYTHONPATH": os.path.pathsep.join(c[0] for c in CASES)}
1706 )
1707 self.assertEqual(err, "")
1708 try:
1709 out = json.loads(out)
1710 except json.JSONDecodeError:
1711 self.fail(f"fail to decode stdout: {out!r}")
1712
1713 results = out['config']["module_search_paths"]
1714 for (_, expected), result in zip(CASES, results):
1715 self.assertEqual(result, expected)
1716
1717 def test_global_pathconfig(self):
1718 # Test C API functions getting the path configuration:
1719 #
1720 # - Py_GetExecPrefix()
1721 # - Py_GetPath()
1722 # - Py_GetPrefix()
1723 # - Py_GetProgramFullPath()
1724 # - Py_GetProgramName()
1725 # - Py_GetPythonHome()
1726 #
1727 # The global path configuration (_Py_path_config) must be a copy
1728 # of the path configuration of PyInterpreter.config (PyConfig).
1729 ctypes = import_helper.import_module('ctypes')
1730
1731 def get_func(name):
1732 func = getattr(ctypes.pythonapi, name)
1733 func.argtypes = ()
1734 func.restype = ctypes.c_wchar_p
1735 return func
1736
1737 Py_GetPath = get_func('Py_GetPath')
1738 Py_GetPrefix = get_func('Py_GetPrefix')
1739 Py_GetExecPrefix = get_func('Py_GetExecPrefix')
1740 Py_GetProgramName = get_func('Py_GetProgramName')
1741 Py_GetProgramFullPath = get_func('Py_GetProgramFullPath')
1742 Py_GetPythonHome = get_func('Py_GetPythonHome')
1743
1744 config = _testinternalcapi.get_configs()['config']
1745
1746 self.assertEqual(Py_GetPath().split(os.path.pathsep),
1747 config['module_search_paths'])
1748 self.assertEqual(Py_GetPrefix(), config['prefix'])
1749 self.assertEqual(Py_GetExecPrefix(), config['exec_prefix'])
1750 self.assertEqual(Py_GetProgramName(), config['program_name'])
1751 self.assertEqual(Py_GetProgramFullPath(), config['executable'])
1752 self.assertEqual(Py_GetPythonHome(), config['home'])
1753
1754 def test_init_warnoptions(self):
1755 # lowest to highest priority
1756 warnoptions = [
1757 'ignore:::PyConfig_Insert0', # PyWideStringList_Insert(0)
1758 'default', # PyConfig.dev_mode=1
1759 'ignore:::env1', # PYTHONWARNINGS env var
1760 'ignore:::env2', # PYTHONWARNINGS env var
1761 'ignore:::cmdline1', # -W opt command line option
1762 'ignore:::cmdline2', # -W opt command line option
1763 'default::BytesWarning', # PyConfig.bytes_warnings=1
1764 'ignore:::PySys_AddWarnOption1', # PySys_AddWarnOption()
1765 'ignore:::PySys_AddWarnOption2', # PySys_AddWarnOption()
1766 'ignore:::PyConfig_BeforeRead', # PyConfig.warnoptions
1767 'ignore:::PyConfig_AfterRead'] # PyWideStringList_Append()
1768 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
1769 config = {
1770 'dev_mode': 1,
1771 'faulthandler': 1,
1772 'bytes_warning': 1,
1773 'warnoptions': warnoptions,
1774 'orig_argv': ['python3',
1775 '-Wignore:::cmdline1',
1776 '-Wignore:::cmdline2'],
1777 }
1778 self.check_all_configs("test_init_warnoptions", config, preconfig,
1779 api=API_PYTHON)
1780
1781 def test_init_set_config(self):
1782 config = {
1783 '_init_main': 0,
1784 'bytes_warning': 2,
1785 'warnoptions': ['error::BytesWarning'],
1786 }
1787 self.check_all_configs("test_init_set_config", config,
1788 api=API_ISOLATED)
1789
1790 def test_get_argc_argv(self):
1791 self.run_embedded_interpreter("test_get_argc_argv")
1792 # ignore output
1793
1794 def test_init_use_frozen_modules(self):
1795 tests = {
1796 ('=on', True),
1797 ('=off', False),
1798 ('=', True),
1799 ('', True),
1800 }
1801 for raw, expected in tests:
1802 optval = f'frozen_modules{raw}'
1803 config = {
1804 'parse_argv': True,
1805 'argv': ['-c'],
1806 'orig_argv': ['./argv0', '-X', optval, '-c', 'pass'],
1807 'program_name': './argv0',
1808 'run_command': 'pass\n',
1809 'use_environment': True,
1810 'xoptions': [optval],
1811 'use_frozen_modules': expected,
1812 }
1813 env = {'TESTFROZEN': raw[1:]} if raw else None
1814 with self.subTest(repr(raw)):
1815 self.check_all_configs("test_init_use_frozen_modules", config,
1816 api=API_PYTHON, env=env)
1817
1818 def test_init_main_interpreter_settings(self):
1819 OBMALLOC = 1<<5
1820 EXTENSIONS = 1<<8
1821 THREADS = 1<<10
1822 DAEMON_THREADS = 1<<11
1823 FORK = 1<<15
1824 EXEC = 1<<16
1825 expected = {
1826 # All optional features should be enabled.
1827 'feature_flags':
1828 OBMALLOC | FORK | EXEC | THREADS | DAEMON_THREADS,
1829 'own_gil': True,
1830 }
1831 out, err = self.run_embedded_interpreter(
1832 'test_init_main_interpreter_settings',
1833 )
1834 self.assertEqual(err, '')
1835 try:
1836 out = json.loads(out)
1837 except json.JSONDecodeError:
1838 self.fail(f'fail to decode stdout: {out!r}')
1839
1840 self.assertEqual(out, expected)
1841
1842 @threading_helper.requires_working_threading()
1843 def test_init_in_background_thread(self):
1844 # gh-123022: Check that running Py_Initialize() in a background
1845 # thread doesn't crash.
1846 out, err = self.run_embedded_interpreter("test_init_in_background_thread")
1847 self.assertEqual(err, "")
1848
1849
1850 class SetConfigTests(unittest.TestCase):
1851 def test_set_config(self):
1852 # bpo-42260: Test _PyInterpreterState_SetConfig()
1853 import_helper.import_module('_testcapi')
1854 cmd = [sys.executable, '-X', 'utf8', '-I', '-m', 'test._test_embed_set_config']
1855 proc = subprocess.run(cmd,
1856 stdout=subprocess.PIPE,
1857 stderr=subprocess.PIPE,
1858 encoding='utf-8', errors='backslashreplace')
1859 if proc.returncode and support.verbose:
1860 print(proc.stdout)
1861 print(proc.stderr)
1862 self.assertEqual(proc.returncode, 0,
1863 (proc.returncode, proc.stdout, proc.stderr))
1864
1865
1866 class AuditingTests(EmbeddingTestsMixin, unittest.TestCase):
1867 def test_open_code_hook(self):
1868 self.run_embedded_interpreter("test_open_code_hook")
1869
1870 def test_audit(self):
1871 self.run_embedded_interpreter("test_audit")
1872
1873 def test_audit_tuple(self):
1874 self.run_embedded_interpreter("test_audit_tuple")
1875
1876 def test_audit_subinterpreter(self):
1877 self.run_embedded_interpreter("test_audit_subinterpreter")
1878
1879 def test_audit_run_command(self):
1880 self.run_embedded_interpreter("test_audit_run_command",
1881 timeout=support.SHORT_TIMEOUT,
1882 returncode=1)
1883
1884 def test_audit_run_file(self):
1885 self.run_embedded_interpreter("test_audit_run_file",
1886 timeout=support.SHORT_TIMEOUT,
1887 returncode=1)
1888
1889 def test_audit_run_interactivehook(self):
1890 startup = os.path.join(self.oldcwd, os_helper.TESTFN) + ".py"
1891 with open(startup, "w", encoding="utf-8") as f:
1892 print("import sys", file=f)
1893 print("sys.__interactivehook__ = lambda: None", file=f)
1894 try:
1895 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
1896 self.run_embedded_interpreter("test_audit_run_interactivehook",
1897 timeout=support.SHORT_TIMEOUT,
1898 returncode=10, env=env)
1899 finally:
1900 os.unlink(startup)
1901
1902 def test_audit_run_startup(self):
1903 startup = os.path.join(self.oldcwd, os_helper.TESTFN) + ".py"
1904 with open(startup, "w", encoding="utf-8") as f:
1905 print("pass", file=f)
1906 try:
1907 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
1908 self.run_embedded_interpreter("test_audit_run_startup",
1909 timeout=support.SHORT_TIMEOUT,
1910 returncode=10, env=env)
1911 finally:
1912 os.unlink(startup)
1913
1914 def test_audit_run_stdin(self):
1915 self.run_embedded_interpreter("test_audit_run_stdin",
1916 timeout=support.SHORT_TIMEOUT,
1917 returncode=1)
1918
1919 def test_get_incomplete_frame(self):
1920 self.run_embedded_interpreter("test_get_incomplete_frame")
1921
1922
1923 class MiscTests(EmbeddingTestsMixin, unittest.TestCase):
1924 def test_unicode_id_init(self):
1925 # bpo-42882: Test that _PyUnicode_FromId() works
1926 # when Python is initialized multiples times.
1927 self.run_embedded_interpreter("test_unicode_id_init")
1928
1929 # See bpo-44133
1930 @unittest.skipIf(os.name == 'nt',
1931 'Py_FrozenMain is not exported on Windows')
1932 @unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
1933 def test_frozenmain(self):
1934 env = dict(os.environ)
1935 env['PYTHONUNBUFFERED'] = '1'
1936 out, err = self.run_embedded_interpreter("test_frozenmain", env=env)
1937 executable = os.path.realpath('./argv0')
1938 expected = textwrap.dedent(f"""
1939 Frozen Hello World
1940 sys.argv ['./argv0', '-E', 'arg1', 'arg2']
1941 config program_name: ./argv0
1942 config executable: {executable}
1943 config use_environment: True
1944 config configure_c_stdio: True
1945 config buffered_stdio: False
1946 """).lstrip()
1947 self.assertEqual(out, expected)
1948
1949 @unittest.skipUnless(support.Py_DEBUG,
1950 '-X showrefcount requires a Python debug build')
1951 def test_no_memleak(self):
1952 # bpo-1635741: Python must release all memory at exit
1953 tests = (
1954 ('off', 'pass'),
1955 ('on', 'pass'),
1956 ('off', 'import __hello__'),
1957 ('on', 'import __hello__'),
1958 )
1959 for flag, stmt in tests:
1960 xopt = f"frozen_modules={flag}"
1961 cmd = [sys.executable, "-I", "-X", "showrefcount", "-X", xopt, "-c", stmt]
1962 proc = subprocess.run(cmd,
1963 stdout=subprocess.PIPE,
1964 stderr=subprocess.STDOUT,
1965 text=True)
1966 self.assertEqual(proc.returncode, 0)
1967 out = proc.stdout.rstrip()
1968 match = re.match(r'^\[(-?\d+) refs, (-?\d+) blocks\]', out)
1969 if not match:
1970 self.fail(f"unexpected output: {out!a}")
1971 refs = int(match.group(1))
1972 blocks = int(match.group(2))
1973 with self.subTest(frozen_modules=flag, stmt=stmt):
1974 self.assertEqual(refs, 0, out)
1975 self.assertEqual(blocks, 0, out)
1976
1977 @unittest.skipUnless(support.Py_DEBUG,
1978 '-X presite requires a Python debug build')
1979 def test_presite(self):
1980 cmd = [sys.executable, "-I", "-X", "presite=test.reperf", "-c", "print('cmd')"]
1981 proc = subprocess.run(
1982 cmd,
1983 stdout=subprocess.PIPE,
1984 stderr=subprocess.STDOUT,
1985 text=True,
1986 )
1987 self.assertEqual(proc.returncode, 0)
1988 out = proc.stdout.strip()
1989 self.assertIn("10 times sub", out)
1990 self.assertIn("CPU seconds", out)
1991 self.assertIn("cmd", out)
1992
1993
1994 if __name__ == "__main__":
1995 unittest.main()