Debian Codegraph @

Lib/test/test_sysconfig.py

raw ◀ ▶
1 Debian patch touch this file
1 import platform
2 import re
3 import unittest
4 import sys
5 import os
6 import subprocess
7 import shutil
8 import json
9 import textwrap
10 from copy import copy
11
12 from test import support
13 from test.support import (
14 captured_stdout,
15 is_android,
16 is_apple_mobile,
17 is_wasi,
18 PythonSymlink,
19 requires_subprocess,
20 )
21 from test.support.import_helper import import_module
22 from test.support.os_helper import (TESTFN, unlink, skip_unless_symlink,
23 change_cwd)
24 from test.support.venv import VirtualEnvironmentMixin
25
26 import sysconfig
27 from sysconfig import (get_paths, get_platform, get_config_vars,
28 get_path, get_path_names, _INSTALL_SCHEMES,
29 get_default_scheme, get_scheme_names, get_config_var,
30 _expand_vars, _get_preferred_schemes,
31 is_python_build, _PROJECT_BASE)
32 from sysconfig.__main__ import _main, _parse_makefile, _get_pybuilddir, _get_json_data_name
33 import _imp
34 import _osx_support
35 import _sysconfig
36
37
38 HAS_USER_BASE = sysconfig._HAS_USER_BASE
39
40
41 class TestSysConfig(unittest.TestCase, VirtualEnvironmentMixin):
42
43 def setUp(self):
44 super(TestSysConfig, self).setUp()
45 self.maxDiff = None
46 self.sys_path = sys.path[:]
47 # patching os.uname
48 if hasattr(os, 'uname'):
49 self.uname = os.uname
50 self._uname = os.uname()
51 else:
52 self.uname = None
53 self._set_uname(('',)*5)
54 os.uname = self._get_uname
55 # saving the environment
56 self.name = os.name
57 self.prefix = sys.prefix
58 self.exec_prefix = sys.exec_prefix
59 self.platform = sys.platform
60 self.version = sys.version
61 self._framework = sys._framework
62 self.sep = os.sep
63 self.join = os.path.join
64 self.isabs = os.path.isabs
65 self.splitdrive = os.path.splitdrive
66 self._config_vars = sysconfig._CONFIG_VARS, copy(sysconfig._CONFIG_VARS)
67 self._added_envvars = []
68 self._changed_envvars = []
69 for var in ('MACOSX_DEPLOYMENT_TARGET', 'PATH'):
70 if var in os.environ:
71 self._changed_envvars.append((var, os.environ[var]))
72 else:
73 self._added_envvars.append(var)
74
75 def tearDown(self):
76 sys.path[:] = self.sys_path
77 self._cleanup_testfn()
78 if self.uname is not None:
79 os.uname = self.uname
80 else:
81 del os.uname
82 os.name = self.name
83 sys.prefix = self.prefix
84 sys.exec_prefix = self.exec_prefix
85 sys.platform = self.platform
86 sys.version = self.version
87 sys._framework = self._framework
88 os.sep = self.sep
89 os.path.join = self.join
90 os.path.isabs = self.isabs
91 os.path.splitdrive = self.splitdrive
92 sysconfig._CONFIG_VARS = self._config_vars[0]
93 sysconfig._CONFIG_VARS.clear()
94 sysconfig._CONFIG_VARS.update(self._config_vars[1])
95 for var, value in self._changed_envvars:
96 os.environ[var] = value
97 for var in self._added_envvars:
98 os.environ.pop(var, None)
99
100 super(TestSysConfig, self).tearDown()
101
102 def _set_uname(self, uname):
103 self._uname = os.uname_result(uname)
104
105 def _get_uname(self):
106 return self._uname
107
108 def _cleanup_testfn(self):
109 path = TESTFN
110 if os.path.isfile(path):
111 os.remove(path)
112 elif os.path.isdir(path):
113 shutil.rmtree(path)
114
115 def test_get_path_names(self):
116 self.assertEqual(get_path_names(), sysconfig._SCHEME_KEYS)
117
118 def test_get_paths(self):
119 scheme = get_paths()
120 default_scheme = get_default_scheme()
121 wanted = _expand_vars(default_scheme, None)
122 wanted = sorted(wanted.items())
123 scheme = sorted(scheme.items())
124 self.assertEqual(scheme, wanted)
125
126 def test_get_path(self):
127 config_vars = get_config_vars()
128 if os.name == 'nt':
129 # On Windows, we replace the native platlibdir name with the
130 # default so that POSIX schemes resolve correctly
131 config_vars = config_vars | {'platlibdir': 'lib'}
132 for scheme in _INSTALL_SCHEMES:
133 for name in _INSTALL_SCHEMES[scheme]:
134 expected = _INSTALL_SCHEMES[scheme][name].format(**config_vars)
135 self.assertEqual(
136 os.path.normpath(get_path(name, scheme)),
137 os.path.normpath(expected),
138 )
139
140 def test_get_default_scheme(self):
141 self.assertIn(get_default_scheme(), _INSTALL_SCHEMES)
142
143 def test_get_preferred_schemes(self):
144 expected_schemes = {'prefix', 'home', 'user'}
145
146 # Windows.
147 os.name = 'nt'
148 schemes = _get_preferred_schemes()
149 self.assertIsInstance(schemes, dict)
150 self.assertEqual(set(schemes), expected_schemes)
151
152 # Mac and Linux, shared library build.
153 os.name = 'posix'
154 schemes = _get_preferred_schemes()
155 self.assertIsInstance(schemes, dict)
156 self.assertEqual(set(schemes), expected_schemes)
157
158 # Mac, framework build.
159 os.name = 'posix'
160 sys.platform = 'darwin'
161 sys._framework = "MyPython"
162 self.assertIsInstance(schemes, dict)
163 self.assertEqual(set(schemes), expected_schemes)
164
165 def test_posix_venv_scheme(self):
166 # The following directories were hardcoded in the venv module
167 # before bpo-45413, here we assert the posix_venv scheme does not regress
168 binpath = 'bin'
169 incpath = 'include'
170 libpath = os.path.join('lib',
171 f'python{sysconfig._get_python_version_abi()}',
172 'site-packages')
173
174 # Resolve the paths in an imaginary venv/ directory
175 binpath = os.path.join('venv', binpath)
176 incpath = os.path.join('venv', incpath)
177 libpath = os.path.join('venv', libpath)
178
179 # Mimic the venv module, set all bases to the venv directory
180 bases = ('base', 'platbase', 'installed_base', 'installed_platbase')
181 vars = {base: 'venv' for base in bases}
182
183 self.assertEqual(binpath, sysconfig.get_path('scripts', scheme='posix_venv', vars=vars))
184 self.assertEqual(libpath, sysconfig.get_path('purelib', scheme='posix_venv', vars=vars))
185
186 # The include directory on POSIX isn't exactly the same as before,
187 # but it is "within"
188 sysconfig_includedir = sysconfig.get_path('include', scheme='posix_venv', vars=vars)
189 self.assertStartsWith(sysconfig_includedir, incpath + os.sep)
190
191 def test_nt_venv_scheme(self):
192 # The following directories were hardcoded in the venv module
193 # before bpo-45413, here we assert the posix_venv scheme does not regress
194 binpath = 'Scripts'
195 incpath = 'Include'
196 libpath = os.path.join('Lib', 'site-packages')
197
198 # Resolve the paths in an imaginary venv\ directory
199 venv = 'venv'
200 binpath = os.path.join(venv, binpath)
201 incpath = os.path.join(venv, incpath)
202 libpath = os.path.join(venv, libpath)
203
204 # Mimic the venv module, set all bases to the venv directory
205 bases = ('base', 'platbase', 'installed_base', 'installed_platbase')
206 vars = {base: 'venv' for base in bases}
207
208 self.assertEqual(binpath, sysconfig.get_path('scripts', scheme='nt_venv', vars=vars))
209 self.assertEqual(incpath, sysconfig.get_path('include', scheme='nt_venv', vars=vars))
210 self.assertEqual(libpath, sysconfig.get_path('purelib', scheme='nt_venv', vars=vars))
211
212 def test_venv_scheme(self):
213 if sys.platform == 'win32':
214 self.assertEqual(
215 sysconfig.get_path('scripts', scheme='venv'),
216 sysconfig.get_path('scripts', scheme='nt_venv')
217 )
218 self.assertEqual(
219 sysconfig.get_path('include', scheme='venv'),
220 sysconfig.get_path('include', scheme='nt_venv')
221 )
222 self.assertEqual(
223 sysconfig.get_path('purelib', scheme='venv'),
224 sysconfig.get_path('purelib', scheme='nt_venv')
225 )
226 else:
227 self.assertEqual(
228 sysconfig.get_path('scripts', scheme='venv'),
229 sysconfig.get_path('scripts', scheme='posix_venv')
230 )
231 self.assertEqual(
232 sysconfig.get_path('include', scheme='venv'),
233 sysconfig.get_path('include', scheme='posix_venv')
234 )
235 self.assertEqual(
236 sysconfig.get_path('purelib', scheme='venv'),
237 sysconfig.get_path('purelib', scheme='posix_venv')
238 )
239
240 def test_get_config_vars(self):
241 cvars = get_config_vars()
242 self.assertIsInstance(cvars, dict)
243 self.assertTrue(cvars)
244
245 def test_get_platform(self):
246 # Check the actual platform returns something reasonable.
247 actual_platform = get_platform()
248 self.assertIsInstance(actual_platform, str)
249 self.assertTrue(actual_platform)
250
251 # windows XP, 32bits
252 os.name = 'nt'
253 sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
254 '[MSC v.1310 32 bit (Intel)]')
255 sys.platform = 'win32'
256 self.assertEqual(get_platform(), 'win32')
257
258 # windows XP, amd64
259 os.name = 'nt'
260 sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
261 '[MSC v.1310 32 bit (Amd64)]')
262 sys.platform = 'win32'
263 self.assertEqual(get_platform(), 'win-amd64')
264
265 # macbook
266 os.name = 'posix'
267 sys.version = ('2.5 (r25:51918, Sep 19 2006, 08:49:13) '
268 '\n[GCC 4.0.1 (Apple Computer, Inc. build 5341)]')
269 sys.platform = 'darwin'
270 self._set_uname(('Darwin', 'macziade', '8.11.1',
271 ('Darwin Kernel Version 8.11.1: '
272 'Wed Oct 10 18:23:28 PDT 2007; '
273 'root:xnu-792.25.20~1/RELEASE_I386'), 'PowerPC'))
274 _osx_support._remove_original_values(get_config_vars())
275 get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
276
277 get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
278 '-fwrapv -O3 -Wall -Wstrict-prototypes')
279
280 maxint = sys.maxsize
281 try:
282 sys.maxsize = 2147483647
283 self.assertEqual(get_platform(), 'macosx-10.3-ppc')
284 sys.maxsize = 9223372036854775807
285 self.assertEqual(get_platform(), 'macosx-10.3-ppc64')
286 finally:
287 sys.maxsize = maxint
288
289 self._set_uname(('Darwin', 'macziade', '8.11.1',
290 ('Darwin Kernel Version 8.11.1: '
291 'Wed Oct 10 18:23:28 PDT 2007; '
292 'root:xnu-792.25.20~1/RELEASE_I386'), 'i386'))
293 _osx_support._remove_original_values(get_config_vars())
294 get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
295
296 get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
297 '-fwrapv -O3 -Wall -Wstrict-prototypes')
298 maxint = sys.maxsize
299 try:
300 sys.maxsize = 2147483647
301 self.assertEqual(get_platform(), 'macosx-10.3-i386')
302 sys.maxsize = 9223372036854775807
303 self.assertEqual(get_platform(), 'macosx-10.3-x86_64')
304 finally:
305 sys.maxsize = maxint
306
307 # macbook with fat binaries (fat, universal or fat64)
308 _osx_support._remove_original_values(get_config_vars())
309 get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.4'
310 get_config_vars()['CFLAGS'] = ('-arch ppc -arch i386 -isysroot '
311 '/Developer/SDKs/MacOSX10.4u.sdk '
312 '-fno-strict-aliasing -fno-common '
313 '-dynamic -DNDEBUG -g -O3')
314
315 self.assertEqual(get_platform(), 'macosx-10.4-fat')
316
317 _osx_support._remove_original_values(get_config_vars())
318 get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot '
319 '/Developer/SDKs/MacOSX10.4u.sdk '
320 '-fno-strict-aliasing -fno-common '
321 '-dynamic -DNDEBUG -g -O3')
322
323 self.assertEqual(get_platform(), 'macosx-10.4-intel')
324
325 _osx_support._remove_original_values(get_config_vars())
326 get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot '
327 '/Developer/SDKs/MacOSX10.4u.sdk '
328 '-fno-strict-aliasing -fno-common '
329 '-dynamic -DNDEBUG -g -O3')
330 self.assertEqual(get_platform(), 'macosx-10.4-fat3')
331
332 _osx_support._remove_original_values(get_config_vars())
333 get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot '
334 '/Developer/SDKs/MacOSX10.4u.sdk '
335 '-fno-strict-aliasing -fno-common '
336 '-dynamic -DNDEBUG -g -O3')
337 self.assertEqual(get_platform(), 'macosx-10.4-universal')
338
339 _osx_support._remove_original_values(get_config_vars())
340 get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot '
341 '/Developer/SDKs/MacOSX10.4u.sdk '
342 '-fno-strict-aliasing -fno-common '
343 '-dynamic -DNDEBUG -g -O3')
344
345 self.assertEqual(get_platform(), 'macosx-10.4-fat64')
346
347 for arch in ('ppc', 'i386', 'x86_64', 'ppc64'):
348 _osx_support._remove_original_values(get_config_vars())
349 get_config_vars()['CFLAGS'] = ('-arch %s -isysroot '
350 '/Developer/SDKs/MacOSX10.4u.sdk '
351 '-fno-strict-aliasing -fno-common '
352 '-dynamic -DNDEBUG -g -O3' % arch)
353
354 self.assertEqual(get_platform(), 'macosx-10.4-%s' % arch)
355
356 for macver in range(11, 16):
357 _osx_support._remove_original_values(get_config_vars())
358 get_config_vars()['CFLAGS'] = ('-fno-strict-overflow -Wsign-compare -Wunreachable-code'
359 '-arch arm64 -fno-common -dynamic -DNDEBUG -g -O3 -Wall')
360 get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = f"{macver}.0"
361 self.assertEqual(get_platform(), 'macosx-%d.0-arm64' % macver)
362
363 # linux debian sarge
364 os.name = 'posix'
365 sys.version = ('2.3.5 (#1, Jul 4 2007, 17:28:59) '
366 '\n[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)]')
367 sys.platform = 'linux2'
368 self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7',
369 '#1 Mon Apr 30 17:25:38 CEST 2007', 'i686'))
370
371 self.assertEqual(get_platform(), 'linux-i686')
372
373 # Android
374 os.name = 'posix'
375 sys.platform = 'android'
376 get_config_vars()['ANDROID_API_LEVEL'] = 9
377 for machine, abi in {
378 'aarch64': 'arm64_v8a',
379 'arm': 'armeabi_v7a',
380 'armv7l': 'armeabi_v7a',
381 'armv8l': 'armeabi_v7a',
382 'i686': 'x86',
383 'x86_64': 'x86_64',
384 }.items():
385 with self.subTest(machine):
386 self._set_uname(('Linux', 'localhost', '3.18.91+',
387 '#1 Tue Jan 9 20:35:43 UTC 2018', machine))
388 self.assertEqual(get_platform(), f'android-9-{abi}')
389
390 # XXX more platforms to tests here
391
392 @unittest.skipIf(is_wasi, "Incompatible with WASI mapdir and OOT builds")
393 @unittest.skipIf(is_apple_mobile,
394 f"{sys.platform} doesn't distribute header files in the runtime environment")
395 def test_get_config_h_filename(self):
396 config_h = sysconfig.get_config_h_filename()
397 self.assertTrue(os.path.isfile(config_h), config_h)
398
399 def test_get_scheme_names(self):
•400 wanted = ['deb_system', 'posix_local', 'nt', 'posix_home', 'posix_prefix', 'posix_venv', 'nt_venv', 'venv']
401 if HAS_USER_BASE:
402 wanted.extend(['nt_user', 'osx_framework_user', 'posix_user'])
403 self.assertEqual(get_scheme_names(), tuple(sorted(wanted)))
404
405 @skip_unless_symlink
406 @requires_subprocess()
407 def test_symlink(self): # Issue 7880
408 with PythonSymlink() as py:
409 cmd = "-c", "import sysconfig; print(sysconfig.get_platform())"
410 self.assertEqual(py.call_real(*cmd), py.call_link(*cmd))
411
412 def test_user_similar(self):
413 # Issue #8759: make sure the posix scheme for the users
414 # is similar to the global posix_prefix one
415 base = get_config_var('base')
416 if HAS_USER_BASE:
417 user = get_config_var('userbase')
418 # the global scheme mirrors the distinction between prefix and
419 # exec-prefix but not the user scheme, so we have to adapt the paths
420 # before comparing (issue #9100)
421 adapt = sys.base_prefix != sys.base_exec_prefix
422 for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'):
423 global_path = get_path(name, 'posix_prefix')
424 if adapt:
425 global_path = global_path.replace(sys.exec_prefix, sys.base_prefix)
426 base = base.replace(sys.exec_prefix, sys.base_prefix)
427 elif sys.base_prefix != sys.prefix:
428 # virtual environment? Likewise, we have to adapt the paths
429 # before comparing
430 global_path = global_path.replace(sys.base_prefix, sys.prefix)
431 base = base.replace(sys.base_prefix, sys.prefix)
432 if HAS_USER_BASE:
433 user_path = get_path(name, 'posix_user')
434 expected = os.path.normpath(global_path.replace(base, user, 1))
435 # bpo-44860: platlib of posix_user doesn't use sys.platlibdir,
436 # whereas posix_prefix does.
437 if name == 'platlib':
438 # Replace "/lib64/python3.11/site-packages" suffix
439 # with "/lib/python3.11/site-packages".
440 py_version_abi = sysconfig._get_python_version_abi()
441 suffix = f'python{py_version_abi}/site-packages'
442 expected = expected.replace(f'/{sys.platlibdir}/{suffix}',
443 f'/lib/{suffix}')
444 self.assertEqual(user_path, expected)
445
446 def test_main(self):
447 # just making sure _main() runs and returns things in the stdout
448 with captured_stdout() as output:
449 _main()
450 self.assertTrue(len(output.getvalue().split('\n')) > 0)
451
452 @unittest.skipIf(sys.platform == "win32", "Does not apply to Windows")
453 def test_ldshared_value(self):
454 ldflags = sysconfig.get_config_var('LDFLAGS')
455 ldshared = sysconfig.get_config_var('LDSHARED')
456
457 self.assertIn(ldflags, ldshared)
458
459 @unittest.skipIf(not _imp.extension_suffixes(), "stub loader has no suffixes")
460 def test_soabi(self):
461 soabi = sysconfig.get_config_var('SOABI')
462 self.assertIn(soabi, _imp.extension_suffixes()[0])
463
464 def test_library(self):
465 library = sysconfig.get_config_var('LIBRARY')
466 ldlibrary = sysconfig.get_config_var('LDLIBRARY')
467 major, minor = sys.version_info[:2]
468 abiflags = sysconfig.get_config_var('ABIFLAGS')
469 if sys.platform.startswith('win'):
470 self.assertEqual(library, f'python{major}{minor}{abiflags}.dll')
471 self.assertEqual(library, ldlibrary)
472 elif is_apple_mobile:
473 framework = sysconfig.get_config_var('PYTHONFRAMEWORK')
474 self.assertEqual(ldlibrary, f"{framework}.framework/{framework}")
475 else:
476 self.assertStartsWith(library, f'libpython{major}.{minor}')
477 self.assertEndsWith(library, '.a')
478 if sys.platform == 'darwin' and sys._framework:
479 self.skipTest('gh-110824: skip LDLIBRARY test for framework build')
480 else:
481 self.assertStartsWith(ldlibrary, f'libpython{major}.{minor}')
482
483 @unittest.skipUnless(sys.platform == "darwin", "test only relevant on MacOSX")
484 @requires_subprocess()
485 def test_platform_in_subprocess(self):
486 my_platform = sysconfig.get_platform()
487
488 # Test without MACOSX_DEPLOYMENT_TARGET in the environment
489
490 env = os.environ.copy()
491 if 'MACOSX_DEPLOYMENT_TARGET' in env:
492 del env['MACOSX_DEPLOYMENT_TARGET']
493
494 p = subprocess.Popen([
495 sys.executable, '-c',
496 'import sysconfig; print(sysconfig.get_platform())',
497 ],
498 stdout=subprocess.PIPE,
499 stderr=subprocess.DEVNULL,
500 env=env)
501 test_platform = p.communicate()[0].strip()
502 test_platform = test_platform.decode('utf-8')
503 status = p.wait()
504
505 self.assertEqual(status, 0)
506 self.assertEqual(my_platform, test_platform)
507
508 # Test with MACOSX_DEPLOYMENT_TARGET in the environment, and
509 # using a value that is unlikely to be the default one.
510 env = os.environ.copy()
511 env['MACOSX_DEPLOYMENT_TARGET'] = '10.1'
512
513 p = subprocess.Popen([
514 sys.executable, '-c',
515 'import sysconfig; print(sysconfig.get_platform())',
516 ],
517 stdout=subprocess.PIPE,
518 stderr=subprocess.DEVNULL,
519 env=env)
520 test_platform = p.communicate()[0].strip()
521 test_platform = test_platform.decode('utf-8')
522 status = p.wait()
523
524 self.assertEqual(status, 0)
525 self.assertEqual(my_platform, test_platform)
526
527 @unittest.skipIf(is_wasi, "Incompatible with WASI mapdir and OOT builds")
528 @unittest.skipIf(is_apple_mobile,
529 f"{sys.platform} doesn't include config folder at runtime")
530 def test_srcdir(self):
531 # See Issues #15322, #15364.
532 srcdir = sysconfig.get_config_var('srcdir')
533
534 self.assertTrue(os.path.isabs(srcdir), srcdir)
535 self.assertTrue(os.path.isdir(srcdir), srcdir)
536
537 if sysconfig._PYTHON_BUILD:
538 # The python executable has not been installed so srcdir
539 # should be a full source checkout.
540 Python_h = os.path.join(srcdir, 'Include', 'Python.h')
541 self.assertTrue(os.path.exists(Python_h), Python_h)
542 # <srcdir>/PC/pyconfig.h.in always exists even if unused
543 pyconfig_h_in = os.path.join(srcdir, 'pyconfig.h.in')
544 self.assertTrue(os.path.exists(pyconfig_h_in), pyconfig_h_in)
545 if os.name == 'nt':
546 pyconfig_h = os.path.join(srcdir, 'PC', 'pyconfig.h')
547 self.assertTrue(os.path.exists(pyconfig_h), pyconfig_h)
548 elif os.name == 'posix':
549 makefile_dir = os.path.dirname(sysconfig.get_makefile_filename())
550 # Issue #19340: srcdir has been realpath'ed already
551 makefile_dir = os.path.realpath(makefile_dir)
552 self.assertEqual(makefile_dir, srcdir)
553
554 def test_srcdir_independent_of_cwd(self):
555 # srcdir should be independent of the current working directory
556 # See Issues #15322, #15364.
557 srcdir = sysconfig.get_config_var('srcdir')
558 with change_cwd(os.pardir):
559 srcdir2 = sysconfig.get_config_var('srcdir')
560 self.assertEqual(srcdir, srcdir2)
561
562 @unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
563 'EXT_SUFFIX required for this test')
564 @unittest.skipIf(not _imp.extension_suffixes(), "stub loader has no suffixes")
565 def test_EXT_SUFFIX_in_vars(self):
566 vars = sysconfig.get_config_vars()
567 self.assertEqual(vars['EXT_SUFFIX'], _imp.extension_suffixes()[0])
568
569 @unittest.skipUnless(sys.platform == 'linux', 'Linux-specific test')
570 def test_linux_ext_suffix(self):
571 ctypes = import_module('ctypes')
572 machine = platform.machine()
573 suffix = sysconfig.get_config_var('EXT_SUFFIX')
574 if re.match('(aarch64|arm|mips|ppc|powerpc|s390|sparc)', machine):
575 self.assertTrue('linux' in suffix, suffix)
576 if re.match('(i[3-6]86|x86_64)$', machine):
577 if ctypes.sizeof(ctypes.c_char_p()) == 4:
578 expected_suffixes = 'i386-linux-gnu.so', 'x86_64-linux-gnux32.so', 'i386-linux-musl.so'
579 else: # 8 byte pointer size
580 expected_suffixes = 'x86_64-linux-gnu.so', 'x86_64-linux-musl.so'
581 self.assertEndsWith(suffix, expected_suffixes)
582
583 @unittest.skipUnless(sys.platform == 'android', 'Android-specific test')
584 def test_android_ext_suffix(self):
585 machine = platform.machine()
586 suffix = sysconfig.get_config_var('EXT_SUFFIX')
587 expected_triplet = {
588 "aarch64": "aarch64-linux-android",
589 "arm": "arm-linux-androideabi",
590 "armv7l": "arm-linux-androideabi",
591 "armv8l": "arm-linux-androideabi",
592 "i686": "i686-linux-android",
593 "x86_64": "x86_64-linux-android",
594 }[machine]
595 self.assertEndsWith(suffix, f"-{expected_triplet}.so")
596
597 @unittest.skipUnless(sys.platform == 'darwin', 'OS X-specific test')
598 def test_osx_ext_suffix(self):
599 suffix = sysconfig.get_config_var('EXT_SUFFIX')
600 self.assertEndsWith(suffix, '-darwin.so')
601
602 def test_always_set_py_debug(self):
603 self.assertIn('Py_DEBUG', sysconfig.get_config_vars())
604 Py_DEBUG = sysconfig.get_config_var('Py_DEBUG')
605 self.assertIn(Py_DEBUG, (0, 1))
606 self.assertEqual(Py_DEBUG, support.Py_DEBUG)
607
608 def test_always_set_py_gil_disabled(self):
609 self.assertIn('Py_GIL_DISABLED', sysconfig.get_config_vars())
610 Py_GIL_DISABLED = sysconfig.get_config_var('Py_GIL_DISABLED')
611 self.assertIn(Py_GIL_DISABLED, (0, 1))
612 self.assertEqual(Py_GIL_DISABLED, support.Py_GIL_DISABLED)
613
614 def test_abiflags(self):
615 # If this test fails on some platforms, maintainers should update the
616 # test to make it pass, rather than changing the definition of ABIFLAGS.
617 self.assertIn('abiflags', sysconfig.get_config_vars())
618 self.assertIn('ABIFLAGS', sysconfig.get_config_vars())
619 abiflags = sysconfig.get_config_var('abiflags')
620 ABIFLAGS = sysconfig.get_config_var('ABIFLAGS')
621 self.assertIsInstance(abiflags, str)
622 self.assertIsInstance(ABIFLAGS, str)
623 self.assertIn(abiflags, ABIFLAGS)
624 if os.name == 'nt':
625 self.assertEqual(abiflags, '')
626
627 if not sys.platform.startswith('win'):
628 valid_abiflags = ('', 't', 'd', 'td')
629 else:
630 # Windows uses '_d' rather than 'd'; see also test_abi_debug below
631 valid_abiflags = ('', 't', '_d', 't_d')
632
633 self.assertIn(ABIFLAGS, valid_abiflags)
634
635 def test_abi_debug(self):
636 ABIFLAGS = sysconfig.get_config_var('ABIFLAGS')
637 if support.Py_DEBUG:
638 self.assertIn('d', ABIFLAGS)
639 else:
640 self.assertNotIn('d', ABIFLAGS)
641
642 # The 'd' flag should always be the last one on Windows.
643 # On Windows, the debug flag is used differently with a underscore prefix.
644 # For example, `python{X}.{Y}td` on Unix and `python{X}.{Y}t_d.exe` on Windows.
645 if support.Py_DEBUG and sys.platform.startswith('win'):
646 self.assertEndsWith(ABIFLAGS, '_d')
647
648 def test_abi_thread(self):
649 abi_thread = sysconfig.get_config_var('abi_thread')
650 ABIFLAGS = sysconfig.get_config_var('ABIFLAGS')
651 self.assertIsInstance(abi_thread, str)
652 if support.Py_GIL_DISABLED:
653 self.assertEqual(abi_thread, 't')
654 self.assertIn('t', ABIFLAGS)
655 else:
656 self.assertEqual(abi_thread, '')
657 self.assertNotIn('t', ABIFLAGS)
658
659 @requires_subprocess()
660 def test_makefile_overwrites_config_vars(self):
661 script = textwrap.dedent("""
662 import sys, sysconfig
663
664 data = {
665 'prefix': sys.prefix,
666 'exec_prefix': sys.exec_prefix,
667 'base_prefix': sys.base_prefix,
668 'base_exec_prefix': sys.base_exec_prefix,
669 'config_vars': sysconfig.get_config_vars(),
670 }
671
672 import json
673 print(json.dumps(data, indent=2))
674 """)
675
676 # We need to run the test inside a virtual environment so that
677 # sys.prefix/sys.exec_prefix have a different value from the
678 # prefix/exec_prefix Makefile variables.
679 with self.venv() as venv:
680 data = json.loads(venv.run('-c', script).stdout)
681
682 # We expect sysconfig.get_config_vars to correctly reflect sys.prefix/sys.exec_prefix
683 self.assertEqual(data['prefix'], data['config_vars']['prefix'])
684 self.assertEqual(data['exec_prefix'], data['config_vars']['exec_prefix'])
685 # As a sanity check, just make sure sys.prefix/sys.exec_prefix really
686 # are different from the Makefile values.
687 # sys.base_prefix/sys.base_exec_prefix should reflect the value of the
688 # prefix/exec_prefix Makefile variables, so we use them in the comparison.
689 self.assertNotEqual(data['prefix'], data['base_prefix'])
690 self.assertNotEqual(data['exec_prefix'], data['base_exec_prefix'])
691
692 @unittest.skipIf(os.name != 'posix', '_sysconfig-vars JSON file is only available on POSIX')
693 @unittest.skipIf(is_wasi, "_sysconfig-vars JSON file currently isn't available on WASI")
694 @unittest.skipIf(is_android or is_apple_mobile, 'Android and iOS change the prefix')
695 def test_sysconfigdata_json(self):
696 if '_PYTHON_SYSCONFIGDATA_PATH' in os.environ:
697 data_dir = os.environ['_PYTHON_SYSCONFIGDATA_PATH']
698 elif is_python_build():
699 data_dir = os.path.join(_PROJECT_BASE, _get_pybuilddir())
700 else:
701 data_dir = sys._stdlib_dir
702
703 json_data_path = os.path.join(data_dir, _get_json_data_name())
704
705 with open(json_data_path) as f:
706 json_config_vars = json.load(f)
707
708 system_config_vars = get_config_vars()
709
710 # Keys dependent on uncontrollable external context
711 ignore_keys = {'userbase'}
712 # Keys dependent on Python being run outside the build directrory
713 if sysconfig.is_python_build():
714 ignore_keys |= {'srcdir'}
715 # Keys dependent on the executable location
716 if os.path.dirname(sys.executable) != system_config_vars['BINDIR']:
717 ignore_keys |= {'projectbase'}
718 # Keys dependent on the environment (different inside virtual environments)
719 if sys.prefix != sys.base_prefix:
720 ignore_keys |= {'prefix', 'exec_prefix', 'base', 'platbase'}
721 # Keys dependent on Python being run from the prefix targetted when building (different on relocatable installs)
722 if sysconfig._installation_is_relocated():
723 ignore_keys |= {'prefix', 'exec_prefix', 'base', 'platbase', 'installed_base', 'installed_platbase', 'srcdir'}
724
725 for key in ignore_keys:
726 json_config_vars.pop(key, None)
727 system_config_vars.pop(key, None)
728
729 self.assertEqual(system_config_vars, json_config_vars)
730
731 def test_sysconfig_config_vars_no_prefix_cache(self):
732 sys.prefix = 'prefix-AAA'
733 sys.exec_prefix = 'exec-prefix-AAA'
734
735 config_vars = sysconfig.get_config_vars()
736
737 self.assertEqual(config_vars['prefix'], sys.prefix)
738 self.assertEqual(config_vars['base'], sys.prefix)
739 self.assertEqual(config_vars['exec_prefix'], sys.exec_prefix)
740 self.assertEqual(config_vars['platbase'], sys.exec_prefix)
741
742 sys.prefix = 'prefix-BBB'
743 sys.exec_prefix = 'exec-prefix-BBB'
744
745 config_vars = sysconfig.get_config_vars()
746
747 self.assertEqual(config_vars['prefix'], sys.prefix)
748 self.assertEqual(config_vars['base'], sys.prefix)
749 self.assertEqual(config_vars['exec_prefix'], sys.exec_prefix)
750 self.assertEqual(config_vars['platbase'], sys.exec_prefix)
751
752
753 class MakefileTests(unittest.TestCase):
754
755 @unittest.skipIf(sys.platform.startswith('win'),
756 'Test is not Windows compatible')
757 @unittest.skipIf(is_wasi, "Incompatible with WASI mapdir and OOT builds")
758 @unittest.skipIf(is_apple_mobile,
759 f"{sys.platform} doesn't include config folder at runtime")
760 def test_get_makefile_filename(self):
761 makefile = sysconfig.get_makefile_filename()
762 self.assertTrue(os.path.isfile(makefile), makefile)
763
764 def test_parse_makefile(self):
765 self.addCleanup(unlink, TESTFN)
766 with open(TESTFN, "w") as makefile:
767 print("var1=a$(VAR2)", file=makefile)
768 print("VAR2=b$(var3)", file=makefile)
769 print("var3=42", file=makefile)
770 print("var4=$/invalid", file=makefile)
771 print("var5=dollar$$5", file=makefile)
772 print("var6=${var3}/lib/python3.5/config-$(VAR2)$(var5)"
773 "-x86_64-linux-gnu", file=makefile)
774 vars = _parse_makefile(TESTFN)
775 self.assertEqual(vars, {
776 'var1': 'ab42',
777 'VAR2': 'b42',
778 'var3': 42,
779 'var4': '$/invalid',
780 'var5': 'dollar$5',
781 'var6': '42/lib/python3.5/config-b42dollar$5-x86_64-linux-gnu',
782 })
783
784
785 class DeprecationTests(unittest.TestCase):
786 def deprecated(self, removal_version, deprecation_msg=None, error=Exception, error_msg=None):
787 if sys.version_info >= removal_version:
788 return self.assertRaises(error, msg=error_msg)
789 else:
790 return self.assertWarns(DeprecationWarning, msg=deprecation_msg)
791
792 def test_expand_makefile_vars(self):
793 with self.deprecated(
794 removal_version=(3, 16),
795 deprecation_msg=(
796 'sysconfig.expand_makefile_vars is deprecated and will be removed in '
797 'Python 3.16. Use sysconfig.get_paths(vars=...) instead.',
798 ),
799 error=AttributeError,
800 error_msg="module 'sysconfig' has no attribute 'expand_makefile_vars'",
801 ):
802 sysconfig.expand_makefile_vars('', {})
803
804 def test_is_python_build_check_home(self):
805 with self.deprecated(
806 removal_version=(3, 15),
807 deprecation_msg=(
808 'The check_home argument of sysconfig.is_python_build is '
809 'deprecated and its value is ignored. '
810 'It will be removed in Python 3.15.'
811 ),
812 error=TypeError,
813 error_msg="is_python_build() takes 0 positional arguments but 1 were given",
814 ):
815 sysconfig.is_python_build('foo')
816
817
818 if __name__ == "__main__":
819 unittest.main()