blob: 31dc39fd9e8efe1509e31585c91abf52f75bc04d [file] [log] [blame]
Nick Coghlan39f0bb52017-11-28 08:11:51 +10001# Run the tests in Programs/_testembed.c (tests for the CPython embedding APIs)
2from test import support
Hai Shibb0424b2020-08-04 00:47:42 +08003from test.support import import_helper
4from test.support import os_helper
Nick Coghlan39f0bb52017-11-28 08:11:51 +10005import unittest
6
7from collections import namedtuple
Victor Stinner52ad33a2019-09-25 02:10:35 +02008import contextlib
Victor Stinner7ddd56f2018-11-14 00:24:28 +01009import json
Nick Coghlan39f0bb52017-11-28 08:11:51 +100010import os
11import re
Victor Stinner52ad33a2019-09-25 02:10:35 +020012import shutil
Nick Coghlan39f0bb52017-11-28 08:11:51 +100013import subprocess
14import sys
Victor Stinner52ad33a2019-09-25 02:10:35 +020015import tempfile
Victor Stinnera6537fb2018-11-26 11:54:12 +010016import textwrap
Nick Coghlan39f0bb52017-11-28 08:11:51 +100017
18
Victor Stinner01de89c2018-11-14 17:39:45 +010019MS_WINDOWS = (os.name == 'nt')
Victor Stinner49d99f02019-09-26 04:01:49 +020020MACOS = (sys.platform == 'darwin')
Victor Stinner022be022019-05-22 23:58:50 +020021
Victor Stinnerb16b4e42019-05-17 15:20:52 +020022PYMEM_ALLOCATOR_NOT_SET = 0
23PYMEM_ALLOCATOR_DEBUG = 2
24PYMEM_ALLOCATOR_MALLOC = 3
Victor Stinner01de89c2018-11-14 17:39:45 +010025
Victor Stinner022be022019-05-22 23:58:50 +020026# _PyCoreConfig_InitCompatConfig()
27API_COMPAT = 1
28# _PyCoreConfig_InitPythonConfig()
29API_PYTHON = 2
30# _PyCoreConfig_InitIsolatedConfig()
31API_ISOLATED = 3
Victor Stinner6d1c4672019-05-20 11:02:00 +020032
Victor Stinner01de89c2018-11-14 17:39:45 +010033
Victor Stinner52ad33a2019-09-25 02:10:35 +020034def debug_build(program):
35 program = os.path.basename(program)
36 name = os.path.splitext(program)[0]
Steve Dowerdcbaa1b2020-07-06 17:32:00 +010037 return name.casefold().endswith("_d".casefold())
Victor Stinner52ad33a2019-09-25 02:10:35 +020038
39
Victor Stinnerdbdc9912019-06-18 00:11:00 +020040def remove_python_envvars():
41 env = dict(os.environ)
42 # Remove PYTHON* environment variables to get deterministic environment
43 for key in list(env):
44 if key.startswith('PYTHON'):
45 del env[key]
46 return env
47
48
Victor Stinner56b29b62018-07-26 18:57:56 +020049class EmbeddingTestsMixin:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100050 def setUp(self):
51 here = os.path.abspath(__file__)
52 basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
53 exename = "_testembed"
Victor Stinner01de89c2018-11-14 17:39:45 +010054 if MS_WINDOWS:
Victor Stinner52ad33a2019-09-25 02:10:35 +020055 ext = ("_d" if debug_build(sys.executable) else "") + ".exe"
Nick Coghlan39f0bb52017-11-28 08:11:51 +100056 exename += ext
57 exepath = os.path.dirname(sys.executable)
58 else:
59 exepath = os.path.join(basepath, "Programs")
60 self.test_exe = exe = os.path.join(exepath, exename)
61 if not os.path.exists(exe):
62 self.skipTest("%r doesn't exist" % exe)
63 # This is needed otherwise we get a fatal error:
64 # "Py_Initialize: Unable to get the locale encoding
65 # LookupError: no codec search functions registered: can't find encoding"
66 self.oldcwd = os.getcwd()
67 os.chdir(basepath)
68
69 def tearDown(self):
70 os.chdir(self.oldcwd)
71
Steve Dowere226e832019-07-01 16:03:53 -070072 def run_embedded_interpreter(self, *args, env=None,
Victor Stinner52ad33a2019-09-25 02:10:35 +020073 timeout=None, returncode=0, input=None,
74 cwd=None):
Nick Coghlan39f0bb52017-11-28 08:11:51 +100075 """Runs a test in the embedded interpreter"""
76 cmd = [self.test_exe]
77 cmd.extend(args)
Victor Stinner01de89c2018-11-14 17:39:45 +010078 if env is not None and MS_WINDOWS:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100079 # Windows requires at least the SYSTEMROOT environment variable to
80 # start Python.
81 env = env.copy()
82 env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
83
84 p = subprocess.Popen(cmd,
85 stdout=subprocess.PIPE,
86 stderr=subprocess.PIPE,
87 universal_newlines=True,
Victor Stinner52ad33a2019-09-25 02:10:35 +020088 env=env,
89 cwd=cwd)
Victor Stinner2f549082019-03-29 15:13:46 +010090 try:
Steve Dowere226e832019-07-01 16:03:53 -070091 (out, err) = p.communicate(input=input, timeout=timeout)
Victor Stinner2f549082019-03-29 15:13:46 +010092 except:
93 p.terminate()
94 p.wait()
95 raise
Steve Dowere226e832019-07-01 16:03:53 -070096 if p.returncode != returncode and support.verbose:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100097 print(f"--- {cmd} failed ---")
98 print(f"stdout:\n{out}")
Nick Coghlanbc77eff2018-03-25 20:44:30 +100099 print(f"stderr:\n{err}")
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000100 print(f"------")
101
Steve Dowere226e832019-07-01 16:03:53 -0700102 self.assertEqual(p.returncode, returncode,
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000103 "bad returncode %d, stderr is %r" %
104 (p.returncode, err))
105 return out, err
106
107 def run_repeated_init_and_subinterpreters(self):
Victor Stinner5edcf262019-05-23 00:57:57 +0200108 out, err = self.run_embedded_interpreter("test_repeated_init_and_subinterpreters")
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000109 self.assertEqual(err, "")
110
111 # The output from _testembed looks like this:
112 # --- Pass 0 ---
113 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
114 # interp 1 <0x1d4f690>, thread state <0x1d35350>: id(modules) = 139650431165784
115 # interp 2 <0x1d5a690>, thread state <0x1d99ed0>: id(modules) = 139650413140368
116 # interp 3 <0x1d4f690>, thread state <0x1dc3340>: id(modules) = 139650412862200
117 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
118 # --- Pass 1 ---
119 # ...
120
121 interp_pat = (r"^interp (\d+) <(0x[\dA-F]+)>, "
122 r"thread state <(0x[\dA-F]+)>: "
123 r"id\(modules\) = ([\d]+)$")
124 Interp = namedtuple("Interp", "id interp tstate modules")
125
126 numloops = 0
127 current_run = []
128 for line in out.splitlines():
129 if line == "--- Pass {} ---".format(numloops):
130 self.assertEqual(len(current_run), 0)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000131 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000132 print(line)
133 numloops += 1
134 continue
135
136 self.assertLess(len(current_run), 5)
137 match = re.match(interp_pat, line)
138 if match is None:
139 self.assertRegex(line, interp_pat)
140
141 # Parse the line from the loop. The first line is the main
142 # interpreter and the 3 afterward are subinterpreters.
143 interp = Interp(*match.groups())
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000144 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000145 print(interp)
146 self.assertTrue(interp.interp)
147 self.assertTrue(interp.tstate)
148 self.assertTrue(interp.modules)
149 current_run.append(interp)
150
151 # The last line in the loop should be the same as the first.
152 if len(current_run) == 5:
153 main = current_run[0]
154 self.assertEqual(interp, main)
155 yield current_run
156 current_run = []
157
Victor Stinner56b29b62018-07-26 18:57:56 +0200158
159class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase):
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000160 def test_subinterps_main(self):
161 for run in self.run_repeated_init_and_subinterpreters():
162 main = run[0]
163
164 self.assertEqual(main.id, '0')
165
166 def test_subinterps_different_ids(self):
167 for run in self.run_repeated_init_and_subinterpreters():
168 main, *subs, _ = run
169
170 mainid = int(main.id)
171 for i, sub in enumerate(subs):
172 self.assertEqual(sub.id, str(mainid + i + 1))
173
174 def test_subinterps_distinct_state(self):
175 for run in self.run_repeated_init_and_subinterpreters():
176 main, *subs, _ = run
177
178 if '0x0' in main:
179 # XXX Fix on Windows (and other platforms): something
180 # is going on with the pointers in Programs/_testembed.c.
181 # interp.interp is 0x0 and interp.modules is the same
182 # between interpreters.
183 raise unittest.SkipTest('platform prints pointers as 0x0')
184
185 for sub in subs:
186 # A new subinterpreter may have the same
187 # PyInterpreterState pointer as a previous one if
188 # the earlier one has already been destroyed. So
189 # we compare with the main interpreter. The same
190 # applies to tstate.
191 self.assertNotEqual(sub.interp, main.interp)
192 self.assertNotEqual(sub.tstate, main.tstate)
193 self.assertNotEqual(sub.modules, main.modules)
194
195 def test_forced_io_encoding(self):
196 # Checks forced configuration of embedded interpreter IO streams
197 env = dict(os.environ, PYTHONIOENCODING="utf-8:surrogateescape")
Victor Stinner5edcf262019-05-23 00:57:57 +0200198 out, err = self.run_embedded_interpreter("test_forced_io_encoding", env=env)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000199 if support.verbose > 1:
200 print()
201 print(out)
202 print(err)
203 expected_stream_encoding = "utf-8"
204 expected_errors = "surrogateescape"
205 expected_output = '\n'.join([
206 "--- Use defaults ---",
207 "Expected encoding: default",
208 "Expected errors: default",
209 "stdin: {in_encoding}:{errors}",
210 "stdout: {out_encoding}:{errors}",
211 "stderr: {out_encoding}:backslashreplace",
212 "--- Set errors only ---",
213 "Expected encoding: default",
214 "Expected errors: ignore",
215 "stdin: {in_encoding}:ignore",
216 "stdout: {out_encoding}:ignore",
217 "stderr: {out_encoding}:backslashreplace",
218 "--- Set encoding only ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200219 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000220 "Expected errors: default",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200221 "stdin: iso8859-1:{errors}",
222 "stdout: iso8859-1:{errors}",
223 "stderr: iso8859-1:backslashreplace",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000224 "--- Set encoding and errors ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200225 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000226 "Expected errors: replace",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200227 "stdin: iso8859-1:replace",
228 "stdout: iso8859-1:replace",
229 "stderr: iso8859-1:backslashreplace"])
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000230 expected_output = expected_output.format(
231 in_encoding=expected_stream_encoding,
232 out_encoding=expected_stream_encoding,
233 errors=expected_errors)
234 # This is useful if we ever trip over odd platform behaviour
235 self.maxDiff = None
236 self.assertEqual(out.strip(), expected_output)
237
238 def test_pre_initialization_api(self):
239 """
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000240 Checks some key parts of the C-API that need to work before the runtine
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000241 is initialized (via Py_Initialize()).
242 """
243 env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path))
Victor Stinner5edcf262019-05-23 00:57:57 +0200244 out, err = self.run_embedded_interpreter("test_pre_initialization_api", env=env)
Victor Stinner01de89c2018-11-14 17:39:45 +0100245 if MS_WINDOWS:
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000246 expected_path = self.test_exe
247 else:
248 expected_path = os.path.join(os.getcwd(), "spam")
249 expected_output = f"sys.executable: {expected_path}\n"
250 self.assertIn(expected_output, out)
251 self.assertEqual(err, '')
252
253 def test_pre_initialization_sys_options(self):
254 """
255 Checks that sys.warnoptions and sys._xoptions can be set before the
256 runtime is initialized (otherwise they won't be effective).
257 """
Victor Stinnerdbdc9912019-06-18 00:11:00 +0200258 env = remove_python_envvars()
259 env['PYTHONPATH'] = os.pathsep.join(sys.path)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000260 out, err = self.run_embedded_interpreter(
Victor Stinner5edcf262019-05-23 00:57:57 +0200261 "test_pre_initialization_sys_options", env=env)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000262 expected_output = (
263 "sys.warnoptions: ['once', 'module', 'default']\n"
264 "sys._xoptions: {'not_an_option': '1', 'also_not_an_option': '2'}\n"
265 "warnings.filters[:3]: ['default', 'module', 'once']\n"
266 )
267 self.assertIn(expected_output, out)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000268 self.assertEqual(err, '')
269
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100270 def test_bpo20891(self):
271 """
Victor Stinner3225b9f2020-03-09 20:56:57 +0100272 bpo-20891: Calling PyGILState_Ensure in a non-Python thread must not
273 crash.
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100274 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200275 out, err = self.run_embedded_interpreter("test_bpo20891")
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100276 self.assertEqual(out, '')
277 self.assertEqual(err, '')
278
Victor Stinner209abf72018-06-22 19:14:51 +0200279 def test_initialize_twice(self):
280 """
281 bpo-33932: Calling Py_Initialize() twice should do nothing (and not
282 crash!).
283 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200284 out, err = self.run_embedded_interpreter("test_initialize_twice")
Victor Stinner209abf72018-06-22 19:14:51 +0200285 self.assertEqual(out, '')
286 self.assertEqual(err, '')
287
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200288 def test_initialize_pymain(self):
289 """
290 bpo-34008: Calling Py_Main() after Py_Initialize() must not fail.
291 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200292 out, err = self.run_embedded_interpreter("test_initialize_pymain")
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200293 self.assertEqual(out.rstrip(), "Py_Main() after Py_Initialize: sys.argv=['-c', 'arg2']")
294 self.assertEqual(err, '')
295
Victor Stinner2f549082019-03-29 15:13:46 +0100296 def test_run_main(self):
Victor Stinner5edcf262019-05-23 00:57:57 +0200297 out, err = self.run_embedded_interpreter("test_run_main")
Victor Stinner331a6a52019-05-27 16:39:22 +0200298 self.assertEqual(out.rstrip(), "Py_RunMain(): sys.argv=['-c', 'arg2']")
Victor Stinner2f549082019-03-29 15:13:46 +0100299 self.assertEqual(err, '')
300
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000301
Victor Stinner56b29b62018-07-26 18:57:56 +0200302class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
303 maxDiff = 4096
Victor Stinner01de89c2018-11-14 17:39:45 +0100304 UTF8_MODE_ERRORS = ('surrogatepass' if MS_WINDOWS else 'surrogateescape')
305
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200306 # Marker to read the default configuration: get_default_config()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100307 GET_DEFAULT_CONFIG = object()
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200308
309 # Marker to ignore a configuration parameter
310 IGNORE_CONFIG = object()
311
Victor Stinner022be022019-05-22 23:58:50 +0200312 PRE_CONFIG_COMPAT = {
Victor Stinner20e1e252019-05-23 04:12:27 +0200313 '_config_init': API_COMPAT,
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200314 'allocator': PYMEM_ALLOCATOR_NOT_SET,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200315 'parse_argv': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200316 'configure_locale': 1,
Victor Stinner1075d162019-03-25 23:19:57 +0100317 'coerce_c_locale': 0,
318 'coerce_c_locale_warn': 0,
Victor Stinner1075d162019-03-25 23:19:57 +0100319 'utf8_mode': 0,
320 }
Victor Stinner6d1c4672019-05-20 11:02:00 +0200321 if MS_WINDOWS:
Victor Stinner022be022019-05-22 23:58:50 +0200322 PRE_CONFIG_COMPAT.update({
Victor Stinner6d1c4672019-05-20 11:02:00 +0200323 'legacy_windows_fs_encoding': 0,
324 })
Victor Stinner022be022019-05-22 23:58:50 +0200325 PRE_CONFIG_PYTHON = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200326 _config_init=API_PYTHON,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200327 parse_argv=1,
Victor Stinner425717f2019-05-20 16:38:48 +0200328 coerce_c_locale=GET_DEFAULT_CONFIG,
329 utf8_mode=GET_DEFAULT_CONFIG,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200330 )
Victor Stinner022be022019-05-22 23:58:50 +0200331 PRE_CONFIG_ISOLATED = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200332 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200333 configure_locale=0,
334 isolated=1,
335 use_environment=0,
336 utf8_mode=0,
337 dev_mode=0,
Victor Stinner425717f2019-05-20 16:38:48 +0200338 coerce_c_locale=0,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200339 )
Victor Stinnerbab0db62019-05-18 03:21:27 +0200340
Victor Stinner20004952019-03-26 02:31:11 +0100341 COPY_PRE_CONFIG = [
342 'dev_mode',
343 'isolated',
344 'use_environment',
345 ]
346
Victor Stinner331a6a52019-05-27 16:39:22 +0200347 CONFIG_COMPAT = {
Victor Stinner022be022019-05-22 23:58:50 +0200348 '_config_init': API_COMPAT,
Victor Stinner20004952019-03-26 02:31:11 +0100349 'isolated': 0,
350 'use_environment': 1,
351 'dev_mode': 0,
352
Victor Stinner56b29b62018-07-26 18:57:56 +0200353 'install_signal_handlers': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200354 'use_hash_seed': 0,
355 'hash_seed': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200356 'faulthandler': 0,
357 'tracemalloc': 0,
358 'import_time': 0,
359 'show_ref_count': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200360 'dump_refs': 0,
361 'malloc_stats': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200362
Victor Stinnera6537fb2018-11-26 11:54:12 +0100363 'filesystem_encoding': GET_DEFAULT_CONFIG,
364 'filesystem_errors': GET_DEFAULT_CONFIG,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200365
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100366 'pycache_prefix': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200367 'program_name': GET_DEFAULT_CONFIG,
Victor Stinnercab5d072019-05-17 19:01:14 +0200368 'parse_argv': 0,
Victor Stinner62599762019-03-15 16:03:23 +0100369 'argv': [""],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200370 'orig_argv': [],
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100371
372 'xoptions': [],
373 'warnoptions': [],
Victor Stinner56b29b62018-07-26 18:57:56 +0200374
Victor Stinner331a6a52019-05-27 16:39:22 +0200375 'pythonpath_env': None,
Victor Stinner01de89c2018-11-14 17:39:45 +0100376 'home': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200377 'executable': GET_DEFAULT_CONFIG,
Steve Dower9048c492019-06-29 10:34:11 -0700378 'base_executable': GET_DEFAULT_CONFIG,
Victor Stinnera6537fb2018-11-26 11:54:12 +0100379
380 'prefix': GET_DEFAULT_CONFIG,
381 'base_prefix': GET_DEFAULT_CONFIG,
382 'exec_prefix': GET_DEFAULT_CONFIG,
383 'base_exec_prefix': GET_DEFAULT_CONFIG,
Victor Stinner5eb8b072019-05-15 02:12:48 +0200384 'module_search_paths': GET_DEFAULT_CONFIG,
Sandro Mani8f023a22020-06-08 17:28:11 +0200385 'platlibdir': sys.platlibdir,
Victor Stinner01de89c2018-11-14 17:39:45 +0100386
Victor Stinner56b29b62018-07-26 18:57:56 +0200387 'site_import': 1,
388 'bytes_warning': 0,
389 'inspect': 0,
390 'interactive': 0,
391 'optimization_level': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200392 'parser_debug': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200393 'write_bytecode': 1,
394 'verbose': 0,
395 'quiet': 0,
396 'user_site_directory': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200397 'configure_c_stdio': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200398 'buffered_stdio': 1,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200399
Victor Stinnera6537fb2018-11-26 11:54:12 +0100400 'stdio_encoding': GET_DEFAULT_CONFIG,
401 'stdio_errors': GET_DEFAULT_CONFIG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200402
Victor Stinner62be7632019-03-01 13:10:14 +0100403 'skip_source_first_line': 0,
404 'run_command': None,
405 'run_module': None,
406 'run_filename': None,
407
Victor Stinner56b29b62018-07-26 18:57:56 +0200408 '_install_importlib': 1,
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400409 'check_hash_pycs_mode': 'default',
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200410 'pathconfig_warnings': 1,
411 '_init_main': 1,
Victor Stinner252346a2020-05-01 11:33:44 +0200412 '_isolated_interpreter': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200413 }
Victor Stinner01de89c2018-11-14 17:39:45 +0100414 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200415 CONFIG_COMPAT.update({
Victor Stinner01de89c2018-11-14 17:39:45 +0100416 'legacy_windows_stdio': 0,
417 })
418
Victor Stinner331a6a52019-05-27 16:39:22 +0200419 CONFIG_PYTHON = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200420 _config_init=API_PYTHON,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200421 configure_c_stdio=1,
422 parse_argv=1,
423 )
Victor Stinner331a6a52019-05-27 16:39:22 +0200424 CONFIG_ISOLATED = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200425 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200426 isolated=1,
427 use_environment=0,
428 user_site_directory=0,
429 dev_mode=0,
430 install_signal_handlers=0,
431 use_hash_seed=0,
432 faulthandler=0,
433 tracemalloc=0,
434 pathconfig_warnings=0,
435 )
436 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200437 CONFIG_ISOLATED['legacy_windows_stdio'] = 0
Victor Stinnerbab0db62019-05-18 03:21:27 +0200438
Victor Stinner01de89c2018-11-14 17:39:45 +0100439 # global config
440 DEFAULT_GLOBAL_CONFIG = {
441 'Py_HasFileSystemDefaultEncoding': 0,
442 'Py_HashRandomizationFlag': 1,
443 '_Py_HasFileSystemDefaultEncodeErrors': 0,
444 }
Victor Stinner1075d162019-03-25 23:19:57 +0100445 COPY_GLOBAL_PRE_CONFIG = [
Victor Stinner1075d162019-03-25 23:19:57 +0100446 ('Py_UTF8Mode', 'utf8_mode'),
447 ]
Victor Stinner01de89c2018-11-14 17:39:45 +0100448 COPY_GLOBAL_CONFIG = [
449 # Copy core config to global config for expected values
450 # True means that the core config value is inverted (0 => 1 and 1 => 0)
451 ('Py_BytesWarningFlag', 'bytes_warning'),
452 ('Py_DebugFlag', 'parser_debug'),
453 ('Py_DontWriteBytecodeFlag', 'write_bytecode', True),
454 ('Py_FileSystemDefaultEncodeErrors', 'filesystem_errors'),
455 ('Py_FileSystemDefaultEncoding', 'filesystem_encoding'),
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200456 ('Py_FrozenFlag', 'pathconfig_warnings', True),
Victor Stinner20004952019-03-26 02:31:11 +0100457 ('Py_IgnoreEnvironmentFlag', 'use_environment', True),
Victor Stinner01de89c2018-11-14 17:39:45 +0100458 ('Py_InspectFlag', 'inspect'),
459 ('Py_InteractiveFlag', 'interactive'),
Victor Stinner20004952019-03-26 02:31:11 +0100460 ('Py_IsolatedFlag', 'isolated'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100461 ('Py_NoSiteFlag', 'site_import', True),
462 ('Py_NoUserSiteDirectory', 'user_site_directory', True),
463 ('Py_OptimizeFlag', 'optimization_level'),
464 ('Py_QuietFlag', 'quiet'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100465 ('Py_UnbufferedStdioFlag', 'buffered_stdio', True),
466 ('Py_VerboseFlag', 'verbose'),
467 ]
468 if MS_WINDOWS:
Victor Stinner1075d162019-03-25 23:19:57 +0100469 COPY_GLOBAL_PRE_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100470 ('Py_LegacyWindowsFSEncodingFlag', 'legacy_windows_fs_encoding'),
Victor Stinner1075d162019-03-25 23:19:57 +0100471 ))
472 COPY_GLOBAL_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100473 ('Py_LegacyWindowsStdioFlag', 'legacy_windows_stdio'),
474 ))
Victor Stinner56b29b62018-07-26 18:57:56 +0200475
Victor Stinner8f427482020-07-08 00:20:37 +0200476 # path config
477 if MS_WINDOWS:
478 PATH_CONFIG = {
479 'isolated': -1,
480 'site_import': -1,
481 'python3_dll': GET_DEFAULT_CONFIG,
482 }
483 else:
484 PATH_CONFIG = {}
485 # other keys are copied by COPY_PATH_CONFIG
486
487 COPY_PATH_CONFIG = [
488 # Copy core config to global config for expected values
489 'prefix',
490 'exec_prefix',
491 'program_name',
492 'home',
493 # program_full_path and module_search_path are copied indirectly from
494 # the core configuration in check_path_config().
495 ]
496 if MS_WINDOWS:
497 COPY_PATH_CONFIG.extend((
498 'base_executable',
499 ))
500
Victor Stinner425717f2019-05-20 16:38:48 +0200501 EXPECTED_CONFIG = None
502
Victor Stinner52ad33a2019-09-25 02:10:35 +0200503 @classmethod
504 def tearDownClass(cls):
505 # clear cache
506 cls.EXPECTED_CONFIG = None
507
Victor Stinner01de89c2018-11-14 17:39:45 +0100508 def main_xoptions(self, xoptions_list):
509 xoptions = {}
510 for opt in xoptions_list:
511 if '=' in opt:
512 key, value = opt.split('=', 1)
513 xoptions[key] = value
514 else:
515 xoptions[opt] = True
516 return xoptions
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200517
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200518 def _get_expected_config_impl(self):
519 env = remove_python_envvars()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100520 code = textwrap.dedent('''
521 import json
Victor Stinnera6537fb2018-11-26 11:54:12 +0100522 import sys
Victor Stinner5eb8b072019-05-15 02:12:48 +0200523 import _testinternalcapi
Victor Stinnera6537fb2018-11-26 11:54:12 +0100524
Victor Stinner5eb8b072019-05-15 02:12:48 +0200525 configs = _testinternalcapi.get_configs()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100526
Victor Stinner425717f2019-05-20 16:38:48 +0200527 data = json.dumps(configs)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100528 data = data.encode('utf-8')
529 sys.stdout.buffer.write(data)
530 sys.stdout.buffer.flush()
531 ''')
532
533 # Use -S to not import the site module: get the proper configuration
534 # when test_embed is run from a venv (bpo-35313)
Victor Stinner5eb8b072019-05-15 02:12:48 +0200535 args = [sys.executable, '-S', '-c', code]
Victor Stinnera6537fb2018-11-26 11:54:12 +0100536 proc = subprocess.run(args, env=env,
537 stdout=subprocess.PIPE,
Victor Stinner52ad33a2019-09-25 02:10:35 +0200538 stderr=subprocess.PIPE)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100539 if proc.returncode:
540 raise Exception(f"failed to get the default config: "
541 f"stdout={proc.stdout!r} stderr={proc.stderr!r}")
542 stdout = proc.stdout.decode('utf-8')
Victor Stinner52ad33a2019-09-25 02:10:35 +0200543 # ignore stderr
Victor Stinner4631da12019-05-02 15:30:21 -0400544 try:
Victor Stinner425717f2019-05-20 16:38:48 +0200545 return json.loads(stdout)
Victor Stinner4631da12019-05-02 15:30:21 -0400546 except json.JSONDecodeError:
547 self.fail(f"fail to decode stdout: {stdout!r}")
Victor Stinnera6537fb2018-11-26 11:54:12 +0100548
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200549 def _get_expected_config(self):
550 cls = InitConfigTests
551 if cls.EXPECTED_CONFIG is None:
552 cls.EXPECTED_CONFIG = self._get_expected_config_impl()
553
554 # get a copy
Victor Stinner52ad33a2019-09-25 02:10:35 +0200555 configs = {}
556 for config_key, config_value in cls.EXPECTED_CONFIG.items():
557 config = {}
558 for key, value in config_value.items():
559 if isinstance(value, list):
560 value = value.copy()
561 config[key] = value
562 configs[config_key] = config
563 return configs
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200564
Victor Stinner8f427482020-07-08 00:20:37 +0200565 def get_expected_config(self, expected_preconfig, expected,
566 expected_pathconfig, env, api,
Victor Stinner3842f292019-08-23 16:57:54 +0100567 modify_path_cb=None):
Victor Stinner425717f2019-05-20 16:38:48 +0200568 cls = self.__class__
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200569 configs = self._get_expected_config()
Victor Stinner425717f2019-05-20 16:38:48 +0200570
571 pre_config = configs['pre_config']
572 for key, value in expected_preconfig.items():
573 if value is self.GET_DEFAULT_CONFIG:
574 expected_preconfig[key] = pre_config[key]
575
Victor Stinner8f427482020-07-08 00:20:37 +0200576 path_config = configs['path_config']
577 for key, value in expected_pathconfig.items():
578 if value is self.GET_DEFAULT_CONFIG:
579 expected_pathconfig[key] = path_config[key]
580
Victor Stinner022be022019-05-22 23:58:50 +0200581 if not expected_preconfig['configure_locale'] or api == API_COMPAT:
Victor Stinner425717f2019-05-20 16:38:48 +0200582 # there is no easy way to get the locale encoding before
583 # setlocale(LC_CTYPE, "") is called: don't test encodings
584 for key in ('filesystem_encoding', 'filesystem_errors',
585 'stdio_encoding', 'stdio_errors'):
586 expected[key] = self.IGNORE_CONFIG
587
588 if not expected_preconfig['configure_locale']:
589 # UTF-8 Mode depends on the locale. There is no easy way
590 # to guess if UTF-8 Mode will be enabled or not if the locale
591 # is not configured.
592 expected_preconfig['utf8_mode'] = self.IGNORE_CONFIG
593
594 if expected_preconfig['utf8_mode'] == 1:
595 if expected['filesystem_encoding'] is self.GET_DEFAULT_CONFIG:
596 expected['filesystem_encoding'] = 'utf-8'
597 if expected['filesystem_errors'] is self.GET_DEFAULT_CONFIG:
598 expected['filesystem_errors'] = self.UTF8_MODE_ERRORS
599 if expected['stdio_encoding'] is self.GET_DEFAULT_CONFIG:
600 expected['stdio_encoding'] = 'utf-8'
601 if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG:
602 expected['stdio_errors'] = 'surrogateescape'
603
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100604 if MS_WINDOWS:
Steve Dower9048c492019-06-29 10:34:11 -0700605 default_executable = self.test_exe
606 elif expected['program_name'] is not self.GET_DEFAULT_CONFIG:
607 default_executable = os.path.abspath(expected['program_name'])
608 else:
609 default_executable = os.path.join(os.getcwd(), '_testembed')
Victor Stinner91c99872019-05-14 22:01:51 +0200610 if expected['executable'] is self.GET_DEFAULT_CONFIG:
Steve Dower9048c492019-06-29 10:34:11 -0700611 expected['executable'] = default_executable
612 if expected['base_executable'] is self.GET_DEFAULT_CONFIG:
613 expected['base_executable'] = default_executable
Victor Stinner91c99872019-05-14 22:01:51 +0200614 if expected['program_name'] is self.GET_DEFAULT_CONFIG:
615 expected['program_name'] = './_testembed'
616
Victor Stinner331a6a52019-05-27 16:39:22 +0200617 config = configs['config']
Victor Stinnera6537fb2018-11-26 11:54:12 +0100618 for key, value in expected.items():
619 if value is self.GET_DEFAULT_CONFIG:
Victor Stinner331a6a52019-05-27 16:39:22 +0200620 expected[key] = config[key]
Victor Stinner5eb8b072019-05-15 02:12:48 +0200621
Sandro Mani8f023a22020-06-08 17:28:11 +0200622 if expected['module_search_paths'] is not self.IGNORE_CONFIG:
623 pythonpath_env = expected['pythonpath_env']
624 if pythonpath_env is not None:
625 paths = pythonpath_env.split(os.path.pathsep)
626 expected['module_search_paths'] = [*paths, *expected['module_search_paths']]
627 if modify_path_cb is not None:
628 expected['module_search_paths'] = expected['module_search_paths'].copy()
629 modify_path_cb(expected['module_search_paths'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200630
Victor Stinner425717f2019-05-20 16:38:48 +0200631 for key in self.COPY_PRE_CONFIG:
632 if key not in expected_preconfig:
633 expected_preconfig[key] = expected[key]
Victor Stinner01de89c2018-11-14 17:39:45 +0100634
Victor Stinner331a6a52019-05-27 16:39:22 +0200635 def check_pre_config(self, configs, expected):
636 pre_config = dict(configs['pre_config'])
Victor Stinner425717f2019-05-20 16:38:48 +0200637 for key, value in list(expected.items()):
638 if value is self.IGNORE_CONFIG:
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100639 pre_config.pop(key, None)
Victor Stinner425717f2019-05-20 16:38:48 +0200640 del expected[key]
641 self.assertEqual(pre_config, expected)
Victor Stinner1075d162019-03-25 23:19:57 +0100642
Victor Stinner331a6a52019-05-27 16:39:22 +0200643 def check_config(self, configs, expected):
644 config = dict(configs['config'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200645 for key, value in list(expected.items()):
646 if value is self.IGNORE_CONFIG:
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100647 config.pop(key, None)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200648 del expected[key]
Victor Stinner331a6a52019-05-27 16:39:22 +0200649 self.assertEqual(config, expected)
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200650
Victor Stinner331a6a52019-05-27 16:39:22 +0200651 def check_global_config(self, configs):
652 pre_config = configs['pre_config']
653 config = configs['config']
Victor Stinner00b137c2018-11-13 19:59:26 +0100654
Victor Stinnera6537fb2018-11-26 11:54:12 +0100655 expected = dict(self.DEFAULT_GLOBAL_CONFIG)
Victor Stinner01de89c2018-11-14 17:39:45 +0100656 for item in self.COPY_GLOBAL_CONFIG:
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100657 if len(item) == 3:
658 global_key, core_key, opposite = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200659 expected[global_key] = 0 if config[core_key] else 1
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100660 else:
661 global_key, core_key = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200662 expected[global_key] = config[core_key]
Victor Stinner1075d162019-03-25 23:19:57 +0100663 for item in self.COPY_GLOBAL_PRE_CONFIG:
664 if len(item) == 3:
665 global_key, core_key, opposite = item
666 expected[global_key] = 0 if pre_config[core_key] else 1
667 else:
668 global_key, core_key = item
669 expected[global_key] = pre_config[core_key]
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100670
Victor Stinner331a6a52019-05-27 16:39:22 +0200671 self.assertEqual(configs['global_config'], expected)
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100672
Victor Stinner8f427482020-07-08 00:20:37 +0200673 def check_path_config(self, configs, expected):
674 config = configs['config']
675
676 for key in self.COPY_PATH_CONFIG:
677 expected[key] = config[key]
678 expected['module_search_path'] = os.path.pathsep.join(config['module_search_paths'])
679 expected['program_full_path'] = config['executable']
680
681 self.assertEqual(configs['path_config'], expected)
682
Victor Stinner331a6a52019-05-27 16:39:22 +0200683 def check_all_configs(self, testname, expected_config=None,
Victor Stinner8f427482020-07-08 00:20:37 +0200684 expected_preconfig=None, expected_pathconfig=None,
685 modify_path_cb=None,
Victor Stinner8bf39b62019-09-26 02:22:35 +0200686 stderr=None, *, api, preconfig_api=None,
687 env=None, ignore_stderr=False, cwd=None):
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200688 new_env = remove_python_envvars()
689 if env is not None:
690 new_env.update(env)
691 env = new_env
Victor Stinner01de89c2018-11-14 17:39:45 +0100692
Victor Stinner8bf39b62019-09-26 02:22:35 +0200693 if preconfig_api is None:
694 preconfig_api = api
695 if preconfig_api == API_ISOLATED:
Victor Stinner022be022019-05-22 23:58:50 +0200696 default_preconfig = self.PRE_CONFIG_ISOLATED
Victor Stinner8bf39b62019-09-26 02:22:35 +0200697 elif preconfig_api == API_PYTHON:
Victor Stinner022be022019-05-22 23:58:50 +0200698 default_preconfig = self.PRE_CONFIG_PYTHON
Victor Stinnerbab0db62019-05-18 03:21:27 +0200699 else:
Victor Stinner022be022019-05-22 23:58:50 +0200700 default_preconfig = self.PRE_CONFIG_COMPAT
Victor Stinnerbab0db62019-05-18 03:21:27 +0200701 if expected_preconfig is None:
702 expected_preconfig = {}
703 expected_preconfig = dict(default_preconfig, **expected_preconfig)
Victor Stinner8f427482020-07-08 00:20:37 +0200704
Victor Stinnerbab0db62019-05-18 03:21:27 +0200705 if expected_config is None:
706 expected_config = {}
Victor Stinner425717f2019-05-20 16:38:48 +0200707
Victor Stinner8f427482020-07-08 00:20:37 +0200708 if expected_pathconfig is None:
709 expected_pathconfig = {}
710 expected_pathconfig = dict(self.PATH_CONFIG, **expected_pathconfig)
711
Victor Stinner022be022019-05-22 23:58:50 +0200712 if api == API_PYTHON:
Victor Stinner331a6a52019-05-27 16:39:22 +0200713 default_config = self.CONFIG_PYTHON
Victor Stinner022be022019-05-22 23:58:50 +0200714 elif api == API_ISOLATED:
Victor Stinner331a6a52019-05-27 16:39:22 +0200715 default_config = self.CONFIG_ISOLATED
Victor Stinner425717f2019-05-20 16:38:48 +0200716 else:
Victor Stinner331a6a52019-05-27 16:39:22 +0200717 default_config = self.CONFIG_COMPAT
Victor Stinner425717f2019-05-20 16:38:48 +0200718 expected_config = dict(default_config, **expected_config)
Victor Stinner425717f2019-05-20 16:38:48 +0200719
720 self.get_expected_config(expected_preconfig,
Victor Stinner8f427482020-07-08 00:20:37 +0200721 expected_config,
722 expected_pathconfig,
723 env,
Victor Stinner3842f292019-08-23 16:57:54 +0100724 api, modify_path_cb)
Victor Stinner1075d162019-03-25 23:19:57 +0100725
Victor Stinner52ad33a2019-09-25 02:10:35 +0200726 out, err = self.run_embedded_interpreter(testname,
727 env=env, cwd=cwd)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200728 if stderr is None and not expected_config['verbose']:
729 stderr = ""
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200730 if stderr is not None and not ignore_stderr:
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200731 self.assertEqual(err.rstrip(), stderr)
732 try:
Victor Stinner331a6a52019-05-27 16:39:22 +0200733 configs = json.loads(out)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200734 except json.JSONDecodeError:
735 self.fail(f"fail to decode stdout: {out!r}")
736
Victor Stinner331a6a52019-05-27 16:39:22 +0200737 self.check_pre_config(configs, expected_preconfig)
738 self.check_config(configs, expected_config)
739 self.check_global_config(configs)
Victor Stinner8f427482020-07-08 00:20:37 +0200740 self.check_path_config(configs, expected_pathconfig)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100741 return configs
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100742
Victor Stinner56b29b62018-07-26 18:57:56 +0200743 def test_init_default_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200744 self.check_all_configs("test_init_initialize_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200745
746 def test_preinit_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200747 self.check_all_configs("test_preinit_compat_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200748
749 def test_init_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200750 self.check_all_configs("test_init_compat_config", api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200751
752 def test_init_global_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100753 preconfig = {
754 'utf8_mode': 1,
755 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200756 config = {
757 'program_name': './globalvar',
758 'site_import': 0,
759 'bytes_warning': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100760 'warnoptions': ['default::BytesWarning'],
Victor Stinner56b29b62018-07-26 18:57:56 +0200761 'inspect': 1,
762 'interactive': 1,
763 'optimization_level': 2,
764 'write_bytecode': 0,
765 'verbose': 1,
766 'quiet': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200767 'buffered_stdio': 0,
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200768
Victor Stinner56b29b62018-07-26 18:57:56 +0200769 'user_site_directory': 0,
Victor Stinner54b43bb2019-05-16 18:30:15 +0200770 'pathconfig_warnings': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200771 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200772 self.check_all_configs("test_init_global_config", config, preconfig,
773 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200774
775 def test_init_from_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100776 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200777 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner1075d162019-03-25 23:19:57 +0100778 'utf8_mode': 1,
779 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200780 config = {
781 'install_signal_handlers': 0,
782 'use_hash_seed': 1,
783 'hash_seed': 123,
Victor Stinner56b29b62018-07-26 18:57:56 +0200784 'tracemalloc': 2,
785 'import_time': 1,
786 'show_ref_count': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200787 'malloc_stats': 1,
788
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200789 'stdio_encoding': 'iso8859-1',
790 'stdio_errors': 'replace',
Victor Stinner56b29b62018-07-26 18:57:56 +0200791
792 'pycache_prefix': 'conf_pycache_prefix',
793 'program_name': './conf_program_name',
Victor Stinnere81f6e62020-06-08 18:12:59 +0200794 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200795 'orig_argv': ['python3',
796 '-W', 'cmdline_warnoption',
797 '-X', 'cmdline_xoption',
798 '-c', 'pass',
799 'arg2'],
Victor Stinnercab5d072019-05-17 19:01:14 +0200800 'parse_argv': 1,
Victor Stinner67310022019-07-01 19:52:45 +0200801 'xoptions': [
802 'config_xoption1=3',
803 'config_xoption2=',
804 'config_xoption3',
805 'cmdline_xoption',
806 ],
807 'warnoptions': [
Victor Stinner67310022019-07-01 19:52:45 +0200808 'cmdline_warnoption',
809 'default::BytesWarning',
Victor Stinnerfb4ae152019-09-30 01:40:17 +0200810 'config_warnoption',
Victor Stinner67310022019-07-01 19:52:45 +0200811 ],
Victor Stinner2f549082019-03-29 15:13:46 +0100812 'run_command': 'pass\n',
Victor Stinner56b29b62018-07-26 18:57:56 +0200813
814 'site_import': 0,
815 'bytes_warning': 1,
816 'inspect': 1,
817 'interactive': 1,
818 'optimization_level': 2,
819 'write_bytecode': 0,
820 'verbose': 1,
821 'quiet': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200822 'configure_c_stdio': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200823 'buffered_stdio': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200824 'user_site_directory': 0,
825 'faulthandler': 1,
Sandro Mani8f023a22020-06-08 17:28:11 +0200826 'platlibdir': 'my_platlibdir',
827 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinnerb75d7e22018-08-01 02:13:04 +0200828
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400829 'check_hash_pycs_mode': 'always',
Victor Stinner54b43bb2019-05-16 18:30:15 +0200830 'pathconfig_warnings': 0,
Victor Stinner252346a2020-05-01 11:33:44 +0200831
832 '_isolated_interpreter': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200833 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200834 self.check_all_configs("test_init_from_config", config, preconfig,
835 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200836
Victor Stinner20e1e252019-05-23 04:12:27 +0200837 def test_init_compat_env(self):
838 preconfig = {
839 'allocator': PYMEM_ALLOCATOR_MALLOC,
840 }
841 config = {
842 'use_hash_seed': 1,
843 'hash_seed': 42,
844 'tracemalloc': 2,
845 'import_time': 1,
846 'malloc_stats': 1,
847 'inspect': 1,
848 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200849 'pythonpath_env': '/my/path',
Victor Stinner20e1e252019-05-23 04:12:27 +0200850 'pycache_prefix': 'env_pycache_prefix',
851 'write_bytecode': 0,
852 'verbose': 1,
853 'buffered_stdio': 0,
854 'stdio_encoding': 'iso8859-1',
855 'stdio_errors': 'replace',
856 'user_site_directory': 0,
857 'faulthandler': 1,
858 'warnoptions': ['EnvVar'],
Sandro Mani8f023a22020-06-08 17:28:11 +0200859 'platlibdir': 'env_platlibdir',
860 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinner20e1e252019-05-23 04:12:27 +0200861 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200862 self.check_all_configs("test_init_compat_env", config, preconfig,
863 api=API_COMPAT)
Victor Stinner20e1e252019-05-23 04:12:27 +0200864
865 def test_init_python_env(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200866 preconfig = {
867 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner022be022019-05-22 23:58:50 +0200868 'utf8_mode': 1,
Victor Stinner425717f2019-05-20 16:38:48 +0200869 }
870 config = {
871 'use_hash_seed': 1,
872 'hash_seed': 42,
873 'tracemalloc': 2,
874 'import_time': 1,
875 'malloc_stats': 1,
876 'inspect': 1,
877 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200878 'pythonpath_env': '/my/path',
Victor Stinner425717f2019-05-20 16:38:48 +0200879 'pycache_prefix': 'env_pycache_prefix',
880 'write_bytecode': 0,
881 'verbose': 1,
882 'buffered_stdio': 0,
883 'stdio_encoding': 'iso8859-1',
884 'stdio_errors': 'replace',
885 'user_site_directory': 0,
886 'faulthandler': 1,
887 'warnoptions': ['EnvVar'],
Sandro Mani8f023a22020-06-08 17:28:11 +0200888 'platlibdir': 'env_platlibdir',
889 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinner425717f2019-05-20 16:38:48 +0200890 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200891 self.check_all_configs("test_init_python_env", config, preconfig,
892 api=API_PYTHON)
Victor Stinnerb35be4b2019-03-05 17:37:44 +0100893
894 def test_init_env_dev_mode(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200895 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
896 config = dict(dev_mode=1,
897 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100898 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200899 self.check_all_configs("test_init_env_dev_mode", config, preconfig,
900 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200901
Victor Stinner20004952019-03-26 02:31:11 +0100902 def test_init_env_dev_mode_alloc(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200903 preconfig = dict(allocator=PYMEM_ALLOCATOR_MALLOC)
904 config = dict(dev_mode=1,
905 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100906 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200907 self.check_all_configs("test_init_env_dev_mode_alloc", config, preconfig,
908 api=API_COMPAT)
Victor Stinner25d13f32019-03-06 12:51:53 +0100909
Victor Stinner56b29b62018-07-26 18:57:56 +0200910 def test_init_dev_mode(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100911 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200912 'allocator': PYMEM_ALLOCATOR_DEBUG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200913 }
Victor Stinner1075d162019-03-25 23:19:57 +0100914 config = {
915 'faulthandler': 1,
Victor Stinner20004952019-03-26 02:31:11 +0100916 'dev_mode': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100917 'warnoptions': ['default'],
Victor Stinner1075d162019-03-25 23:19:57 +0100918 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200919 self.check_all_configs("test_init_dev_mode", config, preconfig,
920 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200921
922 def test_preinit_parse_argv(self):
923 # Pre-initialize implicitly using argv: make sure that -X dev
924 # is used to configure the allocation in preinitialization
925 preconfig = {
926 'allocator': PYMEM_ALLOCATOR_DEBUG,
927 }
928 config = {
Victor Stinnera1a99b42019-12-09 17:34:02 +0100929 'argv': ['script.py'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200930 'orig_argv': ['python3', '-X', 'dev', 'script.py'],
Victor Stinnera1a99b42019-12-09 17:34:02 +0100931 'run_filename': os.path.abspath('script.py'),
Victor Stinner6d1c4672019-05-20 11:02:00 +0200932 'dev_mode': 1,
933 'faulthandler': 1,
934 'warnoptions': ['default'],
935 'xoptions': ['dev'],
936 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200937 self.check_all_configs("test_preinit_parse_argv", config, preconfig,
938 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200939
940 def test_preinit_dont_parse_argv(self):
941 # -X dev must be ignored by isolated preconfiguration
942 preconfig = {
943 'isolated': 0,
944 }
Victor Stinnere81f6e62020-06-08 18:12:59 +0200945 argv = ["python3",
946 "-E", "-I",
947 "-X", "dev",
948 "-X", "utf8",
949 "script.py"]
Victor Stinner6d1c4672019-05-20 11:02:00 +0200950 config = {
Victor Stinnere81f6e62020-06-08 18:12:59 +0200951 'argv': argv,
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200952 'orig_argv': argv,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200953 'isolated': 0,
954 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200955 self.check_all_configs("test_preinit_dont_parse_argv", config, preconfig,
956 api=API_ISOLATED)
Victor Stinner56b29b62018-07-26 18:57:56 +0200957
Victor Stinnercab5d072019-05-17 19:01:14 +0200958 def test_init_isolated_flag(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100959 config = {
Victor Stinner20004952019-03-26 02:31:11 +0100960 'isolated': 1,
961 'use_environment': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200962 'user_site_directory': 0,
963 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200964 self.check_all_configs("test_init_isolated_flag", config, api=API_PYTHON)
Victor Stinner56b29b62018-07-26 18:57:56 +0200965
Victor Stinner6da20a42019-03-27 00:26:18 +0100966 def test_preinit_isolated1(self):
967 # _PyPreConfig.isolated=1, _PyCoreConfig.isolated not set
Victor Stinner6da20a42019-03-27 00:26:18 +0100968 config = {
969 'isolated': 1,
970 'use_environment': 0,
971 'user_site_directory': 0,
972 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200973 self.check_all_configs("test_preinit_isolated1", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100974
975 def test_preinit_isolated2(self):
976 # _PyPreConfig.isolated=0, _PyCoreConfig.isolated=1
Victor Stinner6da20a42019-03-27 00:26:18 +0100977 config = {
978 'isolated': 1,
979 'use_environment': 0,
980 'user_site_directory': 0,
981 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200982 self.check_all_configs("test_preinit_isolated2", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100983
Victor Stinner6d1c4672019-05-20 11:02:00 +0200984 def test_preinit_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200985 self.check_all_configs("test_preinit_isolated_config", api=API_ISOLATED)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200986
Victor Stinnercab5d072019-05-17 19:01:14 +0200987 def test_init_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200988 self.check_all_configs("test_init_isolated_config", api=API_ISOLATED)
Victor Stinner5edcf262019-05-23 00:57:57 +0200989
990 def test_preinit_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200991 self.check_all_configs("test_preinit_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200992
993 def test_init_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200994 self.check_all_configs("test_init_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200995
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200996 def test_init_dont_configure_locale(self):
997 # _PyPreConfig.configure_locale=0
998 preconfig = {
999 'configure_locale': 0,
Victor Stinner425717f2019-05-20 16:38:48 +02001000 'coerce_c_locale': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +02001001 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001002 self.check_all_configs("test_init_dont_configure_locale", {}, preconfig,
1003 api=API_PYTHON)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +02001004
Victor Stinner91c99872019-05-14 22:01:51 +02001005 def test_init_read_set(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001006 config = {
Victor Stinner91c99872019-05-14 22:01:51 +02001007 'program_name': './init_read_set',
1008 'executable': 'my_executable',
1009 }
Victor Stinner3842f292019-08-23 16:57:54 +01001010 def modify_path(path):
1011 path.insert(1, "test_path_insert1")
1012 path.append("test_path_append")
Victor Stinner331a6a52019-05-27 16:39:22 +02001013 self.check_all_configs("test_init_read_set", config,
1014 api=API_PYTHON,
Victor Stinner3842f292019-08-23 16:57:54 +01001015 modify_path_cb=modify_path)
Victor Stinner91c99872019-05-14 22:01:51 +02001016
Victor Stinner120b7072019-08-23 18:03:08 +01001017 def test_init_sys_add(self):
1018 config = {
1019 'faulthandler': 1,
1020 'xoptions': [
1021 'config_xoption',
1022 'cmdline_xoption',
1023 'sysadd_xoption',
1024 'faulthandler',
1025 ],
1026 'warnoptions': [
Victor Stinner120b7072019-08-23 18:03:08 +01001027 'ignore:::cmdline_warnoption',
1028 'ignore:::sysadd_warnoption',
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001029 'ignore:::config_warnoption',
Victor Stinner120b7072019-08-23 18:03:08 +01001030 ],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001031 'orig_argv': ['python3',
1032 '-W', 'ignore:::cmdline_warnoption',
1033 '-X', 'cmdline_xoption'],
Victor Stinner120b7072019-08-23 18:03:08 +01001034 }
1035 self.check_all_configs("test_init_sys_add", config, api=API_PYTHON)
1036
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001037 def test_init_run_main(self):
Victor Stinner5eb8b072019-05-15 02:12:48 +02001038 code = ('import _testinternalcapi, json; '
1039 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +02001040 config = {
Victor Stinner5eb8b072019-05-15 02:12:48 +02001041 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001042 'orig_argv': ['python3', '-c', code, 'arg2'],
Victor Stinner5eb8b072019-05-15 02:12:48 +02001043 'program_name': './python3',
1044 'run_command': code + '\n',
Victor Stinnercab5d072019-05-17 19:01:14 +02001045 'parse_argv': 1,
Victor Stinner5eb8b072019-05-15 02:12:48 +02001046 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001047 self.check_all_configs("test_init_run_main", config, api=API_PYTHON)
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001048
1049 def test_init_main(self):
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001050 code = ('import _testinternalcapi, json; '
1051 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +02001052 config = {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001053 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001054 'orig_argv': ['python3',
1055 '-c', code,
1056 'arg2'],
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001057 'program_name': './python3',
1058 'run_command': code + '\n',
Victor Stinnercab5d072019-05-17 19:01:14 +02001059 'parse_argv': 1,
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001060 '_init_main': 0,
1061 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001062 self.check_all_configs("test_init_main", config,
1063 api=API_PYTHON,
1064 stderr="Run Python code before _Py_InitializeMain")
Victor Stinner5eb8b072019-05-15 02:12:48 +02001065
Victor Stinnercab5d072019-05-17 19:01:14 +02001066 def test_init_parse_argv(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001067 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +02001068 'parse_argv': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +02001069 'argv': ['-c', 'arg1', '-v', 'arg3'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001070 'orig_argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnercab5d072019-05-17 19:01:14 +02001071 'program_name': './argv0',
Victor Stinnercab5d072019-05-17 19:01:14 +02001072 'run_command': 'pass\n',
1073 'use_environment': 0,
1074 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001075 self.check_all_configs("test_init_parse_argv", config, api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +02001076
Victor Stinnerae239f62019-05-16 17:02:56 +02001077 def test_init_dont_parse_argv(self):
Victor Stinner6d1c4672019-05-20 11:02:00 +02001078 pre_config = {
1079 'parse_argv': 0,
1080 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001081 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +02001082 'parse_argv': 0,
Victor Stinnercab5d072019-05-17 19:01:14 +02001083 'argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001084 'orig_argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnercab5d072019-05-17 19:01:14 +02001085 'program_name': './argv0',
Victor Stinnerae239f62019-05-16 17:02:56 +02001086 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001087 self.check_all_configs("test_init_dont_parse_argv", config, pre_config,
1088 api=API_PYTHON)
Victor Stinnerae239f62019-05-16 17:02:56 +02001089
Victor Stinner8bf39b62019-09-26 02:22:35 +02001090 def default_program_name(self, config):
1091 if MS_WINDOWS:
1092 program_name = 'python'
1093 executable = self.test_exe
1094 else:
1095 program_name = 'python3'
Victor Stinner49d99f02019-09-26 04:01:49 +02001096 if MACOS:
1097 executable = self.test_exe
1098 else:
1099 executable = shutil.which(program_name) or ''
Victor Stinner8bf39b62019-09-26 02:22:35 +02001100 config.update({
1101 'program_name': program_name,
1102 'base_executable': executable,
1103 'executable': executable,
1104 })
1105
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001106 def test_init_setpath(self):
Victor Stinner8bf39b62019-09-26 02:22:35 +02001107 # Test Py_SetPath()
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001108 config = self._get_expected_config()
1109 paths = config['config']['module_search_paths']
1110
1111 config = {
1112 'module_search_paths': paths,
1113 'prefix': '',
1114 'base_prefix': '',
1115 'exec_prefix': '',
1116 'base_exec_prefix': '',
1117 }
Victor Stinner8bf39b62019-09-26 02:22:35 +02001118 self.default_program_name(config)
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001119 env = {'TESTPATH': os.path.pathsep.join(paths)}
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001120
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001121 self.check_all_configs("test_init_setpath", config,
1122 api=API_COMPAT, env=env,
1123 ignore_stderr=True)
1124
Victor Stinner8bf39b62019-09-26 02:22:35 +02001125 def test_init_setpath_config(self):
1126 # Test Py_SetPath() with PyConfig
1127 config = self._get_expected_config()
1128 paths = config['config']['module_search_paths']
1129
1130 config = {
1131 # set by Py_SetPath()
1132 'module_search_paths': paths,
1133 'prefix': '',
1134 'base_prefix': '',
1135 'exec_prefix': '',
1136 'base_exec_prefix': '',
1137 # overriden by PyConfig
1138 'program_name': 'conf_program_name',
1139 'base_executable': 'conf_executable',
1140 'executable': 'conf_executable',
1141 }
1142 env = {'TESTPATH': os.path.pathsep.join(paths)}
Victor Stinner8bf39b62019-09-26 02:22:35 +02001143 self.check_all_configs("test_init_setpath_config", config,
Victor Stinner49d99f02019-09-26 04:01:49 +02001144 api=API_PYTHON, env=env, ignore_stderr=True)
Victor Stinner8bf39b62019-09-26 02:22:35 +02001145
Victor Stinner52ad33a2019-09-25 02:10:35 +02001146 def module_search_paths(self, prefix=None, exec_prefix=None):
1147 config = self._get_expected_config()
1148 if prefix is None:
1149 prefix = config['config']['prefix']
1150 if exec_prefix is None:
1151 exec_prefix = config['config']['prefix']
1152 if MS_WINDOWS:
1153 return config['config']['module_search_paths']
1154 else:
1155 ver = sys.version_info
1156 return [
Victor Stinner8510f432020-03-10 09:53:09 +01001157 os.path.join(prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001158 f'python{ver.major}{ver.minor}.zip'),
Victor Stinner8510f432020-03-10 09:53:09 +01001159 os.path.join(prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001160 f'python{ver.major}.{ver.minor}'),
Victor Stinner8510f432020-03-10 09:53:09 +01001161 os.path.join(exec_prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001162 f'python{ver.major}.{ver.minor}', 'lib-dynload'),
1163 ]
1164
1165 @contextlib.contextmanager
1166 def tmpdir_with_python(self):
1167 # Temporary directory with a copy of the Python program
1168 with tempfile.TemporaryDirectory() as tmpdir:
Victor Stinner00508a72019-09-25 16:30:36 +02001169 # bpo-38234: On macOS and FreeBSD, the temporary directory
1170 # can be symbolic link. For example, /tmp can be a symbolic link
1171 # to /var/tmp. Call realpath() to resolve all symbolic links.
1172 tmpdir = os.path.realpath(tmpdir)
1173
Victor Stinner52ad33a2019-09-25 02:10:35 +02001174 if MS_WINDOWS:
1175 # Copy pythonXY.dll (or pythonXY_d.dll)
1176 ver = sys.version_info
1177 dll = f'python{ver.major}{ver.minor}'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001178 dll3 = f'python{ver.major}'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001179 if debug_build(sys.executable):
1180 dll += '_d'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001181 dll3 += '_d'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001182 dll += '.dll'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001183 dll3 += '.dll'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001184 dll = os.path.join(os.path.dirname(self.test_exe), dll)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001185 dll3 = os.path.join(os.path.dirname(self.test_exe), dll3)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001186 dll_copy = os.path.join(tmpdir, os.path.basename(dll))
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001187 dll3_copy = os.path.join(tmpdir, os.path.basename(dll3))
Victor Stinner52ad33a2019-09-25 02:10:35 +02001188 shutil.copyfile(dll, dll_copy)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001189 shutil.copyfile(dll3, dll3_copy)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001190
1191 # Copy Python program
1192 exec_copy = os.path.join(tmpdir, os.path.basename(self.test_exe))
1193 shutil.copyfile(self.test_exe, exec_copy)
1194 shutil.copystat(self.test_exe, exec_copy)
1195 self.test_exe = exec_copy
1196
1197 yield tmpdir
1198
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001199 def test_init_setpythonhome(self):
Victor Stinner8bf39b62019-09-26 02:22:35 +02001200 # Test Py_SetPythonHome(home) with PYTHONPATH env var
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001201 config = self._get_expected_config()
1202 paths = config['config']['module_search_paths']
1203 paths_str = os.path.pathsep.join(paths)
1204
1205 for path in paths:
1206 if not os.path.isdir(path):
1207 continue
1208 if os.path.exists(os.path.join(path, 'os.py')):
1209 home = os.path.dirname(path)
1210 break
1211 else:
1212 self.fail(f"Unable to find home in {paths!r}")
1213
1214 prefix = exec_prefix = home
1215 ver = sys.version_info
Victor Stinner52ad33a2019-09-25 02:10:35 +02001216 expected_paths = self.module_search_paths(prefix=home, exec_prefix=home)
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001217
1218 config = {
1219 'home': home,
1220 'module_search_paths': expected_paths,
1221 'prefix': prefix,
1222 'base_prefix': prefix,
1223 'exec_prefix': exec_prefix,
1224 'base_exec_prefix': exec_prefix,
1225 'pythonpath_env': paths_str,
1226 }
Victor Stinner8bf39b62019-09-26 02:22:35 +02001227 self.default_program_name(config)
1228 env = {'TESTHOME': home, 'PYTHONPATH': paths_str}
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001229 self.check_all_configs("test_init_setpythonhome", config,
1230 api=API_COMPAT, env=env)
1231
Victor Stinner52ad33a2019-09-25 02:10:35 +02001232 def copy_paths_by_env(self, config):
1233 all_configs = self._get_expected_config()
1234 paths = all_configs['config']['module_search_paths']
1235 paths_str = os.path.pathsep.join(paths)
1236 config['pythonpath_env'] = paths_str
1237 env = {'PYTHONPATH': paths_str}
1238 return env
1239
1240 @unittest.skipIf(MS_WINDOWS, 'Windows does not use pybuilddir.txt')
1241 def test_init_pybuilddir(self):
1242 # Test path configuration with pybuilddir.txt configuration file
1243
1244 with self.tmpdir_with_python() as tmpdir:
1245 # pybuilddir.txt is a sub-directory relative to the current
1246 # directory (tmpdir)
1247 subdir = 'libdir'
1248 libdir = os.path.join(tmpdir, subdir)
1249 os.mkdir(libdir)
1250
1251 filename = os.path.join(tmpdir, 'pybuilddir.txt')
1252 with open(filename, "w", encoding="utf8") as fp:
1253 fp.write(subdir)
1254
1255 module_search_paths = self.module_search_paths()
1256 module_search_paths[-1] = libdir
1257
1258 executable = self.test_exe
1259 config = {
1260 'base_executable': executable,
1261 'executable': executable,
1262 'module_search_paths': module_search_paths,
1263 }
1264 env = self.copy_paths_by_env(config)
1265 self.check_all_configs("test_init_compat_config", config,
1266 api=API_COMPAT, env=env,
1267 ignore_stderr=True, cwd=tmpdir)
1268
1269 def test_init_pyvenv_cfg(self):
1270 # Test path configuration with pyvenv.cfg configuration file
1271
1272 with self.tmpdir_with_python() as tmpdir, \
1273 tempfile.TemporaryDirectory() as pyvenv_home:
1274 ver = sys.version_info
1275
1276 if not MS_WINDOWS:
1277 lib_dynload = os.path.join(pyvenv_home,
Victor Stinner8510f432020-03-10 09:53:09 +01001278 sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001279 f'python{ver.major}.{ver.minor}',
1280 'lib-dynload')
1281 os.makedirs(lib_dynload)
1282 else:
1283 lib_dynload = os.path.join(pyvenv_home, 'lib')
1284 os.makedirs(lib_dynload)
1285 # getpathp.c uses Lib\os.py as the LANDMARK
1286 shutil.copyfile(os.__file__, os.path.join(lib_dynload, 'os.py'))
1287
1288 filename = os.path.join(tmpdir, 'pyvenv.cfg')
1289 with open(filename, "w", encoding="utf8") as fp:
1290 print("home = %s" % pyvenv_home, file=fp)
1291 print("include-system-site-packages = false", file=fp)
1292
1293 paths = self.module_search_paths()
1294 if not MS_WINDOWS:
1295 paths[-1] = lib_dynload
1296 else:
1297 for index, path in enumerate(paths):
1298 if index == 0:
1299 paths[index] = os.path.join(tmpdir, os.path.basename(path))
1300 else:
1301 paths[index] = os.path.join(pyvenv_home, os.path.basename(path))
1302 paths[-1] = pyvenv_home
1303
1304 executable = self.test_exe
1305 exec_prefix = pyvenv_home
1306 config = {
1307 'base_exec_prefix': exec_prefix,
1308 'exec_prefix': exec_prefix,
1309 'base_executable': executable,
1310 'executable': executable,
1311 'module_search_paths': paths,
1312 }
Victor Stinner8f427482020-07-08 00:20:37 +02001313 path_config = {}
Victor Stinner52ad33a2019-09-25 02:10:35 +02001314 if MS_WINDOWS:
1315 config['base_prefix'] = pyvenv_home
1316 config['prefix'] = pyvenv_home
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001317
Victor Stinner8f427482020-07-08 00:20:37 +02001318 ver = sys.version_info
1319 dll = f'python{ver.major}'
1320 if debug_build(executable):
1321 dll += '_d'
1322 dll += '.DLL'
1323 dll = os.path.join(os.path.dirname(executable), dll)
1324 path_config['python3_dll'] = dll
1325
1326 env = self.copy_paths_by_env(config)
1327 self.check_all_configs("test_init_compat_config", config,
1328 expected_pathconfig=path_config,
1329 api=API_COMPAT, env=env,
1330 ignore_stderr=True, cwd=tmpdir)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001331
Victor Stinner12f2f172019-09-26 15:51:50 +02001332 def test_global_pathconfig(self):
1333 # Test C API functions getting the path configuration:
1334 #
1335 # - Py_GetExecPrefix()
1336 # - Py_GetPath()
1337 # - Py_GetPrefix()
1338 # - Py_GetProgramFullPath()
1339 # - Py_GetProgramName()
1340 # - Py_GetPythonHome()
1341 #
1342 # The global path configuration (_Py_path_config) must be a copy
1343 # of the path configuration of PyInterpreter.config (PyConfig).
Hai Shibb0424b2020-08-04 00:47:42 +08001344 ctypes = import_helper.import_module('ctypes')
1345 _testinternalcapi = import_helper.import_module('_testinternalcapi')
Victor Stinner12f2f172019-09-26 15:51:50 +02001346
1347 def get_func(name):
1348 func = getattr(ctypes.pythonapi, name)
1349 func.argtypes = ()
1350 func.restype = ctypes.c_wchar_p
1351 return func
1352
1353 Py_GetPath = get_func('Py_GetPath')
1354 Py_GetPrefix = get_func('Py_GetPrefix')
1355 Py_GetExecPrefix = get_func('Py_GetExecPrefix')
1356 Py_GetProgramName = get_func('Py_GetProgramName')
1357 Py_GetProgramFullPath = get_func('Py_GetProgramFullPath')
1358 Py_GetPythonHome = get_func('Py_GetPythonHome')
1359
1360 config = _testinternalcapi.get_configs()['config']
1361
1362 self.assertEqual(Py_GetPath().split(os.path.pathsep),
1363 config['module_search_paths'])
1364 self.assertEqual(Py_GetPrefix(), config['prefix'])
1365 self.assertEqual(Py_GetExecPrefix(), config['exec_prefix'])
1366 self.assertEqual(Py_GetProgramName(), config['program_name'])
1367 self.assertEqual(Py_GetProgramFullPath(), config['executable'])
1368 self.assertEqual(Py_GetPythonHome(), config['home'])
1369
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001370 def test_init_warnoptions(self):
1371 # lowest to highest priority
1372 warnoptions = [
1373 'ignore:::PyConfig_Insert0', # PyWideStringList_Insert(0)
1374 'default', # PyConfig.dev_mode=1
1375 'ignore:::env1', # PYTHONWARNINGS env var
1376 'ignore:::env2', # PYTHONWARNINGS env var
1377 'ignore:::cmdline1', # -W opt command line option
1378 'ignore:::cmdline2', # -W opt command line option
1379 'default::BytesWarning', # PyConfig.bytes_warnings=1
1380 'ignore:::PySys_AddWarnOption1', # PySys_AddWarnOption()
1381 'ignore:::PySys_AddWarnOption2', # PySys_AddWarnOption()
1382 'ignore:::PyConfig_BeforeRead', # PyConfig.warnoptions
1383 'ignore:::PyConfig_AfterRead'] # PyWideStringList_Append()
1384 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
1385 config = {
1386 'dev_mode': 1,
1387 'faulthandler': 1,
1388 'bytes_warning': 1,
1389 'warnoptions': warnoptions,
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001390 'orig_argv': ['python3',
1391 '-Wignore:::cmdline1',
1392 '-Wignore:::cmdline2'],
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001393 }
1394 self.check_all_configs("test_init_warnoptions", config, preconfig,
1395 api=API_PYTHON)
1396
Victor Stinnere81f6e62020-06-08 18:12:59 +02001397 def test_get_argc_argv(self):
1398 self.run_embedded_interpreter("test_get_argc_argv")
1399 # ignore output
1400
Victor Stinner56b29b62018-07-26 18:57:56 +02001401
Steve Dowerb82e17e2019-05-23 08:45:22 -07001402class AuditingTests(EmbeddingTestsMixin, unittest.TestCase):
1403 def test_open_code_hook(self):
1404 self.run_embedded_interpreter("test_open_code_hook")
1405
1406 def test_audit(self):
1407 self.run_embedded_interpreter("test_audit")
1408
1409 def test_audit_subinterpreter(self):
1410 self.run_embedded_interpreter("test_audit_subinterpreter")
1411
Steve Dowere226e832019-07-01 16:03:53 -07001412 def test_audit_run_command(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001413 self.run_embedded_interpreter("test_audit_run_command",
1414 timeout=support.SHORT_TIMEOUT,
1415 returncode=1)
Steve Dowere226e832019-07-01 16:03:53 -07001416
1417 def test_audit_run_file(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001418 self.run_embedded_interpreter("test_audit_run_file",
1419 timeout=support.SHORT_TIMEOUT,
1420 returncode=1)
Steve Dowere226e832019-07-01 16:03:53 -07001421
1422 def test_audit_run_interactivehook(self):
Hai Shibb0424b2020-08-04 00:47:42 +08001423 startup = os.path.join(self.oldcwd, os_helper.TESTFN) + ".py"
Steve Dowere226e832019-07-01 16:03:53 -07001424 with open(startup, "w", encoding="utf-8") as f:
1425 print("import sys", file=f)
1426 print("sys.__interactivehook__ = lambda: None", file=f)
1427 try:
1428 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
Victor Stinner7772b1a2019-12-11 22:17:04 +01001429 self.run_embedded_interpreter("test_audit_run_interactivehook",
1430 timeout=support.SHORT_TIMEOUT,
Steve Dowere226e832019-07-01 16:03:53 -07001431 returncode=10, env=env)
1432 finally:
1433 os.unlink(startup)
1434
1435 def test_audit_run_startup(self):
Hai Shibb0424b2020-08-04 00:47:42 +08001436 startup = os.path.join(self.oldcwd, os_helper.TESTFN) + ".py"
Steve Dowere226e832019-07-01 16:03:53 -07001437 with open(startup, "w", encoding="utf-8") as f:
1438 print("pass", file=f)
1439 try:
1440 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
Victor Stinner7772b1a2019-12-11 22:17:04 +01001441 self.run_embedded_interpreter("test_audit_run_startup",
1442 timeout=support.SHORT_TIMEOUT,
Steve Dowere226e832019-07-01 16:03:53 -07001443 returncode=10, env=env)
1444 finally:
1445 os.unlink(startup)
1446
1447 def test_audit_run_stdin(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001448 self.run_embedded_interpreter("test_audit_run_stdin",
1449 timeout=support.SHORT_TIMEOUT,
1450 returncode=1)
Steve Dowerb82e17e2019-05-23 08:45:22 -07001451
Nick Coghlan39f0bb52017-11-28 08:11:51 +10001452if __name__ == "__main__":
1453 unittest.main()