blob: 646cd0632edd8c70f65ab8b643b02ab4564fb637 [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,
Inada Naoki48274832021-03-29 12:28:14 +0900392 'warn_default_encoding': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200393 'inspect': 0,
394 'interactive': 0,
395 'optimization_level': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200396 'parser_debug': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200397 'write_bytecode': 1,
398 'verbose': 0,
399 'quiet': 0,
400 'user_site_directory': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200401 'configure_c_stdio': 0,
Victor Stinner98512272018-08-01 03:07:00 +0200402 'buffered_stdio': 1,
Victor Stinnerc5989cd2018-08-29 19:32:47 +0200403
Victor Stinnera6537fb2018-11-26 11:54:12 +0100404 'stdio_encoding': GET_DEFAULT_CONFIG,
405 'stdio_errors': GET_DEFAULT_CONFIG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200406
Victor Stinner62be7632019-03-01 13:10:14 +0100407 'skip_source_first_line': 0,
408 'run_command': None,
409 'run_module': None,
410 'run_filename': None,
411
Victor Stinner56b29b62018-07-26 18:57:56 +0200412 '_install_importlib': 1,
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400413 'check_hash_pycs_mode': 'default',
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200414 'pathconfig_warnings': 1,
415 '_init_main': 1,
Victor Stinner252346a2020-05-01 11:33:44 +0200416 '_isolated_interpreter': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200417 }
Victor Stinner01de89c2018-11-14 17:39:45 +0100418 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200419 CONFIG_COMPAT.update({
Victor Stinner01de89c2018-11-14 17:39:45 +0100420 'legacy_windows_stdio': 0,
421 })
422
Victor Stinner331a6a52019-05-27 16:39:22 +0200423 CONFIG_PYTHON = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200424 _config_init=API_PYTHON,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200425 configure_c_stdio=1,
Victor Stinnerdc42af82020-11-05 18:58:07 +0100426 parse_argv=2,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200427 )
Victor Stinner331a6a52019-05-27 16:39:22 +0200428 CONFIG_ISOLATED = dict(CONFIG_COMPAT,
Victor Stinner20e1e252019-05-23 04:12:27 +0200429 _config_init=API_ISOLATED,
Victor Stinnerbab0db62019-05-18 03:21:27 +0200430 isolated=1,
431 use_environment=0,
432 user_site_directory=0,
433 dev_mode=0,
434 install_signal_handlers=0,
435 use_hash_seed=0,
436 faulthandler=0,
437 tracemalloc=0,
438 pathconfig_warnings=0,
439 )
440 if MS_WINDOWS:
Victor Stinner331a6a52019-05-27 16:39:22 +0200441 CONFIG_ISOLATED['legacy_windows_stdio'] = 0
Victor Stinnerbab0db62019-05-18 03:21:27 +0200442
Victor Stinner01de89c2018-11-14 17:39:45 +0100443 # global config
444 DEFAULT_GLOBAL_CONFIG = {
445 'Py_HasFileSystemDefaultEncoding': 0,
446 'Py_HashRandomizationFlag': 1,
447 '_Py_HasFileSystemDefaultEncodeErrors': 0,
448 }
Victor Stinner1075d162019-03-25 23:19:57 +0100449 COPY_GLOBAL_PRE_CONFIG = [
Victor Stinner1075d162019-03-25 23:19:57 +0100450 ('Py_UTF8Mode', 'utf8_mode'),
451 ]
Victor Stinner01de89c2018-11-14 17:39:45 +0100452 COPY_GLOBAL_CONFIG = [
453 # Copy core config to global config for expected values
454 # True means that the core config value is inverted (0 => 1 and 1 => 0)
455 ('Py_BytesWarningFlag', 'bytes_warning'),
456 ('Py_DebugFlag', 'parser_debug'),
457 ('Py_DontWriteBytecodeFlag', 'write_bytecode', True),
458 ('Py_FileSystemDefaultEncodeErrors', 'filesystem_errors'),
459 ('Py_FileSystemDefaultEncoding', 'filesystem_encoding'),
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200460 ('Py_FrozenFlag', 'pathconfig_warnings', True),
Victor Stinner20004952019-03-26 02:31:11 +0100461 ('Py_IgnoreEnvironmentFlag', 'use_environment', True),
Victor Stinner01de89c2018-11-14 17:39:45 +0100462 ('Py_InspectFlag', 'inspect'),
463 ('Py_InteractiveFlag', 'interactive'),
Victor Stinner20004952019-03-26 02:31:11 +0100464 ('Py_IsolatedFlag', 'isolated'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100465 ('Py_NoSiteFlag', 'site_import', True),
466 ('Py_NoUserSiteDirectory', 'user_site_directory', True),
467 ('Py_OptimizeFlag', 'optimization_level'),
468 ('Py_QuietFlag', 'quiet'),
Victor Stinner01de89c2018-11-14 17:39:45 +0100469 ('Py_UnbufferedStdioFlag', 'buffered_stdio', True),
470 ('Py_VerboseFlag', 'verbose'),
471 ]
472 if MS_WINDOWS:
Victor Stinner1075d162019-03-25 23:19:57 +0100473 COPY_GLOBAL_PRE_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100474 ('Py_LegacyWindowsFSEncodingFlag', 'legacy_windows_fs_encoding'),
Victor Stinner1075d162019-03-25 23:19:57 +0100475 ))
476 COPY_GLOBAL_CONFIG.extend((
Victor Stinner01de89c2018-11-14 17:39:45 +0100477 ('Py_LegacyWindowsStdioFlag', 'legacy_windows_stdio'),
478 ))
Victor Stinner56b29b62018-07-26 18:57:56 +0200479
Victor Stinner8f427482020-07-08 00:20:37 +0200480 # path config
481 if MS_WINDOWS:
482 PATH_CONFIG = {
483 'isolated': -1,
484 'site_import': -1,
485 'python3_dll': GET_DEFAULT_CONFIG,
486 }
487 else:
488 PATH_CONFIG = {}
489 # other keys are copied by COPY_PATH_CONFIG
490
491 COPY_PATH_CONFIG = [
492 # Copy core config to global config for expected values
493 'prefix',
494 'exec_prefix',
495 'program_name',
496 'home',
497 # program_full_path and module_search_path are copied indirectly from
498 # the core configuration in check_path_config().
499 ]
500 if MS_WINDOWS:
501 COPY_PATH_CONFIG.extend((
502 'base_executable',
503 ))
504
Victor Stinner425717f2019-05-20 16:38:48 +0200505 EXPECTED_CONFIG = None
506
Victor Stinner52ad33a2019-09-25 02:10:35 +0200507 @classmethod
508 def tearDownClass(cls):
509 # clear cache
510 cls.EXPECTED_CONFIG = None
511
Victor Stinner01de89c2018-11-14 17:39:45 +0100512 def main_xoptions(self, xoptions_list):
513 xoptions = {}
514 for opt in xoptions_list:
515 if '=' in opt:
516 key, value = opt.split('=', 1)
517 xoptions[key] = value
518 else:
519 xoptions[opt] = True
520 return xoptions
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200521
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200522 def _get_expected_config_impl(self):
523 env = remove_python_envvars()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100524 code = textwrap.dedent('''
525 import json
Victor Stinnera6537fb2018-11-26 11:54:12 +0100526 import sys
Victor Stinner5eb8b072019-05-15 02:12:48 +0200527 import _testinternalcapi
Victor Stinnera6537fb2018-11-26 11:54:12 +0100528
Victor Stinner5eb8b072019-05-15 02:12:48 +0200529 configs = _testinternalcapi.get_configs()
Victor Stinnera6537fb2018-11-26 11:54:12 +0100530
Victor Stinner425717f2019-05-20 16:38:48 +0200531 data = json.dumps(configs)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100532 data = data.encode('utf-8')
533 sys.stdout.buffer.write(data)
534 sys.stdout.buffer.flush()
535 ''')
536
537 # Use -S to not import the site module: get the proper configuration
538 # when test_embed is run from a venv (bpo-35313)
Victor Stinner5eb8b072019-05-15 02:12:48 +0200539 args = [sys.executable, '-S', '-c', code]
Victor Stinnera6537fb2018-11-26 11:54:12 +0100540 proc = subprocess.run(args, env=env,
541 stdout=subprocess.PIPE,
Victor Stinner52ad33a2019-09-25 02:10:35 +0200542 stderr=subprocess.PIPE)
Victor Stinnera6537fb2018-11-26 11:54:12 +0100543 if proc.returncode:
544 raise Exception(f"failed to get the default config: "
545 f"stdout={proc.stdout!r} stderr={proc.stderr!r}")
546 stdout = proc.stdout.decode('utf-8')
Victor Stinner52ad33a2019-09-25 02:10:35 +0200547 # ignore stderr
Victor Stinner4631da12019-05-02 15:30:21 -0400548 try:
Victor Stinner425717f2019-05-20 16:38:48 +0200549 return json.loads(stdout)
Victor Stinner4631da12019-05-02 15:30:21 -0400550 except json.JSONDecodeError:
551 self.fail(f"fail to decode stdout: {stdout!r}")
Victor Stinnera6537fb2018-11-26 11:54:12 +0100552
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200553 def _get_expected_config(self):
554 cls = InitConfigTests
555 if cls.EXPECTED_CONFIG is None:
556 cls.EXPECTED_CONFIG = self._get_expected_config_impl()
557
558 # get a copy
Victor Stinner52ad33a2019-09-25 02:10:35 +0200559 configs = {}
560 for config_key, config_value in cls.EXPECTED_CONFIG.items():
561 config = {}
562 for key, value in config_value.items():
563 if isinstance(value, list):
564 value = value.copy()
565 config[key] = value
566 configs[config_key] = config
567 return configs
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200568
Victor Stinner8f427482020-07-08 00:20:37 +0200569 def get_expected_config(self, expected_preconfig, expected,
570 expected_pathconfig, env, api,
Victor Stinner3842f292019-08-23 16:57:54 +0100571 modify_path_cb=None):
Victor Stinner425717f2019-05-20 16:38:48 +0200572 cls = self.__class__
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200573 configs = self._get_expected_config()
Victor Stinner425717f2019-05-20 16:38:48 +0200574
575 pre_config = configs['pre_config']
576 for key, value in expected_preconfig.items():
577 if value is self.GET_DEFAULT_CONFIG:
578 expected_preconfig[key] = pre_config[key]
579
Victor Stinner8f427482020-07-08 00:20:37 +0200580 path_config = configs['path_config']
581 for key, value in expected_pathconfig.items():
582 if value is self.GET_DEFAULT_CONFIG:
583 expected_pathconfig[key] = path_config[key]
584
Victor Stinner022be022019-05-22 23:58:50 +0200585 if not expected_preconfig['configure_locale'] or api == API_COMPAT:
Victor Stinner425717f2019-05-20 16:38:48 +0200586 # there is no easy way to get the locale encoding before
587 # setlocale(LC_CTYPE, "") is called: don't test encodings
588 for key in ('filesystem_encoding', 'filesystem_errors',
589 'stdio_encoding', 'stdio_errors'):
590 expected[key] = self.IGNORE_CONFIG
591
592 if not expected_preconfig['configure_locale']:
593 # UTF-8 Mode depends on the locale. There is no easy way
594 # to guess if UTF-8 Mode will be enabled or not if the locale
595 # is not configured.
596 expected_preconfig['utf8_mode'] = self.IGNORE_CONFIG
597
598 if expected_preconfig['utf8_mode'] == 1:
599 if expected['filesystem_encoding'] is self.GET_DEFAULT_CONFIG:
600 expected['filesystem_encoding'] = 'utf-8'
601 if expected['filesystem_errors'] is self.GET_DEFAULT_CONFIG:
602 expected['filesystem_errors'] = self.UTF8_MODE_ERRORS
603 if expected['stdio_encoding'] is self.GET_DEFAULT_CONFIG:
604 expected['stdio_encoding'] = 'utf-8'
605 if expected['stdio_errors'] is self.GET_DEFAULT_CONFIG:
606 expected['stdio_errors'] = 'surrogateescape'
607
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100608 if MS_WINDOWS:
Steve Dower9048c492019-06-29 10:34:11 -0700609 default_executable = self.test_exe
610 elif expected['program_name'] is not self.GET_DEFAULT_CONFIG:
611 default_executable = os.path.abspath(expected['program_name'])
612 else:
613 default_executable = os.path.join(os.getcwd(), '_testembed')
Victor Stinner91c99872019-05-14 22:01:51 +0200614 if expected['executable'] is self.GET_DEFAULT_CONFIG:
Steve Dower9048c492019-06-29 10:34:11 -0700615 expected['executable'] = default_executable
616 if expected['base_executable'] is self.GET_DEFAULT_CONFIG:
617 expected['base_executable'] = default_executable
Victor Stinner91c99872019-05-14 22:01:51 +0200618 if expected['program_name'] is self.GET_DEFAULT_CONFIG:
619 expected['program_name'] = './_testembed'
620
Victor Stinner331a6a52019-05-27 16:39:22 +0200621 config = configs['config']
Victor Stinnera6537fb2018-11-26 11:54:12 +0100622 for key, value in expected.items():
623 if value is self.GET_DEFAULT_CONFIG:
Victor Stinner331a6a52019-05-27 16:39:22 +0200624 expected[key] = config[key]
Victor Stinner5eb8b072019-05-15 02:12:48 +0200625
Sandro Mani8f023a22020-06-08 17:28:11 +0200626 if expected['module_search_paths'] is not self.IGNORE_CONFIG:
627 pythonpath_env = expected['pythonpath_env']
628 if pythonpath_env is not None:
629 paths = pythonpath_env.split(os.path.pathsep)
630 expected['module_search_paths'] = [*paths, *expected['module_search_paths']]
631 if modify_path_cb is not None:
632 expected['module_search_paths'] = expected['module_search_paths'].copy()
633 modify_path_cb(expected['module_search_paths'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200634
Victor Stinner425717f2019-05-20 16:38:48 +0200635 for key in self.COPY_PRE_CONFIG:
636 if key not in expected_preconfig:
637 expected_preconfig[key] = expected[key]
Victor Stinner01de89c2018-11-14 17:39:45 +0100638
Victor Stinner331a6a52019-05-27 16:39:22 +0200639 def check_pre_config(self, configs, expected):
640 pre_config = dict(configs['pre_config'])
Victor Stinner425717f2019-05-20 16:38:48 +0200641 for key, value in list(expected.items()):
642 if value is self.IGNORE_CONFIG:
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100643 pre_config.pop(key, None)
Victor Stinner425717f2019-05-20 16:38:48 +0200644 del expected[key]
645 self.assertEqual(pre_config, expected)
Victor Stinner1075d162019-03-25 23:19:57 +0100646
Victor Stinner331a6a52019-05-27 16:39:22 +0200647 def check_config(self, configs, expected):
648 config = dict(configs['config'])
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200649 for key, value in list(expected.items()):
650 if value is self.IGNORE_CONFIG:
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100651 config.pop(key, None)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +0200652 del expected[key]
Victor Stinner331a6a52019-05-27 16:39:22 +0200653 self.assertEqual(config, expected)
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200654
Victor Stinner331a6a52019-05-27 16:39:22 +0200655 def check_global_config(self, configs):
656 pre_config = configs['pre_config']
657 config = configs['config']
Victor Stinner00b137c2018-11-13 19:59:26 +0100658
Victor Stinnera6537fb2018-11-26 11:54:12 +0100659 expected = dict(self.DEFAULT_GLOBAL_CONFIG)
Victor Stinner01de89c2018-11-14 17:39:45 +0100660 for item in self.COPY_GLOBAL_CONFIG:
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100661 if len(item) == 3:
662 global_key, core_key, opposite = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200663 expected[global_key] = 0 if config[core_key] else 1
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100664 else:
665 global_key, core_key = item
Victor Stinner331a6a52019-05-27 16:39:22 +0200666 expected[global_key] = config[core_key]
Victor Stinner1075d162019-03-25 23:19:57 +0100667 for item in self.COPY_GLOBAL_PRE_CONFIG:
668 if len(item) == 3:
669 global_key, core_key, opposite = item
670 expected[global_key] = 0 if pre_config[core_key] else 1
671 else:
672 global_key, core_key = item
673 expected[global_key] = pre_config[core_key]
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100674
Victor Stinner331a6a52019-05-27 16:39:22 +0200675 self.assertEqual(configs['global_config'], expected)
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100676
Victor Stinner8f427482020-07-08 00:20:37 +0200677 def check_path_config(self, configs, expected):
678 config = configs['config']
679
680 for key in self.COPY_PATH_CONFIG:
681 expected[key] = config[key]
682 expected['module_search_path'] = os.path.pathsep.join(config['module_search_paths'])
683 expected['program_full_path'] = config['executable']
684
685 self.assertEqual(configs['path_config'], expected)
686
Victor Stinner331a6a52019-05-27 16:39:22 +0200687 def check_all_configs(self, testname, expected_config=None,
Victor Stinner8f427482020-07-08 00:20:37 +0200688 expected_preconfig=None, expected_pathconfig=None,
689 modify_path_cb=None,
Victor Stinner8bf39b62019-09-26 02:22:35 +0200690 stderr=None, *, api, preconfig_api=None,
691 env=None, ignore_stderr=False, cwd=None):
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200692 new_env = remove_python_envvars()
693 if env is not None:
694 new_env.update(env)
695 env = new_env
Victor Stinner01de89c2018-11-14 17:39:45 +0100696
Victor Stinner8bf39b62019-09-26 02:22:35 +0200697 if preconfig_api is None:
698 preconfig_api = api
699 if preconfig_api == API_ISOLATED:
Victor Stinner022be022019-05-22 23:58:50 +0200700 default_preconfig = self.PRE_CONFIG_ISOLATED
Victor Stinner8bf39b62019-09-26 02:22:35 +0200701 elif preconfig_api == API_PYTHON:
Victor Stinner022be022019-05-22 23:58:50 +0200702 default_preconfig = self.PRE_CONFIG_PYTHON
Victor Stinnerbab0db62019-05-18 03:21:27 +0200703 else:
Victor Stinner022be022019-05-22 23:58:50 +0200704 default_preconfig = self.PRE_CONFIG_COMPAT
Victor Stinnerbab0db62019-05-18 03:21:27 +0200705 if expected_preconfig is None:
706 expected_preconfig = {}
707 expected_preconfig = dict(default_preconfig, **expected_preconfig)
Victor Stinner8f427482020-07-08 00:20:37 +0200708
Victor Stinnerbab0db62019-05-18 03:21:27 +0200709 if expected_config is None:
710 expected_config = {}
Victor Stinner425717f2019-05-20 16:38:48 +0200711
Victor Stinner8f427482020-07-08 00:20:37 +0200712 if expected_pathconfig is None:
713 expected_pathconfig = {}
714 expected_pathconfig = dict(self.PATH_CONFIG, **expected_pathconfig)
715
Victor Stinner022be022019-05-22 23:58:50 +0200716 if api == API_PYTHON:
Victor Stinner331a6a52019-05-27 16:39:22 +0200717 default_config = self.CONFIG_PYTHON
Victor Stinner022be022019-05-22 23:58:50 +0200718 elif api == API_ISOLATED:
Victor Stinner331a6a52019-05-27 16:39:22 +0200719 default_config = self.CONFIG_ISOLATED
Victor Stinner425717f2019-05-20 16:38:48 +0200720 else:
Victor Stinner331a6a52019-05-27 16:39:22 +0200721 default_config = self.CONFIG_COMPAT
Victor Stinner425717f2019-05-20 16:38:48 +0200722 expected_config = dict(default_config, **expected_config)
Victor Stinner425717f2019-05-20 16:38:48 +0200723
724 self.get_expected_config(expected_preconfig,
Victor Stinner8f427482020-07-08 00:20:37 +0200725 expected_config,
726 expected_pathconfig,
727 env,
Victor Stinner3842f292019-08-23 16:57:54 +0100728 api, modify_path_cb)
Victor Stinner1075d162019-03-25 23:19:57 +0100729
Victor Stinner52ad33a2019-09-25 02:10:35 +0200730 out, err = self.run_embedded_interpreter(testname,
731 env=env, cwd=cwd)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200732 if stderr is None and not expected_config['verbose']:
733 stderr = ""
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +0200734 if stderr is not None and not ignore_stderr:
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200735 self.assertEqual(err.rstrip(), stderr)
736 try:
Victor Stinner331a6a52019-05-27 16:39:22 +0200737 configs = json.loads(out)
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200738 except json.JSONDecodeError:
739 self.fail(f"fail to decode stdout: {out!r}")
740
Victor Stinner331a6a52019-05-27 16:39:22 +0200741 self.check_pre_config(configs, expected_preconfig)
742 self.check_config(configs, expected_config)
743 self.check_global_config(configs)
Victor Stinner8f427482020-07-08 00:20:37 +0200744 self.check_path_config(configs, expected_pathconfig)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +0100745 return configs
Victor Stinner7ddd56f2018-11-14 00:24:28 +0100746
Victor Stinner56b29b62018-07-26 18:57:56 +0200747 def test_init_default_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200748 self.check_all_configs("test_init_initialize_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200749
750 def test_preinit_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200751 self.check_all_configs("test_preinit_compat_config", api=API_COMPAT)
Victor Stinner022be022019-05-22 23:58:50 +0200752
753 def test_init_compat_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200754 self.check_all_configs("test_init_compat_config", api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200755
756 def test_init_global_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100757 preconfig = {
758 'utf8_mode': 1,
759 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200760 config = {
761 'program_name': './globalvar',
762 'site_import': 0,
763 'bytes_warning': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100764 'warnoptions': ['default::BytesWarning'],
Victor Stinner56b29b62018-07-26 18:57:56 +0200765 'inspect': 1,
766 'interactive': 1,
767 'optimization_level': 2,
768 'write_bytecode': 0,
769 'verbose': 1,
770 'quiet': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200771 'buffered_stdio': 0,
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200772
Victor Stinner56b29b62018-07-26 18:57:56 +0200773 'user_site_directory': 0,
Victor Stinner54b43bb2019-05-16 18:30:15 +0200774 'pathconfig_warnings': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200775 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200776 self.check_all_configs("test_init_global_config", config, preconfig,
777 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200778
779 def test_init_from_config(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100780 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200781 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner1075d162019-03-25 23:19:57 +0100782 'utf8_mode': 1,
783 }
Victor Stinner56b29b62018-07-26 18:57:56 +0200784 config = {
785 'install_signal_handlers': 0,
786 'use_hash_seed': 1,
787 'hash_seed': 123,
Victor Stinner56b29b62018-07-26 18:57:56 +0200788 'tracemalloc': 2,
789 'import_time': 1,
790 'show_ref_count': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200791 'malloc_stats': 1,
792
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200793 'stdio_encoding': 'iso8859-1',
794 'stdio_errors': 'replace',
Victor Stinner56b29b62018-07-26 18:57:56 +0200795
796 'pycache_prefix': 'conf_pycache_prefix',
797 'program_name': './conf_program_name',
Victor Stinnere81f6e62020-06-08 18:12:59 +0200798 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200799 'orig_argv': ['python3',
800 '-W', 'cmdline_warnoption',
801 '-X', 'cmdline_xoption',
802 '-c', 'pass',
803 'arg2'],
Victor Stinnerdc42af82020-11-05 18:58:07 +0100804 'parse_argv': 2,
Victor Stinner67310022019-07-01 19:52:45 +0200805 'xoptions': [
806 'config_xoption1=3',
807 'config_xoption2=',
808 'config_xoption3',
809 'cmdline_xoption',
810 ],
811 'warnoptions': [
Victor Stinner67310022019-07-01 19:52:45 +0200812 'cmdline_warnoption',
813 'default::BytesWarning',
Victor Stinnerfb4ae152019-09-30 01:40:17 +0200814 'config_warnoption',
Victor Stinner67310022019-07-01 19:52:45 +0200815 ],
Victor Stinner2f549082019-03-29 15:13:46 +0100816 'run_command': 'pass\n',
Victor Stinner56b29b62018-07-26 18:57:56 +0200817
818 'site_import': 0,
819 'bytes_warning': 1,
820 'inspect': 1,
821 'interactive': 1,
822 'optimization_level': 2,
823 'write_bytecode': 0,
824 'verbose': 1,
825 'quiet': 1,
Victor Stinnercab5d072019-05-17 19:01:14 +0200826 'configure_c_stdio': 1,
Victor Stinner98512272018-08-01 03:07:00 +0200827 'buffered_stdio': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200828 'user_site_directory': 0,
829 'faulthandler': 1,
Sandro Mani8f023a22020-06-08 17:28:11 +0200830 'platlibdir': 'my_platlibdir',
831 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinnerb75d7e22018-08-01 02:13:04 +0200832
Victor Stinnercb9fbd32019-05-01 23:51:56 -0400833 'check_hash_pycs_mode': 'always',
Victor Stinner54b43bb2019-05-16 18:30:15 +0200834 'pathconfig_warnings': 0,
Victor Stinner252346a2020-05-01 11:33:44 +0200835
836 '_isolated_interpreter': 1,
Victor Stinner56b29b62018-07-26 18:57:56 +0200837 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200838 self.check_all_configs("test_init_from_config", config, preconfig,
839 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200840
Victor Stinner20e1e252019-05-23 04:12:27 +0200841 def test_init_compat_env(self):
842 preconfig = {
843 'allocator': PYMEM_ALLOCATOR_MALLOC,
844 }
845 config = {
846 'use_hash_seed': 1,
847 'hash_seed': 42,
848 'tracemalloc': 2,
849 'import_time': 1,
850 'malloc_stats': 1,
851 'inspect': 1,
852 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200853 'pythonpath_env': '/my/path',
Victor Stinner20e1e252019-05-23 04:12:27 +0200854 'pycache_prefix': 'env_pycache_prefix',
855 'write_bytecode': 0,
856 'verbose': 1,
857 'buffered_stdio': 0,
858 'stdio_encoding': 'iso8859-1',
859 'stdio_errors': 'replace',
860 'user_site_directory': 0,
861 'faulthandler': 1,
862 'warnoptions': ['EnvVar'],
Sandro Mani8f023a22020-06-08 17:28:11 +0200863 'platlibdir': 'env_platlibdir',
864 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinner20e1e252019-05-23 04:12:27 +0200865 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200866 self.check_all_configs("test_init_compat_env", config, preconfig,
867 api=API_COMPAT)
Victor Stinner20e1e252019-05-23 04:12:27 +0200868
869 def test_init_python_env(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200870 preconfig = {
871 'allocator': PYMEM_ALLOCATOR_MALLOC,
Victor Stinner022be022019-05-22 23:58:50 +0200872 'utf8_mode': 1,
Victor Stinner425717f2019-05-20 16:38:48 +0200873 }
874 config = {
875 'use_hash_seed': 1,
876 'hash_seed': 42,
877 'tracemalloc': 2,
878 'import_time': 1,
879 'malloc_stats': 1,
880 'inspect': 1,
881 'optimization_level': 2,
Victor Stinner331a6a52019-05-27 16:39:22 +0200882 'pythonpath_env': '/my/path',
Victor Stinner425717f2019-05-20 16:38:48 +0200883 'pycache_prefix': 'env_pycache_prefix',
884 'write_bytecode': 0,
885 'verbose': 1,
886 'buffered_stdio': 0,
887 'stdio_encoding': 'iso8859-1',
888 'stdio_errors': 'replace',
889 'user_site_directory': 0,
890 'faulthandler': 1,
891 'warnoptions': ['EnvVar'],
Sandro Mani8f023a22020-06-08 17:28:11 +0200892 'platlibdir': 'env_platlibdir',
893 'module_search_paths': self.IGNORE_CONFIG,
Victor Stinner425717f2019-05-20 16:38:48 +0200894 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200895 self.check_all_configs("test_init_python_env", config, preconfig,
896 api=API_PYTHON)
Victor Stinnerb35be4b2019-03-05 17:37:44 +0100897
898 def test_init_env_dev_mode(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200899 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
900 config = dict(dev_mode=1,
901 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100902 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200903 self.check_all_configs("test_init_env_dev_mode", config, preconfig,
904 api=API_COMPAT)
Victor Stinner56b29b62018-07-26 18:57:56 +0200905
Victor Stinner20004952019-03-26 02:31:11 +0100906 def test_init_env_dev_mode_alloc(self):
Victor Stinner425717f2019-05-20 16:38:48 +0200907 preconfig = dict(allocator=PYMEM_ALLOCATOR_MALLOC)
908 config = dict(dev_mode=1,
909 faulthandler=1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100910 warnoptions=['default'])
Victor Stinner331a6a52019-05-27 16:39:22 +0200911 self.check_all_configs("test_init_env_dev_mode_alloc", config, preconfig,
912 api=API_COMPAT)
Victor Stinner25d13f32019-03-06 12:51:53 +0100913
Victor Stinner56b29b62018-07-26 18:57:56 +0200914 def test_init_dev_mode(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100915 preconfig = {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200916 'allocator': PYMEM_ALLOCATOR_DEBUG,
Victor Stinner56b29b62018-07-26 18:57:56 +0200917 }
Victor Stinner1075d162019-03-25 23:19:57 +0100918 config = {
919 'faulthandler': 1,
Victor Stinner20004952019-03-26 02:31:11 +0100920 'dev_mode': 1,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100921 'warnoptions': ['default'],
Victor Stinner1075d162019-03-25 23:19:57 +0100922 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200923 self.check_all_configs("test_init_dev_mode", config, preconfig,
924 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200925
926 def test_preinit_parse_argv(self):
927 # Pre-initialize implicitly using argv: make sure that -X dev
928 # is used to configure the allocation in preinitialization
929 preconfig = {
930 'allocator': PYMEM_ALLOCATOR_DEBUG,
931 }
932 config = {
Victor Stinnera1a99b42019-12-09 17:34:02 +0100933 'argv': ['script.py'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200934 'orig_argv': ['python3', '-X', 'dev', 'script.py'],
Victor Stinnera1a99b42019-12-09 17:34:02 +0100935 'run_filename': os.path.abspath('script.py'),
Victor Stinner6d1c4672019-05-20 11:02:00 +0200936 'dev_mode': 1,
937 'faulthandler': 1,
938 'warnoptions': ['default'],
939 'xoptions': ['dev'],
940 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200941 self.check_all_configs("test_preinit_parse_argv", config, preconfig,
942 api=API_PYTHON)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200943
944 def test_preinit_dont_parse_argv(self):
945 # -X dev must be ignored by isolated preconfiguration
946 preconfig = {
947 'isolated': 0,
948 }
Victor Stinnere81f6e62020-06-08 18:12:59 +0200949 argv = ["python3",
950 "-E", "-I",
951 "-X", "dev",
952 "-X", "utf8",
953 "script.py"]
Victor Stinner6d1c4672019-05-20 11:02:00 +0200954 config = {
Victor Stinnere81f6e62020-06-08 18:12:59 +0200955 'argv': argv,
Victor Stinnerdd8a93e2020-06-30 00:49:03 +0200956 'orig_argv': argv,
Victor Stinner6d1c4672019-05-20 11:02:00 +0200957 'isolated': 0,
958 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200959 self.check_all_configs("test_preinit_dont_parse_argv", config, preconfig,
960 api=API_ISOLATED)
Victor Stinner56b29b62018-07-26 18:57:56 +0200961
Victor Stinnercab5d072019-05-17 19:01:14 +0200962 def test_init_isolated_flag(self):
Victor Stinner1075d162019-03-25 23:19:57 +0100963 config = {
Victor Stinner20004952019-03-26 02:31:11 +0100964 'isolated': 1,
965 'use_environment': 0,
Victor Stinner56b29b62018-07-26 18:57:56 +0200966 'user_site_directory': 0,
967 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200968 self.check_all_configs("test_init_isolated_flag", config, api=API_PYTHON)
Victor Stinner56b29b62018-07-26 18:57:56 +0200969
Victor Stinner6da20a42019-03-27 00:26:18 +0100970 def test_preinit_isolated1(self):
971 # _PyPreConfig.isolated=1, _PyCoreConfig.isolated not set
Victor Stinner6da20a42019-03-27 00:26:18 +0100972 config = {
973 'isolated': 1,
974 'use_environment': 0,
975 'user_site_directory': 0,
976 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200977 self.check_all_configs("test_preinit_isolated1", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100978
979 def test_preinit_isolated2(self):
980 # _PyPreConfig.isolated=0, _PyCoreConfig.isolated=1
Victor Stinner6da20a42019-03-27 00:26:18 +0100981 config = {
982 'isolated': 1,
983 'use_environment': 0,
984 'user_site_directory': 0,
985 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200986 self.check_all_configs("test_preinit_isolated2", config, api=API_COMPAT)
Victor Stinner6da20a42019-03-27 00:26:18 +0100987
Victor Stinner6d1c4672019-05-20 11:02:00 +0200988 def test_preinit_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200989 self.check_all_configs("test_preinit_isolated_config", api=API_ISOLATED)
Victor Stinner6d1c4672019-05-20 11:02:00 +0200990
Victor Stinnercab5d072019-05-17 19:01:14 +0200991 def test_init_isolated_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200992 self.check_all_configs("test_init_isolated_config", api=API_ISOLATED)
Victor Stinner5edcf262019-05-23 00:57:57 +0200993
994 def test_preinit_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200995 self.check_all_configs("test_preinit_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200996
997 def test_init_python_config(self):
Victor Stinner331a6a52019-05-27 16:39:22 +0200998 self.check_all_configs("test_init_python_config", api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +0200999
Victor Stinnerbcfbbd72019-05-17 22:44:16 +02001000 def test_init_dont_configure_locale(self):
1001 # _PyPreConfig.configure_locale=0
1002 preconfig = {
1003 'configure_locale': 0,
Victor Stinner425717f2019-05-20 16:38:48 +02001004 'coerce_c_locale': 0,
Victor Stinnerbcfbbd72019-05-17 22:44:16 +02001005 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001006 self.check_all_configs("test_init_dont_configure_locale", {}, preconfig,
1007 api=API_PYTHON)
Victor Stinnerbcfbbd72019-05-17 22:44:16 +02001008
Victor Stinner91c99872019-05-14 22:01:51 +02001009 def test_init_read_set(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001010 config = {
Victor Stinner91c99872019-05-14 22:01:51 +02001011 'program_name': './init_read_set',
1012 'executable': 'my_executable',
1013 }
Victor Stinner3842f292019-08-23 16:57:54 +01001014 def modify_path(path):
1015 path.insert(1, "test_path_insert1")
1016 path.append("test_path_append")
Victor Stinner331a6a52019-05-27 16:39:22 +02001017 self.check_all_configs("test_init_read_set", config,
1018 api=API_PYTHON,
Victor Stinner3842f292019-08-23 16:57:54 +01001019 modify_path_cb=modify_path)
Victor Stinner91c99872019-05-14 22:01:51 +02001020
Victor Stinner120b7072019-08-23 18:03:08 +01001021 def test_init_sys_add(self):
1022 config = {
1023 'faulthandler': 1,
1024 'xoptions': [
1025 'config_xoption',
1026 'cmdline_xoption',
1027 'sysadd_xoption',
1028 'faulthandler',
1029 ],
1030 'warnoptions': [
Victor Stinner120b7072019-08-23 18:03:08 +01001031 'ignore:::cmdline_warnoption',
1032 'ignore:::sysadd_warnoption',
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001033 'ignore:::config_warnoption',
Victor Stinner120b7072019-08-23 18:03:08 +01001034 ],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001035 'orig_argv': ['python3',
1036 '-W', 'ignore:::cmdline_warnoption',
1037 '-X', 'cmdline_xoption'],
Victor Stinner120b7072019-08-23 18:03:08 +01001038 }
1039 self.check_all_configs("test_init_sys_add", config, api=API_PYTHON)
1040
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001041 def test_init_run_main(self):
Victor Stinner5eb8b072019-05-15 02:12:48 +02001042 code = ('import _testinternalcapi, json; '
1043 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +02001044 config = {
Victor Stinner5eb8b072019-05-15 02:12:48 +02001045 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001046 'orig_argv': ['python3', '-c', code, 'arg2'],
Victor Stinner5eb8b072019-05-15 02:12:48 +02001047 'program_name': './python3',
1048 'run_command': code + '\n',
Victor Stinnerdc42af82020-11-05 18:58:07 +01001049 'parse_argv': 2,
Victor Stinner5eb8b072019-05-15 02:12:48 +02001050 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001051 self.check_all_configs("test_init_run_main", config, api=API_PYTHON)
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001052
1053 def test_init_main(self):
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001054 code = ('import _testinternalcapi, json; '
1055 'print(json.dumps(_testinternalcapi.get_configs()))')
Victor Stinner331a6a52019-05-27 16:39:22 +02001056 config = {
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001057 'argv': ['-c', 'arg2'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001058 'orig_argv': ['python3',
1059 '-c', code,
1060 'arg2'],
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001061 'program_name': './python3',
1062 'run_command': code + '\n',
Victor Stinnerdc42af82020-11-05 18:58:07 +01001063 'parse_argv': 2,
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001064 '_init_main': 0,
1065 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001066 self.check_all_configs("test_init_main", config,
1067 api=API_PYTHON,
1068 stderr="Run Python code before _Py_InitializeMain")
Victor Stinner5eb8b072019-05-15 02:12:48 +02001069
Victor Stinnercab5d072019-05-17 19:01:14 +02001070 def test_init_parse_argv(self):
Victor Stinner331a6a52019-05-27 16:39:22 +02001071 config = {
Victor Stinnerdc42af82020-11-05 18:58:07 +01001072 'parse_argv': 2,
Victor Stinnercab5d072019-05-17 19:01:14 +02001073 'argv': ['-c', 'arg1', '-v', 'arg3'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001074 'orig_argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnercab5d072019-05-17 19:01:14 +02001075 'program_name': './argv0',
Victor Stinnercab5d072019-05-17 19:01:14 +02001076 'run_command': 'pass\n',
1077 'use_environment': 0,
1078 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001079 self.check_all_configs("test_init_parse_argv", config, api=API_PYTHON)
Victor Stinnercab5d072019-05-17 19:01:14 +02001080
Victor Stinnerae239f62019-05-16 17:02:56 +02001081 def test_init_dont_parse_argv(self):
Victor Stinner6d1c4672019-05-20 11:02:00 +02001082 pre_config = {
1083 'parse_argv': 0,
1084 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001085 config = {
Victor Stinnerbab0db62019-05-18 03:21:27 +02001086 'parse_argv': 0,
Victor Stinnercab5d072019-05-17 19:01:14 +02001087 'argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001088 'orig_argv': ['./argv0', '-E', '-c', 'pass', 'arg1', '-v', 'arg3'],
Victor Stinnercab5d072019-05-17 19:01:14 +02001089 'program_name': './argv0',
Victor Stinnerae239f62019-05-16 17:02:56 +02001090 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001091 self.check_all_configs("test_init_dont_parse_argv", config, pre_config,
1092 api=API_PYTHON)
Victor Stinnerae239f62019-05-16 17:02:56 +02001093
Victor Stinner8bf39b62019-09-26 02:22:35 +02001094 def default_program_name(self, config):
1095 if MS_WINDOWS:
1096 program_name = 'python'
1097 executable = self.test_exe
1098 else:
1099 program_name = 'python3'
Victor Stinner49d99f02019-09-26 04:01:49 +02001100 if MACOS:
1101 executable = self.test_exe
1102 else:
1103 executable = shutil.which(program_name) or ''
Victor Stinner8bf39b62019-09-26 02:22:35 +02001104 config.update({
1105 'program_name': program_name,
1106 'base_executable': executable,
1107 'executable': executable,
1108 })
1109
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001110 def test_init_setpath(self):
Victor Stinner8bf39b62019-09-26 02:22:35 +02001111 # Test Py_SetPath()
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001112 config = self._get_expected_config()
1113 paths = config['config']['module_search_paths']
1114
1115 config = {
1116 'module_search_paths': paths,
1117 'prefix': '',
1118 'base_prefix': '',
1119 'exec_prefix': '',
1120 'base_exec_prefix': '',
1121 }
Victor Stinner8bf39b62019-09-26 02:22:35 +02001122 self.default_program_name(config)
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001123 env = {'TESTPATH': os.path.pathsep.join(paths)}
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001124
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001125 self.check_all_configs("test_init_setpath", config,
1126 api=API_COMPAT, env=env,
1127 ignore_stderr=True)
1128
Victor Stinner8bf39b62019-09-26 02:22:35 +02001129 def test_init_setpath_config(self):
1130 # Test Py_SetPath() with PyConfig
1131 config = self._get_expected_config()
1132 paths = config['config']['module_search_paths']
1133
1134 config = {
1135 # set by Py_SetPath()
1136 'module_search_paths': paths,
1137 'prefix': '',
1138 'base_prefix': '',
1139 'exec_prefix': '',
1140 'base_exec_prefix': '',
1141 # overriden by PyConfig
1142 'program_name': 'conf_program_name',
1143 'base_executable': 'conf_executable',
1144 'executable': 'conf_executable',
1145 }
1146 env = {'TESTPATH': os.path.pathsep.join(paths)}
Victor Stinner8bf39b62019-09-26 02:22:35 +02001147 self.check_all_configs("test_init_setpath_config", config,
Victor Stinner49d99f02019-09-26 04:01:49 +02001148 api=API_PYTHON, env=env, ignore_stderr=True)
Victor Stinner8bf39b62019-09-26 02:22:35 +02001149
Victor Stinner52ad33a2019-09-25 02:10:35 +02001150 def module_search_paths(self, prefix=None, exec_prefix=None):
1151 config = self._get_expected_config()
1152 if prefix is None:
1153 prefix = config['config']['prefix']
1154 if exec_prefix is None:
1155 exec_prefix = config['config']['prefix']
1156 if MS_WINDOWS:
1157 return config['config']['module_search_paths']
1158 else:
1159 ver = sys.version_info
1160 return [
Victor Stinner8510f432020-03-10 09:53:09 +01001161 os.path.join(prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001162 f'python{ver.major}{ver.minor}.zip'),
Victor Stinner8510f432020-03-10 09:53:09 +01001163 os.path.join(prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001164 f'python{ver.major}.{ver.minor}'),
Victor Stinner8510f432020-03-10 09:53:09 +01001165 os.path.join(exec_prefix, sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001166 f'python{ver.major}.{ver.minor}', 'lib-dynload'),
1167 ]
1168
1169 @contextlib.contextmanager
1170 def tmpdir_with_python(self):
1171 # Temporary directory with a copy of the Python program
1172 with tempfile.TemporaryDirectory() as tmpdir:
Victor Stinner00508a72019-09-25 16:30:36 +02001173 # bpo-38234: On macOS and FreeBSD, the temporary directory
1174 # can be symbolic link. For example, /tmp can be a symbolic link
1175 # to /var/tmp. Call realpath() to resolve all symbolic links.
1176 tmpdir = os.path.realpath(tmpdir)
1177
Victor Stinner52ad33a2019-09-25 02:10:35 +02001178 if MS_WINDOWS:
1179 # Copy pythonXY.dll (or pythonXY_d.dll)
1180 ver = sys.version_info
1181 dll = f'python{ver.major}{ver.minor}'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001182 dll3 = f'python{ver.major}'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001183 if debug_build(sys.executable):
1184 dll += '_d'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001185 dll3 += '_d'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001186 dll += '.dll'
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001187 dll3 += '.dll'
Victor Stinner52ad33a2019-09-25 02:10:35 +02001188 dll = os.path.join(os.path.dirname(self.test_exe), dll)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001189 dll3 = os.path.join(os.path.dirname(self.test_exe), dll3)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001190 dll_copy = os.path.join(tmpdir, os.path.basename(dll))
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001191 dll3_copy = os.path.join(tmpdir, os.path.basename(dll3))
Victor Stinner52ad33a2019-09-25 02:10:35 +02001192 shutil.copyfile(dll, dll_copy)
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001193 shutil.copyfile(dll3, dll3_copy)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001194
1195 # Copy Python program
1196 exec_copy = os.path.join(tmpdir, os.path.basename(self.test_exe))
1197 shutil.copyfile(self.test_exe, exec_copy)
1198 shutil.copystat(self.test_exe, exec_copy)
1199 self.test_exe = exec_copy
1200
1201 yield tmpdir
1202
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001203 def test_init_setpythonhome(self):
Victor Stinner8bf39b62019-09-26 02:22:35 +02001204 # Test Py_SetPythonHome(home) with PYTHONPATH env var
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001205 config = self._get_expected_config()
1206 paths = config['config']['module_search_paths']
1207 paths_str = os.path.pathsep.join(paths)
1208
1209 for path in paths:
1210 if not os.path.isdir(path):
1211 continue
1212 if os.path.exists(os.path.join(path, 'os.py')):
1213 home = os.path.dirname(path)
1214 break
1215 else:
1216 self.fail(f"Unable to find home in {paths!r}")
1217
1218 prefix = exec_prefix = home
1219 ver = sys.version_info
Victor Stinner52ad33a2019-09-25 02:10:35 +02001220 expected_paths = self.module_search_paths(prefix=home, exec_prefix=home)
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001221
1222 config = {
1223 'home': home,
1224 'module_search_paths': expected_paths,
1225 'prefix': prefix,
1226 'base_prefix': prefix,
1227 'exec_prefix': exec_prefix,
1228 'base_exec_prefix': exec_prefix,
1229 'pythonpath_env': paths_str,
1230 }
Victor Stinner8bf39b62019-09-26 02:22:35 +02001231 self.default_program_name(config)
1232 env = {'TESTHOME': home, 'PYTHONPATH': paths_str}
Victor Stinnerbb6bf7d2019-09-24 18:21:02 +02001233 self.check_all_configs("test_init_setpythonhome", config,
1234 api=API_COMPAT, env=env)
1235
Victor Stinner52ad33a2019-09-25 02:10:35 +02001236 def copy_paths_by_env(self, config):
1237 all_configs = self._get_expected_config()
1238 paths = all_configs['config']['module_search_paths']
1239 paths_str = os.path.pathsep.join(paths)
1240 config['pythonpath_env'] = paths_str
1241 env = {'PYTHONPATH': paths_str}
1242 return env
1243
1244 @unittest.skipIf(MS_WINDOWS, 'Windows does not use pybuilddir.txt')
1245 def test_init_pybuilddir(self):
1246 # Test path configuration with pybuilddir.txt configuration file
1247
1248 with self.tmpdir_with_python() as tmpdir:
1249 # pybuilddir.txt is a sub-directory relative to the current
1250 # directory (tmpdir)
1251 subdir = 'libdir'
1252 libdir = os.path.join(tmpdir, subdir)
1253 os.mkdir(libdir)
1254
1255 filename = os.path.join(tmpdir, 'pybuilddir.txt')
1256 with open(filename, "w", encoding="utf8") as fp:
1257 fp.write(subdir)
1258
1259 module_search_paths = self.module_search_paths()
1260 module_search_paths[-1] = libdir
1261
1262 executable = self.test_exe
1263 config = {
1264 'base_executable': executable,
1265 'executable': executable,
1266 'module_search_paths': module_search_paths,
1267 }
1268 env = self.copy_paths_by_env(config)
1269 self.check_all_configs("test_init_compat_config", config,
1270 api=API_COMPAT, env=env,
1271 ignore_stderr=True, cwd=tmpdir)
1272
1273 def test_init_pyvenv_cfg(self):
1274 # Test path configuration with pyvenv.cfg configuration file
1275
1276 with self.tmpdir_with_python() as tmpdir, \
1277 tempfile.TemporaryDirectory() as pyvenv_home:
1278 ver = sys.version_info
1279
1280 if not MS_WINDOWS:
1281 lib_dynload = os.path.join(pyvenv_home,
Victor Stinner8510f432020-03-10 09:53:09 +01001282 sys.platlibdir,
Victor Stinner52ad33a2019-09-25 02:10:35 +02001283 f'python{ver.major}.{ver.minor}',
1284 'lib-dynload')
1285 os.makedirs(lib_dynload)
1286 else:
1287 lib_dynload = os.path.join(pyvenv_home, 'lib')
1288 os.makedirs(lib_dynload)
1289 # getpathp.c uses Lib\os.py as the LANDMARK
1290 shutil.copyfile(os.__file__, os.path.join(lib_dynload, 'os.py'))
1291
1292 filename = os.path.join(tmpdir, 'pyvenv.cfg')
1293 with open(filename, "w", encoding="utf8") as fp:
1294 print("home = %s" % pyvenv_home, file=fp)
1295 print("include-system-site-packages = false", file=fp)
1296
1297 paths = self.module_search_paths()
1298 if not MS_WINDOWS:
1299 paths[-1] = lib_dynload
1300 else:
1301 for index, path in enumerate(paths):
1302 if index == 0:
1303 paths[index] = os.path.join(tmpdir, os.path.basename(path))
1304 else:
1305 paths[index] = os.path.join(pyvenv_home, os.path.basename(path))
1306 paths[-1] = pyvenv_home
1307
1308 executable = self.test_exe
1309 exec_prefix = pyvenv_home
1310 config = {
1311 'base_exec_prefix': exec_prefix,
1312 'exec_prefix': exec_prefix,
1313 'base_executable': executable,
1314 'executable': executable,
1315 'module_search_paths': paths,
1316 }
Victor Stinner8f427482020-07-08 00:20:37 +02001317 path_config = {}
Victor Stinner52ad33a2019-09-25 02:10:35 +02001318 if MS_WINDOWS:
1319 config['base_prefix'] = pyvenv_home
1320 config['prefix'] = pyvenv_home
Steve Dowerdcbaa1b2020-07-06 17:32:00 +01001321
Victor Stinner8f427482020-07-08 00:20:37 +02001322 ver = sys.version_info
1323 dll = f'python{ver.major}'
1324 if debug_build(executable):
1325 dll += '_d'
1326 dll += '.DLL'
1327 dll = os.path.join(os.path.dirname(executable), dll)
1328 path_config['python3_dll'] = dll
1329
1330 env = self.copy_paths_by_env(config)
1331 self.check_all_configs("test_init_compat_config", config,
1332 expected_pathconfig=path_config,
1333 api=API_COMPAT, env=env,
1334 ignore_stderr=True, cwd=tmpdir)
Victor Stinner52ad33a2019-09-25 02:10:35 +02001335
Victor Stinner12f2f172019-09-26 15:51:50 +02001336 def test_global_pathconfig(self):
1337 # Test C API functions getting the path configuration:
1338 #
1339 # - Py_GetExecPrefix()
1340 # - Py_GetPath()
1341 # - Py_GetPrefix()
1342 # - Py_GetProgramFullPath()
1343 # - Py_GetProgramName()
1344 # - Py_GetPythonHome()
1345 #
1346 # The global path configuration (_Py_path_config) must be a copy
1347 # of the path configuration of PyInterpreter.config (PyConfig).
Hai Shibb0424b2020-08-04 00:47:42 +08001348 ctypes = import_helper.import_module('ctypes')
1349 _testinternalcapi = import_helper.import_module('_testinternalcapi')
Victor Stinner12f2f172019-09-26 15:51:50 +02001350
1351 def get_func(name):
1352 func = getattr(ctypes.pythonapi, name)
1353 func.argtypes = ()
1354 func.restype = ctypes.c_wchar_p
1355 return func
1356
1357 Py_GetPath = get_func('Py_GetPath')
1358 Py_GetPrefix = get_func('Py_GetPrefix')
1359 Py_GetExecPrefix = get_func('Py_GetExecPrefix')
1360 Py_GetProgramName = get_func('Py_GetProgramName')
1361 Py_GetProgramFullPath = get_func('Py_GetProgramFullPath')
1362 Py_GetPythonHome = get_func('Py_GetPythonHome')
1363
1364 config = _testinternalcapi.get_configs()['config']
1365
1366 self.assertEqual(Py_GetPath().split(os.path.pathsep),
1367 config['module_search_paths'])
1368 self.assertEqual(Py_GetPrefix(), config['prefix'])
1369 self.assertEqual(Py_GetExecPrefix(), config['exec_prefix'])
1370 self.assertEqual(Py_GetProgramName(), config['program_name'])
1371 self.assertEqual(Py_GetProgramFullPath(), config['executable'])
1372 self.assertEqual(Py_GetPythonHome(), config['home'])
1373
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001374 def test_init_warnoptions(self):
1375 # lowest to highest priority
1376 warnoptions = [
1377 'ignore:::PyConfig_Insert0', # PyWideStringList_Insert(0)
1378 'default', # PyConfig.dev_mode=1
1379 'ignore:::env1', # PYTHONWARNINGS env var
1380 'ignore:::env2', # PYTHONWARNINGS env var
1381 'ignore:::cmdline1', # -W opt command line option
1382 'ignore:::cmdline2', # -W opt command line option
1383 'default::BytesWarning', # PyConfig.bytes_warnings=1
1384 'ignore:::PySys_AddWarnOption1', # PySys_AddWarnOption()
1385 'ignore:::PySys_AddWarnOption2', # PySys_AddWarnOption()
1386 'ignore:::PyConfig_BeforeRead', # PyConfig.warnoptions
1387 'ignore:::PyConfig_AfterRead'] # PyWideStringList_Append()
1388 preconfig = dict(allocator=PYMEM_ALLOCATOR_DEBUG)
1389 config = {
1390 'dev_mode': 1,
1391 'faulthandler': 1,
1392 'bytes_warning': 1,
1393 'warnoptions': warnoptions,
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001394 'orig_argv': ['python3',
1395 '-Wignore:::cmdline1',
1396 '-Wignore:::cmdline2'],
Victor Stinnerfb4ae152019-09-30 01:40:17 +02001397 }
1398 self.check_all_configs("test_init_warnoptions", config, preconfig,
1399 api=API_PYTHON)
1400
Victor Stinner048a3562020-11-05 00:45:56 +01001401 def test_init_set_config(self):
1402 config = {
1403 '_init_main': 0,
1404 'bytes_warning': 2,
1405 'warnoptions': ['error::BytesWarning'],
1406 }
1407 self.check_all_configs("test_init_set_config", config,
1408 api=API_ISOLATED)
1409
Victor Stinnere81f6e62020-06-08 18:12:59 +02001410 def test_get_argc_argv(self):
1411 self.run_embedded_interpreter("test_get_argc_argv")
1412 # ignore output
1413
Victor Stinner56b29b62018-07-26 18:57:56 +02001414
Victor Stinnerf3cb8142020-11-05 18:12:33 +01001415class SetConfigTests(unittest.TestCase):
1416 def test_set_config(self):
1417 # bpo-42260: Test _PyInterpreterState_SetConfig()
1418 cmd = [sys.executable, '-I', '-m', 'test._test_embed_set_config']
1419 proc = subprocess.run(cmd,
1420 stdout=subprocess.PIPE,
1421 stderr=subprocess.PIPE)
1422 self.assertEqual(proc.returncode, 0,
1423 (proc.returncode, proc.stdout, proc.stderr))
1424
1425
Steve Dowerb82e17e2019-05-23 08:45:22 -07001426class AuditingTests(EmbeddingTestsMixin, unittest.TestCase):
1427 def test_open_code_hook(self):
1428 self.run_embedded_interpreter("test_open_code_hook")
1429
1430 def test_audit(self):
1431 self.run_embedded_interpreter("test_audit")
1432
1433 def test_audit_subinterpreter(self):
1434 self.run_embedded_interpreter("test_audit_subinterpreter")
1435
Steve Dowere226e832019-07-01 16:03:53 -07001436 def test_audit_run_command(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001437 self.run_embedded_interpreter("test_audit_run_command",
1438 timeout=support.SHORT_TIMEOUT,
1439 returncode=1)
Steve Dowere226e832019-07-01 16:03:53 -07001440
1441 def test_audit_run_file(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001442 self.run_embedded_interpreter("test_audit_run_file",
1443 timeout=support.SHORT_TIMEOUT,
1444 returncode=1)
Steve Dowere226e832019-07-01 16:03:53 -07001445
1446 def test_audit_run_interactivehook(self):
Hai Shibb0424b2020-08-04 00:47:42 +08001447 startup = os.path.join(self.oldcwd, os_helper.TESTFN) + ".py"
Steve Dowere226e832019-07-01 16:03:53 -07001448 with open(startup, "w", encoding="utf-8") as f:
1449 print("import sys", file=f)
1450 print("sys.__interactivehook__ = lambda: None", file=f)
1451 try:
1452 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
Victor Stinner7772b1a2019-12-11 22:17:04 +01001453 self.run_embedded_interpreter("test_audit_run_interactivehook",
1454 timeout=support.SHORT_TIMEOUT,
Steve Dowere226e832019-07-01 16:03:53 -07001455 returncode=10, env=env)
1456 finally:
1457 os.unlink(startup)
1458
1459 def test_audit_run_startup(self):
Hai Shibb0424b2020-08-04 00:47:42 +08001460 startup = os.path.join(self.oldcwd, os_helper.TESTFN) + ".py"
Steve Dowere226e832019-07-01 16:03:53 -07001461 with open(startup, "w", encoding="utf-8") as f:
1462 print("pass", file=f)
1463 try:
1464 env = {**remove_python_envvars(), "PYTHONSTARTUP": startup}
Victor Stinner7772b1a2019-12-11 22:17:04 +01001465 self.run_embedded_interpreter("test_audit_run_startup",
1466 timeout=support.SHORT_TIMEOUT,
Steve Dowere226e832019-07-01 16:03:53 -07001467 returncode=10, env=env)
1468 finally:
1469 os.unlink(startup)
1470
1471 def test_audit_run_stdin(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001472 self.run_embedded_interpreter("test_audit_run_stdin",
1473 timeout=support.SHORT_TIMEOUT,
1474 returncode=1)
Steve Dowerb82e17e2019-05-23 08:45:22 -07001475
Victor Stinner11d13e82021-01-12 11:26:26 +01001476class MiscTests(EmbeddingTestsMixin, unittest.TestCase):
1477 def test_unicode_id_init(self):
1478 # bpo-42882: Test that _PyUnicode_FromId() works
1479 # when Python is initialized multiples times.
1480 self.run_embedded_interpreter("test_unicode_id_init")
1481
Nick Coghlan39f0bb52017-11-28 08:11:51 +10001482if __name__ == "__main__":
1483 unittest.main()