Debian Codegraph @

lib-python/3/test/test_sysconfig.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 import unittest
2 import sys
3 import os
4 import subprocess
5 import shutil
6 from copy import copy
7
8 from test.support import (
9 captured_stdout, PythonSymlink, requires_subprocess, is_wasi, is_pypy
10 )
11 from test.support.import_helper import import_module
12 from test.support.os_helper import (TESTFN, unlink, skip_unless_symlink,
13 change_cwd)
14 from test.support.warnings_helper import check_warnings
15
16 import sysconfig
17 from sysconfig import (get_paths, get_platform, get_config_vars,
18 get_path, get_path_names, _INSTALL_SCHEMES,
19 get_default_scheme, get_scheme_names, get_config_var,
20 _expand_vars, _get_preferred_schemes, _main)
21 import _osx_support
22
23
24 HAS_USER_BASE = sysconfig._HAS_USER_BASE
25
26
27 class TestSysConfig(unittest.TestCase):
28
29 def setUp(self):
30 super(TestSysConfig, self).setUp()
31 self.sys_path = sys.path[:]
32 # patching os.uname
33 if hasattr(os, 'uname'):
34 self.uname = os.uname
35 self._uname = os.uname()
36 else:
37 self.uname = None
38 self._set_uname(('',)*5)
39 os.uname = self._get_uname
40 # saving the environment
41 self.name = os.name
42 self.platform = sys.platform
43 self.version = sys.version
44 self.sep = os.sep
45 self.join = os.path.join
46 self.isabs = os.path.isabs
47 self.splitdrive = os.path.splitdrive
48 self._config_vars = sysconfig._CONFIG_VARS, copy(sysconfig._CONFIG_VARS)
49 self._added_envvars = []
50 self._changed_envvars = []
51 for var in ('MACOSX_DEPLOYMENT_TARGET', 'PATH'):
52 if var in os.environ:
53 self._changed_envvars.append((var, os.environ[var]))
54 else:
55 self._added_envvars.append(var)
56
57 def tearDown(self):
58 sys.path[:] = self.sys_path
59 self._cleanup_testfn()
60 if self.uname is not None:
61 os.uname = self.uname
62 else:
63 del os.uname
64 os.name = self.name
65 sys.platform = self.platform
66 sys.version = self.version
67 os.sep = self.sep
68 os.path.join = self.join
69 os.path.isabs = self.isabs
70 os.path.splitdrive = self.splitdrive
71 sysconfig._CONFIG_VARS = self._config_vars[0]
72 sysconfig._CONFIG_VARS.clear()
73 sysconfig._CONFIG_VARS.update(self._config_vars[1])
74 for var, value in self._changed_envvars:
75 os.environ[var] = value
76 for var in self._added_envvars:
77 os.environ.pop(var, None)
78
79 super(TestSysConfig, self).tearDown()
80
81 def _set_uname(self, uname):
82 self._uname = os.uname_result(uname)
83
84 def _get_uname(self):
85 return self._uname
86
87 def _cleanup_testfn(self):
88 path = TESTFN
89 if os.path.isfile(path):
90 os.remove(path)
91 elif os.path.isdir(path):
92 shutil.rmtree(path)
93
94 def test_get_path_names(self):
95 self.assertEqual(get_path_names(), sysconfig._SCHEME_KEYS)
96
97 def test_get_paths(self):
98 scheme = get_paths()
99 default_scheme = get_default_scheme()
100 wanted = _expand_vars(default_scheme, None)
101 wanted = sorted(wanted.items())
102 scheme = sorted(scheme.items())
103 self.assertEqual(scheme, wanted)
104
105 def test_get_path(self):
106 config_vars = get_config_vars()
107 if os.name == 'nt':
108 # On Windows, we replace the native platlibdir name with the
109 # default so that POSIX schemes resolve correctly
110 config_vars = config_vars | {'platlibdir': 'lib'}
111 for scheme in _INSTALL_SCHEMES:
112 for name in _INSTALL_SCHEMES[scheme]:
113 expected = _INSTALL_SCHEMES[scheme][name].format(**config_vars)
114 self.assertEqual(
115 os.path.normpath(get_path(name, scheme)),
116 os.path.normpath(expected),
117 )
118
119 def test_get_default_scheme(self):
120 self.assertIn(get_default_scheme(), _INSTALL_SCHEMES)
121
122 def test_get_preferred_schemes(self):
123 expected_schemes = {'prefix', 'home', 'user'}
124
125 # Windows.
126 os.name = 'nt'
127 schemes = _get_preferred_schemes()
128 self.assertIsInstance(schemes, dict)
129 self.assertEqual(set(schemes), expected_schemes)
130
131 # Mac and Linux, shared library build.
132 os.name = 'posix'
133 schemes = _get_preferred_schemes()
134 self.assertIsInstance(schemes, dict)
135 self.assertEqual(set(schemes), expected_schemes)
136
137 # Mac, framework build.
138 os.name = 'posix'
139 sys.platform = 'darwin'
140 sys._framework = True
141 self.assertIsInstance(schemes, dict)
142 self.assertEqual(set(schemes), expected_schemes)
143
144 def test_posix_venv_scheme(self):
145 # The following directories were hardcoded in the venv module
146 # before bpo-45413, here we assert the posix_venv scheme does not regress
147 binpath = 'bin'
148 incpath = 'include'
149 if is_pypy:
150 libpath = os.path.join('lib',
151 'pypy%d.%d' % sys.version_info[:2],
152 'site-packages')
153 else:
154 libpath = os.path.join('lib',
155 'python%d.%d' % sys.version_info[:2],
156 'site-packages')
157
158 # Resolve the paths in an imaginary venv/ directory
159 binpath = os.path.join('venv', binpath)
160 incpath = os.path.join('venv', incpath)
161 libpath = os.path.join('venv', libpath)
162
163 # Mimic the venv module, set all bases to the venv directory
164 bases = ('base', 'platbase', 'installed_base', 'installed_platbase')
165 vars = {base: 'venv' for base in bases}
166
167 self.assertEqual(binpath, sysconfig.get_path('scripts', scheme='posix_venv', vars=vars))
168 self.assertEqual(libpath, sysconfig.get_path('purelib', scheme='posix_venv', vars=vars))
169
170 # The include directory on POSIX isn't exactly the same as before,
171 # but it is "within"
172 sysconfig_includedir = sysconfig.get_path('include', scheme='posix_venv', vars=vars)
173 self.assertTrue(sysconfig_includedir.startswith(incpath + os.sep))
174
175 def test_nt_venv_scheme(self):
176 # The following directories were hardcoded in the venv module
177 # before bpo-45413, here we assert the posix_venv scheme does not regress
178 binpath = 'Scripts'
179 incpath = 'Include'
180 libpath = os.path.join('Lib', 'site-packages')
181
182 # Resolve the paths in an imaginary venv\ directory
183 venv = 'venv'
184 binpath = os.path.join(venv, binpath)
185 incpath = os.path.join(venv, incpath)
186 libpath = os.path.join(venv, libpath)
187
188 # Mimic the venv module, set all bases to the venv directory
189 bases = ('base', 'platbase', 'installed_base', 'installed_platbase')
190 vars = {base: 'venv' for base in bases}
191
192 self.assertEqual(binpath, sysconfig.get_path('scripts', scheme='nt_venv', vars=vars))
193 self.assertEqual(incpath, sysconfig.get_path('include', scheme='nt_venv', vars=vars))
194 self.assertEqual(libpath, sysconfig.get_path('purelib', scheme='nt_venv', vars=vars))
195
196 def test_venv_scheme(self):
197 if sys.platform == 'win32':
198 self.assertEqual(
199 sysconfig.get_path('scripts', scheme='venv'),
200 sysconfig.get_path('scripts', scheme='nt_venv')
201 )
202 self.assertEqual(
203 sysconfig.get_path('include', scheme='venv'),
204 sysconfig.get_path('include', scheme='nt_venv')
205 )
206 self.assertEqual(
207 sysconfig.get_path('purelib', scheme='venv'),
208 sysconfig.get_path('purelib', scheme='nt_venv')
209 )
210 else:
211 self.assertEqual(
212 sysconfig.get_path('scripts', scheme='venv'),
213 sysconfig.get_path('scripts', scheme='posix_venv')
214 )
215 self.assertEqual(
216 sysconfig.get_path('include', scheme='venv'),
217 sysconfig.get_path('include', scheme='posix_venv')
218 )
219 self.assertEqual(
220 sysconfig.get_path('purelib', scheme='venv'),
221 sysconfig.get_path('purelib', scheme='posix_venv')
222 )
223
224 def test_get_config_vars(self):
225 cvars = get_config_vars()
226 self.assertIsInstance(cvars, dict)
227 self.assertTrue(cvars)
228
229 def test_get_platform(self):
230 # windows XP, 32bits
231 os.name = 'nt'
232 sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
233 '[MSC v.1310 32 bit (Intel)]')
234 sys.platform = 'win32'
235 self.assertEqual(get_platform(), 'win32')
236
237 # windows XP, amd64
238 os.name = 'nt'
239 sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
240 '[MSC v.1310 32 bit (Amd64)]')
241 sys.platform = 'win32'
242 self.assertEqual(get_platform(), 'win-amd64')
243
244 # macbook
245 os.name = 'posix'
246 sys.version = ('2.5 (r25:51918, Sep 19 2006, 08:49:13) '
247 '\n[GCC 4.0.1 (Apple Computer, Inc. build 5341)]')
248 sys.platform = 'darwin'
249 self._set_uname(('Darwin', 'macziade', '8.11.1',
250 ('Darwin Kernel Version 8.11.1: '
251 'Wed Oct 10 18:23:28 PDT 2007; '
252 'root:xnu-792.25.20~1/RELEASE_I386'), 'PowerPC'))
253 _osx_support._remove_original_values(get_config_vars())
254 get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
255
256 get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
257 '-fwrapv -O3 -Wall -Wstrict-prototypes')
258
259 maxint = sys.maxsize
260 try:
261 sys.maxsize = 2147483647
262 self.assertEqual(get_platform(), 'macosx-10.3-ppc')
263 sys.maxsize = 9223372036854775807
264 self.assertEqual(get_platform(), 'macosx-10.3-ppc64')
265 finally:
266 sys.maxsize = maxint
267
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'), 'i386'))
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 maxint = sys.maxsize
278 try:
279 sys.maxsize = 2147483647
280 self.assertEqual(get_platform(), 'macosx-10.3-i386')
281 sys.maxsize = 9223372036854775807
282 self.assertEqual(get_platform(), 'macosx-10.3-x86_64')
283 finally:
284 sys.maxsize = maxint
285
286 # macbook with fat binaries (fat, universal or fat64)
287 _osx_support._remove_original_values(get_config_vars())
288 get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.4'
289 get_config_vars()['CFLAGS'] = ('-arch ppc -arch i386 -isysroot '
290 '/Developer/SDKs/MacOSX10.4u.sdk '
291 '-fno-strict-aliasing -fno-common '
292 '-dynamic -DNDEBUG -g -O3')
293
294 self.assertEqual(get_platform(), 'macosx-10.4-fat')
295
296 _osx_support._remove_original_values(get_config_vars())
297 get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot '
298 '/Developer/SDKs/MacOSX10.4u.sdk '
299 '-fno-strict-aliasing -fno-common '
300 '-dynamic -DNDEBUG -g -O3')
301
302 self.assertEqual(get_platform(), 'macosx-10.4-intel')
303
304 _osx_support._remove_original_values(get_config_vars())
305 get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot '
306 '/Developer/SDKs/MacOSX10.4u.sdk '
307 '-fno-strict-aliasing -fno-common '
308 '-dynamic -DNDEBUG -g -O3')
309 self.assertEqual(get_platform(), 'macosx-10.4-fat3')
310
311 _osx_support._remove_original_values(get_config_vars())
312 get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot '
313 '/Developer/SDKs/MacOSX10.4u.sdk '
314 '-fno-strict-aliasing -fno-common '
315 '-dynamic -DNDEBUG -g -O3')
316 self.assertEqual(get_platform(), 'macosx-10.4-universal')
317
318 _osx_support._remove_original_values(get_config_vars())
319 get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot '
320 '/Developer/SDKs/MacOSX10.4u.sdk '
321 '-fno-strict-aliasing -fno-common '
322 '-dynamic -DNDEBUG -g -O3')
323
324 self.assertEqual(get_platform(), 'macosx-10.4-fat64')
325
326 for arch in ('ppc', 'i386', 'x86_64', 'ppc64'):
327 _osx_support._remove_original_values(get_config_vars())
328 get_config_vars()['CFLAGS'] = ('-arch %s -isysroot '
329 '/Developer/SDKs/MacOSX10.4u.sdk '
330 '-fno-strict-aliasing -fno-common '
331 '-dynamic -DNDEBUG -g -O3' % arch)
332
333 self.assertEqual(get_platform(), 'macosx-10.4-%s' % arch)
334
335 # linux debian sarge
336 os.name = 'posix'
337 sys.version = ('2.3.5 (#1, Jul 4 2007, 17:28:59) '
338 '\n[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)]')
339 sys.platform = 'linux2'
340 self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7',
341 '#1 Mon Apr 30 17:25:38 CEST 2007', 'i686'))
342
343 self.assertEqual(get_platform(), 'linux-i686')
344
345 # XXX more platforms to tests here
346
347 @unittest.skipIf(is_wasi, "Incompatible with WASI mapdir and OOT builds")
348 @unittest.skipIf(is_pypy, "Incompatible with PyPy")
349 def test_get_config_h_filename(self):
350 config_h = sysconfig.get_config_h_filename()
351 self.assertTrue(os.path.isfile(config_h), config_h)
352
353 def test_get_scheme_names(self):
•354 wanted = ['deb_system', 'nt', 'posix_home', 'posix_local', 'posix_prefix', 'posix_venv', 'nt_venv', 'venv']
355 if HAS_USER_BASE:
356 wanted.extend(['nt_user', 'osx_framework_user', 'posix_user'])
357 self.assertEqual(get_scheme_names(), tuple(sorted(wanted)))
358
359 @skip_unless_symlink
360 @requires_subprocess()
361 def test_symlink(self): # Issue 7880
362 with PythonSymlink() as py:
363 cmd = "-c", "import sysconfig; print(sysconfig.get_platform())"
364 self.assertEqual(py.call_real(*cmd), py.call_link(*cmd))
365
366 def test_user_similar(self):
367 # Issue #8759: make sure the posix scheme for the users
368 # is similar to the global posix_prefix one
369 base = get_config_var('base')
370 if HAS_USER_BASE:
371 user = get_config_var('userbase')
372 # the global scheme mirrors the distinction between prefix and
373 # exec-prefix but not the user scheme, so we have to adapt the paths
374 # before comparing (issue #9100)
375 adapt = sys.base_prefix != sys.base_exec_prefix
376 for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'):
377 global_path = get_path(name, 'posix_prefix')
378 if adapt:
379 global_path = global_path.replace(sys.exec_prefix, sys.base_prefix)
380 base = base.replace(sys.exec_prefix, sys.base_prefix)
381 elif sys.base_prefix != sys.prefix:
382 # virtual environment? Likewise, we have to adapt the paths
383 # before comparing
384 global_path = global_path.replace(sys.base_prefix, sys.prefix)
385 base = base.replace(sys.base_prefix, sys.prefix)
386 if HAS_USER_BASE:
387 user_path = get_path(name, 'posix_user')
388 expected = os.path.normpath(global_path.replace(base, user, 1))
389 # bpo-44860: platlib of posix_user doesn't use sys.platlibdir,
390 # whereas posix_prefix does.
391 if name == 'platlib':
392 # Replace "/lib64/python3.11/site-packages" suffix
393 # with "/lib/python3.11/site-packages".
394 py_version_short = sysconfig.get_python_version()
395 suffix = f'python{py_version_short}/site-packages'
396 expected = expected.replace(f'/{sys.platlibdir}/{suffix}',
397 f'/lib/{suffix}')
398 self.assertEqual(user_path, expected)
399
400 def test_main(self):
401 # just making sure _main() runs and returns things in the stdout
402 with captured_stdout() as output:
403 _main()
404 self.assertTrue(len(output.getvalue().split('\n')) > 0)
405
406 @unittest.skipIf(sys.platform == "win32", "Does not apply to Windows")
407 def test_ldshared_value(self):
408 ldflags = sysconfig.get_config_var('LDFLAGS')
409 ldshared = sysconfig.get_config_var('LDSHARED')
410
411 self.assertIn(ldflags, ldshared)
412
413 @unittest.skipUnless(sys.platform == "darwin", "test only relevant on MacOSX")
414 @requires_subprocess()
415 def test_platform_in_subprocess(self):
416 my_platform = sysconfig.get_platform()
417
418 # Test without MACOSX_DEPLOYMENT_TARGET in the environment
419
420 env = os.environ.copy()
421 if 'MACOSX_DEPLOYMENT_TARGET' in env:
422 del env['MACOSX_DEPLOYMENT_TARGET']
423
424 p = subprocess.Popen([
425 sys.executable, '-c',
426 'import sysconfig; print(sysconfig.get_platform())',
427 ],
428 stdout=subprocess.PIPE,
429 stderr=subprocess.DEVNULL,
430 env=env)
431 test_platform = p.communicate()[0].strip()
432 test_platform = test_platform.decode('utf-8')
433 status = p.wait()
434
435 self.assertEqual(status, 0)
436 self.assertEqual(my_platform, test_platform)
437
438 # Test with MACOSX_DEPLOYMENT_TARGET in the environment, and
439 # using a value that is unlikely to be the default one.
440 env = os.environ.copy()
441 env['MACOSX_DEPLOYMENT_TARGET'] = '10.1'
442
443 p = subprocess.Popen([
444 sys.executable, '-c',
445 'import sysconfig; print(sysconfig.get_platform())',
446 ],
447 stdout=subprocess.PIPE,
448 stderr=subprocess.DEVNULL,
449 env=env)
450 test_platform = p.communicate()[0].strip()
451 test_platform = test_platform.decode('utf-8')
452 status = p.wait()
453
454 self.assertEqual(status, 0)
455 self.assertEqual(my_platform, test_platform)
456
457 @unittest.skipIf(is_wasi, "Incompatible with WASI mapdir and OOT builds")
458 @unittest.skipIf(is_pypy, "Incompatible with PyPy")
459 def test_srcdir(self):
460 # See Issues #15322, #15364.
461 srcdir = sysconfig.get_config_var('srcdir')
462
463 self.assertTrue(os.path.isabs(srcdir), srcdir)
464 self.assertTrue(os.path.isdir(srcdir), srcdir)
465
466 if sysconfig._PYTHON_BUILD:
467 # The python executable has not been installed so srcdir
468 # should be a full source checkout.
469 Python_h = os.path.join(srcdir, 'Include', 'Python.h')
470 self.assertTrue(os.path.exists(Python_h), Python_h)
471 # <srcdir>/PC/pyconfig.h always exists even if unused on POSIX.
472 pyconfig_h = os.path.join(srcdir, 'PC', 'pyconfig.h')
473 self.assertTrue(os.path.exists(pyconfig_h), pyconfig_h)
474 pyconfig_h_in = os.path.join(srcdir, 'pyconfig.h.in')
475 self.assertTrue(os.path.exists(pyconfig_h_in), pyconfig_h_in)
476 elif os.name == 'posix':
477 makefile_dir = os.path.dirname(sysconfig.get_makefile_filename())
478 # Issue #19340: srcdir has been realpath'ed already
479 makefile_dir = os.path.realpath(makefile_dir)
480 self.assertEqual(makefile_dir, srcdir)
481
482 def test_srcdir_independent_of_cwd(self):
483 # srcdir should be independent of the current working directory
484 # See Issues #15322, #15364.
485 srcdir = sysconfig.get_config_var('srcdir')
486 with change_cwd(os.pardir):
487 srcdir2 = sysconfig.get_config_var('srcdir')
488 self.assertEqual(srcdir, srcdir2)
489
490 @unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
491 'EXT_SUFFIX required for this test')
492 def test_EXT_SUFFIX_in_vars(self):
493 import _imp
494 if not _imp.extension_suffixes():
495 self.skipTest("stub loader has no suffixes")
496 vars = sysconfig.get_config_vars()
497 self.assertEqual(vars['EXT_SUFFIX'], _imp.extension_suffixes()[0])
498
499 @unittest.skipUnless(sys.platform == 'linux' and
500 hasattr(sys.implementation, '_multiarch'),
501 'multiarch-specific test')
502 def test_triplet_in_ext_suffix(self):
503 ctypes = import_module('ctypes')
504 import platform, re
505 machine = platform.machine()
506 suffix = sysconfig.get_config_var('EXT_SUFFIX')
507 if re.match('(aarch64|arm|mips|ppc|powerpc|s390|sparc)', machine):
508 self.assertTrue('linux' in suffix, suffix)
509 if re.match('(i[3-6]86|x86_64)$', machine):
510 if ctypes.sizeof(ctypes.c_char_p()) == 4:
511 expected_suffixes = 'i386-linux-gnu.so', 'x86_64-linux-gnux32.so', 'i386-linux-musl.so'
512 else: # 8 byte pointer size
513 expected_suffixes = 'x86_64-linux-gnu.so', 'x86_64-linux-musl.so'
514 self.assertTrue(suffix.endswith(expected_suffixes),
515 f'unexpected suffix {suffix!r}')
516
517 @unittest.skipUnless(sys.platform == 'darwin', 'OS X-specific test')
518 def test_osx_ext_suffix(self):
519 suffix = sysconfig.get_config_var('EXT_SUFFIX')
520 self.assertTrue(suffix.endswith('-darwin.so'), suffix)
521
522 class MakefileTests(unittest.TestCase):
523
524 @unittest.skipIf(is_pypy, "Incompatible with PyPy")
525 @unittest.skipIf(sys.platform.startswith('win'),
526 'Test is not Windows compatible')
527 @unittest.skipIf(is_wasi, "Incompatible with WASI mapdir and OOT builds")
528 def test_get_makefile_filename(self):
529 makefile = sysconfig.get_makefile_filename()
530 self.assertTrue(os.path.isfile(makefile), makefile)
531
532 def test_parse_makefile(self):
533 self.addCleanup(unlink, TESTFN)
534 with open(TESTFN, "w") as makefile:
535 print("var1=a$(VAR2)", file=makefile)
536 print("VAR2=b$(var3)", file=makefile)
537 print("var3=42", file=makefile)
538 print("var4=$/invalid", file=makefile)
539 print("var5=dollar$$5", file=makefile)
540 print("var6=${var3}/lib/python3.5/config-$(VAR2)$(var5)"
541 "-x86_64-linux-gnu", file=makefile)
542 vars = sysconfig._parse_makefile(TESTFN)
543 self.assertEqual(vars, {
544 'var1': 'ab42',
545 'VAR2': 'b42',
546 'var3': 42,
547 'var4': '$/invalid',
548 'var5': 'dollar$5',
549 'var6': '42/lib/python3.5/config-b42dollar$5-x86_64-linux-gnu',
550 })
551
552
553 if __name__ == "__main__":
554 unittest.main()