blob: a7d912178a2ad4d3e0a8f8b1714bcbbdb49ef505 [file] [log] [blame]
Nick Coghlan39f0bb52017-11-28 08:11:51 +10001# Run the tests in Programs/_testembed.c (tests for the CPython embedding APIs)
2from test import support
Hai Shibb0424b2020-08-04 00:47:42 +08003from test.support import import_helper
4from test.support import os_helper
Nick Coghlan39f0bb52017-11-28 08:11:51 +10005import unittest
6
7from collections import namedtuple
Victor Stinner52ad33a2019-09-25 02:10:35 +02008import contextlib
Victor Stinner7ddd56f2018-11-14 00:24:28 +01009import json
Nick Coghlan39f0bb52017-11-28 08:11:51 +100010import os
11import re
Victor Stinner52ad33a2019-09-25 02:10:35 +020012import shutil
Nick Coghlan39f0bb52017-11-28 08:11:51 +100013import subprocess
14import sys
Victor Stinner52ad33a2019-09-25 02:10:35 +020015import tempfile
Victor Stinnera6537fb2018-11-26 11:54:12 +010016import textwrap
Nick Coghlan39f0bb52017-11-28 08:11:51 +100017
18
Victor Stinner01de89c2018-11-14 17:39:45 +010019MS_WINDOWS = (os.name == 'nt')
Victor Stinner49d99f02019-09-26 04:01:49 +020020MACOS = (sys.platform == 'darwin')
Victor Stinner022be022019-05-22 23:58:50 +020021
Victor Stinnerb16b4e42019-05-17 15:20:52 +020022PYMEM_ALLOCATOR_NOT_SET = 0
23PYMEM_ALLOCATOR_DEBUG = 2
24PYMEM_ALLOCATOR_MALLOC = 3
Victor Stinner01de89c2018-11-14 17:39:45 +010025
Victor Stinner022be022019-05-22 23:58:50 +020026# _PyCoreConfig_InitCompatConfig()
27API_COMPAT = 1
28# _PyCoreConfig_InitPythonConfig()
29API_PYTHON = 2
30# _PyCoreConfig_InitIsolatedConfig()
31API_ISOLATED = 3
Victor Stinner6d1c4672019-05-20 11:02:00 +020032
Victor Stinnerf3cb8142020-11-05 18:12:33 +010033MAX_HASH_SEED = 4294967295
34
Victor Stinner01de89c2018-11-14 17:39:45 +010035
Victor Stinner52ad33a2019-09-25 02:10:35 +020036def debug_build(program):
37 program = os.path.basename(program)
38 name = os.path.splitext(program)[0]
Steve Dowerdcbaa1b2020-07-06 17:32:00 +010039 return name.casefold().endswith("_d".casefold())
Victor Stinner52ad33a2019-09-25 02:10:35 +020040
41
Victor Stinnerdbdc9912019-06-18 00:11:00 +020042def remove_python_envvars():
43 env = dict(os.environ)
44 # Remove PYTHON* environment variables to get deterministic environment
45 for key in list(env):
46 if key.startswith('PYTHON'):
47 del env[key]
48 return env
49
50
Victor Stinner56b29b62018-07-26 18:57:56 +020051class EmbeddingTestsMixin:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100052 def setUp(self):
53 here = os.path.abspath(__file__)
54 basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
55 exename = "_testembed"
Victor Stinner01de89c2018-11-14 17:39:45 +010056 if MS_WINDOWS:
Victor Stinner52ad33a2019-09-25 02:10:35 +020057 ext = ("_d" if debug_build(sys.executable) else "") + ".exe"
Nick Coghlan39f0bb52017-11-28 08:11:51 +100058 exename += ext
59 exepath = os.path.dirname(sys.executable)
60 else:
61 exepath = os.path.join(basepath, "Programs")
62 self.test_exe = exe = os.path.join(exepath, exename)
63 if not os.path.exists(exe):
64 self.skipTest("%r doesn't exist" % exe)
65 # This is needed otherwise we get a fatal error:
66 # "Py_Initialize: Unable to get the locale encoding
67 # LookupError: no codec search functions registered: can't find encoding"
68 self.oldcwd = os.getcwd()
69 os.chdir(basepath)
70
71 def tearDown(self):
72 os.chdir(self.oldcwd)
73
Steve Dowere226e832019-07-01 16:03:53 -070074 def run_embedded_interpreter(self, *args, env=None,
Victor Stinner52ad33a2019-09-25 02:10:35 +020075 timeout=None, returncode=0, input=None,
76 cwd=None):
Nick Coghlan39f0bb52017-11-28 08:11:51 +100077 """Runs a test in the embedded interpreter"""
78 cmd = [self.test_exe]
79 cmd.extend(args)
Victor Stinner01de89c2018-11-14 17:39:45 +010080 if env is not None and MS_WINDOWS:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100081 # Windows requires at least the SYSTEMROOT environment variable to
82 # start Python.
83 env = env.copy()
84 env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
85
86 p = subprocess.Popen(cmd,
87 stdout=subprocess.PIPE,
88 stderr=subprocess.PIPE,
89 universal_newlines=True,
Victor Stinner52ad33a2019-09-25 02:10:35 +020090 env=env,
91 cwd=cwd)
Victor Stinner2f549082019-03-29 15:13:46 +010092 try:
Steve Dowere226e832019-07-01 16:03:53 -070093 (out, err) = p.communicate(input=input, timeout=timeout)
Victor Stinner2f549082019-03-29 15:13:46 +010094 except:
95 p.terminate()
96 p.wait()
97 raise
Steve Dowere226e832019-07-01 16:03:53 -070098 if p.returncode != returncode and support.verbose:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100099 print(f"--- {cmd} failed ---")
100 print(f"stdout:\n{out}")
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000101 print(f"stderr:\n{err}")
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000102 print(f"------")
103
Steve Dowere226e832019-07-01 16:03:53 -0700104 self.assertEqual(p.returncode, returncode,
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000105 "bad returncode %d, stderr is %r" %
106 (p.returncode, err))
107 return out, err
108
109 def run_repeated_init_and_subinterpreters(self):
Victor Stinner5edcf262019-05-23 00:57:57 +0200110 out, err = self.run_embedded_interpreter("test_repeated_init_and_subinterpreters")
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000111 self.assertEqual(err, "")
112
113 # The output from _testembed looks like this:
114 # --- Pass 0 ---
115 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
116 # interp 1 <0x1d4f690>, thread state <0x1d35350>: id(modules) = 139650431165784
117 # interp 2 <0x1d5a690>, thread state <0x1d99ed0>: id(modules) = 139650413140368
118 # interp 3 <0x1d4f690>, thread state <0x1dc3340>: id(modules) = 139650412862200
119 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
120 # --- Pass 1 ---
121 # ...
122
123 interp_pat = (r"^interp (\d+) <(0x[\dA-F]+)>, "
124 r"thread state <(0x[\dA-F]+)>: "
125 r"id\(modules\) = ([\d]+)$")
126 Interp = namedtuple("Interp", "id interp tstate modules")
127
128 numloops = 0
129 current_run = []
130 for line in out.splitlines():
131 if line == "--- Pass {} ---".format(numloops):
132 self.assertEqual(len(current_run), 0)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000133 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000134 print(line)
135 numloops += 1
136 continue
137
138 self.assertLess(len(current_run), 5)
139 match = re.match(interp_pat, line)
140 if match is None:
141 self.assertRegex(line, interp_pat)
142
143 # Parse the line from the loop. The first line is the main
144 # interpreter and the 3 afterward are subinterpreters.
145 interp = Interp(*match.groups())
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000146 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000147 print(interp)
148 self.assertTrue(interp.interp)
149 self.assertTrue(interp.tstate)
150 self.assertTrue(interp.modules)
151 current_run.append(interp)
152
153 # The last line in the loop should be the same as the first.
154 if len(current_run) == 5:
155 main = current_run[0]
156 self.assertEqual(interp, main)
157 yield current_run
158 current_run = []
159
Victor Stinner56b29b62018-07-26 18:57:56 +0200160
161class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase):
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000162 def test_subinterps_main(self):
163 for run in self.run_repeated_init_and_subinterpreters():
164 main = run[0]
165
166 self.assertEqual(main.id, '0')
167
168 def test_subinterps_different_ids(self):
169 for run in self.run_repeated_init_and_subinterpreters():
170 main, *subs, _ = run
171
172 mainid = int(main.id)
173 for i, sub in enumerate(subs):
174 self.assertEqual(sub.id, str(mainid + i + 1))
175
176 def test_subinterps_distinct_state(self):
177 for run in self.run_repeated_init_and_subinterpreters():
178 main, *subs, _ = run
179
180 if '0x0' in main:
181 # XXX Fix on Windows (and other platforms): something
182 # is going on with the pointers in Programs/_testembed.c.
183 # interp.interp is 0x0 and interp.modules is the same
184 # between interpreters.
185 raise unittest.SkipTest('platform prints pointers as 0x0')
186
187 for sub in subs:
188 # A new subinterpreter may have the same
189 # PyInterpreterState pointer as a previous one if
190 # the earlier one has already been destroyed. So
191 # we compare with the main interpreter. The same
192 # applies to tstate.
193 self.assertNotEqual(sub.interp, main.interp)
194 self.assertNotEqual(sub.tstate, main.tstate)
195 self.assertNotEqual(sub.modules, main.modules)
196
197 def test_forced_io_encoding(self):
198 # Checks forced configuration of embedded interpreter IO streams
199 env = dict(os.environ, PYTHONIOENCODING="utf-8:surrogateescape")
Victor Stinner5edcf262019-05-23 00:57:57 +0200200 out, err = self.run_embedded_interpreter("test_forced_io_encoding", env=env)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000201 if support.verbose > 1:
202 print()
203 print(out)
204 print(err)
205 expected_stream_encoding = "utf-8"
206 expected_errors = "surrogateescape"
207 expected_output = '\n'.join([
208 "--- Use defaults ---",
209 "Expected encoding: default",
210 "Expected errors: default",
211 "stdin: {in_encoding}:{errors}",
212 "stdout: {out_encoding}:{errors}",
213 "stderr: {out_encoding}:backslashreplace",
214 "--- Set errors only ---",
215 "Expected encoding: default",
216 "Expected errors: ignore",
217 "stdin: {in_encoding}:ignore",
218 "stdout: {out_encoding}:ignore",
219 "stderr: {out_encoding}:backslashreplace",
220 "--- Set encoding only ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200221 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000222 "Expected errors: default",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200223 "stdin: iso8859-1:{errors}",
224 "stdout: iso8859-1:{errors}",
225 "stderr: iso8859-1:backslashreplace",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000226 "--- Set encoding and errors ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200227 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000228 "Expected errors: replace",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200229 "stdin: iso8859-1:replace",
230 "stdout: iso8859-1:replace",
231 "stderr: iso8859-1:backslashreplace"])
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000232 expected_output = expected_output.format(
233 in_encoding=expected_stream_encoding,
234 out_encoding=expected_stream_encoding,
235 errors=expected_errors)
236 # This is useful if we ever trip over odd platform behaviour
237 self.maxDiff = None
238 self.assertEqual(out.strip(), expected_output)
239
240 def test_pre_initialization_api(self):
241 """
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000242 Checks some key parts of the C-API that need to work before the runtine
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000243 is initialized (via Py_Initialize()).
244 """
245 env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path))
Victor Stinner5edcf262019-05-23 00:57:57 +0200246 out, err = self.run_embedded_interpreter("test_pre_initialization_api", env=env)
Victor Stinner01de89c2018-11-14 17:39:45 +0100247 if MS_WINDOWS:
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000248 expected_path = self.test_exe
249 else:
250 expected_path = os.path.join(os.getcwd(), "spam")
251 expected_output = f"sys.executable: {expected_path}\n"
252 self.assertIn(expected_output, out)
253 self.assertEqual(err, '')
254
255 def test_pre_initialization_sys_options(self):
256 """
257 Checks that sys.warnoptions and sys._xoptions can be set before the
258 runtime is initialized (otherwise they won't be effective).
259 """
Victor Stinnerdbdc9912019-06-18 00:11:00 +0200260 env = remove_python_envvars()
261 env['PYTHONPATH'] = os.pathsep.join(sys.path)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000262 out, err = self.run_embedded_interpreter(
Victor Stinner5edcf262019-05-23 00:57:57 +0200263 "test_pre_initialization_sys_options", env=env)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000264 expected_output = (
265 "sys.warnoptions: ['once', 'module', 'default']\n"
266 "sys._xoptions: {'not_an_option': '1', 'also_not_an_option': '2'}\n"
267 "warnings.filters[:3]: ['default', 'module', 'once']\n"
268 )
269 self.assertIn(expected_output, out)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000270 self.assertEqual(err, '')
271
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100272 def test_bpo20891(self):
273 """
Victor Stinner3225b9f2020-03-09 20:56:57 +0100274 bpo-20891: Calling PyGILState_Ensure in a non-Python thread must not
275 crash.
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100276 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200277 out, err = self.run_embedded_interpreter("test_bpo20891")
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100278 self.assertEqual(out, '')
279 self.assertEqual(err, '')
280
Victor Stinner209abf72018-06-22 19:14:51 +0200281 def test_initialize_twice(self):
282 """
283 bpo-33932: Calling Py_Initialize() twice should do nothing (and not
284 crash!).
285 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200286 out, err = self.run_embedded_interpreter("test_initialize_twice")
Victor Stinner209abf72018-06-22 19:14:51 +0200287 self.assertEqual(out, '')
288 self.assertEqual(err, '')
289
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200290 def test_initialize_pymain(self):
291 """
292 bpo-34008: Calling Py_Main() after Py_Initialize() must not fail.
293 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200294 out, err = self.run_embedded_interpreter("test_initialize_pymain")
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200295 self.assertEqual(out.rstrip(), "Py_Main() after Py_Initialize: sys.argv=['-c', 'arg2']")
296 self.assertEqual(err, '')
297
Victor Stinner2f549082019-03-29 15:13:46 +0100298 def test_run_main(self):
Victor Stinner5edcf262019-05-23 00:57:57 +0200299 out, err = self.run_embedded_interpreter("test_run_main")
Victor Stinner331a6a52019-05-27 16:39:22 +0200300 self.assertEqual(out.rstrip(), "Py_RunMain(): sys.argv=['-c', 'arg2']")
Victor Stinner2f549082019-03-29 15:13:46 +0100301 self.assertEqual(err, '')
302
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000303
Victor Stinner56b29b62018-07-26 18:57:56 +0200304class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
305 maxDiff = 4096
Victor Stinner01de89c2018-11-14 17:39:45 +0100306 UTF8_MODE_ERRORS = ('surrogatepass' if MS_WINDOWS else 'surrogateescape')
307
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200308 # Marker to read the default configuration: get_default_config()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100309 GET_DEFAULT_CONFIG = object()
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200310
311 # Marker to ignore a configuration parameter
312 IGNORE_CONFIG = object()
313
Victor Stinner022be022019-05-22 23:58:50 +0200314 PRE_CONFIG_COMPAT = {
Victor Stinner20e1e252019-05-23 04:12:27 +0200315 '_config_init': API_COMPAT,
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200316 'allocator': PYMEM_ALLOCATOR_NOT_SET,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200317 'parse_argv': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200318 'configure_locale': 1,
Victor Stinner1075d162019-03-25 23:19:57 +0100319 'coerce_c_locale': 0,
320 'coerce_c_locale_warn': 0,
Victor Stinner1075d162019-03-25 23:19:57 +0100321 'utf8_mode': 0,
322 }
Victor Stinner6d1c4672019-05-20 11:02:00 +0200323 if MS_WINDOWS:
Victor Stinner022be022019-05-22 23:58:50 +0200324 PRE_CONFIG_COMPAT.update({
Victor Stinner6d1c4672019-05-20 11:02:00 +0200325 'legacy_windows_fs_encoding': 0,
326 })
Victor Stinner022be022019-05-22 23:58:50 +0200327 PRE_CONFIG_PYTHON = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200328 _config_init=API_PYTHON,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200329 parse_argv=1,
Victor Stinner425717f2019-05-20 16:38:48 +0200330 coerce_c_locale=GET_DEFAULT_CONFIG,
331 utf8_mode=GET_DEFAULT_CONFIG,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200332 )
Victor Stinner022be022019-05-22 23:58:50 +0200333 PRE_CONFIG_ISOLATED = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200334 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200335 configure_locale=0,
336 isolated=1,
337 use_environment=0,
338 utf8_mode=0,
339 dev_mode=0,
Victor Stinner425717f2019-05-20 16:38:48 +0200340 coerce_c_locale=0,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200341 )
Victor Stinnerbab0db62019-05-18 03:21:27 +0200342
Victor Stinner20004952019-03-26 02:31:11 +0100343 COPY_PRE_CONFIG = [
344 'dev_mode',
345 'isolated',
346 'use_environment',
347 ]
348
Victor Stinner331a6a52019-05-27 16:39:22 +0200349 CONFIG_COMPAT = {
Victor Stinner022be022019-05-22 23:58:50 +0200350 '_config_init': API_COMPAT,
Victor Stinner20004952019-03-26 02:31:11 +0100351 'isolated': 0,
352 'use_environment': 1,
353 'dev_mode': 0,
354
Victor Stinner56b29b62018-07-26 18:57:56 +0200355 'install_signal_handlers': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200356 'use_hash_seed': 0,
357 'hash_seed': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200358 'faulthandler': 0,
359 'tracemalloc': 0,
360 'import_time': 0,
361 'show_ref_count': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200362 'dump_refs': 0,
363 'malloc_stats': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200364
Victor Stinnera6537fb2018-11-26 11:54:12 +0100365 'filesystem_encoding': GET_DEFAULT_CONFIG,
366 'filesystem_errors': GET_DEFAULT_CONFIG,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200367
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100368 'pycache_prefix': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200369 'program_name': GET_DEFAULT_CONFIG,
Victor Stinnercab5d072019-05-17 19:01:14 +0200370 'parse_argv': 0,
Victor Stinner62599762019-03-15 16:03:23 +0100371 'argv': [""],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200372 'orig_argv': [],
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100373
374 'xoptions': [],
375 'warnoptions': [],
Victor Stinner56b29b62018-07-26 18:57:56 +0200376
Victor Stinner331a6a52019-05-27 16:39:22 +0200377 'pythonpath_env': None,
Victor Stinner01de89c2018-11-14 17:39:45 +0100378 'home': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200379 'executable': GET_DEFAULT_CONFIG,
Steve Dower9048c492019-06-29 10:34:11 -0700380 'base_executable': GET_DEFAULT_CONFIG,
Victor Stinnera6537fb2018-11-26 11:54:12 +0100381
382 'prefix': GET_DEFAULT_CONFIG,
383 'base_prefix': GET_DEFAULT_CONFIG,
384 'exec_prefix': GET_DEFAULT_CONFIG,
385 'base_exec_prefix': GET_DEFAULT_CONFIG,
Victor Stinner5eb8b072019-05-15 02:12:48 +0200386 'module_search_paths': GET_DEFAULT_CONFIG,
Victor Stinnerf3cb8142020-11-05 18:12:33 +0100387 'module_search_paths_set': 1,
Sandro Mani8f023a22020-06-08 17:28:11 +0200388 'platlibdir': sys.platlibdir,
Victor Stinner01de89c2018-11-14 17:39:45 +0100389
Victor Stinner56b29b62018-07-26 18:57:56 +0200390 'site_import': 1,
391 'bytes_warning': 0,
392 'inspect': 0,
393 'interactive': 0,
394 'optimization_level': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200395 'parser_debug': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200396 'write_bytecode': 1,
397 'verbose': 0,
398 'quiet': 0,
399 'user_site_directory': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200400 'configure_c_stdio': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200401 'buffered_stdio': 1,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200402
Victor Stinnera6537fb2018-11-26 11:54:12 +0100403 'stdio_encoding': GET_DEFAULT_CONFIG,
404 'stdio_errors': GET_DEFAULT_CONFIG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200405
Victor Stinner62be7632019-03-01 13:10:14 +0100406 'skip_source_first_line': 0,
407 'run_command': None,
408 'run_module': None,
409 'run_filename': None,
410
Victor Stinner56b29b62018-07-26 18:57:56 +0200411 '_install_importlib': 1,
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400412 'check_hash_pycs_mode': 'default',
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200413 'pathconfig_warnings': 1,
414 '_init_main': 1,
Victor Stinner252346a2020-05-01 11:33:44 +0200415 '_isolated_interpreter': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200416 }
Victor Stinner01de89c2018-11-14 17:39:45 +0100417 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200418 CONFIG_COMPAT.update({
Victor Stinner01de89c2018-11-14 17:39:45 +0100419 'legacy_windows_stdio': 0,
420 })
421
Victor Stinner331a6a52019-05-27 16:39:22 +0200422 CONFIG_PYTHON = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200423 _config_init=API_PYTHON,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200424 configure_c_stdio=1,
Victor Stinnerdc42af82020-11-05 18:58:07 +0100425 parse_argv=2,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200426 )
Victor Stinner331a6a52019-05-27 16:39:22 +0200427 CONFIG_ISOLATED = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200428 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200429 isolated=1,
430 use_environment=0,
431 user_site_directory=0,
432 dev_mode=0,
433 install_signal_handlers=0,
434 use_hash_seed=0,
435 faulthandler=0,
436 tracemalloc=0,
437 pathconfig_warnings=0,
438 )
439 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200440 CONFIG_ISOLATED['legacy_windows_stdio'] = 0
Victor Stinnerbab0db62019-05-18 03:21:27 +0200441
Victor Stinner01de89c2018-11-14 17:39:45 +0100442 # global config
443 DEFAULT_GLOBAL_CONFIG = {
444 'Py_HasFileSystemDefaultEncoding': 0,
445 'Py_HashRandomizationFlag': 1,
446 '_Py_HasFileSystemDefaultEncodeErrors': 0,
447 }
Victor Stinner1075d162019-03-25 23:19:57 +0100448 COPY_GLOBAL_PRE_CONFIG = [
Victor Stinner1075d162019-03-25 23:19:57 +0100449 ('Py_UTF8Mode', 'utf8_mode'),
450 ]
Victor Stinner01de89c2018-11-14 17:39:45 +0100451 COPY_GLOBAL_CONFIG = [
452 # Copy core config to global config for expected values
453 # True means that the core config value is inverted (0 => 1 and 1 => 0)
454 ('Py_BytesWarningFlag', 'bytes_warning'),
455 ('Py_DebugFlag', 'parser_debug'),
456 ('Py_DontWriteBytecodeFlag', 'write_bytecode', True),
457 ('Py_FileSystemDefaultEncodeErrors', 'filesystem_errors'),
458 ('Py_FileSystemDefaultEncoding', 'filesystem_encoding'),
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200459 ('Py_FrozenFlag', 'pathconfig_warnings', True),
Victor Stinner20004952019-03-26 02:31:11 +0100460 ('Py_IgnoreEnvironmentFlag', 'use_environment', True),
Victor Stinner01de89c2018-11-14 17:39:45 +0100461 ('Py_InspectFlag', 'inspect'),
462 ('Py_InteractiveFlag', 'interactive'),
Victor Stinner20004952019-03-26 02:31:11 +0100463 ('Py_IsolatedFlag', 'isolated'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100464 ('Py_NoSiteFlag', 'site_import', True),
465 ('Py_NoUserSiteDirectory', 'user_site_directory', True),
466 ('Py_OptimizeFlag', 'optimization_level'),
467 ('Py_QuietFlag', 'quiet'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100468 ('Py_UnbufferedStdioFlag', 'buffered_stdio', True),
469 ('Py_VerboseFlag', 'verbose'),
470 ]
471 if MS_WINDOWS:
Victor Stinner1075d162019-03-25 23:19:57 +0100472 COPY_GLOBAL_PRE_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100473 ('Py_LegacyWindowsFSEncodingFlag', 'legacy_windows_fs_encoding'),
Victor Stinner1075d162019-03-25 23:19:57 +0100474 ))
475 COPY_GLOBAL_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100476 ('Py_LegacyWindowsStdioFlag', 'legacy_windows_stdio'),
477 ))
Victor Stinner56b29b62018-07-26 18:57:56 +0200478
Victor Stinner8f427482020-07-08 00:20:37 +0200479 # path config
480 if MS_WINDOWS:
481 PATH_CONFIG = {
482 'isolated': -1,
483 'site_import': -1,
484 'python3_dll': GET_DEFAULT_CONFIG,
485 }
486 else:
487 PATH_CONFIG = {}
488 # other keys are copied by COPY_PATH_CONFIG
489
490 COPY_PATH_CONFIG = [
491 # Copy core config to global config for expected values
492 'prefix',
493 'exec_prefix',
494 'program_name',
495 'home',
496 # program_full_path and module_search_path are copied indirectly from
497 # the core configuration in check_path_config().
498 ]
499 if MS_WINDOWS:
500 COPY_PATH_CONFIG.extend((
501 'base_executable',
502 ))
503
Victor Stinner425717f2019-05-20 16:38:48 +0200504 EXPECTED_CONFIG = None
505
Victor Stinner52ad33a2019-09-25 02:10:35 +0200506 @classmethod
507 def tearDownClass(cls):
508 # clear cache
509 cls.EXPECTED_CONFIG = None
510
Victor Stinner01de89c2018-11-14 17:39:45 +0100511 def main_xoptions(self, xoptions_list):
512 xoptions = {}
513 for opt in xoptions_list:
514 if '=' in opt:
515 key, value = opt.split('=', 1)
516 xoptions[key] = value
517 else:
518 xoptions[opt] = True
519 return xoptions
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200520
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200521 def _get_expected_config_impl(self):
522 env = remove_python_envvars()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100523 code = textwrap.dedent('''
524 import json
Victor Stinnera6537fb2018-11-26 11:54:12 +0100525 import sys
Victor Stinner5eb8b072019-05-15 02:12:48 +0200526 import _testinternalcapi
Victor Stinnera6537fb2018-11-26 11:54:12 +0100527
Victor Stinner5eb8b072019-05-15 02:12:48 +0200528 configs = _testinternalcapi.get_configs()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100529
Victor Stinner425717f2019-05-20 16:38:48 +0200530 data = json.dumps(configs)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100531 data = data.encode('utf-8')
532 sys.stdout.buffer.write(data)
533 sys.stdout.buffer.flush()
534 ''')
535
536 # Use -S to not import the site module: get the proper configuration
537 # when test_embed is run from a venv (bpo-35313)
Victor Stinner5eb8b072019-05-15 02:12:48 +0200538 args = [sys.executable, '-S', '-c', code]
Victor Stinnera6537fb2018-11-26 11:54:12 +0100539 proc = subprocess.run(args, env=env,
540 stdout=subprocess.PIPE,
Victor Stinner52ad33a2019-09-25 02:10:35 +0200541 stderr=subprocess.PIPE)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100542 if proc.returncode:
543 raise Exception(f"failed to get the default config: "
544 f"stdout={proc.stdout!r} stderr={proc.stderr!r}")
545 stdout = proc.stdout.decode('utf-8')
Victor Stinner52ad33a2019-09-25 02:10:35 +0200546 # ignore stderr
Victor Stinner4631da12019-05-02 15:30:21 -0400547 try:
Victor Stinner425717f2019-05-20 16:38:48 +0200548 return json.loads(stdout)
Victor Stinner4631da12019-05-02 15:30:21 -0400549 except json.JSONDecodeError:
550 self.fail(f"fail to decode stdout: {stdout!r}")
Victor Stinnera6537fb2018-11-26 11:54:12 +0100551
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200552 def _get_expected_config(self):
553 cls = InitConfigTests
554 if cls.EXPECTED_CONFIG is None:
555 cls.EXPECTED_CONFIG = self._get_expected_config_impl()
556
557 # get a copy
Victor Stinner52ad33a2019-09-25 02:10:35 +0200558 configs = {}
559 for config_key, config_value in cls.EXPECTED_CONFIG.items():
560 config = {}
561 for key, value in config_value.items():
562 if isinstance(value, list):
563 value = value.copy()
564 config[key] = value
565 configs[config_key] = config
566 return configs
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200567
Victor Stinner8f427482020-07-08 00:20:37 +0200568 def get_expected_config(self, expected_preconfig, expected,
569 expected_pathconfig, env, api,
Victor Stinner3842f292019-08-23 16:57:54 +0100570 modify_path_cb=None):
Victor Stinner425717f2019-05-20 16:38:48 +0200571 cls = self.__class__
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200572 configs = self._get_expected_config()
Victor Stinner425717f2019-05-20 16:38:48 +0200573
574 pre_config = configs['pre_config']
575 for key, value in expected_preconfig.items():
576 if value is self.GET_DEFAULT_CONFIG:
577 expected_preconfig[key] = pre_config[key]
578
Victor Stinner8f427482020-07-08 00:20:37 +0200579 path_config = configs['path_config']
580 for key, value in expected_pathconfig.items():
581 if value is self.GET_DEFAULT_CONFIG:
582 expected_pathconfig[key] = path_config[key]
583
Victor Stinner022be022019-05-22 23:58:50 +0200584 if not expected_preconfig['configure_locale'] or api == API_COMPAT:
Victor Stinner425717f2019-05-20 16:38:48 +0200585 # there is no easy way to get the locale encoding before
586 # setlocale(LC_CTYPE, "") is called: don't test encodings
587 for key in ('filesystem_encoding', 'filesystem_errors',
588 'stdio_encoding', 'stdio_errors'):
589 expected[key] = self.IGNORE_CONFIG
590
591 if not expected_preconfig['configure_locale']:
592 # UTF-8 Mode depends on the locale. There is no easy way
593 # to guess if UTF-8 Mode will be enabled or not if the locale
594 # is not configured.
595 expected_preconfig['utf8_mode'] = self.IGNORE_CONFIG
596
597 if expected_preconfig['utf8_mode'] == 1:
598 if expected['filesystem_encoding'] is self.GET_DEFAULT_CONFIG:
599 expected['filesystem_encoding'] = 'utf-8'
600 if expected['filesystem_errors'] is self.GET_DEFAULT_CONFIG:
601 expected['filesystem_errors'] = self.UTF8_MODE_ERRORS
602 if expected['stdio_encoding'] is self.GET_DEFAULT_CONFIG:
603 expected['stdio_encoding'] = 'utf-8'
604 if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG:
605 expected['stdio_errors'] = 'surrogateescape'
606
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100607 if MS_WINDOWS:
Steve Dower9048c492019-06-29 10:34:11 -0700608 default_executable = self.test_exe
609 elif expected['program_name'] is not self.GET_DEFAULT_CONFIG:
610 default_executable = os.path.abspath(expected['program_name'])
611 else:
612 default_executable = os.path.join(os.getcwd(), '_testembed')
Victor Stinner91c99872019-05-14 22:01:51 +0200613 if expected['executable'] is self.GET_DEFAULT_CONFIG:
Steve Dower9048c492019-06-29 10:34:11 -0700614 expected['executable'] = default_executable
615 if expected['base_executable'] is self.GET_DEFAULT_CONFIG:
616 expected['base_executable'] = default_executable
Victor Stinner91c99872019-05-14 22:01:51 +0200617 if expected['program_name'] is self.GET_DEFAULT_CONFIG:
618 expected['program_name'] = './_testembed'
619
Victor Stinner331a6a52019-05-27 16:39:22 +0200620 config = configs['config']
Victor Stinnera6537fb2018-11-26 11:54:12 +0100621 for key, value in expected.items():
622 if value is self.GET_DEFAULT_CONFIG:
Victor Stinner331a6a52019-05-27 16:39:22 +0200623 expected[key] = config[key]
Victor Stinner5eb8b072019-05-15 02:12:48 +0200624
Sandro Mani8f023a22020-06-08 17:28:11 +0200625 if expected['module_search_paths'] is not self.IGNORE_CONFIG:
626 pythonpath_env = expected['pythonpath_env']
627 if pythonpath_env is not None:
628 paths = pythonpath_env.split(os.path.pathsep)
629 expected['module_search_paths'] = [*paths, *expected['module_search_paths']]
630 if modify_path_cb is not None:
631 expected['module_search_paths'] = expected['module_search_paths'].copy()
632 modify_path_cb(expected['module_search_paths'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200633
Victor Stinner425717f2019-05-20 16:38:48 +0200634 for key in self.COPY_PRE_CONFIG:
635 if key not in expected_preconfig:
636 expected_preconfig[key] = expected[key]
Victor Stinner01de89c2018-11-14 17:39:45 +0100637
Victor Stinner331a6a52019-05-27 16:39:22 +0200638 def check_pre_config(self, configs, expected):
639 pre_config = dict(configs['pre_config'])
Victor Stinner425717f2019-05-20 16:38:48 +0200640 for key, value in list(expected.items()):
641 if value is self.IGNORE_CONFIG:
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100642 pre_config.pop(key, None)
Victor Stinner425717f2019-05-20 16:38:48 +0200643 del expected[key]
644 self.assertEqual(pre_config, expected)
Victor Stinner1075d162019-03-25 23:19:57 +0100645
Victor Stinner331a6a52019-05-27 16:39:22 +0200646 def check_config(self, configs, expected):
647 config = dict(configs['config'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200648 for key, value in list(expected.items()):
649 if value is self.IGNORE_CONFIG:
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100650 config.pop(key, None)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200651 del expected[key]
Victor Stinner331a6a52019-05-27 16:39:22 +0200652 self.assertEqual(config, expected)
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200653
Victor Stinner331a6a52019-05-27 16:39:22 +0200654 def check_global_config(self, configs):
655 pre_config = configs['pre_config']
656 config = configs['config']
Victor Stinner00b137c2018-11-13 19:59:26 +0100657
Victor Stinnera6537fb2018-11-26 11:54:12 +0100658 expected = dict(self.DEFAULT_GLOBAL_CONFIG)
Victor Stinner01de89c2018-11-14 17:39:45 +0100659 for item in self.COPY_GLOBAL_CONFIG:
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100660 if len(item) == 3:
661 global_key, core_key, opposite = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200662 expected[global_key] = 0 if config[core_key] else 1
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100663 else:
664 global_key, core_key = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200665 expected[global_key] = config[core_key]
Victor Stinner1075d162019-03-25 23:19:57 +0100666 for item in self.COPY_GLOBAL_PRE_CONFIG:
667 if len(item) == 3:
668 global_key, core_key, opposite = item
669 expected[global_key] = 0 if pre_config[core_key] else 1
670 else:
671 global_key, core_key = item
672 expected[global_key] = pre_config[core_key]
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100673
Victor Stinner331a6a52019-05-27 16:39:22 +0200674 self.assertEqual(configs['global_config'], expected)
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100675
Victor Stinner8f427482020-07-08 00:20:37 +0200676 def check_path_config(self, configs, expected):
677 config = configs['config']
678
679 for key in self.COPY_PATH_CONFIG:
680 expected[key] = config[key]
681 expected['module_search_path'] = os.path.pathsep.join(config['module_search_paths'])
682 expected['program_full_path'] = config['executable']
683
684 self.assertEqual(configs['path_config'], expected)
685
Victor Stinner331a6a52019-05-27 16:39:22 +0200686 def check_all_configs(self, testname, expected_config=None,
Victor Stinner8f427482020-07-08 00:20:37 +0200687 expected_preconfig=None, expected_pathconfig=None,
688 modify_path_cb=None,
Victor Stinner8bf39b62019-09-26 02:22:35 +0200689 stderr=None, *, api, preconfig_api=None,
690 env=None, ignore_stderr=False, cwd=None):
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200691 new_env = remove_python_envvars()
692 if env is not None:
693 new_env.update(env)
694 env = new_env
Victor Stinner01de89c2018-11-14 17:39:45 +0100695
Victor Stinner8bf39b62019-09-26 02:22:35 +0200696 if preconfig_api is None:
697 preconfig_api = api
698 if preconfig_api == API_ISOLATED:
Victor Stinner022be022019-05-22 23:58:50 +0200699 default_preconfig = self.PRE_CONFIG_ISOLATED
Victor Stinner8bf39b62019-09-26 02:22:35 +0200700 elif preconfig_api == API_PYTHON:
Victor Stinner022be022019-05-22 23:58:50 +0200701 default_preconfig = self.PRE_CONFIG_PYTHON
Victor Stinnerbab0db62019-05-18 03:21:27 +0200702 else:
Victor Stinner022be022019-05-22 23:58:50 +0200703 default_preconfig = self.PRE_CONFIG_COMPAT
Victor Stinnerbab0db62019-05-18 03:21:27 +0200704 if expected_preconfig is None:
705 expected_preconfig = {}
706 expected_preconfig = dict(default_preconfig, **expected_preconfig)
Victor Stinner8f427482020-07-08 00:20:37 +0200707
Victor Stinnerbab0db62019-05-18 03:21:27 +0200708 if expected_config is None:
709 expected_config = {}
Victor Stinner425717f2019-05-20 16:38:48 +0200710
Victor Stinner8f427482020-07-08 00:20:37 +0200711 if expected_pathconfig is None:
712 expected_pathconfig = {}
713 expected_pathconfig = dict(self.PATH_CONFIG, **expected_pathconfig)
714
Victor Stinner022be022019-05-22 23:58:50 +0200715 if api == API_PYTHON:
Victor Stinner331a6a52019-05-27 16:39:22 +0200716 default_config = self.CONFIG_PYTHON
Victor Stinner022be022019-05-22 23:58:50 +0200717 elif api == API_ISOLATED:
Victor Stinner331a6a52019-05-27 16:39:22 +0200718 default_config = self.CONFIG_ISOLATED
Victor Stinner425717f2019-05-20 16:38:48 +0200719 else:
Victor Stinner331a6a52019-05-27 16:39:22 +0200720 default_config = self.CONFIG_COMPAT
Victor Stinner425717f2019-05-20 16:38:48 +0200721 expected_config = dict(default_config, **expected_config)
Victor Stinner425717f2019-05-20 16:38:48 +0200722
723 self.get_expected_config(expected_preconfig,
Victor Stinner8f427482020-07-08 00:20:37 +0200724 expected_config,
725 expected_pathconfig,
726 env,
Victor Stinner3842f292019-08-23 16:57:54 +0100727 api, modify_path_cb)
Victor Stinner1075d162019-03-25 23:19:57 +0100728
Victor Stinner52ad33a2019-09-25 02:10:35 +0200729 out, err = self.run_embedded_interpreter(testname,
730 env=env, cwd=cwd)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200731 if stderr is None and not expected_config['verbose']:
732 stderr = ""
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200733 if stderr is not None and not ignore_stderr:
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200734 self.assertEqual(err.rstrip(), stderr)
735 try:
Victor Stinner331a6a52019-05-27 16:39:22 +0200736 configs = json.loads(out)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200737 except json.JSONDecodeError:
738 self.fail(f"fail to decode stdout: {out!r}")
739
Victor Stinner331a6a52019-05-27 16:39:22 +0200740 self.check_pre_config(configs, expected_preconfig)
741 self.check_config(configs, expected_config)
742 self.check_global_config(configs)
Victor Stinner8f427482020-07-08 00:20:37 +0200743 self.check_path_config(configs, expected_pathconfig)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100744 return configs
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100745
Victor Stinner56b29b62018-07-26 18:57:56 +0200746 def test_init_default_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200747 self.check_all_configs("test_init_initialize_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200748
749 def test_preinit_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200750 self.check_all_configs("test_preinit_compat_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200751
752 def test_init_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200753 self.check_all_configs("test_init_compat_config", api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200754
755 def test_init_global_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100756 preconfig = {
757 'utf8_mode': 1,
758 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200759 config = {
760 'program_name': './globalvar',
761 'site_import': 0,
762 'bytes_warning': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100763 'warnoptions': ['default::BytesWarning'],
Victor Stinner56b29b62018-07-26 18:57:56 +0200764 'inspect': 1,
765 'interactive': 1,
766 'optimization_level': 2,
767 'write_bytecode': 0,
768 'verbose': 1,
769 'quiet': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200770 'buffered_stdio': 0,
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200771
Victor Stinner56b29b62018-07-26 18:57:56 +0200772 'user_site_directory': 0,
Victor Stinner54b43bb2019-05-16 18:30:15 +0200773 'pathconfig_warnings': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200774 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200775 self.check_all_configs("test_init_global_config", config, preconfig,
776 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200777
778 def test_init_from_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100779 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200780 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner1075d162019-03-25 23:19:57 +0100781 'utf8_mode': 1,
782 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200783 config = {
784 'install_signal_handlers': 0,
785 'use_hash_seed': 1,
786 'hash_seed': 123,
Victor Stinner56b29b62018-07-26 18:57:56 +0200787 'tracemalloc': 2,
788 'import_time': 1,
789 'show_ref_count': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200790 'malloc_stats': 1,
791
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200792 'stdio_encoding': 'iso8859-1',
793 'stdio_errors': 'replace',
Victor Stinner56b29b62018-07-26 18:57:56 +0200794
795 'pycache_prefix': 'conf_pycache_prefix',
796 'program_name': './conf_program_name',
Victor Stinnere81f6e62020-06-08 18:12:59 +0200797 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200798 'orig_argv': ['python3',
799 '-W', 'cmdline_warnoption',
800 '-X', 'cmdline_xoption',
801 '-c', 'pass',
802 'arg2'],
Victor Stinnerdc42af82020-11-05 18:58:07 +0100803 'parse_argv': 2,
Victor Stinner67310022019-07-01 19:52:45 +0200804 'xoptions': [
805 'config_xoption1=3',
806 'config_xoption2=',
807 'config_xoption3',
808 'cmdline_xoption',
809 ],
810 'warnoptions': [
Victor Stinner67310022019-07-01 19:52:45 +0200811 'cmdline_warnoption',
812 'default::BytesWarning',
Victor Stinnerfb4ae152019-09-30 01:40:17 +0200813 'config_warnoption',
Victor Stinner67310022019-07-01 19:52:45 +0200814 ],
Victor Stinner2f549082019-03-29 15:13:46 +0100815 'run_command': 'pass\n',
Victor Stinner56b29b62018-07-26 18:57:56 +0200816
817 'site_import': 0,
818 'bytes_warning': 1,
819 'inspect': 1,
820 'interactive': 1,
821 'optimization_level': 2,
822 'write_bytecode': 0,
823 'verbose': 1,
824 'quiet': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200825 'configure_c_stdio': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200826 'buffered_stdio': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200827 'user_site_directory': 0,
828 'faulthandler': 1,
Sandro Mani8f023a22020-06-08 17:28:11 +0200829 'platlibdir': 'my_platlibdir',
830 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinnerb75d7e22018-08-01 02:13:04 +0200831
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400832 'check_hash_pycs_mode': 'always',
Victor Stinner54b43bb2019-05-16 18:30:15 +0200833 'pathconfig_warnings': 0,
Victor Stinner252346a2020-05-01 11:33:44 +0200834
835 '_isolated_interpreter': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200836 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200837 self.check_all_configs("test_init_from_config", config, preconfig,
838 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200839
Victor Stinner20e1e252019-05-23 04:12:27 +0200840 def test_init_compat_env(self):
841 preconfig = {
842 'allocator': PYMEM_ALLOCATOR_MALLOC,
843 }
844 config = {
845 'use_hash_seed': 1,
846 'hash_seed': 42,
847 'tracemalloc': 2,
848 'import_time': 1,
849 'malloc_stats': 1,
850 'inspect': 1,
851 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200852 'pythonpath_env': '/my/path',
Victor Stinner20e1e252019-05-23 04:12:27 +0200853 'pycache_prefix': 'env_pycache_prefix',
854 'write_bytecode': 0,
855 'verbose': 1,
856 'buffered_stdio': 0,
857 'stdio_encoding': 'iso8859-1',
858 'stdio_errors': 'replace',
859 'user_site_directory': 0,
860 'faulthandler': 1,
861 'warnoptions': ['EnvVar'],
Sandro Mani8f023a22020-06-08 17:28:11 +0200862 'platlibdir': 'env_platlibdir',
863 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinner20e1e252019-05-23 04:12:27 +0200864 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200865 self.check_all_configs("test_init_compat_env", config, preconfig,
866 api=API_COMPAT)
Victor Stinner20e1e252019-05-23 04:12:27 +0200867
868 def test_init_python_env(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200869 preconfig = {
870 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner022be022019-05-22 23:58:50 +0200871 'utf8_mode': 1,
Victor Stinner425717f2019-05-20 16:38:48 +0200872 }
873 config = {
874 'use_hash_seed': 1,
875 'hash_seed': 42,
876 'tracemalloc': 2,
877 'import_time': 1,
878 'malloc_stats': 1,
879 'inspect': 1,
880 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200881 'pythonpath_env': '/my/path',
Victor Stinner425717f2019-05-20 16:38:48 +0200882 'pycache_prefix': 'env_pycache_prefix',
883 'write_bytecode': 0,
884 'verbose': 1,
885 'buffered_stdio': 0,
886 'stdio_encoding': 'iso8859-1',
887 'stdio_errors': 'replace',
888 'user_site_directory': 0,
889 'faulthandler': 1,
890 'warnoptions': ['EnvVar'],
Sandro Mani8f023a22020-06-08 17:28:11 +0200891 'platlibdir': 'env_platlibdir',
892 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinner425717f2019-05-20 16:38:48 +0200893 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200894 self.check_all_configs("test_init_python_env", config, preconfig,
895 api=API_PYTHON)
Victor Stinnerb35be4b2019-03-05 17:37:44 +0100896
897 def test_init_env_dev_mode(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200898 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
899 config = dict(dev_mode=1,
900 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100901 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200902 self.check_all_configs("test_init_env_dev_mode", config, preconfig,
903 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200904
Victor Stinner20004952019-03-26 02:31:11 +0100905 def test_init_env_dev_mode_alloc(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200906 preconfig = dict(allocator=PYMEM_ALLOCATOR_MALLOC)
907 config = dict(dev_mode=1,
908 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100909 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200910 self.check_all_configs("test_init_env_dev_mode_alloc", config, preconfig,
911 api=API_COMPAT)
Victor Stinner25d13f32019-03-06 12:51:53 +0100912
Victor Stinner56b29b62018-07-26 18:57:56 +0200913 def test_init_dev_mode(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100914 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200915 'allocator': PYMEM_ALLOCATOR_DEBUG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200916 }
Victor Stinner1075d162019-03-25 23:19:57 +0100917 config = {
918 'faulthandler': 1,
Victor Stinner20004952019-03-26 02:31:11 +0100919 'dev_mode': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100920 'warnoptions': ['default'],
Victor Stinner1075d162019-03-25 23:19:57 +0100921 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200922 self.check_all_configs("test_init_dev_mode", config, preconfig,
923 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200924
925 def test_preinit_parse_argv(self):
926 # Pre-initialize implicitly using argv: make sure that -X dev
927 # is used to configure the allocation in preinitialization
928 preconfig = {
929 'allocator': PYMEM_ALLOCATOR_DEBUG,
930 }
931 config = {
Victor Stinnera1a99b42019-12-09 17:34:02 +0100932 'argv': ['script.py'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200933 'orig_argv': ['python3', '-X', 'dev', 'script.py'],
Victor Stinnera1a99b42019-12-09 17:34:02 +0100934 'run_filename': os.path.abspath('script.py'),
Victor Stinner6d1c4672019-05-20 11:02:00 +0200935 'dev_mode': 1,
936 'faulthandler': 1,
937 'warnoptions': ['default'],
938 'xoptions': ['dev'],
939 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200940 self.check_all_configs("test_preinit_parse_argv", config, preconfig,
941 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200942
943 def test_preinit_dont_parse_argv(self):
944 # -X dev must be ignored by isolated preconfiguration
945 preconfig = {
946 'isolated': 0,
947 }
Victor Stinnere81f6e62020-06-08 18:12:59 +0200948 argv = ["python3",
949 "-E", "-I",
950 "-X", "dev",
951 "-X", "utf8",
952 "script.py"]
Victor Stinner6d1c4672019-05-20 11:02:00 +0200953 config = {
Victor Stinnere81f6e62020-06-08 18:12:59 +0200954 'argv': argv,
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200955 'orig_argv': argv,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200956 'isolated': 0,
957 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200958 self.check_all_configs("test_preinit_dont_parse_argv", config, preconfig,
959 api=API_ISOLATED)
Victor Stinner56b29b62018-07-26 18:57:56 +0200960
Victor Stinnercab5d072019-05-17 19:01:14 +0200961 def test_init_isolated_flag(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100962 config = {
Victor Stinner20004952019-03-26 02:31:11 +0100963 'isolated': 1,
964 'use_environment': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200965 'user_site_directory': 0,
966 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200967 self.check_all_configs("test_init_isolated_flag", config, api=API_PYTHON)
Victor Stinner56b29b62018-07-26 18:57:56 +0200968
Victor Stinner6da20a42019-03-27 00:26:18 +0100969 def test_preinit_isolated1(self):
970 # _PyPreConfig.isolated=1, _PyCoreConfig.isolated not set
Victor Stinner6da20a42019-03-27 00:26:18 +0100971 config = {
972 'isolated': 1,
973 'use_environment': 0,
974 'user_site_directory': 0,
975 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200976 self.check_all_configs("test_preinit_isolated1", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100977
978 def test_preinit_isolated2(self):
979 # _PyPreConfig.isolated=0, _PyCoreConfig.isolated=1
Victor Stinner6da20a42019-03-27 00:26:18 +0100980 config = {
981 'isolated': 1,
982 'use_environment': 0,
983 'user_site_directory': 0,
984 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200985 self.check_all_configs("test_preinit_isolated2", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100986
Victor Stinner6d1c4672019-05-20 11:02:00 +0200987 def test_preinit_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200988 self.check_all_configs("test_preinit_isolated_config", api=API_ISOLATED)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200989
Victor Stinnercab5d072019-05-17 19:01:14 +0200990 def test_init_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200991 self.check_all_configs("test_init_isolated_config", api=API_ISOLATED)
Victor Stinner5edcf262019-05-23 00:57:57 +0200992
993 def test_preinit_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200994 self.check_all_configs("test_preinit_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200995
996 def test_init_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200997 self.check_all_configs("test_init_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200998
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200999 def test_init_dont_configure_locale(self):
1000 # _PyPreConfig.configure_locale=0
1001 preconfig = {
1002 'configure_locale': 0,
Victor Stinner425717f2019-05-20 16:38:48 +02001003 'coerce_c_locale': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +02001004 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001005 self.check_all_configs("test_init_dont_configure_locale", {}, preconfig,
1006 api=API_PYTHON)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +02001007
Victor Stinner91c99872019-05-14 22:01:51 +02001008 def test_init_read_set(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001009 config = {
Victor Stinner91c99872019-05-14 22:01:51 +02001010 'program_name': './init_read_set',
1011 'executable': 'my_executable',
1012 }
Victor Stinner3842f292019-08-23 16:57:54 +01001013 def modify_path(path):
1014 path.insert(1, "test_path_insert1")
1015 path.append("test_path_append")
Victor Stinner331a6a52019-05-27 16:39:22 +02001016 self.check_all_configs("test_init_read_set", config,
1017 api=API_PYTHON,
Victor Stinner3842f292019-08-23 16:57:54 +01001018 modify_path_cb=modify_path)
Victor Stinner91c99872019-05-14 22:01:51 +02001019
Victor Stinner120b7072019-08-23 18:03:08 +01001020 def test_init_sys_add(self):
1021 config = {
1022 'faulthandler': 1,
1023 'xoptions': [
1024 'config_xoption',
1025 'cmdline_xoption',
1026 'sysadd_xoption',
1027 'faulthandler',
1028 ],
1029 'warnoptions': [
Victor Stinner120b7072019-08-23 18:03:08 +01001030 'ignore:::cmdline_warnoption',
1031 'ignore:::sysadd_warnoption',
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001032 'ignore:::config_warnoption',
Victor Stinner120b7072019-08-23 18:03:08 +01001033 ],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001034 'orig_argv': ['python3',
1035 '-W', 'ignore:::cmdline_warnoption',
1036 '-X', 'cmdline_xoption'],
Victor Stinner120b7072019-08-23 18:03:08 +01001037 }
1038 self.check_all_configs("test_init_sys_add", config, api=API_PYTHON)
1039
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001040 def test_init_run_main(self):
Victor Stinner5eb8b072019-05-15 02:12:48 +02001041 code = ('import _testinternalcapi, json; '
1042 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +02001043 config = {
Victor Stinner5eb8b072019-05-15 02:12:48 +02001044 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001045 'orig_argv': ['python3', '-c', code, 'arg2'],
Victor Stinner5eb8b072019-05-15 02:12:48 +02001046 'program_name': './python3',
1047 'run_command': code + '\n',
Victor Stinnerdc42af82020-11-05 18:58:07 +01001048 'parse_argv': 2,
Victor Stinner5eb8b072019-05-15 02:12:48 +02001049 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001050 self.check_all_configs("test_init_run_main", config, api=API_PYTHON)
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001051
1052 def test_init_main(self):
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001053 code = ('import _testinternalcapi, json; '
1054 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +02001055 config = {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001056 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001057 'orig_argv': ['python3',
1058 '-c', code,
1059 'arg2'],
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001060 'program_name': './python3',
1061 'run_command': code + '\n',
Victor Stinnerdc42af82020-11-05 18:58:07 +01001062 'parse_argv': 2,
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001063 '_init_main': 0,
1064 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001065 self.check_all_configs("test_init_main", config,
1066 api=API_PYTHON,
1067 stderr="Run Python code before _Py_InitializeMain")
Victor Stinner5eb8b072019-05-15 02:12:48 +02001068
Victor Stinnercab5d072019-05-17 19:01:14 +02001069 def test_init_parse_argv(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001070 config = {
Victor Stinnerdc42af82020-11-05 18:58:07 +01001071 'parse_argv': 2,
Victor Stinnercab5d072019-05-17 19:01:14 +02001072 'argv': ['-c', 'arg1', '-v', 'arg3'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001073 'orig_argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnercab5d072019-05-17 19:01:14 +02001074 'program_name': './argv0',
Victor Stinnercab5d072019-05-17 19:01:14 +02001075 'run_command': 'pass\n',
1076 'use_environment': 0,
1077 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001078 self.check_all_configs("test_init_parse_argv", config, api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +02001079
Victor Stinnerae239f62019-05-16 17:02:56 +02001080 def test_init_dont_parse_argv(self):
Victor Stinner6d1c4672019-05-20 11:02:00 +02001081 pre_config = {
1082 'parse_argv': 0,
1083 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001084 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +02001085 'parse_argv': 0,
Victor Stinnercab5d072019-05-17 19:01:14 +02001086 'argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001087 'orig_argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnercab5d072019-05-17 19:01:14 +02001088 'program_name': './argv0',
Victor Stinnerae239f62019-05-16 17:02:56 +02001089 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001090 self.check_all_configs("test_init_dont_parse_argv", config, pre_config,
1091 api=API_PYTHON)
Victor Stinnerae239f62019-05-16 17:02:56 +02001092
Victor Stinner8bf39b62019-09-26 02:22:35 +02001093 def default_program_name(self, config):
1094 if MS_WINDOWS:
1095 program_name = 'python'
1096 executable = self.test_exe
1097 else:
1098 program_name = 'python3'
Victor Stinner49d99f02019-09-26 04:01:49 +02001099 if MACOS:
1100 executable = self.test_exe
1101 else:
1102 executable = shutil.which(program_name) or ''
Victor Stinner8bf39b62019-09-26 02:22:35 +02001103 config.update({
1104 'program_name': program_name,
1105 'base_executable': executable,
1106 'executable': executable,
1107 })
1108
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001109 def test_init_setpath(self):
Victor Stinner8bf39b62019-09-26 02:22:35 +02001110 # Test Py_SetPath()
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001111 config = self._get_expected_config()
1112 paths = config['config']['module_search_paths']
1113
1114 config = {
1115 'module_search_paths': paths,
1116 'prefix': '',
1117 'base_prefix': '',
1118 'exec_prefix': '',
1119 'base_exec_prefix': '',
1120 }
Victor Stinner8bf39b62019-09-26 02:22:35 +02001121 self.default_program_name(config)
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001122 env = {'TESTPATH': os.path.pathsep.join(paths)}
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001123
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001124 self.check_all_configs("test_init_setpath", config,
1125 api=API_COMPAT, env=env,
1126 ignore_stderr=True)
1127
Victor Stinner8bf39b62019-09-26 02:22:35 +02001128 def test_init_setpath_config(self):
1129 # Test Py_SetPath() with PyConfig
1130 config = self._get_expected_config()
1131 paths = config['config']['module_search_paths']
1132
1133 config = {
1134 # set by Py_SetPath()
1135 'module_search_paths': paths,
1136 'prefix': '',
1137 'base_prefix': '',
1138 'exec_prefix': '',
1139 'base_exec_prefix': '',
1140 # overriden by PyConfig
1141 'program_name': 'conf_program_name',
1142 'base_executable': 'conf_executable',
1143 'executable': 'conf_executable',
1144 }
1145 env = {'TESTPATH': os.path.pathsep.join(paths)}
Victor Stinner8bf39b62019-09-26 02:22:35 +02001146 self.check_all_configs("test_init_setpath_config", config,
Victor Stinner49d99f02019-09-26 04:01:49 +02001147 api=API_PYTHON, env=env, ignore_stderr=True)
Victor Stinner8bf39b62019-09-26 02:22:35 +02001148
Victor Stinner52ad33a2019-09-25 02:10:35 +02001149 def module_search_paths(self, prefix=None, exec_prefix=None):
1150 config = self._get_expected_config()
1151 if prefix is None:
1152 prefix = config['config']['prefix']
1153 if exec_prefix is None:
1154 exec_prefix = config['config']['prefix']
1155 if MS_WINDOWS:
1156 return config['config']['module_search_paths']
1157 else:
1158 ver = sys.version_info
1159 return [
Victor Stinner8510f432020-03-10 09:53:09 +01001160 os.path.join(prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001161 f'python{ver.major}{ver.minor}.zip'),
Victor Stinner8510f432020-03-10 09:53:09 +01001162 os.path.join(prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001163 f'python{ver.major}.{ver.minor}'),
Victor Stinner8510f432020-03-10 09:53:09 +01001164 os.path.join(exec_prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001165 f'python{ver.major}.{ver.minor}', 'lib-dynload'),
1166 ]
1167
1168 @contextlib.contextmanager
1169 def tmpdir_with_python(self):
1170 # Temporary directory with a copy of the Python program
1171 with tempfile.TemporaryDirectory() as tmpdir:
Victor Stinner00508a72019-09-25 16:30:36 +02001172 # bpo-38234: On macOS and FreeBSD, the temporary directory
1173 # can be symbolic link. For example, /tmp can be a symbolic link
1174 # to /var/tmp. Call realpath() to resolve all symbolic links.
1175 tmpdir = os.path.realpath(tmpdir)
1176
Victor Stinner52ad33a2019-09-25 02:10:35 +02001177 if MS_WINDOWS:
1178 # Copy pythonXY.dll (or pythonXY_d.dll)
1179 ver = sys.version_info
1180 dll = f'python{ver.major}{ver.minor}'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001181 dll3 = f'python{ver.major}'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001182 if debug_build(sys.executable):
1183 dll += '_d'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001184 dll3 += '_d'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001185 dll += '.dll'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001186 dll3 += '.dll'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001187 dll = os.path.join(os.path.dirname(self.test_exe), dll)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001188 dll3 = os.path.join(os.path.dirname(self.test_exe), dll3)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001189 dll_copy = os.path.join(tmpdir, os.path.basename(dll))
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001190 dll3_copy = os.path.join(tmpdir, os.path.basename(dll3))
Victor Stinner52ad33a2019-09-25 02:10:35 +02001191 shutil.copyfile(dll, dll_copy)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001192 shutil.copyfile(dll3, dll3_copy)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001193
1194 # Copy Python program
1195 exec_copy = os.path.join(tmpdir, os.path.basename(self.test_exe))
1196 shutil.copyfile(self.test_exe, exec_copy)
1197 shutil.copystat(self.test_exe, exec_copy)
1198 self.test_exe = exec_copy
1199
1200 yield tmpdir
1201
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001202 def test_init_setpythonhome(self):
Victor Stinner8bf39b62019-09-26 02:22:35 +02001203 # Test Py_SetPythonHome(home) with PYTHONPATH env var
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001204 config = self._get_expected_config()
1205 paths = config['config']['module_search_paths']
1206 paths_str = os.path.pathsep.join(paths)
1207
1208 for path in paths:
1209 if not os.path.isdir(path):
1210 continue
1211 if os.path.exists(os.path.join(path, 'os.py')):
1212 home = os.path.dirname(path)
1213 break
1214 else:
1215 self.fail(f"Unable to find home in {paths!r}")
1216
1217 prefix = exec_prefix = home
1218 ver = sys.version_info
Victor Stinner52ad33a2019-09-25 02:10:35 +02001219 expected_paths = self.module_search_paths(prefix=home, exec_prefix=home)
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001220
1221 config = {
1222 'home': home,
1223 'module_search_paths': expected_paths,
1224 'prefix': prefix,
1225 'base_prefix': prefix,
1226 'exec_prefix': exec_prefix,
1227 'base_exec_prefix': exec_prefix,
1228 'pythonpath_env': paths_str,
1229 }
Victor Stinner8bf39b62019-09-26 02:22:35 +02001230 self.default_program_name(config)
1231 env = {'TESTHOME': home, 'PYTHONPATH': paths_str}
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001232 self.check_all_configs("test_init_setpythonhome", config,
1233 api=API_COMPAT, env=env)
1234
Victor Stinner52ad33a2019-09-25 02:10:35 +02001235 def copy_paths_by_env(self, config):
1236 all_configs = self._get_expected_config()
1237 paths = all_configs['config']['module_search_paths']
1238 paths_str = os.path.pathsep.join(paths)
1239 config['pythonpath_env'] = paths_str
1240 env = {'PYTHONPATH': paths_str}
1241 return env
1242
1243 @unittest.skipIf(MS_WINDOWS, 'Windows does not use pybuilddir.txt')
1244 def test_init_pybuilddir(self):
1245 # Test path configuration with pybuilddir.txt configuration file
1246
1247 with self.tmpdir_with_python() as tmpdir:
1248 # pybuilddir.txt is a sub-directory relative to the current
1249 # directory (tmpdir)
1250 subdir = 'libdir'
1251 libdir = os.path.join(tmpdir, subdir)
1252 os.mkdir(libdir)
1253
1254 filename = os.path.join(tmpdir, 'pybuilddir.txt')
1255 with open(filename, "w", encoding="utf8") as fp:
1256 fp.write(subdir)
1257
1258 module_search_paths = self.module_search_paths()
1259 module_search_paths[-1] = libdir
1260
1261 executable = self.test_exe
1262 config = {
1263 'base_executable': executable,
1264 'executable': executable,
1265 'module_search_paths': module_search_paths,
1266 }
1267 env = self.copy_paths_by_env(config)
1268 self.check_all_configs("test_init_compat_config", config,
1269 api=API_COMPAT, env=env,
1270 ignore_stderr=True, cwd=tmpdir)
1271
1272 def test_init_pyvenv_cfg(self):
1273 # Test path configuration with pyvenv.cfg configuration file
1274
1275 with self.tmpdir_with_python() as tmpdir, \
1276 tempfile.TemporaryDirectory() as pyvenv_home:
1277 ver = sys.version_info
1278
1279 if not MS_WINDOWS:
1280 lib_dynload = os.path.join(pyvenv_home,
Victor Stinner8510f432020-03-10 09:53:09 +01001281 sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001282 f'python{ver.major}.{ver.minor}',
1283 'lib-dynload')
1284 os.makedirs(lib_dynload)
1285 else:
1286 lib_dynload = os.path.join(pyvenv_home, 'lib')
1287 os.makedirs(lib_dynload)
1288 # getpathp.c uses Lib\os.py as the LANDMARK
1289 shutil.copyfile(os.__file__, os.path.join(lib_dynload, 'os.py'))
1290
1291 filename = os.path.join(tmpdir, 'pyvenv.cfg')
1292 with open(filename, "w", encoding="utf8") as fp:
1293 print("home = %s" % pyvenv_home, file=fp)
1294 print("include-system-site-packages = false", file=fp)
1295
1296 paths = self.module_search_paths()
1297 if not MS_WINDOWS:
1298 paths[-1] = lib_dynload
1299 else:
1300 for index, path in enumerate(paths):
1301 if index == 0:
1302 paths[index] = os.path.join(tmpdir, os.path.basename(path))
1303 else:
1304 paths[index] = os.path.join(pyvenv_home, os.path.basename(path))
1305 paths[-1] = pyvenv_home
1306
1307 executable = self.test_exe
1308 exec_prefix = pyvenv_home
1309 config = {
1310 'base_exec_prefix': exec_prefix,
1311 'exec_prefix': exec_prefix,
1312 'base_executable': executable,
1313 'executable': executable,
1314 'module_search_paths': paths,
1315 }
Victor Stinner8f427482020-07-08 00:20:37 +02001316 path_config = {}
Victor Stinner52ad33a2019-09-25 02:10:35 +02001317 if MS_WINDOWS:
1318 config['base_prefix'] = pyvenv_home
1319 config['prefix'] = pyvenv_home
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001320
Victor Stinner8f427482020-07-08 00:20:37 +02001321 ver = sys.version_info
1322 dll = f'python{ver.major}'
1323 if debug_build(executable):
1324 dll += '_d'
1325 dll += '.DLL'
1326 dll = os.path.join(os.path.dirname(executable), dll)
1327 path_config['python3_dll'] = dll
1328
1329 env = self.copy_paths_by_env(config)
1330 self.check_all_configs("test_init_compat_config", config,
1331 expected_pathconfig=path_config,
1332 api=API_COMPAT, env=env,
1333 ignore_stderr=True, cwd=tmpdir)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001334
Victor Stinner12f2f172019-09-26 15:51:50 +02001335 def test_global_pathconfig(self):
1336 # Test C API functions getting the path configuration:
1337 #
1338 # - Py_GetExecPrefix()
1339 # - Py_GetPath()
1340 # - Py_GetPrefix()
1341 # - Py_GetProgramFullPath()
1342 # - Py_GetProgramName()
1343 # - Py_GetPythonHome()
1344 #
1345 # The global path configuration (_Py_path_config) must be a copy
1346 # of the path configuration of PyInterpreter.config (PyConfig).
Hai Shibb0424b2020-08-04 00:47:42 +08001347 ctypes = import_helper.import_module('ctypes')
1348 _testinternalcapi = import_helper.import_module('_testinternalcapi')
Victor Stinner12f2f172019-09-26 15:51:50 +02001349
1350 def get_func(name):
1351 func = getattr(ctypes.pythonapi, name)
1352 func.argtypes = ()
1353 func.restype = ctypes.c_wchar_p
1354 return func
1355
1356 Py_GetPath = get_func('Py_GetPath')
1357 Py_GetPrefix = get_func('Py_GetPrefix')
1358 Py_GetExecPrefix = get_func('Py_GetExecPrefix')
1359 Py_GetProgramName = get_func('Py_GetProgramName')
1360 Py_GetProgramFullPath = get_func('Py_GetProgramFullPath')
1361 Py_GetPythonHome = get_func('Py_GetPythonHome')
1362
1363 config = _testinternalcapi.get_configs()['config']
1364
1365 self.assertEqual(Py_GetPath().split(os.path.pathsep),
1366 config['module_search_paths'])
1367 self.assertEqual(Py_GetPrefix(), config['prefix'])
1368 self.assertEqual(Py_GetExecPrefix(), config['exec_prefix'])
1369 self.assertEqual(Py_GetProgramName(), config['program_name'])
1370 self.assertEqual(Py_GetProgramFullPath(), config['executable'])
1371 self.assertEqual(Py_GetPythonHome(), config['home'])
1372
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001373 def test_init_warnoptions(self):
1374 # lowest to highest priority
1375 warnoptions = [
1376 'ignore:::PyConfig_Insert0', # PyWideStringList_Insert(0)
1377 'default', # PyConfig.dev_mode=1
1378 'ignore:::env1', # PYTHONWARNINGS env var
1379 'ignore:::env2', # PYTHONWARNINGS env var
1380 'ignore:::cmdline1', # -W opt command line option
1381 'ignore:::cmdline2', # -W opt command line option
1382 'default::BytesWarning', # PyConfig.bytes_warnings=1
1383 'ignore:::PySys_AddWarnOption1', # PySys_AddWarnOption()
1384 'ignore:::PySys_AddWarnOption2', # PySys_AddWarnOption()
1385 'ignore:::PyConfig_BeforeRead', # PyConfig.warnoptions
1386 'ignore:::PyConfig_AfterRead'] # PyWideStringList_Append()
1387 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
1388 config = {
1389 'dev_mode': 1,
1390 'faulthandler': 1,
1391 'bytes_warning': 1,
1392 'warnoptions': warnoptions,
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001393 'orig_argv': ['python3',
1394 '-Wignore:::cmdline1',
1395 '-Wignore:::cmdline2'],
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001396 }
1397 self.check_all_configs("test_init_warnoptions", config, preconfig,
1398 api=API_PYTHON)
1399
Victor Stinner048a3562020-11-05 00:45:56 +01001400 def test_init_set_config(self):
1401 config = {
1402 '_init_main': 0,
1403 'bytes_warning': 2,
1404 'warnoptions': ['error::BytesWarning'],
1405 }
1406 self.check_all_configs("test_init_set_config", config,
1407 api=API_ISOLATED)
1408
Victor Stinnere81f6e62020-06-08 18:12:59 +02001409 def test_get_argc_argv(self):
1410 self.run_embedded_interpreter("test_get_argc_argv")
1411 # ignore output
1412
Victor Stinner56b29b62018-07-26 18:57:56 +02001413
Victor Stinnerf3cb8142020-11-05 18:12:33 +01001414class SetConfigTests(unittest.TestCase):
1415 def test_set_config(self):
1416 # bpo-42260: Test _PyInterpreterState_SetConfig()
1417 cmd = [sys.executable, '-I', '-m', 'test._test_embed_set_config']
1418 proc = subprocess.run(cmd,
1419 stdout=subprocess.PIPE,
1420 stderr=subprocess.PIPE)
1421 self.assertEqual(proc.returncode, 0,
1422 (proc.returncode, proc.stdout, proc.stderr))
1423
1424
Steve Dowerb82e17e2019-05-23 08:45:22 -07001425class AuditingTests(EmbeddingTestsMixin, unittest.TestCase):
1426 def test_open_code_hook(self):
1427 self.run_embedded_interpreter("test_open_code_hook")
1428
1429 def test_audit(self):
1430 self.run_embedded_interpreter("test_audit")
1431
1432 def test_audit_subinterpreter(self):
1433 self.run_embedded_interpreter("test_audit_subinterpreter")
1434
Steve Dowere226e832019-07-01 16:03:53 -07001435 def test_audit_run_command(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001436 self.run_embedded_interpreter("test_audit_run_command",
1437 timeout=support.SHORT_TIMEOUT,
1438 returncode=1)
Steve Dowere226e832019-07-01 16:03:53 -07001439
1440 def test_audit_run_file(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001441 self.run_embedded_interpreter("test_audit_run_file",
1442 timeout=support.SHORT_TIMEOUT,
1443 returncode=1)
Steve Dowere226e832019-07-01 16:03:53 -07001444
1445 def test_audit_run_interactivehook(self):
Hai Shibb0424b2020-08-04 00:47:42 +08001446 startup = os.path.join(self.oldcwd, os_helper.TESTFN) + ".py"
Steve Dowere226e832019-07-01 16:03:53 -07001447 with open(startup, "w", encoding="utf-8") as f:
1448 print("import sys", file=f)
1449 print("sys.__interactivehook__ = lambda: None", file=f)
1450 try:
1451 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
Victor Stinner7772b1a2019-12-11 22:17:04 +01001452 self.run_embedded_interpreter("test_audit_run_interactivehook",
1453 timeout=support.SHORT_TIMEOUT,
Steve Dowere226e832019-07-01 16:03:53 -07001454 returncode=10, env=env)
1455 finally:
1456 os.unlink(startup)
1457
1458 def test_audit_run_startup(self):
Hai Shibb0424b2020-08-04 00:47:42 +08001459 startup = os.path.join(self.oldcwd, os_helper.TESTFN) + ".py"
Steve Dowere226e832019-07-01 16:03:53 -07001460 with open(startup, "w", encoding="utf-8") as f:
1461 print("pass", file=f)
1462 try:
1463 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
Victor Stinner7772b1a2019-12-11 22:17:04 +01001464 self.run_embedded_interpreter("test_audit_run_startup",
1465 timeout=support.SHORT_TIMEOUT,
Steve Dowere226e832019-07-01 16:03:53 -07001466 returncode=10, env=env)
1467 finally:
1468 os.unlink(startup)
1469
1470 def test_audit_run_stdin(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001471 self.run_embedded_interpreter("test_audit_run_stdin",
1472 timeout=support.SHORT_TIMEOUT,
1473 returncode=1)
Steve Dowerb82e17e2019-05-23 08:45:22 -07001474
Nick Coghlan39f0bb52017-11-28 08:11:51 +10001475if __name__ == "__main__":
1476 unittest.main()