Debian Codegraph @

Lib/test/test_platform.py

raw
1 import contextlib
2 import copy
3 import io
4 import itertools
5 import os
6 import pickle
7 import platform
8 import subprocess
9 import sys
10 import unittest
11 from unittest import mock
12
13 from test import support
14 from test.support import os_helper
15
16 try:
17 # Some of the iOS tests need ctypes to operate.
18 # Confirm that the ctypes module is available
19 # is available.
20 import _ctypes
21 except ImportError:
22 _ctypes = None
23
24 FEDORA_OS_RELEASE = """\
25 NAME=Fedora
26 VERSION="32 (Thirty Two)"
27 ID=fedora
28 VERSION_ID=32
29 VERSION_CODENAME=""
30 PLATFORM_ID="platform:f32"
31 PRETTY_NAME="Fedora 32 (Thirty Two)"
32 ANSI_COLOR="0;34"
33 LOGO=fedora-logo-icon
34 CPE_NAME="cpe:/o:fedoraproject:fedora:32"
35 HOME_URL="https://fedoraproject.org/"
36 DOCUMENTATION_URL="https://docs.fedoraproject.org/en-US/fedora/f32/system-administrators-guide/"
37 SUPPORT_URL="https://fedoraproject.org/wiki/Communicating_and_getting_help"
38 BUG_REPORT_URL="https://bugzilla.redhat.com/"
39 REDHAT_BUGZILLA_PRODUCT="Fedora"
40 REDHAT_BUGZILLA_PRODUCT_VERSION=32
41 REDHAT_SUPPORT_PRODUCT="Fedora"
42 REDHAT_SUPPORT_PRODUCT_VERSION=32
43 PRIVACY_POLICY_URL="https://fedoraproject.org/wiki/Legal:PrivacyPolicy"
44 """
45
46 UBUNTU_OS_RELEASE = """\
47 NAME="Ubuntu"
48 VERSION="20.04.1 LTS (Focal Fossa)"
49 ID=ubuntu
50 ID_LIKE=debian
51 PRETTY_NAME="Ubuntu 20.04.1 LTS"
52 VERSION_ID="20.04"
53 HOME_URL="https://www.ubuntu.com/"
54 SUPPORT_URL="https://help.ubuntu.com/"
55 BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
56 PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
57 VERSION_CODENAME=focal
58 UBUNTU_CODENAME=focal
59 """
60
61 TEST_OS_RELEASE = r"""
62 # test data
63 ID_LIKE="egg spam viking"
64 EMPTY=
65 # comments and empty lines are ignored
66
67 SINGLE_QUOTE='single'
68 EMPTY_SINGLE=''
69 DOUBLE_QUOTE="double"
70 EMPTY_DOUBLE=""
71 QUOTES="double\'s"
72 SPECIALS="\$\`\\\'\""
73 # invalid lines
74 =invalid
75 =
76 INVALID
77 IN-VALID=value
78 IN VALID=value
79 """
80
81
82 class PlatformTest(unittest.TestCase):
83 def clear_caches(self):
84 platform._platform_cache.clear()
85 platform._sys_version_cache.clear()
86 platform._uname_cache = None
87 platform._os_release_cache = None
88
89 def test_invalidate_caches(self):
90 self.clear_caches()
91
92 self.assertDictEqual(platform._platform_cache, {})
93 self.assertDictEqual(platform._sys_version_cache, {})
94 self.assertIsNone(platform._uname_cache)
95 self.assertIsNone(platform._os_release_cache)
96
97 # fill the cached entries (some have side effects on others)
98 platform.platform() # for platform._platform_cache
99 platform.python_implementation() # for platform._sys_version_cache
100 platform.uname() # for platform._uname_cache
101
102 # check that the cache are filled
103 self.assertNotEqual(platform._platform_cache, {})
104 self.assertNotEqual(platform._sys_version_cache, {})
105 self.assertIsNotNone(platform._uname_cache)
106
107 try:
108 platform.freedesktop_os_release()
109 except OSError:
110 self.assertIsNone(platform._os_release_cache)
111 else:
112 self.assertIsNotNone(platform._os_release_cache)
113
114 with self.subTest('clear platform caches'):
115 platform.invalidate_caches()
116 self.assertDictEqual(platform._platform_cache, {})
117 self.assertDictEqual(platform._sys_version_cache, {})
118 self.assertIsNone(platform._uname_cache)
119 self.assertIsNone(platform._os_release_cache)
120
121 def test_architecture(self):
122 res = platform.architecture()
123
124 @os_helper.skip_unless_symlink
125 @support.requires_subprocess()
126 def test_architecture_via_symlink(self): # issue3762
127 with support.PythonSymlink() as py:
128 cmd = "-c", "import platform; print(platform.architecture())"
129 self.assertEqual(py.call_real(*cmd), py.call_link(*cmd))
130
131 def test_platform(self):
132 for aliased in (False, True):
133 for terse in (False, True):
134 res = platform.platform(aliased, terse)
135
136 def test_system(self):
137 res = platform.system()
138
139 def test_node(self):
140 res = platform.node()
141
142 def test_release(self):
143 res = platform.release()
144
145 def test_version(self):
146 res = platform.version()
147
148 def test_machine(self):
149 res = platform.machine()
150
151 def test_processor(self):
152 res = platform.processor()
153
154 def setUp(self):
155 self.save_version = sys.version
156 self.save_git = sys._git
157 self.save_platform = sys.platform
158
159 def tearDown(self):
160 sys.version = self.save_version
161 sys._git = self.save_git
162 sys.platform = self.save_platform
163
164 def test_sys_version(self):
165 # Old test.
166 for input, output in (
167 ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
168 ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')),
169 ('2.4.3 (truncation, date, t) \n[GCC]',
170 ('CPython', '2.4.3', '', '', 'truncation', 'date t', 'GCC')),
171 ('2.4.3 (truncation, date, ) \n[GCC]',
172 ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
173 ('2.4.3 (truncation, date,) \n[GCC]',
174 ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
175 ('2.4.3 (truncation, date) \n[GCC]',
176 ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
177 ('2.4.3 (truncation, d) \n[GCC]',
178 ('CPython', '2.4.3', '', '', 'truncation', 'd', 'GCC')),
179 ('2.4.3 (truncation, ) \n[GCC]',
180 ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
181 ('2.4.3 (truncation,) \n[GCC]',
182 ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
183 ('2.4.3 (truncation) \n[GCC]',
184 ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
185 ):
186 # branch and revision are not "parsed", but fetched
187 # from sys._git. Ignore them
188 (name, version, branch, revision, buildno, builddate, compiler) \
189 = platform._sys_version(input)
190 self.assertEqual(
191 (name, version, '', '', buildno, builddate, compiler), output)
192
193 # Tests for python_implementation(), python_version(), python_branch(),
194 # python_revision(), python_build(), and python_compiler().
195 sys_versions = {
196 ("2.6.1 (r261:67515, Dec 6 2008, 15:26:00) \n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]",
197 ('CPython', 'tags/r261', '67515'), self.save_platform)
198 :
199 ("CPython", "2.6.1", "tags/r261", "67515",
200 ('r261:67515', 'Dec 6 2008 15:26:00'),
201 'GCC 4.0.1 (Apple Computer, Inc. build 5370)'),
202
203 ("3.10.8 (tags/v3.10.8:aaaf517424, Feb 14 2023, 16:28:12) [GCC 9.4.0]",
204 None, "linux")
205 :
206 ('CPython', '3.10.8', '', '',
207 ('tags/v3.10.8:aaaf517424', 'Feb 14 2023 16:28:12'), 'GCC 9.4.0'),
208
209 ("2.5 (trunk:6107, Mar 26 2009, 13:02:18) \n[Java HotSpot(TM) Client VM (\"Apple Computer, Inc.\")]",
210 ('Jython', 'trunk', '6107'), "java1.5.0_16")
211 :
212 ("Jython", "2.5.0", "trunk", "6107",
213 ('trunk:6107', 'Mar 26 2009'), "java1.5.0_16"),
214
215 ("2.5.2 (63378, Mar 26 2009, 18:03:29)\n[PyPy 1.0.0]",
216 ('PyPy', 'trunk', '63378'), self.save_platform)
217 :
218 ("PyPy", "2.5.2", "trunk", "63378", ('63378', 'Mar 26 2009'),
219 "")
220 }
221 for (version_tag, scm, sys_platform), info in \
222 sys_versions.items():
223 sys.version = version_tag
224 if scm is None:
225 if hasattr(sys, "_git"):
226 del sys._git
227 else:
228 sys._git = scm
229 if sys_platform is not None:
230 sys.platform = sys_platform
231 self.assertEqual(platform.python_implementation(), info[0])
232 self.assertEqual(platform.python_version(), info[1])
233 self.assertEqual(platform.python_branch(), info[2])
234 self.assertEqual(platform.python_revision(), info[3])
235 self.assertEqual(platform.python_build(), info[4])
236 self.assertEqual(platform.python_compiler(), info[5])
237
238 with self.assertRaises(ValueError):
239 platform._sys_version('2. 4.3 (truncation) \n[GCC]')
240
241 def test_system_alias(self):
242 res = platform.system_alias(
243 platform.system(),
244 platform.release(),
245 platform.version(),
246 )
247
248 def test_uname(self):
249 res = platform.uname()
250 self.assertTrue(any(res))
251 self.assertEqual(res[0], res.system)
252 self.assertEqual(res[-6], res.system)
253 self.assertEqual(res[1], res.node)
254 self.assertEqual(res[-5], res.node)
255 self.assertEqual(res[2], res.release)
256 self.assertEqual(res[-4], res.release)
257 self.assertEqual(res[3], res.version)
258 self.assertEqual(res[-3], res.version)
259 self.assertEqual(res[4], res.machine)
260 self.assertEqual(res[-2], res.machine)
261 self.assertEqual(res[5], res.processor)
262 self.assertEqual(res[-1], res.processor)
263 self.assertEqual(len(res), 6)
264
265 if os.name == "posix":
266 uname = os.uname()
267 self.assertEqual(res.node, uname.nodename)
268 self.assertEqual(res.version, uname.version)
269 self.assertEqual(res.machine, uname.machine)
270
271 if sys.platform == "android":
272 self.assertEqual(res.system, "Android")
273 self.assertEqual(res.release, platform.android_ver().release)
274 elif sys.platform == "ios":
275 # Platform module needs ctypes for full operation. If ctypes
276 # isn't available, there's no ObjC module, and dummy values are
277 # returned.
278 if _ctypes:
279 self.assertIn(res.system, {"iOS", "iPadOS"})
280 self.assertEqual(res.release, platform.ios_ver().release)
281 else:
282 self.assertEqual(res.system, "")
283 self.assertEqual(res.release, "")
284 else:
285 self.assertEqual(res.system, uname.sysname)
286 self.assertEqual(res.release, uname.release)
287
288
289 @unittest.skipUnless(sys.platform.startswith('win'), "windows only test")
290 def test_uname_win32_without_wmi(self):
291 def raises_oserror(*a):
292 raise OSError()
293
294 with support.swap_attr(platform, '_wmi_query', raises_oserror):
295 self.test_uname()
296
297 def test_uname_cast_to_tuple(self):
298 res = platform.uname()
299 expected = (
300 res.system, res.node, res.release, res.version, res.machine,
301 res.processor,
302 )
303 self.assertEqual(tuple(res), expected)
304
305 def test_uname_replace(self):
306 res = platform.uname()
307 new = res._replace(
308 system='system', node='node', release='release',
309 version='version', machine='machine')
310 self.assertEqual(new.system, 'system')
311 self.assertEqual(new.node, 'node')
312 self.assertEqual(new.release, 'release')
313 self.assertEqual(new.version, 'version')
314 self.assertEqual(new.machine, 'machine')
315 # processor cannot be replaced
316 self.assertEqual(new.processor, res.processor)
317
318 def test_uname_copy(self):
319 uname = platform.uname()
320 self.assertEqual(copy.copy(uname), uname)
321 self.assertEqual(copy.deepcopy(uname), uname)
322
323 def test_uname_pickle(self):
324 orig = platform.uname()
325 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
326 with self.subTest(protocol=proto):
327 pickled = pickle.dumps(orig, proto)
328 restored = pickle.loads(pickled)
329 self.assertEqual(restored, orig)
330
331 def test_uname_slices(self):
332 res = platform.uname()
333 expected = tuple(res)
334 self.assertEqual(res[:], expected)
335 self.assertEqual(res[:5], expected[:5])
336
337 def test_uname_fields(self):
338 self.assertIn('processor', platform.uname()._fields)
339
340 def test_uname_asdict(self):
341 res = platform.uname()._asdict()
342 self.assertEqual(len(res), 6)
343 self.assertIn('processor', res)
344
345 @unittest.skipIf(sys.platform in ['win32', 'OpenVMS'], "uname -p not used")
346 @support.requires_subprocess()
347 def test_uname_processor(self):
348 """
349 On some systems, the processor must match the output
350 of 'uname -p'. See Issue 35967 for rationale.
351 """
352 try:
353 proc_res = subprocess.check_output(['uname', '-p'], text=True).strip()
354 expect = platform._unknown_as_blank(proc_res)
355 except (OSError, subprocess.CalledProcessError):
356 expect = ''
357 self.assertEqual(platform.uname().processor, expect)
358
359 @unittest.skipUnless(sys.platform.startswith('win'), "windows only test")
360 def test_uname_win32_ARCHITEW6432(self):
361 # Issue 7860: make sure we get architecture from the correct variable
362 # on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
363 # using it, per
364 # http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
365
366 # We also need to suppress WMI checks, as those are reliable and
367 # overrule the environment variables
368 def raises_oserror(*a):
369 raise OSError()
370
371 with support.swap_attr(platform, '_wmi_query', raises_oserror):
372 with os_helper.EnvironmentVarGuard() as environ:
373 try:
374 del environ['PROCESSOR_ARCHITEW6432']
375 environ['PROCESSOR_ARCHITECTURE'] = 'foo'
376 platform._uname_cache = None
377 system, node, release, version, machine, processor = platform.uname()
378 self.assertEqual(machine, 'foo')
379 environ['PROCESSOR_ARCHITEW6432'] = 'bar'
380 platform._uname_cache = None
381 system, node, release, version, machine, processor = platform.uname()
382 self.assertEqual(machine, 'bar')
383 finally:
384 platform._uname_cache = None
385
386 def test_java_ver(self):
387 import re
388 msg = re.escape(
389 "'java_ver' is deprecated and slated for removal in Python 3.15"
390 )
391 with self.assertWarnsRegex(DeprecationWarning, msg):
392 res = platform.java_ver()
393 self.assertEqual(len(res), 4)
394
395 @unittest.skipUnless(support.MS_WINDOWS, 'This test only makes sense on Windows')
396 def test_win32_ver(self):
397 release1, version1, csd1, ptype1 = 'a', 'b', 'c', 'd'
398 res = platform.win32_ver(release1, version1, csd1, ptype1)
399 self.assertEqual(len(res), 4)
400 release, version, csd, ptype = res
401 if release:
402 # Currently, release names always come from internal dicts,
403 # but this could change over time. For now, we just check that
404 # release is something different from what we have passed.
405 self.assertNotEqual(release, release1)
406 if version:
407 # It is rather hard to test explicit version without
408 # going deep into the details.
409 self.assertIn('.', version)
410 for v in version.split('.'):
411 int(v) # should not fail
412 if csd:
413 self.assertStartsWith(csd, 'SP')
414 if ptype:
415 if os.cpu_count() > 1:
416 self.assertIn('Multiprocessor', ptype)
417 else:
418 self.assertIn('Uniprocessor', ptype)
419
420 @unittest.skipIf(support.MS_WINDOWS, 'This test only makes sense on non Windows')
421 def test_win32_ver_on_non_windows(self):
422 release, version, csd, ptype = 'a', '1.0', 'c', 'd'
423 res = platform.win32_ver(release, version, csd, ptype)
424 self.assertSequenceEqual(res, (release, version, csd, ptype), seq_type=tuple)
425
426 def test_mac_ver(self):
427 res = platform.mac_ver()
428
429 if platform.uname().system == 'Darwin':
430 # We are on a macOS system, check that the right version
431 # information is returned
432 output = subprocess.check_output(['sw_vers'], text=True)
433 for line in output.splitlines():
434 if line.startswith('ProductVersion:'):
435 real_ver = line.strip().split()[-1]
436 break
437 else:
438 self.fail(f"failed to parse sw_vers output: {output!r}")
439
440 result_list = res[0].split('.')
441 expect_list = real_ver.split('.')
442 len_diff = len(result_list) - len(expect_list)
443 # On Snow Leopard, sw_vers reports 10.6.0 as 10.6
444 if len_diff > 0:
445 expect_list.extend(['0'] * len_diff)
446 # For compatibility with older binaries, macOS 11.x may report
447 # itself as '10.16' rather than '11.x.y'.
448 if result_list != ['10', '16']:
449 self.assertEqual(result_list, expect_list)
450
451 # res[1] claims to contain
452 # (version, dev_stage, non_release_version)
453 # That information is no longer available
454 self.assertEqual(res[1], ('', '', ''))
455
456 if sys.byteorder == 'little':
457 self.assertIn(res[2], ('i386', 'x86_64', 'arm64'))
458 else:
459 self.assertEqual(res[2], 'PowerPC')
460
461
462 @unittest.skipUnless(sys.platform == 'darwin', "OSX only test")
463 def test_mac_ver_with_fork(self):
464 # Issue7895: platform.mac_ver() crashes when using fork without exec
465 #
466 # This test checks that the fix for that issue works.
467 #
468 pid = os.fork()
469 if pid == 0:
470 # child
471 info = platform.mac_ver()
472 os._exit(0)
473
474 else:
475 # parent
476 support.wait_process(pid, exitcode=0)
477
478 def test_ios_ver(self):
479 result = platform.ios_ver()
480
481 # ios_ver is only fully available on iOS where ctypes is available.
482 if sys.platform == "ios" and _ctypes:
483 system, release, model, is_simulator = result
484 # Result is a namedtuple
485 self.assertEqual(result.system, system)
486 self.assertEqual(result.release, release)
487 self.assertEqual(result.model, model)
488 self.assertEqual(result.is_simulator, is_simulator)
489
490 # We can't assert specific values without reproducing the logic of
491 # ios_ver(), so we check that the values are broadly what we expect.
492
493 # System is either iOS or iPadOS, depending on the test device
494 self.assertIn(system, {"iOS", "iPadOS"})
495
496 # Release is a numeric version specifier with at least 2 parts
497 parts = release.split(".")
498 self.assertGreaterEqual(len(parts), 2)
499 self.assertTrue(all(part.isdigit() for part in parts))
500
501 # If this is a simulator, we get a high level device descriptor
502 # with no identifying model number. If this is a physical device,
503 # we get a model descriptor like "iPhone13,1"
504 if is_simulator:
505 self.assertIn(model, {"iPhone", "iPad"})
506 else:
507 self.assertTrue(
508 (model.startswith("iPhone") or model.startswith("iPad"))
509 and "," in model
510 )
511
512 self.assertEqual(type(is_simulator), bool)
513 else:
514 # On non-iOS platforms, calling ios_ver doesn't fail; you get
515 # default values
516 self.assertEqual(result.system, "")
517 self.assertEqual(result.release, "")
518 self.assertEqual(result.model, "")
519 self.assertFalse(result.is_simulator)
520
521 # Check the fallback values can be overridden by arguments
522 override = platform.ios_ver("Foo", "Bar", "Whiz", True)
523 self.assertEqual(override.system, "Foo")
524 self.assertEqual(override.release, "Bar")
525 self.assertEqual(override.model, "Whiz")
526 self.assertTrue(override.is_simulator)
527
528 def test_libc_ver(self):
529 if support.is_emscripten:
530 assert platform.libc_ver() == ("emscripten", "4.0.12")
531 return
532 # check that libc_ver(executable) doesn't raise an exception
533 if os.path.isdir(sys.executable) and \
534 os.path.exists(sys.executable+'.exe'):
535 # Cygwin horror
536 executable = sys.executable + '.exe'
537 elif sys.platform == "win32" and not os.path.exists(sys.executable):
538 # App symlink appears to not exist, but we want the
539 # real executable here anyway
540 import _winapi
541 executable = _winapi.GetModuleFileName(0)
542 else:
543 executable = sys.executable
544 platform.libc_ver(executable)
545
546 filename = os_helper.TESTFN
547 self.addCleanup(os_helper.unlink, filename)
548
549 with mock.patch('os.confstr', create=True, return_value='mock 1.0'):
550 # test os.confstr() code path
551 self.assertEqual(platform.libc_ver(), ('mock', '1.0'))
552
553 # test the different regular expressions
554 for data, expected in (
555 (b'__libc_init', ('libc', '')),
556 (b'GLIBC_2.9', ('glibc', '2.9')),
557 (b'libc.so.1.2.5', ('libc', '1.2.5')),
558 (b'libc_pthread.so.1.2.5', ('libc', '1.2.5_pthread')),
559 (b'/aports/main/musl/src/musl-1.2.5', ('musl', '1.2.5')),
560 # musl uses semver, but we accept some variations anyway:
561 (b'/aports/main/musl/src/musl-12.5', ('musl', '12.5')),
562 (b'/aports/main/musl/src/musl-1.2.5.7', ('musl', '1.2.5.7')),
563 (b'libc.musl.so.1', ('musl', '1')),
564 (b'libc.musl-x86_64.so.1.2.5', ('musl', '1.2.5')),
565 (b'ld-musl.so.1', ('musl', '1')),
566 (b'ld-musl-x86_64.so.1.2.5', ('musl', '1.2.5')),
567 (b'', ('', '')),
568 ):
569 with open(filename, 'wb') as fp:
570 fp.write(b'[xxx%sxxx]' % data)
571 fp.flush()
572
573 # os.confstr() must not be used if executable is set
574 self.assertEqual(platform.libc_ver(executable=filename),
575 expected)
576
577 # binary containing multiple versions: get the most recent,
578 # make sure that eg 1.9 is seen as older than 1.23.4, and that
579 # the arguments don't count even if they are set.
580 chunksize = 200
581 for data, expected in (
582 (b'GLIBC_1.23.4\0GLIBC_1.9\0GLIBC_1.21\0', ('glibc', '1.23.4')),
583 (b'libc.so.2.4\0libc.so.9\0libc.so.23.1\0', ('libc', '23.1')),
584 (b'musl-1.4.1\0musl-2.1.1\0musl-2.0.1\0', ('musl', '2.1.1')),
585 (
586 b'libc.musl-x86_64.so.1.4.1\0libc.musl-x86_64.so.2.1.1\0libc.musl-x86_64.so.2.0.1',
587 ('musl', '2.1.1'),
588 ),
589 (
590 b'ld-musl-x86_64.so.1.4.1\0ld-musl-x86_64.so.2.1.1\0ld-musl-x86_64.so.2.0.1',
591 ('musl', '2.1.1'),
592 ),
593 (b'no match here, so defaults are used', ('test', '100.1.0')),
594 ):
595 with open(filename, 'wb') as f:
596 # test match at chunk boundary
597 f.write(b'x'*(chunksize - 10))
598 f.write(data)
599 self.assertEqual(
600 expected,
601 platform.libc_ver(
602 filename,
603 lib='test',
604 version='100.1.0',
605 chunksize=chunksize,
606 ),
607 )
608
609
610 def test_android_ver(self):
611 res = platform.android_ver()
612 self.assertIsInstance(res, tuple)
613 self.assertEqual(res, (res.release, res.api_level, res.manufacturer,
614 res.model, res.device, res.is_emulator))
615
616 if sys.platform == "android":
617 for name in ["release", "manufacturer", "model", "device"]:
618 with self.subTest(name):
619 value = getattr(res, name)
620 self.assertIsInstance(value, str)
621 self.assertNotEqual(value, "")
622
623 self.assertIsInstance(res.api_level, int)
624 self.assertGreaterEqual(res.api_level, sys.getandroidapilevel())
625
626 self.assertIsInstance(res.is_emulator, bool)
627
628 # When not running on Android, it should return the default values.
629 else:
630 self.assertEqual(res.release, "")
631 self.assertEqual(res.api_level, 0)
632 self.assertEqual(res.manufacturer, "")
633 self.assertEqual(res.model, "")
634 self.assertEqual(res.device, "")
635 self.assertEqual(res.is_emulator, False)
636
637 # Default values may also be overridden using parameters.
638 res = platform.android_ver(
639 "alpha", 1, "bravo", "charlie", "delta", True)
640 self.assertEqual(res.release, "alpha")
641 self.assertEqual(res.api_level, 1)
642 self.assertEqual(res.manufacturer, "bravo")
643 self.assertEqual(res.model, "charlie")
644 self.assertEqual(res.device, "delta")
645 self.assertEqual(res.is_emulator, True)
646
647 @support.cpython_only
648 def test__comparable_version(self):
649 from platform import _comparable_version as V
650 self.assertEqual(V('1.2.3'), V('1.2.3'))
651 self.assertLess(V('1.2.3'), V('1.2.10'))
652 self.assertEqual(V('1.2.3.4'), V('1_2-3+4'))
653 self.assertLess(V('1.2spam'), V('1.2dev'))
654 self.assertLess(V('1.2dev'), V('1.2alpha'))
655 self.assertLess(V('1.2dev'), V('1.2a'))
656 self.assertLess(V('1.2alpha'), V('1.2beta'))
657 self.assertLess(V('1.2a'), V('1.2b'))
658 self.assertLess(V('1.2beta'), V('1.2c'))
659 self.assertLess(V('1.2b'), V('1.2c'))
660 self.assertLess(V('1.2c'), V('1.2RC'))
661 self.assertLess(V('1.2c'), V('1.2rc'))
662 self.assertLess(V('1.2RC'), V('1.2.0'))
663 self.assertLess(V('1.2rc'), V('1.2.0'))
664 self.assertLess(V('1.2.0'), V('1.2pl'))
665 self.assertLess(V('1.2.0'), V('1.2p'))
666
667 self.assertLess(V('1.5.1'), V('1.5.2b2'))
668 self.assertLess(V('3.10a'), V('161'))
669 self.assertEqual(V('8.02'), V('8.02'))
670 self.assertLess(V('3.4j'), V('1996.07.12'))
671 self.assertLess(V('3.1.1.6'), V('3.2.pl0'))
672 self.assertLess(V('2g6'), V('11g'))
673 self.assertLess(V('0.9'), V('2.2'))
674 self.assertLess(V('1.2'), V('1.2.1'))
675 self.assertLess(V('1.1'), V('1.2.2'))
676 self.assertLess(V('1.1'), V('1.2'))
677 self.assertLess(V('1.2.1'), V('1.2.2'))
678 self.assertLess(V('1.2'), V('1.2.2'))
679 self.assertLess(V('0.4'), V('0.4.0'))
680 self.assertLess(V('1.13++'), V('5.5.kw'))
681 self.assertLess(V('0.960923'), V('2.2beta29'))
682
683
684 def test_macos(self):
685 self.addCleanup(self.clear_caches)
686
687 uname = ('Darwin', 'hostname', '17.7.0',
688 ('Darwin Kernel Version 17.7.0: '
689 'Thu Jun 21 22:53:14 PDT 2018; '
690 'root:xnu-4570.71.2~1/RELEASE_X86_64'),
691 'x86_64', 'i386')
692 arch = ('64bit', '')
693 with mock.patch.object(sys, "platform", "darwin"), \
694 mock.patch.object(platform, 'uname', return_value=uname), \
695 mock.patch.object(platform, 'architecture', return_value=arch):
696 for mac_ver, expected_terse, expected in [
697 # darwin: mac_ver() returns empty strings
698 (('', '', ''),
699 'Darwin-17.7.0',
700 'Darwin-17.7.0-x86_64-i386-64bit'),
701 # macOS: mac_ver() returns macOS version
702 (('10.13.6', ('', '', ''), 'x86_64'),
703 'macOS-10.13.6',
704 'macOS-10.13.6-x86_64-i386-64bit'),
705 ]:
706 with mock.patch.object(platform, 'mac_ver',
707 return_value=mac_ver):
708 self.clear_caches()
709 self.assertEqual(platform.platform(terse=1), expected_terse)
710 self.assertEqual(platform.platform(), expected)
711
712 def test_freedesktop_os_release(self):
713 self.addCleanup(self.clear_caches)
714 self.clear_caches()
715
716 if any(os.path.isfile(fn) for fn in platform._os_release_candidates):
717 info = platform.freedesktop_os_release()
718 self.assertIn("NAME", info)
719 self.assertIn("ID", info)
720
721 info["CPYTHON_TEST"] = "test"
722 self.assertNotIn(
723 "CPYTHON_TEST",
724 platform.freedesktop_os_release()
725 )
726 else:
727 with self.assertRaises(OSError):
728 platform.freedesktop_os_release()
729
730 def test_parse_os_release(self):
731 info = platform._parse_os_release(FEDORA_OS_RELEASE.splitlines())
732 self.assertEqual(info["NAME"], "Fedora")
733 self.assertEqual(info["ID"], "fedora")
734 self.assertNotIn("ID_LIKE", info)
735 self.assertEqual(info["VERSION_CODENAME"], "")
736
737 info = platform._parse_os_release(UBUNTU_OS_RELEASE.splitlines())
738 self.assertEqual(info["NAME"], "Ubuntu")
739 self.assertEqual(info["ID"], "ubuntu")
740 self.assertEqual(info["ID_LIKE"], "debian")
741 self.assertEqual(info["VERSION_CODENAME"], "focal")
742
743 info = platform._parse_os_release(TEST_OS_RELEASE.splitlines())
744 expected = {
745 "ID": "linux",
746 "NAME": "Linux",
747 "PRETTY_NAME": "Linux",
748 "ID_LIKE": "egg spam viking",
749 "EMPTY": "",
750 "DOUBLE_QUOTE": "double",
751 "EMPTY_DOUBLE": "",
752 "SINGLE_QUOTE": "single",
753 "EMPTY_SINGLE": "",
754 "QUOTES": "double's",
755 "SPECIALS": "$`\\'\"",
756 }
757 self.assertEqual(info, expected)
758 self.assertEqual(len(info["SPECIALS"]), 5)
759
760
761 class CommandLineTest(unittest.TestCase):
762 def setUp(self):
763 platform.invalidate_caches()
764 self.addCleanup(platform.invalidate_caches)
765
766 def invoke_platform(self, *flags):
767 output = io.StringIO()
768 with contextlib.redirect_stdout(output):
769 platform._main(args=flags)
770 return output.getvalue()
771
772 def test_unknown_flag(self):
773 with self.assertRaises(SystemExit):
774 output = io.StringIO()
775 # suppress argparse error message
776 with contextlib.redirect_stderr(output):
777 _ = self.invoke_platform('--unknown')
778 self.assertStartsWith(output, "usage: ")
779
780 def test_invocation(self):
781 flags = (
782 "--terse", "--nonaliased", "terse", "nonaliased"
783 )
784
785 for r in range(len(flags) + 1):
786 for combination in itertools.combinations(flags, r):
787 self.invoke_platform(*combination)
788
789 def test_arg_parsing(self):
790 # For backwards compatibility, the `aliased` and `terse` parameters are
791 # computed based on a combination of positional arguments and flags.
792 #
793 # Test that the arguments are correctly passed to the underlying
794 # `platform.platform()` call.
795 options = (
796 (["--nonaliased"], False, False),
797 (["nonaliased"], False, False),
798 (["--terse"], True, True),
799 (["terse"], True, True),
800 (["nonaliased", "terse"], False, True),
801 (["--nonaliased", "terse"], False, True),
802 (["--terse", "nonaliased"], False, True),
803 )
804
805 for flags, aliased, terse in options:
806 with self.subTest(flags=flags, aliased=aliased, terse=terse):
807 with mock.patch.object(platform, 'platform') as obj:
808 self.invoke_platform(*flags)
809 obj.assert_called_once_with(aliased, terse)
810
811 @support.force_not_colorized
812 def test_help(self):
813 output = io.StringIO()
814
815 with self.assertRaises(SystemExit):
816 with contextlib.redirect_stdout(output):
817 platform._main(args=["--help"])
818
819 self.assertStartsWith(output.getvalue(), "usage:")
820
821
822 if __name__ == '__main__':
823 unittest.main()