Debian Codegraph @

Lib/test/test_platform.py

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