test_testutils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. """Tests for testing utils (psutil.tests namespace)."""
  6. import collections
  7. import errno
  8. import os
  9. import socket
  10. import stat
  11. import subprocess
  12. import textwrap
  13. import unittest
  14. import warnings
  15. from unittest import mock
  16. import psutil
  17. import psutil.tests
  18. from psutil import FREEBSD
  19. from psutil import NETBSD
  20. from psutil import POSIX
  21. from psutil._common import open_binary
  22. from psutil._common import open_text
  23. from psutil._common import supports_ipv6
  24. from psutil.tests import CI_TESTING
  25. from psutil.tests import COVERAGE
  26. from psutil.tests import HAS_NET_CONNECTIONS_UNIX
  27. from psutil.tests import HERE
  28. from psutil.tests import PYTHON_EXE
  29. from psutil.tests import PYTHON_EXE_ENV
  30. from psutil.tests import PsutilTestCase
  31. from psutil.tests import TestMemoryLeak
  32. from psutil.tests import bind_socket
  33. from psutil.tests import bind_unix_socket
  34. from psutil.tests import call_until
  35. from psutil.tests import chdir
  36. from psutil.tests import create_sockets
  37. from psutil.tests import fake_pytest
  38. from psutil.tests import filter_proc_net_connections
  39. from psutil.tests import get_free_port
  40. from psutil.tests import is_namedtuple
  41. from psutil.tests import process_namespace
  42. from psutil.tests import pytest
  43. from psutil.tests import reap_children
  44. from psutil.tests import retry
  45. from psutil.tests import retry_on_failure
  46. from psutil.tests import safe_mkdir
  47. from psutil.tests import safe_rmpath
  48. from psutil.tests import system_namespace
  49. from psutil.tests import tcp_socketpair
  50. from psutil.tests import terminate
  51. from psutil.tests import unix_socketpair
  52. from psutil.tests import wait_for_file
  53. from psutil.tests import wait_for_pid
  54. # ===================================================================
  55. # --- Unit tests for test utilities.
  56. # ===================================================================
  57. class TestRetryDecorator(PsutilTestCase):
  58. @mock.patch('time.sleep')
  59. def test_retry_success(self, sleep):
  60. # Fail 3 times out of 5; make sure the decorated fun returns.
  61. @retry(retries=5, interval=1, logfun=None)
  62. def foo():
  63. while queue:
  64. queue.pop()
  65. 1 / 0 # noqa: B018
  66. return 1
  67. queue = list(range(3))
  68. assert foo() == 1
  69. assert sleep.call_count == 3
  70. @mock.patch('time.sleep')
  71. def test_retry_failure(self, sleep):
  72. # Fail 6 times out of 5; th function is supposed to raise exc.
  73. @retry(retries=5, interval=1, logfun=None)
  74. def foo():
  75. while queue:
  76. queue.pop()
  77. 1 / 0 # noqa: B018
  78. return 1
  79. queue = list(range(6))
  80. with pytest.raises(ZeroDivisionError):
  81. foo()
  82. assert sleep.call_count == 5
  83. @mock.patch('time.sleep')
  84. def test_exception_arg(self, sleep):
  85. @retry(exception=ValueError, interval=1)
  86. def foo():
  87. raise TypeError
  88. with pytest.raises(TypeError):
  89. foo()
  90. assert sleep.call_count == 0
  91. @mock.patch('time.sleep')
  92. def test_no_interval_arg(self, sleep):
  93. # if interval is not specified sleep is not supposed to be called
  94. @retry(retries=5, interval=None, logfun=None)
  95. def foo():
  96. 1 / 0 # noqa: B018
  97. with pytest.raises(ZeroDivisionError):
  98. foo()
  99. assert sleep.call_count == 0
  100. @mock.patch('time.sleep')
  101. def test_retries_arg(self, sleep):
  102. @retry(retries=5, interval=1, logfun=None)
  103. def foo():
  104. 1 / 0 # noqa: B018
  105. with pytest.raises(ZeroDivisionError):
  106. foo()
  107. assert sleep.call_count == 5
  108. @mock.patch('time.sleep')
  109. def test_retries_and_timeout_args(self, sleep):
  110. with pytest.raises(ValueError):
  111. retry(retries=5, timeout=1)
  112. class TestSyncTestUtils(PsutilTestCase):
  113. def test_wait_for_pid(self):
  114. wait_for_pid(os.getpid())
  115. nopid = max(psutil.pids()) + 99999
  116. with mock.patch('psutil.tests.retry.__iter__', return_value=iter([0])):
  117. with pytest.raises(psutil.NoSuchProcess):
  118. wait_for_pid(nopid)
  119. def test_wait_for_file(self):
  120. testfn = self.get_testfn()
  121. with open(testfn, 'w') as f:
  122. f.write('foo')
  123. wait_for_file(testfn)
  124. assert not os.path.exists(testfn)
  125. def test_wait_for_file_empty(self):
  126. testfn = self.get_testfn()
  127. with open(testfn, 'w'):
  128. pass
  129. wait_for_file(testfn, empty=True)
  130. assert not os.path.exists(testfn)
  131. def test_wait_for_file_no_file(self):
  132. testfn = self.get_testfn()
  133. with mock.patch('psutil.tests.retry.__iter__', return_value=iter([0])):
  134. with pytest.raises(OSError):
  135. wait_for_file(testfn)
  136. def test_wait_for_file_no_delete(self):
  137. testfn = self.get_testfn()
  138. with open(testfn, 'w') as f:
  139. f.write('foo')
  140. wait_for_file(testfn, delete=False)
  141. assert os.path.exists(testfn)
  142. def test_call_until(self):
  143. call_until(lambda: 1)
  144. # TODO: test for timeout
  145. class TestFSTestUtils(PsutilTestCase):
  146. def test_open_text(self):
  147. with open_text(__file__) as f:
  148. assert f.mode == 'r'
  149. def test_open_binary(self):
  150. with open_binary(__file__) as f:
  151. assert f.mode == 'rb'
  152. def test_safe_mkdir(self):
  153. testfn = self.get_testfn()
  154. safe_mkdir(testfn)
  155. assert os.path.isdir(testfn)
  156. safe_mkdir(testfn)
  157. assert os.path.isdir(testfn)
  158. def test_safe_rmpath(self):
  159. # test file is removed
  160. testfn = self.get_testfn()
  161. open(testfn, 'w').close()
  162. safe_rmpath(testfn)
  163. assert not os.path.exists(testfn)
  164. # test no exception if path does not exist
  165. safe_rmpath(testfn)
  166. # test dir is removed
  167. os.mkdir(testfn)
  168. safe_rmpath(testfn)
  169. assert not os.path.exists(testfn)
  170. # test other exceptions are raised
  171. with mock.patch(
  172. 'psutil.tests.os.stat', side_effect=OSError(errno.EINVAL, "")
  173. ) as m:
  174. with pytest.raises(OSError):
  175. safe_rmpath(testfn)
  176. assert m.called
  177. def test_chdir(self):
  178. testfn = self.get_testfn()
  179. base = os.getcwd()
  180. os.mkdir(testfn)
  181. with chdir(testfn):
  182. assert os.getcwd() == os.path.join(base, testfn)
  183. assert os.getcwd() == base
  184. class TestProcessUtils(PsutilTestCase):
  185. def test_reap_children(self):
  186. subp = self.spawn_testproc()
  187. p = psutil.Process(subp.pid)
  188. assert p.is_running()
  189. reap_children()
  190. assert not p.is_running()
  191. assert not psutil.tests._pids_started
  192. assert not psutil.tests._subprocesses_started
  193. def test_spawn_children_pair(self):
  194. child, grandchild = self.spawn_children_pair()
  195. assert child.pid != grandchild.pid
  196. assert child.is_running()
  197. assert grandchild.is_running()
  198. children = psutil.Process().children()
  199. assert children == [child]
  200. children = psutil.Process().children(recursive=True)
  201. assert len(children) == 2
  202. assert child in children
  203. assert grandchild in children
  204. assert child.ppid() == os.getpid()
  205. assert grandchild.ppid() == child.pid
  206. terminate(child)
  207. assert not child.is_running()
  208. assert grandchild.is_running()
  209. terminate(grandchild)
  210. assert not grandchild.is_running()
  211. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  212. def test_spawn_zombie(self):
  213. _parent, zombie = self.spawn_zombie()
  214. assert zombie.status() == psutil.STATUS_ZOMBIE
  215. def test_terminate(self):
  216. # by subprocess.Popen
  217. p = self.spawn_testproc()
  218. terminate(p)
  219. self.assertPidGone(p.pid)
  220. terminate(p)
  221. # by psutil.Process
  222. p = psutil.Process(self.spawn_testproc().pid)
  223. terminate(p)
  224. self.assertPidGone(p.pid)
  225. terminate(p)
  226. # by psutil.Popen
  227. cmd = [
  228. PYTHON_EXE,
  229. "-c",
  230. "import time; [time.sleep(0.1) for x in range(100)];",
  231. ]
  232. p = psutil.Popen(
  233. cmd,
  234. stdout=subprocess.PIPE,
  235. stderr=subprocess.PIPE,
  236. env=PYTHON_EXE_ENV,
  237. )
  238. terminate(p)
  239. self.assertPidGone(p.pid)
  240. terminate(p)
  241. # by PID
  242. pid = self.spawn_testproc().pid
  243. terminate(pid)
  244. self.assertPidGone(p.pid)
  245. terminate(pid)
  246. # zombie
  247. if POSIX:
  248. parent, zombie = self.spawn_zombie()
  249. terminate(parent)
  250. terminate(zombie)
  251. self.assertPidGone(parent.pid)
  252. self.assertPidGone(zombie.pid)
  253. class TestNetUtils(PsutilTestCase):
  254. def bind_socket(self):
  255. port = get_free_port()
  256. with bind_socket(addr=('', port)) as s:
  257. assert s.getsockname()[1] == port
  258. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  259. def test_bind_unix_socket(self):
  260. name = self.get_testfn()
  261. with bind_unix_socket(name) as sock:
  262. assert sock.family == socket.AF_UNIX
  263. assert sock.type == socket.SOCK_STREAM
  264. assert sock.getsockname() == name
  265. assert os.path.exists(name)
  266. assert stat.S_ISSOCK(os.stat(name).st_mode)
  267. # UDP
  268. name = self.get_testfn()
  269. with bind_unix_socket(name, type=socket.SOCK_DGRAM) as sock:
  270. assert sock.type == socket.SOCK_DGRAM
  271. def test_tcp_socketpair(self):
  272. addr = ("127.0.0.1", get_free_port())
  273. server, client = tcp_socketpair(socket.AF_INET, addr=addr)
  274. with server, client:
  275. # Ensure they are connected and the positions are correct.
  276. assert server.getsockname() == addr
  277. assert client.getpeername() == addr
  278. assert client.getsockname() != addr
  279. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  280. @pytest.mark.skipif(
  281. NETBSD or FREEBSD, reason="/var/run/log UNIX socket opened by default"
  282. )
  283. def test_unix_socketpair(self):
  284. p = psutil.Process()
  285. num_fds = p.num_fds()
  286. assert not filter_proc_net_connections(p.net_connections(kind='unix'))
  287. name = self.get_testfn()
  288. server, client = unix_socketpair(name)
  289. try:
  290. assert os.path.exists(name)
  291. assert stat.S_ISSOCK(os.stat(name).st_mode)
  292. assert p.num_fds() - num_fds == 2
  293. assert (
  294. len(
  295. filter_proc_net_connections(p.net_connections(kind='unix'))
  296. )
  297. == 2
  298. )
  299. assert server.getsockname() == name
  300. assert client.getpeername() == name
  301. finally:
  302. client.close()
  303. server.close()
  304. def test_create_sockets(self):
  305. with create_sockets() as socks:
  306. fams = collections.defaultdict(int)
  307. types = collections.defaultdict(int)
  308. for s in socks:
  309. fams[s.family] += 1
  310. # work around http://bugs.python.org/issue30204
  311. types[s.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)] += 1
  312. assert fams[socket.AF_INET] >= 2
  313. if supports_ipv6():
  314. assert fams[socket.AF_INET6] >= 2
  315. if POSIX and HAS_NET_CONNECTIONS_UNIX:
  316. assert fams[socket.AF_UNIX] >= 2
  317. assert types[socket.SOCK_STREAM] >= 2
  318. assert types[socket.SOCK_DGRAM] >= 2
  319. @pytest.mark.xdist_group(name="serial")
  320. class TestMemLeakClass(TestMemoryLeak):
  321. @retry_on_failure()
  322. def test_times(self):
  323. def fun():
  324. cnt['cnt'] += 1
  325. cnt = {'cnt': 0}
  326. self.execute(fun, times=10, warmup_times=15)
  327. assert cnt['cnt'] == 26
  328. def test_param_err(self):
  329. with pytest.raises(ValueError):
  330. self.execute(lambda: 0, times=0)
  331. with pytest.raises(ValueError):
  332. self.execute(lambda: 0, times=-1)
  333. with pytest.raises(ValueError):
  334. self.execute(lambda: 0, warmup_times=-1)
  335. with pytest.raises(ValueError):
  336. self.execute(lambda: 0, tolerance=-1)
  337. with pytest.raises(ValueError):
  338. self.execute(lambda: 0, retries=-1)
  339. @retry_on_failure()
  340. @pytest.mark.skipif(CI_TESTING, reason="skipped on CI")
  341. @pytest.mark.skipif(COVERAGE, reason="skipped during test coverage")
  342. def test_leak_mem(self):
  343. ls = []
  344. def fun(ls=ls):
  345. ls.append("x" * 248 * 1024)
  346. try:
  347. # will consume around 60M in total
  348. with pytest.raises(AssertionError, match="extra-mem"):
  349. self.execute(fun, times=100)
  350. finally:
  351. del ls
  352. def test_unclosed_files(self):
  353. def fun():
  354. f = open(__file__) # noqa: SIM115
  355. self.addCleanup(f.close)
  356. box.append(f)
  357. box = []
  358. kind = "fd" if POSIX else "handle"
  359. with pytest.raises(AssertionError, match="unclosed " + kind):
  360. self.execute(fun)
  361. def test_tolerance(self):
  362. def fun():
  363. ls.append("x" * 24 * 1024)
  364. ls = []
  365. times = 100
  366. self.execute(
  367. fun, times=times, warmup_times=0, tolerance=200 * 1024 * 1024
  368. )
  369. assert len(ls) == times + 1
  370. def test_execute_w_exc(self):
  371. def fun_1():
  372. 1 / 0 # noqa: B018
  373. self.execute_w_exc(ZeroDivisionError, fun_1)
  374. with pytest.raises(ZeroDivisionError):
  375. self.execute_w_exc(OSError, fun_1)
  376. def fun_2():
  377. pass
  378. with pytest.raises(AssertionError):
  379. self.execute_w_exc(ZeroDivisionError, fun_2)
  380. class TestFakePytest(PsutilTestCase):
  381. def run_test_class(self, klass):
  382. suite = unittest.TestSuite()
  383. suite.addTest(klass)
  384. runner = unittest.TextTestRunner()
  385. result = runner.run(suite)
  386. return result
  387. def test_raises(self):
  388. with fake_pytest.raises(ZeroDivisionError) as cm:
  389. 1 / 0 # noqa: B018
  390. assert isinstance(cm.value, ZeroDivisionError)
  391. with fake_pytest.raises(ValueError, match="foo") as cm:
  392. raise ValueError("foo")
  393. try:
  394. with fake_pytest.raises(ValueError, match="foo") as cm:
  395. raise ValueError("bar")
  396. except AssertionError as err:
  397. assert str(err) == '"foo" does not match "bar"'
  398. else:
  399. raise self.fail("exception not raised")
  400. def test_mark(self):
  401. @fake_pytest.mark.xdist_group(name="serial")
  402. def foo():
  403. return 1
  404. assert foo() == 1
  405. @fake_pytest.mark.xdist_group(name="serial")
  406. class Foo:
  407. def bar(self):
  408. return 1
  409. assert Foo().bar() == 1
  410. def test_skipif(self):
  411. class TestCase(unittest.TestCase):
  412. @fake_pytest.mark.skipif(True, reason="reason")
  413. def foo(self):
  414. assert 1 == 1 # noqa: PLR0133
  415. result = self.run_test_class(TestCase("foo"))
  416. assert result.wasSuccessful()
  417. assert len(result.skipped) == 1
  418. assert result.skipped[0][1] == "reason"
  419. class TestCase(unittest.TestCase):
  420. @fake_pytest.mark.skipif(False, reason="reason")
  421. def foo(self):
  422. assert 1 == 1 # noqa: PLR0133
  423. result = self.run_test_class(TestCase("foo"))
  424. assert result.wasSuccessful()
  425. assert len(result.skipped) == 0
  426. def test_skip(self):
  427. class TestCase(unittest.TestCase):
  428. def foo(self):
  429. fake_pytest.skip("reason")
  430. assert 1 == 0 # noqa: PLR0133
  431. result = self.run_test_class(TestCase("foo"))
  432. assert result.wasSuccessful()
  433. assert len(result.skipped) == 1
  434. assert result.skipped[0][1] == "reason"
  435. def test_main(self):
  436. tmpdir = self.get_testfn(dir=HERE)
  437. os.mkdir(tmpdir)
  438. with open(os.path.join(tmpdir, "__init__.py"), "w"):
  439. pass
  440. with open(os.path.join(tmpdir, "test_file.py"), "w") as f:
  441. f.write(textwrap.dedent("""\
  442. import unittest
  443. class TestCase(unittest.TestCase):
  444. def test_passed(self):
  445. pass
  446. """).lstrip())
  447. with mock.patch.object(psutil.tests, "HERE", tmpdir):
  448. with self.assertWarnsRegex(
  449. UserWarning, "Fake pytest module was used"
  450. ):
  451. suite = fake_pytest.main()
  452. assert suite.countTestCases() == 1
  453. def test_warns(self):
  454. # success
  455. with fake_pytest.warns(UserWarning):
  456. warnings.warn("foo", UserWarning, stacklevel=1)
  457. # failure
  458. try:
  459. with fake_pytest.warns(UserWarning):
  460. warnings.warn("foo", DeprecationWarning, stacklevel=1)
  461. except AssertionError:
  462. pass
  463. else:
  464. raise self.fail("exception not raised")
  465. # match success
  466. with fake_pytest.warns(UserWarning, match="foo"):
  467. warnings.warn("foo", UserWarning, stacklevel=1)
  468. # match failure
  469. try:
  470. with fake_pytest.warns(UserWarning, match="foo"):
  471. warnings.warn("bar", UserWarning, stacklevel=1)
  472. except AssertionError:
  473. pass
  474. else:
  475. raise self.fail("exception not raised")
  476. class TestTestingUtils(PsutilTestCase):
  477. def test_process_namespace(self):
  478. p = psutil.Process()
  479. ns = process_namespace(p)
  480. ns.test()
  481. fun = next(x for x in ns.iter(ns.getters) if x[1] == 'ppid')[0]
  482. assert fun() == p.ppid()
  483. def test_system_namespace(self):
  484. ns = system_namespace()
  485. fun = next(x for x in ns.iter(ns.getters) if x[1] == 'net_if_addrs')[0]
  486. assert fun() == psutil.net_if_addrs()
  487. class TestOtherUtils(PsutilTestCase):
  488. def test_is_namedtuple(self):
  489. assert is_namedtuple(collections.namedtuple('foo', 'a b c')(1, 2, 3))
  490. assert not is_namedtuple(tuple())