PageRenderTime 57ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/test/test_platform.py

https://gitlab.com/unofficial-mirrors/cpython
Python | 370 lines | 332 code | 29 blank | 9 comment | 27 complexity | d2458dcb9e781c66fb60cb8a0b82290c MD5 | raw file
  1. from unittest import mock
  2. import os
  3. import platform
  4. import subprocess
  5. import sys
  6. import tempfile
  7. import unittest
  8. import warnings
  9. from test import support
  10. class PlatformTest(unittest.TestCase):
  11. def test_architecture(self):
  12. res = platform.architecture()
  13. @support.skip_unless_symlink
  14. def test_architecture_via_symlink(self): # issue3762
  15. # On Windows, the EXE needs to know where pythonXY.dll and *.pyd is at
  16. # so we add the directory to the path and PYTHONPATH.
  17. if sys.platform == "win32":
  18. def restore_environ(old_env):
  19. os.environ.clear()
  20. os.environ.update(old_env)
  21. self.addCleanup(restore_environ, dict(os.environ))
  22. os.environ["Path"] = "{};{}".format(
  23. os.path.dirname(sys.executable), os.environ["Path"])
  24. os.environ["PYTHONPATH"] = os.path.dirname(sys.executable)
  25. def get(python):
  26. cmd = [python, '-c',
  27. 'import platform; print(platform.architecture())']
  28. p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  29. return p.communicate()
  30. real = os.path.realpath(sys.executable)
  31. link = os.path.abspath(support.TESTFN)
  32. os.symlink(real, link)
  33. try:
  34. self.assertEqual(get(real), get(link))
  35. finally:
  36. os.remove(link)
  37. def test_platform(self):
  38. for aliased in (False, True):
  39. for terse in (False, True):
  40. res = platform.platform(aliased, terse)
  41. def test_system(self):
  42. res = platform.system()
  43. def test_node(self):
  44. res = platform.node()
  45. def test_release(self):
  46. res = platform.release()
  47. def test_version(self):
  48. res = platform.version()
  49. def test_machine(self):
  50. res = platform.machine()
  51. def test_processor(self):
  52. res = platform.processor()
  53. def setUp(self):
  54. self.save_version = sys.version
  55. self.save_mercurial = sys._mercurial
  56. self.save_platform = sys.platform
  57. def tearDown(self):
  58. sys.version = self.save_version
  59. sys._mercurial = self.save_mercurial
  60. sys.platform = self.save_platform
  61. def test_sys_version(self):
  62. # Old test.
  63. for input, output in (
  64. ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
  65. ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')),
  66. ('IronPython 1.0.60816 on .NET 2.0.50727.42',
  67. ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
  68. ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
  69. ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
  70. ('2.4.3 (truncation, date, t) \n[GCC]',
  71. ('CPython', '2.4.3', '', '', 'truncation', 'date t', 'GCC')),
  72. ('2.4.3 (truncation, date, ) \n[GCC]',
  73. ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
  74. ('2.4.3 (truncation, date,) \n[GCC]',
  75. ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
  76. ('2.4.3 (truncation, date) \n[GCC]',
  77. ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
  78. ('2.4.3 (truncation, d) \n[GCC]',
  79. ('CPython', '2.4.3', '', '', 'truncation', 'd', 'GCC')),
  80. ('2.4.3 (truncation, ) \n[GCC]',
  81. ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
  82. ('2.4.3 (truncation,) \n[GCC]',
  83. ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
  84. ('2.4.3 (truncation) \n[GCC]',
  85. ('CPython', '2.4.3', '', '', 'truncation', '', 'GCC')),
  86. ):
  87. # branch and revision are not "parsed", but fetched
  88. # from sys._mercurial. Ignore them
  89. (name, version, branch, revision, buildno, builddate, compiler) \
  90. = platform._sys_version(input)
  91. self.assertEqual(
  92. (name, version, '', '', buildno, builddate, compiler), output)
  93. # Tests for python_implementation(), python_version(), python_branch(),
  94. # python_revision(), python_build(), and python_compiler().
  95. sys_versions = {
  96. ("2.6.1 (r261:67515, Dec 6 2008, 15:26:00) \n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]",
  97. ('CPython', 'tags/r261', '67515'), self.save_platform)
  98. :
  99. ("CPython", "2.6.1", "tags/r261", "67515",
  100. ('r261:67515', 'Dec 6 2008 15:26:00'),
  101. 'GCC 4.0.1 (Apple Computer, Inc. build 5370)'),
  102. ("IronPython 2.0 (2.0.0.0) on .NET 2.0.50727.3053", None, "cli")
  103. :
  104. ("IronPython", "2.0.0", "", "", ("", ""),
  105. ".NET 2.0.50727.3053"),
  106. ("2.6.1 (IronPython 2.6.1 (2.6.10920.0) on .NET 2.0.50727.1433)", None, "cli")
  107. :
  108. ("IronPython", "2.6.1", "", "", ("", ""),
  109. ".NET 2.0.50727.1433"),
  110. ("2.7.4 (IronPython 2.7.4 (2.7.0.40) on Mono 4.0.30319.1 (32-bit))", None, "cli")
  111. :
  112. ("IronPython", "2.7.4", "", "", ("", ""),
  113. "Mono 4.0.30319.1 (32-bit)"),
  114. ("2.5 (trunk:6107, Mar 26 2009, 13:02:18) \n[Java HotSpot(TM) Client VM (\"Apple Computer, Inc.\")]",
  115. ('Jython', 'trunk', '6107'), "java1.5.0_16")
  116. :
  117. ("Jython", "2.5.0", "trunk", "6107",
  118. ('trunk:6107', 'Mar 26 2009'), "java1.5.0_16"),
  119. ("2.5.2 (63378, Mar 26 2009, 18:03:29)\n[PyPy 1.0.0]",
  120. ('PyPy', 'trunk', '63378'), self.save_platform)
  121. :
  122. ("PyPy", "2.5.2", "trunk", "63378", ('63378', 'Mar 26 2009'),
  123. "")
  124. }
  125. for (version_tag, subversion, sys_platform), info in \
  126. sys_versions.items():
  127. sys.version = version_tag
  128. if subversion is None:
  129. if hasattr(sys, "_mercurial"):
  130. del sys._mercurial
  131. else:
  132. sys._mercurial = subversion
  133. if sys_platform is not None:
  134. sys.platform = sys_platform
  135. self.assertEqual(platform.python_implementation(), info[0])
  136. self.assertEqual(platform.python_version(), info[1])
  137. self.assertEqual(platform.python_branch(), info[2])
  138. self.assertEqual(platform.python_revision(), info[3])
  139. self.assertEqual(platform.python_build(), info[4])
  140. self.assertEqual(platform.python_compiler(), info[5])
  141. def test_system_alias(self):
  142. res = platform.system_alias(
  143. platform.system(),
  144. platform.release(),
  145. platform.version(),
  146. )
  147. def test_uname(self):
  148. res = platform.uname()
  149. self.assertTrue(any(res))
  150. self.assertEqual(res[0], res.system)
  151. self.assertEqual(res[1], res.node)
  152. self.assertEqual(res[2], res.release)
  153. self.assertEqual(res[3], res.version)
  154. self.assertEqual(res[4], res.machine)
  155. self.assertEqual(res[5], res.processor)
  156. @unittest.skipUnless(sys.platform.startswith('win'), "windows only test")
  157. def test_uname_win32_ARCHITEW6432(self):
  158. # Issue 7860: make sure we get architecture from the correct variable
  159. # on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
  160. # using it, per
  161. # http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
  162. try:
  163. with support.EnvironmentVarGuard() as environ:
  164. if 'PROCESSOR_ARCHITEW6432' in environ:
  165. del environ['PROCESSOR_ARCHITEW6432']
  166. environ['PROCESSOR_ARCHITECTURE'] = 'foo'
  167. platform._uname_cache = None
  168. system, node, release, version, machine, processor = platform.uname()
  169. self.assertEqual(machine, 'foo')
  170. environ['PROCESSOR_ARCHITEW6432'] = 'bar'
  171. platform._uname_cache = None
  172. system, node, release, version, machine, processor = platform.uname()
  173. self.assertEqual(machine, 'bar')
  174. finally:
  175. platform._uname_cache = None
  176. def test_java_ver(self):
  177. res = platform.java_ver()
  178. if sys.platform == 'java':
  179. self.assertTrue(all(res))
  180. def test_win32_ver(self):
  181. res = platform.win32_ver()
  182. def test_mac_ver(self):
  183. res = platform.mac_ver()
  184. if platform.uname().system == 'Darwin':
  185. # We're on a MacOSX system, check that
  186. # the right version information is returned
  187. fd = os.popen('sw_vers', 'r')
  188. real_ver = None
  189. for ln in fd:
  190. if ln.startswith('ProductVersion:'):
  191. real_ver = ln.strip().split()[-1]
  192. break
  193. fd.close()
  194. self.assertFalse(real_ver is None)
  195. result_list = res[0].split('.')
  196. expect_list = real_ver.split('.')
  197. len_diff = len(result_list) - len(expect_list)
  198. # On Snow Leopard, sw_vers reports 10.6.0 as 10.6
  199. if len_diff > 0:
  200. expect_list.extend(['0'] * len_diff)
  201. self.assertEqual(result_list, expect_list)
  202. # res[1] claims to contain
  203. # (version, dev_stage, non_release_version)
  204. # That information is no longer available
  205. self.assertEqual(res[1], ('', '', ''))
  206. if sys.byteorder == 'little':
  207. self.assertIn(res[2], ('i386', 'x86_64'))
  208. else:
  209. self.assertEqual(res[2], 'PowerPC')
  210. @unittest.skipUnless(sys.platform == 'darwin', "OSX only test")
  211. def test_mac_ver_with_fork(self):
  212. # Issue7895: platform.mac_ver() crashes when using fork without exec
  213. #
  214. # This test checks that the fix for that issue works.
  215. #
  216. pid = os.fork()
  217. if pid == 0:
  218. # child
  219. info = platform.mac_ver()
  220. os._exit(0)
  221. else:
  222. # parent
  223. cpid, sts = os.waitpid(pid, 0)
  224. self.assertEqual(cpid, pid)
  225. self.assertEqual(sts, 0)
  226. def test_dist(self):
  227. with warnings.catch_warnings():
  228. warnings.filterwarnings(
  229. 'ignore',
  230. r'dist\(\) and linux_distribution\(\) '
  231. 'functions are deprecated .*',
  232. PendingDeprecationWarning,
  233. )
  234. res = platform.dist()
  235. def test_libc_ver(self):
  236. import os
  237. if os.path.isdir(sys.executable) and \
  238. os.path.exists(sys.executable+'.exe'):
  239. # Cygwin horror
  240. executable = sys.executable + '.exe'
  241. else:
  242. executable = sys.executable
  243. res = platform.libc_ver(executable)
  244. def test_parse_release_file(self):
  245. for input, output in (
  246. # Examples of release file contents:
  247. ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64')),
  248. ('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64')),
  249. ('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586')),
  250. ('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux')),
  251. ('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche')),
  252. ('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike')),
  253. ('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant')),
  254. ('CentOS release 4', ('CentOS', '4', None)),
  255. ('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia')),
  256. ('', ('', '', '')), # If there's nothing there.
  257. ):
  258. self.assertEqual(platform._parse_release_file(input), output)
  259. def test_popen(self):
  260. mswindows = (sys.platform == "win32")
  261. if mswindows:
  262. command = '"{}" -c "print(\'Hello\')"'.format(sys.executable)
  263. else:
  264. command = "'{}' -c 'print(\"Hello\")'".format(sys.executable)
  265. with warnings.catch_warnings():
  266. warnings.simplefilter("ignore", DeprecationWarning)
  267. with platform.popen(command) as stdout:
  268. hello = stdout.read().strip()
  269. stdout.close()
  270. self.assertEqual(hello, "Hello")
  271. data = 'plop'
  272. if mswindows:
  273. command = '"{}" -c "import sys; data=sys.stdin.read(); exit(len(data))"'
  274. else:
  275. command = "'{}' -c 'import sys; data=sys.stdin.read(); exit(len(data))'"
  276. command = command.format(sys.executable)
  277. with warnings.catch_warnings():
  278. warnings.simplefilter("ignore", DeprecationWarning)
  279. with platform.popen(command, 'w') as stdin:
  280. stdout = stdin.write(data)
  281. ret = stdin.close()
  282. self.assertIsNotNone(ret)
  283. if os.name == 'nt':
  284. returncode = ret
  285. else:
  286. returncode = ret >> 8
  287. self.assertEqual(returncode, len(data))
  288. def test_linux_distribution_encoding(self):
  289. # Issue #17429
  290. with tempfile.TemporaryDirectory() as tempdir:
  291. filename = os.path.join(tempdir, 'fedora-release')
  292. with open(filename, 'w', encoding='utf-8') as f:
  293. f.write('Fedora release 19 (Schr\xf6dinger\u2019s Cat)\n')
  294. with mock.patch('platform._UNIXCONFDIR', tempdir):
  295. with warnings.catch_warnings():
  296. warnings.filterwarnings(
  297. 'ignore',
  298. r'dist\(\) and linux_distribution\(\) '
  299. 'functions are deprecated .*',
  300. PendingDeprecationWarning,
  301. )
  302. distname, version, distid = platform.linux_distribution()
  303. self.assertEqual(distname, 'Fedora')
  304. self.assertEqual(version, '19')
  305. self.assertEqual(distid, 'Schr\xf6dinger\u2019s Cat')
  306. class DeprecationTest(unittest.TestCase):
  307. def test_dist_deprecation(self):
  308. with self.assertWarns(PendingDeprecationWarning) as cm:
  309. platform.dist()
  310. self.assertEqual(str(cm.warning),
  311. 'dist() and linux_distribution() functions are '
  312. 'deprecated in Python 3.5')
  313. def test_linux_distribution_deprecation(self):
  314. with self.assertWarns(PendingDeprecationWarning) as cm:
  315. platform.linux_distribution()
  316. self.assertEqual(str(cm.warning),
  317. 'dist() and linux_distribution() functions are '
  318. 'deprecated in Python 3.5')
  319. if __name__ == '__main__':
  320. unittest.main()