blob: da9b555522f4fa0f09daf537063d9f743032e1a0 [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 Stinnerece38412021-06-23 17:47:38 +020033INIT_LOOPS = 16
Victor Stinnerf3cb8142020-11-05 18:12:33 +010034MAX_HASH_SEED = 4294967295
35
Victor Stinner01de89c2018-11-14 17:39:45 +010036
Victor Stinner52ad33a2019-09-25 02:10:35 +020037def debug_build(program):
38 program = os.path.basename(program)
39 name = os.path.splitext(program)[0]
Steve Dowerdcbaa1b2020-07-06 17:32:00 +010040 return name.casefold().endswith("_d".casefold())
Victor Stinner52ad33a2019-09-25 02:10:35 +020041
42
Victor Stinnerdbdc9912019-06-18 00:11:00 +020043def remove_python_envvars():
44 env = dict(os.environ)
45 # Remove PYTHON* environment variables to get deterministic environment
46 for key in list(env):
47 if key.startswith('PYTHON'):
48 del env[key]
49 return env
50
51
Victor Stinner56b29b62018-07-26 18:57:56 +020052class EmbeddingTestsMixin:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100053 def setUp(self):
54 here = os.path.abspath(__file__)
55 basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
56 exename = "_testembed"
Victor Stinner01de89c2018-11-14 17:39:45 +010057 if MS_WINDOWS:
Victor Stinner52ad33a2019-09-25 02:10:35 +020058 ext = ("_d" if debug_build(sys.executable) else "") + ".exe"
Nick Coghlan39f0bb52017-11-28 08:11:51 +100059 exename += ext
60 exepath = os.path.dirname(sys.executable)
61 else:
62 exepath = os.path.join(basepath, "Programs")
63 self.test_exe = exe = os.path.join(exepath, exename)
64 if not os.path.exists(exe):
65 self.skipTest("%r doesn't exist" % exe)
66 # This is needed otherwise we get a fatal error:
67 # "Py_Initialize: Unable to get the locale encoding
68 # LookupError: no codec search functions registered: can't find encoding"
69 self.oldcwd = os.getcwd()
70 os.chdir(basepath)
71
72 def tearDown(self):
73 os.chdir(self.oldcwd)
74
Steve Dowere226e832019-07-01 16:03:53 -070075 def run_embedded_interpreter(self, *args, env=None,
Victor Stinner52ad33a2019-09-25 02:10:35 +020076 timeout=None, returncode=0, input=None,
77 cwd=None):
Nick Coghlan39f0bb52017-11-28 08:11:51 +100078 """Runs a test in the embedded interpreter"""
79 cmd = [self.test_exe]
80 cmd.extend(args)
Victor Stinner01de89c2018-11-14 17:39:45 +010081 if env is not None and MS_WINDOWS:
Nick Coghlan39f0bb52017-11-28 08:11:51 +100082 # Windows requires at least the SYSTEMROOT environment variable to
83 # start Python.
84 env = env.copy()
85 env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
86
87 p = subprocess.Popen(cmd,
88 stdout=subprocess.PIPE,
89 stderr=subprocess.PIPE,
90 universal_newlines=True,
Victor Stinner52ad33a2019-09-25 02:10:35 +020091 env=env,
92 cwd=cwd)
Victor Stinner2f549082019-03-29 15:13:46 +010093 try:
Steve Dowere226e832019-07-01 16:03:53 -070094 (out, err) = p.communicate(input=input, timeout=timeout)
Victor Stinner2f549082019-03-29 15:13:46 +010095 except:
96 p.terminate()
97 p.wait()
98 raise
Steve Dowere226e832019-07-01 16:03:53 -070099 if p.returncode != returncode and support.verbose:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000100 print(f"--- {cmd} failed ---")
101 print(f"stdout:\n{out}")
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000102 print(f"stderr:\n{err}")
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000103 print(f"------")
104
Steve Dowere226e832019-07-01 16:03:53 -0700105 self.assertEqual(p.returncode, returncode,
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000106 "bad returncode %d, stderr is %r" %
107 (p.returncode, err))
108 return out, err
109
110 def run_repeated_init_and_subinterpreters(self):
Victor Stinner5edcf262019-05-23 00:57:57 +0200111 out, err = self.run_embedded_interpreter("test_repeated_init_and_subinterpreters")
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000112 self.assertEqual(err, "")
113
114 # The output from _testembed looks like this:
Victor Stinnerece38412021-06-23 17:47:38 +0200115 # --- Pass 1 ---
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000116 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
117 # interp 1 <0x1d4f690>, thread state <0x1d35350>: id(modules) = 139650431165784
118 # interp 2 <0x1d5a690>, thread state <0x1d99ed0>: id(modules) = 139650413140368
119 # interp 3 <0x1d4f690>, thread state <0x1dc3340>: id(modules) = 139650412862200
120 # interp 0 <0x1cf9330>, thread state <0x1cf9700>: id(modules) = 139650431942728
Victor Stinnerece38412021-06-23 17:47:38 +0200121 # --- Pass 2 ---
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000122 # ...
123
124 interp_pat = (r"^interp (\d+) <(0x[\dA-F]+)>, "
125 r"thread state <(0x[\dA-F]+)>: "
126 r"id\(modules\) = ([\d]+)$")
127 Interp = namedtuple("Interp", "id interp tstate modules")
128
Victor Stinnerece38412021-06-23 17:47:38 +0200129 numloops = 1
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000130 current_run = []
131 for line in out.splitlines():
132 if line == "--- Pass {} ---".format(numloops):
133 self.assertEqual(len(current_run), 0)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000134 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000135 print(line)
136 numloops += 1
137 continue
138
139 self.assertLess(len(current_run), 5)
140 match = re.match(interp_pat, line)
141 if match is None:
142 self.assertRegex(line, interp_pat)
143
144 # Parse the line from the loop. The first line is the main
145 # interpreter and the 3 afterward are subinterpreters.
146 interp = Interp(*match.groups())
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000147 if support.verbose > 1:
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000148 print(interp)
149 self.assertTrue(interp.interp)
150 self.assertTrue(interp.tstate)
151 self.assertTrue(interp.modules)
152 current_run.append(interp)
153
154 # The last line in the loop should be the same as the first.
155 if len(current_run) == 5:
156 main = current_run[0]
157 self.assertEqual(interp, main)
158 yield current_run
159 current_run = []
160
Victor Stinner56b29b62018-07-26 18:57:56 +0200161
162class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase):
Victor Stinnerece38412021-06-23 17:47:38 +0200163 maxDiff = 100 * 50
164
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000165 def test_subinterps_main(self):
166 for run in self.run_repeated_init_and_subinterpreters():
167 main = run[0]
168
169 self.assertEqual(main.id, '0')
170
171 def test_subinterps_different_ids(self):
172 for run in self.run_repeated_init_and_subinterpreters():
173 main, *subs, _ = run
174
175 mainid = int(main.id)
176 for i, sub in enumerate(subs):
177 self.assertEqual(sub.id, str(mainid + i + 1))
178
179 def test_subinterps_distinct_state(self):
180 for run in self.run_repeated_init_and_subinterpreters():
181 main, *subs, _ = run
182
183 if '0x0' in main:
184 # XXX Fix on Windows (and other platforms): something
185 # is going on with the pointers in Programs/_testembed.c.
186 # interp.interp is 0x0 and interp.modules is the same
187 # between interpreters.
188 raise unittest.SkipTest('platform prints pointers as 0x0')
189
190 for sub in subs:
191 # A new subinterpreter may have the same
192 # PyInterpreterState pointer as a previous one if
193 # the earlier one has already been destroyed. So
194 # we compare with the main interpreter. The same
195 # applies to tstate.
196 self.assertNotEqual(sub.interp, main.interp)
197 self.assertNotEqual(sub.tstate, main.tstate)
198 self.assertNotEqual(sub.modules, main.modules)
199
Victor Stinnerece38412021-06-23 17:47:38 +0200200 def test_repeated_init_and_inittab(self):
201 out, err = self.run_embedded_interpreter("test_repeated_init_and_inittab")
202 self.assertEqual(err, "")
203
204 lines = [f"--- Pass {i} ---" for i in range(1, INIT_LOOPS+1)]
205 lines = "\n".join(lines) + "\n"
206 self.assertEqual(out, lines)
207
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000208 def test_forced_io_encoding(self):
209 # Checks forced configuration of embedded interpreter IO streams
210 env = dict(os.environ, PYTHONIOENCODING="utf-8:surrogateescape")
Victor Stinner5edcf262019-05-23 00:57:57 +0200211 out, err = self.run_embedded_interpreter("test_forced_io_encoding", env=env)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000212 if support.verbose > 1:
213 print()
214 print(out)
215 print(err)
216 expected_stream_encoding = "utf-8"
217 expected_errors = "surrogateescape"
218 expected_output = '\n'.join([
219 "--- Use defaults ---",
220 "Expected encoding: default",
221 "Expected errors: default",
222 "stdin: {in_encoding}:{errors}",
223 "stdout: {out_encoding}:{errors}",
224 "stderr: {out_encoding}:backslashreplace",
225 "--- Set errors only ---",
226 "Expected encoding: default",
227 "Expected errors: ignore",
228 "stdin: {in_encoding}:ignore",
229 "stdout: {out_encoding}:ignore",
230 "stderr: {out_encoding}:backslashreplace",
231 "--- Set encoding only ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200232 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000233 "Expected errors: default",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200234 "stdin: iso8859-1:{errors}",
235 "stdout: iso8859-1:{errors}",
236 "stderr: iso8859-1:backslashreplace",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000237 "--- Set encoding and errors ---",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200238 "Expected encoding: iso8859-1",
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000239 "Expected errors: replace",
Victor Stinner9e4994d2018-08-28 23:26:33 +0200240 "stdin: iso8859-1:replace",
241 "stdout: iso8859-1:replace",
242 "stderr: iso8859-1:backslashreplace"])
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000243 expected_output = expected_output.format(
244 in_encoding=expected_stream_encoding,
245 out_encoding=expected_stream_encoding,
246 errors=expected_errors)
247 # This is useful if we ever trip over odd platform behaviour
248 self.maxDiff = None
249 self.assertEqual(out.strip(), expected_output)
250
251 def test_pre_initialization_api(self):
252 """
Christian Clausscfca4a62021-10-07 17:49:47 +0200253 Checks some key parts of the C-API that need to work before the runtime
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000254 is initialized (via Py_Initialize()).
255 """
256 env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path))
Victor Stinner5edcf262019-05-23 00:57:57 +0200257 out, err = self.run_embedded_interpreter("test_pre_initialization_api", env=env)
Victor Stinner01de89c2018-11-14 17:39:45 +0100258 if MS_WINDOWS:
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000259 expected_path = self.test_exe
260 else:
261 expected_path = os.path.join(os.getcwd(), "spam")
262 expected_output = f"sys.executable: {expected_path}\n"
263 self.assertIn(expected_output, out)
264 self.assertEqual(err, '')
265
266 def test_pre_initialization_sys_options(self):
267 """
268 Checks that sys.warnoptions and sys._xoptions can be set before the
269 runtime is initialized (otherwise they won't be effective).
270 """
Victor Stinnerdbdc9912019-06-18 00:11:00 +0200271 env = remove_python_envvars()
272 env['PYTHONPATH'] = os.pathsep.join(sys.path)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000273 out, err = self.run_embedded_interpreter(
Victor Stinner5edcf262019-05-23 00:57:57 +0200274 "test_pre_initialization_sys_options", env=env)
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000275 expected_output = (
276 "sys.warnoptions: ['once', 'module', 'default']\n"
277 "sys._xoptions: {'not_an_option': '1', 'also_not_an_option': '2'}\n"
278 "warnings.filters[:3]: ['default', 'module', 'once']\n"
279 )
280 self.assertIn(expected_output, out)
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000281 self.assertEqual(err, '')
282
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100283 def test_bpo20891(self):
284 """
Victor Stinner3225b9f2020-03-09 20:56:57 +0100285 bpo-20891: Calling PyGILState_Ensure in a non-Python thread must not
286 crash.
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100287 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200288 out, err = self.run_embedded_interpreter("test_bpo20891")
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100289 self.assertEqual(out, '')
290 self.assertEqual(err, '')
291
Victor Stinner209abf72018-06-22 19:14:51 +0200292 def test_initialize_twice(self):
293 """
294 bpo-33932: Calling Py_Initialize() twice should do nothing (and not
295 crash!).
296 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200297 out, err = self.run_embedded_interpreter("test_initialize_twice")
Victor Stinner209abf72018-06-22 19:14:51 +0200298 self.assertEqual(out, '')
299 self.assertEqual(err, '')
300
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200301 def test_initialize_pymain(self):
302 """
303 bpo-34008: Calling Py_Main() after Py_Initialize() must not fail.
304 """
Victor Stinner5edcf262019-05-23 00:57:57 +0200305 out, err = self.run_embedded_interpreter("test_initialize_pymain")
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200306 self.assertEqual(out.rstrip(), "Py_Main() after Py_Initialize: sys.argv=['-c', 'arg2']")
307 self.assertEqual(err, '')
308
Victor Stinner2f549082019-03-29 15:13:46 +0100309 def test_run_main(self):
Victor Stinner5edcf262019-05-23 00:57:57 +0200310 out, err = self.run_embedded_interpreter("test_run_main")
Victor Stinner331a6a52019-05-27 16:39:22 +0200311 self.assertEqual(out.rstrip(), "Py_RunMain(): sys.argv=['-c', 'arg2']")
Victor Stinner2f549082019-03-29 15:13:46 +0100312 self.assertEqual(err, '')
313
Miss Islington (bot)3d16fc92021-09-20 01:47:58 -0700314 def test_run_main_loop(self):
315 # bpo-40413: Calling Py_InitializeFromConfig()+Py_RunMain() multiple
316 # times must not crash.
317 nloop = 5
318 out, err = self.run_embedded_interpreter("test_run_main_loop")
319 self.assertEqual(out, "Py_RunMain(): sys.argv=['-c', 'arg2']\n" * nloop)
320 self.assertEqual(err, '')
321
Nick Coghlan39f0bb52017-11-28 08:11:51 +1000322
Victor Stinner56b29b62018-07-26 18:57:56 +0200323class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
324 maxDiff = 4096
Victor Stinner01de89c2018-11-14 17:39:45 +0100325 UTF8_MODE_ERRORS = ('surrogatepass' if MS_WINDOWS else 'surrogateescape')
326
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200327 # Marker to read the default configuration: get_default_config()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100328 GET_DEFAULT_CONFIG = object()
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200329
330 # Marker to ignore a configuration parameter
331 IGNORE_CONFIG = object()
332
Victor Stinner022be022019-05-22 23:58:50 +0200333 PRE_CONFIG_COMPAT = {
Victor Stinner20e1e252019-05-23 04:12:27 +0200334 '_config_init': API_COMPAT,
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200335 'allocator': PYMEM_ALLOCATOR_NOT_SET,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200336 'parse_argv': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200337 'configure_locale': 1,
Victor Stinner1075d162019-03-25 23:19:57 +0100338 'coerce_c_locale': 0,
339 'coerce_c_locale_warn': 0,
Victor Stinner1075d162019-03-25 23:19:57 +0100340 'utf8_mode': 0,
341 }
Victor Stinner6d1c4672019-05-20 11:02:00 +0200342 if MS_WINDOWS:
Victor Stinner022be022019-05-22 23:58:50 +0200343 PRE_CONFIG_COMPAT.update({
Victor Stinner6d1c4672019-05-20 11:02:00 +0200344 'legacy_windows_fs_encoding': 0,
345 })
Victor Stinner022be022019-05-22 23:58:50 +0200346 PRE_CONFIG_PYTHON = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200347 _config_init=API_PYTHON,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200348 parse_argv=1,
Victor Stinner425717f2019-05-20 16:38:48 +0200349 coerce_c_locale=GET_DEFAULT_CONFIG,
350 utf8_mode=GET_DEFAULT_CONFIG,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200351 )
Victor Stinner022be022019-05-22 23:58:50 +0200352 PRE_CONFIG_ISOLATED = dict(PRE_CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200353 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200354 configure_locale=0,
355 isolated=1,
356 use_environment=0,
357 utf8_mode=0,
358 dev_mode=0,
Victor Stinner425717f2019-05-20 16:38:48 +0200359 coerce_c_locale=0,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200360 )
Victor Stinnerbab0db62019-05-18 03:21:27 +0200361
Victor Stinner20004952019-03-26 02:31:11 +0100362 COPY_PRE_CONFIG = [
363 'dev_mode',
364 'isolated',
365 'use_environment',
366 ]
367
Victor Stinner331a6a52019-05-27 16:39:22 +0200368 CONFIG_COMPAT = {
Victor Stinner022be022019-05-22 23:58:50 +0200369 '_config_init': API_COMPAT,
Victor Stinner20004952019-03-26 02:31:11 +0100370 'isolated': 0,
371 'use_environment': 1,
372 'dev_mode': 0,
373
Victor Stinner56b29b62018-07-26 18:57:56 +0200374 'install_signal_handlers': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200375 'use_hash_seed': 0,
376 'hash_seed': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200377 'faulthandler': 0,
378 'tracemalloc': 0,
379 'import_time': 0,
380 'show_ref_count': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200381 'dump_refs': 0,
382 'malloc_stats': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200383
Victor Stinnera6537fb2018-11-26 11:54:12 +0100384 'filesystem_encoding': GET_DEFAULT_CONFIG,
385 'filesystem_errors': GET_DEFAULT_CONFIG,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200386
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100387 'pycache_prefix': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200388 'program_name': GET_DEFAULT_CONFIG,
Victor Stinnercab5d072019-05-17 19:01:14 +0200389 'parse_argv': 0,
Victor Stinner62599762019-03-15 16:03:23 +0100390 'argv': [""],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200391 'orig_argv': [],
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100392
393 'xoptions': [],
394 'warnoptions': [],
Victor Stinner56b29b62018-07-26 18:57:56 +0200395
Victor Stinner331a6a52019-05-27 16:39:22 +0200396 'pythonpath_env': None,
Victor Stinner01de89c2018-11-14 17:39:45 +0100397 'home': None,
Victor Stinner91c99872019-05-14 22:01:51 +0200398 'executable': GET_DEFAULT_CONFIG,
Steve Dower9048c492019-06-29 10:34:11 -0700399 'base_executable': GET_DEFAULT_CONFIG,
Victor Stinnera6537fb2018-11-26 11:54:12 +0100400
401 'prefix': GET_DEFAULT_CONFIG,
402 'base_prefix': GET_DEFAULT_CONFIG,
403 'exec_prefix': GET_DEFAULT_CONFIG,
404 'base_exec_prefix': GET_DEFAULT_CONFIG,
Victor Stinner5eb8b072019-05-15 02:12:48 +0200405 'module_search_paths': GET_DEFAULT_CONFIG,
Victor Stinnerf3cb8142020-11-05 18:12:33 +0100406 'module_search_paths_set': 1,
Sandro Mani8f023a22020-06-08 17:28:11 +0200407 'platlibdir': sys.platlibdir,
Victor Stinner01de89c2018-11-14 17:39:45 +0100408
Victor Stinner56b29b62018-07-26 18:57:56 +0200409 'site_import': 1,
410 'bytes_warning': 0,
Inada Naoki48274832021-03-29 12:28:14 +0900411 'warn_default_encoding': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200412 'inspect': 0,
413 'interactive': 0,
414 'optimization_level': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200415 'parser_debug': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200416 'write_bytecode': 1,
417 'verbose': 0,
418 'quiet': 0,
419 'user_site_directory': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200420 'configure_c_stdio': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200421 'buffered_stdio': 1,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200422
Victor Stinnera6537fb2018-11-26 11:54:12 +0100423 'stdio_encoding': GET_DEFAULT_CONFIG,
424 'stdio_errors': GET_DEFAULT_CONFIG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200425
Victor Stinner62be7632019-03-01 13:10:14 +0100426 'skip_source_first_line': 0,
427 'run_command': None,
428 'run_module': None,
429 'run_filename': None,
430
Victor Stinner56b29b62018-07-26 18:57:56 +0200431 '_install_importlib': 1,
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400432 'check_hash_pycs_mode': 'default',
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200433 'pathconfig_warnings': 1,
434 '_init_main': 1,
Victor Stinner252346a2020-05-01 11:33:44 +0200435 '_isolated_interpreter': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200436 }
Victor Stinner01de89c2018-11-14 17:39:45 +0100437 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200438 CONFIG_COMPAT.update({
Victor Stinner01de89c2018-11-14 17:39:45 +0100439 'legacy_windows_stdio': 0,
440 })
441
Victor Stinner331a6a52019-05-27 16:39:22 +0200442 CONFIG_PYTHON = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200443 _config_init=API_PYTHON,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200444 configure_c_stdio=1,
Victor Stinnerdc42af82020-11-05 18:58:07 +0100445 parse_argv=2,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200446 )
Victor Stinner331a6a52019-05-27 16:39:22 +0200447 CONFIG_ISOLATED = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200448 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200449 isolated=1,
450 use_environment=0,
451 user_site_directory=0,
452 dev_mode=0,
453 install_signal_handlers=0,
454 use_hash_seed=0,
455 faulthandler=0,
456 tracemalloc=0,
457 pathconfig_warnings=0,
458 )
459 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200460 CONFIG_ISOLATED['legacy_windows_stdio'] = 0
Victor Stinnerbab0db62019-05-18 03:21:27 +0200461
Victor Stinner01de89c2018-11-14 17:39:45 +0100462 # global config
463 DEFAULT_GLOBAL_CONFIG = {
464 'Py_HasFileSystemDefaultEncoding': 0,
465 'Py_HashRandomizationFlag': 1,
466 '_Py_HasFileSystemDefaultEncodeErrors': 0,
467 }
Victor Stinner1075d162019-03-25 23:19:57 +0100468 COPY_GLOBAL_PRE_CONFIG = [
Victor Stinner1075d162019-03-25 23:19:57 +0100469 ('Py_UTF8Mode', 'utf8_mode'),
470 ]
Victor Stinner01de89c2018-11-14 17:39:45 +0100471 COPY_GLOBAL_CONFIG = [
472 # Copy core config to global config for expected values
473 # True means that the core config value is inverted (0 => 1 and 1 => 0)
474 ('Py_BytesWarningFlag', 'bytes_warning'),
475 ('Py_DebugFlag', 'parser_debug'),
476 ('Py_DontWriteBytecodeFlag', 'write_bytecode', True),
477 ('Py_FileSystemDefaultEncodeErrors', 'filesystem_errors'),
478 ('Py_FileSystemDefaultEncoding', 'filesystem_encoding'),
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200479 ('Py_FrozenFlag', 'pathconfig_warnings', True),
Victor Stinner20004952019-03-26 02:31:11 +0100480 ('Py_IgnoreEnvironmentFlag', 'use_environment', True),
Victor Stinner01de89c2018-11-14 17:39:45 +0100481 ('Py_InspectFlag', 'inspect'),
482 ('Py_InteractiveFlag', 'interactive'),
Victor Stinner20004952019-03-26 02:31:11 +0100483 ('Py_IsolatedFlag', 'isolated'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100484 ('Py_NoSiteFlag', 'site_import', True),
485 ('Py_NoUserSiteDirectory', 'user_site_directory', True),
486 ('Py_OptimizeFlag', 'optimization_level'),
487 ('Py_QuietFlag', 'quiet'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100488 ('Py_UnbufferedStdioFlag', 'buffered_stdio', True),
489 ('Py_VerboseFlag', 'verbose'),
490 ]
491 if MS_WINDOWS:
Victor Stinner1075d162019-03-25 23:19:57 +0100492 COPY_GLOBAL_PRE_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100493 ('Py_LegacyWindowsFSEncodingFlag', 'legacy_windows_fs_encoding'),
Victor Stinner1075d162019-03-25 23:19:57 +0100494 ))
495 COPY_GLOBAL_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100496 ('Py_LegacyWindowsStdioFlag', 'legacy_windows_stdio'),
497 ))
Victor Stinner56b29b62018-07-26 18:57:56 +0200498
Victor Stinner8f427482020-07-08 00:20:37 +0200499 # path config
500 if MS_WINDOWS:
501 PATH_CONFIG = {
502 'isolated': -1,
503 'site_import': -1,
504 'python3_dll': GET_DEFAULT_CONFIG,
505 }
506 else:
507 PATH_CONFIG = {}
508 # other keys are copied by COPY_PATH_CONFIG
509
510 COPY_PATH_CONFIG = [
511 # Copy core config to global config for expected values
512 'prefix',
513 'exec_prefix',
514 'program_name',
515 'home',
516 # program_full_path and module_search_path are copied indirectly from
517 # the core configuration in check_path_config().
518 ]
519 if MS_WINDOWS:
520 COPY_PATH_CONFIG.extend((
521 'base_executable',
522 ))
523
Victor Stinner425717f2019-05-20 16:38:48 +0200524 EXPECTED_CONFIG = None
525
Victor Stinner52ad33a2019-09-25 02:10:35 +0200526 @classmethod
527 def tearDownClass(cls):
528 # clear cache
529 cls.EXPECTED_CONFIG = None
530
Victor Stinner01de89c2018-11-14 17:39:45 +0100531 def main_xoptions(self, xoptions_list):
532 xoptions = {}
533 for opt in xoptions_list:
534 if '=' in opt:
535 key, value = opt.split('=', 1)
536 xoptions[key] = value
537 else:
538 xoptions[opt] = True
539 return xoptions
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200540
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200541 def _get_expected_config_impl(self):
542 env = remove_python_envvars()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100543 code = textwrap.dedent('''
544 import json
Victor Stinnera6537fb2018-11-26 11:54:12 +0100545 import sys
Victor Stinner5eb8b072019-05-15 02:12:48 +0200546 import _testinternalcapi
Victor Stinnera6537fb2018-11-26 11:54:12 +0100547
Victor Stinner5eb8b072019-05-15 02:12:48 +0200548 configs = _testinternalcapi.get_configs()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100549
Victor Stinner425717f2019-05-20 16:38:48 +0200550 data = json.dumps(configs)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100551 data = data.encode('utf-8')
552 sys.stdout.buffer.write(data)
553 sys.stdout.buffer.flush()
554 ''')
555
556 # Use -S to not import the site module: get the proper configuration
557 # when test_embed is run from a venv (bpo-35313)
Victor Stinner5eb8b072019-05-15 02:12:48 +0200558 args = [sys.executable, '-S', '-c', code]
Victor Stinnera6537fb2018-11-26 11:54:12 +0100559 proc = subprocess.run(args, env=env,
560 stdout=subprocess.PIPE,
Victor Stinner52ad33a2019-09-25 02:10:35 +0200561 stderr=subprocess.PIPE)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100562 if proc.returncode:
563 raise Exception(f"failed to get the default config: "
564 f"stdout={proc.stdout!r} stderr={proc.stderr!r}")
565 stdout = proc.stdout.decode('utf-8')
Victor Stinner52ad33a2019-09-25 02:10:35 +0200566 # ignore stderr
Victor Stinner4631da12019-05-02 15:30:21 -0400567 try:
Victor Stinner425717f2019-05-20 16:38:48 +0200568 return json.loads(stdout)
Victor Stinner4631da12019-05-02 15:30:21 -0400569 except json.JSONDecodeError:
570 self.fail(f"fail to decode stdout: {stdout!r}")
Victor Stinnera6537fb2018-11-26 11:54:12 +0100571
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200572 def _get_expected_config(self):
573 cls = InitConfigTests
574 if cls.EXPECTED_CONFIG is None:
575 cls.EXPECTED_CONFIG = self._get_expected_config_impl()
576
577 # get a copy
Victor Stinner52ad33a2019-09-25 02:10:35 +0200578 configs = {}
579 for config_key, config_value in cls.EXPECTED_CONFIG.items():
580 config = {}
581 for key, value in config_value.items():
582 if isinstance(value, list):
583 value = value.copy()
584 config[key] = value
585 configs[config_key] = config
586 return configs
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200587
Victor Stinner8f427482020-07-08 00:20:37 +0200588 def get_expected_config(self, expected_preconfig, expected,
589 expected_pathconfig, env, api,
Victor Stinner3842f292019-08-23 16:57:54 +0100590 modify_path_cb=None):
Victor Stinner425717f2019-05-20 16:38:48 +0200591 cls = self.__class__
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200592 configs = self._get_expected_config()
Victor Stinner425717f2019-05-20 16:38:48 +0200593
594 pre_config = configs['pre_config']
595 for key, value in expected_preconfig.items():
596 if value is self.GET_DEFAULT_CONFIG:
597 expected_preconfig[key] = pre_config[key]
598
Victor Stinner8f427482020-07-08 00:20:37 +0200599 path_config = configs['path_config']
600 for key, value in expected_pathconfig.items():
601 if value is self.GET_DEFAULT_CONFIG:
602 expected_pathconfig[key] = path_config[key]
603
Victor Stinner022be022019-05-22 23:58:50 +0200604 if not expected_preconfig['configure_locale'] or api == API_COMPAT:
Victor Stinner425717f2019-05-20 16:38:48 +0200605 # there is no easy way to get the locale encoding before
606 # setlocale(LC_CTYPE, "") is called: don't test encodings
607 for key in ('filesystem_encoding', 'filesystem_errors',
608 'stdio_encoding', 'stdio_errors'):
609 expected[key] = self.IGNORE_CONFIG
610
611 if not expected_preconfig['configure_locale']:
612 # UTF-8 Mode depends on the locale. There is no easy way
613 # to guess if UTF-8 Mode will be enabled or not if the locale
614 # is not configured.
615 expected_preconfig['utf8_mode'] = self.IGNORE_CONFIG
616
617 if expected_preconfig['utf8_mode'] == 1:
618 if expected['filesystem_encoding'] is self.GET_DEFAULT_CONFIG:
619 expected['filesystem_encoding'] = 'utf-8'
620 if expected['filesystem_errors'] is self.GET_DEFAULT_CONFIG:
621 expected['filesystem_errors'] = self.UTF8_MODE_ERRORS
622 if expected['stdio_encoding'] is self.GET_DEFAULT_CONFIG:
623 expected['stdio_encoding'] = 'utf-8'
624 if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG:
625 expected['stdio_errors'] = 'surrogateescape'
626
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100627 if MS_WINDOWS:
Steve Dower9048c492019-06-29 10:34:11 -0700628 default_executable = self.test_exe
629 elif expected['program_name'] is not self.GET_DEFAULT_CONFIG:
630 default_executable = os.path.abspath(expected['program_name'])
631 else:
632 default_executable = os.path.join(os.getcwd(), '_testembed')
Victor Stinner91c99872019-05-14 22:01:51 +0200633 if expected['executable'] is self.GET_DEFAULT_CONFIG:
Steve Dower9048c492019-06-29 10:34:11 -0700634 expected['executable'] = default_executable
635 if expected['base_executable'] is self.GET_DEFAULT_CONFIG:
636 expected['base_executable'] = default_executable
Victor Stinner91c99872019-05-14 22:01:51 +0200637 if expected['program_name'] is self.GET_DEFAULT_CONFIG:
638 expected['program_name'] = './_testembed'
639
Victor Stinner331a6a52019-05-27 16:39:22 +0200640 config = configs['config']
Victor Stinnera6537fb2018-11-26 11:54:12 +0100641 for key, value in expected.items():
642 if value is self.GET_DEFAULT_CONFIG:
Victor Stinner331a6a52019-05-27 16:39:22 +0200643 expected[key] = config[key]
Victor Stinner5eb8b072019-05-15 02:12:48 +0200644
Sandro Mani8f023a22020-06-08 17:28:11 +0200645 if expected['module_search_paths'] is not self.IGNORE_CONFIG:
646 pythonpath_env = expected['pythonpath_env']
647 if pythonpath_env is not None:
648 paths = pythonpath_env.split(os.path.pathsep)
649 expected['module_search_paths'] = [*paths, *expected['module_search_paths']]
650 if modify_path_cb is not None:
651 expected['module_search_paths'] = expected['module_search_paths'].copy()
652 modify_path_cb(expected['module_search_paths'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200653
Victor Stinner425717f2019-05-20 16:38:48 +0200654 for key in self.COPY_PRE_CONFIG:
655 if key not in expected_preconfig:
656 expected_preconfig[key] = expected[key]
Victor Stinner01de89c2018-11-14 17:39:45 +0100657
Victor Stinner331a6a52019-05-27 16:39:22 +0200658 def check_pre_config(self, configs, expected):
659 pre_config = dict(configs['pre_config'])
Victor Stinner425717f2019-05-20 16:38:48 +0200660 for key, value in list(expected.items()):
661 if value is self.IGNORE_CONFIG:
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100662 pre_config.pop(key, None)
Victor Stinner425717f2019-05-20 16:38:48 +0200663 del expected[key]
664 self.assertEqual(pre_config, expected)
Victor Stinner1075d162019-03-25 23:19:57 +0100665
Victor Stinner331a6a52019-05-27 16:39:22 +0200666 def check_config(self, configs, expected):
667 config = dict(configs['config'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200668 for key, value in list(expected.items()):
669 if value is self.IGNORE_CONFIG:
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100670 config.pop(key, None)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200671 del expected[key]
Victor Stinner331a6a52019-05-27 16:39:22 +0200672 self.assertEqual(config, expected)
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200673
Victor Stinner331a6a52019-05-27 16:39:22 +0200674 def check_global_config(self, configs):
675 pre_config = configs['pre_config']
676 config = configs['config']
Victor Stinner00b137c2018-11-13 19:59:26 +0100677
Victor Stinnera6537fb2018-11-26 11:54:12 +0100678 expected = dict(self.DEFAULT_GLOBAL_CONFIG)
Victor Stinner01de89c2018-11-14 17:39:45 +0100679 for item in self.COPY_GLOBAL_CONFIG:
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100680 if len(item) == 3:
681 global_key, core_key, opposite = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200682 expected[global_key] = 0 if config[core_key] else 1
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100683 else:
684 global_key, core_key = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200685 expected[global_key] = config[core_key]
Victor Stinner1075d162019-03-25 23:19:57 +0100686 for item in self.COPY_GLOBAL_PRE_CONFIG:
687 if len(item) == 3:
688 global_key, core_key, opposite = item
689 expected[global_key] = 0 if pre_config[core_key] else 1
690 else:
691 global_key, core_key = item
692 expected[global_key] = pre_config[core_key]
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100693
Victor Stinner331a6a52019-05-27 16:39:22 +0200694 self.assertEqual(configs['global_config'], expected)
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100695
Victor Stinner8f427482020-07-08 00:20:37 +0200696 def check_path_config(self, configs, expected):
697 config = configs['config']
698
699 for key in self.COPY_PATH_CONFIG:
700 expected[key] = config[key]
701 expected['module_search_path'] = os.path.pathsep.join(config['module_search_paths'])
702 expected['program_full_path'] = config['executable']
703
704 self.assertEqual(configs['path_config'], expected)
705
Victor Stinner331a6a52019-05-27 16:39:22 +0200706 def check_all_configs(self, testname, expected_config=None,
Victor Stinner8f427482020-07-08 00:20:37 +0200707 expected_preconfig=None, expected_pathconfig=None,
708 modify_path_cb=None,
Victor Stinner8bf39b62019-09-26 02:22:35 +0200709 stderr=None, *, api, preconfig_api=None,
710 env=None, ignore_stderr=False, cwd=None):
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200711 new_env = remove_python_envvars()
712 if env is not None:
713 new_env.update(env)
714 env = new_env
Victor Stinner01de89c2018-11-14 17:39:45 +0100715
Victor Stinner8bf39b62019-09-26 02:22:35 +0200716 if preconfig_api is None:
717 preconfig_api = api
718 if preconfig_api == API_ISOLATED:
Victor Stinner022be022019-05-22 23:58:50 +0200719 default_preconfig = self.PRE_CONFIG_ISOLATED
Victor Stinner8bf39b62019-09-26 02:22:35 +0200720 elif preconfig_api == API_PYTHON:
Victor Stinner022be022019-05-22 23:58:50 +0200721 default_preconfig = self.PRE_CONFIG_PYTHON
Victor Stinnerbab0db62019-05-18 03:21:27 +0200722 else:
Victor Stinner022be022019-05-22 23:58:50 +0200723 default_preconfig = self.PRE_CONFIG_COMPAT
Victor Stinnerbab0db62019-05-18 03:21:27 +0200724 if expected_preconfig is None:
725 expected_preconfig = {}
726 expected_preconfig = dict(default_preconfig, **expected_preconfig)
Victor Stinner8f427482020-07-08 00:20:37 +0200727
Victor Stinnerbab0db62019-05-18 03:21:27 +0200728 if expected_config is None:
729 expected_config = {}
Victor Stinner425717f2019-05-20 16:38:48 +0200730
Victor Stinner8f427482020-07-08 00:20:37 +0200731 if expected_pathconfig is None:
732 expected_pathconfig = {}
733 expected_pathconfig = dict(self.PATH_CONFIG, **expected_pathconfig)
734
Victor Stinner022be022019-05-22 23:58:50 +0200735 if api == API_PYTHON:
Victor Stinner331a6a52019-05-27 16:39:22 +0200736 default_config = self.CONFIG_PYTHON
Victor Stinner022be022019-05-22 23:58:50 +0200737 elif api == API_ISOLATED:
Victor Stinner331a6a52019-05-27 16:39:22 +0200738 default_config = self.CONFIG_ISOLATED
Victor Stinner425717f2019-05-20 16:38:48 +0200739 else:
Victor Stinner331a6a52019-05-27 16:39:22 +0200740 default_config = self.CONFIG_COMPAT
Victor Stinner425717f2019-05-20 16:38:48 +0200741 expected_config = dict(default_config, **expected_config)
Victor Stinner425717f2019-05-20 16:38:48 +0200742
743 self.get_expected_config(expected_preconfig,
Victor Stinner8f427482020-07-08 00:20:37 +0200744 expected_config,
745 expected_pathconfig,
746 env,
Victor Stinner3842f292019-08-23 16:57:54 +0100747 api, modify_path_cb)
Victor Stinner1075d162019-03-25 23:19:57 +0100748
Victor Stinner52ad33a2019-09-25 02:10:35 +0200749 out, err = self.run_embedded_interpreter(testname,
750 env=env, cwd=cwd)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200751 if stderr is None and not expected_config['verbose']:
752 stderr = ""
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200753 if stderr is not None and not ignore_stderr:
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200754 self.assertEqual(err.rstrip(), stderr)
755 try:
Victor Stinner331a6a52019-05-27 16:39:22 +0200756 configs = json.loads(out)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200757 except json.JSONDecodeError:
758 self.fail(f"fail to decode stdout: {out!r}")
759
Victor Stinner331a6a52019-05-27 16:39:22 +0200760 self.check_pre_config(configs, expected_preconfig)
761 self.check_config(configs, expected_config)
762 self.check_global_config(configs)
Victor Stinner8f427482020-07-08 00:20:37 +0200763 self.check_path_config(configs, expected_pathconfig)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100764 return configs
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100765
Victor Stinner56b29b62018-07-26 18:57:56 +0200766 def test_init_default_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200767 self.check_all_configs("test_init_initialize_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200768
769 def test_preinit_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200770 self.check_all_configs("test_preinit_compat_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200771
772 def test_init_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200773 self.check_all_configs("test_init_compat_config", api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200774
775 def test_init_global_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100776 preconfig = {
777 'utf8_mode': 1,
778 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200779 config = {
780 'program_name': './globalvar',
781 'site_import': 0,
782 'bytes_warning': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100783 'warnoptions': ['default::BytesWarning'],
Victor Stinner56b29b62018-07-26 18:57:56 +0200784 'inspect': 1,
785 'interactive': 1,
786 'optimization_level': 2,
787 'write_bytecode': 0,
788 'verbose': 1,
789 'quiet': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200790 'buffered_stdio': 0,
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200791
Victor Stinner56b29b62018-07-26 18:57:56 +0200792 'user_site_directory': 0,
Victor Stinner54b43bb2019-05-16 18:30:15 +0200793 'pathconfig_warnings': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200794 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200795 self.check_all_configs("test_init_global_config", config, preconfig,
796 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200797
798 def test_init_from_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100799 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200800 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner1075d162019-03-25 23:19:57 +0100801 'utf8_mode': 1,
802 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200803 config = {
804 'install_signal_handlers': 0,
805 'use_hash_seed': 1,
806 'hash_seed': 123,
Victor Stinner56b29b62018-07-26 18:57:56 +0200807 'tracemalloc': 2,
808 'import_time': 1,
809 'show_ref_count': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200810 'malloc_stats': 1,
811
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200812 'stdio_encoding': 'iso8859-1',
813 'stdio_errors': 'replace',
Victor Stinner56b29b62018-07-26 18:57:56 +0200814
815 'pycache_prefix': 'conf_pycache_prefix',
816 'program_name': './conf_program_name',
Victor Stinnere81f6e62020-06-08 18:12:59 +0200817 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200818 'orig_argv': ['python3',
819 '-W', 'cmdline_warnoption',
820 '-X', 'cmdline_xoption',
821 '-c', 'pass',
822 'arg2'],
Victor Stinnerdc42af82020-11-05 18:58:07 +0100823 'parse_argv': 2,
Victor Stinner67310022019-07-01 19:52:45 +0200824 'xoptions': [
825 'config_xoption1=3',
826 'config_xoption2=',
827 'config_xoption3',
828 'cmdline_xoption',
829 ],
830 'warnoptions': [
Victor Stinner67310022019-07-01 19:52:45 +0200831 'cmdline_warnoption',
832 'default::BytesWarning',
Victor Stinnerfb4ae152019-09-30 01:40:17 +0200833 'config_warnoption',
Victor Stinner67310022019-07-01 19:52:45 +0200834 ],
Victor Stinner2f549082019-03-29 15:13:46 +0100835 'run_command': 'pass\n',
Victor Stinner56b29b62018-07-26 18:57:56 +0200836
837 'site_import': 0,
838 'bytes_warning': 1,
839 'inspect': 1,
840 'interactive': 1,
841 'optimization_level': 2,
842 'write_bytecode': 0,
843 'verbose': 1,
844 'quiet': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200845 'configure_c_stdio': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200846 'buffered_stdio': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200847 'user_site_directory': 0,
848 'faulthandler': 1,
Sandro Mani8f023a22020-06-08 17:28:11 +0200849 'platlibdir': 'my_platlibdir',
850 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinnerb75d7e22018-08-01 02:13:04 +0200851
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400852 'check_hash_pycs_mode': 'always',
Victor Stinner54b43bb2019-05-16 18:30:15 +0200853 'pathconfig_warnings': 0,
Victor Stinner252346a2020-05-01 11:33:44 +0200854
855 '_isolated_interpreter': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200856 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200857 self.check_all_configs("test_init_from_config", config, preconfig,
858 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200859
Victor Stinner20e1e252019-05-23 04:12:27 +0200860 def test_init_compat_env(self):
861 preconfig = {
862 'allocator': PYMEM_ALLOCATOR_MALLOC,
863 }
864 config = {
865 'use_hash_seed': 1,
866 'hash_seed': 42,
867 'tracemalloc': 2,
868 'import_time': 1,
869 'malloc_stats': 1,
870 'inspect': 1,
871 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200872 'pythonpath_env': '/my/path',
Victor Stinner20e1e252019-05-23 04:12:27 +0200873 'pycache_prefix': 'env_pycache_prefix',
874 'write_bytecode': 0,
875 'verbose': 1,
876 'buffered_stdio': 0,
877 'stdio_encoding': 'iso8859-1',
878 'stdio_errors': 'replace',
879 'user_site_directory': 0,
880 'faulthandler': 1,
881 'warnoptions': ['EnvVar'],
Sandro Mani8f023a22020-06-08 17:28:11 +0200882 'platlibdir': 'env_platlibdir',
883 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinner20e1e252019-05-23 04:12:27 +0200884 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200885 self.check_all_configs("test_init_compat_env", config, preconfig,
886 api=API_COMPAT)
Victor Stinner20e1e252019-05-23 04:12:27 +0200887
888 def test_init_python_env(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200889 preconfig = {
890 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner022be022019-05-22 23:58:50 +0200891 'utf8_mode': 1,
Victor Stinner425717f2019-05-20 16:38:48 +0200892 }
893 config = {
894 'use_hash_seed': 1,
895 'hash_seed': 42,
896 'tracemalloc': 2,
897 'import_time': 1,
898 'malloc_stats': 1,
899 'inspect': 1,
900 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200901 'pythonpath_env': '/my/path',
Victor Stinner425717f2019-05-20 16:38:48 +0200902 'pycache_prefix': 'env_pycache_prefix',
903 'write_bytecode': 0,
904 'verbose': 1,
905 'buffered_stdio': 0,
906 'stdio_encoding': 'iso8859-1',
907 'stdio_errors': 'replace',
908 'user_site_directory': 0,
909 'faulthandler': 1,
910 'warnoptions': ['EnvVar'],
Sandro Mani8f023a22020-06-08 17:28:11 +0200911 'platlibdir': 'env_platlibdir',
912 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinner425717f2019-05-20 16:38:48 +0200913 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200914 self.check_all_configs("test_init_python_env", config, preconfig,
915 api=API_PYTHON)
Victor Stinnerb35be4b2019-03-05 17:37:44 +0100916
917 def test_init_env_dev_mode(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200918 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
919 config = dict(dev_mode=1,
920 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100921 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200922 self.check_all_configs("test_init_env_dev_mode", config, preconfig,
923 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200924
Victor Stinner20004952019-03-26 02:31:11 +0100925 def test_init_env_dev_mode_alloc(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200926 preconfig = dict(allocator=PYMEM_ALLOCATOR_MALLOC)
927 config = dict(dev_mode=1,
928 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100929 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200930 self.check_all_configs("test_init_env_dev_mode_alloc", config, preconfig,
931 api=API_COMPAT)
Victor Stinner25d13f32019-03-06 12:51:53 +0100932
Victor Stinner56b29b62018-07-26 18:57:56 +0200933 def test_init_dev_mode(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100934 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200935 'allocator': PYMEM_ALLOCATOR_DEBUG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200936 }
Victor Stinner1075d162019-03-25 23:19:57 +0100937 config = {
938 'faulthandler': 1,
Victor Stinner20004952019-03-26 02:31:11 +0100939 'dev_mode': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100940 'warnoptions': ['default'],
Victor Stinner1075d162019-03-25 23:19:57 +0100941 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200942 self.check_all_configs("test_init_dev_mode", config, preconfig,
943 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200944
945 def test_preinit_parse_argv(self):
946 # Pre-initialize implicitly using argv: make sure that -X dev
947 # is used to configure the allocation in preinitialization
948 preconfig = {
949 'allocator': PYMEM_ALLOCATOR_DEBUG,
950 }
951 config = {
Victor Stinnera1a99b42019-12-09 17:34:02 +0100952 'argv': ['script.py'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200953 'orig_argv': ['python3', '-X', 'dev', 'script.py'],
Victor Stinnera1a99b42019-12-09 17:34:02 +0100954 'run_filename': os.path.abspath('script.py'),
Victor Stinner6d1c4672019-05-20 11:02:00 +0200955 'dev_mode': 1,
956 'faulthandler': 1,
957 'warnoptions': ['default'],
958 'xoptions': ['dev'],
959 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200960 self.check_all_configs("test_preinit_parse_argv", config, preconfig,
961 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200962
963 def test_preinit_dont_parse_argv(self):
964 # -X dev must be ignored by isolated preconfiguration
965 preconfig = {
966 'isolated': 0,
967 }
Victor Stinnere81f6e62020-06-08 18:12:59 +0200968 argv = ["python3",
969 "-E", "-I",
970 "-X", "dev",
971 "-X", "utf8",
972 "script.py"]
Victor Stinner6d1c4672019-05-20 11:02:00 +0200973 config = {
Victor Stinnere81f6e62020-06-08 18:12:59 +0200974 'argv': argv,
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200975 'orig_argv': argv,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200976 'isolated': 0,
977 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200978 self.check_all_configs("test_preinit_dont_parse_argv", config, preconfig,
979 api=API_ISOLATED)
Victor Stinner56b29b62018-07-26 18:57:56 +0200980
Victor Stinnercab5d072019-05-17 19:01:14 +0200981 def test_init_isolated_flag(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100982 config = {
Victor Stinner20004952019-03-26 02:31:11 +0100983 'isolated': 1,
984 'use_environment': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200985 'user_site_directory': 0,
986 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200987 self.check_all_configs("test_init_isolated_flag", config, api=API_PYTHON)
Victor Stinner56b29b62018-07-26 18:57:56 +0200988
Victor Stinner6da20a42019-03-27 00:26:18 +0100989 def test_preinit_isolated1(self):
990 # _PyPreConfig.isolated=1, _PyCoreConfig.isolated not set
Victor Stinner6da20a42019-03-27 00:26:18 +0100991 config = {
992 'isolated': 1,
993 'use_environment': 0,
994 'user_site_directory': 0,
995 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200996 self.check_all_configs("test_preinit_isolated1", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100997
998 def test_preinit_isolated2(self):
999 # _PyPreConfig.isolated=0, _PyCoreConfig.isolated=1
Victor Stinner6da20a42019-03-27 00:26:18 +01001000 config = {
1001 'isolated': 1,
1002 'use_environment': 0,
1003 'user_site_directory': 0,
1004 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001005 self.check_all_configs("test_preinit_isolated2", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +01001006
Victor Stinner6d1c4672019-05-20 11:02:00 +02001007 def test_preinit_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001008 self.check_all_configs("test_preinit_isolated_config", api=API_ISOLATED)
Victor Stinner6d1c4672019-05-20 11:02:00 +02001009
Victor Stinnercab5d072019-05-17 19:01:14 +02001010 def test_init_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001011 self.check_all_configs("test_init_isolated_config", api=API_ISOLATED)
Victor Stinner5edcf262019-05-23 00:57:57 +02001012
1013 def test_preinit_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001014 self.check_all_configs("test_preinit_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +02001015
1016 def test_init_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001017 self.check_all_configs("test_init_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +02001018
Victor Stinnerbcfbbd72019-05-17 22:44:16 +02001019 def test_init_dont_configure_locale(self):
1020 # _PyPreConfig.configure_locale=0
1021 preconfig = {
1022 'configure_locale': 0,
Victor Stinner425717f2019-05-20 16:38:48 +02001023 'coerce_c_locale': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +02001024 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001025 self.check_all_configs("test_init_dont_configure_locale", {}, preconfig,
1026 api=API_PYTHON)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +02001027
Victor Stinner91c99872019-05-14 22:01:51 +02001028 def test_init_read_set(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001029 config = {
Victor Stinner91c99872019-05-14 22:01:51 +02001030 'program_name': './init_read_set',
1031 'executable': 'my_executable',
1032 }
Victor Stinner3842f292019-08-23 16:57:54 +01001033 def modify_path(path):
1034 path.insert(1, "test_path_insert1")
1035 path.append("test_path_append")
Victor Stinner331a6a52019-05-27 16:39:22 +02001036 self.check_all_configs("test_init_read_set", config,
1037 api=API_PYTHON,
Victor Stinner3842f292019-08-23 16:57:54 +01001038 modify_path_cb=modify_path)
Victor Stinner91c99872019-05-14 22:01:51 +02001039
Victor Stinner120b7072019-08-23 18:03:08 +01001040 def test_init_sys_add(self):
1041 config = {
1042 'faulthandler': 1,
1043 'xoptions': [
1044 'config_xoption',
1045 'cmdline_xoption',
1046 'sysadd_xoption',
1047 'faulthandler',
1048 ],
1049 'warnoptions': [
Victor Stinner120b7072019-08-23 18:03:08 +01001050 'ignore:::cmdline_warnoption',
1051 'ignore:::sysadd_warnoption',
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001052 'ignore:::config_warnoption',
Victor Stinner120b7072019-08-23 18:03:08 +01001053 ],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001054 'orig_argv': ['python3',
1055 '-W', 'ignore:::cmdline_warnoption',
1056 '-X', 'cmdline_xoption'],
Victor Stinner120b7072019-08-23 18:03:08 +01001057 }
1058 self.check_all_configs("test_init_sys_add", config, api=API_PYTHON)
1059
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001060 def test_init_run_main(self):
Victor Stinner5eb8b072019-05-15 02:12:48 +02001061 code = ('import _testinternalcapi, json; '
1062 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +02001063 config = {
Victor Stinner5eb8b072019-05-15 02:12:48 +02001064 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001065 'orig_argv': ['python3', '-c', code, 'arg2'],
Victor Stinner5eb8b072019-05-15 02:12:48 +02001066 'program_name': './python3',
1067 'run_command': code + '\n',
Victor Stinnerdc42af82020-11-05 18:58:07 +01001068 'parse_argv': 2,
Victor Stinner5eb8b072019-05-15 02:12:48 +02001069 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001070 self.check_all_configs("test_init_run_main", config, api=API_PYTHON)
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001071
1072 def test_init_main(self):
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001073 code = ('import _testinternalcapi, json; '
1074 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +02001075 config = {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001076 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001077 'orig_argv': ['python3',
1078 '-c', code,
1079 'arg2'],
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001080 'program_name': './python3',
1081 'run_command': code + '\n',
Victor Stinnerdc42af82020-11-05 18:58:07 +01001082 'parse_argv': 2,
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001083 '_init_main': 0,
1084 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001085 self.check_all_configs("test_init_main", config,
1086 api=API_PYTHON,
1087 stderr="Run Python code before _Py_InitializeMain")
Victor Stinner5eb8b072019-05-15 02:12:48 +02001088
Victor Stinnercab5d072019-05-17 19:01:14 +02001089 def test_init_parse_argv(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001090 config = {
Victor Stinnerdc42af82020-11-05 18:58:07 +01001091 'parse_argv': 2,
Victor Stinnercab5d072019-05-17 19:01:14 +02001092 'argv': ['-c', 'arg1', '-v', 'arg3'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001093 'orig_argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnercab5d072019-05-17 19:01:14 +02001094 'program_name': './argv0',
Victor Stinnercab5d072019-05-17 19:01:14 +02001095 'run_command': 'pass\n',
1096 'use_environment': 0,
1097 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001098 self.check_all_configs("test_init_parse_argv", config, api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +02001099
Victor Stinnerae239f62019-05-16 17:02:56 +02001100 def test_init_dont_parse_argv(self):
Victor Stinner6d1c4672019-05-20 11:02:00 +02001101 pre_config = {
1102 'parse_argv': 0,
1103 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001104 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +02001105 'parse_argv': 0,
Victor Stinnercab5d072019-05-17 19:01:14 +02001106 'argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001107 'orig_argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnercab5d072019-05-17 19:01:14 +02001108 'program_name': './argv0',
Victor Stinnerae239f62019-05-16 17:02:56 +02001109 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001110 self.check_all_configs("test_init_dont_parse_argv", config, pre_config,
1111 api=API_PYTHON)
Victor Stinnerae239f62019-05-16 17:02:56 +02001112
Victor Stinner8bf39b62019-09-26 02:22:35 +02001113 def default_program_name(self, config):
1114 if MS_WINDOWS:
1115 program_name = 'python'
1116 executable = self.test_exe
1117 else:
1118 program_name = 'python3'
Victor Stinner49d99f02019-09-26 04:01:49 +02001119 if MACOS:
1120 executable = self.test_exe
1121 else:
1122 executable = shutil.which(program_name) or ''
Victor Stinner8bf39b62019-09-26 02:22:35 +02001123 config.update({
1124 'program_name': program_name,
1125 'base_executable': executable,
1126 'executable': executable,
1127 })
1128
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001129 def test_init_setpath(self):
Victor Stinner8bf39b62019-09-26 02:22:35 +02001130 # Test Py_SetPath()
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001131 config = self._get_expected_config()
1132 paths = config['config']['module_search_paths']
1133
1134 config = {
1135 'module_search_paths': paths,
1136 'prefix': '',
1137 'base_prefix': '',
1138 'exec_prefix': '',
1139 'base_exec_prefix': '',
1140 }
Victor Stinner8bf39b62019-09-26 02:22:35 +02001141 self.default_program_name(config)
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001142 env = {'TESTPATH': os.path.pathsep.join(paths)}
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001143
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001144 self.check_all_configs("test_init_setpath", config,
1145 api=API_COMPAT, env=env,
1146 ignore_stderr=True)
1147
Victor Stinner8bf39b62019-09-26 02:22:35 +02001148 def test_init_setpath_config(self):
1149 # Test Py_SetPath() with PyConfig
1150 config = self._get_expected_config()
1151 paths = config['config']['module_search_paths']
1152
1153 config = {
1154 # set by Py_SetPath()
1155 'module_search_paths': paths,
1156 'prefix': '',
1157 'base_prefix': '',
1158 'exec_prefix': '',
1159 'base_exec_prefix': '',
Christian Clausscfca4a62021-10-07 17:49:47 +02001160 # overridden by PyConfig
Victor Stinner8bf39b62019-09-26 02:22:35 +02001161 'program_name': 'conf_program_name',
1162 'base_executable': 'conf_executable',
1163 'executable': 'conf_executable',
1164 }
1165 env = {'TESTPATH': os.path.pathsep.join(paths)}
Victor Stinner8bf39b62019-09-26 02:22:35 +02001166 self.check_all_configs("test_init_setpath_config", config,
Victor Stinner49d99f02019-09-26 04:01:49 +02001167 api=API_PYTHON, env=env, ignore_stderr=True)
Victor Stinner8bf39b62019-09-26 02:22:35 +02001168
Victor Stinner52ad33a2019-09-25 02:10:35 +02001169 def module_search_paths(self, prefix=None, exec_prefix=None):
1170 config = self._get_expected_config()
1171 if prefix is None:
1172 prefix = config['config']['prefix']
1173 if exec_prefix is None:
1174 exec_prefix = config['config']['prefix']
1175 if MS_WINDOWS:
1176 return config['config']['module_search_paths']
1177 else:
1178 ver = sys.version_info
1179 return [
Victor Stinner8510f432020-03-10 09:53:09 +01001180 os.path.join(prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001181 f'python{ver.major}{ver.minor}.zip'),
Victor Stinner8510f432020-03-10 09:53:09 +01001182 os.path.join(prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001183 f'python{ver.major}.{ver.minor}'),
Victor Stinner8510f432020-03-10 09:53:09 +01001184 os.path.join(exec_prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001185 f'python{ver.major}.{ver.minor}', 'lib-dynload'),
1186 ]
1187
1188 @contextlib.contextmanager
1189 def tmpdir_with_python(self):
1190 # Temporary directory with a copy of the Python program
1191 with tempfile.TemporaryDirectory() as tmpdir:
Victor Stinner00508a72019-09-25 16:30:36 +02001192 # bpo-38234: On macOS and FreeBSD, the temporary directory
1193 # can be symbolic link. For example, /tmp can be a symbolic link
1194 # to /var/tmp. Call realpath() to resolve all symbolic links.
1195 tmpdir = os.path.realpath(tmpdir)
1196
Victor Stinner52ad33a2019-09-25 02:10:35 +02001197 if MS_WINDOWS:
1198 # Copy pythonXY.dll (or pythonXY_d.dll)
1199 ver = sys.version_info
1200 dll = f'python{ver.major}{ver.minor}'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001201 dll3 = f'python{ver.major}'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001202 if debug_build(sys.executable):
1203 dll += '_d'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001204 dll3 += '_d'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001205 dll += '.dll'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001206 dll3 += '.dll'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001207 dll = os.path.join(os.path.dirname(self.test_exe), dll)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001208 dll3 = os.path.join(os.path.dirname(self.test_exe), dll3)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001209 dll_copy = os.path.join(tmpdir, os.path.basename(dll))
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001210 dll3_copy = os.path.join(tmpdir, os.path.basename(dll3))
Victor Stinner52ad33a2019-09-25 02:10:35 +02001211 shutil.copyfile(dll, dll_copy)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001212 shutil.copyfile(dll3, dll3_copy)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001213
1214 # Copy Python program
1215 exec_copy = os.path.join(tmpdir, os.path.basename(self.test_exe))
1216 shutil.copyfile(self.test_exe, exec_copy)
1217 shutil.copystat(self.test_exe, exec_copy)
1218 self.test_exe = exec_copy
1219
1220 yield tmpdir
1221
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001222 def test_init_setpythonhome(self):
Victor Stinner8bf39b62019-09-26 02:22:35 +02001223 # Test Py_SetPythonHome(home) with PYTHONPATH env var
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001224 config = self._get_expected_config()
1225 paths = config['config']['module_search_paths']
1226 paths_str = os.path.pathsep.join(paths)
1227
1228 for path in paths:
1229 if not os.path.isdir(path):
1230 continue
1231 if os.path.exists(os.path.join(path, 'os.py')):
1232 home = os.path.dirname(path)
1233 break
1234 else:
1235 self.fail(f"Unable to find home in {paths!r}")
1236
1237 prefix = exec_prefix = home
1238 ver = sys.version_info
Victor Stinner52ad33a2019-09-25 02:10:35 +02001239 expected_paths = self.module_search_paths(prefix=home, exec_prefix=home)
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001240
1241 config = {
1242 'home': home,
1243 'module_search_paths': expected_paths,
1244 'prefix': prefix,
1245 'base_prefix': prefix,
1246 'exec_prefix': exec_prefix,
1247 'base_exec_prefix': exec_prefix,
1248 'pythonpath_env': paths_str,
1249 }
Victor Stinner8bf39b62019-09-26 02:22:35 +02001250 self.default_program_name(config)
1251 env = {'TESTHOME': home, 'PYTHONPATH': paths_str}
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001252 self.check_all_configs("test_init_setpythonhome", config,
1253 api=API_COMPAT, env=env)
1254
Victor Stinner52ad33a2019-09-25 02:10:35 +02001255 def copy_paths_by_env(self, config):
1256 all_configs = self._get_expected_config()
1257 paths = all_configs['config']['module_search_paths']
1258 paths_str = os.path.pathsep.join(paths)
1259 config['pythonpath_env'] = paths_str
1260 env = {'PYTHONPATH': paths_str}
1261 return env
1262
1263 @unittest.skipIf(MS_WINDOWS, 'Windows does not use pybuilddir.txt')
1264 def test_init_pybuilddir(self):
1265 # Test path configuration with pybuilddir.txt configuration file
1266
1267 with self.tmpdir_with_python() as tmpdir:
1268 # pybuilddir.txt is a sub-directory relative to the current
1269 # directory (tmpdir)
1270 subdir = 'libdir'
1271 libdir = os.path.join(tmpdir, subdir)
1272 os.mkdir(libdir)
1273
1274 filename = os.path.join(tmpdir, 'pybuilddir.txt')
1275 with open(filename, "w", encoding="utf8") as fp:
1276 fp.write(subdir)
1277
1278 module_search_paths = self.module_search_paths()
1279 module_search_paths[-1] = libdir
1280
1281 executable = self.test_exe
1282 config = {
1283 'base_executable': executable,
1284 'executable': executable,
1285 'module_search_paths': module_search_paths,
1286 }
1287 env = self.copy_paths_by_env(config)
1288 self.check_all_configs("test_init_compat_config", config,
1289 api=API_COMPAT, env=env,
1290 ignore_stderr=True, cwd=tmpdir)
1291
1292 def test_init_pyvenv_cfg(self):
1293 # Test path configuration with pyvenv.cfg configuration file
1294
1295 with self.tmpdir_with_python() as tmpdir, \
1296 tempfile.TemporaryDirectory() as pyvenv_home:
1297 ver = sys.version_info
1298
1299 if not MS_WINDOWS:
1300 lib_dynload = os.path.join(pyvenv_home,
Victor Stinner8510f432020-03-10 09:53:09 +01001301 sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001302 f'python{ver.major}.{ver.minor}',
1303 'lib-dynload')
1304 os.makedirs(lib_dynload)
1305 else:
1306 lib_dynload = os.path.join(pyvenv_home, 'lib')
1307 os.makedirs(lib_dynload)
1308 # getpathp.c uses Lib\os.py as the LANDMARK
1309 shutil.copyfile(os.__file__, os.path.join(lib_dynload, 'os.py'))
1310
1311 filename = os.path.join(tmpdir, 'pyvenv.cfg')
1312 with open(filename, "w", encoding="utf8") as fp:
1313 print("home = %s" % pyvenv_home, file=fp)
1314 print("include-system-site-packages = false", file=fp)
1315
1316 paths = self.module_search_paths()
1317 if not MS_WINDOWS:
1318 paths[-1] = lib_dynload
1319 else:
1320 for index, path in enumerate(paths):
1321 if index == 0:
1322 paths[index] = os.path.join(tmpdir, os.path.basename(path))
1323 else:
1324 paths[index] = os.path.join(pyvenv_home, os.path.basename(path))
1325 paths[-1] = pyvenv_home
1326
1327 executable = self.test_exe
1328 exec_prefix = pyvenv_home
1329 config = {
1330 'base_exec_prefix': exec_prefix,
1331 'exec_prefix': exec_prefix,
1332 'base_executable': executable,
1333 'executable': executable,
1334 'module_search_paths': paths,
1335 }
Victor Stinner8f427482020-07-08 00:20:37 +02001336 path_config = {}
Victor Stinner52ad33a2019-09-25 02:10:35 +02001337 if MS_WINDOWS:
1338 config['base_prefix'] = pyvenv_home
1339 config['prefix'] = pyvenv_home
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001340
Victor Stinner8f427482020-07-08 00:20:37 +02001341 ver = sys.version_info
1342 dll = f'python{ver.major}'
1343 if debug_build(executable):
1344 dll += '_d'
1345 dll += '.DLL'
1346 dll = os.path.join(os.path.dirname(executable), dll)
1347 path_config['python3_dll'] = dll
1348
1349 env = self.copy_paths_by_env(config)
1350 self.check_all_configs("test_init_compat_config", config,
1351 expected_pathconfig=path_config,
1352 api=API_COMPAT, env=env,
1353 ignore_stderr=True, cwd=tmpdir)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001354
Victor Stinner12f2f172019-09-26 15:51:50 +02001355 def test_global_pathconfig(self):
1356 # Test C API functions getting the path configuration:
1357 #
1358 # - Py_GetExecPrefix()
1359 # - Py_GetPath()
1360 # - Py_GetPrefix()
1361 # - Py_GetProgramFullPath()
1362 # - Py_GetProgramName()
1363 # - Py_GetPythonHome()
1364 #
1365 # The global path configuration (_Py_path_config) must be a copy
1366 # of the path configuration of PyInterpreter.config (PyConfig).
Hai Shibb0424b2020-08-04 00:47:42 +08001367 ctypes = import_helper.import_module('ctypes')
1368 _testinternalcapi = import_helper.import_module('_testinternalcapi')
Victor Stinner12f2f172019-09-26 15:51:50 +02001369
1370 def get_func(name):
1371 func = getattr(ctypes.pythonapi, name)
1372 func.argtypes = ()
1373 func.restype = ctypes.c_wchar_p
1374 return func
1375
1376 Py_GetPath = get_func('Py_GetPath')
1377 Py_GetPrefix = get_func('Py_GetPrefix')
1378 Py_GetExecPrefix = get_func('Py_GetExecPrefix')
1379 Py_GetProgramName = get_func('Py_GetProgramName')
1380 Py_GetProgramFullPath = get_func('Py_GetProgramFullPath')
1381 Py_GetPythonHome = get_func('Py_GetPythonHome')
1382
1383 config = _testinternalcapi.get_configs()['config']
1384
1385 self.assertEqual(Py_GetPath().split(os.path.pathsep),
1386 config['module_search_paths'])
1387 self.assertEqual(Py_GetPrefix(), config['prefix'])
1388 self.assertEqual(Py_GetExecPrefix(), config['exec_prefix'])
1389 self.assertEqual(Py_GetProgramName(), config['program_name'])
1390 self.assertEqual(Py_GetProgramFullPath(), config['executable'])
1391 self.assertEqual(Py_GetPythonHome(), config['home'])
1392
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001393 def test_init_warnoptions(self):
1394 # lowest to highest priority
1395 warnoptions = [
1396 'ignore:::PyConfig_Insert0', # PyWideStringList_Insert(0)
1397 'default', # PyConfig.dev_mode=1
1398 'ignore:::env1', # PYTHONWARNINGS env var
1399 'ignore:::env2', # PYTHONWARNINGS env var
1400 'ignore:::cmdline1', # -W opt command line option
1401 'ignore:::cmdline2', # -W opt command line option
1402 'default::BytesWarning', # PyConfig.bytes_warnings=1
1403 'ignore:::PySys_AddWarnOption1', # PySys_AddWarnOption()
1404 'ignore:::PySys_AddWarnOption2', # PySys_AddWarnOption()
1405 'ignore:::PyConfig_BeforeRead', # PyConfig.warnoptions
1406 'ignore:::PyConfig_AfterRead'] # PyWideStringList_Append()
1407 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
1408 config = {
1409 'dev_mode': 1,
1410 'faulthandler': 1,
1411 'bytes_warning': 1,
1412 'warnoptions': warnoptions,
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001413 'orig_argv': ['python3',
1414 '-Wignore:::cmdline1',
1415 '-Wignore:::cmdline2'],
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001416 }
1417 self.check_all_configs("test_init_warnoptions", config, preconfig,
1418 api=API_PYTHON)
1419
Victor Stinner048a3562020-11-05 00:45:56 +01001420 def test_init_set_config(self):
1421 config = {
1422 '_init_main': 0,
1423 'bytes_warning': 2,
1424 'warnoptions': ['error::BytesWarning'],
1425 }
1426 self.check_all_configs("test_init_set_config", config,
1427 api=API_ISOLATED)
1428
Victor Stinnere81f6e62020-06-08 18:12:59 +02001429 def test_get_argc_argv(self):
1430 self.run_embedded_interpreter("test_get_argc_argv")
1431 # ignore output
1432
Victor Stinner56b29b62018-07-26 18:57:56 +02001433
Victor Stinnerf3cb8142020-11-05 18:12:33 +01001434class SetConfigTests(unittest.TestCase):
1435 def test_set_config(self):
1436 # bpo-42260: Test _PyInterpreterState_SetConfig()
1437 cmd = [sys.executable, '-I', '-m', 'test._test_embed_set_config']
1438 proc = subprocess.run(cmd,
1439 stdout=subprocess.PIPE,
1440 stderr=subprocess.PIPE)
1441 self.assertEqual(proc.returncode, 0,
1442 (proc.returncode, proc.stdout, proc.stderr))
1443
1444
Steve Dowerb82e17e2019-05-23 08:45:22 -07001445class AuditingTests(EmbeddingTestsMixin, unittest.TestCase):
1446 def test_open_code_hook(self):
1447 self.run_embedded_interpreter("test_open_code_hook")
1448
1449 def test_audit(self):
1450 self.run_embedded_interpreter("test_audit")
1451
1452 def test_audit_subinterpreter(self):
1453 self.run_embedded_interpreter("test_audit_subinterpreter")
1454
Steve Dowere226e832019-07-01 16:03:53 -07001455 def test_audit_run_command(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001456 self.run_embedded_interpreter("test_audit_run_command",
1457 timeout=support.SHORT_TIMEOUT,
1458 returncode=1)
Steve Dowere226e832019-07-01 16:03:53 -07001459
1460 def test_audit_run_file(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001461 self.run_embedded_interpreter("test_audit_run_file",
1462 timeout=support.SHORT_TIMEOUT,
1463 returncode=1)
Steve Dowere226e832019-07-01 16:03:53 -07001464
1465 def test_audit_run_interactivehook(self):
Hai Shibb0424b2020-08-04 00:47:42 +08001466 startup = os.path.join(self.oldcwd, os_helper.TESTFN) + ".py"
Steve Dowere226e832019-07-01 16:03:53 -07001467 with open(startup, "w", encoding="utf-8") as f:
1468 print("import sys", file=f)
1469 print("sys.__interactivehook__ = lambda: None", file=f)
1470 try:
1471 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
Victor Stinner7772b1a2019-12-11 22:17:04 +01001472 self.run_embedded_interpreter("test_audit_run_interactivehook",
1473 timeout=support.SHORT_TIMEOUT,
Steve Dowere226e832019-07-01 16:03:53 -07001474 returncode=10, env=env)
1475 finally:
1476 os.unlink(startup)
1477
1478 def test_audit_run_startup(self):
Hai Shibb0424b2020-08-04 00:47:42 +08001479 startup = os.path.join(self.oldcwd, os_helper.TESTFN) + ".py"
Steve Dowere226e832019-07-01 16:03:53 -07001480 with open(startup, "w", encoding="utf-8") as f:
1481 print("pass", file=f)
1482 try:
1483 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
Victor Stinner7772b1a2019-12-11 22:17:04 +01001484 self.run_embedded_interpreter("test_audit_run_startup",
1485 timeout=support.SHORT_TIMEOUT,
Steve Dowere226e832019-07-01 16:03:53 -07001486 returncode=10, env=env)
1487 finally:
1488 os.unlink(startup)
1489
1490 def test_audit_run_stdin(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001491 self.run_embedded_interpreter("test_audit_run_stdin",
1492 timeout=support.SHORT_TIMEOUT,
1493 returncode=1)
Steve Dowerb82e17e2019-05-23 08:45:22 -07001494
Victor Stinner4908fae2021-04-30 14:56:27 +02001495
Victor Stinner11d13e82021-01-12 11:26:26 +01001496class MiscTests(EmbeddingTestsMixin, unittest.TestCase):
1497 def test_unicode_id_init(self):
1498 # bpo-42882: Test that _PyUnicode_FromId() works
1499 # when Python is initialized multiples times.
1500 self.run_embedded_interpreter("test_unicode_id_init")
1501
Victor Stinner4908fae2021-04-30 14:56:27 +02001502
1503class StdPrinterTests(EmbeddingTestsMixin, unittest.TestCase):
1504 # Test PyStdPrinter_Type which is used by _PySys_SetPreliminaryStderr():
1505 # "Set up a preliminary stderr printer until we have enough
1506 # infrastructure for the io module in place."
1507
1508 def get_stdout_fd(self):
1509 return sys.__stdout__.fileno()
1510
1511 def create_printer(self, fd):
1512 ctypes = import_helper.import_module('ctypes')
1513 PyFile_NewStdPrinter = ctypes.pythonapi.PyFile_NewStdPrinter
1514 PyFile_NewStdPrinter.argtypes = (ctypes.c_int,)
1515 PyFile_NewStdPrinter.restype = ctypes.py_object
1516 return PyFile_NewStdPrinter(fd)
1517
1518 def test_write(self):
1519 message = "unicode:\xe9-\u20ac-\udc80!\n"
1520
1521 stdout_fd = self.get_stdout_fd()
1522 stdout_fd_copy = os.dup(stdout_fd)
1523 self.addCleanup(os.close, stdout_fd_copy)
1524
1525 rfd, wfd = os.pipe()
1526 self.addCleanup(os.close, rfd)
1527 self.addCleanup(os.close, wfd)
1528 try:
1529 # PyFile_NewStdPrinter() only accepts fileno(stdout)
1530 # or fileno(stderr) file descriptor.
1531 os.dup2(wfd, stdout_fd)
1532
1533 printer = self.create_printer(stdout_fd)
1534 printer.write(message)
1535 finally:
1536 os.dup2(stdout_fd_copy, stdout_fd)
1537
1538 data = os.read(rfd, 100)
1539 self.assertEqual(data, message.encode('utf8', 'backslashreplace'))
1540
1541 def test_methods(self):
1542 fd = self.get_stdout_fd()
1543 printer = self.create_printer(fd)
1544 self.assertEqual(printer.fileno(), fd)
1545 self.assertEqual(printer.isatty(), os.isatty(fd))
1546 printer.flush() # noop
1547 printer.close() # noop
1548
1549 def test_disallow_instantiation(self):
1550 fd = self.get_stdout_fd()
1551 printer = self.create_printer(fd)
Erlend Egeberg Aasland0a3452e2021-06-24 01:46:25 +02001552 support.check_disallow_instantiation(self, type(printer))
Victor Stinner4908fae2021-04-30 14:56:27 +02001553
1554
Nick Coghlan39f0bb52017-11-28 08:11:51 +10001555if __name__ == "__main__":
1556 unittest.main()