test_misc.py 29 KB

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