blob: 2b740521e723cac20f23005c5cf2329937fe6882 [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
3import unittest
4
5from collections import namedtuple
Victor Stinner52ad33a2019-09-25 02:10:35 +02006import contextlib
Victor Stinner7ddd56f2018-11-14 00:24:28 +01007import json
Nick Coghlan39f0bb52017-11-28 08:11:51 +10008import os
9import re
Victor Stinner52ad33a2019-09-25 02:10:35 +020010import shutil
Nick Coghlan39f0bb52017-11-28 08:11:51 +100011import subprocess
12import sys
Victor Stinner52ad33a2019-09-25 02:10:35 +020013import tempfile
Victor Stinnera6537fb2018-11-26 11:54:12 +010014import textwrap
Nick Coghlan39f0bb52017-11-28 08:11:51 +100015
16
Victor Stinner01de89c2018-11-14 17:39:45 +010017MS_WINDOWS = (os.name == 'nt')
Victor Stinner49d99f02019-09-26 04:01:49 +020018MACOS = (sys.platform == 'darwin')
Victor Stinner022be022019-05-22 23:58:50 +020019
Victor Stinnerb16b4e42019-05-17 15:20:52 +020020PYMEM_ALLOCATOR_NOT_SET = 0
21PYMEM_ALLOCATOR_DEBUG = 2
22PYMEM_ALLOCATOR_MALLOC = 3
Victor Stinner01de89c2018-11-14 17:39:45 +010023
Victor Stinner022be022019-05-22 23:58:50 +020024# _PyCoreConfig_InitCompatConfig()
25API_COMPAT = 1
26# _PyCoreConfig_InitPythonConfig()
27API_PYTHON = 2
28# _PyCoreConfig_InitIsolatedConfig()
29API_ISOLATED = 3
Victor Stinner6d1c4672019-05-20 11:02:00 +020030
Victor Stinner01de89c2018-11-14 17:39:45 +010031
Victor Stinner52ad33a2019-09-25 02:10:35 +020032def debug_build(program):
33 program = os.path.basename(program)
34 name = os.path.splitext(program)[0]
Steve Dowerdcbaa1b2020-07-06 17:32:00 +010035 return name.casefold().endswith("_d".casefold())
Victor Stinner52ad33a2019-09-25 02:10:35 +020036
37
Victor Stinnerdbdc9912019-06-18 00:11:00 +020038def remove_python_envvars():
39 env = dict(os.environ)
40 # Remove PYTHON* environment variables to get deterministic environment
41 for key in list(env):
42 if key.startswith('PYTHON'):
43 del env[key]
44 return env
45
46
Victor Stinner56b29b62018-07-26 18:57:56 +020047class EmbeddingTestsMixin:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100048 def setUp(self):
49 here = os.path.abspath(__file__)
50 basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
51 exename = "_testembed"
Victor Stinner01de89c2018-11-14 17:39:45 +010052 if MS_WINDOWS:
Victor Stinner52ad33a2019-09-25 02:10:35 +020053 ext = ("_d" if debug_build(sys.executable) else "") + ".exe"
Nick Coghlan39f0bb52017-11-28 08:11:51 +100054 exename += ext
55 exepath = os.path.dirname(sys.executable)
56 else:
57 exepath = os.path.join(basepath, "Programs")
58 self.test_exe = exe = os.path.join(exepath, exename)
59 if not os.path.exists(exe):
60 self.skipTest("%r doesn't exist" % exe)
61 # This is needed otherwise we get a fatal error:
62 # "Py_Initialize: Unable to get the locale encoding
63 # LookupError: no codec search functions registered: can't find encoding"
64 self.oldcwd = os.getcwd()
65 os.chdir(basepath)
66
67 def tearDown(self):
68 os.chdir(self.oldcwd)
69
Steve Dowere226e832019-07-01 16:03:53 -070070 def run_embedded_interpreter(self, *args, env=None,
Victor Stinner52ad33a2019-09-25 02:10:35 +020071 timeout=None, returncode=0, input=None,
72 cwd=None):
Nick Coghlan39f0bb52017-11-28 08:11:51 +100073 """Runs a test in the embedded interpreter"""
74 cmd = [self.test_exe]
75 cmd.extend(args)
Victor Stinner01de89c2018-11-14 17:39:45 +010076 if env is not None and MS_WINDOWS:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100077 # Windows requires at least the SYSTEMROOT environment variable to
78 # start Python.
79 env = env.copy()
80 env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
81
82 p = subprocess.Popen(cmd,
83 stdout=subprocess.PIPE,
84 stderr=subprocess.PIPE,
85 universal_newlines=True,
Victor Stinner52ad33a2019-09-25 02:10:35 +020086 env=env,
87 cwd=cwd)
Victor Stinner2f549082019-03-29 15:13:46 +010088 try:
Steve Dowere226e832019-07-01 16:03:53 -070089 (out, err) = p.communicate(input=input, timeout=timeout)
Victor Stinner2f549082019-03-29 15:13:46 +010090 except:
91 p.terminate()
92 p.wait()
93 raise
Steve Dowere226e832019-07-01 16:03:53 -070094 if p.returncode != returncode and support.verbose:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100095 print(f"--- {cmd} failed ---")
96 print(f"stdout:\n{out}")
Nick Coghlanbc77eff2018-03-25 20:44:30 +100097 print(f"stderr:\n{err}")
Nick Coghlan39f0bb52017-11-28 08:11:51 +100098 print(f"------")
99
Steve Dowere226e832019-07-01 16:03:53 -0700100 self.assertEqual(p.returncode, returncode,
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000101 "bad returncode %d, stderr is %r" %
102 (p.returncode, err))
103 return out, err
104
105 def run_repeated_init_and_subinterpreters(self):
Victor Stinner5edcf262019-05-23 00:57:57 +0200106 out, err = self.run_embedded_interpreter("test_repeated_init_and_subinterpreters")
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000107 self.assertEqual(err, "")
108
109 # The output from _testembed looks like this:
110 # --- Pass 0 ---
111 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
112 # interp 1 <0x1d4f690>, thread state <0x1d35350>: id(modules) = 139650431165784
113 # interp 2 <0x1d5a690>, thread state <0x1d99ed0>: id(modules) = 139650413140368
114 # interp 3 <0x1d4f690>, thread state <0x1dc3340>: id(modules) = 139650412862200
115 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
116 # --- Pass 1 ---
117 # ...
118
119 interp_pat = (r"^interp (\d+) <(0x[\dA-F]+)>, "
120 r"thread state <(0x[\dA-F]+)>: "
121 r"id\(modules\) = ([\d]+)$")
122 Interp = namedtuple("Interp", "id interp tstate modules")
123
124 numloops = 0
125 current_run = []
126 for line in out.splitlines():
127 if line == "--- Pass {} ---".format(numloops):
128 self.assertEqual(len(current_run), 0)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000129 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000130 print(line)
131 numloops += 1
132 continue
133
134 self.assertLess(len(current_run), 5)
135 match = re.match(interp_pat, line)
136 if match is None:
137 self.assertRegex(line, interp_pat)
138
139 # Parse the line from the loop. The first line is the main
140 # interpreter and the 3 afterward are subinterpreters.
141 interp = Interp(*match.groups())
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000142 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000143 print(interp)
144 self.assertTrue(interp.interp)
145 self.assertTrue(interp.tstate)
146 self.assertTrue(interp.modules)
147 current_run.append(interp)
148
149 # The last line in the loop should be the same as the first.
150 if len(current_run) == 5:
151 main = current_run[0]
152 self.assertEqual(interp, main)
153 yield current_run
154 current_run = []
155
Victor Stinner56b29b62018-07-26 18:57:56 +0200156
157class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase):
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000158 def test_subinterps_main(self):
159 for run in self.run_repeated_init_and_subinterpreters():
160 main = run[0]
161
162 self.assertEqual(main.id, '0')
163
164 def test_subinterps_different_ids(self):
165 for run in self.run_repeated_init_and_subinterpreters():
166 main, *subs, _ = run
167
168 mainid = int(main.id)
169 for i, sub in enumerate(subs):
170 self.assertEqual(sub.id, str(mainid + i + 1))
171
172 def test_subinterps_distinct_state(self):
173 for run in self.run_repeated_init_and_subinterpreters():
174 main, *subs, _ = run
175
176 if '0x0' in main:
177 # XXX Fix on Windows (and other platforms): something
178 # is going on with the pointers in Programs/_testembed.c.
179 # interp.interp is 0x0 and interp.modules is the same
180 # between interpreters.
181 raise unittest.SkipTest('platform prints pointers as 0x0')
182
183 for sub in subs:
184 # A new subinterpreter may have the same
185 # PyInterpreterState pointer as a previous one if
186 # the earlier one has already been destroyed. So
187 # we compare with the main interpreter. The same
188 # applies to tstate.
189 self.assertNotEqual(sub.interp, main.interp)
190 self.assertNotEqual(sub.tstate, main.tstate)
191 self.assertNotEqual(sub.modules, main.modules)
192
193 def test_forced_io_encoding(self):
194 # Checks forced configuration of embedded interpreter IO streams
195 env = dict(os.environ, PYTHONIOENCODING="utf-8:surrogateescape")
Victor Stinner5edcf262019-05-23 00:57:57 +0200196 out, err = self.run_embedded_interpreter("test_forced_io_encoding", env=env)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000197 if support.verbose > 1:
198 print()
199 print(out)
200 print(err)
201 expected_stream_encoding = "utf-8"
202 expected_errors = "surrogateescape"
203 expected_output = '\n'.join([
204 "--- Use defaults ---",
205 "Expected encoding: default",
206 "Expected errors: default",
207 "stdin: {in_encoding}:{errors}",
208 "stdout: {out_encoding}:{errors}",
209 "stderr: {out_encoding}:backslashreplace",
210 "--- Set errors only ---",
211 "Expected encoding: default",
212 "Expected errors: ignore",
213 "stdin: {in_encoding}:ignore",
214 "stdout: {out_encoding}:ignore",
215 "stderr: {out_encoding}:backslashreplace",
216 "--- Set encoding only ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200217 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000218 "Expected errors: default",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200219 "stdin: iso8859-1:{errors}",
220 "stdout: iso8859-1:{errors}",
221 "stderr: iso8859-1:backslashreplace",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000222 "--- Set encoding and errors ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200223 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000224 "Expected errors: replace",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200225 "stdin: iso8859-1:replace",
226 "stdout: iso8859-1:replace",
227 "stderr: iso8859-1:backslashreplace"])
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000228 expected_output = expected_output.format(
229 in_encoding=expected_stream_encoding,
230 out_encoding=expected_stream_encoding,
231 errors=expected_errors)
232 # This is useful if we ever trip over odd platform behaviour
233 self.maxDiff = None
234 self.assertEqual(out.strip(), expected_output)
235
236 def test_pre_initialization_api(self):
237 """
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000238 Checks some key parts of the C-API that need to work before the runtine
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000239 is initialized (via Py_Initialize()).
240 """
241 env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path))
Victor Stinner5edcf262019-05-23 00:57:57 +0200242 out, err = self.run_embedded_interpreter("test_pre_initialization_api", env=env)
Victor Stinner01de89c2018-11-14 17:39:45 +0100243 if MS_WINDOWS:
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000244 expected_path = self.test_exe
245 else:
246 expected_path = os.path.join(os.getcwd(), "spam")
247 expected_output = f"sys.executable: {expected_path}\n"
248 self.assertIn(expected_output, out)
249 self.assertEqual(err, '')
250
251 def test_pre_initialization_sys_options(self):
252 """
253 Checks that sys.warnoptions and sys._xoptions can be set before the
254 runtime is initialized (otherwise they won't be effective).
255 """
Victor Stinnerdbdc9912019-06-18 00:11:00 +0200256 env = remove_python_envvars()
257 env['PYTHONPATH'] = os.pathsep.join(sys.path)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000258 out, err = self.run_embedded_interpreter(
Victor Stinner5edcf262019-05-23 00:57:57 +0200259 "test_pre_initialization_sys_options", env=env)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000260 expected_output = (
261 "sys.warnoptions: ['once', 'module', 'default']\n"
262 "sys._xoptions: {'not_an_option': '1', 'also_not_an_option': '2'}\n"
263 "warnings.filters[:3]: ['default', 'module', 'once']\n"
264 )
265 self.assertIn(expected_output, out)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000266 self.assertEqual(err, '')
267
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100268 def test_bpo20891(self):
269 """
Victor Stinner3225b9f2020-03-09 20:56:57 +0100270 bpo-20891: Calling PyGILState_Ensure in a non-Python thread must not
271 crash.
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100272 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200273 out, err = self.run_embedded_interpreter("test_bpo20891")
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100274 self.assertEqual(out, '')
275 self.assertEqual(err, '')
276
Victor Stinner209abf72018-06-22 19:14:51 +0200277 def test_initialize_twice(self):
278 """
279 bpo-33932: Calling Py_Initialize() twice should do nothing (and not
280 crash!).
281 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200282 out, err = self.run_embedded_interpreter("test_initialize_twice")
Victor Stinner209abf72018-06-22 19:14:51 +0200283 self.assertEqual(out, '')
284 self.assertEqual(err, '')
285
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200286 def test_initialize_pymain(self):
287 """
288 bpo-34008: Calling Py_Main() after Py_Initialize() must not fail.
289 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200290 out, err = self.run_embedded_interpreter("test_initialize_pymain")
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200291 self.assertEqual(out.rstrip(), "Py_Main() after Py_Initialize: sys.argv=['-c', 'arg2']")
292 self.assertEqual(err, '')
293
Victor Stinner2f549082019-03-29 15:13:46 +0100294 def test_run_main(self):
Victor Stinner5edcf262019-05-23 00:57:57 +0200295 out, err = self.run_embedded_interpreter("test_run_main")
Victor Stinner331a6a52019-05-27 16:39:22 +0200296 self.assertEqual(out.rstrip(), "Py_RunMain(): sys.argv=['-c', 'arg2']")
Victor Stinner2f549082019-03-29 15:13:46 +0100297 self.assertEqual(err, '')
298
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000299
Victor Stinner56b29b62018-07-26 18:57:56 +0200300class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
301 maxDiff = 4096
Victor Stinner01de89c2018-11-14 17:39:45 +0100302 UTF8_MODE_ERRORS = ('surrogatepass' if MS_WINDOWS else 'surrogateescape')
303
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200304 # Marker to read the default configuration: get_default_config()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100305 GET_DEFAULT_CONFIG = object()
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200306
307 # Marker to ignore a configuration parameter
308 IGNORE_CONFIG = object()
309
Victor Stinner022be022019-05-22 23:58:50 +0200310 PRE_CONFIG_COMPAT = {
Victor Stinner20e1e252019-05-23 04:12:27 +0200311 '_config_init': API_COMPAT,
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200312 'allocator': PYMEM_ALLOCATOR_NOT_SET,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200313 'parse_argv': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200314 'configure_locale': 1,
Victor Stinner1075d162019-03-25 23:19:57 +0100315 'coerce_c_locale': 0,
316 'coerce_c_locale_warn': 0,
Victor Stinner1075d162019-03-25 23:19:57 +0100317 'utf8_mode': 0,
318 }
Victor Stinner6d1c4672019-05-20 11:02:00 +0200319 if MS_WINDOWS:
Victor Stinner022be022019-05-22 23:58:50 +0200320 PRE_CONFIG_COMPAT.update({
Victor Stinner6d1c4672019-05-20 11:02:00 +0200321 'legacy_windows_fs_encoding': 0,
322 })
Victor Stinner022be022019-05-22 23:58:50 +0200323 PRE_CONFIG_PYTHON = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200324 _config_init=API_PYTHON,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200325 parse_argv=1,
Victor Stinner425717f2019-05-20 16:38:48 +0200326 coerce_c_locale=GET_DEFAULT_CONFIG,
327 utf8_mode=GET_DEFAULT_CONFIG,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200328 )
Victor Stinner022be022019-05-22 23:58:50 +0200329 PRE_CONFIG_ISOLATED = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200330 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200331 configure_locale=0,
332 isolated=1,
333 use_environment=0,
334 utf8_mode=0,
335 dev_mode=0,
Victor Stinner425717f2019-05-20 16:38:48 +0200336 coerce_c_locale=0,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200337 )
Victor Stinnerbab0db62019-05-18 03:21:27 +0200338
Victor Stinner20004952019-03-26 02:31:11 +0100339 COPY_PRE_CONFIG = [
340 'dev_mode',
341 'isolated',
342 'use_environment',
343 ]
344
Victor Stinner331a6a52019-05-27 16:39:22 +0200345 CONFIG_COMPAT = {
Victor Stinner022be022019-05-22 23:58:50 +0200346 '_config_init': API_COMPAT,
Victor Stinner20004952019-03-26 02:31:11 +0100347 'isolated': 0,
348 'use_environment': 1,
349 'dev_mode': 0,
350
Victor Stinner56b29b62018-07-26 18:57:56 +0200351 'install_signal_handlers': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200352 'use_hash_seed': 0,
353 'hash_seed': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200354 'faulthandler': 0,
355 'tracemalloc': 0,
356 'import_time': 0,
357 'show_ref_count': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200358 'dump_refs': 0,
359 'malloc_stats': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200360
Victor Stinnera6537fb2018-11-26 11:54:12 +0100361 'filesystem_encoding': GET_DEFAULT_CONFIG,
362 'filesystem_errors': GET_DEFAULT_CONFIG,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200363
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100364 'pycache_prefix': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200365 'program_name': GET_DEFAULT_CONFIG,
Victor Stinnercab5d072019-05-17 19:01:14 +0200366 'parse_argv': 0,
Victor Stinner62599762019-03-15 16:03:23 +0100367 'argv': [""],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200368 'orig_argv': [],
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100369
370 'xoptions': [],
371 'warnoptions': [],
Victor Stinner56b29b62018-07-26 18:57:56 +0200372
Victor Stinner331a6a52019-05-27 16:39:22 +0200373 'pythonpath_env': None,
Victor Stinner01de89c2018-11-14 17:39:45 +0100374 'home': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200375 'executable': GET_DEFAULT_CONFIG,
Steve Dower9048c492019-06-29 10:34:11 -0700376 'base_executable': GET_DEFAULT_CONFIG,
Victor Stinnera6537fb2018-11-26 11:54:12 +0100377
378 'prefix': GET_DEFAULT_CONFIG,
379 'base_prefix': GET_DEFAULT_CONFIG,
380 'exec_prefix': GET_DEFAULT_CONFIG,
381 'base_exec_prefix': GET_DEFAULT_CONFIG,
Victor Stinner5eb8b072019-05-15 02:12:48 +0200382 'module_search_paths': GET_DEFAULT_CONFIG,
Sandro Mani8f023a22020-06-08 17:28:11 +0200383 'platlibdir': sys.platlibdir,
Victor Stinner01de89c2018-11-14 17:39:45 +0100384
Victor Stinner56b29b62018-07-26 18:57:56 +0200385 'site_import': 1,
386 'bytes_warning': 0,
387 'inspect': 0,
388 'interactive': 0,
389 'optimization_level': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200390 'parser_debug': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200391 'write_bytecode': 1,
392 'verbose': 0,
393 'quiet': 0,
394 'user_site_directory': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200395 'configure_c_stdio': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200396 'buffered_stdio': 1,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200397
Victor Stinnera6537fb2018-11-26 11:54:12 +0100398 'stdio_encoding': GET_DEFAULT_CONFIG,
399 'stdio_errors': GET_DEFAULT_CONFIG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200400
Victor Stinner62be7632019-03-01 13:10:14 +0100401 'skip_source_first_line': 0,
402 'run_command': None,
403 'run_module': None,
404 'run_filename': None,
405
Victor Stinner56b29b62018-07-26 18:57:56 +0200406 '_install_importlib': 1,
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400407 'check_hash_pycs_mode': 'default',
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200408 'pathconfig_warnings': 1,
409 '_init_main': 1,
Victor Stinner252346a2020-05-01 11:33:44 +0200410 '_isolated_interpreter': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200411 }
Victor Stinner01de89c2018-11-14 17:39:45 +0100412 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200413 CONFIG_COMPAT.update({
Victor Stinner01de89c2018-11-14 17:39:45 +0100414 'legacy_windows_stdio': 0,
415 })
416
Victor Stinner331a6a52019-05-27 16:39:22 +0200417 CONFIG_PYTHON = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200418 _config_init=API_PYTHON,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200419 configure_c_stdio=1,
420 parse_argv=1,
421 )
Victor Stinner331a6a52019-05-27 16:39:22 +0200422 CONFIG_ISOLATED = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200423 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200424 isolated=1,
425 use_environment=0,
426 user_site_directory=0,
427 dev_mode=0,
428 install_signal_handlers=0,
429 use_hash_seed=0,
430 faulthandler=0,
431 tracemalloc=0,
432 pathconfig_warnings=0,
433 )
434 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200435 CONFIG_ISOLATED['legacy_windows_stdio'] = 0
Victor Stinnerbab0db62019-05-18 03:21:27 +0200436
Victor Stinner01de89c2018-11-14 17:39:45 +0100437 # global config
438 DEFAULT_GLOBAL_CONFIG = {
439 'Py_HasFileSystemDefaultEncoding': 0,
440 'Py_HashRandomizationFlag': 1,
441 '_Py_HasFileSystemDefaultEncodeErrors': 0,
442 }
Victor Stinner1075d162019-03-25 23:19:57 +0100443 COPY_GLOBAL_PRE_CONFIG = [
Victor Stinner1075d162019-03-25 23:19:57 +0100444 ('Py_UTF8Mode', 'utf8_mode'),
445 ]
Victor Stinner01de89c2018-11-14 17:39:45 +0100446 COPY_GLOBAL_CONFIG = [
447 # Copy core config to global config for expected values
448 # True means that the core config value is inverted (0 => 1 and 1 => 0)
449 ('Py_BytesWarningFlag', 'bytes_warning'),
450 ('Py_DebugFlag', 'parser_debug'),
451 ('Py_DontWriteBytecodeFlag', 'write_bytecode', True),
452 ('Py_FileSystemDefaultEncodeErrors', 'filesystem_errors'),
453 ('Py_FileSystemDefaultEncoding', 'filesystem_encoding'),
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200454 ('Py_FrozenFlag', 'pathconfig_warnings', True),
Victor Stinner20004952019-03-26 02:31:11 +0100455 ('Py_IgnoreEnvironmentFlag', 'use_environment', True),
Victor Stinner01de89c2018-11-14 17:39:45 +0100456 ('Py_InspectFlag', 'inspect'),
457 ('Py_InteractiveFlag', 'interactive'),
Victor Stinner20004952019-03-26 02:31:11 +0100458 ('Py_IsolatedFlag', 'isolated'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100459 ('Py_NoSiteFlag', 'site_import', True),
460 ('Py_NoUserSiteDirectory', 'user_site_directory', True),
461 ('Py_OptimizeFlag', 'optimization_level'),
462 ('Py_QuietFlag', 'quiet'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100463 ('Py_UnbufferedStdioFlag', 'buffered_stdio', True),
464 ('Py_VerboseFlag', 'verbose'),
465 ]
466 if MS_WINDOWS:
Victor Stinner1075d162019-03-25 23:19:57 +0100467 COPY_GLOBAL_PRE_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100468 ('Py_LegacyWindowsFSEncodingFlag', 'legacy_windows_fs_encoding'),
Victor Stinner1075d162019-03-25 23:19:57 +0100469 ))
470 COPY_GLOBAL_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100471 ('Py_LegacyWindowsStdioFlag', 'legacy_windows_stdio'),
472 ))
Victor Stinner56b29b62018-07-26 18:57:56 +0200473
Victor Stinner8f427482020-07-08 00:20:37 +0200474 # path config
475 if MS_WINDOWS:
476 PATH_CONFIG = {
477 'isolated': -1,
478 'site_import': -1,
479 'python3_dll': GET_DEFAULT_CONFIG,
480 }
481 else:
482 PATH_CONFIG = {}
483 # other keys are copied by COPY_PATH_CONFIG
484
485 COPY_PATH_CONFIG = [
486 # Copy core config to global config for expected values
487 'prefix',
488 'exec_prefix',
489 'program_name',
490 'home',
491 # program_full_path and module_search_path are copied indirectly from
492 # the core configuration in check_path_config().
493 ]
494 if MS_WINDOWS:
495 COPY_PATH_CONFIG.extend((
496 'base_executable',
497 ))
498
Victor Stinner425717f2019-05-20 16:38:48 +0200499 EXPECTED_CONFIG = None
500
Victor Stinner52ad33a2019-09-25 02:10:35 +0200501 @classmethod
502 def tearDownClass(cls):
503 # clear cache
504 cls.EXPECTED_CONFIG = None
505
Victor Stinner01de89c2018-11-14 17:39:45 +0100506 def main_xoptions(self, xoptions_list):
507 xoptions = {}
508 for opt in xoptions_list:
509 if '=' in opt:
510 key, value = opt.split('=', 1)
511 xoptions[key] = value
512 else:
513 xoptions[opt] = True
514 return xoptions
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200515
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200516 def _get_expected_config_impl(self):
517 env = remove_python_envvars()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100518 code = textwrap.dedent('''
519 import json
Victor Stinnera6537fb2018-11-26 11:54:12 +0100520 import sys
Victor Stinner5eb8b072019-05-15 02:12:48 +0200521 import _testinternalcapi
Victor Stinnera6537fb2018-11-26 11:54:12 +0100522
Victor Stinner5eb8b072019-05-15 02:12:48 +0200523 configs = _testinternalcapi.get_configs()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100524
Victor Stinner425717f2019-05-20 16:38:48 +0200525 data = json.dumps(configs)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100526 data = data.encode('utf-8')
527 sys.stdout.buffer.write(data)
528 sys.stdout.buffer.flush()
529 ''')
530
531 # Use -S to not import the site module: get the proper configuration
532 # when test_embed is run from a venv (bpo-35313)
Victor Stinner5eb8b072019-05-15 02:12:48 +0200533 args = [sys.executable, '-S', '-c', code]
Victor Stinnera6537fb2018-11-26 11:54:12 +0100534 proc = subprocess.run(args, env=env,
535 stdout=subprocess.PIPE,
Victor Stinner52ad33a2019-09-25 02:10:35 +0200536 stderr=subprocess.PIPE)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100537 if proc.returncode:
538 raise Exception(f"failed to get the default config: "
539 f"stdout={proc.stdout!r} stderr={proc.stderr!r}")
540 stdout = proc.stdout.decode('utf-8')
Victor Stinner52ad33a2019-09-25 02:10:35 +0200541 # ignore stderr
Victor Stinner4631da12019-05-02 15:30:21 -0400542 try:
Victor Stinner425717f2019-05-20 16:38:48 +0200543 return json.loads(stdout)
Victor Stinner4631da12019-05-02 15:30:21 -0400544 except json.JSONDecodeError:
545 self.fail(f"fail to decode stdout: {stdout!r}")
Victor Stinnera6537fb2018-11-26 11:54:12 +0100546
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200547 def _get_expected_config(self):
548 cls = InitConfigTests
549 if cls.EXPECTED_CONFIG is None:
550 cls.EXPECTED_CONFIG = self._get_expected_config_impl()
551
552 # get a copy
Victor Stinner52ad33a2019-09-25 02:10:35 +0200553 configs = {}
554 for config_key, config_value in cls.EXPECTED_CONFIG.items():
555 config = {}
556 for key, value in config_value.items():
557 if isinstance(value, list):
558 value = value.copy()
559 config[key] = value
560 configs[config_key] = config
561 return configs
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200562
Victor Stinner8f427482020-07-08 00:20:37 +0200563 def get_expected_config(self, expected_preconfig, expected,
564 expected_pathconfig, env, api,
Victor Stinner3842f292019-08-23 16:57:54 +0100565 modify_path_cb=None):
Victor Stinner425717f2019-05-20 16:38:48 +0200566 cls = self.__class__
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200567 configs = self._get_expected_config()
Victor Stinner425717f2019-05-20 16:38:48 +0200568
569 pre_config = configs['pre_config']
570 for key, value in expected_preconfig.items():
571 if value is self.GET_DEFAULT_CONFIG:
572 expected_preconfig[key] = pre_config[key]
573
Victor Stinner8f427482020-07-08 00:20:37 +0200574 path_config = configs['path_config']
575 for key, value in expected_pathconfig.items():
576 if value is self.GET_DEFAULT_CONFIG:
577 expected_pathconfig[key] = path_config[key]
578
Victor Stinner022be022019-05-22 23:58:50 +0200579 if not expected_preconfig['configure_locale'] or api == API_COMPAT:
Victor Stinner425717f2019-05-20 16:38:48 +0200580 # there is no easy way to get the locale encoding before
581 # setlocale(LC_CTYPE, "") is called: don't test encodings
582 for key in ('filesystem_encoding', 'filesystem_errors',
583 'stdio_encoding', 'stdio_errors'):
584 expected[key] = self.IGNORE_CONFIG
585
586 if not expected_preconfig['configure_locale']:
587 # UTF-8 Mode depends on the locale. There is no easy way
588 # to guess if UTF-8 Mode will be enabled or not if the locale
589 # is not configured.
590 expected_preconfig['utf8_mode'] = self.IGNORE_CONFIG
591
592 if expected_preconfig['utf8_mode'] == 1:
593 if expected['filesystem_encoding'] is self.GET_DEFAULT_CONFIG:
594 expected['filesystem_encoding'] = 'utf-8'
595 if expected['filesystem_errors'] is self.GET_DEFAULT_CONFIG:
596 expected['filesystem_errors'] = self.UTF8_MODE_ERRORS
597 if expected['stdio_encoding'] is self.GET_DEFAULT_CONFIG:
598 expected['stdio_encoding'] = 'utf-8'
599 if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG:
600 expected['stdio_errors'] = 'surrogateescape'
601
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100602 if MS_WINDOWS:
Steve Dower9048c492019-06-29 10:34:11 -0700603 default_executable = self.test_exe
604 elif expected['program_name'] is not self.GET_DEFAULT_CONFIG:
605 default_executable = os.path.abspath(expected['program_name'])
606 else:
607 default_executable = os.path.join(os.getcwd(), '_testembed')
Victor Stinner91c99872019-05-14 22:01:51 +0200608 if expected['executable'] is self.GET_DEFAULT_CONFIG:
Steve Dower9048c492019-06-29 10:34:11 -0700609 expected['executable'] = default_executable
610 if expected['base_executable'] is self.GET_DEFAULT_CONFIG:
611 expected['base_executable'] = default_executable
Victor Stinner91c99872019-05-14 22:01:51 +0200612 if expected['program_name'] is self.GET_DEFAULT_CONFIG:
613 expected['program_name'] = './_testembed'
614
Victor Stinner331a6a52019-05-27 16:39:22 +0200615 config = configs['config']
Victor Stinnera6537fb2018-11-26 11:54:12 +0100616 for key, value in expected.items():
617 if value is self.GET_DEFAULT_CONFIG:
Victor Stinner331a6a52019-05-27 16:39:22 +0200618 expected[key] = config[key]
Victor Stinner5eb8b072019-05-15 02:12:48 +0200619
Sandro Mani8f023a22020-06-08 17:28:11 +0200620 if expected['module_search_paths'] is not self.IGNORE_CONFIG:
621 pythonpath_env = expected['pythonpath_env']
622 if pythonpath_env is not None:
623 paths = pythonpath_env.split(os.path.pathsep)
624 expected['module_search_paths'] = [*paths, *expected['module_search_paths']]
625 if modify_path_cb is not None:
626 expected['module_search_paths'] = expected['module_search_paths'].copy()
627 modify_path_cb(expected['module_search_paths'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200628
Victor Stinner425717f2019-05-20 16:38:48 +0200629 for key in self.COPY_PRE_CONFIG:
630 if key not in expected_preconfig:
631 expected_preconfig[key] = expected[key]
Victor Stinner01de89c2018-11-14 17:39:45 +0100632
Victor Stinner331a6a52019-05-27 16:39:22 +0200633 def check_pre_config(self, configs, expected):
634 pre_config = dict(configs['pre_config'])
Victor Stinner425717f2019-05-20 16:38:48 +0200635 for key, value in list(expected.items()):
636 if value is self.IGNORE_CONFIG:
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100637 pre_config.pop(key, None)
Victor Stinner425717f2019-05-20 16:38:48 +0200638 del expected[key]
639 self.assertEqual(pre_config, expected)
Victor Stinner1075d162019-03-25 23:19:57 +0100640
Victor Stinner331a6a52019-05-27 16:39:22 +0200641 def check_config(self, configs, expected):
642 config = dict(configs['config'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200643 for key, value in list(expected.items()):
644 if value is self.IGNORE_CONFIG:
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100645 config.pop(key, None)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200646 del expected[key]
Victor Stinner331a6a52019-05-27 16:39:22 +0200647 self.assertEqual(config, expected)
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200648
Victor Stinner331a6a52019-05-27 16:39:22 +0200649 def check_global_config(self, configs):
650 pre_config = configs['pre_config']
651 config = configs['config']
Victor Stinner00b137c2018-11-13 19:59:26 +0100652
Victor Stinnera6537fb2018-11-26 11:54:12 +0100653 expected = dict(self.DEFAULT_GLOBAL_CONFIG)
Victor Stinner01de89c2018-11-14 17:39:45 +0100654 for item in self.COPY_GLOBAL_CONFIG:
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100655 if len(item) == 3:
656 global_key, core_key, opposite = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200657 expected[global_key] = 0 if config[core_key] else 1
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100658 else:
659 global_key, core_key = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200660 expected[global_key] = config[core_key]
Victor Stinner1075d162019-03-25 23:19:57 +0100661 for item in self.COPY_GLOBAL_PRE_CONFIG:
662 if len(item) == 3:
663 global_key, core_key, opposite = item
664 expected[global_key] = 0 if pre_config[core_key] else 1
665 else:
666 global_key, core_key = item
667 expected[global_key] = pre_config[core_key]
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100668
Victor Stinner331a6a52019-05-27 16:39:22 +0200669 self.assertEqual(configs['global_config'], expected)
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100670
Victor Stinner8f427482020-07-08 00:20:37 +0200671 def check_path_config(self, configs, expected):
672 config = configs['config']
673
674 for key in self.COPY_PATH_CONFIG:
675 expected[key] = config[key]
676 expected['module_search_path'] = os.path.pathsep.join(config['module_search_paths'])
677 expected['program_full_path'] = config['executable']
678
679 self.assertEqual(configs['path_config'], expected)
680
Victor Stinner331a6a52019-05-27 16:39:22 +0200681 def check_all_configs(self, testname, expected_config=None,
Victor Stinner8f427482020-07-08 00:20:37 +0200682 expected_preconfig=None, expected_pathconfig=None,
683 modify_path_cb=None,
Victor Stinner8bf39b62019-09-26 02:22:35 +0200684 stderr=None, *, api, preconfig_api=None,
685 env=None, ignore_stderr=False, cwd=None):
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200686 new_env = remove_python_envvars()
687 if env is not None:
688 new_env.update(env)
689 env = new_env
Victor Stinner01de89c2018-11-14 17:39:45 +0100690
Victor Stinner8bf39b62019-09-26 02:22:35 +0200691 if preconfig_api is None:
692 preconfig_api = api
693 if preconfig_api == API_ISOLATED:
Victor Stinner022be022019-05-22 23:58:50 +0200694 default_preconfig = self.PRE_CONFIG_ISOLATED
Victor Stinner8bf39b62019-09-26 02:22:35 +0200695 elif preconfig_api == API_PYTHON:
Victor Stinner022be022019-05-22 23:58:50 +0200696 default_preconfig = self.PRE_CONFIG_PYTHON
Victor Stinnerbab0db62019-05-18 03:21:27 +0200697 else:
Victor Stinner022be022019-05-22 23:58:50 +0200698 default_preconfig = self.PRE_CONFIG_COMPAT
Victor Stinnerbab0db62019-05-18 03:21:27 +0200699 if expected_preconfig is None:
700 expected_preconfig = {}
701 expected_preconfig = dict(default_preconfig, **expected_preconfig)
Victor Stinner8f427482020-07-08 00:20:37 +0200702
Victor Stinnerbab0db62019-05-18 03:21:27 +0200703 if expected_config is None:
704 expected_config = {}
Victor Stinner425717f2019-05-20 16:38:48 +0200705
Victor Stinner8f427482020-07-08 00:20:37 +0200706 if expected_pathconfig is None:
707 expected_pathconfig = {}
708 expected_pathconfig = dict(self.PATH_CONFIG, **expected_pathconfig)
709
Victor Stinner022be022019-05-22 23:58:50 +0200710 if api == API_PYTHON:
Victor Stinner331a6a52019-05-27 16:39:22 +0200711 default_config = self.CONFIG_PYTHON
Victor Stinner022be022019-05-22 23:58:50 +0200712 elif api == API_ISOLATED:
Victor Stinner331a6a52019-05-27 16:39:22 +0200713 default_config = self.CONFIG_ISOLATED
Victor Stinner425717f2019-05-20 16:38:48 +0200714 else:
Victor Stinner331a6a52019-05-27 16:39:22 +0200715 default_config = self.CONFIG_COMPAT
Victor Stinner425717f2019-05-20 16:38:48 +0200716 expected_config = dict(default_config, **expected_config)
Victor Stinner425717f2019-05-20 16:38:48 +0200717
718 self.get_expected_config(expected_preconfig,
Victor Stinner8f427482020-07-08 00:20:37 +0200719 expected_config,
720 expected_pathconfig,
721 env,
Victor Stinner3842f292019-08-23 16:57:54 +0100722 api, modify_path_cb)
Victor Stinner1075d162019-03-25 23:19:57 +0100723
Victor Stinner52ad33a2019-09-25 02:10:35 +0200724 out, err = self.run_embedded_interpreter(testname,
725 env=env, cwd=cwd)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200726 if stderr is None and not expected_config['verbose']:
727 stderr = ""
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200728 if stderr is not None and not ignore_stderr:
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200729 self.assertEqual(err.rstrip(), stderr)
730 try:
Victor Stinner331a6a52019-05-27 16:39:22 +0200731 configs = json.loads(out)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200732 except json.JSONDecodeError:
733 self.fail(f"fail to decode stdout: {out!r}")
734
Victor Stinner331a6a52019-05-27 16:39:22 +0200735 self.check_pre_config(configs, expected_preconfig)
736 self.check_config(configs, expected_config)
737 self.check_global_config(configs)
Victor Stinner8f427482020-07-08 00:20:37 +0200738 self.check_path_config(configs, expected_pathconfig)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100739 return configs
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100740
Victor Stinner56b29b62018-07-26 18:57:56 +0200741 def test_init_default_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200742 self.check_all_configs("test_init_initialize_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200743
744 def test_preinit_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200745 self.check_all_configs("test_preinit_compat_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200746
747 def test_init_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200748 self.check_all_configs("test_init_compat_config", api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200749
750 def test_init_global_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100751 preconfig = {
752 'utf8_mode': 1,
753 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200754 config = {
755 'program_name': './globalvar',
756 'site_import': 0,
757 'bytes_warning': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100758 'warnoptions': ['default::BytesWarning'],
Victor Stinner56b29b62018-07-26 18:57:56 +0200759 'inspect': 1,
760 'interactive': 1,
761 'optimization_level': 2,
762 'write_bytecode': 0,
763 'verbose': 1,
764 'quiet': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200765 'buffered_stdio': 0,
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200766
Victor Stinner56b29b62018-07-26 18:57:56 +0200767 'user_site_directory': 0,
Victor Stinner54b43bb2019-05-16 18:30:15 +0200768 'pathconfig_warnings': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200769 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200770 self.check_all_configs("test_init_global_config", config, preconfig,
771 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200772
773 def test_init_from_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100774 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200775 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner1075d162019-03-25 23:19:57 +0100776 'utf8_mode': 1,
777 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200778 config = {
779 'install_signal_handlers': 0,
780 'use_hash_seed': 1,
781 'hash_seed': 123,
Victor Stinner56b29b62018-07-26 18:57:56 +0200782 'tracemalloc': 2,
783 'import_time': 1,
784 'show_ref_count': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200785 'malloc_stats': 1,
786
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200787 'stdio_encoding': 'iso8859-1',
788 'stdio_errors': 'replace',
Victor Stinner56b29b62018-07-26 18:57:56 +0200789
790 'pycache_prefix': 'conf_pycache_prefix',
791 'program_name': './conf_program_name',
Victor Stinnere81f6e62020-06-08 18:12:59 +0200792 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200793 'orig_argv': ['python3',
794 '-W', 'cmdline_warnoption',
795 '-X', 'cmdline_xoption',
796 '-c', 'pass',
797 'arg2'],
Victor Stinnercab5d072019-05-17 19:01:14 +0200798 'parse_argv': 1,
Victor Stinner67310022019-07-01 19:52:45 +0200799 'xoptions': [
800 'config_xoption1=3',
801 'config_xoption2=',
802 'config_xoption3',
803 'cmdline_xoption',
804 ],
805 'warnoptions': [
Victor Stinner67310022019-07-01 19:52:45 +0200806 'cmdline_warnoption',
807 'default::BytesWarning',
Victor Stinnerfb4ae152019-09-30 01:40:17 +0200808 'config_warnoption',
Victor Stinner67310022019-07-01 19:52:45 +0200809 ],
Victor Stinner2f549082019-03-29 15:13:46 +0100810 'run_command': 'pass\n',
Victor Stinner56b29b62018-07-26 18:57:56 +0200811
812 'site_import': 0,
813 'bytes_warning': 1,
814 'inspect': 1,
815 'interactive': 1,
816 'optimization_level': 2,
817 'write_bytecode': 0,
818 'verbose': 1,
819 'quiet': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200820 'configure_c_stdio': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200821 'buffered_stdio': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200822 'user_site_directory': 0,
823 'faulthandler': 1,
Sandro Mani8f023a22020-06-08 17:28:11 +0200824 'platlibdir': 'my_platlibdir',
825 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinnerb75d7e22018-08-01 02:13:04 +0200826
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400827 'check_hash_pycs_mode': 'always',
Victor Stinner54b43bb2019-05-16 18:30:15 +0200828 'pathconfig_warnings': 0,
Victor Stinner252346a2020-05-01 11:33:44 +0200829
830 '_isolated_interpreter': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200831 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200832 self.check_all_configs("test_init_from_config", config, preconfig,
833 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200834
Victor Stinner20e1e252019-05-23 04:12:27 +0200835 def test_init_compat_env(self):
836 preconfig = {
837 'allocator': PYMEM_ALLOCATOR_MALLOC,
838 }
839 config = {
840 'use_hash_seed': 1,
841 'hash_seed': 42,
842 'tracemalloc': 2,
843 'import_time': 1,
844 'malloc_stats': 1,
845 'inspect': 1,
846 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200847 'pythonpath_env': '/my/path',
Victor Stinner20e1e252019-05-23 04:12:27 +0200848 'pycache_prefix': 'env_pycache_prefix',
849 'write_bytecode': 0,
850 'verbose': 1,
851 'buffered_stdio': 0,
852 'stdio_encoding': 'iso8859-1',
853 'stdio_errors': 'replace',
854 'user_site_directory': 0,
855 'faulthandler': 1,
856 'warnoptions': ['EnvVar'],
Sandro Mani8f023a22020-06-08 17:28:11 +0200857 'platlibdir': 'env_platlibdir',
858 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinner20e1e252019-05-23 04:12:27 +0200859 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200860 self.check_all_configs("test_init_compat_env", config, preconfig,
861 api=API_COMPAT)
Victor Stinner20e1e252019-05-23 04:12:27 +0200862
863 def test_init_python_env(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200864 preconfig = {
865 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner022be022019-05-22 23:58:50 +0200866 'utf8_mode': 1,
Victor Stinner425717f2019-05-20 16:38:48 +0200867 }
868 config = {
869 'use_hash_seed': 1,
870 'hash_seed': 42,
871 'tracemalloc': 2,
872 'import_time': 1,
873 'malloc_stats': 1,
874 'inspect': 1,
875 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200876 'pythonpath_env': '/my/path',
Victor Stinner425717f2019-05-20 16:38:48 +0200877 'pycache_prefix': 'env_pycache_prefix',
878 'write_bytecode': 0,
879 'verbose': 1,
880 'buffered_stdio': 0,
881 'stdio_encoding': 'iso8859-1',
882 'stdio_errors': 'replace',
883 'user_site_directory': 0,
884 'faulthandler': 1,
885 'warnoptions': ['EnvVar'],
Sandro Mani8f023a22020-06-08 17:28:11 +0200886 'platlibdir': 'env_platlibdir',
887 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinner425717f2019-05-20 16:38:48 +0200888 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200889 self.check_all_configs("test_init_python_env", config, preconfig,
890 api=API_PYTHON)
Victor Stinnerb35be4b2019-03-05 17:37:44 +0100891
892 def test_init_env_dev_mode(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200893 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
894 config = dict(dev_mode=1,
895 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100896 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200897 self.check_all_configs("test_init_env_dev_mode", config, preconfig,
898 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200899
Victor Stinner20004952019-03-26 02:31:11 +0100900 def test_init_env_dev_mode_alloc(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200901 preconfig = dict(allocator=PYMEM_ALLOCATOR_MALLOC)
902 config = dict(dev_mode=1,
903 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100904 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200905 self.check_all_configs("test_init_env_dev_mode_alloc", config, preconfig,
906 api=API_COMPAT)
Victor Stinner25d13f32019-03-06 12:51:53 +0100907
Victor Stinner56b29b62018-07-26 18:57:56 +0200908 def test_init_dev_mode(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100909 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200910 'allocator': PYMEM_ALLOCATOR_DEBUG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200911 }
Victor Stinner1075d162019-03-25 23:19:57 +0100912 config = {
913 'faulthandler': 1,
Victor Stinner20004952019-03-26 02:31:11 +0100914 'dev_mode': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100915 'warnoptions': ['default'],
Victor Stinner1075d162019-03-25 23:19:57 +0100916 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200917 self.check_all_configs("test_init_dev_mode", config, preconfig,
918 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200919
920 def test_preinit_parse_argv(self):
921 # Pre-initialize implicitly using argv: make sure that -X dev
922 # is used to configure the allocation in preinitialization
923 preconfig = {
924 'allocator': PYMEM_ALLOCATOR_DEBUG,
925 }
926 config = {
Victor Stinnera1a99b42019-12-09 17:34:02 +0100927 'argv': ['script.py'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200928 'orig_argv': ['python3', '-X', 'dev', 'script.py'],
Victor Stinnera1a99b42019-12-09 17:34:02 +0100929 'run_filename': os.path.abspath('script.py'),
Victor Stinner6d1c4672019-05-20 11:02:00 +0200930 'dev_mode': 1,
931 'faulthandler': 1,
932 'warnoptions': ['default'],
933 'xoptions': ['dev'],
934 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200935 self.check_all_configs("test_preinit_parse_argv", config, preconfig,
936 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200937
938 def test_preinit_dont_parse_argv(self):
939 # -X dev must be ignored by isolated preconfiguration
940 preconfig = {
941 'isolated': 0,
942 }
Victor Stinnere81f6e62020-06-08 18:12:59 +0200943 argv = ["python3",
944 "-E", "-I",
945 "-X", "dev",
946 "-X", "utf8",
947 "script.py"]
Victor Stinner6d1c4672019-05-20 11:02:00 +0200948 config = {
Victor Stinnere81f6e62020-06-08 18:12:59 +0200949 'argv': argv,
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200950 'orig_argv': argv,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200951 'isolated': 0,
952 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200953 self.check_all_configs("test_preinit_dont_parse_argv", config, preconfig,
954 api=API_ISOLATED)
Victor Stinner56b29b62018-07-26 18:57:56 +0200955
Victor Stinnercab5d072019-05-17 19:01:14 +0200956 def test_init_isolated_flag(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100957 config = {
Victor Stinner20004952019-03-26 02:31:11 +0100958 'isolated': 1,
959 'use_environment': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200960 'user_site_directory': 0,
961 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200962 self.check_all_configs("test_init_isolated_flag", config, api=API_PYTHON)
Victor Stinner56b29b62018-07-26 18:57:56 +0200963
Victor Stinner6da20a42019-03-27 00:26:18 +0100964 def test_preinit_isolated1(self):
965 # _PyPreConfig.isolated=1, _PyCoreConfig.isolated not set
Victor Stinner6da20a42019-03-27 00:26:18 +0100966 config = {
967 'isolated': 1,
968 'use_environment': 0,
969 'user_site_directory': 0,
970 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200971 self.check_all_configs("test_preinit_isolated1", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100972
973 def test_preinit_isolated2(self):
974 # _PyPreConfig.isolated=0, _PyCoreConfig.isolated=1
Victor Stinner6da20a42019-03-27 00:26:18 +0100975 config = {
976 'isolated': 1,
977 'use_environment': 0,
978 'user_site_directory': 0,
979 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200980 self.check_all_configs("test_preinit_isolated2", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100981
Victor Stinner6d1c4672019-05-20 11:02:00 +0200982 def test_preinit_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200983 self.check_all_configs("test_preinit_isolated_config", api=API_ISOLATED)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200984
Victor Stinnercab5d072019-05-17 19:01:14 +0200985 def test_init_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200986 self.check_all_configs("test_init_isolated_config", api=API_ISOLATED)
Victor Stinner5edcf262019-05-23 00:57:57 +0200987
988 def test_preinit_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200989 self.check_all_configs("test_preinit_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200990
991 def test_init_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200992 self.check_all_configs("test_init_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200993
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200994 def test_init_dont_configure_locale(self):
995 # _PyPreConfig.configure_locale=0
996 preconfig = {
997 'configure_locale': 0,
Victor Stinner425717f2019-05-20 16:38:48 +0200998 'coerce_c_locale': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200999 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001000 self.check_all_configs("test_init_dont_configure_locale", {}, preconfig,
1001 api=API_PYTHON)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +02001002
Victor Stinner91c99872019-05-14 22:01:51 +02001003 def test_init_read_set(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001004 config = {
Victor Stinner91c99872019-05-14 22:01:51 +02001005 'program_name': './init_read_set',
1006 'executable': 'my_executable',
1007 }
Victor Stinner3842f292019-08-23 16:57:54 +01001008 def modify_path(path):
1009 path.insert(1, "test_path_insert1")
1010 path.append("test_path_append")
Victor Stinner331a6a52019-05-27 16:39:22 +02001011 self.check_all_configs("test_init_read_set", config,
1012 api=API_PYTHON,
Victor Stinner3842f292019-08-23 16:57:54 +01001013 modify_path_cb=modify_path)
Victor Stinner91c99872019-05-14 22:01:51 +02001014
Victor Stinner120b7072019-08-23 18:03:08 +01001015 def test_init_sys_add(self):
1016 config = {
1017 'faulthandler': 1,
1018 'xoptions': [
1019 'config_xoption',
1020 'cmdline_xoption',
1021 'sysadd_xoption',
1022 'faulthandler',
1023 ],
1024 'warnoptions': [
Victor Stinner120b7072019-08-23 18:03:08 +01001025 'ignore:::cmdline_warnoption',
1026 'ignore:::sysadd_warnoption',
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001027 'ignore:::config_warnoption',
Victor Stinner120b7072019-08-23 18:03:08 +01001028 ],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001029 'orig_argv': ['python3',
1030 '-W', 'ignore:::cmdline_warnoption',
1031 '-X', 'cmdline_xoption'],
Victor Stinner120b7072019-08-23 18:03:08 +01001032 }
1033 self.check_all_configs("test_init_sys_add", config, api=API_PYTHON)
1034
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001035 def test_init_run_main(self):
Victor Stinner5eb8b072019-05-15 02:12:48 +02001036 code = ('import _testinternalcapi, json; '
1037 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +02001038 config = {
Victor Stinner5eb8b072019-05-15 02:12:48 +02001039 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001040 'orig_argv': ['python3', '-c', code, 'arg2'],
Victor Stinner5eb8b072019-05-15 02:12:48 +02001041 'program_name': './python3',
1042 'run_command': code + '\n',
Victor Stinnercab5d072019-05-17 19:01:14 +02001043 'parse_argv': 1,
Victor Stinner5eb8b072019-05-15 02:12:48 +02001044 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001045 self.check_all_configs("test_init_run_main", config, api=API_PYTHON)
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001046
1047 def test_init_main(self):
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001048 code = ('import _testinternalcapi, json; '
1049 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +02001050 config = {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001051 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001052 'orig_argv': ['python3',
1053 '-c', code,
1054 'arg2'],
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001055 'program_name': './python3',
1056 'run_command': code + '\n',
Victor Stinnercab5d072019-05-17 19:01:14 +02001057 'parse_argv': 1,
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001058 '_init_main': 0,
1059 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001060 self.check_all_configs("test_init_main", config,
1061 api=API_PYTHON,
1062 stderr="Run Python code before _Py_InitializeMain")
Victor Stinner5eb8b072019-05-15 02:12:48 +02001063
Victor Stinnercab5d072019-05-17 19:01:14 +02001064 def test_init_parse_argv(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001065 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +02001066 'parse_argv': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +02001067 'argv': ['-c', 'arg1', '-v', 'arg3'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001068 'orig_argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnercab5d072019-05-17 19:01:14 +02001069 'program_name': './argv0',
Victor Stinnercab5d072019-05-17 19:01:14 +02001070 'run_command': 'pass\n',
1071 'use_environment': 0,
1072 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001073 self.check_all_configs("test_init_parse_argv", config, api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +02001074
Victor Stinnerae239f62019-05-16 17:02:56 +02001075 def test_init_dont_parse_argv(self):
Victor Stinner6d1c4672019-05-20 11:02:00 +02001076 pre_config = {
1077 'parse_argv': 0,
1078 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001079 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +02001080 'parse_argv': 0,
Victor Stinnercab5d072019-05-17 19:01:14 +02001081 'argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001082 'orig_argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnercab5d072019-05-17 19:01:14 +02001083 'program_name': './argv0',
Victor Stinnerae239f62019-05-16 17:02:56 +02001084 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001085 self.check_all_configs("test_init_dont_parse_argv", config, pre_config,
1086 api=API_PYTHON)
Victor Stinnerae239f62019-05-16 17:02:56 +02001087
Victor Stinner8bf39b62019-09-26 02:22:35 +02001088 def default_program_name(self, config):
1089 if MS_WINDOWS:
1090 program_name = 'python'
1091 executable = self.test_exe
1092 else:
1093 program_name = 'python3'
Victor Stinner49d99f02019-09-26 04:01:49 +02001094 if MACOS:
1095 executable = self.test_exe
1096 else:
1097 executable = shutil.which(program_name) or ''
Victor Stinner8bf39b62019-09-26 02:22:35 +02001098 config.update({
1099 'program_name': program_name,
1100 'base_executable': executable,
1101 'executable': executable,
1102 })
1103
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001104 def test_init_setpath(self):
Victor Stinner8bf39b62019-09-26 02:22:35 +02001105 # Test Py_SetPath()
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001106 config = self._get_expected_config()
1107 paths = config['config']['module_search_paths']
1108
1109 config = {
1110 'module_search_paths': paths,
1111 'prefix': '',
1112 'base_prefix': '',
1113 'exec_prefix': '',
1114 'base_exec_prefix': '',
1115 }
Victor Stinner8bf39b62019-09-26 02:22:35 +02001116 self.default_program_name(config)
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001117 env = {'TESTPATH': os.path.pathsep.join(paths)}
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001118
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001119 self.check_all_configs("test_init_setpath", config,
1120 api=API_COMPAT, env=env,
1121 ignore_stderr=True)
1122
Victor Stinner8bf39b62019-09-26 02:22:35 +02001123 def test_init_setpath_config(self):
1124 # Test Py_SetPath() with PyConfig
1125 config = self._get_expected_config()
1126 paths = config['config']['module_search_paths']
1127
1128 config = {
1129 # set by Py_SetPath()
1130 'module_search_paths': paths,
1131 'prefix': '',
1132 'base_prefix': '',
1133 'exec_prefix': '',
1134 'base_exec_prefix': '',
1135 # overriden by PyConfig
1136 'program_name': 'conf_program_name',
1137 'base_executable': 'conf_executable',
1138 'executable': 'conf_executable',
1139 }
1140 env = {'TESTPATH': os.path.pathsep.join(paths)}
Victor Stinner8bf39b62019-09-26 02:22:35 +02001141 self.check_all_configs("test_init_setpath_config", config,
Victor Stinner49d99f02019-09-26 04:01:49 +02001142 api=API_PYTHON, env=env, ignore_stderr=True)
Victor Stinner8bf39b62019-09-26 02:22:35 +02001143
Victor Stinner52ad33a2019-09-25 02:10:35 +02001144 def module_search_paths(self, prefix=None, exec_prefix=None):
1145 config = self._get_expected_config()
1146 if prefix is None:
1147 prefix = config['config']['prefix']
1148 if exec_prefix is None:
1149 exec_prefix = config['config']['prefix']
1150 if MS_WINDOWS:
1151 return config['config']['module_search_paths']
1152 else:
1153 ver = sys.version_info
1154 return [
Victor Stinner8510f432020-03-10 09:53:09 +01001155 os.path.join(prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001156 f'python{ver.major}{ver.minor}.zip'),
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}'),
Victor Stinner8510f432020-03-10 09:53:09 +01001159 os.path.join(exec_prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001160 f'python{ver.major}.{ver.minor}', 'lib-dynload'),
1161 ]
1162
1163 @contextlib.contextmanager
1164 def tmpdir_with_python(self):
1165 # Temporary directory with a copy of the Python program
1166 with tempfile.TemporaryDirectory() as tmpdir:
Victor Stinner00508a72019-09-25 16:30:36 +02001167 # bpo-38234: On macOS and FreeBSD, the temporary directory
1168 # can be symbolic link. For example, /tmp can be a symbolic link
1169 # to /var/tmp. Call realpath() to resolve all symbolic links.
1170 tmpdir = os.path.realpath(tmpdir)
1171
Victor Stinner52ad33a2019-09-25 02:10:35 +02001172 if MS_WINDOWS:
1173 # Copy pythonXY.dll (or pythonXY_d.dll)
1174 ver = sys.version_info
1175 dll = f'python{ver.major}{ver.minor}'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001176 dll3 = f'python{ver.major}'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001177 if debug_build(sys.executable):
1178 dll += '_d'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001179 dll3 += '_d'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001180 dll += '.dll'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001181 dll3 += '.dll'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001182 dll = os.path.join(os.path.dirname(self.test_exe), dll)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001183 dll3 = os.path.join(os.path.dirname(self.test_exe), dll3)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001184 dll_copy = os.path.join(tmpdir, os.path.basename(dll))
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001185 dll3_copy = os.path.join(tmpdir, os.path.basename(dll3))
Victor Stinner52ad33a2019-09-25 02:10:35 +02001186 shutil.copyfile(dll, dll_copy)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001187 shutil.copyfile(dll3, dll3_copy)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001188
1189 # Copy Python program
1190 exec_copy = os.path.join(tmpdir, os.path.basename(self.test_exe))
1191 shutil.copyfile(self.test_exe, exec_copy)
1192 shutil.copystat(self.test_exe, exec_copy)
1193 self.test_exe = exec_copy
1194
1195 yield tmpdir
1196
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001197 def test_init_setpythonhome(self):
Victor Stinner8bf39b62019-09-26 02:22:35 +02001198 # Test Py_SetPythonHome(home) with PYTHONPATH env var
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001199 config = self._get_expected_config()
1200 paths = config['config']['module_search_paths']
1201 paths_str = os.path.pathsep.join(paths)
1202
1203 for path in paths:
1204 if not os.path.isdir(path):
1205 continue
1206 if os.path.exists(os.path.join(path, 'os.py')):
1207 home = os.path.dirname(path)
1208 break
1209 else:
1210 self.fail(f"Unable to find home in {paths!r}")
1211
1212 prefix = exec_prefix = home
1213 ver = sys.version_info
Victor Stinner52ad33a2019-09-25 02:10:35 +02001214 expected_paths = self.module_search_paths(prefix=home, exec_prefix=home)
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001215
1216 config = {
1217 'home': home,
1218 'module_search_paths': expected_paths,
1219 'prefix': prefix,
1220 'base_prefix': prefix,
1221 'exec_prefix': exec_prefix,
1222 'base_exec_prefix': exec_prefix,
1223 'pythonpath_env': paths_str,
1224 }
Victor Stinner8bf39b62019-09-26 02:22:35 +02001225 self.default_program_name(config)
1226 env = {'TESTHOME': home, 'PYTHONPATH': paths_str}
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001227 self.check_all_configs("test_init_setpythonhome", config,
1228 api=API_COMPAT, env=env)
1229
Victor Stinner52ad33a2019-09-25 02:10:35 +02001230 def copy_paths_by_env(self, config):
1231 all_configs = self._get_expected_config()
1232 paths = all_configs['config']['module_search_paths']
1233 paths_str = os.path.pathsep.join(paths)
1234 config['pythonpath_env'] = paths_str
1235 env = {'PYTHONPATH': paths_str}
1236 return env
1237
1238 @unittest.skipIf(MS_WINDOWS, 'Windows does not use pybuilddir.txt')
1239 def test_init_pybuilddir(self):
1240 # Test path configuration with pybuilddir.txt configuration file
1241
1242 with self.tmpdir_with_python() as tmpdir:
1243 # pybuilddir.txt is a sub-directory relative to the current
1244 # directory (tmpdir)
1245 subdir = 'libdir'
1246 libdir = os.path.join(tmpdir, subdir)
1247 os.mkdir(libdir)
1248
1249 filename = os.path.join(tmpdir, 'pybuilddir.txt')
1250 with open(filename, "w", encoding="utf8") as fp:
1251 fp.write(subdir)
1252
1253 module_search_paths = self.module_search_paths()
1254 module_search_paths[-1] = libdir
1255
1256 executable = self.test_exe
1257 config = {
1258 'base_executable': executable,
1259 'executable': executable,
1260 'module_search_paths': module_search_paths,
1261 }
1262 env = self.copy_paths_by_env(config)
1263 self.check_all_configs("test_init_compat_config", config,
1264 api=API_COMPAT, env=env,
1265 ignore_stderr=True, cwd=tmpdir)
1266
1267 def test_init_pyvenv_cfg(self):
1268 # Test path configuration with pyvenv.cfg configuration file
1269
1270 with self.tmpdir_with_python() as tmpdir, \
1271 tempfile.TemporaryDirectory() as pyvenv_home:
1272 ver = sys.version_info
1273
1274 if not MS_WINDOWS:
1275 lib_dynload = os.path.join(pyvenv_home,
Victor Stinner8510f432020-03-10 09:53:09 +01001276 sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001277 f'python{ver.major}.{ver.minor}',
1278 'lib-dynload')
1279 os.makedirs(lib_dynload)
1280 else:
1281 lib_dynload = os.path.join(pyvenv_home, 'lib')
1282 os.makedirs(lib_dynload)
1283 # getpathp.c uses Lib\os.py as the LANDMARK
1284 shutil.copyfile(os.__file__, os.path.join(lib_dynload, 'os.py'))
1285
1286 filename = os.path.join(tmpdir, 'pyvenv.cfg')
1287 with open(filename, "w", encoding="utf8") as fp:
1288 print("home = %s" % pyvenv_home, file=fp)
1289 print("include-system-site-packages = false", file=fp)
1290
1291 paths = self.module_search_paths()
1292 if not MS_WINDOWS:
1293 paths[-1] = lib_dynload
1294 else:
1295 for index, path in enumerate(paths):
1296 if index == 0:
1297 paths[index] = os.path.join(tmpdir, os.path.basename(path))
1298 else:
1299 paths[index] = os.path.join(pyvenv_home, os.path.basename(path))
1300 paths[-1] = pyvenv_home
1301
1302 executable = self.test_exe
1303 exec_prefix = pyvenv_home
1304 config = {
1305 'base_exec_prefix': exec_prefix,
1306 'exec_prefix': exec_prefix,
1307 'base_executable': executable,
1308 'executable': executable,
1309 'module_search_paths': paths,
1310 }
Victor Stinner8f427482020-07-08 00:20:37 +02001311 path_config = {}
Victor Stinner52ad33a2019-09-25 02:10:35 +02001312 if MS_WINDOWS:
1313 config['base_prefix'] = pyvenv_home
1314 config['prefix'] = pyvenv_home
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001315
Victor Stinner8f427482020-07-08 00:20:37 +02001316 ver = sys.version_info
1317 dll = f'python{ver.major}'
1318 if debug_build(executable):
1319 dll += '_d'
1320 dll += '.DLL'
1321 dll = os.path.join(os.path.dirname(executable), dll)
1322 path_config['python3_dll'] = dll
1323
1324 env = self.copy_paths_by_env(config)
1325 self.check_all_configs("test_init_compat_config", config,
1326 expected_pathconfig=path_config,
1327 api=API_COMPAT, env=env,
1328 ignore_stderr=True, cwd=tmpdir)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001329
Victor Stinner12f2f172019-09-26 15:51:50 +02001330 def test_global_pathconfig(self):
1331 # Test C API functions getting the path configuration:
1332 #
1333 # - Py_GetExecPrefix()
1334 # - Py_GetPath()
1335 # - Py_GetPrefix()
1336 # - Py_GetProgramFullPath()
1337 # - Py_GetProgramName()
1338 # - Py_GetPythonHome()
1339 #
1340 # The global path configuration (_Py_path_config) must be a copy
1341 # of the path configuration of PyInterpreter.config (PyConfig).
1342 ctypes = support.import_module('ctypes')
1343 _testinternalcapi = support.import_module('_testinternalcapi')
1344
1345 def get_func(name):
1346 func = getattr(ctypes.pythonapi, name)
1347 func.argtypes = ()
1348 func.restype = ctypes.c_wchar_p
1349 return func
1350
1351 Py_GetPath = get_func('Py_GetPath')
1352 Py_GetPrefix = get_func('Py_GetPrefix')
1353 Py_GetExecPrefix = get_func('Py_GetExecPrefix')
1354 Py_GetProgramName = get_func('Py_GetProgramName')
1355 Py_GetProgramFullPath = get_func('Py_GetProgramFullPath')
1356 Py_GetPythonHome = get_func('Py_GetPythonHome')
1357
1358 config = _testinternalcapi.get_configs()['config']
1359
1360 self.assertEqual(Py_GetPath().split(os.path.pathsep),
1361 config['module_search_paths'])
1362 self.assertEqual(Py_GetPrefix(), config['prefix'])
1363 self.assertEqual(Py_GetExecPrefix(), config['exec_prefix'])
1364 self.assertEqual(Py_GetProgramName(), config['program_name'])
1365 self.assertEqual(Py_GetProgramFullPath(), config['executable'])
1366 self.assertEqual(Py_GetPythonHome(), config['home'])
1367
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001368 def test_init_warnoptions(self):
1369 # lowest to highest priority
1370 warnoptions = [
1371 'ignore:::PyConfig_Insert0', # PyWideStringList_Insert(0)
1372 'default', # PyConfig.dev_mode=1
1373 'ignore:::env1', # PYTHONWARNINGS env var
1374 'ignore:::env2', # PYTHONWARNINGS env var
1375 'ignore:::cmdline1', # -W opt command line option
1376 'ignore:::cmdline2', # -W opt command line option
1377 'default::BytesWarning', # PyConfig.bytes_warnings=1
1378 'ignore:::PySys_AddWarnOption1', # PySys_AddWarnOption()
1379 'ignore:::PySys_AddWarnOption2', # PySys_AddWarnOption()
1380 'ignore:::PyConfig_BeforeRead', # PyConfig.warnoptions
1381 'ignore:::PyConfig_AfterRead'] # PyWideStringList_Append()
1382 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
1383 config = {
1384 'dev_mode': 1,
1385 'faulthandler': 1,
1386 'bytes_warning': 1,
1387 'warnoptions': warnoptions,
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001388 'orig_argv': ['python3',
1389 '-Wignore:::cmdline1',
1390 '-Wignore:::cmdline2'],
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001391 }
1392 self.check_all_configs("test_init_warnoptions", config, preconfig,
1393 api=API_PYTHON)
1394
Victor Stinnere81f6e62020-06-08 18:12:59 +02001395 def test_get_argc_argv(self):
1396 self.run_embedded_interpreter("test_get_argc_argv")
1397 # ignore output
1398
Victor Stinner56b29b62018-07-26 18:57:56 +02001399
Steve Dowerb82e17e2019-05-23 08:45:22 -07001400class AuditingTests(EmbeddingTestsMixin, unittest.TestCase):
1401 def test_open_code_hook(self):
1402 self.run_embedded_interpreter("test_open_code_hook")
1403
1404 def test_audit(self):
1405 self.run_embedded_interpreter("test_audit")
1406
1407 def test_audit_subinterpreter(self):
1408 self.run_embedded_interpreter("test_audit_subinterpreter")
1409
Steve Dowere226e832019-07-01 16:03:53 -07001410 def test_audit_run_command(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001411 self.run_embedded_interpreter("test_audit_run_command",
1412 timeout=support.SHORT_TIMEOUT,
1413 returncode=1)
Steve Dowere226e832019-07-01 16:03:53 -07001414
1415 def test_audit_run_file(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001416 self.run_embedded_interpreter("test_audit_run_file",
1417 timeout=support.SHORT_TIMEOUT,
1418 returncode=1)
Steve Dowere226e832019-07-01 16:03:53 -07001419
1420 def test_audit_run_interactivehook(self):
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001421 startup = os.path.join(self.oldcwd, support.TESTFN) + ".py"
Steve Dowere226e832019-07-01 16:03:53 -07001422 with open(startup, "w", encoding="utf-8") as f:
1423 print("import sys", file=f)
1424 print("sys.__interactivehook__ = lambda: None", file=f)
1425 try:
1426 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
Victor Stinner7772b1a2019-12-11 22:17:04 +01001427 self.run_embedded_interpreter("test_audit_run_interactivehook",
1428 timeout=support.SHORT_TIMEOUT,
Steve Dowere226e832019-07-01 16:03:53 -07001429 returncode=10, env=env)
1430 finally:
1431 os.unlink(startup)
1432
1433 def test_audit_run_startup(self):
Serhiy Storchaka700cfa82020-06-25 17:56:31 +03001434 startup = os.path.join(self.oldcwd, support.TESTFN) + ".py"
Steve Dowere226e832019-07-01 16:03:53 -07001435 with open(startup, "w", encoding="utf-8") as f:
1436 print("pass", file=f)
1437 try:
1438 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
Victor Stinner7772b1a2019-12-11 22:17:04 +01001439 self.run_embedded_interpreter("test_audit_run_startup",
1440 timeout=support.SHORT_TIMEOUT,
Steve Dowere226e832019-07-01 16:03:53 -07001441 returncode=10, env=env)
1442 finally:
1443 os.unlink(startup)
1444
1445 def test_audit_run_stdin(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001446 self.run_embedded_interpreter("test_audit_run_stdin",
1447 timeout=support.SHORT_TIMEOUT,
1448 returncode=1)
Steve Dowerb82e17e2019-05-23 08:45:22 -07001449
Nick Coghlan39f0bb52017-11-28 08:11:51 +10001450if __name__ == "__main__":
1451 unittest.main()