blob: 7808a1a2cf6a6481c24d8c493be611b3596bfe83 [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 Stinner7ddd56f2018-11-14 00:24:28 +01006import json
Nick Coghlan39f0bb52017-11-28 08:11:51 +10007import os
8import re
9import subprocess
10import sys
Victor Stinnera6537fb2018-11-26 11:54:12 +010011import textwrap
Nick Coghlan39f0bb52017-11-28 08:11:51 +100012
13
Victor Stinner01de89c2018-11-14 17:39:45 +010014MS_WINDOWS = (os.name == 'nt')
Victor Stinner022be022019-05-22 23:58:50 +020015
Victor Stinnerb16b4e42019-05-17 15:20:52 +020016PYMEM_ALLOCATOR_NOT_SET = 0
17PYMEM_ALLOCATOR_DEBUG = 2
18PYMEM_ALLOCATOR_MALLOC = 3
Victor Stinner01de89c2018-11-14 17:39:45 +010019
Victor Stinner022be022019-05-22 23:58:50 +020020# _PyCoreConfig_InitCompatConfig()
21API_COMPAT = 1
22# _PyCoreConfig_InitPythonConfig()
23API_PYTHON = 2
24# _PyCoreConfig_InitIsolatedConfig()
25API_ISOLATED = 3
Victor Stinner6d1c4672019-05-20 11:02:00 +020026
Victor Stinner01de89c2018-11-14 17:39:45 +010027
Victor Stinnerdbdc9912019-06-18 00:11:00 +020028def remove_python_envvars():
29 env = dict(os.environ)
30 # Remove PYTHON* environment variables to get deterministic environment
31 for key in list(env):
32 if key.startswith('PYTHON'):
33 del env[key]
34 return env
35
36
Victor Stinner56b29b62018-07-26 18:57:56 +020037class EmbeddingTestsMixin:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100038 def setUp(self):
39 here = os.path.abspath(__file__)
40 basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
41 exename = "_testembed"
Victor Stinner01de89c2018-11-14 17:39:45 +010042 if MS_WINDOWS:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100043 ext = ("_d" if "_d" in sys.executable else "") + ".exe"
44 exename += ext
45 exepath = os.path.dirname(sys.executable)
46 else:
47 exepath = os.path.join(basepath, "Programs")
48 self.test_exe = exe = os.path.join(exepath, exename)
49 if not os.path.exists(exe):
50 self.skipTest("%r doesn't exist" % exe)
51 # This is needed otherwise we get a fatal error:
52 # "Py_Initialize: Unable to get the locale encoding
53 # LookupError: no codec search functions registered: can't find encoding"
54 self.oldcwd = os.getcwd()
55 os.chdir(basepath)
56
57 def tearDown(self):
58 os.chdir(self.oldcwd)
59
Steve Dowere226e832019-07-01 16:03:53 -070060 def run_embedded_interpreter(self, *args, env=None,
61 timeout=None, returncode=0, input=None):
Nick Coghlan39f0bb52017-11-28 08:11:51 +100062 """Runs a test in the embedded interpreter"""
63 cmd = [self.test_exe]
64 cmd.extend(args)
Victor Stinner01de89c2018-11-14 17:39:45 +010065 if env is not None and MS_WINDOWS:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100066 # Windows requires at least the SYSTEMROOT environment variable to
67 # start Python.
68 env = env.copy()
69 env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
70
71 p = subprocess.Popen(cmd,
72 stdout=subprocess.PIPE,
73 stderr=subprocess.PIPE,
74 universal_newlines=True,
75 env=env)
Victor Stinner2f549082019-03-29 15:13:46 +010076 try:
Steve Dowere226e832019-07-01 16:03:53 -070077 (out, err) = p.communicate(input=input, timeout=timeout)
Victor Stinner2f549082019-03-29 15:13:46 +010078 except:
79 p.terminate()
80 p.wait()
81 raise
Steve Dowere226e832019-07-01 16:03:53 -070082 if p.returncode != returncode and support.verbose:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100083 print(f"--- {cmd} failed ---")
84 print(f"stdout:\n{out}")
Nick Coghlanbc77eff2018-03-25 20:44:30 +100085 print(f"stderr:\n{err}")
Nick Coghlan39f0bb52017-11-28 08:11:51 +100086 print(f"------")
87
Steve Dowere226e832019-07-01 16:03:53 -070088 self.assertEqual(p.returncode, returncode,
Nick Coghlan39f0bb52017-11-28 08:11:51 +100089 "bad returncode %d, stderr is %r" %
90 (p.returncode, err))
91 return out, err
92
93 def run_repeated_init_and_subinterpreters(self):
Victor Stinner5edcf262019-05-23 00:57:57 +020094 out, err = self.run_embedded_interpreter("test_repeated_init_and_subinterpreters")
Nick Coghlan39f0bb52017-11-28 08:11:51 +100095 self.assertEqual(err, "")
96
97 # The output from _testembed looks like this:
98 # --- Pass 0 ---
99 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
100 # interp 1 <0x1d4f690>, thread state <0x1d35350>: id(modules) = 139650431165784
101 # interp 2 <0x1d5a690>, thread state <0x1d99ed0>: id(modules) = 139650413140368
102 # interp 3 <0x1d4f690>, thread state <0x1dc3340>: id(modules) = 139650412862200
103 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
104 # --- Pass 1 ---
105 # ...
106
107 interp_pat = (r"^interp (\d+) <(0x[\dA-F]+)>, "
108 r"thread state <(0x[\dA-F]+)>: "
109 r"id\(modules\) = ([\d]+)$")
110 Interp = namedtuple("Interp", "id interp tstate modules")
111
112 numloops = 0
113 current_run = []
114 for line in out.splitlines():
115 if line == "--- Pass {} ---".format(numloops):
116 self.assertEqual(len(current_run), 0)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000117 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000118 print(line)
119 numloops += 1
120 continue
121
122 self.assertLess(len(current_run), 5)
123 match = re.match(interp_pat, line)
124 if match is None:
125 self.assertRegex(line, interp_pat)
126
127 # Parse the line from the loop. The first line is the main
128 # interpreter and the 3 afterward are subinterpreters.
129 interp = Interp(*match.groups())
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000130 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000131 print(interp)
132 self.assertTrue(interp.interp)
133 self.assertTrue(interp.tstate)
134 self.assertTrue(interp.modules)
135 current_run.append(interp)
136
137 # The last line in the loop should be the same as the first.
138 if len(current_run) == 5:
139 main = current_run[0]
140 self.assertEqual(interp, main)
141 yield current_run
142 current_run = []
143
Victor Stinner56b29b62018-07-26 18:57:56 +0200144
145class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase):
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000146 def test_subinterps_main(self):
147 for run in self.run_repeated_init_and_subinterpreters():
148 main = run[0]
149
150 self.assertEqual(main.id, '0')
151
152 def test_subinterps_different_ids(self):
153 for run in self.run_repeated_init_and_subinterpreters():
154 main, *subs, _ = run
155
156 mainid = int(main.id)
157 for i, sub in enumerate(subs):
158 self.assertEqual(sub.id, str(mainid + i + 1))
159
160 def test_subinterps_distinct_state(self):
161 for run in self.run_repeated_init_and_subinterpreters():
162 main, *subs, _ = run
163
164 if '0x0' in main:
165 # XXX Fix on Windows (and other platforms): something
166 # is going on with the pointers in Programs/_testembed.c.
167 # interp.interp is 0x0 and interp.modules is the same
168 # between interpreters.
169 raise unittest.SkipTest('platform prints pointers as 0x0')
170
171 for sub in subs:
172 # A new subinterpreter may have the same
173 # PyInterpreterState pointer as a previous one if
174 # the earlier one has already been destroyed. So
175 # we compare with the main interpreter. The same
176 # applies to tstate.
177 self.assertNotEqual(sub.interp, main.interp)
178 self.assertNotEqual(sub.tstate, main.tstate)
179 self.assertNotEqual(sub.modules, main.modules)
180
181 def test_forced_io_encoding(self):
182 # Checks forced configuration of embedded interpreter IO streams
183 env = dict(os.environ, PYTHONIOENCODING="utf-8:surrogateescape")
Victor Stinner5edcf262019-05-23 00:57:57 +0200184 out, err = self.run_embedded_interpreter("test_forced_io_encoding", env=env)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000185 if support.verbose > 1:
186 print()
187 print(out)
188 print(err)
189 expected_stream_encoding = "utf-8"
190 expected_errors = "surrogateescape"
191 expected_output = '\n'.join([
192 "--- Use defaults ---",
193 "Expected encoding: default",
194 "Expected errors: default",
195 "stdin: {in_encoding}:{errors}",
196 "stdout: {out_encoding}:{errors}",
197 "stderr: {out_encoding}:backslashreplace",
198 "--- Set errors only ---",
199 "Expected encoding: default",
200 "Expected errors: ignore",
201 "stdin: {in_encoding}:ignore",
202 "stdout: {out_encoding}:ignore",
203 "stderr: {out_encoding}:backslashreplace",
204 "--- Set encoding only ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200205 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000206 "Expected errors: default",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200207 "stdin: iso8859-1:{errors}",
208 "stdout: iso8859-1:{errors}",
209 "stderr: iso8859-1:backslashreplace",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000210 "--- Set encoding and errors ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200211 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000212 "Expected errors: replace",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200213 "stdin: iso8859-1:replace",
214 "stdout: iso8859-1:replace",
215 "stderr: iso8859-1:backslashreplace"])
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000216 expected_output = expected_output.format(
217 in_encoding=expected_stream_encoding,
218 out_encoding=expected_stream_encoding,
219 errors=expected_errors)
220 # This is useful if we ever trip over odd platform behaviour
221 self.maxDiff = None
222 self.assertEqual(out.strip(), expected_output)
223
224 def test_pre_initialization_api(self):
225 """
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000226 Checks some key parts of the C-API that need to work before the runtine
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000227 is initialized (via Py_Initialize()).
228 """
229 env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path))
Victor Stinner5edcf262019-05-23 00:57:57 +0200230 out, err = self.run_embedded_interpreter("test_pre_initialization_api", env=env)
Victor Stinner01de89c2018-11-14 17:39:45 +0100231 if MS_WINDOWS:
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000232 expected_path = self.test_exe
233 else:
234 expected_path = os.path.join(os.getcwd(), "spam")
235 expected_output = f"sys.executable: {expected_path}\n"
236 self.assertIn(expected_output, out)
237 self.assertEqual(err, '')
238
239 def test_pre_initialization_sys_options(self):
240 """
241 Checks that sys.warnoptions and sys._xoptions can be set before the
242 runtime is initialized (otherwise they won't be effective).
243 """
Victor Stinnerdbdc9912019-06-18 00:11:00 +0200244 env = remove_python_envvars()
245 env['PYTHONPATH'] = os.pathsep.join(sys.path)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000246 out, err = self.run_embedded_interpreter(
Victor Stinner5edcf262019-05-23 00:57:57 +0200247 "test_pre_initialization_sys_options", env=env)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000248 expected_output = (
249 "sys.warnoptions: ['once', 'module', 'default']\n"
250 "sys._xoptions: {'not_an_option': '1', 'also_not_an_option': '2'}\n"
251 "warnings.filters[:3]: ['default', 'module', 'once']\n"
252 )
253 self.assertIn(expected_output, out)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000254 self.assertEqual(err, '')
255
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100256 def test_bpo20891(self):
257 """
258 bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
259 calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must
260 call PyEval_InitThreads() for us in this case.
261 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200262 out, err = self.run_embedded_interpreter("test_bpo20891")
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100263 self.assertEqual(out, '')
264 self.assertEqual(err, '')
265
Victor Stinner209abf72018-06-22 19:14:51 +0200266 def test_initialize_twice(self):
267 """
268 bpo-33932: Calling Py_Initialize() twice should do nothing (and not
269 crash!).
270 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200271 out, err = self.run_embedded_interpreter("test_initialize_twice")
Victor Stinner209abf72018-06-22 19:14:51 +0200272 self.assertEqual(out, '')
273 self.assertEqual(err, '')
274
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200275 def test_initialize_pymain(self):
276 """
277 bpo-34008: Calling Py_Main() after Py_Initialize() must not fail.
278 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200279 out, err = self.run_embedded_interpreter("test_initialize_pymain")
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200280 self.assertEqual(out.rstrip(), "Py_Main() after Py_Initialize: sys.argv=['-c', 'arg2']")
281 self.assertEqual(err, '')
282
Victor Stinner2f549082019-03-29 15:13:46 +0100283 def test_run_main(self):
Victor Stinner5edcf262019-05-23 00:57:57 +0200284 out, err = self.run_embedded_interpreter("test_run_main")
Victor Stinner331a6a52019-05-27 16:39:22 +0200285 self.assertEqual(out.rstrip(), "Py_RunMain(): sys.argv=['-c', 'arg2']")
Victor Stinner2f549082019-03-29 15:13:46 +0100286 self.assertEqual(err, '')
287
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000288
Victor Stinner56b29b62018-07-26 18:57:56 +0200289class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
290 maxDiff = 4096
Victor Stinner01de89c2018-11-14 17:39:45 +0100291 UTF8_MODE_ERRORS = ('surrogatepass' if MS_WINDOWS else 'surrogateescape')
292
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200293 # Marker to read the default configuration: get_default_config()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100294 GET_DEFAULT_CONFIG = object()
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200295
296 # Marker to ignore a configuration parameter
297 IGNORE_CONFIG = object()
298
Victor Stinner022be022019-05-22 23:58:50 +0200299 PRE_CONFIG_COMPAT = {
Victor Stinner20e1e252019-05-23 04:12:27 +0200300 '_config_init': API_COMPAT,
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200301 'allocator': PYMEM_ALLOCATOR_NOT_SET,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200302 'parse_argv': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200303 'configure_locale': 1,
Victor Stinner1075d162019-03-25 23:19:57 +0100304 'coerce_c_locale': 0,
305 'coerce_c_locale_warn': 0,
Victor Stinner1075d162019-03-25 23:19:57 +0100306 'utf8_mode': 0,
307 }
Victor Stinner6d1c4672019-05-20 11:02:00 +0200308 if MS_WINDOWS:
Victor Stinner022be022019-05-22 23:58:50 +0200309 PRE_CONFIG_COMPAT.update({
Victor Stinner6d1c4672019-05-20 11:02:00 +0200310 'legacy_windows_fs_encoding': 0,
311 })
Victor Stinner022be022019-05-22 23:58:50 +0200312 PRE_CONFIG_PYTHON = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200313 _config_init=API_PYTHON,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200314 parse_argv=1,
Victor Stinner425717f2019-05-20 16:38:48 +0200315 coerce_c_locale=GET_DEFAULT_CONFIG,
316 utf8_mode=GET_DEFAULT_CONFIG,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200317 )
Victor Stinner022be022019-05-22 23:58:50 +0200318 PRE_CONFIG_ISOLATED = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200319 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200320 configure_locale=0,
321 isolated=1,
322 use_environment=0,
323 utf8_mode=0,
324 dev_mode=0,
Victor Stinner425717f2019-05-20 16:38:48 +0200325 coerce_c_locale=0,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200326 )
Victor Stinnerbab0db62019-05-18 03:21:27 +0200327
Victor Stinner20004952019-03-26 02:31:11 +0100328 COPY_PRE_CONFIG = [
329 'dev_mode',
330 'isolated',
331 'use_environment',
332 ]
333
Victor Stinner331a6a52019-05-27 16:39:22 +0200334 CONFIG_COMPAT = {
Victor Stinner022be022019-05-22 23:58:50 +0200335 '_config_init': API_COMPAT,
Victor Stinner20004952019-03-26 02:31:11 +0100336 'isolated': 0,
337 'use_environment': 1,
338 'dev_mode': 0,
339
Victor Stinner56b29b62018-07-26 18:57:56 +0200340 'install_signal_handlers': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200341 'use_hash_seed': 0,
342 'hash_seed': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200343 'faulthandler': 0,
344 'tracemalloc': 0,
345 'import_time': 0,
346 'show_ref_count': 0,
347 'show_alloc_count': 0,
348 'dump_refs': 0,
349 'malloc_stats': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200350
Victor Stinnera6537fb2018-11-26 11:54:12 +0100351 'filesystem_encoding': GET_DEFAULT_CONFIG,
352 'filesystem_errors': GET_DEFAULT_CONFIG,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200353
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100354 'pycache_prefix': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200355 'program_name': GET_DEFAULT_CONFIG,
Victor Stinnercab5d072019-05-17 19:01:14 +0200356 'parse_argv': 0,
Victor Stinner62599762019-03-15 16:03:23 +0100357 'argv': [""],
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100358
359 'xoptions': [],
360 'warnoptions': [],
Victor Stinner56b29b62018-07-26 18:57:56 +0200361
Victor Stinner331a6a52019-05-27 16:39:22 +0200362 'pythonpath_env': None,
Victor Stinner01de89c2018-11-14 17:39:45 +0100363 'home': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200364 'executable': GET_DEFAULT_CONFIG,
Steve Dower9048c492019-06-29 10:34:11 -0700365 'base_executable': GET_DEFAULT_CONFIG,
Victor Stinnera6537fb2018-11-26 11:54:12 +0100366
367 'prefix': GET_DEFAULT_CONFIG,
368 'base_prefix': GET_DEFAULT_CONFIG,
369 'exec_prefix': GET_DEFAULT_CONFIG,
370 'base_exec_prefix': GET_DEFAULT_CONFIG,
Victor Stinner5eb8b072019-05-15 02:12:48 +0200371 'module_search_paths': GET_DEFAULT_CONFIG,
Victor Stinner01de89c2018-11-14 17:39:45 +0100372
Victor Stinner56b29b62018-07-26 18:57:56 +0200373 'site_import': 1,
374 'bytes_warning': 0,
375 'inspect': 0,
376 'interactive': 0,
377 'optimization_level': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200378 'parser_debug': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200379 'write_bytecode': 1,
380 'verbose': 0,
381 'quiet': 0,
382 'user_site_directory': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200383 'configure_c_stdio': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200384 'buffered_stdio': 1,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200385
Victor Stinnera6537fb2018-11-26 11:54:12 +0100386 'stdio_encoding': GET_DEFAULT_CONFIG,
387 'stdio_errors': GET_DEFAULT_CONFIG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200388
Victor Stinner62be7632019-03-01 13:10:14 +0100389 'skip_source_first_line': 0,
390 'run_command': None,
391 'run_module': None,
392 'run_filename': None,
393
Victor Stinner56b29b62018-07-26 18:57:56 +0200394 '_install_importlib': 1,
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400395 'check_hash_pycs_mode': 'default',
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200396 'pathconfig_warnings': 1,
397 '_init_main': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200398 }
Victor Stinner01de89c2018-11-14 17:39:45 +0100399 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200400 CONFIG_COMPAT.update({
Victor Stinner01de89c2018-11-14 17:39:45 +0100401 'legacy_windows_stdio': 0,
402 })
403
Victor Stinner331a6a52019-05-27 16:39:22 +0200404 CONFIG_PYTHON = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200405 _config_init=API_PYTHON,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200406 configure_c_stdio=1,
407 parse_argv=1,
408 )
Victor Stinner331a6a52019-05-27 16:39:22 +0200409 CONFIG_ISOLATED = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200410 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200411 isolated=1,
412 use_environment=0,
413 user_site_directory=0,
414 dev_mode=0,
415 install_signal_handlers=0,
416 use_hash_seed=0,
417 faulthandler=0,
418 tracemalloc=0,
419 pathconfig_warnings=0,
420 )
421 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200422 CONFIG_ISOLATED['legacy_windows_stdio'] = 0
Victor Stinnerbab0db62019-05-18 03:21:27 +0200423
Victor Stinner01de89c2018-11-14 17:39:45 +0100424 # global config
425 DEFAULT_GLOBAL_CONFIG = {
426 'Py_HasFileSystemDefaultEncoding': 0,
427 'Py_HashRandomizationFlag': 1,
428 '_Py_HasFileSystemDefaultEncodeErrors': 0,
429 }
Victor Stinner1075d162019-03-25 23:19:57 +0100430 COPY_GLOBAL_PRE_CONFIG = [
Victor Stinner1075d162019-03-25 23:19:57 +0100431 ('Py_UTF8Mode', 'utf8_mode'),
432 ]
Victor Stinner01de89c2018-11-14 17:39:45 +0100433 COPY_GLOBAL_CONFIG = [
434 # Copy core config to global config for expected values
435 # True means that the core config value is inverted (0 => 1 and 1 => 0)
436 ('Py_BytesWarningFlag', 'bytes_warning'),
437 ('Py_DebugFlag', 'parser_debug'),
438 ('Py_DontWriteBytecodeFlag', 'write_bytecode', True),
439 ('Py_FileSystemDefaultEncodeErrors', 'filesystem_errors'),
440 ('Py_FileSystemDefaultEncoding', 'filesystem_encoding'),
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200441 ('Py_FrozenFlag', 'pathconfig_warnings', True),
Victor Stinner20004952019-03-26 02:31:11 +0100442 ('Py_IgnoreEnvironmentFlag', 'use_environment', True),
Victor Stinner01de89c2018-11-14 17:39:45 +0100443 ('Py_InspectFlag', 'inspect'),
444 ('Py_InteractiveFlag', 'interactive'),
Victor Stinner20004952019-03-26 02:31:11 +0100445 ('Py_IsolatedFlag', 'isolated'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100446 ('Py_NoSiteFlag', 'site_import', True),
447 ('Py_NoUserSiteDirectory', 'user_site_directory', True),
448 ('Py_OptimizeFlag', 'optimization_level'),
449 ('Py_QuietFlag', 'quiet'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100450 ('Py_UnbufferedStdioFlag', 'buffered_stdio', True),
451 ('Py_VerboseFlag', 'verbose'),
452 ]
453 if MS_WINDOWS:
Victor Stinner1075d162019-03-25 23:19:57 +0100454 COPY_GLOBAL_PRE_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100455 ('Py_LegacyWindowsFSEncodingFlag', 'legacy_windows_fs_encoding'),
Victor Stinner1075d162019-03-25 23:19:57 +0100456 ))
457 COPY_GLOBAL_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100458 ('Py_LegacyWindowsStdioFlag', 'legacy_windows_stdio'),
459 ))
Victor Stinner56b29b62018-07-26 18:57:56 +0200460
Victor Stinner425717f2019-05-20 16:38:48 +0200461 EXPECTED_CONFIG = None
462
Victor Stinner01de89c2018-11-14 17:39:45 +0100463 def main_xoptions(self, xoptions_list):
464 xoptions = {}
465 for opt in xoptions_list:
466 if '=' in opt:
467 key, value = opt.split('=', 1)
468 xoptions[key] = value
469 else:
470 xoptions[opt] = True
471 return xoptions
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200472
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200473 def _get_expected_config_impl(self):
474 env = remove_python_envvars()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100475 code = textwrap.dedent('''
476 import json
Victor Stinnera6537fb2018-11-26 11:54:12 +0100477 import sys
Victor Stinner5eb8b072019-05-15 02:12:48 +0200478 import _testinternalcapi
Victor Stinnera6537fb2018-11-26 11:54:12 +0100479
Victor Stinner5eb8b072019-05-15 02:12:48 +0200480 configs = _testinternalcapi.get_configs()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100481
Victor Stinner425717f2019-05-20 16:38:48 +0200482 data = json.dumps(configs)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100483 data = data.encode('utf-8')
484 sys.stdout.buffer.write(data)
485 sys.stdout.buffer.flush()
486 ''')
487
488 # Use -S to not import the site module: get the proper configuration
489 # when test_embed is run from a venv (bpo-35313)
Victor Stinner5eb8b072019-05-15 02:12:48 +0200490 args = [sys.executable, '-S', '-c', code]
Victor Stinnera6537fb2018-11-26 11:54:12 +0100491 proc = subprocess.run(args, env=env,
492 stdout=subprocess.PIPE,
493 stderr=subprocess.STDOUT)
494 if proc.returncode:
495 raise Exception(f"failed to get the default config: "
496 f"stdout={proc.stdout!r} stderr={proc.stderr!r}")
497 stdout = proc.stdout.decode('utf-8')
Victor Stinner4631da12019-05-02 15:30:21 -0400498 try:
Victor Stinner425717f2019-05-20 16:38:48 +0200499 return json.loads(stdout)
Victor Stinner4631da12019-05-02 15:30:21 -0400500 except json.JSONDecodeError:
501 self.fail(f"fail to decode stdout: {stdout!r}")
Victor Stinnera6537fb2018-11-26 11:54:12 +0100502
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200503 def _get_expected_config(self):
504 cls = InitConfigTests
505 if cls.EXPECTED_CONFIG is None:
506 cls.EXPECTED_CONFIG = self._get_expected_config_impl()
507
508 # get a copy
509 return {key: dict(value)
510 for key, value in cls.EXPECTED_CONFIG.items()}
511
Victor Stinner425717f2019-05-20 16:38:48 +0200512 def get_expected_config(self, expected_preconfig, expected, env, api,
Victor Stinner3842f292019-08-23 16:57:54 +0100513 modify_path_cb=None):
Victor Stinner425717f2019-05-20 16:38:48 +0200514 cls = self.__class__
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200515 configs = self._get_expected_config()
Victor Stinner425717f2019-05-20 16:38:48 +0200516
517 pre_config = configs['pre_config']
518 for key, value in expected_preconfig.items():
519 if value is self.GET_DEFAULT_CONFIG:
520 expected_preconfig[key] = pre_config[key]
521
Victor Stinner022be022019-05-22 23:58:50 +0200522 if not expected_preconfig['configure_locale'] or api == API_COMPAT:
Victor Stinner425717f2019-05-20 16:38:48 +0200523 # there is no easy way to get the locale encoding before
524 # setlocale(LC_CTYPE, "") is called: don't test encodings
525 for key in ('filesystem_encoding', 'filesystem_errors',
526 'stdio_encoding', 'stdio_errors'):
527 expected[key] = self.IGNORE_CONFIG
528
529 if not expected_preconfig['configure_locale']:
530 # UTF-8 Mode depends on the locale. There is no easy way
531 # to guess if UTF-8 Mode will be enabled or not if the locale
532 # is not configured.
533 expected_preconfig['utf8_mode'] = self.IGNORE_CONFIG
534
535 if expected_preconfig['utf8_mode'] == 1:
536 if expected['filesystem_encoding'] is self.GET_DEFAULT_CONFIG:
537 expected['filesystem_encoding'] = 'utf-8'
538 if expected['filesystem_errors'] is self.GET_DEFAULT_CONFIG:
539 expected['filesystem_errors'] = self.UTF8_MODE_ERRORS
540 if expected['stdio_encoding'] is self.GET_DEFAULT_CONFIG:
541 expected['stdio_encoding'] = 'utf-8'
542 if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG:
543 expected['stdio_errors'] = 'surrogateescape'
544
Steve Dower9048c492019-06-29 10:34:11 -0700545 if sys.platform == 'win32':
546 default_executable = self.test_exe
547 elif expected['program_name'] is not self.GET_DEFAULT_CONFIG:
548 default_executable = os.path.abspath(expected['program_name'])
549 else:
550 default_executable = os.path.join(os.getcwd(), '_testembed')
Victor Stinner91c99872019-05-14 22:01:51 +0200551 if expected['executable'] is self.GET_DEFAULT_CONFIG:
Steve Dower9048c492019-06-29 10:34:11 -0700552 expected['executable'] = default_executable
553 if expected['base_executable'] is self.GET_DEFAULT_CONFIG:
554 expected['base_executable'] = default_executable
Victor Stinner91c99872019-05-14 22:01:51 +0200555 if expected['program_name'] is self.GET_DEFAULT_CONFIG:
556 expected['program_name'] = './_testembed'
557
Victor Stinner331a6a52019-05-27 16:39:22 +0200558 config = configs['config']
Victor Stinnera6537fb2018-11-26 11:54:12 +0100559 for key, value in expected.items():
560 if value is self.GET_DEFAULT_CONFIG:
Victor Stinner331a6a52019-05-27 16:39:22 +0200561 expected[key] = config[key]
Victor Stinner5eb8b072019-05-15 02:12:48 +0200562
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200563 pythonpath_env = expected['pythonpath_env']
564 if pythonpath_env is not None:
565 paths = pythonpath_env.split(os.path.pathsep)
566 expected['module_search_paths'] = [*paths, *expected['module_search_paths']]
Victor Stinner3842f292019-08-23 16:57:54 +0100567 if modify_path_cb is not None:
568 expected['module_search_paths'] = expected['module_search_paths'].copy()
569 modify_path_cb(expected['module_search_paths'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200570
Victor Stinner425717f2019-05-20 16:38:48 +0200571 for key in self.COPY_PRE_CONFIG:
572 if key not in expected_preconfig:
573 expected_preconfig[key] = expected[key]
Victor Stinner01de89c2018-11-14 17:39:45 +0100574
Victor Stinner331a6a52019-05-27 16:39:22 +0200575 def check_pre_config(self, configs, expected):
576 pre_config = dict(configs['pre_config'])
Victor Stinner425717f2019-05-20 16:38:48 +0200577 for key, value in list(expected.items()):
578 if value is self.IGNORE_CONFIG:
579 del pre_config[key]
580 del expected[key]
581 self.assertEqual(pre_config, expected)
Victor Stinner1075d162019-03-25 23:19:57 +0100582
Victor Stinner331a6a52019-05-27 16:39:22 +0200583 def check_config(self, configs, expected):
584 config = dict(configs['config'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200585 for key, value in list(expected.items()):
586 if value is self.IGNORE_CONFIG:
Victor Stinner331a6a52019-05-27 16:39:22 +0200587 del config[key]
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200588 del expected[key]
Victor Stinner331a6a52019-05-27 16:39:22 +0200589 self.assertEqual(config, expected)
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200590
Victor Stinner331a6a52019-05-27 16:39:22 +0200591 def check_global_config(self, configs):
592 pre_config = configs['pre_config']
593 config = configs['config']
Victor Stinner00b137c2018-11-13 19:59:26 +0100594
Victor Stinnera6537fb2018-11-26 11:54:12 +0100595 expected = dict(self.DEFAULT_GLOBAL_CONFIG)
Victor Stinner01de89c2018-11-14 17:39:45 +0100596 for item in self.COPY_GLOBAL_CONFIG:
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100597 if len(item) == 3:
598 global_key, core_key, opposite = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200599 expected[global_key] = 0 if config[core_key] else 1
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100600 else:
601 global_key, core_key = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200602 expected[global_key] = config[core_key]
Victor Stinner1075d162019-03-25 23:19:57 +0100603 for item in self.COPY_GLOBAL_PRE_CONFIG:
604 if len(item) == 3:
605 global_key, core_key, opposite = item
606 expected[global_key] = 0 if pre_config[core_key] else 1
607 else:
608 global_key, core_key = item
609 expected[global_key] = pre_config[core_key]
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100610
Victor Stinner331a6a52019-05-27 16:39:22 +0200611 self.assertEqual(configs['global_config'], expected)
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100612
Victor Stinner331a6a52019-05-27 16:39:22 +0200613 def check_all_configs(self, testname, expected_config=None,
Victor Stinner3842f292019-08-23 16:57:54 +0100614 expected_preconfig=None, modify_path_cb=None, stderr=None,
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200615 *, api, env=None, ignore_stderr=False):
616 new_env = remove_python_envvars()
617 if env is not None:
618 new_env.update(env)
619 env = new_env
Victor Stinner01de89c2018-11-14 17:39:45 +0100620
Victor Stinner022be022019-05-22 23:58:50 +0200621 if api == API_ISOLATED:
622 default_preconfig = self.PRE_CONFIG_ISOLATED
623 elif api == API_PYTHON:
624 default_preconfig = self.PRE_CONFIG_PYTHON
Victor Stinnerbab0db62019-05-18 03:21:27 +0200625 else:
Victor Stinner022be022019-05-22 23:58:50 +0200626 default_preconfig = self.PRE_CONFIG_COMPAT
Victor Stinnerbab0db62019-05-18 03:21:27 +0200627 if expected_preconfig is None:
628 expected_preconfig = {}
629 expected_preconfig = dict(default_preconfig, **expected_preconfig)
630 if expected_config is None:
631 expected_config = {}
Victor Stinner425717f2019-05-20 16:38:48 +0200632
Victor Stinner022be022019-05-22 23:58:50 +0200633 if api == API_PYTHON:
Victor Stinner331a6a52019-05-27 16:39:22 +0200634 default_config = self.CONFIG_PYTHON
Victor Stinner022be022019-05-22 23:58:50 +0200635 elif api == API_ISOLATED:
Victor Stinner331a6a52019-05-27 16:39:22 +0200636 default_config = self.CONFIG_ISOLATED
Victor Stinner425717f2019-05-20 16:38:48 +0200637 else:
Victor Stinner331a6a52019-05-27 16:39:22 +0200638 default_config = self.CONFIG_COMPAT
Victor Stinner425717f2019-05-20 16:38:48 +0200639 expected_config = dict(default_config, **expected_config)
Victor Stinner425717f2019-05-20 16:38:48 +0200640
641 self.get_expected_config(expected_preconfig,
642 expected_config, env,
Victor Stinner3842f292019-08-23 16:57:54 +0100643 api, modify_path_cb)
Victor Stinner1075d162019-03-25 23:19:57 +0100644
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200645 out, err = self.run_embedded_interpreter(testname, env=env)
646 if stderr is None and not expected_config['verbose']:
647 stderr = ""
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200648 if stderr is not None and not ignore_stderr:
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200649 self.assertEqual(err.rstrip(), stderr)
650 try:
Victor Stinner331a6a52019-05-27 16:39:22 +0200651 configs = json.loads(out)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200652 except json.JSONDecodeError:
653 self.fail(f"fail to decode stdout: {out!r}")
654
Victor Stinner331a6a52019-05-27 16:39:22 +0200655 self.check_pre_config(configs, expected_preconfig)
656 self.check_config(configs, expected_config)
657 self.check_global_config(configs)
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100658
Victor Stinner56b29b62018-07-26 18:57:56 +0200659 def test_init_default_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200660 self.check_all_configs("test_init_initialize_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200661
662 def test_preinit_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200663 self.check_all_configs("test_preinit_compat_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200664
665 def test_init_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200666 self.check_all_configs("test_init_compat_config", api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200667
668 def test_init_global_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100669 preconfig = {
670 'utf8_mode': 1,
671 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200672 config = {
673 'program_name': './globalvar',
674 'site_import': 0,
675 'bytes_warning': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100676 'warnoptions': ['default::BytesWarning'],
Victor Stinner56b29b62018-07-26 18:57:56 +0200677 'inspect': 1,
678 'interactive': 1,
679 'optimization_level': 2,
680 'write_bytecode': 0,
681 'verbose': 1,
682 'quiet': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200683 'buffered_stdio': 0,
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200684
Victor Stinner56b29b62018-07-26 18:57:56 +0200685 'user_site_directory': 0,
Victor Stinner54b43bb2019-05-16 18:30:15 +0200686 'pathconfig_warnings': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200687 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200688 self.check_all_configs("test_init_global_config", config, preconfig,
689 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200690
691 def test_init_from_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100692 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200693 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner1075d162019-03-25 23:19:57 +0100694 'utf8_mode': 1,
695 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200696 config = {
697 'install_signal_handlers': 0,
698 'use_hash_seed': 1,
699 'hash_seed': 123,
Victor Stinner56b29b62018-07-26 18:57:56 +0200700 'tracemalloc': 2,
701 'import_time': 1,
702 'show_ref_count': 1,
703 'show_alloc_count': 1,
704 'malloc_stats': 1,
705
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200706 'stdio_encoding': 'iso8859-1',
707 'stdio_errors': 'replace',
Victor Stinner56b29b62018-07-26 18:57:56 +0200708
709 'pycache_prefix': 'conf_pycache_prefix',
710 'program_name': './conf_program_name',
Victor Stinner67310022019-07-01 19:52:45 +0200711 'argv': ['-c', 'arg2', ],
Victor Stinnercab5d072019-05-17 19:01:14 +0200712 'parse_argv': 1,
Victor Stinner67310022019-07-01 19:52:45 +0200713 'xoptions': [
714 'config_xoption1=3',
715 'config_xoption2=',
716 'config_xoption3',
717 'cmdline_xoption',
718 ],
719 'warnoptions': [
720 'config_warnoption',
721 'cmdline_warnoption',
722 'default::BytesWarning',
723 ],
Victor Stinner2f549082019-03-29 15:13:46 +0100724 'run_command': 'pass\n',
Victor Stinner56b29b62018-07-26 18:57:56 +0200725
726 'site_import': 0,
727 'bytes_warning': 1,
728 'inspect': 1,
729 'interactive': 1,
730 'optimization_level': 2,
731 'write_bytecode': 0,
732 'verbose': 1,
733 'quiet': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200734 'configure_c_stdio': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200735 'buffered_stdio': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200736 'user_site_directory': 0,
737 'faulthandler': 1,
Victor Stinnerb75d7e22018-08-01 02:13:04 +0200738
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400739 'check_hash_pycs_mode': 'always',
Victor Stinner54b43bb2019-05-16 18:30:15 +0200740 'pathconfig_warnings': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200741 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200742 self.check_all_configs("test_init_from_config", config, preconfig,
743 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200744
Victor Stinner20e1e252019-05-23 04:12:27 +0200745 def test_init_compat_env(self):
746 preconfig = {
747 'allocator': PYMEM_ALLOCATOR_MALLOC,
748 }
749 config = {
750 'use_hash_seed': 1,
751 'hash_seed': 42,
752 'tracemalloc': 2,
753 'import_time': 1,
754 'malloc_stats': 1,
755 'inspect': 1,
756 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200757 'pythonpath_env': '/my/path',
Victor Stinner20e1e252019-05-23 04:12:27 +0200758 'pycache_prefix': 'env_pycache_prefix',
759 'write_bytecode': 0,
760 'verbose': 1,
761 'buffered_stdio': 0,
762 'stdio_encoding': 'iso8859-1',
763 'stdio_errors': 'replace',
764 'user_site_directory': 0,
765 'faulthandler': 1,
766 'warnoptions': ['EnvVar'],
767 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200768 self.check_all_configs("test_init_compat_env", config, preconfig,
769 api=API_COMPAT)
Victor Stinner20e1e252019-05-23 04:12:27 +0200770
771 def test_init_python_env(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200772 preconfig = {
773 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner022be022019-05-22 23:58:50 +0200774 'utf8_mode': 1,
Victor Stinner425717f2019-05-20 16:38:48 +0200775 }
776 config = {
777 'use_hash_seed': 1,
778 'hash_seed': 42,
779 'tracemalloc': 2,
780 'import_time': 1,
781 'malloc_stats': 1,
782 'inspect': 1,
783 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200784 'pythonpath_env': '/my/path',
Victor Stinner425717f2019-05-20 16:38:48 +0200785 'pycache_prefix': 'env_pycache_prefix',
786 'write_bytecode': 0,
787 'verbose': 1,
788 'buffered_stdio': 0,
789 'stdio_encoding': 'iso8859-1',
790 'stdio_errors': 'replace',
791 'user_site_directory': 0,
792 'faulthandler': 1,
793 'warnoptions': ['EnvVar'],
794 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200795 self.check_all_configs("test_init_python_env", config, preconfig,
796 api=API_PYTHON)
Victor Stinnerb35be4b2019-03-05 17:37:44 +0100797
798 def test_init_env_dev_mode(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200799 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
800 config = dict(dev_mode=1,
801 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100802 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200803 self.check_all_configs("test_init_env_dev_mode", config, preconfig,
804 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200805
Victor Stinner20004952019-03-26 02:31:11 +0100806 def test_init_env_dev_mode_alloc(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200807 preconfig = dict(allocator=PYMEM_ALLOCATOR_MALLOC)
808 config = dict(dev_mode=1,
809 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100810 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200811 self.check_all_configs("test_init_env_dev_mode_alloc", config, preconfig,
812 api=API_COMPAT)
Victor Stinner25d13f32019-03-06 12:51:53 +0100813
Victor Stinner56b29b62018-07-26 18:57:56 +0200814 def test_init_dev_mode(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100815 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200816 'allocator': PYMEM_ALLOCATOR_DEBUG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200817 }
Victor Stinner1075d162019-03-25 23:19:57 +0100818 config = {
819 'faulthandler': 1,
Victor Stinner20004952019-03-26 02:31:11 +0100820 'dev_mode': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100821 'warnoptions': ['default'],
Victor Stinner1075d162019-03-25 23:19:57 +0100822 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200823 self.check_all_configs("test_init_dev_mode", config, preconfig,
824 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200825
826 def test_preinit_parse_argv(self):
827 # Pre-initialize implicitly using argv: make sure that -X dev
828 # is used to configure the allocation in preinitialization
829 preconfig = {
830 'allocator': PYMEM_ALLOCATOR_DEBUG,
831 }
Victor Stinner3939c322019-06-25 15:02:43 +0200832 script_abspath = os.path.abspath('script.py')
Victor Stinner6d1c4672019-05-20 11:02:00 +0200833 config = {
Victor Stinner3939c322019-06-25 15:02:43 +0200834 'argv': [script_abspath],
835 'run_filename': script_abspath,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200836 'dev_mode': 1,
837 'faulthandler': 1,
838 'warnoptions': ['default'],
839 'xoptions': ['dev'],
840 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200841 self.check_all_configs("test_preinit_parse_argv", config, preconfig,
842 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200843
844 def test_preinit_dont_parse_argv(self):
845 # -X dev must be ignored by isolated preconfiguration
846 preconfig = {
847 'isolated': 0,
848 }
849 config = {
850 'argv': ["python3", "-E", "-I",
851 "-X", "dev", "-X", "utf8", "script.py"],
852 'isolated': 0,
853 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200854 self.check_all_configs("test_preinit_dont_parse_argv", config, preconfig,
855 api=API_ISOLATED)
Victor Stinner56b29b62018-07-26 18:57:56 +0200856
Victor Stinnercab5d072019-05-17 19:01:14 +0200857 def test_init_isolated_flag(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100858 config = {
Victor Stinner20004952019-03-26 02:31:11 +0100859 'isolated': 1,
860 'use_environment': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200861 'user_site_directory': 0,
862 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200863 self.check_all_configs("test_init_isolated_flag", config, api=API_PYTHON)
Victor Stinner56b29b62018-07-26 18:57:56 +0200864
Victor Stinner6da20a42019-03-27 00:26:18 +0100865 def test_preinit_isolated1(self):
866 # _PyPreConfig.isolated=1, _PyCoreConfig.isolated not set
Victor Stinner6da20a42019-03-27 00:26:18 +0100867 config = {
868 'isolated': 1,
869 'use_environment': 0,
870 'user_site_directory': 0,
871 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200872 self.check_all_configs("test_preinit_isolated1", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100873
874 def test_preinit_isolated2(self):
875 # _PyPreConfig.isolated=0, _PyCoreConfig.isolated=1
Victor Stinner6da20a42019-03-27 00:26:18 +0100876 config = {
877 'isolated': 1,
878 'use_environment': 0,
879 'user_site_directory': 0,
880 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200881 self.check_all_configs("test_preinit_isolated2", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100882
Victor Stinner6d1c4672019-05-20 11:02:00 +0200883 def test_preinit_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200884 self.check_all_configs("test_preinit_isolated_config", api=API_ISOLATED)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200885
Victor Stinnercab5d072019-05-17 19:01:14 +0200886 def test_init_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200887 self.check_all_configs("test_init_isolated_config", api=API_ISOLATED)
Victor Stinner5edcf262019-05-23 00:57:57 +0200888
889 def test_preinit_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200890 self.check_all_configs("test_preinit_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200891
892 def test_init_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200893 self.check_all_configs("test_init_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200894
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200895 def test_init_dont_configure_locale(self):
896 # _PyPreConfig.configure_locale=0
897 preconfig = {
898 'configure_locale': 0,
Victor Stinner425717f2019-05-20 16:38:48 +0200899 'coerce_c_locale': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200900 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200901 self.check_all_configs("test_init_dont_configure_locale", {}, preconfig,
902 api=API_PYTHON)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200903
Victor Stinner91c99872019-05-14 22:01:51 +0200904 def test_init_read_set(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200905 config = {
Victor Stinner91c99872019-05-14 22:01:51 +0200906 'program_name': './init_read_set',
907 'executable': 'my_executable',
908 }
Victor Stinner3842f292019-08-23 16:57:54 +0100909 def modify_path(path):
910 path.insert(1, "test_path_insert1")
911 path.append("test_path_append")
Victor Stinner331a6a52019-05-27 16:39:22 +0200912 self.check_all_configs("test_init_read_set", config,
913 api=API_PYTHON,
Victor Stinner3842f292019-08-23 16:57:54 +0100914 modify_path_cb=modify_path)
Victor Stinner91c99872019-05-14 22:01:51 +0200915
Victor Stinner120b7072019-08-23 18:03:08 +0100916 def test_init_sys_add(self):
917 config = {
918 'faulthandler': 1,
919 'xoptions': [
920 'config_xoption',
921 'cmdline_xoption',
922 'sysadd_xoption',
923 'faulthandler',
924 ],
925 'warnoptions': [
926 'ignore:::config_warnoption',
927 'ignore:::cmdline_warnoption',
928 'ignore:::sysadd_warnoption',
929 ],
930 }
931 self.check_all_configs("test_init_sys_add", config, api=API_PYTHON)
932
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200933 def test_init_run_main(self):
Victor Stinner5eb8b072019-05-15 02:12:48 +0200934 code = ('import _testinternalcapi, json; '
935 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +0200936 config = {
Victor Stinner5eb8b072019-05-15 02:12:48 +0200937 'argv': ['-c', 'arg2'],
Victor Stinner5eb8b072019-05-15 02:12:48 +0200938 'program_name': './python3',
939 'run_command': code + '\n',
Victor Stinnercab5d072019-05-17 19:01:14 +0200940 'parse_argv': 1,
Victor Stinner5eb8b072019-05-15 02:12:48 +0200941 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200942 self.check_all_configs("test_init_run_main", config, api=API_PYTHON)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200943
944 def test_init_main(self):
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200945 code = ('import _testinternalcapi, json; '
946 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +0200947 config = {
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200948 'argv': ['-c', 'arg2'],
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200949 'program_name': './python3',
950 'run_command': code + '\n',
Victor Stinnercab5d072019-05-17 19:01:14 +0200951 'parse_argv': 1,
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200952 '_init_main': 0,
953 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200954 self.check_all_configs("test_init_main", config,
955 api=API_PYTHON,
956 stderr="Run Python code before _Py_InitializeMain")
Victor Stinner5eb8b072019-05-15 02:12:48 +0200957
Victor Stinnercab5d072019-05-17 19:01:14 +0200958 def test_init_parse_argv(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200959 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +0200960 'parse_argv': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200961 'argv': ['-c', 'arg1', '-v', 'arg3'],
962 'program_name': './argv0',
Victor Stinnercab5d072019-05-17 19:01:14 +0200963 'run_command': 'pass\n',
964 'use_environment': 0,
965 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200966 self.check_all_configs("test_init_parse_argv", config, api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200967
Victor Stinnerae239f62019-05-16 17:02:56 +0200968 def test_init_dont_parse_argv(self):
Victor Stinner6d1c4672019-05-20 11:02:00 +0200969 pre_config = {
970 'parse_argv': 0,
971 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200972 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +0200973 'parse_argv': 0,
Victor Stinnercab5d072019-05-17 19:01:14 +0200974 'argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
975 'program_name': './argv0',
Victor Stinnerae239f62019-05-16 17:02:56 +0200976 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200977 self.check_all_configs("test_init_dont_parse_argv", config, pre_config,
978 api=API_PYTHON)
Victor Stinnerae239f62019-05-16 17:02:56 +0200979
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200980 def test_init_setpath(self):
981 # Test Py_SetProgramName() + Py_SetPath()
982 config = self._get_expected_config()
983 paths = config['config']['module_search_paths']
984
985 config = {
986 'module_search_paths': paths,
987 'prefix': '',
988 'base_prefix': '',
989 'exec_prefix': '',
990 'base_exec_prefix': '',
991 }
992 env = {'TESTPATH': os.path.pathsep.join(paths)}
993 self.check_all_configs("test_init_setpath", config,
994 api=API_COMPAT, env=env,
995 ignore_stderr=True)
996
997 def test_init_setpythonhome(self):
998 # Test Py_SetPythonHome(home) + PYTHONPATH env var
999 # + Py_SetProgramName()
1000 config = self._get_expected_config()
1001 paths = config['config']['module_search_paths']
1002 paths_str = os.path.pathsep.join(paths)
1003
1004 for path in paths:
1005 if not os.path.isdir(path):
1006 continue
1007 if os.path.exists(os.path.join(path, 'os.py')):
1008 home = os.path.dirname(path)
1009 break
1010 else:
1011 self.fail(f"Unable to find home in {paths!r}")
1012
1013 prefix = exec_prefix = home
1014 ver = sys.version_info
1015 if MS_WINDOWS:
1016 expected_paths = paths
1017 else:
1018 expected_paths = [
1019 os.path.join(prefix, 'lib', f'python{ver.major}{ver.minor}.zip'),
1020 os.path.join(home, 'lib', f'python{ver.major}.{ver.minor}'),
1021 os.path.join(home, 'lib', f'python{ver.major}.{ver.minor}/lib-dynload')]
1022
1023 config = {
1024 'home': home,
1025 'module_search_paths': expected_paths,
1026 'prefix': prefix,
1027 'base_prefix': prefix,
1028 'exec_prefix': exec_prefix,
1029 'base_exec_prefix': exec_prefix,
1030 'pythonpath_env': paths_str,
1031 }
1032 env = {'TESTHOME': home, 'TESTPATH': paths_str}
1033 self.check_all_configs("test_init_setpythonhome", config,
1034 api=API_COMPAT, env=env)
1035
Victor Stinner56b29b62018-07-26 18:57:56 +02001036
Steve Dowerb82e17e2019-05-23 08:45:22 -07001037class AuditingTests(EmbeddingTestsMixin, unittest.TestCase):
1038 def test_open_code_hook(self):
1039 self.run_embedded_interpreter("test_open_code_hook")
1040
1041 def test_audit(self):
1042 self.run_embedded_interpreter("test_audit")
1043
1044 def test_audit_subinterpreter(self):
1045 self.run_embedded_interpreter("test_audit_subinterpreter")
1046
Steve Dowere226e832019-07-01 16:03:53 -07001047 def test_audit_run_command(self):
1048 self.run_embedded_interpreter("test_audit_run_command", timeout=3, returncode=1)
1049
1050 def test_audit_run_file(self):
1051 self.run_embedded_interpreter("test_audit_run_file", timeout=3, returncode=1)
1052
1053 def test_audit_run_interactivehook(self):
1054 startup = os.path.join(self.oldcwd, support.TESTFN) + ".py"
1055 with open(startup, "w", encoding="utf-8") as f:
1056 print("import sys", file=f)
1057 print("sys.__interactivehook__ = lambda: None", file=f)
1058 try:
1059 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
1060 self.run_embedded_interpreter("test_audit_run_interactivehook", timeout=5,
1061 returncode=10, env=env)
1062 finally:
1063 os.unlink(startup)
1064
1065 def test_audit_run_startup(self):
1066 startup = os.path.join(self.oldcwd, support.TESTFN) + ".py"
1067 with open(startup, "w", encoding="utf-8") as f:
1068 print("pass", file=f)
1069 try:
1070 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
1071 self.run_embedded_interpreter("test_audit_run_startup", timeout=5,
1072 returncode=10, env=env)
1073 finally:
1074 os.unlink(startup)
1075
1076 def test_audit_run_stdin(self):
1077 self.run_embedded_interpreter("test_audit_run_stdin", timeout=3, returncode=1)
Steve Dowerb82e17e2019-05-23 08:45:22 -07001078
Nick Coghlan39f0bb52017-11-28 08:11:51 +10001079if __name__ == "__main__":
1080 unittest.main()