Skip to content

Commit 35c28d5

Browse files
authored
[3.7] bpo-35233: Rewrite test_embed.InitConfigTests (GH-10524) (GH-10529)
* Add C functions: * _Py_GetGlobalVariablesAsDict() * _PyCoreConfig_AsDict() * _PyMainInterpreterConfig_AsDict() * Add new _testcapi methods: * get_global_config() * get_core_config() * get_main_config() * test.pythoninfo: get global, core and main configuration * _testembed now serializes global, core and main configurations using JSON to reuse _Py_GetGlobalVariablesAsDict(), _PyCoreConfig_AsDict() and _PyMainInterpreterConfig_AsDict(), rather than duplicating code. * test_embed.InitConfigTests now test much more configuration variables
1 parent 52fb9f1 commit 35c28d5

6 files changed

Lines changed: 498 additions & 129 deletions

File tree

‎Include/pylifecycle.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,11 +61,14 @@ PyAPI_FUNC(_PyInitError) _Py_InitializeFromConfig(
6161
PyAPI_FUNC(void) _Py_Initialize_ReadEnvVarsNoAlloc(void);
6262
#endif
6363

64+
PyAPI_FUNC(PyObject *) _Py_GetGlobalVariablesAsDict(void);
65+
6466
PyAPI_FUNC(_PyInitError) _PyCoreConfig_Read(_PyCoreConfig *);
6567
PyAPI_FUNC(void) _PyCoreConfig_Clear(_PyCoreConfig *);
6668
PyAPI_FUNC(int) _PyCoreConfig_Copy(
6769
_PyCoreConfig *config,
6870
const _PyCoreConfig *config2);
71+
PyAPI_FUNC(PyObject *) _PyCoreConfig_AsDict(const _PyCoreConfig *config);
6972
PyAPI_FUNC(void) _PyCoreConfig_SetGlobalConfig(
7073
const _PyCoreConfig *config);
7174

@@ -77,6 +80,8 @@ PyAPI_FUNC(void) _PyMainInterpreterConfig_Clear(_PyMainInterpreterConfig *);
7780
PyAPI_FUNC(int) _PyMainInterpreterConfig_Copy(
7881
_PyMainInterpreterConfig *config,
7982
const _PyMainInterpreterConfig *config2);
83+
PyAPI_FUNC(PyObject*) _PyMainInterpreterConfig_AsDict(
84+
const _PyMainInterpreterConfig *config);
8085

8186
PyAPI_FUNC(_PyInitError) _Py_InitializeMainInterpreter(
8287
PyInterpreterState *interp,

‎Lib/test/pythoninfo.py‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ def collect_platform(info_add):
142142
info_add('platform.python_implementation',
143143
platform.python_implementation())
144144
info_add('platform.platform',
145-
platform.platform(aliased=True, terse=True))
145+
platform.platform(aliased=True))
146146

147147

148148
def collect_locale(info_add):
@@ -525,6 +525,33 @@ def collect_cc(info_add):
525525
info_add('CC.version', text)
526526

527527

528+
def collect_gdbm(info_add):
529+
try:
530+
from _gdbm import _GDBM_VERSION
531+
except ImportError:
532+
return
533+
534+
info_add('gdbm.GDBM_VERSION', '.'.join(map(str, _GDBM_VERSION)))
535+
536+
537+
def collect_get_config(info_add):
538+
# Dump global configuration variables, _PyCoreConfig
539+
# and _PyMainInterpreterConfig
540+
try:
541+
from _testcapi import get_global_config, get_core_config, get_main_config
542+
except ImportError:
543+
return
544+
545+
for prefix, get_config_func in (
546+
('global_config', get_global_config),
547+
('core_config', get_core_config),
548+
('main_config', get_main_config),
549+
):
550+
config = get_config_func()
551+
for key in sorted(config):
552+
info_add('%s[%s]' % (prefix, key), repr(config[key]))
553+
554+
528555
def collect_info(info):
529556
error = False
530557
info_add = info.add
@@ -552,6 +579,8 @@ def collect_info(info):
552579
collect_testcapi,
553580
collect_resource,
554581
collect_cc,
582+
collect_gdbm,
583+
collect_get_config,
555584

556585
# Collecting from tests should be last as they have side effects.
557586
collect_test_socket,

‎Lib/test/test_embed.py‎

Lines changed: 148 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import unittest
44

55
from collections import namedtuple
6+
import json
67
import os
78
import re
89
import subprocess
@@ -251,12 +252,52 @@ def test_initialize_pymain(self):
251252

252253
class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
253254
maxDiff = 4096
254-
DEFAULT_CONFIG = {
255+
UTF8_MODE_ERRORS = ('surrogatepass' if sys.platform == 'win32'
256+
else 'surrogateescape')
257+
# FIXME: untested core configuration variables
258+
UNTESTED_CORE_CONFIG = (
259+
'base_exec_prefix',
260+
'base_prefix',
261+
'exec_prefix',
262+
'executable',
263+
'home',
264+
'module_search_path_env',
265+
'module_search_paths',
266+
'prefix',
267+
)
268+
# FIXME: untested main configuration variables
269+
UNTESTED_MAIN_CONFIG = (
270+
'install_signal_handlers',
271+
'module_search_path',
272+
)
273+
DEFAULT_GLOBAL_CONFIG = {
274+
'Py_BytesWarningFlag': 0,
275+
'Py_DebugFlag': 0,
276+
'Py_DontWriteBytecodeFlag': 0,
277+
'Py_FrozenFlag': 0,
278+
'Py_HasFileSystemDefaultEncoding': 0,
279+
'Py_HashRandomizationFlag': 1,
280+
'Py_InspectFlag': 0,
281+
'Py_InteractiveFlag': 0,
282+
'Py_IsolatedFlag': 0,
283+
'Py_NoSiteFlag': 0,
284+
'Py_NoUserSiteDirectory': 0,
285+
'Py_OptimizeFlag': 0,
286+
'Py_QuietFlag': 0,
287+
'Py_UnbufferedStdioFlag': 0,
288+
'Py_VerboseFlag': 0,
289+
}
290+
if os.name == 'nt':
291+
DEFAULT_GLOBAL_CONFIG['Py_HasFileSystemDefaultEncoding'] = 1
292+
DEFAULT_GLOBAL_CONFIG['Py_LegacyWindowsFSEncodingFlag'] = 0
293+
DEFAULT_GLOBAL_CONFIG['Py_LegacyWindowsStdioFlag'] = 0
294+
295+
DEFAULT_CORE_CONFIG = {
255296
'install_signal_handlers': 1,
256-
'Py_IgnoreEnvironmentFlag': 0,
297+
'ignore_environment': 0,
257298
'use_hash_seed': 0,
258299
'hash_seed': 0,
259-
'allocator': '(null)',
300+
'allocator': None,
260301
'dev_mode': 0,
261302
'faulthandler': 0,
262303
'tracemalloc': 0,
@@ -265,34 +306,42 @@ class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
265306
'show_alloc_count': 0,
266307
'dump_refs': 0,
267308
'malloc_stats': 0,
268-
'utf8_mode': 0,
269309

310+
'utf8_mode': 0,
270311
'coerce_c_locale': 0,
271312
'coerce_c_locale_warn': 0,
272313

273314
'program_name': './_testembed',
274-
'argc': 0,
275-
'argv': '[]',
276-
'program': '(null)',
315+
'argv': [],
316+
'program': None,
277317

278-
'Py_IsolatedFlag': 0,
279-
'Py_NoSiteFlag': 0,
280-
'Py_BytesWarningFlag': 0,
281-
'Py_InspectFlag': 0,
282-
'Py_InteractiveFlag': 0,
283-
'Py_OptimizeFlag': 0,
284-
'Py_DebugFlag': 0,
285-
'Py_DontWriteBytecodeFlag': 0,
286-
'Py_VerboseFlag': 0,
287-
'Py_QuietFlag': 0,
288-
'Py_NoUserSiteDirectory': 0,
289-
'Py_UnbufferedStdioFlag': 0,
318+
'xoptions': [],
319+
'warnoptions': [],
290320

291321
'_disable_importlib': 0,
292-
'Py_FrozenFlag': 0,
293322
}
294323

295-
def check_config(self, testname, expected):
324+
def get_filesystem_encoding(self, isolated, env):
325+
code = ('import codecs, locale, sys; '
326+
'print(sys.getfilesystemencoding(), '
327+
'sys.getfilesystemencodeerrors())')
328+
args = (sys.executable, '-c', code)
329+
env = dict(env)
330+
if not isolated:
331+
env['PYTHONCOERCECLOCALE'] = '0'
332+
env['PYTHONUTF8'] = '0'
333+
proc = subprocess.run(args, text=True, env=env,
334+
stdout=subprocess.PIPE,
335+
stderr=subprocess.PIPE)
336+
if proc.returncode:
337+
raise Exception(f"failed to get the locale encoding: "
338+
f"stdout={proc.stdout!r} stderr={proc.stderr!r}")
339+
out = proc.stdout.rstrip()
340+
return out.split()
341+
342+
def check_config(self, testname, expected, expected_global):
343+
expected = dict(self.DEFAULT_CORE_CONFIG, **expected)
344+
296345
env = dict(os.environ)
297346
for key in list(env):
298347
if key.startswith('PYTHON'):
@@ -301,42 +350,78 @@ def check_config(self, testname, expected):
301350
# on the current locale
302351
env['PYTHONCOERCECLOCALE'] = '0'
303352
env['PYTHONUTF8'] = '0'
353+
304354
out, err = self.run_embedded_interpreter(testname, env=env)
305355
# Ignore err
306356

307-
expected = dict(self.DEFAULT_CONFIG, **expected)
308-
for key, value in expected.items():
309-
expected[key] = str(value)
357+
config = json.loads(out)
358+
core_config = config['core_config']
359+
executable = core_config['executable']
360+
main_config = config['main_config']
361+
362+
for key in self.UNTESTED_MAIN_CONFIG:
363+
del main_config[key]
364+
365+
expected_main = {
366+
'argv': [],
367+
'prefix': sys.prefix,
368+
'executable': core_config['executable'],
369+
'base_prefix': sys.base_prefix,
370+
'base_exec_prefix': sys.base_exec_prefix,
371+
'warnoptions': core_config['warnoptions'],
372+
'xoptions': {},
373+
'exec_prefix': core_config['exec_prefix'],
374+
}
375+
self.assertEqual(main_config, expected_main)
310376

311-
config = {}
312-
for line in out.splitlines():
313-
key, value = line.split(' = ', 1)
314-
config[key] = value
315-
self.assertEqual(config, expected)
377+
expected_global = dict(self.DEFAULT_GLOBAL_CONFIG, **expected_global)
378+
379+
if 'Py_FileSystemDefaultEncoding' not in expected_global:
380+
isolated = expected_global['Py_IsolatedFlag']
381+
fs_encoding, fs_errors = self.get_filesystem_encoding(isolated, env)
382+
expected_global['Py_FileSystemDefaultEncodeErrors'] = fs_errors
383+
expected_global['Py_FileSystemDefaultEncoding'] = fs_encoding
384+
385+
for global_key, core_key in (
386+
('Py_UTF8Mode', 'utf8_mode'),
387+
('Py_IgnoreEnvironmentFlag', 'ignore_environment'),
388+
):
389+
expected_global[global_key] = core_config[core_key]
390+
391+
self.assertEqual(config['global_config'], expected_global)
392+
393+
for key in self.UNTESTED_CORE_CONFIG:
394+
core_config.pop(key, None)
395+
self.assertEqual(core_config, expected)
316396

317397
def test_init_default_config(self):
318-
self.check_config("init_default_config", {})
398+
self.check_config("init_default_config", {}, {})
319399

320400
def test_init_global_config(self):
321-
config = {
401+
core_config = {
322402
'program_name': './globalvar',
323-
'Py_NoSiteFlag': 1,
403+
'utf8_mode': 1,
404+
}
405+
global_config = {
324406
'Py_BytesWarningFlag': 1,
407+
'Py_DontWriteBytecodeFlag': 1,
408+
'Py_HasFileSystemDefaultEncoding': 1,
409+
'Py_FileSystemDefaultEncodeErrors': self.UTF8_MODE_ERRORS,
410+
'Py_FileSystemDefaultEncoding': 'utf-8',
325411
'Py_InspectFlag': 1,
326412
'Py_InteractiveFlag': 1,
413+
'Py_NoSiteFlag': 1,
414+
'Py_NoUserSiteDirectory': 1,
327415
'Py_OptimizeFlag': 2,
328-
'Py_DontWriteBytecodeFlag': 1,
329-
'Py_VerboseFlag': 1,
330416
'Py_QuietFlag': 1,
331-
'Py_UnbufferedStdioFlag': 1,
332-
'utf8_mode': 1,
333-
'Py_NoUserSiteDirectory': 1,
417+
'Py_VerboseFlag': 1,
334418
'Py_FrozenFlag': 1,
419+
'Py_UnbufferedStdioFlag': 1,
335420
}
336-
self.check_config("init_global_config", config)
421+
self.check_config("init_global_config", core_config, global_config)
337422

338423
def test_init_from_config(self):
339-
config = {
424+
core_config = {
340425
'install_signal_handlers': 0,
341426
'use_hash_seed': 1,
342427
'hash_seed': 123,
@@ -354,43 +439,54 @@ def test_init_from_config(self):
354439

355440
'faulthandler': 1,
356441
}
357-
self.check_config("init_from_config", config)
442+
global_config = {
443+
'Py_HasFileSystemDefaultEncoding': 1,
444+
'Py_NoUserSiteDirectory': 0,
445+
}
446+
self.check_config("init_from_config", core_config, global_config)
358447

359448
def test_init_env(self):
360-
config = {
449+
core_config = {
361450
'use_hash_seed': 1,
362451
'hash_seed': 42,
363452
'allocator': 'malloc_debug',
364453
'tracemalloc': 2,
365454
'import_time': 1,
366455
'malloc_stats': 1,
367456
'utf8_mode': 1,
457+
'faulthandler': 1,
458+
'dev_mode': 1,
459+
}
460+
global_config = {
461+
'Py_DontWriteBytecodeFlag': 1,
462+
'Py_HasFileSystemDefaultEncoding': 1,
368463
'Py_InspectFlag': 1,
464+
'Py_NoUserSiteDirectory': 1,
369465
'Py_OptimizeFlag': 2,
370-
'Py_DontWriteBytecodeFlag': 1,
371-
'Py_VerboseFlag': 1,
372466
'Py_UnbufferedStdioFlag': 1,
373-
'Py_NoUserSiteDirectory': 1,
374-
'faulthandler': 1,
375-
'dev_mode': 1,
467+
'Py_VerboseFlag': 1,
468+
'Py_FileSystemDefaultEncoding': 'utf-8',
469+
'Py_FileSystemDefaultEncodeErrors': self.UTF8_MODE_ERRORS,
376470
}
377-
self.check_config("init_env", config)
471+
self.check_config("init_env", core_config, global_config)
378472

379473
def test_init_dev_mode(self):
380-
config = {
474+
core_config = {
381475
'dev_mode': 1,
382476
'faulthandler': 1,
383477
'allocator': 'debug',
384478
}
385-
self.check_config("init_dev_mode", config)
479+
self.check_config("init_dev_mode", core_config, {})
386480

387481
def test_init_isolated(self):
388-
config = {
482+
core_config = {
483+
'ignore_environment': 1,
484+
}
485+
global_config = {
389486
'Py_IsolatedFlag': 1,
390-
'Py_IgnoreEnvironmentFlag': 1,
391487
'Py_NoUserSiteDirectory': 1,
392488
}
393-
self.check_config("init_isolated", config)
489+
self.check_config("init_isolated", core_config, global_config)
394490

395491

396492
if __name__ == "__main__":

0 commit comments

Comments
 (0)