test_misc.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  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. """Miscellaneous tests."""
  7. import ast
  8. import collections
  9. import errno
  10. import json
  11. import os
  12. import pickle
  13. import socket
  14. import stat
  15. import unittest
  16. import psutil
  17. import psutil.tests
  18. from psutil import LINUX
  19. from psutil import POSIX
  20. from psutil import WINDOWS
  21. from psutil._common import bcat
  22. from psutil._common import cat
  23. from psutil._common import debug
  24. from psutil._common import isfile_strict
  25. from psutil._common import memoize
  26. from psutil._common import memoize_when_activated
  27. from psutil._common import parse_environ_block
  28. from psutil._common import supports_ipv6
  29. from psutil._common import wrap_numbers
  30. from psutil._compat import PY3
  31. from psutil._compat import FileNotFoundError
  32. from psutil._compat import redirect_stderr
  33. from psutil.tests import APPVEYOR
  34. from psutil.tests import CI_TESTING
  35. from psutil.tests import HAS_BATTERY
  36. from psutil.tests import HAS_MEMORY_MAPS
  37. from psutil.tests import HAS_NET_IO_COUNTERS
  38. from psutil.tests import HAS_SENSORS_BATTERY
  39. from psutil.tests import HAS_SENSORS_FANS
  40. from psutil.tests import HAS_SENSORS_TEMPERATURES
  41. from psutil.tests import PYTHON_EXE
  42. from psutil.tests import PYTHON_EXE_ENV
  43. from psutil.tests import SCRIPTS_DIR
  44. from psutil.tests import PsutilTestCase
  45. from psutil.tests import mock
  46. from psutil.tests import reload_module
  47. from psutil.tests import sh
  48. # ===================================================================
  49. # --- Test classes' repr(), str(), ...
  50. # ===================================================================
  51. class TestSpecialMethods(PsutilTestCase):
  52. def test_check_pid_range(self):
  53. with self.assertRaises(OverflowError):
  54. psutil._psplatform.cext.check_pid_range(2 ** 128)
  55. with self.assertRaises(psutil.NoSuchProcess):
  56. psutil.Process(2 ** 128)
  57. def test_process__repr__(self, func=repr):
  58. p = psutil.Process(self.spawn_testproc().pid)
  59. r = func(p)
  60. self.assertIn("psutil.Process", r)
  61. self.assertIn("pid=%s" % p.pid, r)
  62. self.assertIn("name='%s'" % str(p.name()),
  63. r.replace("name=u'", "name='"))
  64. self.assertIn("status=", r)
  65. self.assertNotIn("exitcode=", r)
  66. p.terminate()
  67. p.wait()
  68. r = func(p)
  69. self.assertIn("status='terminated'", r)
  70. self.assertIn("exitcode=", r)
  71. with mock.patch.object(psutil.Process, "name",
  72. side_effect=psutil.ZombieProcess(os.getpid())):
  73. p = psutil.Process()
  74. r = func(p)
  75. self.assertIn("pid=%s" % p.pid, r)
  76. self.assertIn("status='zombie'", r)
  77. self.assertNotIn("name=", r)
  78. with mock.patch.object(psutil.Process, "name",
  79. side_effect=psutil.NoSuchProcess(os.getpid())):
  80. p = psutil.Process()
  81. r = func(p)
  82. self.assertIn("pid=%s" % p.pid, r)
  83. self.assertIn("terminated", r)
  84. self.assertNotIn("name=", r)
  85. with mock.patch.object(psutil.Process, "name",
  86. side_effect=psutil.AccessDenied(os.getpid())):
  87. p = psutil.Process()
  88. r = func(p)
  89. self.assertIn("pid=%s" % p.pid, r)
  90. self.assertNotIn("name=", r)
  91. def test_process__str__(self):
  92. self.test_process__repr__(func=str)
  93. def test_error__repr__(self):
  94. self.assertEqual(repr(psutil.Error()), "psutil.Error()")
  95. def test_error__str__(self):
  96. self.assertEqual(str(psutil.Error()), "")
  97. def test_no_such_process__repr__(self):
  98. self.assertEqual(
  99. repr(psutil.NoSuchProcess(321)),
  100. "psutil.NoSuchProcess(pid=321, msg='process no longer exists')")
  101. self.assertEqual(
  102. repr(psutil.NoSuchProcess(321, name="name", msg="msg")),
  103. "psutil.NoSuchProcess(pid=321, name='name', msg='msg')")
  104. def test_no_such_process__str__(self):
  105. self.assertEqual(
  106. str(psutil.NoSuchProcess(321)),
  107. "process no longer exists (pid=321)")
  108. self.assertEqual(
  109. str(psutil.NoSuchProcess(321, name="name", msg="msg")),
  110. "msg (pid=321, name='name')")
  111. def test_zombie_process__repr__(self):
  112. self.assertEqual(
  113. repr(psutil.ZombieProcess(321)),
  114. 'psutil.ZombieProcess(pid=321, msg="PID still '
  115. 'exists but it\'s a zombie")')
  116. self.assertEqual(
  117. repr(psutil.ZombieProcess(321, name="name", ppid=320, msg="foo")),
  118. "psutil.ZombieProcess(pid=321, ppid=320, name='name', msg='foo')")
  119. def test_zombie_process__str__(self):
  120. self.assertEqual(
  121. str(psutil.ZombieProcess(321)),
  122. "PID still exists but it's a zombie (pid=321)")
  123. self.assertEqual(
  124. str(psutil.ZombieProcess(321, name="name", ppid=320, msg="foo")),
  125. "foo (pid=321, ppid=320, name='name')")
  126. def test_access_denied__repr__(self):
  127. self.assertEqual(
  128. repr(psutil.AccessDenied(321)),
  129. "psutil.AccessDenied(pid=321)")
  130. self.assertEqual(
  131. repr(psutil.AccessDenied(321, name="name", msg="msg")),
  132. "psutil.AccessDenied(pid=321, name='name', msg='msg')")
  133. def test_access_denied__str__(self):
  134. self.assertEqual(
  135. str(psutil.AccessDenied(321)),
  136. "(pid=321)")
  137. self.assertEqual(
  138. str(psutil.AccessDenied(321, name="name", msg="msg")),
  139. "msg (pid=321, name='name')")
  140. def test_timeout_expired__repr__(self):
  141. self.assertEqual(
  142. repr(psutil.TimeoutExpired(5)),
  143. "psutil.TimeoutExpired(seconds=5, msg='timeout after 5 seconds')")
  144. self.assertEqual(
  145. repr(psutil.TimeoutExpired(5, pid=321, name="name")),
  146. "psutil.TimeoutExpired(pid=321, name='name', seconds=5, "
  147. "msg='timeout after 5 seconds')")
  148. def test_timeout_expired__str__(self):
  149. self.assertEqual(
  150. str(psutil.TimeoutExpired(5)),
  151. "timeout after 5 seconds")
  152. self.assertEqual(
  153. str(psutil.TimeoutExpired(5, pid=321, name="name")),
  154. "timeout after 5 seconds (pid=321, name='name')")
  155. def test_process__eq__(self):
  156. p1 = psutil.Process()
  157. p2 = psutil.Process()
  158. self.assertEqual(p1, p2)
  159. p2._ident = (0, 0)
  160. self.assertNotEqual(p1, p2)
  161. self.assertNotEqual(p1, 'foo')
  162. def test_process__hash__(self):
  163. s = set([psutil.Process(), psutil.Process()])
  164. self.assertEqual(len(s), 1)
  165. # ===================================================================
  166. # --- Misc, generic, corner cases
  167. # ===================================================================
  168. class TestMisc(PsutilTestCase):
  169. def test__all__(self):
  170. dir_psutil = dir(psutil)
  171. for name in dir_psutil:
  172. if name in ('long', 'tests', 'test', 'PermissionError',
  173. 'ProcessLookupError'):
  174. continue
  175. if not name.startswith('_'):
  176. try:
  177. __import__(name)
  178. except ImportError:
  179. if name not in psutil.__all__:
  180. fun = getattr(psutil, name)
  181. if fun is None:
  182. continue
  183. if (fun.__doc__ is not None and
  184. 'deprecated' not in fun.__doc__.lower()):
  185. raise self.fail('%r not in psutil.__all__' % name)
  186. # Import 'star' will break if __all__ is inconsistent, see:
  187. # https://github.com/giampaolo/psutil/issues/656
  188. # Can't do `from psutil import *` as it won't work on python 3
  189. # so we simply iterate over __all__.
  190. for name in psutil.__all__:
  191. self.assertIn(name, dir_psutil)
  192. def test_version(self):
  193. self.assertEqual('.'.join([str(x) for x in psutil.version_info]),
  194. psutil.__version__)
  195. def test_process_as_dict_no_new_names(self):
  196. # See https://github.com/giampaolo/psutil/issues/813
  197. p = psutil.Process()
  198. p.foo = '1'
  199. self.assertNotIn('foo', p.as_dict())
  200. def test_serialization(self):
  201. def check(ret):
  202. if json is not None:
  203. json.loads(json.dumps(ret))
  204. a = pickle.dumps(ret)
  205. b = pickle.loads(a)
  206. self.assertEqual(ret, b)
  207. check(psutil.Process().as_dict())
  208. check(psutil.virtual_memory())
  209. check(psutil.swap_memory())
  210. check(psutil.cpu_times())
  211. check(psutil.cpu_times_percent(interval=0))
  212. check(psutil.net_io_counters())
  213. if LINUX and not os.path.exists('/proc/diskstats'):
  214. pass
  215. else:
  216. if not APPVEYOR:
  217. check(psutil.disk_io_counters())
  218. check(psutil.disk_partitions())
  219. check(psutil.disk_usage(os.getcwd()))
  220. check(psutil.users())
  221. # # XXX: https://github.com/pypa/setuptools/pull/2896
  222. # @unittest.skipIf(APPVEYOR, "temporarily disabled due to setuptools bug")
  223. # def test_setup_script(self):
  224. # setup_py = os.path.join(ROOT_DIR, 'setup.py')
  225. # if CI_TESTING and not os.path.exists(setup_py):
  226. # return self.skipTest("can't find setup.py")
  227. # module = import_module_by_path(setup_py)
  228. # self.assertRaises(SystemExit, module.setup)
  229. # self.assertEqual(module.get_version(), psutil.__version__)
  230. def test_ad_on_process_creation(self):
  231. # We are supposed to be able to instantiate Process also in case
  232. # of zombie processes or access denied.
  233. with mock.patch.object(psutil.Process, 'create_time',
  234. side_effect=psutil.AccessDenied) as meth:
  235. psutil.Process()
  236. assert meth.called
  237. with mock.patch.object(psutil.Process, 'create_time',
  238. side_effect=psutil.ZombieProcess(1)) as meth:
  239. psutil.Process()
  240. assert meth.called
  241. with mock.patch.object(psutil.Process, 'create_time',
  242. side_effect=ValueError) as meth:
  243. with self.assertRaises(ValueError):
  244. psutil.Process()
  245. assert meth.called
  246. def test_sanity_version_check(self):
  247. # see: https://github.com/giampaolo/psutil/issues/564
  248. with mock.patch(
  249. "psutil._psplatform.cext.version", return_value="0.0.0"):
  250. with self.assertRaises(ImportError) as cm:
  251. reload_module(psutil)
  252. self.assertIn("version conflict", str(cm.exception).lower())
  253. # ===================================================================
  254. # --- psutil/_common.py utils
  255. # ===================================================================
  256. class TestMemoizeDecorator(PsutilTestCase):
  257. def setUp(self):
  258. self.calls = []
  259. tearDown = setUp
  260. def run_against(self, obj, expected_retval=None):
  261. # no args
  262. for _ in range(2):
  263. ret = obj()
  264. self.assertEqual(self.calls, [((), {})])
  265. if expected_retval is not None:
  266. self.assertEqual(ret, expected_retval)
  267. # with args
  268. for _ in range(2):
  269. ret = obj(1)
  270. self.assertEqual(self.calls, [((), {}), ((1, ), {})])
  271. if expected_retval is not None:
  272. self.assertEqual(ret, expected_retval)
  273. # with args + kwargs
  274. for _ in range(2):
  275. ret = obj(1, bar=2)
  276. self.assertEqual(
  277. self.calls, [((), {}), ((1, ), {}), ((1, ), {'bar': 2})])
  278. if expected_retval is not None:
  279. self.assertEqual(ret, expected_retval)
  280. # clear cache
  281. self.assertEqual(len(self.calls), 3)
  282. obj.cache_clear()
  283. ret = obj()
  284. if expected_retval is not None:
  285. self.assertEqual(ret, expected_retval)
  286. self.assertEqual(len(self.calls), 4)
  287. # docstring
  288. self.assertEqual(obj.__doc__, "My docstring.")
  289. def test_function(self):
  290. @memoize
  291. def foo(*args, **kwargs):
  292. """My docstring."""
  293. baseclass.calls.append((args, kwargs))
  294. return 22
  295. baseclass = self
  296. self.run_against(foo, expected_retval=22)
  297. def test_class(self):
  298. @memoize
  299. class Foo:
  300. """My docstring."""
  301. def __init__(self, *args, **kwargs):
  302. baseclass.calls.append((args, kwargs))
  303. def bar(self):
  304. return 22
  305. baseclass = self
  306. self.run_against(Foo, expected_retval=None)
  307. self.assertEqual(Foo().bar(), 22)
  308. def test_class_singleton(self):
  309. # @memoize can be used against classes to create singletons
  310. @memoize
  311. class Bar:
  312. def __init__(self, *args, **kwargs):
  313. pass
  314. self.assertIs(Bar(), Bar())
  315. self.assertEqual(id(Bar()), id(Bar()))
  316. self.assertEqual(id(Bar(1)), id(Bar(1)))
  317. self.assertEqual(id(Bar(1, foo=3)), id(Bar(1, foo=3)))
  318. self.assertNotEqual(id(Bar(1)), id(Bar(2)))
  319. def test_staticmethod(self):
  320. class Foo:
  321. @staticmethod
  322. @memoize
  323. def bar(*args, **kwargs):
  324. """My docstring."""
  325. baseclass.calls.append((args, kwargs))
  326. return 22
  327. baseclass = self
  328. self.run_against(Foo().bar, expected_retval=22)
  329. def test_classmethod(self):
  330. class Foo:
  331. @classmethod
  332. @memoize
  333. def bar(cls, *args, **kwargs):
  334. """My docstring."""
  335. baseclass.calls.append((args, kwargs))
  336. return 22
  337. baseclass = self
  338. self.run_against(Foo().bar, expected_retval=22)
  339. def test_original(self):
  340. # This was the original test before I made it dynamic to test it
  341. # against different types. Keeping it anyway.
  342. @memoize
  343. def foo(*args, **kwargs):
  344. """Foo docstring."""
  345. calls.append(None)
  346. return (args, kwargs)
  347. calls = []
  348. # no args
  349. for _ in range(2):
  350. ret = foo()
  351. expected = ((), {})
  352. self.assertEqual(ret, expected)
  353. self.assertEqual(len(calls), 1)
  354. # with args
  355. for _ in range(2):
  356. ret = foo(1)
  357. expected = ((1, ), {})
  358. self.assertEqual(ret, expected)
  359. self.assertEqual(len(calls), 2)
  360. # with args + kwargs
  361. for _ in range(2):
  362. ret = foo(1, bar=2)
  363. expected = ((1, ), {'bar': 2})
  364. self.assertEqual(ret, expected)
  365. self.assertEqual(len(calls), 3)
  366. # clear cache
  367. foo.cache_clear()
  368. ret = foo()
  369. expected = ((), {})
  370. self.assertEqual(ret, expected)
  371. self.assertEqual(len(calls), 4)
  372. # docstring
  373. self.assertEqual(foo.__doc__, "Foo docstring.")
  374. class TestCommonModule(PsutilTestCase):
  375. def test_memoize_when_activated(self):
  376. class Foo:
  377. @memoize_when_activated
  378. def foo(self):
  379. calls.append(None)
  380. f = Foo()
  381. calls = []
  382. f.foo()
  383. f.foo()
  384. self.assertEqual(len(calls), 2)
  385. # activate
  386. calls = []
  387. f.foo.cache_activate(f)
  388. f.foo()
  389. f.foo()
  390. self.assertEqual(len(calls), 1)
  391. # deactivate
  392. calls = []
  393. f.foo.cache_deactivate(f)
  394. f.foo()
  395. f.foo()
  396. self.assertEqual(len(calls), 2)
  397. def test_parse_environ_block(self):
  398. def k(s):
  399. return s.upper() if WINDOWS else s
  400. self.assertEqual(parse_environ_block("a=1\0"),
  401. {k("a"): "1"})
  402. self.assertEqual(parse_environ_block("a=1\0b=2\0\0"),
  403. {k("a"): "1", k("b"): "2"})
  404. self.assertEqual(parse_environ_block("a=1\0b=\0\0"),
  405. {k("a"): "1", k("b"): ""})
  406. # ignore everything after \0\0
  407. self.assertEqual(parse_environ_block("a=1\0b=2\0\0c=3\0"),
  408. {k("a"): "1", k("b"): "2"})
  409. # ignore everything that is not an assignment
  410. self.assertEqual(parse_environ_block("xxx\0a=1\0"), {k("a"): "1"})
  411. self.assertEqual(parse_environ_block("a=1\0=b=2\0"), {k("a"): "1"})
  412. # do not fail if the block is incomplete
  413. self.assertEqual(parse_environ_block("a=1\0b=2"), {k("a"): "1"})
  414. def test_supports_ipv6(self):
  415. self.addCleanup(supports_ipv6.cache_clear)
  416. if supports_ipv6():
  417. with mock.patch('psutil._common.socket') as s:
  418. s.has_ipv6 = False
  419. supports_ipv6.cache_clear()
  420. assert not supports_ipv6()
  421. supports_ipv6.cache_clear()
  422. with mock.patch('psutil._common.socket.socket',
  423. side_effect=socket.error) as s:
  424. assert not supports_ipv6()
  425. assert s.called
  426. supports_ipv6.cache_clear()
  427. with mock.patch('psutil._common.socket.socket',
  428. side_effect=socket.gaierror) as s:
  429. assert not supports_ipv6()
  430. supports_ipv6.cache_clear()
  431. assert s.called
  432. supports_ipv6.cache_clear()
  433. with mock.patch('psutil._common.socket.socket.bind',
  434. side_effect=socket.gaierror) as s:
  435. assert not supports_ipv6()
  436. supports_ipv6.cache_clear()
  437. assert s.called
  438. else:
  439. with self.assertRaises(socket.error):
  440. sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  441. try:
  442. sock.bind(("::1", 0))
  443. finally:
  444. sock.close()
  445. def test_isfile_strict(self):
  446. this_file = os.path.abspath(__file__)
  447. assert isfile_strict(this_file)
  448. assert not isfile_strict(os.path.dirname(this_file))
  449. with mock.patch('psutil._common.os.stat',
  450. side_effect=OSError(errno.EPERM, "foo")):
  451. self.assertRaises(OSError, isfile_strict, this_file)
  452. with mock.patch('psutil._common.os.stat',
  453. side_effect=OSError(errno.EACCES, "foo")):
  454. self.assertRaises(OSError, isfile_strict, this_file)
  455. with mock.patch('psutil._common.os.stat',
  456. side_effect=OSError(errno.ENOENT, "foo")):
  457. assert not isfile_strict(this_file)
  458. with mock.patch('psutil._common.stat.S_ISREG', return_value=False):
  459. assert not isfile_strict(this_file)
  460. def test_debug(self):
  461. if PY3:
  462. from io import StringIO
  463. else:
  464. from StringIO import StringIO
  465. with redirect_stderr(StringIO()) as f:
  466. debug("hello")
  467. msg = f.getvalue()
  468. assert msg.startswith("psutil-debug"), msg
  469. self.assertIn("hello", msg)
  470. self.assertIn(__file__.replace('.pyc', '.py'), msg)
  471. # supposed to use repr(exc)
  472. with redirect_stderr(StringIO()) as f:
  473. debug(ValueError("this is an error"))
  474. msg = f.getvalue()
  475. self.assertIn("ignoring ValueError", msg)
  476. self.assertIn("'this is an error'", msg)
  477. # supposed to use str(exc), because of extra info about file name
  478. with redirect_stderr(StringIO()) as f:
  479. exc = OSError(2, "no such file")
  480. exc.filename = "/foo"
  481. debug(exc)
  482. msg = f.getvalue()
  483. self.assertIn("no such file", msg)
  484. self.assertIn("/foo", msg)
  485. def test_cat_bcat(self):
  486. testfn = self.get_testfn()
  487. with open(testfn, "w") as f:
  488. f.write("foo")
  489. self.assertEqual(cat(testfn), "foo")
  490. self.assertEqual(bcat(testfn), b"foo")
  491. self.assertRaises(FileNotFoundError, cat, testfn + '-invalid')
  492. self.assertRaises(FileNotFoundError, bcat, testfn + '-invalid')
  493. self.assertEqual(cat(testfn + '-invalid', fallback="bar"), "bar")
  494. self.assertEqual(bcat(testfn + '-invalid', fallback="bar"), "bar")
  495. # ===================================================================
  496. # --- Tests for wrap_numbers() function.
  497. # ===================================================================
  498. nt = collections.namedtuple('foo', 'a b c')
  499. class TestWrapNumbers(PsutilTestCase):
  500. def setUp(self):
  501. wrap_numbers.cache_clear()
  502. tearDown = setUp
  503. def test_first_call(self):
  504. input = {'disk1': nt(5, 5, 5)}
  505. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  506. def test_input_hasnt_changed(self):
  507. input = {'disk1': nt(5, 5, 5)}
  508. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  509. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  510. def test_increase_but_no_wrap(self):
  511. input = {'disk1': nt(5, 5, 5)}
  512. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  513. input = {'disk1': nt(10, 15, 20)}
  514. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  515. input = {'disk1': nt(20, 25, 30)}
  516. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  517. input = {'disk1': nt(20, 25, 30)}
  518. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  519. def test_wrap(self):
  520. # let's say 100 is the threshold
  521. input = {'disk1': nt(100, 100, 100)}
  522. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  523. # first wrap restarts from 10
  524. input = {'disk1': nt(100, 100, 10)}
  525. self.assertEqual(wrap_numbers(input, 'disk_io'),
  526. {'disk1': nt(100, 100, 110)})
  527. # then it remains the same
  528. input = {'disk1': nt(100, 100, 10)}
  529. self.assertEqual(wrap_numbers(input, 'disk_io'),
  530. {'disk1': nt(100, 100, 110)})
  531. # then it goes up
  532. input = {'disk1': nt(100, 100, 90)}
  533. self.assertEqual(wrap_numbers(input, 'disk_io'),
  534. {'disk1': nt(100, 100, 190)})
  535. # then it wraps again
  536. input = {'disk1': nt(100, 100, 20)}
  537. self.assertEqual(wrap_numbers(input, 'disk_io'),
  538. {'disk1': nt(100, 100, 210)})
  539. # and remains the same
  540. input = {'disk1': nt(100, 100, 20)}
  541. self.assertEqual(wrap_numbers(input, 'disk_io'),
  542. {'disk1': nt(100, 100, 210)})
  543. # now wrap another num
  544. input = {'disk1': nt(50, 100, 20)}
  545. self.assertEqual(wrap_numbers(input, 'disk_io'),
  546. {'disk1': nt(150, 100, 210)})
  547. # and again
  548. input = {'disk1': nt(40, 100, 20)}
  549. self.assertEqual(wrap_numbers(input, 'disk_io'),
  550. {'disk1': nt(190, 100, 210)})
  551. # keep it the same
  552. input = {'disk1': nt(40, 100, 20)}
  553. self.assertEqual(wrap_numbers(input, 'disk_io'),
  554. {'disk1': nt(190, 100, 210)})
  555. def test_changing_keys(self):
  556. # Emulate a case where the second call to disk_io()
  557. # (or whatever) provides a new disk, then the new disk
  558. # disappears on the third call.
  559. input = {'disk1': nt(5, 5, 5)}
  560. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  561. input = {'disk1': nt(5, 5, 5),
  562. 'disk2': nt(7, 7, 7)}
  563. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  564. input = {'disk1': nt(8, 8, 8)}
  565. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  566. def test_changing_keys_w_wrap(self):
  567. input = {'disk1': nt(50, 50, 50),
  568. 'disk2': nt(100, 100, 100)}
  569. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  570. # disk 2 wraps
  571. input = {'disk1': nt(50, 50, 50),
  572. 'disk2': nt(100, 100, 10)}
  573. self.assertEqual(wrap_numbers(input, 'disk_io'),
  574. {'disk1': nt(50, 50, 50),
  575. 'disk2': nt(100, 100, 110)})
  576. # disk 2 disappears
  577. input = {'disk1': nt(50, 50, 50)}
  578. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  579. # then it appears again; the old wrap is supposed to be
  580. # gone.
  581. input = {'disk1': nt(50, 50, 50),
  582. 'disk2': nt(100, 100, 100)}
  583. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  584. # remains the same
  585. input = {'disk1': nt(50, 50, 50),
  586. 'disk2': nt(100, 100, 100)}
  587. self.assertEqual(wrap_numbers(input, 'disk_io'), input)
  588. # and then wraps again
  589. input = {'disk1': nt(50, 50, 50),
  590. 'disk2': nt(100, 100, 10)}
  591. self.assertEqual(wrap_numbers(input, 'disk_io'),
  592. {'disk1': nt(50, 50, 50),
  593. 'disk2': nt(100, 100, 110)})
  594. def test_real_data(self):
  595. d = {'nvme0n1': (300, 508, 640, 1571, 5970, 1987, 2049, 451751, 47048),
  596. 'nvme0n1p1': (1171, 2, 5600256, 1024, 516, 0, 0, 0, 8),
  597. 'nvme0n1p2': (54, 54, 2396160, 5165056, 4, 24, 30, 1207, 28),
  598. 'nvme0n1p3': (2389, 4539, 5154, 150, 4828, 1844, 2019, 398, 348)}
  599. self.assertEqual(wrap_numbers(d, 'disk_io'), d)
  600. self.assertEqual(wrap_numbers(d, 'disk_io'), d)
  601. # decrease this ↓
  602. d = {'nvme0n1': (100, 508, 640, 1571, 5970, 1987, 2049, 451751, 47048),
  603. 'nvme0n1p1': (1171, 2, 5600256, 1024, 516, 0, 0, 0, 8),
  604. 'nvme0n1p2': (54, 54, 2396160, 5165056, 4, 24, 30, 1207, 28),
  605. 'nvme0n1p3': (2389, 4539, 5154, 150, 4828, 1844, 2019, 398, 348)}
  606. out = wrap_numbers(d, 'disk_io')
  607. self.assertEqual(out['nvme0n1'][0], 400)
  608. # --- cache tests
  609. def test_cache_first_call(self):
  610. input = {'disk1': nt(5, 5, 5)}
  611. wrap_numbers(input, 'disk_io')
  612. cache = wrap_numbers.cache_info()
  613. self.assertEqual(cache[0], {'disk_io': input})
  614. self.assertEqual(cache[1], {'disk_io': {}})
  615. self.assertEqual(cache[2], {'disk_io': {}})
  616. def test_cache_call_twice(self):
  617. input = {'disk1': nt(5, 5, 5)}
  618. wrap_numbers(input, 'disk_io')
  619. input = {'disk1': nt(10, 10, 10)}
  620. wrap_numbers(input, 'disk_io')
  621. cache = wrap_numbers.cache_info()
  622. self.assertEqual(cache[0], {'disk_io': input})
  623. self.assertEqual(
  624. cache[1],
  625. {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 0}})
  626. self.assertEqual(cache[2], {'disk_io': {}})
  627. def test_cache_wrap(self):
  628. # let's say 100 is the threshold
  629. input = {'disk1': nt(100, 100, 100)}
  630. wrap_numbers(input, 'disk_io')
  631. # first wrap restarts from 10
  632. input = {'disk1': nt(100, 100, 10)}
  633. wrap_numbers(input, 'disk_io')
  634. cache = wrap_numbers.cache_info()
  635. self.assertEqual(cache[0], {'disk_io': input})
  636. self.assertEqual(
  637. cache[1],
  638. {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 100}})
  639. self.assertEqual(cache[2], {'disk_io': {'disk1': set([('disk1', 2)])}})
  640. def check_cache_info():
  641. cache = wrap_numbers.cache_info()
  642. self.assertEqual(
  643. cache[1],
  644. {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0,
  645. ('disk1', 2): 100}})
  646. self.assertEqual(cache[2],
  647. {'disk_io': {'disk1': set([('disk1', 2)])}})
  648. # then it remains the same
  649. input = {'disk1': nt(100, 100, 10)}
  650. wrap_numbers(input, 'disk_io')
  651. cache = wrap_numbers.cache_info()
  652. self.assertEqual(cache[0], {'disk_io': input})
  653. check_cache_info()
  654. # then it goes up
  655. input = {'disk1': nt(100, 100, 90)}
  656. wrap_numbers(input, 'disk_io')
  657. cache = wrap_numbers.cache_info()
  658. self.assertEqual(cache[0], {'disk_io': input})
  659. check_cache_info()
  660. # then it wraps again
  661. input = {'disk1': nt(100, 100, 20)}
  662. wrap_numbers(input, 'disk_io')
  663. cache = wrap_numbers.cache_info()
  664. self.assertEqual(cache[0], {'disk_io': input})
  665. self.assertEqual(
  666. cache[1],
  667. {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 190}})
  668. self.assertEqual(cache[2], {'disk_io': {'disk1': set([('disk1', 2)])}})
  669. def test_cache_changing_keys(self):
  670. input = {'disk1': nt(5, 5, 5)}
  671. wrap_numbers(input, 'disk_io')
  672. input = {'disk1': nt(5, 5, 5),
  673. 'disk2': nt(7, 7, 7)}
  674. wrap_numbers(input, 'disk_io')
  675. cache = wrap_numbers.cache_info()
  676. self.assertEqual(cache[0], {'disk_io': input})
  677. self.assertEqual(
  678. cache[1],
  679. {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 0}})
  680. self.assertEqual(cache[2], {'disk_io': {}})
  681. def test_cache_clear(self):
  682. input = {'disk1': nt(5, 5, 5)}
  683. wrap_numbers(input, 'disk_io')
  684. wrap_numbers(input, 'disk_io')
  685. wrap_numbers.cache_clear('disk_io')
  686. self.assertEqual(wrap_numbers.cache_info(), ({}, {}, {}))
  687. wrap_numbers.cache_clear('disk_io')
  688. wrap_numbers.cache_clear('?!?')
  689. @unittest.skipIf(not HAS_NET_IO_COUNTERS, 'not supported')
  690. def test_cache_clear_public_apis(self):
  691. if not psutil.disk_io_counters() or not psutil.net_io_counters():
  692. return self.skipTest("no disks or NICs available")
  693. psutil.disk_io_counters()
  694. psutil.net_io_counters()
  695. caches = wrap_numbers.cache_info()
  696. for cache in caches:
  697. self.assertIn('psutil.disk_io_counters', cache)
  698. self.assertIn('psutil.net_io_counters', cache)
  699. psutil.disk_io_counters.cache_clear()
  700. caches = wrap_numbers.cache_info()
  701. for cache in caches:
  702. self.assertIn('psutil.net_io_counters', cache)
  703. self.assertNotIn('psutil.disk_io_counters', cache)
  704. psutil.net_io_counters.cache_clear()
  705. caches = wrap_numbers.cache_info()
  706. self.assertEqual(caches, ({}, {}, {}))
  707. # ===================================================================
  708. # --- Example script tests
  709. # ===================================================================
  710. @unittest.skipIf(not os.path.exists(SCRIPTS_DIR),
  711. "can't locate scripts directory")
  712. class TestScripts(PsutilTestCase):
  713. """Tests for scripts in the "scripts" directory."""
  714. @staticmethod
  715. def assert_stdout(exe, *args, **kwargs):
  716. kwargs.setdefault("env", PYTHON_EXE_ENV)
  717. exe = '%s' % os.path.join(SCRIPTS_DIR, exe)
  718. cmd = [PYTHON_EXE, exe]
  719. for arg in args:
  720. cmd.append(arg)
  721. try:
  722. out = sh(cmd, **kwargs).strip()
  723. except RuntimeError as err:
  724. if 'AccessDenied' in str(err):
  725. return str(err)
  726. else:
  727. raise
  728. assert out, out
  729. return out
  730. @staticmethod
  731. def assert_syntax(exe):
  732. exe = os.path.join(SCRIPTS_DIR, exe)
  733. with open(exe, encoding="utf8") if PY3 else open(exe) as f:
  734. src = f.read()
  735. ast.parse(src)
  736. def test_coverage(self):
  737. # make sure all example scripts have a test method defined
  738. meths = dir(self)
  739. for name in os.listdir(SCRIPTS_DIR):
  740. if name.endswith('.py'):
  741. if 'test_' + os.path.splitext(name)[0] not in meths:
  742. # self.assert_stdout(name)
  743. raise self.fail('no test defined for %r script'
  744. % os.path.join(SCRIPTS_DIR, name))
  745. @unittest.skipIf(not POSIX, "POSIX only")
  746. def test_executable(self):
  747. for root, dirs, files in os.walk(SCRIPTS_DIR):
  748. for file in files:
  749. if file.endswith('.py'):
  750. path = os.path.join(root, file)
  751. if not stat.S_IXUSR & os.stat(path)[stat.ST_MODE]:
  752. raise self.fail('%r is not executable' % path)
  753. def test_disk_usage(self):
  754. self.assert_stdout('disk_usage.py')
  755. def test_free(self):
  756. self.assert_stdout('free.py')
  757. def test_meminfo(self):
  758. self.assert_stdout('meminfo.py')
  759. def test_procinfo(self):
  760. self.assert_stdout('procinfo.py', str(os.getpid()))
  761. @unittest.skipIf(CI_TESTING and not psutil.users(), "no users")
  762. def test_who(self):
  763. self.assert_stdout('who.py')
  764. def test_ps(self):
  765. self.assert_stdout('ps.py')
  766. def test_pstree(self):
  767. self.assert_stdout('pstree.py')
  768. def test_netstat(self):
  769. self.assert_stdout('netstat.py')
  770. def test_ifconfig(self):
  771. self.assert_stdout('ifconfig.py')
  772. @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
  773. def test_pmap(self):
  774. self.assert_stdout('pmap.py', str(os.getpid()))
  775. def test_procsmem(self):
  776. if 'uss' not in psutil.Process().memory_full_info()._fields:
  777. raise self.skipTest("not supported")
  778. self.assert_stdout('procsmem.py')
  779. def test_killall(self):
  780. self.assert_syntax('killall.py')
  781. def test_nettop(self):
  782. self.assert_syntax('nettop.py')
  783. def test_top(self):
  784. self.assert_syntax('top.py')
  785. def test_iotop(self):
  786. self.assert_syntax('iotop.py')
  787. def test_pidof(self):
  788. output = self.assert_stdout('pidof.py', psutil.Process().name())
  789. self.assertIn(str(os.getpid()), output)
  790. @unittest.skipIf(not WINDOWS, "WINDOWS only")
  791. def test_winservices(self):
  792. self.assert_stdout('winservices.py')
  793. def test_cpu_distribution(self):
  794. self.assert_syntax('cpu_distribution.py')
  795. @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
  796. def test_temperatures(self):
  797. if not psutil.sensors_temperatures():
  798. self.skipTest("no temperatures")
  799. self.assert_stdout('temperatures.py')
  800. @unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
  801. def test_fans(self):
  802. if not psutil.sensors_fans():
  803. self.skipTest("no fans")
  804. self.assert_stdout('fans.py')
  805. @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported")
  806. @unittest.skipIf(not HAS_BATTERY, "no battery")
  807. def test_battery(self):
  808. self.assert_stdout('battery.py')
  809. @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported")
  810. @unittest.skipIf(not HAS_BATTERY, "no battery")
  811. def test_sensors(self):
  812. self.assert_stdout('sensors.py')
  813. if __name__ == '__main__':
  814. from psutil.tests.runner import run_from_name
  815. run_from_name(__file__)