test_contracts.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Contracts tests. These tests mainly check API sanity in terms of
  6. returned types and APIs availability.
  7. Some of these are duplicates of tests test_system.py and test_process.py.
  8. """
  9. import errno
  10. import multiprocessing
  11. import os
  12. import platform
  13. import signal
  14. import stat
  15. import time
  16. import traceback
  17. import unittest
  18. import psutil
  19. from psutil import AIX
  20. from psutil import BSD
  21. from psutil import FREEBSD
  22. from psutil import LINUX
  23. from psutil import MACOS
  24. from psutil import NETBSD
  25. from psutil import OPENBSD
  26. from psutil import OSX
  27. from psutil import POSIX
  28. from psutil import SUNOS
  29. from psutil import WINDOWS
  30. from psutil._compat import PY3
  31. from psutil._compat import FileNotFoundError
  32. from psutil._compat import long
  33. from psutil._compat import range
  34. from psutil._compat import unicode
  35. from psutil.tests import APPVEYOR
  36. from psutil.tests import CI_TESTING
  37. from psutil.tests import GITHUB_ACTIONS
  38. from psutil.tests import HAS_CPU_FREQ
  39. from psutil.tests import HAS_NET_IO_COUNTERS
  40. from psutil.tests import HAS_SENSORS_FANS
  41. from psutil.tests import HAS_SENSORS_TEMPERATURES
  42. from psutil.tests import PYPY
  43. from psutil.tests import SKIP_SYSCONS
  44. from psutil.tests import VALID_PROC_STATUSES
  45. from psutil.tests import PsutilTestCase
  46. from psutil.tests import check_connection_ntuple
  47. from psutil.tests import create_sockets
  48. from psutil.tests import enum
  49. from psutil.tests import is_namedtuple
  50. from psutil.tests import kernel_version
  51. from psutil.tests import process_namespace
  52. from psutil.tests import serialrun
  53. # ===================================================================
  54. # --- APIs availability
  55. # ===================================================================
  56. # Make sure code reflects what doc promises in terms of APIs
  57. # availability.
  58. class TestAvailConstantsAPIs(PsutilTestCase):
  59. def test_PROCFS_PATH(self):
  60. self.assertEqual(hasattr(psutil, "PROCFS_PATH"),
  61. LINUX or SUNOS or AIX)
  62. def test_win_priority(self):
  63. ae = self.assertEqual
  64. ae(hasattr(psutil, "ABOVE_NORMAL_PRIORITY_CLASS"), WINDOWS)
  65. ae(hasattr(psutil, "BELOW_NORMAL_PRIORITY_CLASS"), WINDOWS)
  66. ae(hasattr(psutil, "HIGH_PRIORITY_CLASS"), WINDOWS)
  67. ae(hasattr(psutil, "IDLE_PRIORITY_CLASS"), WINDOWS)
  68. ae(hasattr(psutil, "NORMAL_PRIORITY_CLASS"), WINDOWS)
  69. ae(hasattr(psutil, "REALTIME_PRIORITY_CLASS"), WINDOWS)
  70. def test_linux_ioprio_linux(self):
  71. ae = self.assertEqual
  72. ae(hasattr(psutil, "IOPRIO_CLASS_NONE"), LINUX)
  73. ae(hasattr(psutil, "IOPRIO_CLASS_RT"), LINUX)
  74. ae(hasattr(psutil, "IOPRIO_CLASS_BE"), LINUX)
  75. ae(hasattr(psutil, "IOPRIO_CLASS_IDLE"), LINUX)
  76. def test_linux_ioprio_windows(self):
  77. ae = self.assertEqual
  78. ae(hasattr(psutil, "IOPRIO_HIGH"), WINDOWS)
  79. ae(hasattr(psutil, "IOPRIO_NORMAL"), WINDOWS)
  80. ae(hasattr(psutil, "IOPRIO_LOW"), WINDOWS)
  81. ae(hasattr(psutil, "IOPRIO_VERYLOW"), WINDOWS)
  82. @unittest.skipIf(GITHUB_ACTIONS and LINUX,
  83. "unsupported on GITHUB_ACTIONS + LINUX")
  84. def test_rlimit(self):
  85. ae = self.assertEqual
  86. ae(hasattr(psutil, "RLIM_INFINITY"), LINUX or FREEBSD)
  87. ae(hasattr(psutil, "RLIMIT_AS"), LINUX or FREEBSD)
  88. ae(hasattr(psutil, "RLIMIT_CORE"), LINUX or FREEBSD)
  89. ae(hasattr(psutil, "RLIMIT_CPU"), LINUX or FREEBSD)
  90. ae(hasattr(psutil, "RLIMIT_DATA"), LINUX or FREEBSD)
  91. ae(hasattr(psutil, "RLIMIT_FSIZE"), LINUX or FREEBSD)
  92. ae(hasattr(psutil, "RLIMIT_MEMLOCK"), LINUX or FREEBSD)
  93. ae(hasattr(psutil, "RLIMIT_NOFILE"), LINUX or FREEBSD)
  94. ae(hasattr(psutil, "RLIMIT_NPROC"), LINUX or FREEBSD)
  95. ae(hasattr(psutil, "RLIMIT_RSS"), LINUX or FREEBSD)
  96. ae(hasattr(psutil, "RLIMIT_STACK"), LINUX or FREEBSD)
  97. ae(hasattr(psutil, "RLIMIT_LOCKS"), LINUX)
  98. if POSIX:
  99. if kernel_version() >= (2, 6, 8):
  100. ae(hasattr(psutil, "RLIMIT_MSGQUEUE"), LINUX)
  101. if kernel_version() >= (2, 6, 12):
  102. ae(hasattr(psutil, "RLIMIT_NICE"), LINUX)
  103. if kernel_version() >= (2, 6, 12):
  104. ae(hasattr(psutil, "RLIMIT_RTPRIO"), LINUX)
  105. if kernel_version() >= (2, 6, 25):
  106. ae(hasattr(psutil, "RLIMIT_RTTIME"), LINUX)
  107. if kernel_version() >= (2, 6, 8):
  108. ae(hasattr(psutil, "RLIMIT_SIGPENDING"), LINUX)
  109. ae(hasattr(psutil, "RLIMIT_SWAP"), FREEBSD)
  110. ae(hasattr(psutil, "RLIMIT_SBSIZE"), FREEBSD)
  111. ae(hasattr(psutil, "RLIMIT_NPTS"), FREEBSD)
  112. class TestAvailSystemAPIs(PsutilTestCase):
  113. def test_win_service_iter(self):
  114. self.assertEqual(hasattr(psutil, "win_service_iter"), WINDOWS)
  115. def test_win_service_get(self):
  116. self.assertEqual(hasattr(psutil, "win_service_get"), WINDOWS)
  117. def test_cpu_freq(self):
  118. self.assertEqual(hasattr(psutil, "cpu_freq"),
  119. LINUX or MACOS or WINDOWS or FREEBSD or OPENBSD)
  120. def test_sensors_temperatures(self):
  121. self.assertEqual(
  122. hasattr(psutil, "sensors_temperatures"), LINUX or FREEBSD)
  123. def test_sensors_fans(self):
  124. self.assertEqual(hasattr(psutil, "sensors_fans"), LINUX)
  125. def test_battery(self):
  126. self.assertEqual(hasattr(psutil, "sensors_battery"),
  127. LINUX or WINDOWS or FREEBSD or MACOS)
  128. class TestAvailProcessAPIs(PsutilTestCase):
  129. def test_environ(self):
  130. self.assertEqual(hasattr(psutil.Process, "environ"),
  131. LINUX or MACOS or WINDOWS or AIX or SUNOS or
  132. FREEBSD or OPENBSD or NETBSD)
  133. def test_uids(self):
  134. self.assertEqual(hasattr(psutil.Process, "uids"), POSIX)
  135. def test_gids(self):
  136. self.assertEqual(hasattr(psutil.Process, "uids"), POSIX)
  137. def test_terminal(self):
  138. self.assertEqual(hasattr(psutil.Process, "terminal"), POSIX)
  139. def test_ionice(self):
  140. self.assertEqual(hasattr(psutil.Process, "ionice"), LINUX or WINDOWS)
  141. @unittest.skipIf(GITHUB_ACTIONS and LINUX,
  142. "unsupported on GITHUB_ACTIONS + LINUX")
  143. def test_rlimit(self):
  144. self.assertEqual(hasattr(psutil.Process, "rlimit"), LINUX or FREEBSD)
  145. def test_io_counters(self):
  146. hasit = hasattr(psutil.Process, "io_counters")
  147. self.assertEqual(hasit, not (MACOS or SUNOS))
  148. def test_num_fds(self):
  149. self.assertEqual(hasattr(psutil.Process, "num_fds"), POSIX)
  150. def test_num_handles(self):
  151. self.assertEqual(hasattr(psutil.Process, "num_handles"), WINDOWS)
  152. def test_cpu_affinity(self):
  153. self.assertEqual(hasattr(psutil.Process, "cpu_affinity"),
  154. LINUX or WINDOWS or FREEBSD)
  155. def test_cpu_num(self):
  156. self.assertEqual(hasattr(psutil.Process, "cpu_num"),
  157. LINUX or FREEBSD or SUNOS)
  158. def test_memory_maps(self):
  159. hasit = hasattr(psutil.Process, "memory_maps")
  160. self.assertEqual(
  161. hasit, not (OPENBSD or NETBSD or AIX or MACOS))
  162. # ===================================================================
  163. # --- API types
  164. # ===================================================================
  165. class TestSystemAPITypes(PsutilTestCase):
  166. """Check the return types of system related APIs.
  167. Mainly we want to test we never return unicode on Python 2, see:
  168. https://github.com/giampaolo/psutil/issues/1039.
  169. """
  170. @classmethod
  171. def setUpClass(cls):
  172. cls.proc = psutil.Process()
  173. def assert_ntuple_of_nums(self, nt, type_=float, gezero=True):
  174. assert is_namedtuple(nt)
  175. for n in nt:
  176. self.assertIsInstance(n, type_)
  177. if gezero:
  178. self.assertGreaterEqual(n, 0)
  179. def test_cpu_times(self):
  180. self.assert_ntuple_of_nums(psutil.cpu_times())
  181. for nt in psutil.cpu_times(percpu=True):
  182. self.assert_ntuple_of_nums(nt)
  183. def test_cpu_percent(self):
  184. self.assertIsInstance(psutil.cpu_percent(interval=None), float)
  185. self.assertIsInstance(psutil.cpu_percent(interval=0.00001), float)
  186. def test_cpu_times_percent(self):
  187. self.assert_ntuple_of_nums(psutil.cpu_times_percent(interval=None))
  188. self.assert_ntuple_of_nums(psutil.cpu_times_percent(interval=0.0001))
  189. def test_cpu_count(self):
  190. self.assertIsInstance(psutil.cpu_count(), int)
  191. # TODO: remove this once 1892 is fixed
  192. @unittest.skipIf(MACOS and platform.machine() == 'arm64',
  193. "skipped due to #1892")
  194. @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
  195. def test_cpu_freq(self):
  196. if psutil.cpu_freq() is None:
  197. raise self.skipTest("cpu_freq() returns None")
  198. self.assert_ntuple_of_nums(psutil.cpu_freq(), type_=(float, int, long))
  199. def test_disk_io_counters(self):
  200. # Duplicate of test_system.py. Keep it anyway.
  201. for k, v in psutil.disk_io_counters(perdisk=True).items():
  202. self.assertIsInstance(k, str)
  203. self.assert_ntuple_of_nums(v, type_=(int, long))
  204. def test_disk_partitions(self):
  205. # Duplicate of test_system.py. Keep it anyway.
  206. for disk in psutil.disk_partitions():
  207. self.assertIsInstance(disk.device, str)
  208. self.assertIsInstance(disk.mountpoint, str)
  209. self.assertIsInstance(disk.fstype, str)
  210. self.assertIsInstance(disk.opts, str)
  211. self.assertIsInstance(disk.maxfile, (int, type(None)))
  212. self.assertIsInstance(disk.maxpath, (int, type(None)))
  213. @unittest.skipIf(SKIP_SYSCONS, "requires root")
  214. def test_net_connections(self):
  215. with create_sockets():
  216. ret = psutil.net_connections('all')
  217. self.assertEqual(len(ret), len(set(ret)))
  218. for conn in ret:
  219. assert is_namedtuple(conn)
  220. def test_net_if_addrs(self):
  221. # Duplicate of test_system.py. Keep it anyway.
  222. for ifname, addrs in psutil.net_if_addrs().items():
  223. self.assertIsInstance(ifname, str)
  224. for addr in addrs:
  225. if enum is not None and not PYPY:
  226. self.assertIsInstance(addr.family, enum.IntEnum)
  227. else:
  228. self.assertIsInstance(addr.family, int)
  229. self.assertIsInstance(addr.address, str)
  230. self.assertIsInstance(addr.netmask, (str, type(None)))
  231. self.assertIsInstance(addr.broadcast, (str, type(None)))
  232. def test_net_if_stats(self):
  233. # Duplicate of test_system.py. Keep it anyway.
  234. for ifname, info in psutil.net_if_stats().items():
  235. self.assertIsInstance(ifname, str)
  236. self.assertIsInstance(info.isup, bool)
  237. if enum is not None:
  238. self.assertIsInstance(info.duplex, enum.IntEnum)
  239. else:
  240. self.assertIsInstance(info.duplex, int)
  241. self.assertIsInstance(info.speed, int)
  242. self.assertIsInstance(info.mtu, int)
  243. @unittest.skipIf(not HAS_NET_IO_COUNTERS, 'not supported')
  244. def test_net_io_counters(self):
  245. # Duplicate of test_system.py. Keep it anyway.
  246. for ifname in psutil.net_io_counters(pernic=True):
  247. self.assertIsInstance(ifname, str)
  248. @unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
  249. def test_sensors_fans(self):
  250. # Duplicate of test_system.py. Keep it anyway.
  251. for name, units in psutil.sensors_fans().items():
  252. self.assertIsInstance(name, str)
  253. for unit in units:
  254. self.assertIsInstance(unit.label, str)
  255. self.assertIsInstance(unit.current, (float, int, type(None)))
  256. @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
  257. def test_sensors_temperatures(self):
  258. # Duplicate of test_system.py. Keep it anyway.
  259. for name, units in psutil.sensors_temperatures().items():
  260. self.assertIsInstance(name, str)
  261. for unit in units:
  262. self.assertIsInstance(unit.label, str)
  263. self.assertIsInstance(unit.current, (float, int, type(None)))
  264. self.assertIsInstance(unit.high, (float, int, type(None)))
  265. self.assertIsInstance(unit.critical, (float, int, type(None)))
  266. def test_boot_time(self):
  267. # Duplicate of test_system.py. Keep it anyway.
  268. self.assertIsInstance(psutil.boot_time(), float)
  269. def test_users(self):
  270. # Duplicate of test_system.py. Keep it anyway.
  271. for user in psutil.users():
  272. self.assertIsInstance(user.name, str)
  273. self.assertIsInstance(user.terminal, (str, type(None)))
  274. self.assertIsInstance(user.host, (str, type(None)))
  275. self.assertIsInstance(user.pid, (int, type(None)))
  276. class TestProcessWaitType(PsutilTestCase):
  277. @unittest.skipIf(not POSIX, "not POSIX")
  278. def test_negative_signal(self):
  279. p = psutil.Process(self.spawn_testproc().pid)
  280. p.terminate()
  281. code = p.wait()
  282. self.assertEqual(code, -signal.SIGTERM)
  283. if enum is not None:
  284. self.assertIsInstance(code, enum.IntEnum)
  285. else:
  286. self.assertIsInstance(code, int)
  287. # ===================================================================
  288. # --- Featch all processes test
  289. # ===================================================================
  290. def proc_info(pid):
  291. tcase = PsutilTestCase()
  292. def check_exception(exc, proc, name, ppid):
  293. tcase.assertEqual(exc.pid, pid)
  294. tcase.assertEqual(exc.name, name)
  295. if isinstance(exc, psutil.ZombieProcess):
  296. tcase.assertProcessZombie(proc)
  297. if exc.ppid is not None:
  298. tcase.assertGreaterEqual(exc.ppid, 0)
  299. tcase.assertEqual(exc.ppid, ppid)
  300. elif isinstance(exc, psutil.NoSuchProcess):
  301. tcase.assertProcessGone(proc)
  302. str(exc)
  303. repr(exc)
  304. def do_wait():
  305. if pid != 0:
  306. try:
  307. proc.wait(0)
  308. except psutil.Error as exc:
  309. check_exception(exc, proc, name, ppid)
  310. try:
  311. proc = psutil.Process(pid)
  312. except psutil.NoSuchProcess:
  313. tcase.assertPidGone(pid)
  314. return {}
  315. try:
  316. d = proc.as_dict(['ppid', 'name'])
  317. except psutil.NoSuchProcess:
  318. tcase.assertProcessGone(proc)
  319. else:
  320. name, ppid = d['name'], d['ppid']
  321. info = {'pid': proc.pid}
  322. ns = process_namespace(proc)
  323. # We don't use oneshot() because in order not to fool
  324. # check_exception() in case of NSP.
  325. for fun, fun_name in ns.iter(ns.getters, clear_cache=False):
  326. try:
  327. info[fun_name] = fun()
  328. except psutil.Error as exc:
  329. check_exception(exc, proc, name, ppid)
  330. continue
  331. do_wait()
  332. return info
  333. @serialrun
  334. class TestFetchAllProcesses(PsutilTestCase):
  335. """Test which iterates over all running processes and performs
  336. some sanity checks against Process API's returned values.
  337. Uses a process pool to get info about all processes.
  338. """
  339. use_proc_pool = 0
  340. def setUp(self):
  341. # Using a pool in a CI env may result in deadlock, see:
  342. # https://github.com/giampaolo/psutil/issues/2104
  343. if self.use_proc_pool:
  344. self.pool = multiprocessing.Pool()
  345. def tearDown(self):
  346. if self.use_proc_pool:
  347. self.pool.terminate()
  348. self.pool.join()
  349. def iter_proc_info(self):
  350. # Fixes "can't pickle <function proc_info>: it's not the
  351. # same object as test_contracts.proc_info".
  352. from psutil.tests.test_contracts import proc_info
  353. if self.use_proc_pool:
  354. return self.pool.imap_unordered(proc_info, psutil.pids())
  355. else:
  356. ls = []
  357. for pid in psutil.pids():
  358. ls.append(proc_info(pid))
  359. return ls
  360. def test_all(self):
  361. failures = []
  362. for info in self.iter_proc_info():
  363. for name, value in info.items():
  364. meth = getattr(self, name)
  365. try:
  366. meth(value, info)
  367. except Exception:
  368. s = '\n' + '=' * 70 + '\n'
  369. s += "FAIL: name=test_%s, pid=%s, ret=%s\n" % (
  370. name, info['pid'], repr(value))
  371. s += '-' * 70
  372. s += "\n%s" % traceback.format_exc()
  373. s = "\n".join((" " * 4) + i for i in s.splitlines()) + "\n"
  374. failures.append(s)
  375. else:
  376. if value not in (0, 0.0, [], None, '', {}):
  377. assert value, value
  378. if failures:
  379. raise self.fail(''.join(failures))
  380. def cmdline(self, ret, info):
  381. self.assertIsInstance(ret, list)
  382. for part in ret:
  383. self.assertIsInstance(part, str)
  384. def exe(self, ret, info):
  385. self.assertIsInstance(ret, (str, unicode))
  386. self.assertEqual(ret.strip(), ret)
  387. if ret:
  388. if WINDOWS and not ret.endswith('.exe'):
  389. return # May be "Registry", "MemCompression", ...
  390. assert os.path.isabs(ret), ret
  391. # Note: os.stat() may return False even if the file is there
  392. # hence we skip the test, see:
  393. # http://stackoverflow.com/questions/3112546/os-path-exists-lies
  394. if POSIX and os.path.isfile(ret):
  395. if hasattr(os, 'access') and hasattr(os, "X_OK"):
  396. # XXX: may fail on MACOS
  397. try:
  398. assert os.access(ret, os.X_OK)
  399. except AssertionError:
  400. if os.path.exists(ret) and not CI_TESTING:
  401. raise
  402. def pid(self, ret, info):
  403. self.assertIsInstance(ret, int)
  404. self.assertGreaterEqual(ret, 0)
  405. def ppid(self, ret, info):
  406. self.assertIsInstance(ret, (int, long))
  407. self.assertGreaterEqual(ret, 0)
  408. proc_info(ret)
  409. def name(self, ret, info):
  410. self.assertIsInstance(ret, (str, unicode))
  411. if APPVEYOR and not ret and info['status'] == 'stopped':
  412. return
  413. # on AIX, "<exiting>" processes don't have names
  414. if not AIX:
  415. assert ret
  416. def create_time(self, ret, info):
  417. self.assertIsInstance(ret, float)
  418. try:
  419. self.assertGreaterEqual(ret, 0)
  420. except AssertionError:
  421. # XXX
  422. if OPENBSD and info['status'] == psutil.STATUS_ZOMBIE:
  423. pass
  424. else:
  425. raise
  426. # this can't be taken for granted on all platforms
  427. # self.assertGreaterEqual(ret, psutil.boot_time())
  428. # make sure returned value can be pretty printed
  429. # with strftime
  430. time.strftime("%Y %m %d %H:%M:%S", time.localtime(ret))
  431. def uids(self, ret, info):
  432. assert is_namedtuple(ret)
  433. for uid in ret:
  434. self.assertIsInstance(uid, int)
  435. self.assertGreaterEqual(uid, 0)
  436. def gids(self, ret, info):
  437. assert is_namedtuple(ret)
  438. # note: testing all gids as above seems not to be reliable for
  439. # gid == 30 (nodoby); not sure why.
  440. for gid in ret:
  441. self.assertIsInstance(gid, int)
  442. if not MACOS and not NETBSD:
  443. self.assertGreaterEqual(gid, 0)
  444. def username(self, ret, info):
  445. self.assertIsInstance(ret, str)
  446. self.assertEqual(ret.strip(), ret)
  447. assert ret.strip()
  448. def status(self, ret, info):
  449. self.assertIsInstance(ret, str)
  450. assert ret
  451. self.assertNotEqual(ret, '?') # XXX
  452. self.assertIn(ret, VALID_PROC_STATUSES)
  453. def io_counters(self, ret, info):
  454. assert is_namedtuple(ret)
  455. for field in ret:
  456. self.assertIsInstance(field, (int, long))
  457. if field != -1:
  458. self.assertGreaterEqual(field, 0)
  459. def ionice(self, ret, info):
  460. if LINUX:
  461. self.assertIsInstance(ret.ioclass, int)
  462. self.assertIsInstance(ret.value, int)
  463. self.assertGreaterEqual(ret.ioclass, 0)
  464. self.assertGreaterEqual(ret.value, 0)
  465. else: # Windows, Cygwin
  466. choices = [
  467. psutil.IOPRIO_VERYLOW,
  468. psutil.IOPRIO_LOW,
  469. psutil.IOPRIO_NORMAL,
  470. psutil.IOPRIO_HIGH]
  471. self.assertIsInstance(ret, int)
  472. self.assertGreaterEqual(ret, 0)
  473. self.assertIn(ret, choices)
  474. def num_threads(self, ret, info):
  475. self.assertIsInstance(ret, int)
  476. if APPVEYOR and not ret and info['status'] == 'stopped':
  477. return
  478. self.assertGreaterEqual(ret, 1)
  479. def threads(self, ret, info):
  480. self.assertIsInstance(ret, list)
  481. for t in ret:
  482. assert is_namedtuple(t)
  483. self.assertGreaterEqual(t.id, 0)
  484. self.assertGreaterEqual(t.user_time, 0)
  485. self.assertGreaterEqual(t.system_time, 0)
  486. for field in t:
  487. self.assertIsInstance(field, (int, float))
  488. def cpu_times(self, ret, info):
  489. assert is_namedtuple(ret)
  490. for n in ret:
  491. self.assertIsInstance(n, float)
  492. self.assertGreaterEqual(n, 0)
  493. # TODO: check ntuple fields
  494. def cpu_percent(self, ret, info):
  495. self.assertIsInstance(ret, float)
  496. assert 0.0 <= ret <= 100.0, ret
  497. def cpu_num(self, ret, info):
  498. self.assertIsInstance(ret, int)
  499. if FREEBSD and ret == -1:
  500. return
  501. self.assertGreaterEqual(ret, 0)
  502. if psutil.cpu_count() == 1:
  503. self.assertEqual(ret, 0)
  504. self.assertIn(ret, list(range(psutil.cpu_count())))
  505. def memory_info(self, ret, info):
  506. assert is_namedtuple(ret)
  507. for value in ret:
  508. self.assertIsInstance(value, (int, long))
  509. self.assertGreaterEqual(value, 0)
  510. if WINDOWS:
  511. self.assertGreaterEqual(ret.peak_wset, ret.wset)
  512. self.assertGreaterEqual(ret.peak_paged_pool, ret.paged_pool)
  513. self.assertGreaterEqual(ret.peak_nonpaged_pool, ret.nonpaged_pool)
  514. self.assertGreaterEqual(ret.peak_pagefile, ret.pagefile)
  515. def memory_full_info(self, ret, info):
  516. assert is_namedtuple(ret)
  517. total = psutil.virtual_memory().total
  518. for name in ret._fields:
  519. value = getattr(ret, name)
  520. self.assertIsInstance(value, (int, long))
  521. self.assertGreaterEqual(value, 0, msg=(name, value))
  522. if LINUX or OSX and name in ('vms', 'data'):
  523. # On Linux there are processes (e.g. 'goa-daemon') whose
  524. # VMS is incredibly high for some reason.
  525. continue
  526. self.assertLessEqual(value, total, msg=(name, value, total))
  527. if LINUX:
  528. self.assertGreaterEqual(ret.pss, ret.uss)
  529. def open_files(self, ret, info):
  530. self.assertIsInstance(ret, list)
  531. for f in ret:
  532. self.assertIsInstance(f.fd, int)
  533. self.assertIsInstance(f.path, str)
  534. self.assertEqual(f.path.strip(), f.path)
  535. if WINDOWS:
  536. self.assertEqual(f.fd, -1)
  537. elif LINUX:
  538. self.assertIsInstance(f.position, int)
  539. self.assertIsInstance(f.mode, str)
  540. self.assertIsInstance(f.flags, int)
  541. self.assertGreaterEqual(f.position, 0)
  542. self.assertIn(f.mode, ('r', 'w', 'a', 'r+', 'a+'))
  543. self.assertGreater(f.flags, 0)
  544. elif BSD and not f.path:
  545. # XXX see: https://github.com/giampaolo/psutil/issues/595
  546. continue
  547. assert os.path.isabs(f.path), f
  548. try:
  549. st = os.stat(f.path)
  550. except FileNotFoundError:
  551. pass
  552. else:
  553. assert stat.S_ISREG(st.st_mode), f
  554. def num_fds(self, ret, info):
  555. self.assertIsInstance(ret, int)
  556. self.assertGreaterEqual(ret, 0)
  557. def connections(self, ret, info):
  558. with create_sockets():
  559. self.assertEqual(len(ret), len(set(ret)))
  560. for conn in ret:
  561. assert is_namedtuple(conn)
  562. check_connection_ntuple(conn)
  563. def cwd(self, ret, info):
  564. self.assertIsInstance(ret, (str, unicode))
  565. self.assertEqual(ret.strip(), ret)
  566. if ret:
  567. assert os.path.isabs(ret), ret
  568. try:
  569. st = os.stat(ret)
  570. except OSError as err:
  571. if WINDOWS and psutil._psplatform.is_permission_err(err):
  572. pass
  573. # directory has been removed in mean time
  574. elif err.errno != errno.ENOENT:
  575. raise
  576. else:
  577. assert stat.S_ISDIR(st.st_mode)
  578. def memory_percent(self, ret, info):
  579. self.assertIsInstance(ret, float)
  580. assert 0 <= ret <= 100, ret
  581. def is_running(self, ret, info):
  582. self.assertIsInstance(ret, bool)
  583. def cpu_affinity(self, ret, info):
  584. self.assertIsInstance(ret, list)
  585. assert ret != [], ret
  586. cpus = list(range(psutil.cpu_count()))
  587. for n in ret:
  588. self.assertIsInstance(n, int)
  589. self.assertIn(n, cpus)
  590. def terminal(self, ret, info):
  591. self.assertIsInstance(ret, (str, type(None)))
  592. if ret is not None:
  593. assert os.path.isabs(ret), ret
  594. assert os.path.exists(ret), ret
  595. def memory_maps(self, ret, info):
  596. for nt in ret:
  597. self.assertIsInstance(nt.addr, str)
  598. self.assertIsInstance(nt.perms, str)
  599. self.assertIsInstance(nt.path, str)
  600. for fname in nt._fields:
  601. value = getattr(nt, fname)
  602. if fname == 'path':
  603. if not value.startswith(("[", "anon_inode:")):
  604. assert os.path.isabs(nt.path), nt.path
  605. # commented as on Linux we might get
  606. # '/foo/bar (deleted)'
  607. # assert os.path.exists(nt.path), nt.path
  608. elif fname == 'addr':
  609. assert value, repr(value)
  610. elif fname == 'perms':
  611. if not WINDOWS:
  612. assert value, repr(value)
  613. else:
  614. self.assertIsInstance(value, (int, long))
  615. self.assertGreaterEqual(value, 0)
  616. def num_handles(self, ret, info):
  617. self.assertIsInstance(ret, int)
  618. self.assertGreaterEqual(ret, 0)
  619. def nice(self, ret, info):
  620. self.assertIsInstance(ret, int)
  621. if POSIX:
  622. assert -20 <= ret <= 20, ret
  623. else:
  624. priorities = [getattr(psutil, x) for x in dir(psutil)
  625. if x.endswith('_PRIORITY_CLASS')]
  626. self.assertIn(ret, priorities)
  627. if PY3:
  628. self.assertIsInstance(ret, enum.IntEnum)
  629. else:
  630. self.assertIsInstance(ret, int)
  631. def num_ctx_switches(self, ret, info):
  632. assert is_namedtuple(ret)
  633. for value in ret:
  634. self.assertIsInstance(value, (int, long))
  635. self.assertGreaterEqual(value, 0)
  636. def rlimit(self, ret, info):
  637. self.assertIsInstance(ret, tuple)
  638. self.assertEqual(len(ret), 2)
  639. self.assertGreaterEqual(ret[0], -1)
  640. self.assertGreaterEqual(ret[1], -1)
  641. def environ(self, ret, info):
  642. self.assertIsInstance(ret, dict)
  643. for k, v in ret.items():
  644. self.assertIsInstance(k, str)
  645. self.assertIsInstance(v, str)
  646. if __name__ == '__main__':
  647. from psutil.tests.runner import run_from_name
  648. run_from_name(__file__)