test_posix.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
  4. # Use of this source code is governed by a BSD-style license that can be
  5. # found in the LICENSE file.
  6. """POSIX specific tests."""
  7. import datetime
  8. import errno
  9. import os
  10. import re
  11. import subprocess
  12. import time
  13. import psutil
  14. from psutil import AIX
  15. from psutil import BSD
  16. from psutil import LINUX
  17. from psutil import MACOS
  18. from psutil import OPENBSD
  19. from psutil import POSIX
  20. from psutil import SUNOS
  21. from psutil.tests import CI_TESTING
  22. from psutil.tests import spawn_testproc
  23. from psutil.tests import HAS_NET_IO_COUNTERS
  24. from psutil.tests import mock
  25. from psutil.tests import PsutilTestCase
  26. from psutil.tests import PYTHON_EXE
  27. from psutil.tests import retry_on_failure
  28. from psutil.tests import sh
  29. from psutil.tests import skip_on_access_denied
  30. from psutil.tests import terminate
  31. from psutil.tests import TRAVIS
  32. from psutil.tests import unittest
  33. from psutil.tests import which
  34. def ps(fmt, pid=None):
  35. """
  36. Wrapper for calling the ps command with a little bit of cross-platform
  37. support for a narrow range of features.
  38. """
  39. cmd = ['ps']
  40. if LINUX:
  41. cmd.append('--no-headers')
  42. if pid is not None:
  43. cmd.extend(['-p', str(pid)])
  44. else:
  45. if SUNOS or AIX:
  46. cmd.append('-A')
  47. else:
  48. cmd.append('ax')
  49. if SUNOS:
  50. fmt_map = set(('command', 'comm', 'start', 'stime'))
  51. fmt = fmt_map.get(fmt, fmt)
  52. cmd.extend(['-o', fmt])
  53. output = sh(cmd)
  54. if LINUX:
  55. output = output.splitlines()
  56. else:
  57. output = output.splitlines()[1:]
  58. all_output = []
  59. for line in output:
  60. line = line.strip()
  61. try:
  62. line = int(line)
  63. except ValueError:
  64. pass
  65. all_output.append(line)
  66. if pid is None:
  67. return all_output
  68. else:
  69. return all_output[0]
  70. # ps "-o" field names differ wildly between platforms.
  71. # "comm" means "only executable name" but is not available on BSD platforms.
  72. # "args" means "command with all its arguments", and is also not available
  73. # on BSD platforms.
  74. # "command" is like "args" on most platforms, but like "comm" on AIX,
  75. # and not available on SUNOS.
  76. # so for the executable name we can use "comm" on Solaris and split "command"
  77. # on other platforms.
  78. # to get the cmdline (with args) we have to use "args" on AIX and
  79. # Solaris, and can use "command" on all others.
  80. def ps_name(pid):
  81. field = "command"
  82. if SUNOS:
  83. field = "comm"
  84. return ps(field, pid).split()[0]
  85. def ps_args(pid):
  86. field = "command"
  87. if AIX or SUNOS:
  88. field = "args"
  89. return ps(field, pid)
  90. def ps_rss(pid):
  91. field = "rss"
  92. if AIX:
  93. field = "rssize"
  94. return ps(field, pid)
  95. def ps_vsz(pid):
  96. field = "vsz"
  97. if AIX:
  98. field = "vsize"
  99. return ps(field, pid)
  100. @unittest.skipIf(not POSIX, "POSIX only")
  101. class TestProcess(PsutilTestCase):
  102. """Compare psutil results against 'ps' command line utility (mainly)."""
  103. @classmethod
  104. def setUpClass(cls):
  105. cls.pid = spawn_testproc([PYTHON_EXE, "-E", "-O"],
  106. stdin=subprocess.PIPE).pid
  107. @classmethod
  108. def tearDownClass(cls):
  109. terminate(cls.pid)
  110. def test_ppid(self):
  111. ppid_ps = ps('ppid', self.pid)
  112. ppid_psutil = psutil.Process(self.pid).ppid()
  113. self.assertEqual(ppid_ps, ppid_psutil)
  114. def test_uid(self):
  115. uid_ps = ps('uid', self.pid)
  116. uid_psutil = psutil.Process(self.pid).uids().real
  117. self.assertEqual(uid_ps, uid_psutil)
  118. def test_gid(self):
  119. gid_ps = ps('rgid', self.pid)
  120. gid_psutil = psutil.Process(self.pid).gids().real
  121. self.assertEqual(gid_ps, gid_psutil)
  122. def test_username(self):
  123. username_ps = ps('user', self.pid)
  124. username_psutil = psutil.Process(self.pid).username()
  125. self.assertEqual(username_ps, username_psutil)
  126. def test_username_no_resolution(self):
  127. # Emulate a case where the system can't resolve the uid to
  128. # a username in which case psutil is supposed to return
  129. # the stringified uid.
  130. p = psutil.Process()
  131. with mock.patch("psutil.pwd.getpwuid", side_effect=KeyError) as fun:
  132. self.assertEqual(p.username(), str(p.uids().real))
  133. assert fun.called
  134. @skip_on_access_denied()
  135. @retry_on_failure()
  136. def test_rss_memory(self):
  137. # give python interpreter some time to properly initialize
  138. # so that the results are the same
  139. time.sleep(0.1)
  140. rss_ps = ps_rss(self.pid)
  141. rss_psutil = psutil.Process(self.pid).memory_info()[0] / 1024
  142. self.assertEqual(rss_ps, rss_psutil)
  143. @skip_on_access_denied()
  144. @retry_on_failure()
  145. def test_vsz_memory(self):
  146. # give python interpreter some time to properly initialize
  147. # so that the results are the same
  148. time.sleep(0.1)
  149. vsz_ps = ps_vsz(self.pid)
  150. vsz_psutil = psutil.Process(self.pid).memory_info()[1] / 1024
  151. self.assertEqual(vsz_ps, vsz_psutil)
  152. def test_name(self):
  153. name_ps = ps_name(self.pid)
  154. # remove path if there is any, from the command
  155. name_ps = os.path.basename(name_ps).lower()
  156. name_psutil = psutil.Process(self.pid).name().lower()
  157. # ...because of how we calculate PYTHON_EXE; on MACOS this may
  158. # be "pythonX.Y".
  159. name_ps = re.sub(r"\d.\d", "", name_ps)
  160. name_psutil = re.sub(r"\d.\d", "", name_psutil)
  161. # ...may also be "python.X"
  162. name_ps = re.sub(r"\d", "", name_ps)
  163. name_psutil = re.sub(r"\d", "", name_psutil)
  164. self.assertEqual(name_ps, name_psutil)
  165. def test_name_long(self):
  166. # On UNIX the kernel truncates the name to the first 15
  167. # characters. In such a case psutil tries to determine the
  168. # full name from the cmdline.
  169. name = "long-program-name"
  170. cmdline = ["long-program-name-extended", "foo", "bar"]
  171. with mock.patch("psutil._psplatform.Process.name",
  172. return_value=name):
  173. with mock.patch("psutil._psplatform.Process.cmdline",
  174. return_value=cmdline):
  175. p = psutil.Process()
  176. self.assertEqual(p.name(), "long-program-name-extended")
  177. def test_name_long_cmdline_ad_exc(self):
  178. # Same as above but emulates a case where cmdline() raises
  179. # AccessDenied in which case psutil is supposed to return
  180. # the truncated name instead of crashing.
  181. name = "long-program-name"
  182. with mock.patch("psutil._psplatform.Process.name",
  183. return_value=name):
  184. with mock.patch("psutil._psplatform.Process.cmdline",
  185. side_effect=psutil.AccessDenied(0, "")):
  186. p = psutil.Process()
  187. self.assertEqual(p.name(), "long-program-name")
  188. def test_name_long_cmdline_nsp_exc(self):
  189. # Same as above but emulates a case where cmdline() raises NSP
  190. # which is supposed to propagate.
  191. name = "long-program-name"
  192. with mock.patch("psutil._psplatform.Process.name",
  193. return_value=name):
  194. with mock.patch("psutil._psplatform.Process.cmdline",
  195. side_effect=psutil.NoSuchProcess(0, "")):
  196. p = psutil.Process()
  197. self.assertRaises(psutil.NoSuchProcess, p.name)
  198. @unittest.skipIf(MACOS or BSD, 'ps -o start not available')
  199. def test_create_time(self):
  200. time_ps = ps('start', self.pid)
  201. time_psutil = psutil.Process(self.pid).create_time()
  202. time_psutil_tstamp = datetime.datetime.fromtimestamp(
  203. time_psutil).strftime("%H:%M:%S")
  204. # sometimes ps shows the time rounded up instead of down, so we check
  205. # for both possible values
  206. round_time_psutil = round(time_psutil)
  207. round_time_psutil_tstamp = datetime.datetime.fromtimestamp(
  208. round_time_psutil).strftime("%H:%M:%S")
  209. self.assertIn(time_ps, [time_psutil_tstamp, round_time_psutil_tstamp])
  210. def test_exe(self):
  211. ps_pathname = ps_name(self.pid)
  212. psutil_pathname = psutil.Process(self.pid).exe()
  213. try:
  214. self.assertEqual(ps_pathname, psutil_pathname)
  215. except AssertionError:
  216. # certain platforms such as BSD are more accurate returning:
  217. # "/usr/local/bin/python2.7"
  218. # ...instead of:
  219. # "/usr/local/bin/python"
  220. # We do not want to consider this difference in accuracy
  221. # an error.
  222. adjusted_ps_pathname = ps_pathname[:len(ps_pathname)]
  223. self.assertEqual(ps_pathname, adjusted_ps_pathname)
  224. def test_cmdline(self):
  225. ps_cmdline = ps_args(self.pid)
  226. psutil_cmdline = " ".join(psutil.Process(self.pid).cmdline())
  227. self.assertEqual(ps_cmdline, psutil_cmdline)
  228. # On SUNOS "ps" reads niceness /proc/pid/psinfo which returns an
  229. # incorrect value (20); the real deal is getpriority(2) which
  230. # returns 0; psutil relies on it, see:
  231. # https://github.com/giampaolo/psutil/issues/1082
  232. # AIX has the same issue
  233. @unittest.skipIf(SUNOS, "not reliable on SUNOS")
  234. @unittest.skipIf(AIX, "not reliable on AIX")
  235. def test_nice(self):
  236. ps_nice = ps('nice', self.pid)
  237. psutil_nice = psutil.Process().nice()
  238. self.assertEqual(ps_nice, psutil_nice)
  239. @unittest.skipIf(not POSIX, "POSIX only")
  240. class TestSystemAPIs(PsutilTestCase):
  241. """Test some system APIs."""
  242. @retry_on_failure()
  243. def test_pids(self):
  244. # Note: this test might fail if the OS is starting/killing
  245. # other processes in the meantime
  246. pids_ps = sorted(ps("pid"))
  247. pids_psutil = psutil.pids()
  248. # on MACOS and OPENBSD ps doesn't show pid 0
  249. if MACOS or OPENBSD and 0 not in pids_ps:
  250. pids_ps.insert(0, 0)
  251. # There will often be one more process in pids_ps for ps itself
  252. if len(pids_ps) - len(pids_psutil) > 1:
  253. difference = [x for x in pids_psutil if x not in pids_ps] + \
  254. [x for x in pids_ps if x not in pids_psutil]
  255. self.fail("difference: " + str(difference))
  256. # for some reason ifconfig -a does not report all interfaces
  257. # returned by psutil
  258. @unittest.skipIf(SUNOS, "unreliable on SUNOS")
  259. @unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
  260. @unittest.skipIf(not which('ifconfig'), "no ifconfig cmd")
  261. @unittest.skipIf(not HAS_NET_IO_COUNTERS, "not supported")
  262. def test_nic_names(self):
  263. output = sh("ifconfig -a")
  264. for nic in psutil.net_io_counters(pernic=True).keys():
  265. for line in output.split():
  266. if line.startswith(nic):
  267. break
  268. else:
  269. self.fail(
  270. "couldn't find %s nic in 'ifconfig -a' output\n%s" % (
  271. nic, output))
  272. @unittest.skipIf(CI_TESTING and not psutil.users(), "unreliable on CI")
  273. @retry_on_failure()
  274. def test_users(self):
  275. out = sh("who")
  276. if not out.strip():
  277. raise self.skipTest("no users on this system")
  278. lines = out.split('\n')
  279. users = [x.split()[0] for x in lines]
  280. terminals = [x.split()[1] for x in lines]
  281. self.assertEqual(len(users), len(psutil.users()))
  282. for u in psutil.users():
  283. self.assertIn(u.name, users)
  284. self.assertIn(u.terminal, terminals)
  285. def test_pid_exists_let_raise(self):
  286. # According to "man 2 kill" possible error values for kill
  287. # are (EINVAL, EPERM, ESRCH). Test that any other errno
  288. # results in an exception.
  289. with mock.patch("psutil._psposix.os.kill",
  290. side_effect=OSError(errno.EBADF, "")) as m:
  291. self.assertRaises(OSError, psutil._psposix.pid_exists, os.getpid())
  292. assert m.called
  293. def test_os_waitpid_let_raise(self):
  294. # os.waitpid() is supposed to catch EINTR and ECHILD only.
  295. # Test that any other errno results in an exception.
  296. with mock.patch("psutil._psposix.os.waitpid",
  297. side_effect=OSError(errno.EBADF, "")) as m:
  298. self.assertRaises(OSError, psutil._psposix.wait_pid, os.getpid())
  299. assert m.called
  300. def test_os_waitpid_eintr(self):
  301. # os.waitpid() is supposed to "retry" on EINTR.
  302. with mock.patch("psutil._psposix.os.waitpid",
  303. side_effect=OSError(errno.EINTR, "")) as m:
  304. self.assertRaises(
  305. psutil._psposix.TimeoutExpired,
  306. psutil._psposix.wait_pid, os.getpid(), timeout=0.01)
  307. assert m.called
  308. def test_os_waitpid_bad_ret_status(self):
  309. # Simulate os.waitpid() returning a bad status.
  310. with mock.patch("psutil._psposix.os.waitpid",
  311. return_value=(1, -1)) as m:
  312. self.assertRaises(ValueError,
  313. psutil._psposix.wait_pid, os.getpid())
  314. assert m.called
  315. # AIX can return '-' in df output instead of numbers, e.g. for /proc
  316. @unittest.skipIf(AIX, "unreliable on AIX")
  317. def test_disk_usage(self):
  318. def df(device):
  319. out = sh("df -k %s" % device).strip()
  320. line = out.split('\n')[1]
  321. fields = line.split()
  322. total = int(fields[1]) * 1024
  323. used = int(fields[2]) * 1024
  324. free = int(fields[3]) * 1024
  325. percent = float(fields[4].replace('%', ''))
  326. return (total, used, free, percent)
  327. tolerance = 4 * 1024 * 1024 # 4MB
  328. for part in psutil.disk_partitions(all=False):
  329. usage = psutil.disk_usage(part.mountpoint)
  330. try:
  331. total, used, free, percent = df(part.device)
  332. except RuntimeError as err:
  333. # see:
  334. # https://travis-ci.org/giampaolo/psutil/jobs/138338464
  335. # https://travis-ci.org/giampaolo/psutil/jobs/138343361
  336. err = str(err).lower()
  337. if "no such file or directory" in err or \
  338. "raw devices not supported" in err or \
  339. "permission denied" in err:
  340. continue
  341. else:
  342. raise
  343. else:
  344. self.assertAlmostEqual(usage.total, total, delta=tolerance)
  345. self.assertAlmostEqual(usage.used, used, delta=tolerance)
  346. self.assertAlmostEqual(usage.free, free, delta=tolerance)
  347. self.assertAlmostEqual(usage.percent, percent, delta=1)
  348. if __name__ == '__main__':
  349. from psutil.tests.runner import run_from_name
  350. run_from_name(__file__)