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