test_testutils.py 18 KB

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