test_memleaks.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 detecting function memory leaks (typically the ones
  6. implemented in C). It does so by calling a function many times and
  7. checking whether process memory usage keeps increasing between
  8. calls or over time.
  9. Note that this may produce false positives (especially on Windows
  10. for some reason).
  11. PyPy appears to be completely unstable for this framework, probably
  12. because of how its JIT handles memory, so tests are skipped.
  13. """
  14. import functools
  15. import os
  16. import platform
  17. import psutil
  18. import psutil._common
  19. from psutil import LINUX
  20. from psutil import MACOS
  21. from psutil import OPENBSD
  22. from psutil import POSIX
  23. from psutil import SUNOS
  24. from psutil import WINDOWS
  25. from psutil.tests import HAS_CPU_AFFINITY
  26. from psutil.tests import HAS_CPU_FREQ
  27. from psutil.tests import HAS_ENVIRON
  28. from psutil.tests import HAS_IONICE
  29. from psutil.tests import HAS_MEMORY_MAPS
  30. from psutil.tests import HAS_NET_IO_COUNTERS
  31. from psutil.tests import HAS_PROC_CPU_NUM
  32. from psutil.tests import HAS_PROC_IO_COUNTERS
  33. from psutil.tests import HAS_RLIMIT
  34. from psutil.tests import HAS_SENSORS_BATTERY
  35. from psutil.tests import HAS_SENSORS_FANS
  36. from psutil.tests import HAS_SENSORS_TEMPERATURES
  37. from psutil.tests import TestMemoryLeak
  38. from psutil.tests import create_sockets
  39. from psutil.tests import get_testfn
  40. from psutil.tests import process_namespace
  41. from psutil.tests import pytest
  42. from psutil.tests import skip_on_access_denied
  43. from psutil.tests import spawn_testproc
  44. from psutil.tests import system_namespace
  45. from psutil.tests import terminate
  46. cext = psutil._psplatform.cext
  47. thisproc = psutil.Process()
  48. FEW_TIMES = 5
  49. def fewtimes_if_linux():
  50. """Decorator for those Linux functions which are implemented in pure
  51. Python, and which we want to run faster.
  52. """
  53. def decorator(fun):
  54. @functools.wraps(fun)
  55. def wrapper(self, *args, **kwargs):
  56. if LINUX:
  57. before = self.__class__.times
  58. try:
  59. self.__class__.times = FEW_TIMES
  60. return fun(self, *args, **kwargs)
  61. finally:
  62. self.__class__.times = before
  63. else:
  64. return fun(self, *args, **kwargs)
  65. return wrapper
  66. return decorator
  67. # ===================================================================
  68. # Process class
  69. # ===================================================================
  70. class TestProcessObjectLeaks(TestMemoryLeak):
  71. """Test leaks of Process class methods."""
  72. proc = thisproc
  73. def test_coverage(self):
  74. ns = process_namespace(None)
  75. ns.test_class_coverage(self, ns.getters + ns.setters)
  76. @fewtimes_if_linux()
  77. def test_name(self):
  78. self.execute(self.proc.name)
  79. @fewtimes_if_linux()
  80. def test_cmdline(self):
  81. self.execute(self.proc.cmdline)
  82. @fewtimes_if_linux()
  83. def test_exe(self):
  84. self.execute(self.proc.exe)
  85. @fewtimes_if_linux()
  86. def test_ppid(self):
  87. self.execute(self.proc.ppid)
  88. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  89. @fewtimes_if_linux()
  90. def test_uids(self):
  91. self.execute(self.proc.uids)
  92. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  93. @fewtimes_if_linux()
  94. def test_gids(self):
  95. self.execute(self.proc.gids)
  96. @fewtimes_if_linux()
  97. def test_status(self):
  98. self.execute(self.proc.status)
  99. def test_nice(self):
  100. self.execute(self.proc.nice)
  101. def test_nice_set(self):
  102. niceness = thisproc.nice()
  103. self.execute(lambda: self.proc.nice(niceness))
  104. @pytest.mark.skipif(not HAS_IONICE, reason="not supported")
  105. def test_ionice(self):
  106. self.execute(self.proc.ionice)
  107. @pytest.mark.skipif(not HAS_IONICE, reason="not supported")
  108. def test_ionice_set(self):
  109. if WINDOWS:
  110. value = thisproc.ionice()
  111. self.execute(lambda: self.proc.ionice(value))
  112. else:
  113. self.execute(lambda: self.proc.ionice(psutil.IOPRIO_CLASS_NONE))
  114. fun = functools.partial(cext.proc_ioprio_set, os.getpid(), -1, 0)
  115. self.execute_w_exc(OSError, fun)
  116. @pytest.mark.skipif(not HAS_PROC_IO_COUNTERS, reason="not supported")
  117. @fewtimes_if_linux()
  118. def test_io_counters(self):
  119. self.execute(self.proc.io_counters)
  120. @pytest.mark.skipif(POSIX, reason="worthless on POSIX")
  121. def test_username(self):
  122. # always open 1 handle on Windows (only once)
  123. psutil.Process().username()
  124. self.execute(self.proc.username)
  125. @fewtimes_if_linux()
  126. def test_create_time(self):
  127. self.execute(self.proc.create_time)
  128. @fewtimes_if_linux()
  129. @skip_on_access_denied(only_if=OPENBSD)
  130. def test_num_threads(self):
  131. self.execute(self.proc.num_threads)
  132. @pytest.mark.skipif(not WINDOWS, reason="WINDOWS only")
  133. def test_num_handles(self):
  134. self.execute(self.proc.num_handles)
  135. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  136. @fewtimes_if_linux()
  137. def test_num_fds(self):
  138. self.execute(self.proc.num_fds)
  139. @fewtimes_if_linux()
  140. def test_num_ctx_switches(self):
  141. self.execute(self.proc.num_ctx_switches)
  142. @fewtimes_if_linux()
  143. @skip_on_access_denied(only_if=OPENBSD)
  144. def test_threads(self):
  145. self.execute(self.proc.threads)
  146. @fewtimes_if_linux()
  147. def test_cpu_times(self):
  148. self.execute(self.proc.cpu_times)
  149. @fewtimes_if_linux()
  150. @pytest.mark.skipif(not HAS_PROC_CPU_NUM, reason="not supported")
  151. def test_cpu_num(self):
  152. self.execute(self.proc.cpu_num)
  153. @fewtimes_if_linux()
  154. def test_memory_info(self):
  155. self.execute(self.proc.memory_info)
  156. @fewtimes_if_linux()
  157. def test_memory_full_info(self):
  158. self.execute(self.proc.memory_full_info)
  159. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  160. @fewtimes_if_linux()
  161. def test_terminal(self):
  162. self.execute(self.proc.terminal)
  163. def test_resume(self):
  164. times = FEW_TIMES if POSIX else self.times
  165. self.execute(self.proc.resume, times=times)
  166. @fewtimes_if_linux()
  167. def test_cwd(self):
  168. self.execute(self.proc.cwd)
  169. @pytest.mark.skipif(not HAS_CPU_AFFINITY, reason="not supported")
  170. def test_cpu_affinity(self):
  171. self.execute(self.proc.cpu_affinity)
  172. @pytest.mark.skipif(not HAS_CPU_AFFINITY, reason="not supported")
  173. def test_cpu_affinity_set(self):
  174. affinity = thisproc.cpu_affinity()
  175. self.execute(lambda: self.proc.cpu_affinity(affinity))
  176. self.execute_w_exc(ValueError, lambda: self.proc.cpu_affinity([-1]))
  177. @fewtimes_if_linux()
  178. def test_open_files(self):
  179. with open(get_testfn(), 'w'):
  180. self.execute(self.proc.open_files)
  181. @pytest.mark.skipif(not HAS_MEMORY_MAPS, reason="not supported")
  182. @fewtimes_if_linux()
  183. def test_memory_maps(self):
  184. self.execute(self.proc.memory_maps)
  185. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  186. @pytest.mark.skipif(not HAS_RLIMIT, reason="not supported")
  187. def test_rlimit(self):
  188. self.execute(lambda: self.proc.rlimit(psutil.RLIMIT_NOFILE))
  189. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  190. @pytest.mark.skipif(not HAS_RLIMIT, reason="not supported")
  191. def test_rlimit_set(self):
  192. limit = thisproc.rlimit(psutil.RLIMIT_NOFILE)
  193. self.execute(lambda: self.proc.rlimit(psutil.RLIMIT_NOFILE, limit))
  194. self.execute_w_exc((OSError, ValueError), lambda: self.proc.rlimit(-1))
  195. @fewtimes_if_linux()
  196. # Windows implementation is based on a single system-wide
  197. # function (tested later).
  198. @pytest.mark.skipif(WINDOWS, reason="worthless on WINDOWS")
  199. def test_net_connections(self):
  200. # TODO: UNIX sockets are temporarily implemented by parsing
  201. # 'pfiles' cmd output; we don't want that part of the code to
  202. # be executed.
  203. with create_sockets():
  204. kind = 'inet' if SUNOS else 'all'
  205. self.execute(lambda: self.proc.net_connections(kind))
  206. @pytest.mark.skipif(not HAS_ENVIRON, reason="not supported")
  207. def test_environ(self):
  208. self.execute(self.proc.environ)
  209. @pytest.mark.skipif(not WINDOWS, reason="WINDOWS only")
  210. def test_proc_info(self):
  211. self.execute(lambda: cext.proc_info(os.getpid()))
  212. class TestTerminatedProcessLeaks(TestProcessObjectLeaks):
  213. """Repeat the tests above looking for leaks occurring when dealing
  214. with terminated processes raising NoSuchProcess exception.
  215. The C functions are still invoked but will follow different code
  216. paths. We'll check those code paths.
  217. """
  218. @classmethod
  219. def setUpClass(cls):
  220. super().setUpClass()
  221. cls.subp = spawn_testproc()
  222. cls.proc = psutil.Process(cls.subp.pid)
  223. cls.proc.kill()
  224. cls.proc.wait()
  225. @classmethod
  226. def tearDownClass(cls):
  227. super().tearDownClass()
  228. terminate(cls.subp)
  229. def call(self, fun):
  230. try:
  231. fun()
  232. except psutil.NoSuchProcess:
  233. pass
  234. if WINDOWS:
  235. def test_kill(self):
  236. self.execute(self.proc.kill)
  237. def test_terminate(self):
  238. self.execute(self.proc.terminate)
  239. def test_suspend(self):
  240. self.execute(self.proc.suspend)
  241. def test_resume(self):
  242. self.execute(self.proc.resume)
  243. def test_wait(self):
  244. self.execute(self.proc.wait)
  245. def test_proc_info(self):
  246. # test dual implementation
  247. def call():
  248. try:
  249. return cext.proc_info(self.proc.pid)
  250. except ProcessLookupError:
  251. pass
  252. self.execute(call)
  253. @pytest.mark.skipif(not WINDOWS, reason="WINDOWS only")
  254. class TestProcessDualImplementation(TestMemoryLeak):
  255. def test_cmdline_peb_true(self):
  256. self.execute(lambda: cext.proc_cmdline(os.getpid(), use_peb=True))
  257. def test_cmdline_peb_false(self):
  258. self.execute(lambda: cext.proc_cmdline(os.getpid(), use_peb=False))
  259. # ===================================================================
  260. # system APIs
  261. # ===================================================================
  262. class TestModuleFunctionsLeaks(TestMemoryLeak):
  263. """Test leaks of psutil module functions."""
  264. def test_coverage(self):
  265. ns = system_namespace()
  266. ns.test_class_coverage(self, ns.all)
  267. # --- cpu
  268. @fewtimes_if_linux()
  269. def test_cpu_count(self): # logical
  270. self.execute(lambda: psutil.cpu_count(logical=True))
  271. @fewtimes_if_linux()
  272. def test_cpu_count_cores(self):
  273. self.execute(lambda: psutil.cpu_count(logical=False))
  274. @fewtimes_if_linux()
  275. def test_cpu_times(self):
  276. self.execute(psutil.cpu_times)
  277. @fewtimes_if_linux()
  278. def test_per_cpu_times(self):
  279. self.execute(lambda: psutil.cpu_times(percpu=True))
  280. @fewtimes_if_linux()
  281. def test_cpu_stats(self):
  282. self.execute(psutil.cpu_stats)
  283. @fewtimes_if_linux()
  284. # TODO: remove this once 1892 is fixed
  285. @pytest.mark.skipif(
  286. MACOS and platform.machine() == 'arm64', reason="skipped due to #1892"
  287. )
  288. @pytest.mark.skipif(not HAS_CPU_FREQ, reason="not supported")
  289. def test_cpu_freq(self):
  290. self.execute(psutil.cpu_freq)
  291. @pytest.mark.skipif(not WINDOWS, reason="WINDOWS only")
  292. def test_getloadavg(self):
  293. psutil.getloadavg()
  294. self.execute(psutil.getloadavg)
  295. # --- mem
  296. def test_virtual_memory(self):
  297. self.execute(psutil.virtual_memory)
  298. # TODO: remove this skip when this gets fixed
  299. @pytest.mark.skipif(SUNOS, reason="worthless on SUNOS (uses a subprocess)")
  300. def test_swap_memory(self):
  301. self.execute(psutil.swap_memory)
  302. def test_pid_exists(self):
  303. times = FEW_TIMES if POSIX else self.times
  304. self.execute(lambda: psutil.pid_exists(os.getpid()), times=times)
  305. # --- disk
  306. def test_disk_usage(self):
  307. times = FEW_TIMES if POSIX else self.times
  308. self.execute(lambda: psutil.disk_usage('.'), times=times)
  309. def test_disk_partitions(self):
  310. self.execute(psutil.disk_partitions)
  311. @pytest.mark.skipif(
  312. LINUX and not os.path.exists('/proc/diskstats'),
  313. reason="/proc/diskstats not available on this Linux version",
  314. )
  315. @fewtimes_if_linux()
  316. def test_disk_io_counters(self):
  317. self.execute(lambda: psutil.disk_io_counters(nowrap=False))
  318. # --- proc
  319. @fewtimes_if_linux()
  320. def test_pids(self):
  321. self.execute(psutil.pids)
  322. # --- net
  323. @fewtimes_if_linux()
  324. @pytest.mark.skipif(not HAS_NET_IO_COUNTERS, reason="not supported")
  325. def test_net_io_counters(self):
  326. self.execute(lambda: psutil.net_io_counters(nowrap=False))
  327. @fewtimes_if_linux()
  328. @pytest.mark.skipif(MACOS and os.getuid() != 0, reason="need root access")
  329. def test_net_connections(self):
  330. # always opens and handle on Windows() (once)
  331. psutil.net_connections(kind='all')
  332. with create_sockets():
  333. self.execute(lambda: psutil.net_connections(kind='all'))
  334. def test_net_if_addrs(self):
  335. # Note: verified that on Windows this was a false positive.
  336. tolerance = 80 * 1024 if WINDOWS else self.tolerance
  337. self.execute(psutil.net_if_addrs, tolerance=tolerance)
  338. def test_net_if_stats(self):
  339. self.execute(psutil.net_if_stats)
  340. # --- sensors
  341. @fewtimes_if_linux()
  342. @pytest.mark.skipif(not HAS_SENSORS_BATTERY, reason="not supported")
  343. def test_sensors_battery(self):
  344. self.execute(psutil.sensors_battery)
  345. @fewtimes_if_linux()
  346. @pytest.mark.skipif(not HAS_SENSORS_TEMPERATURES, reason="not supported")
  347. def test_sensors_temperatures(self):
  348. self.execute(psutil.sensors_temperatures)
  349. @fewtimes_if_linux()
  350. @pytest.mark.skipif(not HAS_SENSORS_FANS, reason="not supported")
  351. def test_sensors_fans(self):
  352. self.execute(psutil.sensors_fans)
  353. # --- others
  354. @fewtimes_if_linux()
  355. def test_boot_time(self):
  356. self.execute(psutil.boot_time)
  357. def test_users(self):
  358. self.execute(psutil.users)
  359. def test_set_debug(self):
  360. self.execute(lambda: psutil._set_debug(False))
  361. if WINDOWS:
  362. # --- win services
  363. def test_win_service_iter(self):
  364. self.execute(cext.winservice_enumerate)
  365. def test_win_service_get(self):
  366. pass
  367. def test_win_service_get_config(self):
  368. name = next(psutil.win_service_iter()).name()
  369. self.execute(lambda: cext.winservice_query_config(name))
  370. def test_win_service_get_status(self):
  371. name = next(psutil.win_service_iter()).name()
  372. self.execute(lambda: cext.winservice_query_status(name))
  373. def test_win_service_get_description(self):
  374. name = next(psutil.win_service_iter()).name()
  375. self.execute(lambda: cext.winservice_query_descr(name))