blob: e1cf4be506685a601d8616c962d99857c8e2f2b2 [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
60 def run_embedded_interpreter(self, *args, env=None):
61 """Runs a test in the embedded interpreter"""
62 cmd = [self.test_exe]
63 cmd.extend(args)
Victor Stinner01de89c2018-11-14 17:39:45 +010064 if env is not None and MS_WINDOWS:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100065 # Windows requires at least the SYSTEMROOT environment variable to
66 # start Python.
67 env = env.copy()
68 env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
69
70 p = subprocess.Popen(cmd,
71 stdout=subprocess.PIPE,
72 stderr=subprocess.PIPE,
73 universal_newlines=True,
74 env=env)
Victor Stinner2f549082019-03-29 15:13:46 +010075 try:
76 (out, err) = p.communicate()
77 except:
78 p.terminate()
79 p.wait()
80 raise
Nick Coghlan39f0bb52017-11-28 08:11:51 +100081 if p.returncode != 0 and support.verbose:
82 print(f"--- {cmd} failed ---")
83 print(f"stdout:\n{out}")
Nick Coghlanbc77eff2018-03-25 20:44:30 +100084 print(f"stderr:\n{err}")
Nick Coghlan39f0bb52017-11-28 08:11:51 +100085 print(f"------")
86
87 self.assertEqual(p.returncode, 0,
88 "bad returncode %d, stderr is %r" %
89 (p.returncode, err))
90 return out, err
91
92 def run_repeated_init_and_subinterpreters(self):
Victor Stinner5edcf262019-05-23 00:57:57 +020093 out, err = self.run_embedded_interpreter("test_repeated_init_and_subinterpreters")
Nick Coghlan39f0bb52017-11-28 08:11:51 +100094 self.assertEqual(err, "")
95
96 # The output from _testembed looks like this:
97 # --- Pass 0 ---
98 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
99 # interp 1 <0x1d4f690>, thread state <0x1d35350>: id(modules) = 139650431165784
100 # interp 2 <0x1d5a690>, thread state <0x1d99ed0>: id(modules) = 139650413140368
101 # interp 3 <0x1d4f690>, thread state <0x1dc3340>: id(modules) = 139650412862200
102 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
103 # --- Pass 1 ---
104 # ...
105
106 interp_pat = (r"^interp (\d+) <(0x[\dA-F]+)>, "
107 r"thread state <(0x[\dA-F]+)>: "
108 r"id\(modules\) = ([\d]+)$")
109 Interp = namedtuple("Interp", "id interp tstate modules")
110
111 numloops = 0
112 current_run = []
113 for line in out.splitlines():
114 if line == "--- Pass {} ---".format(numloops):
115 self.assertEqual(len(current_run), 0)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000116 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000117 print(line)
118 numloops += 1
119 continue
120
121 self.assertLess(len(current_run), 5)
122 match = re.match(interp_pat, line)
123 if match is None:
124 self.assertRegex(line, interp_pat)
125
126 # Parse the line from the loop. The first line is the main
127 # interpreter and the 3 afterward are subinterpreters.
128 interp = Interp(*match.groups())
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000129 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000130 print(interp)
131 self.assertTrue(interp.interp)
132 self.assertTrue(interp.tstate)
133 self.assertTrue(interp.modules)
134 current_run.append(interp)
135
136 # The last line in the loop should be the same as the first.
137 if len(current_run) == 5:
138 main = current_run[0]
139 self.assertEqual(interp, main)
140 yield current_run
141 current_run = []
142
Victor Stinner56b29b62018-07-26 18:57:56 +0200143
144class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase):
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000145 def test_subinterps_main(self):
146 for run in self.run_repeated_init_and_subinterpreters():
147 main = run[0]
148
149 self.assertEqual(main.id, '0')
150
151 def test_subinterps_different_ids(self):
152 for run in self.run_repeated_init_and_subinterpreters():
153 main, *subs, _ = run
154
155 mainid = int(main.id)
156 for i, sub in enumerate(subs):
157 self.assertEqual(sub.id, str(mainid + i + 1))
158
159 def test_subinterps_distinct_state(self):
160 for run in self.run_repeated_init_and_subinterpreters():
161 main, *subs, _ = run
162
163 if '0x0' in main:
164 # XXX Fix on Windows (and other platforms): something
165 # is going on with the pointers in Programs/_testembed.c.
166 # interp.interp is 0x0 and interp.modules is the same
167 # between interpreters.
168 raise unittest.SkipTest('platform prints pointers as 0x0')
169
170 for sub in subs:
171 # A new subinterpreter may have the same
172 # PyInterpreterState pointer as a previous one if
173 # the earlier one has already been destroyed. So
174 # we compare with the main interpreter. The same
175 # applies to tstate.
176 self.assertNotEqual(sub.interp, main.interp)
177 self.assertNotEqual(sub.tstate, main.tstate)
178 self.assertNotEqual(sub.modules, main.modules)
179
180 def test_forced_io_encoding(self):
181 # Checks forced configuration of embedded interpreter IO streams
182 env = dict(os.environ, PYTHONIOENCODING="utf-8:surrogateescape")
Victor Stinner5edcf262019-05-23 00:57:57 +0200183 out, err = self.run_embedded_interpreter("test_forced_io_encoding", env=env)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000184 if support.verbose > 1:
185 print()
186 print(out)
187 print(err)
188 expected_stream_encoding = "utf-8"
189 expected_errors = "surrogateescape"
190 expected_output = '\n'.join([
191 "--- Use defaults ---",
192 "Expected encoding: default",
193 "Expected errors: default",
194 "stdin: {in_encoding}:{errors}",
195 "stdout: {out_encoding}:{errors}",
196 "stderr: {out_encoding}:backslashreplace",
197 "--- Set errors only ---",
198 "Expected encoding: default",
199 "Expected errors: ignore",
200 "stdin: {in_encoding}:ignore",
201 "stdout: {out_encoding}:ignore",
202 "stderr: {out_encoding}:backslashreplace",
203 "--- Set encoding only ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200204 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000205 "Expected errors: default",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200206 "stdin: iso8859-1:{errors}",
207 "stdout: iso8859-1:{errors}",
208 "stderr: iso8859-1:backslashreplace",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000209 "--- Set encoding and errors ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200210 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000211 "Expected errors: replace",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200212 "stdin: iso8859-1:replace",
213 "stdout: iso8859-1:replace",
214 "stderr: iso8859-1:backslashreplace"])
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000215 expected_output = expected_output.format(
216 in_encoding=expected_stream_encoding,
217 out_encoding=expected_stream_encoding,
218 errors=expected_errors)
219 # This is useful if we ever trip over odd platform behaviour
220 self.maxDiff = None
221 self.assertEqual(out.strip(), expected_output)
222
223 def test_pre_initialization_api(self):
224 """
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000225 Checks some key parts of the C-API that need to work before the runtine
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000226 is initialized (via Py_Initialize()).
227 """
228 env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path))
Victor Stinner5edcf262019-05-23 00:57:57 +0200229 out, err = self.run_embedded_interpreter("test_pre_initialization_api", env=env)
Victor Stinner01de89c2018-11-14 17:39:45 +0100230 if MS_WINDOWS:
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000231 expected_path = self.test_exe
232 else:
233 expected_path = os.path.join(os.getcwd(), "spam")
234 expected_output = f"sys.executable: {expected_path}\n"
235 self.assertIn(expected_output, out)
236 self.assertEqual(err, '')
237
238 def test_pre_initialization_sys_options(self):
239 """
240 Checks that sys.warnoptions and sys._xoptions can be set before the
241 runtime is initialized (otherwise they won't be effective).
242 """
Victor Stinnerdbdc9912019-06-18 00:11:00 +0200243 env = remove_python_envvars()
244 env['PYTHONPATH'] = os.pathsep.join(sys.path)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000245 out, err = self.run_embedded_interpreter(
Victor Stinner5edcf262019-05-23 00:57:57 +0200246 "test_pre_initialization_sys_options", env=env)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000247 expected_output = (
248 "sys.warnoptions: ['once', 'module', 'default']\n"
249 "sys._xoptions: {'not_an_option': '1', 'also_not_an_option': '2'}\n"
250 "warnings.filters[:3]: ['default', 'module', 'once']\n"
251 )
252 self.assertIn(expected_output, out)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000253 self.assertEqual(err, '')
254
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100255 def test_bpo20891(self):
256 """
257 bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
258 calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must
259 call PyEval_InitThreads() for us in this case.
260 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200261 out, err = self.run_embedded_interpreter("test_bpo20891")
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100262 self.assertEqual(out, '')
263 self.assertEqual(err, '')
264
Victor Stinner209abf72018-06-22 19:14:51 +0200265 def test_initialize_twice(self):
266 """
267 bpo-33932: Calling Py_Initialize() twice should do nothing (and not
268 crash!).
269 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200270 out, err = self.run_embedded_interpreter("test_initialize_twice")
Victor Stinner209abf72018-06-22 19:14:51 +0200271 self.assertEqual(out, '')
272 self.assertEqual(err, '')
273
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200274 def test_initialize_pymain(self):
275 """
276 bpo-34008: Calling Py_Main() after Py_Initialize() must not fail.
277 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200278 out, err = self.run_embedded_interpreter("test_initialize_pymain")
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200279 self.assertEqual(out.rstrip(), "Py_Main() after Py_Initialize: sys.argv=['-c', 'arg2']")
280 self.assertEqual(err, '')
281
Victor Stinner2f549082019-03-29 15:13:46 +0100282 def test_run_main(self):
Victor Stinner5edcf262019-05-23 00:57:57 +0200283 out, err = self.run_embedded_interpreter("test_run_main")
Victor Stinner331a6a52019-05-27 16:39:22 +0200284 self.assertEqual(out.rstrip(), "Py_RunMain(): sys.argv=['-c', 'arg2']")
Victor Stinner2f549082019-03-29 15:13:46 +0100285 self.assertEqual(err, '')
286
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000287
Victor Stinner56b29b62018-07-26 18:57:56 +0200288class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
289 maxDiff = 4096
Victor Stinner01de89c2018-11-14 17:39:45 +0100290 UTF8_MODE_ERRORS = ('surrogatepass' if MS_WINDOWS else 'surrogateescape')
291
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200292 # Marker to read the default configuration: get_default_config()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100293 GET_DEFAULT_CONFIG = object()
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200294
295 # Marker to ignore a configuration parameter
296 IGNORE_CONFIG = object()
297
Victor Stinner022be022019-05-22 23:58:50 +0200298 PRE_CONFIG_COMPAT = {
Victor Stinner20e1e252019-05-23 04:12:27 +0200299 '_config_init': API_COMPAT,
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200300 'allocator': PYMEM_ALLOCATOR_NOT_SET,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200301 'parse_argv': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200302 'configure_locale': 1,
Victor Stinner1075d162019-03-25 23:19:57 +0100303 'coerce_c_locale': 0,
304 'coerce_c_locale_warn': 0,
Victor Stinner1075d162019-03-25 23:19:57 +0100305 'utf8_mode': 0,
306 }
Victor Stinner6d1c4672019-05-20 11:02:00 +0200307 if MS_WINDOWS:
Victor Stinner022be022019-05-22 23:58:50 +0200308 PRE_CONFIG_COMPAT.update({
Victor Stinner6d1c4672019-05-20 11:02:00 +0200309 'legacy_windows_fs_encoding': 0,
310 })
Victor Stinner022be022019-05-22 23:58:50 +0200311 PRE_CONFIG_PYTHON = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200312 _config_init=API_PYTHON,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200313 parse_argv=1,
Victor Stinner425717f2019-05-20 16:38:48 +0200314 coerce_c_locale=GET_DEFAULT_CONFIG,
315 utf8_mode=GET_DEFAULT_CONFIG,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200316 )
Victor Stinner022be022019-05-22 23:58:50 +0200317 PRE_CONFIG_ISOLATED = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200318 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200319 configure_locale=0,
320 isolated=1,
321 use_environment=0,
322 utf8_mode=0,
323 dev_mode=0,
Victor Stinner425717f2019-05-20 16:38:48 +0200324 coerce_c_locale=0,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200325 )
Victor Stinnerbab0db62019-05-18 03:21:27 +0200326
Victor Stinner20004952019-03-26 02:31:11 +0100327 COPY_PRE_CONFIG = [
328 'dev_mode',
329 'isolated',
330 'use_environment',
331 ]
332
Victor Stinner331a6a52019-05-27 16:39:22 +0200333 CONFIG_COMPAT = {
Victor Stinner022be022019-05-22 23:58:50 +0200334 '_config_init': API_COMPAT,
Victor Stinner20004952019-03-26 02:31:11 +0100335 'isolated': 0,
336 'use_environment': 1,
337 'dev_mode': 0,
338
Victor Stinner56b29b62018-07-26 18:57:56 +0200339 'install_signal_handlers': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200340 'use_hash_seed': 0,
341 'hash_seed': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200342 'faulthandler': 0,
343 'tracemalloc': 0,
344 'import_time': 0,
345 'show_ref_count': 0,
346 'show_alloc_count': 0,
347 'dump_refs': 0,
348 'malloc_stats': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200349
Victor Stinnera6537fb2018-11-26 11:54:12 +0100350 'filesystem_encoding': GET_DEFAULT_CONFIG,
351 'filesystem_errors': GET_DEFAULT_CONFIG,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200352
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100353 'pycache_prefix': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200354 'program_name': GET_DEFAULT_CONFIG,
Victor Stinnercab5d072019-05-17 19:01:14 +0200355 'parse_argv': 0,
Victor Stinner62599762019-03-15 16:03:23 +0100356 'argv': [""],
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100357
358 'xoptions': [],
359 'warnoptions': [],
Victor Stinner56b29b62018-07-26 18:57:56 +0200360
Victor Stinner331a6a52019-05-27 16:39:22 +0200361 'pythonpath_env': None,
Victor Stinner01de89c2018-11-14 17:39:45 +0100362 'home': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200363 'executable': GET_DEFAULT_CONFIG,
Steve Dower9048c492019-06-29 10:34:11 -0700364 'base_executable': GET_DEFAULT_CONFIG,
Victor Stinnera6537fb2018-11-26 11:54:12 +0100365
366 'prefix': GET_DEFAULT_CONFIG,
367 'base_prefix': GET_DEFAULT_CONFIG,
368 'exec_prefix': GET_DEFAULT_CONFIG,
369 'base_exec_prefix': GET_DEFAULT_CONFIG,
Victor Stinner5eb8b072019-05-15 02:12:48 +0200370 'module_search_paths': GET_DEFAULT_CONFIG,
Victor Stinner01de89c2018-11-14 17:39:45 +0100371
Victor Stinner56b29b62018-07-26 18:57:56 +0200372 'site_import': 1,
373 'bytes_warning': 0,
374 'inspect': 0,
375 'interactive': 0,
376 'optimization_level': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200377 'parser_debug': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200378 'write_bytecode': 1,
379 'verbose': 0,
380 'quiet': 0,
381 'user_site_directory': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200382 'configure_c_stdio': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200383 'buffered_stdio': 1,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200384
Victor Stinnera6537fb2018-11-26 11:54:12 +0100385 'stdio_encoding': GET_DEFAULT_CONFIG,
386 'stdio_errors': GET_DEFAULT_CONFIG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200387
Victor Stinner62be7632019-03-01 13:10:14 +0100388 'skip_source_first_line': 0,
389 'run_command': None,
390 'run_module': None,
391 'run_filename': None,
392
Victor Stinner56b29b62018-07-26 18:57:56 +0200393 '_install_importlib': 1,
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400394 'check_hash_pycs_mode': 'default',
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200395 'pathconfig_warnings': 1,
396 '_init_main': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200397 }
Victor Stinner01de89c2018-11-14 17:39:45 +0100398 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200399 CONFIG_COMPAT.update({
Victor Stinner01de89c2018-11-14 17:39:45 +0100400 'legacy_windows_stdio': 0,
401 })
402
Victor Stinner331a6a52019-05-27 16:39:22 +0200403 CONFIG_PYTHON = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200404 _config_init=API_PYTHON,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200405 configure_c_stdio=1,
406 parse_argv=1,
407 )
Victor Stinner331a6a52019-05-27 16:39:22 +0200408 CONFIG_ISOLATED = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200409 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200410 isolated=1,
411 use_environment=0,
412 user_site_directory=0,
413 dev_mode=0,
414 install_signal_handlers=0,
415 use_hash_seed=0,
416 faulthandler=0,
417 tracemalloc=0,
418 pathconfig_warnings=0,
419 )
420 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200421 CONFIG_ISOLATED['legacy_windows_stdio'] = 0
Victor Stinnerbab0db62019-05-18 03:21:27 +0200422
Victor Stinner01de89c2018-11-14 17:39:45 +0100423 # global config
424 DEFAULT_GLOBAL_CONFIG = {
425 'Py_HasFileSystemDefaultEncoding': 0,
426 'Py_HashRandomizationFlag': 1,
427 '_Py_HasFileSystemDefaultEncodeErrors': 0,
428 }
Victor Stinner1075d162019-03-25 23:19:57 +0100429 COPY_GLOBAL_PRE_CONFIG = [
Victor Stinner1075d162019-03-25 23:19:57 +0100430 ('Py_UTF8Mode', 'utf8_mode'),
431 ]
Victor Stinner01de89c2018-11-14 17:39:45 +0100432 COPY_GLOBAL_CONFIG = [
433 # Copy core config to global config for expected values
434 # True means that the core config value is inverted (0 => 1 and 1 => 0)
435 ('Py_BytesWarningFlag', 'bytes_warning'),
436 ('Py_DebugFlag', 'parser_debug'),
437 ('Py_DontWriteBytecodeFlag', 'write_bytecode', True),
438 ('Py_FileSystemDefaultEncodeErrors', 'filesystem_errors'),
439 ('Py_FileSystemDefaultEncoding', 'filesystem_encoding'),
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200440 ('Py_FrozenFlag', 'pathconfig_warnings', True),
Victor Stinner20004952019-03-26 02:31:11 +0100441 ('Py_IgnoreEnvironmentFlag', 'use_environment', True),
Victor Stinner01de89c2018-11-14 17:39:45 +0100442 ('Py_InspectFlag', 'inspect'),
443 ('Py_InteractiveFlag', 'interactive'),
Victor Stinner20004952019-03-26 02:31:11 +0100444 ('Py_IsolatedFlag', 'isolated'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100445 ('Py_NoSiteFlag', 'site_import', True),
446 ('Py_NoUserSiteDirectory', 'user_site_directory', True),
447 ('Py_OptimizeFlag', 'optimization_level'),
448 ('Py_QuietFlag', 'quiet'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100449 ('Py_UnbufferedStdioFlag', 'buffered_stdio', True),
450 ('Py_VerboseFlag', 'verbose'),
451 ]
452 if MS_WINDOWS:
Victor Stinner1075d162019-03-25 23:19:57 +0100453 COPY_GLOBAL_PRE_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100454 ('Py_LegacyWindowsFSEncodingFlag', 'legacy_windows_fs_encoding'),
Victor Stinner1075d162019-03-25 23:19:57 +0100455 ))
456 COPY_GLOBAL_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100457 ('Py_LegacyWindowsStdioFlag', 'legacy_windows_stdio'),
458 ))
Victor Stinner56b29b62018-07-26 18:57:56 +0200459
Victor Stinner425717f2019-05-20 16:38:48 +0200460 EXPECTED_CONFIG = None
461
Victor Stinner01de89c2018-11-14 17:39:45 +0100462 def main_xoptions(self, xoptions_list):
463 xoptions = {}
464 for opt in xoptions_list:
465 if '=' in opt:
466 key, value = opt.split('=', 1)
467 xoptions[key] = value
468 else:
469 xoptions[opt] = True
470 return xoptions
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200471
Victor Stinner425717f2019-05-20 16:38:48 +0200472 def _get_expected_config(self, env):
Victor Stinnera6537fb2018-11-26 11:54:12 +0100473 code = textwrap.dedent('''
474 import json
Victor Stinnera6537fb2018-11-26 11:54:12 +0100475 import sys
Victor Stinner5eb8b072019-05-15 02:12:48 +0200476 import _testinternalcapi
Victor Stinnera6537fb2018-11-26 11:54:12 +0100477
Victor Stinner5eb8b072019-05-15 02:12:48 +0200478 configs = _testinternalcapi.get_configs()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100479
Victor Stinner425717f2019-05-20 16:38:48 +0200480 data = json.dumps(configs)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100481 data = data.encode('utf-8')
482 sys.stdout.buffer.write(data)
483 sys.stdout.buffer.flush()
484 ''')
485
486 # Use -S to not import the site module: get the proper configuration
487 # when test_embed is run from a venv (bpo-35313)
Victor Stinner5eb8b072019-05-15 02:12:48 +0200488 args = [sys.executable, '-S', '-c', code]
Victor Stinnera6537fb2018-11-26 11:54:12 +0100489 proc = subprocess.run(args, env=env,
490 stdout=subprocess.PIPE,
491 stderr=subprocess.STDOUT)
492 if proc.returncode:
493 raise Exception(f"failed to get the default config: "
494 f"stdout={proc.stdout!r} stderr={proc.stderr!r}")
495 stdout = proc.stdout.decode('utf-8')
Victor Stinner4631da12019-05-02 15:30:21 -0400496 try:
Victor Stinner425717f2019-05-20 16:38:48 +0200497 return json.loads(stdout)
Victor Stinner4631da12019-05-02 15:30:21 -0400498 except json.JSONDecodeError:
499 self.fail(f"fail to decode stdout: {stdout!r}")
Victor Stinnera6537fb2018-11-26 11:54:12 +0100500
Victor Stinner425717f2019-05-20 16:38:48 +0200501 def get_expected_config(self, expected_preconfig, expected, env, api,
502 add_path=None):
503 cls = self.__class__
504 if cls.EXPECTED_CONFIG is None:
505 cls.EXPECTED_CONFIG = self._get_expected_config(env)
506 configs = {key: dict(value)
507 for key, value in self.EXPECTED_CONFIG.items()}
508
509 pre_config = configs['pre_config']
510 for key, value in expected_preconfig.items():
511 if value is self.GET_DEFAULT_CONFIG:
512 expected_preconfig[key] = pre_config[key]
513
Victor Stinner022be022019-05-22 23:58:50 +0200514 if not expected_preconfig['configure_locale'] or api == API_COMPAT:
Victor Stinner425717f2019-05-20 16:38:48 +0200515 # there is no easy way to get the locale encoding before
516 # setlocale(LC_CTYPE, "") is called: don't test encodings
517 for key in ('filesystem_encoding', 'filesystem_errors',
518 'stdio_encoding', 'stdio_errors'):
519 expected[key] = self.IGNORE_CONFIG
520
521 if not expected_preconfig['configure_locale']:
522 # UTF-8 Mode depends on the locale. There is no easy way
523 # to guess if UTF-8 Mode will be enabled or not if the locale
524 # is not configured.
525 expected_preconfig['utf8_mode'] = self.IGNORE_CONFIG
526
527 if expected_preconfig['utf8_mode'] == 1:
528 if expected['filesystem_encoding'] is self.GET_DEFAULT_CONFIG:
529 expected['filesystem_encoding'] = 'utf-8'
530 if expected['filesystem_errors'] is self.GET_DEFAULT_CONFIG:
531 expected['filesystem_errors'] = self.UTF8_MODE_ERRORS
532 if expected['stdio_encoding'] is self.GET_DEFAULT_CONFIG:
533 expected['stdio_encoding'] = 'utf-8'
534 if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG:
535 expected['stdio_errors'] = 'surrogateescape'
536
Steve Dower9048c492019-06-29 10:34:11 -0700537 if sys.platform == 'win32':
538 default_executable = self.test_exe
539 elif expected['program_name'] is not self.GET_DEFAULT_CONFIG:
540 default_executable = os.path.abspath(expected['program_name'])
541 else:
542 default_executable = os.path.join(os.getcwd(), '_testembed')
Victor Stinner91c99872019-05-14 22:01:51 +0200543 if expected['executable'] is self.GET_DEFAULT_CONFIG:
Steve Dower9048c492019-06-29 10:34:11 -0700544 expected['executable'] = default_executable
545 if expected['base_executable'] is self.GET_DEFAULT_CONFIG:
546 expected['base_executable'] = default_executable
Victor Stinner91c99872019-05-14 22:01:51 +0200547 if expected['program_name'] is self.GET_DEFAULT_CONFIG:
548 expected['program_name'] = './_testembed'
549
Victor Stinner331a6a52019-05-27 16:39:22 +0200550 config = configs['config']
Victor Stinnera6537fb2018-11-26 11:54:12 +0100551 for key, value in expected.items():
552 if value is self.GET_DEFAULT_CONFIG:
Victor Stinner331a6a52019-05-27 16:39:22 +0200553 expected[key] = config[key]
Victor Stinner5eb8b072019-05-15 02:12:48 +0200554
Victor Stinner331a6a52019-05-27 16:39:22 +0200555 prepend_path = expected['pythonpath_env']
Victor Stinner425717f2019-05-20 16:38:48 +0200556 if prepend_path is not None:
557 expected['module_search_paths'] = [prepend_path, *expected['module_search_paths']]
Victor Stinner5eb8b072019-05-15 02:12:48 +0200558 if add_path is not None:
Victor Stinner425717f2019-05-20 16:38:48 +0200559 expected['module_search_paths'] = [*expected['module_search_paths'], add_path]
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200560
Victor Stinner425717f2019-05-20 16:38:48 +0200561 for key in self.COPY_PRE_CONFIG:
562 if key not in expected_preconfig:
563 expected_preconfig[key] = expected[key]
Victor Stinner01de89c2018-11-14 17:39:45 +0100564
Victor Stinner331a6a52019-05-27 16:39:22 +0200565 def check_pre_config(self, configs, expected):
566 pre_config = dict(configs['pre_config'])
Victor Stinner425717f2019-05-20 16:38:48 +0200567 for key, value in list(expected.items()):
568 if value is self.IGNORE_CONFIG:
569 del pre_config[key]
570 del expected[key]
571 self.assertEqual(pre_config, expected)
Victor Stinner1075d162019-03-25 23:19:57 +0100572
Victor Stinner331a6a52019-05-27 16:39:22 +0200573 def check_config(self, configs, expected):
574 config = dict(configs['config'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200575 for key, value in list(expected.items()):
576 if value is self.IGNORE_CONFIG:
Victor Stinner331a6a52019-05-27 16:39:22 +0200577 del config[key]
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200578 del expected[key]
Victor Stinner331a6a52019-05-27 16:39:22 +0200579 self.assertEqual(config, expected)
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200580
Victor Stinner331a6a52019-05-27 16:39:22 +0200581 def check_global_config(self, configs):
582 pre_config = configs['pre_config']
583 config = configs['config']
Victor Stinner00b137c2018-11-13 19:59:26 +0100584
Victor Stinnera6537fb2018-11-26 11:54:12 +0100585 expected = dict(self.DEFAULT_GLOBAL_CONFIG)
Victor Stinner01de89c2018-11-14 17:39:45 +0100586 for item in self.COPY_GLOBAL_CONFIG:
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100587 if len(item) == 3:
588 global_key, core_key, opposite = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200589 expected[global_key] = 0 if config[core_key] else 1
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100590 else:
591 global_key, core_key = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200592 expected[global_key] = config[core_key]
Victor Stinner1075d162019-03-25 23:19:57 +0100593 for item in self.COPY_GLOBAL_PRE_CONFIG:
594 if len(item) == 3:
595 global_key, core_key, opposite = item
596 expected[global_key] = 0 if pre_config[core_key] else 1
597 else:
598 global_key, core_key = item
599 expected[global_key] = pre_config[core_key]
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100600
Victor Stinner331a6a52019-05-27 16:39:22 +0200601 self.assertEqual(configs['global_config'], expected)
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100602
Victor Stinner331a6a52019-05-27 16:39:22 +0200603 def check_all_configs(self, testname, expected_config=None,
Victor Stinner022be022019-05-22 23:58:50 +0200604 expected_preconfig=None, add_path=None, stderr=None,
605 *, api):
Victor Stinnerdbdc9912019-06-18 00:11:00 +0200606 env = remove_python_envvars()
Victor Stinner01de89c2018-11-14 17:39:45 +0100607
Victor Stinner022be022019-05-22 23:58:50 +0200608 if api == API_ISOLATED:
609 default_preconfig = self.PRE_CONFIG_ISOLATED
610 elif api == API_PYTHON:
611 default_preconfig = self.PRE_CONFIG_PYTHON
Victor Stinnerbab0db62019-05-18 03:21:27 +0200612 else:
Victor Stinner022be022019-05-22 23:58:50 +0200613 default_preconfig = self.PRE_CONFIG_COMPAT
Victor Stinnerbab0db62019-05-18 03:21:27 +0200614 if expected_preconfig is None:
615 expected_preconfig = {}
616 expected_preconfig = dict(default_preconfig, **expected_preconfig)
617 if expected_config is None:
618 expected_config = {}
Victor Stinner425717f2019-05-20 16:38:48 +0200619
Victor Stinner022be022019-05-22 23:58:50 +0200620 if api == API_PYTHON:
Victor Stinner331a6a52019-05-27 16:39:22 +0200621 default_config = self.CONFIG_PYTHON
Victor Stinner022be022019-05-22 23:58:50 +0200622 elif api == API_ISOLATED:
Victor Stinner331a6a52019-05-27 16:39:22 +0200623 default_config = self.CONFIG_ISOLATED
Victor Stinner425717f2019-05-20 16:38:48 +0200624 else:
Victor Stinner331a6a52019-05-27 16:39:22 +0200625 default_config = self.CONFIG_COMPAT
Victor Stinner425717f2019-05-20 16:38:48 +0200626 expected_config = dict(default_config, **expected_config)
Victor Stinner425717f2019-05-20 16:38:48 +0200627
628 self.get_expected_config(expected_preconfig,
629 expected_config, env,
630 api, add_path)
Victor Stinner1075d162019-03-25 23:19:57 +0100631
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200632 out, err = self.run_embedded_interpreter(testname, env=env)
633 if stderr is None and not expected_config['verbose']:
634 stderr = ""
635 if stderr is not None:
636 self.assertEqual(err.rstrip(), stderr)
637 try:
Victor Stinner331a6a52019-05-27 16:39:22 +0200638 configs = json.loads(out)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200639 except json.JSONDecodeError:
640 self.fail(f"fail to decode stdout: {out!r}")
641
Victor Stinner331a6a52019-05-27 16:39:22 +0200642 self.check_pre_config(configs, expected_preconfig)
643 self.check_config(configs, expected_config)
644 self.check_global_config(configs)
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100645
Victor Stinner56b29b62018-07-26 18:57:56 +0200646 def test_init_default_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200647 self.check_all_configs("test_init_initialize_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200648
649 def test_preinit_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200650 self.check_all_configs("test_preinit_compat_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200651
652 def test_init_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200653 self.check_all_configs("test_init_compat_config", api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200654
655 def test_init_global_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100656 preconfig = {
657 'utf8_mode': 1,
658 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200659 config = {
660 'program_name': './globalvar',
661 'site_import': 0,
662 'bytes_warning': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100663 'warnoptions': ['default::BytesWarning'],
Victor Stinner56b29b62018-07-26 18:57:56 +0200664 'inspect': 1,
665 'interactive': 1,
666 'optimization_level': 2,
667 'write_bytecode': 0,
668 'verbose': 1,
669 'quiet': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200670 'buffered_stdio': 0,
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200671
Victor Stinner56b29b62018-07-26 18:57:56 +0200672 'user_site_directory': 0,
Victor Stinner54b43bb2019-05-16 18:30:15 +0200673 'pathconfig_warnings': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200674 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200675 self.check_all_configs("test_init_global_config", config, preconfig,
676 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200677
678 def test_init_from_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100679 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200680 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner1075d162019-03-25 23:19:57 +0100681 'utf8_mode': 1,
682 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200683 config = {
684 'install_signal_handlers': 0,
685 'use_hash_seed': 1,
686 'hash_seed': 123,
Victor Stinner56b29b62018-07-26 18:57:56 +0200687 'tracemalloc': 2,
688 'import_time': 1,
689 'show_ref_count': 1,
690 'show_alloc_count': 1,
691 'malloc_stats': 1,
692
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200693 'stdio_encoding': 'iso8859-1',
694 'stdio_errors': 'replace',
Victor Stinner56b29b62018-07-26 18:57:56 +0200695
696 'pycache_prefix': 'conf_pycache_prefix',
697 'program_name': './conf_program_name',
Victor Stinner2f549082019-03-29 15:13:46 +0100698 'argv': ['-c', 'arg2'],
Victor Stinnercab5d072019-05-17 19:01:14 +0200699 'parse_argv': 1,
Victor Stinner331a6a52019-05-27 16:39:22 +0200700 'xoptions': ['xoption1=3', 'xoption2=', 'xoption3'],
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100701 'warnoptions': ['error::ResourceWarning', 'default::BytesWarning'],
Victor Stinner2f549082019-03-29 15:13:46 +0100702 'run_command': 'pass\n',
Victor Stinner56b29b62018-07-26 18:57:56 +0200703
704 'site_import': 0,
705 'bytes_warning': 1,
706 'inspect': 1,
707 'interactive': 1,
708 'optimization_level': 2,
709 'write_bytecode': 0,
710 'verbose': 1,
711 'quiet': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200712 'configure_c_stdio': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200713 'buffered_stdio': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200714 'user_site_directory': 0,
715 'faulthandler': 1,
Victor Stinnerb75d7e22018-08-01 02:13:04 +0200716
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400717 'check_hash_pycs_mode': 'always',
Victor Stinner54b43bb2019-05-16 18:30:15 +0200718 'pathconfig_warnings': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200719 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200720 self.check_all_configs("test_init_from_config", config, preconfig,
721 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200722
Victor Stinner20e1e252019-05-23 04:12:27 +0200723 def test_init_compat_env(self):
724 preconfig = {
725 'allocator': PYMEM_ALLOCATOR_MALLOC,
726 }
727 config = {
728 'use_hash_seed': 1,
729 'hash_seed': 42,
730 'tracemalloc': 2,
731 'import_time': 1,
732 'malloc_stats': 1,
733 'inspect': 1,
734 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200735 'pythonpath_env': '/my/path',
Victor Stinner20e1e252019-05-23 04:12:27 +0200736 'pycache_prefix': 'env_pycache_prefix',
737 'write_bytecode': 0,
738 'verbose': 1,
739 'buffered_stdio': 0,
740 'stdio_encoding': 'iso8859-1',
741 'stdio_errors': 'replace',
742 'user_site_directory': 0,
743 'faulthandler': 1,
744 'warnoptions': ['EnvVar'],
745 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200746 self.check_all_configs("test_init_compat_env", config, preconfig,
747 api=API_COMPAT)
Victor Stinner20e1e252019-05-23 04:12:27 +0200748
749 def test_init_python_env(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200750 preconfig = {
751 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner022be022019-05-22 23:58:50 +0200752 'utf8_mode': 1,
Victor Stinner425717f2019-05-20 16:38:48 +0200753 }
754 config = {
755 'use_hash_seed': 1,
756 'hash_seed': 42,
757 'tracemalloc': 2,
758 'import_time': 1,
759 'malloc_stats': 1,
760 'inspect': 1,
761 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200762 'pythonpath_env': '/my/path',
Victor Stinner425717f2019-05-20 16:38:48 +0200763 'pycache_prefix': 'env_pycache_prefix',
764 'write_bytecode': 0,
765 'verbose': 1,
766 'buffered_stdio': 0,
767 'stdio_encoding': 'iso8859-1',
768 'stdio_errors': 'replace',
769 'user_site_directory': 0,
770 'faulthandler': 1,
771 'warnoptions': ['EnvVar'],
772 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200773 self.check_all_configs("test_init_python_env", config, preconfig,
774 api=API_PYTHON)
Victor Stinnerb35be4b2019-03-05 17:37:44 +0100775
776 def test_init_env_dev_mode(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200777 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
778 config = dict(dev_mode=1,
779 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100780 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200781 self.check_all_configs("test_init_env_dev_mode", config, preconfig,
782 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200783
Victor Stinner20004952019-03-26 02:31:11 +0100784 def test_init_env_dev_mode_alloc(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200785 preconfig = dict(allocator=PYMEM_ALLOCATOR_MALLOC)
786 config = dict(dev_mode=1,
787 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100788 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200789 self.check_all_configs("test_init_env_dev_mode_alloc", config, preconfig,
790 api=API_COMPAT)
Victor Stinner25d13f32019-03-06 12:51:53 +0100791
Victor Stinner56b29b62018-07-26 18:57:56 +0200792 def test_init_dev_mode(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100793 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200794 'allocator': PYMEM_ALLOCATOR_DEBUG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200795 }
Victor Stinner1075d162019-03-25 23:19:57 +0100796 config = {
797 'faulthandler': 1,
Victor Stinner20004952019-03-26 02:31:11 +0100798 'dev_mode': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100799 'warnoptions': ['default'],
Victor Stinner1075d162019-03-25 23:19:57 +0100800 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200801 self.check_all_configs("test_init_dev_mode", config, preconfig,
802 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200803
804 def test_preinit_parse_argv(self):
805 # Pre-initialize implicitly using argv: make sure that -X dev
806 # is used to configure the allocation in preinitialization
807 preconfig = {
808 'allocator': PYMEM_ALLOCATOR_DEBUG,
809 }
Victor Stinner3939c322019-06-25 15:02:43 +0200810 script_abspath = os.path.abspath('script.py')
Victor Stinner6d1c4672019-05-20 11:02:00 +0200811 config = {
Victor Stinner3939c322019-06-25 15:02:43 +0200812 'argv': [script_abspath],
813 'run_filename': script_abspath,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200814 'dev_mode': 1,
815 'faulthandler': 1,
816 'warnoptions': ['default'],
817 'xoptions': ['dev'],
818 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200819 self.check_all_configs("test_preinit_parse_argv", config, preconfig,
820 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200821
822 def test_preinit_dont_parse_argv(self):
823 # -X dev must be ignored by isolated preconfiguration
824 preconfig = {
825 'isolated': 0,
826 }
827 config = {
828 'argv': ["python3", "-E", "-I",
829 "-X", "dev", "-X", "utf8", "script.py"],
830 'isolated': 0,
831 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200832 self.check_all_configs("test_preinit_dont_parse_argv", config, preconfig,
833 api=API_ISOLATED)
Victor Stinner56b29b62018-07-26 18:57:56 +0200834
Victor Stinnercab5d072019-05-17 19:01:14 +0200835 def test_init_isolated_flag(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100836 config = {
Victor Stinner20004952019-03-26 02:31:11 +0100837 'isolated': 1,
838 'use_environment': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200839 'user_site_directory': 0,
840 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200841 self.check_all_configs("test_init_isolated_flag", config, api=API_PYTHON)
Victor Stinner56b29b62018-07-26 18:57:56 +0200842
Victor Stinner6da20a42019-03-27 00:26:18 +0100843 def test_preinit_isolated1(self):
844 # _PyPreConfig.isolated=1, _PyCoreConfig.isolated not set
Victor Stinner6da20a42019-03-27 00:26:18 +0100845 config = {
846 'isolated': 1,
847 'use_environment': 0,
848 'user_site_directory': 0,
849 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200850 self.check_all_configs("test_preinit_isolated1", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100851
852 def test_preinit_isolated2(self):
853 # _PyPreConfig.isolated=0, _PyCoreConfig.isolated=1
Victor Stinner6da20a42019-03-27 00:26:18 +0100854 config = {
855 'isolated': 1,
856 'use_environment': 0,
857 'user_site_directory': 0,
858 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200859 self.check_all_configs("test_preinit_isolated2", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100860
Victor Stinner6d1c4672019-05-20 11:02:00 +0200861 def test_preinit_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200862 self.check_all_configs("test_preinit_isolated_config", api=API_ISOLATED)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200863
Victor Stinnercab5d072019-05-17 19:01:14 +0200864 def test_init_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200865 self.check_all_configs("test_init_isolated_config", api=API_ISOLATED)
Victor Stinner5edcf262019-05-23 00:57:57 +0200866
867 def test_preinit_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200868 self.check_all_configs("test_preinit_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200869
870 def test_init_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200871 self.check_all_configs("test_init_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200872
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200873 def test_init_dont_configure_locale(self):
874 # _PyPreConfig.configure_locale=0
875 preconfig = {
876 'configure_locale': 0,
Victor Stinner425717f2019-05-20 16:38:48 +0200877 'coerce_c_locale': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200878 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200879 self.check_all_configs("test_init_dont_configure_locale", {}, preconfig,
880 api=API_PYTHON)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200881
Victor Stinner91c99872019-05-14 22:01:51 +0200882 def test_init_read_set(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200883 config = {
Victor Stinner91c99872019-05-14 22:01:51 +0200884 'program_name': './init_read_set',
885 'executable': 'my_executable',
886 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200887 self.check_all_configs("test_init_read_set", config,
888 api=API_PYTHON,
889 add_path="init_read_set_path")
Victor Stinner91c99872019-05-14 22:01:51 +0200890
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200891 def test_init_run_main(self):
Victor Stinner5eb8b072019-05-15 02:12:48 +0200892 code = ('import _testinternalcapi, json; '
893 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +0200894 config = {
Victor Stinner5eb8b072019-05-15 02:12:48 +0200895 'argv': ['-c', 'arg2'],
Victor Stinner5eb8b072019-05-15 02:12:48 +0200896 'program_name': './python3',
897 'run_command': code + '\n',
Victor Stinnercab5d072019-05-17 19:01:14 +0200898 'parse_argv': 1,
Victor Stinner5eb8b072019-05-15 02:12:48 +0200899 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200900 self.check_all_configs("test_init_run_main", config, api=API_PYTHON)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200901
902 def test_init_main(self):
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200903 code = ('import _testinternalcapi, json; '
904 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +0200905 config = {
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200906 'argv': ['-c', 'arg2'],
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200907 'program_name': './python3',
908 'run_command': code + '\n',
Victor Stinnercab5d072019-05-17 19:01:14 +0200909 'parse_argv': 1,
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200910 '_init_main': 0,
911 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200912 self.check_all_configs("test_init_main", config,
913 api=API_PYTHON,
914 stderr="Run Python code before _Py_InitializeMain")
Victor Stinner5eb8b072019-05-15 02:12:48 +0200915
Victor Stinnercab5d072019-05-17 19:01:14 +0200916 def test_init_parse_argv(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200917 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +0200918 'parse_argv': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200919 'argv': ['-c', 'arg1', '-v', 'arg3'],
920 'program_name': './argv0',
Victor Stinnercab5d072019-05-17 19:01:14 +0200921 'run_command': 'pass\n',
922 'use_environment': 0,
923 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200924 self.check_all_configs("test_init_parse_argv", config, api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200925
Victor Stinnerae239f62019-05-16 17:02:56 +0200926 def test_init_dont_parse_argv(self):
Victor Stinner6d1c4672019-05-20 11:02:00 +0200927 pre_config = {
928 'parse_argv': 0,
929 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200930 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +0200931 'parse_argv': 0,
Victor Stinnercab5d072019-05-17 19:01:14 +0200932 'argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
933 'program_name': './argv0',
Victor Stinnerae239f62019-05-16 17:02:56 +0200934 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200935 self.check_all_configs("test_init_dont_parse_argv", config, pre_config,
936 api=API_PYTHON)
Victor Stinnerae239f62019-05-16 17:02:56 +0200937
Victor Stinner56b29b62018-07-26 18:57:56 +0200938
Steve Dowerb82e17e2019-05-23 08:45:22 -0700939class AuditingTests(EmbeddingTestsMixin, unittest.TestCase):
940 def test_open_code_hook(self):
941 self.run_embedded_interpreter("test_open_code_hook")
942
943 def test_audit(self):
944 self.run_embedded_interpreter("test_audit")
945
946 def test_audit_subinterpreter(self):
947 self.run_embedded_interpreter("test_audit_subinterpreter")
948
949
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000950if __name__ == "__main__":
951 unittest.main()