test_memleaks.py 15 KB

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