Debian Codegraph @

lib-python/3/test/test_platform.py

raw symbols SCIP
1 import os
2 import copy
3 import pickle
4 import platform
5 import subprocess
6 import sys
7 import unittest
8 from unittest import mock
9
10 from test import support
11 from test.support import os_helper
12
13 FEDORA_OS_RELEASE = """\
14 NAME=Fedora
15 VERSION="32 (Thirty Two)"
16 ID=fedora
17 VERSION_ID=32
18 VERSION_CODENAME=""
19 PLATFORM_ID="platform:f32"
20 PRETTY_NAME="Fedora 32 (Thirty Two)"
21 ANSI_COLOR="0;34"
22 LOGO=fedora-logo-icon
23 CPE_NAME="cpe:/o:fedoraproject:fedora:32"
24 HOME_URL="https://fedoraproject.org/"
25 DOCUMENTATION_URL="https://docs.fedoraproject.org/en-US/fedora/f32/system-administrators-guide/"
26 SUPPORT_URL="https://fedoraproject.org/wiki/Communicating_and_getting_help"
27 BUG_REPORT_URL="https://bugzilla.redhat.com/"
28 REDHAT_BUGZILLA_PRODUCT="Fedora"
29 REDHAT_BUGZILLA_PRODUCT_VERSION=32
30 REDHAT_SUPPORT_PRODUCT="Fedora"
31 REDHAT_SUPPORT_PRODUCT_VERSION=32
32 PRIVACY_POLICY_URL="https://fedoraproject.org/wiki/Legal:PrivacyPolicy"
33 """
34
35 UBUNTU_OS_RELEASE = """\
36 NAME="Ubuntu"
37 VERSION="20.04.1 LTS (Focal Fossa)"
38 ID=ubuntu
39 ID_LIKE=debian
40 PRETTY_NAME="Ubuntu 20.04.1 LTS"
41 VERSION_ID="20.04"
42 HOME_URL="https://www.ubuntu.com/"
43 SUPPORT_URL="https://help.ubuntu.com/"
44 BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
45 PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
46 VERSION_CODENAME=focal
47 UBUNTU_CODENAME=focal
48 """
49
50 TEST_OS_RELEASE = r"""
51 # test data
52 ID_LIKE="egg spam viking"
53 EMPTY=
54 # comments and empty lines are ignored
55
56 SINGLE_QUOTE='single'
57 EMPTY_SINGLE=''
58 DOUBLE_QUOTE="double"
59 EMPTY_DOUBLE=""
60 QUOTES="double\'s"
61 SPECIALS="\$\`\\\'\""
62 # invalid lines
63 =invalid
64 =
65 INVALID
66 IN-VALID=value
67 IN VALID=value
68 """
69
70
71 class PlatformTest(unittest.TestCase):
72 def clear_caches(self):
73 platform._platform_cache.clear()
74 platform._sys_version_cache.clear()
75 platform._uname_cache = None
76 platform._os_release_cache = None
77
78 def test_architecture(self):
79 res = platform.architecture()
80
81 @os_helper.skip_unless_symlink
82 @support.requires_subprocess()
83 def test_architecture_via_symlink(self): # issue3762
84 with support.PythonSymlink() as py:
85 cmd = "-c", "import platform; print(platform.architecture())"
86 self.assertEqual(py.call_real(*cmd), py.call_link(*cmd))
87
88 def test_platform(self):
89 for aliased in (False, True):
90 for terse in (False, True):
91 res = platform.platform(aliased, terse)
92
93 def test_system(self):
94 res = platform.system()
95
96 def test_node(self):
97 res = platform.node()
98
99 def test_release(self):
100 res = platform.release()
101
102 def test_version(self):
103 res = platform.version()
104
105 def test_machine(self):
106 res = platform.machine()
107
108 def test_processor(self):
109 res = platform.processor()
110
111 def setUp(self):
112 self.save_version = sys.version
113 self.save_git = sys._git
114 self.save_platform = sys.platform
115
116 def tearDown(self):
117 sys.version = self.save_version
118 sys._git = self.save_git
119 sys.platform = self.save_platform
120
121 @support.cpython_only
122 def test_sys_version(self):
123 # Old test.
124 # Fails on PyPy for obscure reasons
125 for input, output in (
126 ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
127 ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')),
128 ('IronPython 1.0.60816 on .NET 2.0.50727.42',
129 ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
130 ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
131 ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
132 ('2.4.3 (truncation, date, t) \n[GCC]',
133 ('CPython', '2.4.3', '', '', 'truncation', 'date t', 'GCC')),
134 ('2.4.3 (truncation, date, ) \n[GCC]',
135 ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
136 ('2.4.3 (truncation, date,) \n[GCC]',
137 ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
138 ('2.4.3 (truncation, date) \n[GCC]',
139 ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
140 ('2.4.3 (truncation, d) \n[GCC]',
141 ('CPython', '2.4.3', '', '', 'truncation', 'd', 'GCC')),
142 ('2.4.3 (truncation, ) \n[GCC]',
143 ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
144 ('2.4.3 (truncation,) \n[GCC]',
145 ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
146 ('2.4.3 (truncation) \n[GCC]',
147 ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
148 ):
149 # branch and revision are not "parsed", but fetched
150 # from sys._git. Ignore them
151 (name, version, branch, revision, buildno, builddate, compiler) \
152 = platform._sys_version(input)
153 self.assertEqual(
154 (name, version, '', '', buildno, builddate, compiler), output)
155
156 # Tests for python_implementation(), python_version(), python_branch(),
157 # python_revision(), python_build(), and python_compiler().
158 sys_versions = {
159 ("2.6.1 (r261:67515, Dec 6 2008, 15:26:00) \n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]",
160 ('CPython', 'tags/r261', '67515'), self.save_platform)
161 :
162 ("CPython", "2.6.1", "tags/r261", "67515",
163 ('r261:67515', 'Dec 6 2008 15:26:00'),
164 'GCC 4.0.1 (Apple Computer, Inc. build 5370)'),
165
166 ("IronPython 2.0 (2.0.0.0) on .NET 2.0.50727.3053", None, "cli")
167 :
168 ("IronPython", "2.0.0", "", "", ("", ""),
169 ".NET 2.0.50727.3053"),
170
171 ("2.6.1 (IronPython 2.6.1 (2.6.10920.0) on .NET 2.0.50727.1433)", None, "cli")
172 :
173 ("IronPython", "2.6.1", "", "", ("", ""),
174 ".NET 2.0.50727.1433"),
175
176 ("2.7.4 (IronPython 2.7.4 (2.7.0.40) on Mono 4.0.30319.1 (32-bit))", None, "cli")
177 :
178 ("IronPython", "2.7.4", "", "", ("", ""),
179 "Mono 4.0.30319.1 (32-bit)"),
180
181 ("2.5 (trunk:6107, Mar 26 2009, 13:02:18) \n[Java HotSpot(TM) Client VM (\"Apple Computer, Inc.\")]",
182 ('Jython', 'trunk', '6107'), "java1.5.0_16")
183 :
184 ("Jython", "2.5.0", "trunk", "6107",
185 ('trunk:6107', 'Mar 26 2009'), "java1.5.0_16"),
186
187 ("2.5.2 (63378, Mar 26 2009, 18:03:29)\n[PyPy 1.0.0]",
188 ('PyPy', 'trunk', '63378'), self.save_platform)
189 :
190 ("PyPy", "2.5.2", "trunk", "63378", ('63378', 'Mar 26 2009'),
191 "")
192 }
193 for (version_tag, scm, sys_platform), info in \
194 sys_versions.items():
195 sys.version = version_tag
196 if scm is None:
197 if hasattr(sys, "_git"):
198 del sys._git
199 else:
200 sys._git = scm
201 if sys_platform is not None:
202 sys.platform = sys_platform
203 self.assertEqual(platform.python_implementation(), info[0])
204 self.assertEqual(platform.python_version(), info[1])
205 self.assertEqual(platform.python_branch(), info[2])
206 self.assertEqual(platform.python_revision(), info[3])
207 self.assertEqual(platform.python_build(), info[4])
208 self.assertEqual(platform.python_compiler(), info[5])
209
210 def test_system_alias(self):
211 res = platform.system_alias(
212 platform.system(),
213 platform.release(),
214 platform.version(),
215 )
216
217 def test_uname(self):
218 res = platform.uname()
219 self.assertTrue(any(res))
220 self.assertEqual(res[0], res.system)
221 self.assertEqual(res[-6], res.system)
222 self.assertEqual(res[1], res.node)
223 self.assertEqual(res[-5], res.node)
224 self.assertEqual(res[2], res.release)
225 self.assertEqual(res[-4], res.release)
226 self.assertEqual(res[3], res.version)
227 self.assertEqual(res[-3], res.version)
228 self.assertEqual(res[4], res.machine)
229 self.assertEqual(res[-2], res.machine)
230 self.assertEqual(res[5], res.processor)
231 self.assertEqual(res[-1], res.processor)
232 self.assertEqual(len(res), 6)
233
234 def test_uname_cast_to_tuple(self):
235 res = platform.uname()
236 expected = (
237 res.system, res.node, res.release, res.version, res.machine,
238 res.processor,
239 )
240 self.assertEqual(tuple(res), expected)
241
242 def test_uname_replace(self):
243 res = platform.uname()
244 new = res._replace(
245 system='system', node='node', release='release',
246 version='version', machine='machine')
247 self.assertEqual(new.system, 'system')
248 self.assertEqual(new.node, 'node')
249 self.assertEqual(new.release, 'release')
250 self.assertEqual(new.version, 'version')
251 self.assertEqual(new.machine, 'machine')
252 # processor cannot be replaced
253 self.assertEqual(new.processor, res.processor)
254
255 def test_uname_copy(self):
256 uname = platform.uname()
257 self.assertEqual(copy.copy(uname), uname)
258 self.assertEqual(copy.deepcopy(uname), uname)
259
260 def test_uname_pickle(self):
261 orig = platform.uname()
262 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
263 with self.subTest(protocol=proto):
264 pickled = pickle.dumps(orig, proto)
265 restored = pickle.loads(pickled)
266 self.assertEqual(restored, orig)
267
268 def test_uname_slices(self):
269 res = platform.uname()
270 expected = tuple(res)
271 self.assertEqual(res[:], expected)
272 self.assertEqual(res[:5], expected[:5])
273
274 def test_uname_fields(self):
275 self.assertIn('processor', platform.uname()._fields)
276
277 def test_uname_asdict(self):
278 res = platform.uname()._asdict()
279 self.assertEqual(len(res), 6)
280 self.assertIn('processor', res)
281
282 @unittest.skipIf(sys.platform in ['win32', 'OpenVMS'], "uname -p not used")
283 @support.requires_subprocess()
284 def test_uname_processor(self):
285 """
286 On some systems, the processor must match the output
287 of 'uname -p'. See Issue 35967 for rationale.
288 """
289 try:
290 proc_res = subprocess.check_output(['uname', '-p'], text=True).strip()
291 expect = platform._unknown_as_blank(proc_res)
292 except (OSError, subprocess.CalledProcessError):
293 expect = ''
294 self.assertEqual(platform.uname().processor, expect)
295
296 @unittest.skipUnless(sys.platform.startswith('win'), "windows only test")
297 def test_uname_win32_ARCHITEW6432(self):
298 # Issue 7860: make sure we get architecture from the correct variable
299 # on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
300 # using it, per
301 # http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
302 try:
303 with os_helper.EnvironmentVarGuard() as environ:
304 if 'PROCESSOR_ARCHITEW6432' in environ:
305 del environ['PROCESSOR_ARCHITEW6432']
306 environ['PROCESSOR_ARCHITECTURE'] = 'foo'
307 platform._uname_cache = None
308 system, node, release, version, machine, processor = platform.uname()
309 self.assertEqual(machine, 'foo')
310 environ['PROCESSOR_ARCHITEW6432'] = 'bar'
311 platform._uname_cache = None
312 system, node, release, version, machine, processor = platform.uname()
313 self.assertEqual(machine, 'bar')
314 finally:
315 platform._uname_cache = None
316
317 def test_java_ver(self):
318 res = platform.java_ver()
319 if sys.platform == 'java':
320 self.assertTrue(all(res))
321
322 @unittest.skipUnless(support.MS_WINDOWS, 'This test only makes sense on Windows')
323 def test_win32_ver(self):
324 release1, version1, csd1, ptype1 = 'a', 'b', 'c', 'd'
325 res = platform.win32_ver(release1, version1, csd1, ptype1)
326 self.assertEqual(len(res), 4)
327 release, version, csd, ptype = res
328 if release:
329 # Currently, release names always come from internal dicts,
330 # but this could change over time. For now, we just check that
331 # release is something different from what we have passed.
332 self.assertNotEqual(release, release1)
333 if version:
334 # It is rather hard to test explicit version without
335 # going deep into the details.
336 self.assertIn('.', version)
337 for v in version.split('.'):
338 int(v) # should not fail
339 if csd:
340 self.assertTrue(csd.startswith('SP'), msg=csd)
341 if ptype:
342 if os.cpu_count() > 1:
343 self.assertIn('Multiprocessor', ptype)
344 else:
345 self.assertIn('Uniprocessor', ptype)
346
347 @unittest.skipIf(support.MS_WINDOWS, 'This test only makes sense on non Windows')
348 def test_win32_ver_on_non_windows(self):
349 release, version, csd, ptype = 'a', '1.0', 'c', 'd'
350 res = platform.win32_ver(release, version, csd, ptype)
351 self.assertSequenceEqual(res, (release, version, csd, ptype), seq_type=tuple)
352
353 def test_mac_ver(self):
354 res = platform.mac_ver()
355
356 if platform.uname().system == 'Darwin':
357 # We are on a macOS system, check that the right version
358 # information is returned
359 output = subprocess.check_output(['sw_vers'], text=True)
360 for line in output.splitlines():
361 if line.startswith('ProductVersion:'):
362 real_ver = line.strip().split()[-1]
363 break
364 else:
365 self.fail(f"failed to parse sw_vers output: {output!r}")
366
367 result_list = res[0].split('.')
368 expect_list = real_ver.split('.')
369 len_diff = len(result_list) - len(expect_list)
370 # On Snow Leopard, sw_vers reports 10.6.0 as 10.6
371 if len_diff > 0:
372 expect_list.extend(['0'] * len_diff)
373 # For compatibility with older binaries, macOS 11.x may report
374 # itself as '10.16' rather than '11.x.y'.
375 if result_list != ['10', '16']:
376 self.assertEqual(result_list, expect_list)
377
378 # res[1] claims to contain
379 # (version, dev_stage, non_release_version)
380 # That information is no longer available
381 self.assertEqual(res[1], ('', '', ''))
382
383 if sys.byteorder == 'little':
384 self.assertIn(res[2], ('i386', 'x86_64', 'arm64'))
385 else:
386 self.assertEqual(res[2], 'PowerPC')
387
388
389 @unittest.skipUnless(sys.platform == 'darwin', "OSX only test")
390 def test_mac_ver_with_fork(self):
391 # Issue7895: platform.mac_ver() crashes when using fork without exec
392 #
393 # This test checks that the fix for that issue works.
394 #
395 pid = os.fork()
396 if pid == 0:
397 # child
398 info = platform.mac_ver()
399 os._exit(0)
400
401 else:
402 # parent
403 support.wait_process(pid, exitcode=0)
404
405 @unittest.skipIf(support.is_emscripten, "Does not apply to Emscripten")
406 def test_libc_ver(self):
407 # check that libc_ver(executable) doesn't raise an exception
408 if os.path.isdir(sys.executable) and \
409 os.path.exists(sys.executable+'.exe'):
410 # Cygwin horror
411 executable = sys.executable + '.exe'
412 elif sys.platform == "win32" and not os.path.exists(sys.executable):
413 # App symlink appears to not exist, but we want the
414 # real executable here anyway
415 import _winapi
416 executable = _winapi.GetModuleFileName(0)
417 else:
418 executable = sys.executable
419 platform.libc_ver(executable)
420
421 filename = os_helper.TESTFN
422 self.addCleanup(os_helper.unlink, filename)
423
424 with mock.patch('os.confstr', create=True, return_value='mock 1.0'):
425 # test os.confstr() code path
426 self.assertEqual(platform.libc_ver(), ('mock', '1.0'))
427
428 # test the different regular expressions
429 for data, expected in (
430 (b'__libc_init', ('libc', '')),
431 (b'GLIBC_2.9', ('glibc', '2.9')),
432 (b'libc.so.1.2.5', ('libc', '1.2.5')),
433 (b'libc_pthread.so.1.2.5', ('libc', '1.2.5_pthread')),
434 (b'', ('', '')),
435 ):
436 with open(filename, 'wb') as fp:
437 fp.write(b'[xxx%sxxx]' % data)
438 fp.flush()
439
440 # os.confstr() must not be used if executable is set
441 self.assertEqual(platform.libc_ver(executable=filename),
442 expected)
443
444 # binary containing multiple versions: get the most recent,
445 # make sure that 1.9 is seen as older than 1.23.4
446 chunksize = 16384
447 with open(filename, 'wb') as f:
448 # test match at chunk boundary
449 f.write(b'x'*(chunksize - 10))
450 f.write(b'GLIBC_1.23.4\0GLIBC_1.9\0GLIBC_1.21\0')
451 self.assertEqual(platform.libc_ver(filename, chunksize=chunksize),
452 ('glibc', '1.23.4'))
453
454 @support.cpython_only
455 def test__comparable_version(self):
456 from platform import _comparable_version as V
457 self.assertEqual(V('1.2.3'), V('1.2.3'))
458 self.assertLess(V('1.2.3'), V('1.2.10'))
459 self.assertEqual(V('1.2.3.4'), V('1_2-3+4'))
460 self.assertLess(V('1.2spam'), V('1.2dev'))
461 self.assertLess(V('1.2dev'), V('1.2alpha'))
462 self.assertLess(V('1.2dev'), V('1.2a'))
463 self.assertLess(V('1.2alpha'), V('1.2beta'))
464 self.assertLess(V('1.2a'), V('1.2b'))
465 self.assertLess(V('1.2beta'), V('1.2c'))
466 self.assertLess(V('1.2b'), V('1.2c'))
467 self.assertLess(V('1.2c'), V('1.2RC'))
468 self.assertLess(V('1.2c'), V('1.2rc'))
469 self.assertLess(V('1.2RC'), V('1.2.0'))
470 self.assertLess(V('1.2rc'), V('1.2.0'))
471 self.assertLess(V('1.2.0'), V('1.2pl'))
472 self.assertLess(V('1.2.0'), V('1.2p'))
473
474 self.assertLess(V('1.5.1'), V('1.5.2b2'))
475 self.assertLess(V('3.10a'), V('161'))
476 self.assertEqual(V('8.02'), V('8.02'))
477 self.assertLess(V('3.4j'), V('1996.07.12'))
478 self.assertLess(V('3.1.1.6'), V('3.2.pl0'))
479 self.assertLess(V('2g6'), V('11g'))
480 self.assertLess(V('0.9'), V('2.2'))
481 self.assertLess(V('1.2'), V('1.2.1'))
482 self.assertLess(V('1.1'), V('1.2.2'))
483 self.assertLess(V('1.1'), V('1.2'))
484 self.assertLess(V('1.2.1'), V('1.2.2'))
485 self.assertLess(V('1.2'), V('1.2.2'))
486 self.assertLess(V('0.4'), V('0.4.0'))
487 self.assertLess(V('1.13++'), V('5.5.kw'))
488 self.assertLess(V('0.960923'), V('2.2beta29'))
489
490
491 def test_macos(self):
492 self.addCleanup(self.clear_caches)
493
494 uname = ('Darwin', 'hostname', '17.7.0',
495 ('Darwin Kernel Version 17.7.0: '
496 'Thu Jun 21 22:53:14 PDT 2018; '
497 'root:xnu-4570.71.2~1/RELEASE_X86_64'),
498 'x86_64', 'i386')
499 arch = ('64bit', '')
500 with mock.patch.object(platform, 'uname', return_value=uname), \
501 mock.patch.object(platform, 'architecture', return_value=arch):
502 for mac_ver, expected_terse, expected in [
503 # darwin: mac_ver() returns empty strings
504 (('', '', ''),
505 'Darwin-17.7.0',
506 'Darwin-17.7.0-x86_64-i386-64bit'),
507 # macOS: mac_ver() returns macOS version
508 (('10.13.6', ('', '', ''), 'x86_64'),
509 'macOS-10.13.6',
510 'macOS-10.13.6-x86_64-i386-64bit'),
511 ]:
512 with mock.patch.object(platform, 'mac_ver',
513 return_value=mac_ver):
514 self.clear_caches()
515 self.assertEqual(platform.platform(terse=1), expected_terse)
516 self.assertEqual(platform.platform(), expected)
517
518 def test_freedesktop_os_release(self):
519 self.addCleanup(self.clear_caches)
520 self.clear_caches()
521
522 if any(os.path.isfile(fn) for fn in platform._os_release_candidates):
523 info = platform.freedesktop_os_release()
524 self.assertIn("NAME", info)
525 self.assertIn("ID", info)
526
527 info["CPYTHON_TEST"] = "test"
528 self.assertNotIn(
529 "CPYTHON_TEST",
530 platform.freedesktop_os_release()
531 )
532 else:
533 with self.assertRaises(OSError):
534 platform.freedesktop_os_release()
535
536 def test_parse_os_release(self):
537 info = platform._parse_os_release(FEDORA_OS_RELEASE.splitlines())
538 self.assertEqual(info["NAME"], "Fedora")
539 self.assertEqual(info["ID"], "fedora")
540 self.assertNotIn("ID_LIKE", info)
541 self.assertEqual(info["VERSION_CODENAME"], "")
542
543 info = platform._parse_os_release(UBUNTU_OS_RELEASE.splitlines())
544 self.assertEqual(info["NAME"], "Ubuntu")
545 self.assertEqual(info["ID"], "ubuntu")
546 self.assertEqual(info["ID_LIKE"], "debian")
547 self.assertEqual(info["VERSION_CODENAME"], "focal")
548
549 info = platform._parse_os_release(TEST_OS_RELEASE.splitlines())
550 expected = {
551 "ID": "linux",
552 "NAME": "Linux",
553 "PRETTY_NAME": "Linux",
554 "ID_LIKE": "egg spam viking",
555 "EMPTY": "",
556 "DOUBLE_QUOTE": "double",
557 "EMPTY_DOUBLE": "",
558 "SINGLE_QUOTE": "single",
559 "EMPTY_SINGLE": "",
560 "QUOTES": "double's",
561 "SPECIALS": "$`\\'\"",
562 }
563 self.assertEqual(info, expected)
564 self.assertEqual(len(info["SPECIALS"]), 5)
565
566
567 if __name__ == '__main__':
568 unittest.main()