blob: e7a10b6defea1bb495d061d4592bae947777f91c [file] [log] [blame]
Nick Coghlan39f0bb52017-11-28 08:11:51 +10001# Run the tests in Programs/_testembed.c (tests for the CPython embedding APIs)
2from test import support
3import unittest
4
5from collections import namedtuple
Victor Stinner52ad33a2019-09-25 02:10:35 +02006import contextlib
Victor Stinner7ddd56f2018-11-14 00:24:28 +01007import json
Nick Coghlan39f0bb52017-11-28 08:11:51 +10008import os
9import re
Victor Stinner52ad33a2019-09-25 02:10:35 +020010import shutil
Nick Coghlan39f0bb52017-11-28 08:11:51 +100011import subprocess
12import sys
Victor Stinner52ad33a2019-09-25 02:10:35 +020013import tempfile
Victor Stinnera6537fb2018-11-26 11:54:12 +010014import textwrap
Nick Coghlan39f0bb52017-11-28 08:11:51 +100015
16
Victor Stinner01de89c2018-11-14 17:39:45 +010017MS_WINDOWS = (os.name == 'nt')
Victor Stinner022be022019-05-22 23:58:50 +020018
Victor Stinnerb16b4e42019-05-17 15:20:52 +020019PYMEM_ALLOCATOR_NOT_SET = 0
20PYMEM_ALLOCATOR_DEBUG = 2
21PYMEM_ALLOCATOR_MALLOC = 3
Victor Stinner01de89c2018-11-14 17:39:45 +010022
Victor Stinner022be022019-05-22 23:58:50 +020023# _PyCoreConfig_InitCompatConfig()
24API_COMPAT = 1
25# _PyCoreConfig_InitPythonConfig()
26API_PYTHON = 2
27# _PyCoreConfig_InitIsolatedConfig()
28API_ISOLATED = 3
Victor Stinner6d1c4672019-05-20 11:02:00 +020029
Victor Stinner01de89c2018-11-14 17:39:45 +010030
Victor Stinner52ad33a2019-09-25 02:10:35 +020031def debug_build(program):
32 program = os.path.basename(program)
33 name = os.path.splitext(program)[0]
34 return name.endswith("_d")
35
36
Victor Stinnerdbdc9912019-06-18 00:11:00 +020037def remove_python_envvars():
38 env = dict(os.environ)
39 # Remove PYTHON* environment variables to get deterministic environment
40 for key in list(env):
41 if key.startswith('PYTHON'):
42 del env[key]
43 return env
44
45
Victor Stinner56b29b62018-07-26 18:57:56 +020046class EmbeddingTestsMixin:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100047 def setUp(self):
48 here = os.path.abspath(__file__)
49 basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
50 exename = "_testembed"
Victor Stinner01de89c2018-11-14 17:39:45 +010051 if MS_WINDOWS:
Victor Stinner52ad33a2019-09-25 02:10:35 +020052 ext = ("_d" if debug_build(sys.executable) else "") + ".exe"
Nick Coghlan39f0bb52017-11-28 08:11:51 +100053 exename += ext
54 exepath = os.path.dirname(sys.executable)
55 else:
56 exepath = os.path.join(basepath, "Programs")
57 self.test_exe = exe = os.path.join(exepath, exename)
58 if not os.path.exists(exe):
59 self.skipTest("%r doesn't exist" % exe)
60 # This is needed otherwise we get a fatal error:
61 # "Py_Initialize: Unable to get the locale encoding
62 # LookupError: no codec search functions registered: can't find encoding"
63 self.oldcwd = os.getcwd()
64 os.chdir(basepath)
65
66 def tearDown(self):
67 os.chdir(self.oldcwd)
68
Steve Dowere226e832019-07-01 16:03:53 -070069 def run_embedded_interpreter(self, *args, env=None,
Victor Stinner52ad33a2019-09-25 02:10:35 +020070 timeout=None, returncode=0, input=None,
71 cwd=None):
Nick Coghlan39f0bb52017-11-28 08:11:51 +100072 """Runs a test in the embedded interpreter"""
73 cmd = [self.test_exe]
74 cmd.extend(args)
Victor Stinner01de89c2018-11-14 17:39:45 +010075 if env is not None and MS_WINDOWS:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100076 # Windows requires at least the SYSTEMROOT environment variable to
77 # start Python.
78 env = env.copy()
79 env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
80
81 p = subprocess.Popen(cmd,
82 stdout=subprocess.PIPE,
83 stderr=subprocess.PIPE,
84 universal_newlines=True,
Victor Stinner52ad33a2019-09-25 02:10:35 +020085 env=env,
86 cwd=cwd)
Victor Stinner2f549082019-03-29 15:13:46 +010087 try:
Steve Dowere226e832019-07-01 16:03:53 -070088 (out, err) = p.communicate(input=input, timeout=timeout)
Victor Stinner2f549082019-03-29 15:13:46 +010089 except:
90 p.terminate()
91 p.wait()
92 raise
Steve Dowere226e832019-07-01 16:03:53 -070093 if p.returncode != returncode and support.verbose:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100094 print(f"--- {cmd} failed ---")
95 print(f"stdout:\n{out}")
Nick Coghlanbc77eff2018-03-25 20:44:30 +100096 print(f"stderr:\n{err}")
Nick Coghlan39f0bb52017-11-28 08:11:51 +100097 print(f"------")
98
Steve Dowere226e832019-07-01 16:03:53 -070099 self.assertEqual(p.returncode, returncode,
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000100 "bad returncode %d, stderr is %r" %
101 (p.returncode, err))
102 return out, err
103
104 def run_repeated_init_and_subinterpreters(self):
Victor Stinner5edcf262019-05-23 00:57:57 +0200105 out, err = self.run_embedded_interpreter("test_repeated_init_and_subinterpreters")
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000106 self.assertEqual(err, "")
107
108 # The output from _testembed looks like this:
109 # --- Pass 0 ---
110 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
111 # interp 1 <0x1d4f690>, thread state <0x1d35350>: id(modules) = 139650431165784
112 # interp 2 <0x1d5a690>, thread state <0x1d99ed0>: id(modules) = 139650413140368
113 # interp 3 <0x1d4f690>, thread state <0x1dc3340>: id(modules) = 139650412862200
114 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
115 # --- Pass 1 ---
116 # ...
117
118 interp_pat = (r"^interp (\d+) <(0x[\dA-F]+)>, "
119 r"thread state <(0x[\dA-F]+)>: "
120 r"id\(modules\) = ([\d]+)$")
121 Interp = namedtuple("Interp", "id interp tstate modules")
122
123 numloops = 0
124 current_run = []
125 for line in out.splitlines():
126 if line == "--- Pass {} ---".format(numloops):
127 self.assertEqual(len(current_run), 0)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000128 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000129 print(line)
130 numloops += 1
131 continue
132
133 self.assertLess(len(current_run), 5)
134 match = re.match(interp_pat, line)
135 if match is None:
136 self.assertRegex(line, interp_pat)
137
138 # Parse the line from the loop. The first line is the main
139 # interpreter and the 3 afterward are subinterpreters.
140 interp = Interp(*match.groups())
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000141 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000142 print(interp)
143 self.assertTrue(interp.interp)
144 self.assertTrue(interp.tstate)
145 self.assertTrue(interp.modules)
146 current_run.append(interp)
147
148 # The last line in the loop should be the same as the first.
149 if len(current_run) == 5:
150 main = current_run[0]
151 self.assertEqual(interp, main)
152 yield current_run
153 current_run = []
154
Victor Stinner56b29b62018-07-26 18:57:56 +0200155
156class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase):
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000157 def test_subinterps_main(self):
158 for run in self.run_repeated_init_and_subinterpreters():
159 main = run[0]
160
161 self.assertEqual(main.id, '0')
162
163 def test_subinterps_different_ids(self):
164 for run in self.run_repeated_init_and_subinterpreters():
165 main, *subs, _ = run
166
167 mainid = int(main.id)
168 for i, sub in enumerate(subs):
169 self.assertEqual(sub.id, str(mainid + i + 1))
170
171 def test_subinterps_distinct_state(self):
172 for run in self.run_repeated_init_and_subinterpreters():
173 main, *subs, _ = run
174
175 if '0x0' in main:
176 # XXX Fix on Windows (and other platforms): something
177 # is going on with the pointers in Programs/_testembed.c.
178 # interp.interp is 0x0 and interp.modules is the same
179 # between interpreters.
180 raise unittest.SkipTest('platform prints pointers as 0x0')
181
182 for sub in subs:
183 # A new subinterpreter may have the same
184 # PyInterpreterState pointer as a previous one if
185 # the earlier one has already been destroyed. So
186 # we compare with the main interpreter. The same
187 # applies to tstate.
188 self.assertNotEqual(sub.interp, main.interp)
189 self.assertNotEqual(sub.tstate, main.tstate)
190 self.assertNotEqual(sub.modules, main.modules)
191
192 def test_forced_io_encoding(self):
193 # Checks forced configuration of embedded interpreter IO streams
194 env = dict(os.environ, PYTHONIOENCODING="utf-8:surrogateescape")
Victor Stinner5edcf262019-05-23 00:57:57 +0200195 out, err = self.run_embedded_interpreter("test_forced_io_encoding", env=env)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000196 if support.verbose > 1:
197 print()
198 print(out)
199 print(err)
200 expected_stream_encoding = "utf-8"
201 expected_errors = "surrogateescape"
202 expected_output = '\n'.join([
203 "--- Use defaults ---",
204 "Expected encoding: default",
205 "Expected errors: default",
206 "stdin: {in_encoding}:{errors}",
207 "stdout: {out_encoding}:{errors}",
208 "stderr: {out_encoding}:backslashreplace",
209 "--- Set errors only ---",
210 "Expected encoding: default",
211 "Expected errors: ignore",
212 "stdin: {in_encoding}:ignore",
213 "stdout: {out_encoding}:ignore",
214 "stderr: {out_encoding}:backslashreplace",
215 "--- Set encoding only ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200216 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000217 "Expected errors: default",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200218 "stdin: iso8859-1:{errors}",
219 "stdout: iso8859-1:{errors}",
220 "stderr: iso8859-1:backslashreplace",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000221 "--- Set encoding and errors ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200222 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000223 "Expected errors: replace",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200224 "stdin: iso8859-1:replace",
225 "stdout: iso8859-1:replace",
226 "stderr: iso8859-1:backslashreplace"])
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000227 expected_output = expected_output.format(
228 in_encoding=expected_stream_encoding,
229 out_encoding=expected_stream_encoding,
230 errors=expected_errors)
231 # This is useful if we ever trip over odd platform behaviour
232 self.maxDiff = None
233 self.assertEqual(out.strip(), expected_output)
234
235 def test_pre_initialization_api(self):
236 """
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000237 Checks some key parts of the C-API that need to work before the runtine
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000238 is initialized (via Py_Initialize()).
239 """
240 env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path))
Victor Stinner5edcf262019-05-23 00:57:57 +0200241 out, err = self.run_embedded_interpreter("test_pre_initialization_api", env=env)
Victor Stinner01de89c2018-11-14 17:39:45 +0100242 if MS_WINDOWS:
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000243 expected_path = self.test_exe
244 else:
245 expected_path = os.path.join(os.getcwd(), "spam")
246 expected_output = f"sys.executable: {expected_path}\n"
247 self.assertIn(expected_output, out)
248 self.assertEqual(err, '')
249
250 def test_pre_initialization_sys_options(self):
251 """
252 Checks that sys.warnoptions and sys._xoptions can be set before the
253 runtime is initialized (otherwise they won't be effective).
254 """
Victor Stinnerdbdc9912019-06-18 00:11:00 +0200255 env = remove_python_envvars()
256 env['PYTHONPATH'] = os.pathsep.join(sys.path)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000257 out, err = self.run_embedded_interpreter(
Victor Stinner5edcf262019-05-23 00:57:57 +0200258 "test_pre_initialization_sys_options", env=env)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000259 expected_output = (
260 "sys.warnoptions: ['once', 'module', 'default']\n"
261 "sys._xoptions: {'not_an_option': '1', 'also_not_an_option': '2'}\n"
262 "warnings.filters[:3]: ['default', 'module', 'once']\n"
263 )
264 self.assertIn(expected_output, out)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000265 self.assertEqual(err, '')
266
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100267 def test_bpo20891(self):
268 """
269 bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
270 calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must
271 call PyEval_InitThreads() for us in this case.
272 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200273 out, err = self.run_embedded_interpreter("test_bpo20891")
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100274 self.assertEqual(out, '')
275 self.assertEqual(err, '')
276
Victor Stinner209abf72018-06-22 19:14:51 +0200277 def test_initialize_twice(self):
278 """
279 bpo-33932: Calling Py_Initialize() twice should do nothing (and not
280 crash!).
281 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200282 out, err = self.run_embedded_interpreter("test_initialize_twice")
Victor Stinner209abf72018-06-22 19:14:51 +0200283 self.assertEqual(out, '')
284 self.assertEqual(err, '')
285
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200286 def test_initialize_pymain(self):
287 """
288 bpo-34008: Calling Py_Main() after Py_Initialize() must not fail.
289 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200290 out, err = self.run_embedded_interpreter("test_initialize_pymain")
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200291 self.assertEqual(out.rstrip(), "Py_Main() after Py_Initialize: sys.argv=['-c', 'arg2']")
292 self.assertEqual(err, '')
293
Victor Stinner2f549082019-03-29 15:13:46 +0100294 def test_run_main(self):
Victor Stinner5edcf262019-05-23 00:57:57 +0200295 out, err = self.run_embedded_interpreter("test_run_main")
Victor Stinner331a6a52019-05-27 16:39:22 +0200296 self.assertEqual(out.rstrip(), "Py_RunMain(): sys.argv=['-c', 'arg2']")
Victor Stinner2f549082019-03-29 15:13:46 +0100297 self.assertEqual(err, '')
298
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000299
Victor Stinner56b29b62018-07-26 18:57:56 +0200300class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
301 maxDiff = 4096
Victor Stinner01de89c2018-11-14 17:39:45 +0100302 UTF8_MODE_ERRORS = ('surrogatepass' if MS_WINDOWS else 'surrogateescape')
303
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200304 # Marker to read the default configuration: get_default_config()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100305 GET_DEFAULT_CONFIG = object()
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200306
307 # Marker to ignore a configuration parameter
308 IGNORE_CONFIG = object()
309
Victor Stinner022be022019-05-22 23:58:50 +0200310 PRE_CONFIG_COMPAT = {
Victor Stinner20e1e252019-05-23 04:12:27 +0200311 '_config_init': API_COMPAT,
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200312 'allocator': PYMEM_ALLOCATOR_NOT_SET,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200313 'parse_argv': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200314 'configure_locale': 1,
Victor Stinner1075d162019-03-25 23:19:57 +0100315 'coerce_c_locale': 0,
316 'coerce_c_locale_warn': 0,
Victor Stinner1075d162019-03-25 23:19:57 +0100317 'utf8_mode': 0,
318 }
Victor Stinner6d1c4672019-05-20 11:02:00 +0200319 if MS_WINDOWS:
Victor Stinner022be022019-05-22 23:58:50 +0200320 PRE_CONFIG_COMPAT.update({
Victor Stinner6d1c4672019-05-20 11:02:00 +0200321 'legacy_windows_fs_encoding': 0,
322 })
Victor Stinner022be022019-05-22 23:58:50 +0200323 PRE_CONFIG_PYTHON = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200324 _config_init=API_PYTHON,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200325 parse_argv=1,
Victor Stinner425717f2019-05-20 16:38:48 +0200326 coerce_c_locale=GET_DEFAULT_CONFIG,
327 utf8_mode=GET_DEFAULT_CONFIG,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200328 )
Victor Stinner022be022019-05-22 23:58:50 +0200329 PRE_CONFIG_ISOLATED = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200330 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200331 configure_locale=0,
332 isolated=1,
333 use_environment=0,
334 utf8_mode=0,
335 dev_mode=0,
Victor Stinner425717f2019-05-20 16:38:48 +0200336 coerce_c_locale=0,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200337 )
Victor Stinnerbab0db62019-05-18 03:21:27 +0200338
Victor Stinner20004952019-03-26 02:31:11 +0100339 COPY_PRE_CONFIG = [
340 'dev_mode',
341 'isolated',
342 'use_environment',
343 ]
344
Victor Stinner331a6a52019-05-27 16:39:22 +0200345 CONFIG_COMPAT = {
Victor Stinner022be022019-05-22 23:58:50 +0200346 '_config_init': API_COMPAT,
Victor Stinner20004952019-03-26 02:31:11 +0100347 'isolated': 0,
348 'use_environment': 1,
349 'dev_mode': 0,
350
Victor Stinner56b29b62018-07-26 18:57:56 +0200351 'install_signal_handlers': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200352 'use_hash_seed': 0,
353 'hash_seed': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200354 'faulthandler': 0,
355 'tracemalloc': 0,
356 'import_time': 0,
357 'show_ref_count': 0,
358 'show_alloc_count': 0,
359 'dump_refs': 0,
360 'malloc_stats': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200361
Victor Stinnera6537fb2018-11-26 11:54:12 +0100362 'filesystem_encoding': GET_DEFAULT_CONFIG,
363 'filesystem_errors': GET_DEFAULT_CONFIG,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200364
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100365 'pycache_prefix': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200366 'program_name': GET_DEFAULT_CONFIG,
Victor Stinnercab5d072019-05-17 19:01:14 +0200367 'parse_argv': 0,
Victor Stinner62599762019-03-15 16:03:23 +0100368 'argv': [""],
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100369
370 'xoptions': [],
371 'warnoptions': [],
Victor Stinner56b29b62018-07-26 18:57:56 +0200372
Victor Stinner331a6a52019-05-27 16:39:22 +0200373 'pythonpath_env': None,
Victor Stinner01de89c2018-11-14 17:39:45 +0100374 'home': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200375 'executable': GET_DEFAULT_CONFIG,
Steve Dower9048c492019-06-29 10:34:11 -0700376 'base_executable': GET_DEFAULT_CONFIG,
Victor Stinnera6537fb2018-11-26 11:54:12 +0100377
378 'prefix': GET_DEFAULT_CONFIG,
379 'base_prefix': GET_DEFAULT_CONFIG,
380 'exec_prefix': GET_DEFAULT_CONFIG,
381 'base_exec_prefix': GET_DEFAULT_CONFIG,
Victor Stinner5eb8b072019-05-15 02:12:48 +0200382 'module_search_paths': GET_DEFAULT_CONFIG,
Victor Stinner01de89c2018-11-14 17:39:45 +0100383
Victor Stinner56b29b62018-07-26 18:57:56 +0200384 'site_import': 1,
385 'bytes_warning': 0,
386 'inspect': 0,
387 'interactive': 0,
388 'optimization_level': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200389 'parser_debug': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200390 'write_bytecode': 1,
391 'verbose': 0,
392 'quiet': 0,
393 'user_site_directory': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200394 'configure_c_stdio': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200395 'buffered_stdio': 1,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200396
Victor Stinnera6537fb2018-11-26 11:54:12 +0100397 'stdio_encoding': GET_DEFAULT_CONFIG,
398 'stdio_errors': GET_DEFAULT_CONFIG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200399
Victor Stinner62be7632019-03-01 13:10:14 +0100400 'skip_source_first_line': 0,
401 'run_command': None,
402 'run_module': None,
403 'run_filename': None,
404
Victor Stinner56b29b62018-07-26 18:57:56 +0200405 '_install_importlib': 1,
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400406 'check_hash_pycs_mode': 'default',
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200407 'pathconfig_warnings': 1,
408 '_init_main': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200409 }
Victor Stinner01de89c2018-11-14 17:39:45 +0100410 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200411 CONFIG_COMPAT.update({
Victor Stinner01de89c2018-11-14 17:39:45 +0100412 'legacy_windows_stdio': 0,
413 })
414
Victor Stinner331a6a52019-05-27 16:39:22 +0200415 CONFIG_PYTHON = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200416 _config_init=API_PYTHON,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200417 configure_c_stdio=1,
418 parse_argv=1,
419 )
Victor Stinner331a6a52019-05-27 16:39:22 +0200420 CONFIG_ISOLATED = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200421 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200422 isolated=1,
423 use_environment=0,
424 user_site_directory=0,
425 dev_mode=0,
426 install_signal_handlers=0,
427 use_hash_seed=0,
428 faulthandler=0,
429 tracemalloc=0,
430 pathconfig_warnings=0,
431 )
432 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200433 CONFIG_ISOLATED['legacy_windows_stdio'] = 0
Victor Stinnerbab0db62019-05-18 03:21:27 +0200434
Victor Stinner01de89c2018-11-14 17:39:45 +0100435 # global config
436 DEFAULT_GLOBAL_CONFIG = {
437 'Py_HasFileSystemDefaultEncoding': 0,
438 'Py_HashRandomizationFlag': 1,
439 '_Py_HasFileSystemDefaultEncodeErrors': 0,
440 }
Victor Stinner1075d162019-03-25 23:19:57 +0100441 COPY_GLOBAL_PRE_CONFIG = [
Victor Stinner1075d162019-03-25 23:19:57 +0100442 ('Py_UTF8Mode', 'utf8_mode'),
443 ]
Victor Stinner01de89c2018-11-14 17:39:45 +0100444 COPY_GLOBAL_CONFIG = [
445 # Copy core config to global config for expected values
446 # True means that the core config value is inverted (0 => 1 and 1 => 0)
447 ('Py_BytesWarningFlag', 'bytes_warning'),
448 ('Py_DebugFlag', 'parser_debug'),
449 ('Py_DontWriteBytecodeFlag', 'write_bytecode', True),
450 ('Py_FileSystemDefaultEncodeErrors', 'filesystem_errors'),
451 ('Py_FileSystemDefaultEncoding', 'filesystem_encoding'),
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200452 ('Py_FrozenFlag', 'pathconfig_warnings', True),
Victor Stinner20004952019-03-26 02:31:11 +0100453 ('Py_IgnoreEnvironmentFlag', 'use_environment', True),
Victor Stinner01de89c2018-11-14 17:39:45 +0100454 ('Py_InspectFlag', 'inspect'),
455 ('Py_InteractiveFlag', 'interactive'),
Victor Stinner20004952019-03-26 02:31:11 +0100456 ('Py_IsolatedFlag', 'isolated'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100457 ('Py_NoSiteFlag', 'site_import', True),
458 ('Py_NoUserSiteDirectory', 'user_site_directory', True),
459 ('Py_OptimizeFlag', 'optimization_level'),
460 ('Py_QuietFlag', 'quiet'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100461 ('Py_UnbufferedStdioFlag', 'buffered_stdio', True),
462 ('Py_VerboseFlag', 'verbose'),
463 ]
464 if MS_WINDOWS:
Victor Stinner1075d162019-03-25 23:19:57 +0100465 COPY_GLOBAL_PRE_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100466 ('Py_LegacyWindowsFSEncodingFlag', 'legacy_windows_fs_encoding'),
Victor Stinner1075d162019-03-25 23:19:57 +0100467 ))
468 COPY_GLOBAL_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100469 ('Py_LegacyWindowsStdioFlag', 'legacy_windows_stdio'),
470 ))
Victor Stinner56b29b62018-07-26 18:57:56 +0200471
Victor Stinner425717f2019-05-20 16:38:48 +0200472 EXPECTED_CONFIG = None
473
Victor Stinner52ad33a2019-09-25 02:10:35 +0200474 @classmethod
475 def tearDownClass(cls):
476 # clear cache
477 cls.EXPECTED_CONFIG = None
478
Victor Stinner01de89c2018-11-14 17:39:45 +0100479 def main_xoptions(self, xoptions_list):
480 xoptions = {}
481 for opt in xoptions_list:
482 if '=' in opt:
483 key, value = opt.split('=', 1)
484 xoptions[key] = value
485 else:
486 xoptions[opt] = True
487 return xoptions
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200488
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200489 def _get_expected_config_impl(self):
490 env = remove_python_envvars()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100491 code = textwrap.dedent('''
492 import json
Victor Stinnera6537fb2018-11-26 11:54:12 +0100493 import sys
Victor Stinner5eb8b072019-05-15 02:12:48 +0200494 import _testinternalcapi
Victor Stinnera6537fb2018-11-26 11:54:12 +0100495
Victor Stinner5eb8b072019-05-15 02:12:48 +0200496 configs = _testinternalcapi.get_configs()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100497
Victor Stinner425717f2019-05-20 16:38:48 +0200498 data = json.dumps(configs)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100499 data = data.encode('utf-8')
500 sys.stdout.buffer.write(data)
501 sys.stdout.buffer.flush()
502 ''')
503
504 # Use -S to not import the site module: get the proper configuration
505 # when test_embed is run from a venv (bpo-35313)
Victor Stinner5eb8b072019-05-15 02:12:48 +0200506 args = [sys.executable, '-S', '-c', code]
Victor Stinnera6537fb2018-11-26 11:54:12 +0100507 proc = subprocess.run(args, env=env,
508 stdout=subprocess.PIPE,
Victor Stinner52ad33a2019-09-25 02:10:35 +0200509 stderr=subprocess.PIPE)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100510 if proc.returncode:
511 raise Exception(f"failed to get the default config: "
512 f"stdout={proc.stdout!r} stderr={proc.stderr!r}")
513 stdout = proc.stdout.decode('utf-8')
Victor Stinner52ad33a2019-09-25 02:10:35 +0200514 # ignore stderr
Victor Stinner4631da12019-05-02 15:30:21 -0400515 try:
Victor Stinner425717f2019-05-20 16:38:48 +0200516 return json.loads(stdout)
Victor Stinner4631da12019-05-02 15:30:21 -0400517 except json.JSONDecodeError:
518 self.fail(f"fail to decode stdout: {stdout!r}")
Victor Stinnera6537fb2018-11-26 11:54:12 +0100519
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200520 def _get_expected_config(self):
521 cls = InitConfigTests
522 if cls.EXPECTED_CONFIG is None:
523 cls.EXPECTED_CONFIG = self._get_expected_config_impl()
524
525 # get a copy
Victor Stinner52ad33a2019-09-25 02:10:35 +0200526 configs = {}
527 for config_key, config_value in cls.EXPECTED_CONFIG.items():
528 config = {}
529 for key, value in config_value.items():
530 if isinstance(value, list):
531 value = value.copy()
532 config[key] = value
533 configs[config_key] = config
534 return configs
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200535
Victor Stinner425717f2019-05-20 16:38:48 +0200536 def get_expected_config(self, expected_preconfig, expected, env, api,
Victor Stinner3842f292019-08-23 16:57:54 +0100537 modify_path_cb=None):
Victor Stinner425717f2019-05-20 16:38:48 +0200538 cls = self.__class__
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200539 configs = self._get_expected_config()
Victor Stinner425717f2019-05-20 16:38:48 +0200540
541 pre_config = configs['pre_config']
542 for key, value in expected_preconfig.items():
543 if value is self.GET_DEFAULT_CONFIG:
544 expected_preconfig[key] = pre_config[key]
545
Victor Stinner022be022019-05-22 23:58:50 +0200546 if not expected_preconfig['configure_locale'] or api == API_COMPAT:
Victor Stinner425717f2019-05-20 16:38:48 +0200547 # there is no easy way to get the locale encoding before
548 # setlocale(LC_CTYPE, "") is called: don't test encodings
549 for key in ('filesystem_encoding', 'filesystem_errors',
550 'stdio_encoding', 'stdio_errors'):
551 expected[key] = self.IGNORE_CONFIG
552
553 if not expected_preconfig['configure_locale']:
554 # UTF-8 Mode depends on the locale. There is no easy way
555 # to guess if UTF-8 Mode will be enabled or not if the locale
556 # is not configured.
557 expected_preconfig['utf8_mode'] = self.IGNORE_CONFIG
558
559 if expected_preconfig['utf8_mode'] == 1:
560 if expected['filesystem_encoding'] is self.GET_DEFAULT_CONFIG:
561 expected['filesystem_encoding'] = 'utf-8'
562 if expected['filesystem_errors'] is self.GET_DEFAULT_CONFIG:
563 expected['filesystem_errors'] = self.UTF8_MODE_ERRORS
564 if expected['stdio_encoding'] is self.GET_DEFAULT_CONFIG:
565 expected['stdio_encoding'] = 'utf-8'
566 if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG:
567 expected['stdio_errors'] = 'surrogateescape'
568
Steve Dower9048c492019-06-29 10:34:11 -0700569 if sys.platform == 'win32':
570 default_executable = self.test_exe
571 elif expected['program_name'] is not self.GET_DEFAULT_CONFIG:
572 default_executable = os.path.abspath(expected['program_name'])
573 else:
574 default_executable = os.path.join(os.getcwd(), '_testembed')
Victor Stinner91c99872019-05-14 22:01:51 +0200575 if expected['executable'] is self.GET_DEFAULT_CONFIG:
Steve Dower9048c492019-06-29 10:34:11 -0700576 expected['executable'] = default_executable
577 if expected['base_executable'] is self.GET_DEFAULT_CONFIG:
578 expected['base_executable'] = default_executable
Victor Stinner91c99872019-05-14 22:01:51 +0200579 if expected['program_name'] is self.GET_DEFAULT_CONFIG:
580 expected['program_name'] = './_testembed'
581
Victor Stinner331a6a52019-05-27 16:39:22 +0200582 config = configs['config']
Victor Stinnera6537fb2018-11-26 11:54:12 +0100583 for key, value in expected.items():
584 if value is self.GET_DEFAULT_CONFIG:
Victor Stinner331a6a52019-05-27 16:39:22 +0200585 expected[key] = config[key]
Victor Stinner5eb8b072019-05-15 02:12:48 +0200586
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200587 pythonpath_env = expected['pythonpath_env']
588 if pythonpath_env is not None:
589 paths = pythonpath_env.split(os.path.pathsep)
590 expected['module_search_paths'] = [*paths, *expected['module_search_paths']]
Victor Stinner3842f292019-08-23 16:57:54 +0100591 if modify_path_cb is not None:
592 expected['module_search_paths'] = expected['module_search_paths'].copy()
593 modify_path_cb(expected['module_search_paths'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200594
Victor Stinner425717f2019-05-20 16:38:48 +0200595 for key in self.COPY_PRE_CONFIG:
596 if key not in expected_preconfig:
597 expected_preconfig[key] = expected[key]
Victor Stinner01de89c2018-11-14 17:39:45 +0100598
Victor Stinner331a6a52019-05-27 16:39:22 +0200599 def check_pre_config(self, configs, expected):
600 pre_config = dict(configs['pre_config'])
Victor Stinner425717f2019-05-20 16:38:48 +0200601 for key, value in list(expected.items()):
602 if value is self.IGNORE_CONFIG:
603 del pre_config[key]
604 del expected[key]
605 self.assertEqual(pre_config, expected)
Victor Stinner1075d162019-03-25 23:19:57 +0100606
Victor Stinner331a6a52019-05-27 16:39:22 +0200607 def check_config(self, configs, expected):
608 config = dict(configs['config'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200609 for key, value in list(expected.items()):
610 if value is self.IGNORE_CONFIG:
Victor Stinner331a6a52019-05-27 16:39:22 +0200611 del config[key]
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200612 del expected[key]
Victor Stinner331a6a52019-05-27 16:39:22 +0200613 self.assertEqual(config, expected)
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200614
Victor Stinner331a6a52019-05-27 16:39:22 +0200615 def check_global_config(self, configs):
616 pre_config = configs['pre_config']
617 config = configs['config']
Victor Stinner00b137c2018-11-13 19:59:26 +0100618
Victor Stinnera6537fb2018-11-26 11:54:12 +0100619 expected = dict(self.DEFAULT_GLOBAL_CONFIG)
Victor Stinner01de89c2018-11-14 17:39:45 +0100620 for item in self.COPY_GLOBAL_CONFIG:
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100621 if len(item) == 3:
622 global_key, core_key, opposite = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200623 expected[global_key] = 0 if config[core_key] else 1
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100624 else:
625 global_key, core_key = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200626 expected[global_key] = config[core_key]
Victor Stinner1075d162019-03-25 23:19:57 +0100627 for item in self.COPY_GLOBAL_PRE_CONFIG:
628 if len(item) == 3:
629 global_key, core_key, opposite = item
630 expected[global_key] = 0 if pre_config[core_key] else 1
631 else:
632 global_key, core_key = item
633 expected[global_key] = pre_config[core_key]
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100634
Victor Stinner331a6a52019-05-27 16:39:22 +0200635 self.assertEqual(configs['global_config'], expected)
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100636
Victor Stinner331a6a52019-05-27 16:39:22 +0200637 def check_all_configs(self, testname, expected_config=None,
Victor Stinner3842f292019-08-23 16:57:54 +0100638 expected_preconfig=None, modify_path_cb=None, stderr=None,
Victor Stinner52ad33a2019-09-25 02:10:35 +0200639 *, api, env=None, ignore_stderr=False, cwd=None):
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200640 new_env = remove_python_envvars()
641 if env is not None:
642 new_env.update(env)
643 env = new_env
Victor Stinner01de89c2018-11-14 17:39:45 +0100644
Victor Stinner022be022019-05-22 23:58:50 +0200645 if api == API_ISOLATED:
646 default_preconfig = self.PRE_CONFIG_ISOLATED
647 elif api == API_PYTHON:
648 default_preconfig = self.PRE_CONFIG_PYTHON
Victor Stinnerbab0db62019-05-18 03:21:27 +0200649 else:
Victor Stinner022be022019-05-22 23:58:50 +0200650 default_preconfig = self.PRE_CONFIG_COMPAT
Victor Stinnerbab0db62019-05-18 03:21:27 +0200651 if expected_preconfig is None:
652 expected_preconfig = {}
653 expected_preconfig = dict(default_preconfig, **expected_preconfig)
654 if expected_config is None:
655 expected_config = {}
Victor Stinner425717f2019-05-20 16:38:48 +0200656
Victor Stinner022be022019-05-22 23:58:50 +0200657 if api == API_PYTHON:
Victor Stinner331a6a52019-05-27 16:39:22 +0200658 default_config = self.CONFIG_PYTHON
Victor Stinner022be022019-05-22 23:58:50 +0200659 elif api == API_ISOLATED:
Victor Stinner331a6a52019-05-27 16:39:22 +0200660 default_config = self.CONFIG_ISOLATED
Victor Stinner425717f2019-05-20 16:38:48 +0200661 else:
Victor Stinner331a6a52019-05-27 16:39:22 +0200662 default_config = self.CONFIG_COMPAT
Victor Stinner425717f2019-05-20 16:38:48 +0200663 expected_config = dict(default_config, **expected_config)
Victor Stinner425717f2019-05-20 16:38:48 +0200664
665 self.get_expected_config(expected_preconfig,
666 expected_config, env,
Victor Stinner3842f292019-08-23 16:57:54 +0100667 api, modify_path_cb)
Victor Stinner1075d162019-03-25 23:19:57 +0100668
Victor Stinner52ad33a2019-09-25 02:10:35 +0200669 out, err = self.run_embedded_interpreter(testname,
670 env=env, cwd=cwd)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200671 if stderr is None and not expected_config['verbose']:
672 stderr = ""
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200673 if stderr is not None and not ignore_stderr:
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200674 self.assertEqual(err.rstrip(), stderr)
675 try:
Victor Stinner331a6a52019-05-27 16:39:22 +0200676 configs = json.loads(out)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200677 except json.JSONDecodeError:
678 self.fail(f"fail to decode stdout: {out!r}")
679
Victor Stinner331a6a52019-05-27 16:39:22 +0200680 self.check_pre_config(configs, expected_preconfig)
681 self.check_config(configs, expected_config)
682 self.check_global_config(configs)
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100683
Victor Stinner56b29b62018-07-26 18:57:56 +0200684 def test_init_default_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200685 self.check_all_configs("test_init_initialize_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200686
687 def test_preinit_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200688 self.check_all_configs("test_preinit_compat_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200689
690 def test_init_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200691 self.check_all_configs("test_init_compat_config", api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200692
693 def test_init_global_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100694 preconfig = {
695 'utf8_mode': 1,
696 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200697 config = {
698 'program_name': './globalvar',
699 'site_import': 0,
700 'bytes_warning': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100701 'warnoptions': ['default::BytesWarning'],
Victor Stinner56b29b62018-07-26 18:57:56 +0200702 'inspect': 1,
703 'interactive': 1,
704 'optimization_level': 2,
705 'write_bytecode': 0,
706 'verbose': 1,
707 'quiet': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200708 'buffered_stdio': 0,
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200709
Victor Stinner56b29b62018-07-26 18:57:56 +0200710 'user_site_directory': 0,
Victor Stinner54b43bb2019-05-16 18:30:15 +0200711 'pathconfig_warnings': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200712 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200713 self.check_all_configs("test_init_global_config", config, preconfig,
714 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200715
716 def test_init_from_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100717 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200718 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner1075d162019-03-25 23:19:57 +0100719 'utf8_mode': 1,
720 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200721 config = {
722 'install_signal_handlers': 0,
723 'use_hash_seed': 1,
724 'hash_seed': 123,
Victor Stinner56b29b62018-07-26 18:57:56 +0200725 'tracemalloc': 2,
726 'import_time': 1,
727 'show_ref_count': 1,
728 'show_alloc_count': 1,
729 'malloc_stats': 1,
730
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200731 'stdio_encoding': 'iso8859-1',
732 'stdio_errors': 'replace',
Victor Stinner56b29b62018-07-26 18:57:56 +0200733
734 'pycache_prefix': 'conf_pycache_prefix',
735 'program_name': './conf_program_name',
Victor Stinner67310022019-07-01 19:52:45 +0200736 'argv': ['-c', 'arg2', ],
Victor Stinnercab5d072019-05-17 19:01:14 +0200737 'parse_argv': 1,
Victor Stinner67310022019-07-01 19:52:45 +0200738 'xoptions': [
739 'config_xoption1=3',
740 'config_xoption2=',
741 'config_xoption3',
742 'cmdline_xoption',
743 ],
744 'warnoptions': [
745 'config_warnoption',
746 'cmdline_warnoption',
747 'default::BytesWarning',
748 ],
Victor Stinner2f549082019-03-29 15:13:46 +0100749 'run_command': 'pass\n',
Victor Stinner56b29b62018-07-26 18:57:56 +0200750
751 'site_import': 0,
752 'bytes_warning': 1,
753 'inspect': 1,
754 'interactive': 1,
755 'optimization_level': 2,
756 'write_bytecode': 0,
757 'verbose': 1,
758 'quiet': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200759 'configure_c_stdio': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200760 'buffered_stdio': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200761 'user_site_directory': 0,
762 'faulthandler': 1,
Victor Stinnerb75d7e22018-08-01 02:13:04 +0200763
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400764 'check_hash_pycs_mode': 'always',
Victor Stinner54b43bb2019-05-16 18:30:15 +0200765 'pathconfig_warnings': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200766 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200767 self.check_all_configs("test_init_from_config", config, preconfig,
768 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200769
Victor Stinner20e1e252019-05-23 04:12:27 +0200770 def test_init_compat_env(self):
771 preconfig = {
772 'allocator': PYMEM_ALLOCATOR_MALLOC,
773 }
774 config = {
775 'use_hash_seed': 1,
776 'hash_seed': 42,
777 'tracemalloc': 2,
778 'import_time': 1,
779 'malloc_stats': 1,
780 'inspect': 1,
781 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200782 'pythonpath_env': '/my/path',
Victor Stinner20e1e252019-05-23 04:12:27 +0200783 'pycache_prefix': 'env_pycache_prefix',
784 'write_bytecode': 0,
785 'verbose': 1,
786 'buffered_stdio': 0,
787 'stdio_encoding': 'iso8859-1',
788 'stdio_errors': 'replace',
789 'user_site_directory': 0,
790 'faulthandler': 1,
791 'warnoptions': ['EnvVar'],
792 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200793 self.check_all_configs("test_init_compat_env", config, preconfig,
794 api=API_COMPAT)
Victor Stinner20e1e252019-05-23 04:12:27 +0200795
796 def test_init_python_env(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200797 preconfig = {
798 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner022be022019-05-22 23:58:50 +0200799 'utf8_mode': 1,
Victor Stinner425717f2019-05-20 16:38:48 +0200800 }
801 config = {
802 'use_hash_seed': 1,
803 'hash_seed': 42,
804 'tracemalloc': 2,
805 'import_time': 1,
806 'malloc_stats': 1,
807 'inspect': 1,
808 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200809 'pythonpath_env': '/my/path',
Victor Stinner425717f2019-05-20 16:38:48 +0200810 'pycache_prefix': 'env_pycache_prefix',
811 'write_bytecode': 0,
812 'verbose': 1,
813 'buffered_stdio': 0,
814 'stdio_encoding': 'iso8859-1',
815 'stdio_errors': 'replace',
816 'user_site_directory': 0,
817 'faulthandler': 1,
818 'warnoptions': ['EnvVar'],
819 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200820 self.check_all_configs("test_init_python_env", config, preconfig,
821 api=API_PYTHON)
Victor Stinnerb35be4b2019-03-05 17:37:44 +0100822
823 def test_init_env_dev_mode(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200824 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
825 config = dict(dev_mode=1,
826 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100827 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200828 self.check_all_configs("test_init_env_dev_mode", config, preconfig,
829 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200830
Victor Stinner20004952019-03-26 02:31:11 +0100831 def test_init_env_dev_mode_alloc(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200832 preconfig = dict(allocator=PYMEM_ALLOCATOR_MALLOC)
833 config = dict(dev_mode=1,
834 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100835 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200836 self.check_all_configs("test_init_env_dev_mode_alloc", config, preconfig,
837 api=API_COMPAT)
Victor Stinner25d13f32019-03-06 12:51:53 +0100838
Victor Stinner56b29b62018-07-26 18:57:56 +0200839 def test_init_dev_mode(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100840 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200841 'allocator': PYMEM_ALLOCATOR_DEBUG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200842 }
Victor Stinner1075d162019-03-25 23:19:57 +0100843 config = {
844 'faulthandler': 1,
Victor Stinner20004952019-03-26 02:31:11 +0100845 'dev_mode': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100846 'warnoptions': ['default'],
Victor Stinner1075d162019-03-25 23:19:57 +0100847 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200848 self.check_all_configs("test_init_dev_mode", config, preconfig,
849 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200850
851 def test_preinit_parse_argv(self):
852 # Pre-initialize implicitly using argv: make sure that -X dev
853 # is used to configure the allocation in preinitialization
854 preconfig = {
855 'allocator': PYMEM_ALLOCATOR_DEBUG,
856 }
Victor Stinner3939c322019-06-25 15:02:43 +0200857 script_abspath = os.path.abspath('script.py')
Victor Stinner6d1c4672019-05-20 11:02:00 +0200858 config = {
Victor Stinner3939c322019-06-25 15:02:43 +0200859 'argv': [script_abspath],
860 'run_filename': script_abspath,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200861 'dev_mode': 1,
862 'faulthandler': 1,
863 'warnoptions': ['default'],
864 'xoptions': ['dev'],
865 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200866 self.check_all_configs("test_preinit_parse_argv", config, preconfig,
867 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200868
869 def test_preinit_dont_parse_argv(self):
870 # -X dev must be ignored by isolated preconfiguration
871 preconfig = {
872 'isolated': 0,
873 }
874 config = {
875 'argv': ["python3", "-E", "-I",
876 "-X", "dev", "-X", "utf8", "script.py"],
877 'isolated': 0,
878 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200879 self.check_all_configs("test_preinit_dont_parse_argv", config, preconfig,
880 api=API_ISOLATED)
Victor Stinner56b29b62018-07-26 18:57:56 +0200881
Victor Stinnercab5d072019-05-17 19:01:14 +0200882 def test_init_isolated_flag(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100883 config = {
Victor Stinner20004952019-03-26 02:31:11 +0100884 'isolated': 1,
885 'use_environment': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200886 'user_site_directory': 0,
887 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200888 self.check_all_configs("test_init_isolated_flag", config, api=API_PYTHON)
Victor Stinner56b29b62018-07-26 18:57:56 +0200889
Victor Stinner6da20a42019-03-27 00:26:18 +0100890 def test_preinit_isolated1(self):
891 # _PyPreConfig.isolated=1, _PyCoreConfig.isolated not set
Victor Stinner6da20a42019-03-27 00:26:18 +0100892 config = {
893 'isolated': 1,
894 'use_environment': 0,
895 'user_site_directory': 0,
896 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200897 self.check_all_configs("test_preinit_isolated1", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100898
899 def test_preinit_isolated2(self):
900 # _PyPreConfig.isolated=0, _PyCoreConfig.isolated=1
Victor Stinner6da20a42019-03-27 00:26:18 +0100901 config = {
902 'isolated': 1,
903 'use_environment': 0,
904 'user_site_directory': 0,
905 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200906 self.check_all_configs("test_preinit_isolated2", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100907
Victor Stinner6d1c4672019-05-20 11:02:00 +0200908 def test_preinit_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200909 self.check_all_configs("test_preinit_isolated_config", api=API_ISOLATED)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200910
Victor Stinnercab5d072019-05-17 19:01:14 +0200911 def test_init_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200912 self.check_all_configs("test_init_isolated_config", api=API_ISOLATED)
Victor Stinner5edcf262019-05-23 00:57:57 +0200913
914 def test_preinit_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200915 self.check_all_configs("test_preinit_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200916
917 def test_init_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200918 self.check_all_configs("test_init_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200919
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200920 def test_init_dont_configure_locale(self):
921 # _PyPreConfig.configure_locale=0
922 preconfig = {
923 'configure_locale': 0,
Victor Stinner425717f2019-05-20 16:38:48 +0200924 'coerce_c_locale': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200925 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200926 self.check_all_configs("test_init_dont_configure_locale", {}, preconfig,
927 api=API_PYTHON)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200928
Victor Stinner91c99872019-05-14 22:01:51 +0200929 def test_init_read_set(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200930 config = {
Victor Stinner91c99872019-05-14 22:01:51 +0200931 'program_name': './init_read_set',
932 'executable': 'my_executable',
933 }
Victor Stinner3842f292019-08-23 16:57:54 +0100934 def modify_path(path):
935 path.insert(1, "test_path_insert1")
936 path.append("test_path_append")
Victor Stinner331a6a52019-05-27 16:39:22 +0200937 self.check_all_configs("test_init_read_set", config,
938 api=API_PYTHON,
Victor Stinner3842f292019-08-23 16:57:54 +0100939 modify_path_cb=modify_path)
Victor Stinner91c99872019-05-14 22:01:51 +0200940
Victor Stinner120b7072019-08-23 18:03:08 +0100941 def test_init_sys_add(self):
942 config = {
943 'faulthandler': 1,
944 'xoptions': [
945 'config_xoption',
946 'cmdline_xoption',
947 'sysadd_xoption',
948 'faulthandler',
949 ],
950 'warnoptions': [
951 'ignore:::config_warnoption',
952 'ignore:::cmdline_warnoption',
953 'ignore:::sysadd_warnoption',
954 ],
955 }
956 self.check_all_configs("test_init_sys_add", config, api=API_PYTHON)
957
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200958 def test_init_run_main(self):
Victor Stinner5eb8b072019-05-15 02:12:48 +0200959 code = ('import _testinternalcapi, json; '
960 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +0200961 config = {
Victor Stinner5eb8b072019-05-15 02:12:48 +0200962 'argv': ['-c', 'arg2'],
Victor Stinner5eb8b072019-05-15 02:12:48 +0200963 'program_name': './python3',
964 'run_command': code + '\n',
Victor Stinnercab5d072019-05-17 19:01:14 +0200965 'parse_argv': 1,
Victor Stinner5eb8b072019-05-15 02:12:48 +0200966 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200967 self.check_all_configs("test_init_run_main", config, api=API_PYTHON)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200968
969 def test_init_main(self):
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200970 code = ('import _testinternalcapi, json; '
971 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +0200972 config = {
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200973 'argv': ['-c', 'arg2'],
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200974 'program_name': './python3',
975 'run_command': code + '\n',
Victor Stinnercab5d072019-05-17 19:01:14 +0200976 'parse_argv': 1,
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200977 '_init_main': 0,
978 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200979 self.check_all_configs("test_init_main", config,
980 api=API_PYTHON,
981 stderr="Run Python code before _Py_InitializeMain")
Victor Stinner5eb8b072019-05-15 02:12:48 +0200982
Victor Stinnercab5d072019-05-17 19:01:14 +0200983 def test_init_parse_argv(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200984 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +0200985 'parse_argv': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200986 'argv': ['-c', 'arg1', '-v', 'arg3'],
987 'program_name': './argv0',
Victor Stinnercab5d072019-05-17 19:01:14 +0200988 'run_command': 'pass\n',
989 'use_environment': 0,
990 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200991 self.check_all_configs("test_init_parse_argv", config, api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200992
Victor Stinnerae239f62019-05-16 17:02:56 +0200993 def test_init_dont_parse_argv(self):
Victor Stinner6d1c4672019-05-20 11:02:00 +0200994 pre_config = {
995 'parse_argv': 0,
996 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200997 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +0200998 'parse_argv': 0,
Victor Stinnercab5d072019-05-17 19:01:14 +0200999 'argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
1000 'program_name': './argv0',
Victor Stinnerae239f62019-05-16 17:02:56 +02001001 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001002 self.check_all_configs("test_init_dont_parse_argv", config, pre_config,
1003 api=API_PYTHON)
Victor Stinnerae239f62019-05-16 17:02:56 +02001004
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001005 def test_init_setpath(self):
1006 # Test Py_SetProgramName() + Py_SetPath()
1007 config = self._get_expected_config()
1008 paths = config['config']['module_search_paths']
1009
1010 config = {
1011 'module_search_paths': paths,
1012 'prefix': '',
1013 'base_prefix': '',
1014 'exec_prefix': '',
1015 'base_exec_prefix': '',
1016 }
1017 env = {'TESTPATH': os.path.pathsep.join(paths)}
1018 self.check_all_configs("test_init_setpath", config,
1019 api=API_COMPAT, env=env,
1020 ignore_stderr=True)
1021
Victor Stinner52ad33a2019-09-25 02:10:35 +02001022 def module_search_paths(self, prefix=None, exec_prefix=None):
1023 config = self._get_expected_config()
1024 if prefix is None:
1025 prefix = config['config']['prefix']
1026 if exec_prefix is None:
1027 exec_prefix = config['config']['prefix']
1028 if MS_WINDOWS:
1029 return config['config']['module_search_paths']
1030 else:
1031 ver = sys.version_info
1032 return [
1033 os.path.join(prefix, 'lib',
1034 f'python{ver.major}{ver.minor}.zip'),
1035 os.path.join(prefix, 'lib',
1036 f'python{ver.major}.{ver.minor}'),
1037 os.path.join(exec_prefix, 'lib',
1038 f'python{ver.major}.{ver.minor}', 'lib-dynload'),
1039 ]
1040
1041 @contextlib.contextmanager
1042 def tmpdir_with_python(self):
1043 # Temporary directory with a copy of the Python program
1044 with tempfile.TemporaryDirectory() as tmpdir:
1045 if MS_WINDOWS:
1046 # Copy pythonXY.dll (or pythonXY_d.dll)
1047 ver = sys.version_info
1048 dll = f'python{ver.major}{ver.minor}'
1049 if debug_build(sys.executable):
1050 dll += '_d'
1051 dll += '.dll'
1052 dll = os.path.join(os.path.dirname(self.test_exe), dll)
1053 dll_copy = os.path.join(tmpdir, os.path.basename(dll))
1054 shutil.copyfile(dll, dll_copy)
1055
1056 # Copy Python program
1057 exec_copy = os.path.join(tmpdir, os.path.basename(self.test_exe))
1058 shutil.copyfile(self.test_exe, exec_copy)
1059 shutil.copystat(self.test_exe, exec_copy)
1060 self.test_exe = exec_copy
1061
1062 yield tmpdir
1063
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001064 def test_init_setpythonhome(self):
1065 # Test Py_SetPythonHome(home) + PYTHONPATH env var
1066 # + Py_SetProgramName()
1067 config = self._get_expected_config()
1068 paths = config['config']['module_search_paths']
1069 paths_str = os.path.pathsep.join(paths)
1070
1071 for path in paths:
1072 if not os.path.isdir(path):
1073 continue
1074 if os.path.exists(os.path.join(path, 'os.py')):
1075 home = os.path.dirname(path)
1076 break
1077 else:
1078 self.fail(f"Unable to find home in {paths!r}")
1079
1080 prefix = exec_prefix = home
1081 ver = sys.version_info
Victor Stinner52ad33a2019-09-25 02:10:35 +02001082 expected_paths = self.module_search_paths(prefix=home, exec_prefix=home)
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001083
1084 config = {
1085 'home': home,
1086 'module_search_paths': expected_paths,
1087 'prefix': prefix,
1088 'base_prefix': prefix,
1089 'exec_prefix': exec_prefix,
1090 'base_exec_prefix': exec_prefix,
1091 'pythonpath_env': paths_str,
1092 }
1093 env = {'TESTHOME': home, 'TESTPATH': paths_str}
1094 self.check_all_configs("test_init_setpythonhome", config,
1095 api=API_COMPAT, env=env)
1096
Victor Stinner52ad33a2019-09-25 02:10:35 +02001097 def copy_paths_by_env(self, config):
1098 all_configs = self._get_expected_config()
1099 paths = all_configs['config']['module_search_paths']
1100 paths_str = os.path.pathsep.join(paths)
1101 config['pythonpath_env'] = paths_str
1102 env = {'PYTHONPATH': paths_str}
1103 return env
1104
1105 @unittest.skipIf(MS_WINDOWS, 'Windows does not use pybuilddir.txt')
1106 def test_init_pybuilddir(self):
1107 # Test path configuration with pybuilddir.txt configuration file
1108
1109 with self.tmpdir_with_python() as tmpdir:
1110 # pybuilddir.txt is a sub-directory relative to the current
1111 # directory (tmpdir)
1112 subdir = 'libdir'
1113 libdir = os.path.join(tmpdir, subdir)
1114 os.mkdir(libdir)
1115
1116 filename = os.path.join(tmpdir, 'pybuilddir.txt')
1117 with open(filename, "w", encoding="utf8") as fp:
1118 fp.write(subdir)
1119
1120 module_search_paths = self.module_search_paths()
1121 module_search_paths[-1] = libdir
1122
1123 executable = self.test_exe
1124 config = {
1125 'base_executable': executable,
1126 'executable': executable,
1127 'module_search_paths': module_search_paths,
1128 }
1129 env = self.copy_paths_by_env(config)
1130 self.check_all_configs("test_init_compat_config", config,
1131 api=API_COMPAT, env=env,
1132 ignore_stderr=True, cwd=tmpdir)
1133
1134 def test_init_pyvenv_cfg(self):
1135 # Test path configuration with pyvenv.cfg configuration file
1136
1137 with self.tmpdir_with_python() as tmpdir, \
1138 tempfile.TemporaryDirectory() as pyvenv_home:
1139 ver = sys.version_info
1140
1141 if not MS_WINDOWS:
1142 lib_dynload = os.path.join(pyvenv_home,
1143 'lib',
1144 f'python{ver.major}.{ver.minor}',
1145 'lib-dynload')
1146 os.makedirs(lib_dynload)
1147 else:
1148 lib_dynload = os.path.join(pyvenv_home, 'lib')
1149 os.makedirs(lib_dynload)
1150 # getpathp.c uses Lib\os.py as the LANDMARK
1151 shutil.copyfile(os.__file__, os.path.join(lib_dynload, 'os.py'))
1152
1153 filename = os.path.join(tmpdir, 'pyvenv.cfg')
1154 with open(filename, "w", encoding="utf8") as fp:
1155 print("home = %s" % pyvenv_home, file=fp)
1156 print("include-system-site-packages = false", file=fp)
1157
1158 paths = self.module_search_paths()
1159 if not MS_WINDOWS:
1160 paths[-1] = lib_dynload
1161 else:
1162 for index, path in enumerate(paths):
1163 if index == 0:
1164 paths[index] = os.path.join(tmpdir, os.path.basename(path))
1165 else:
1166 paths[index] = os.path.join(pyvenv_home, os.path.basename(path))
1167 paths[-1] = pyvenv_home
1168
1169 executable = self.test_exe
1170 exec_prefix = pyvenv_home
1171 config = {
1172 'base_exec_prefix': exec_prefix,
1173 'exec_prefix': exec_prefix,
1174 'base_executable': executable,
1175 'executable': executable,
1176 'module_search_paths': paths,
1177 }
1178 if MS_WINDOWS:
1179 config['base_prefix'] = pyvenv_home
1180 config['prefix'] = pyvenv_home
1181 env = self.copy_paths_by_env(config)
1182 self.check_all_configs("test_init_compat_config", config,
1183 api=API_COMPAT, env=env,
1184 ignore_stderr=True, cwd=tmpdir)
1185
Victor Stinner56b29b62018-07-26 18:57:56 +02001186
Steve Dowerb82e17e2019-05-23 08:45:22 -07001187class AuditingTests(EmbeddingTestsMixin, unittest.TestCase):
1188 def test_open_code_hook(self):
1189 self.run_embedded_interpreter("test_open_code_hook")
1190
1191 def test_audit(self):
1192 self.run_embedded_interpreter("test_audit")
1193
1194 def test_audit_subinterpreter(self):
1195 self.run_embedded_interpreter("test_audit_subinterpreter")
1196
Steve Dowere226e832019-07-01 16:03:53 -07001197 def test_audit_run_command(self):
1198 self.run_embedded_interpreter("test_audit_run_command", timeout=3, returncode=1)
1199
1200 def test_audit_run_file(self):
1201 self.run_embedded_interpreter("test_audit_run_file", timeout=3, returncode=1)
1202
1203 def test_audit_run_interactivehook(self):
1204 startup = os.path.join(self.oldcwd, support.TESTFN) + ".py"
1205 with open(startup, "w", encoding="utf-8") as f:
1206 print("import sys", file=f)
1207 print("sys.__interactivehook__ = lambda: None", file=f)
1208 try:
1209 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
1210 self.run_embedded_interpreter("test_audit_run_interactivehook", timeout=5,
1211 returncode=10, env=env)
1212 finally:
1213 os.unlink(startup)
1214
1215 def test_audit_run_startup(self):
1216 startup = os.path.join(self.oldcwd, support.TESTFN) + ".py"
1217 with open(startup, "w", encoding="utf-8") as f:
1218 print("pass", file=f)
1219 try:
1220 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
1221 self.run_embedded_interpreter("test_audit_run_startup", timeout=5,
1222 returncode=10, env=env)
1223 finally:
1224 os.unlink(startup)
1225
1226 def test_audit_run_stdin(self):
1227 self.run_embedded_interpreter("test_audit_run_stdin", timeout=3, returncode=1)
Steve Dowerb82e17e2019-05-23 08:45:22 -07001228
Nick Coghlan39f0bb52017-11-28 08:11:51 +10001229if __name__ == "__main__":
1230 unittest.main()