test_contracts.py 26 KB

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