test_linux.py 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289
  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. """Linux specific tests."""
  6. import collections
  7. import contextlib
  8. import errno
  9. import io
  10. import os
  11. import platform
  12. import re
  13. import shutil
  14. import socket
  15. import struct
  16. import textwrap
  17. import time
  18. import warnings
  19. from unittest import mock
  20. import psutil
  21. from psutil import LINUX
  22. from psutil.tests import AARCH64
  23. from psutil.tests import GITHUB_ACTIONS
  24. from psutil.tests import GLOBAL_TIMEOUT
  25. from psutil.tests import HAS_BATTERY
  26. from psutil.tests import HAS_CPU_FREQ
  27. from psutil.tests import HAS_GETLOADAVG
  28. from psutil.tests import HAS_RLIMIT
  29. from psutil.tests import RISCV64
  30. from psutil.tests import TOLERANCE_DISK_USAGE
  31. from psutil.tests import TOLERANCE_SYS_MEM
  32. from psutil.tests import PsutilTestCase
  33. from psutil.tests import ThreadTask
  34. from psutil.tests import call_until
  35. from psutil.tests import pytest
  36. from psutil.tests import reload_module
  37. from psutil.tests import retry_on_failure
  38. from psutil.tests import safe_rmpath
  39. from psutil.tests import sh
  40. from psutil.tests import skip_on_not_implemented
  41. if LINUX:
  42. from psutil._pslinux import CLOCK_TICKS
  43. from psutil._pslinux import RootFsDeviceFinder
  44. from psutil._pslinux import calculate_avail_vmem
  45. from psutil._pslinux import open_binary
  46. HERE = os.path.abspath(os.path.dirname(__file__))
  47. SIOCGIFADDR = 0x8915
  48. SIOCGIFHWADDR = 0x8927
  49. SIOCGIFNETMASK = 0x891B
  50. SIOCGIFBRDADDR = 0x8919
  51. if LINUX:
  52. SECTOR_SIZE = 512
  53. # =====================================================================
  54. # --- utils
  55. # =====================================================================
  56. def get_ipv4_address(ifname):
  57. import fcntl
  58. ifname = bytes(ifname[:15], "ascii")
  59. with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
  60. return socket.inet_ntoa(
  61. fcntl.ioctl(s.fileno(), SIOCGIFADDR, struct.pack('256s', ifname))[
  62. 20:24
  63. ]
  64. )
  65. def get_ipv4_netmask(ifname):
  66. import fcntl
  67. ifname = bytes(ifname[:15], "ascii")
  68. with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
  69. return socket.inet_ntoa(
  70. fcntl.ioctl(
  71. s.fileno(), SIOCGIFNETMASK, struct.pack('256s', ifname)
  72. )[20:24]
  73. )
  74. def get_ipv4_broadcast(ifname):
  75. import fcntl
  76. ifname = bytes(ifname[:15], "ascii")
  77. with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
  78. return socket.inet_ntoa(
  79. fcntl.ioctl(
  80. s.fileno(), SIOCGIFBRDADDR, struct.pack('256s', ifname)
  81. )[20:24]
  82. )
  83. def get_ipv6_addresses(ifname):
  84. with open("/proc/net/if_inet6") as f:
  85. all_fields = []
  86. for line in f:
  87. fields = line.split()
  88. if fields[-1] == ifname:
  89. all_fields.append(fields)
  90. if len(all_fields) == 0:
  91. raise ValueError(f"could not find interface {ifname!r}")
  92. for i in range(len(all_fields)):
  93. unformatted = all_fields[i][0]
  94. groups = [
  95. unformatted[j : j + 4] for j in range(0, len(unformatted), 4)
  96. ]
  97. formatted = ":".join(groups)
  98. packed = socket.inet_pton(socket.AF_INET6, formatted)
  99. all_fields[i] = socket.inet_ntop(socket.AF_INET6, packed)
  100. return all_fields
  101. def get_mac_address(ifname):
  102. import fcntl
  103. ifname = bytes(ifname[:15], "ascii")
  104. with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
  105. info = fcntl.ioctl(
  106. s.fileno(), SIOCGIFHWADDR, struct.pack('256s', ifname)
  107. )
  108. return "".join([f"{char:02x}:" for char in info[18:24]])[:-1]
  109. def free_swap():
  110. """Parse 'free' cmd and return swap memory's s total, used and free
  111. values.
  112. """
  113. out = sh(["free", "-b"], env={"LANG": "C.UTF-8"})
  114. lines = out.split('\n')
  115. for line in lines:
  116. if line.startswith('Swap'):
  117. _, total, used, free = line.split()
  118. nt = collections.namedtuple('free', 'total used free')
  119. return nt(int(total), int(used), int(free))
  120. raise ValueError(f"can't find 'Swap' in 'free' output:\n{out}")
  121. def free_physmem():
  122. """Parse 'free' cmd and return physical memory's total, used
  123. and free values.
  124. """
  125. # Note: free can have 2 different formats, invalidating 'shared'
  126. # and 'cached' memory which may have different positions so we
  127. # do not return them.
  128. # https://github.com/giampaolo/psutil/issues/538#issuecomment-57059946
  129. out = sh(["free", "-b"], env={"LANG": "C.UTF-8"})
  130. lines = out.split('\n')
  131. for line in lines:
  132. if line.startswith('Mem'):
  133. total, used, free, shared = (int(x) for x in line.split()[1:5])
  134. nt = collections.namedtuple(
  135. 'free', 'total used free shared output'
  136. )
  137. return nt(total, used, free, shared, out)
  138. raise ValueError(f"can't find 'Mem' in 'free' output:\n{out}")
  139. def vmstat(stat):
  140. out = sh(["vmstat", "-s"], env={"LANG": "C.UTF-8"})
  141. for line in out.split("\n"):
  142. line = line.strip()
  143. if stat in line:
  144. return int(line.split(' ')[0])
  145. raise ValueError(f"can't find {stat!r} in 'vmstat' output")
  146. def get_free_version_info():
  147. out = sh(["free", "-V"]).strip()
  148. if 'UNKNOWN' in out:
  149. return pytest.skip("can't determine free version")
  150. return tuple(map(int, re.findall(r'\d+', out.split()[-1])))
  151. @contextlib.contextmanager
  152. def mock_open_content(pairs):
  153. """Mock open() builtin and forces it to return a certain content
  154. for a given path. `pairs` is a {"path": "content", ...} dict.
  155. """
  156. def open_mock(name, *args, **kwargs):
  157. if name in pairs:
  158. content = pairs[name]
  159. if isinstance(content, str):
  160. return io.StringIO(content)
  161. else:
  162. return io.BytesIO(content)
  163. else:
  164. return orig_open(name, *args, **kwargs)
  165. orig_open = open
  166. with mock.patch("builtins.open", create=True, side_effect=open_mock) as m:
  167. yield m
  168. @contextlib.contextmanager
  169. def mock_open_exception(for_path, exc):
  170. """Mock open() builtin and raises `exc` if the path being opened
  171. matches `for_path`.
  172. """
  173. def open_mock(name, *args, **kwargs):
  174. if name == for_path:
  175. raise exc
  176. return orig_open(name, *args, **kwargs)
  177. orig_open = open
  178. with mock.patch("builtins.open", create=True, side_effect=open_mock) as m:
  179. yield m
  180. # =====================================================================
  181. # --- system virtual memory
  182. # =====================================================================
  183. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  184. class TestSystemVirtualMemoryAgainstFree(PsutilTestCase):
  185. def test_total(self):
  186. cli_value = free_physmem().total
  187. psutil_value = psutil.virtual_memory().total
  188. assert cli_value == psutil_value
  189. @retry_on_failure()
  190. def test_used(self):
  191. # Older versions of procps used slab memory to calculate used memory.
  192. # This got changed in:
  193. # https://gitlab.com/procps-ng/procps/commit/
  194. # 05d751c4f076a2f0118b914c5e51cfbb4762ad8e
  195. # Newer versions of procps (>=4.0.1) are using yet another way to
  196. # compute used memory.
  197. # https://gitlab.com/procps-ng/procps/commit/
  198. # 2184e90d2e7cdb582f9a5b706b47015e56707e4d
  199. if get_free_version_info() < (4, 0, 1):
  200. return pytest.skip("free version too old")
  201. cli_value = free_physmem().used
  202. psutil_value = psutil.virtual_memory().used
  203. assert abs(cli_value - psutil_value) < TOLERANCE_SYS_MEM
  204. @retry_on_failure()
  205. def test_free(self):
  206. cli_value = free_physmem().free
  207. psutil_value = psutil.virtual_memory().free
  208. assert abs(cli_value - psutil_value) < TOLERANCE_SYS_MEM
  209. @retry_on_failure()
  210. def test_shared(self):
  211. free = free_physmem()
  212. free_value = free.shared
  213. if free_value == 0:
  214. return pytest.skip("free does not support 'shared' column")
  215. psutil_value = psutil.virtual_memory().shared
  216. assert (
  217. abs(free_value - psutil_value) < TOLERANCE_SYS_MEM
  218. ), f"{free_value} {psutil_value} \n{free.output}"
  219. @retry_on_failure()
  220. def test_available(self):
  221. # "free" output format has changed at some point:
  222. # https://github.com/giampaolo/psutil/issues/538#issuecomment-147192098
  223. out = sh(["free", "-b"])
  224. lines = out.split('\n')
  225. if 'available' not in lines[0]:
  226. return pytest.skip("free does not support 'available' column")
  227. free_value = int(lines[1].split()[-1])
  228. psutil_value = psutil.virtual_memory().available
  229. assert abs(free_value - psutil_value) < TOLERANCE_SYS_MEM
  230. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  231. class TestSystemVirtualMemoryAgainstVmstat(PsutilTestCase):
  232. def test_total(self):
  233. vmstat_value = vmstat('total memory') * 1024
  234. psutil_value = psutil.virtual_memory().total
  235. assert abs(vmstat_value - psutil_value) < TOLERANCE_SYS_MEM
  236. @retry_on_failure()
  237. def test_used(self):
  238. # Older versions of procps used slab memory to calculate used memory.
  239. # This got changed in:
  240. # https://gitlab.com/procps-ng/procps/commit/
  241. # 05d751c4f076a2f0118b914c5e51cfbb4762ad8e
  242. # Newer versions of procps (>=4.0.1) are using yet another way to
  243. # compute used memory.
  244. # https://gitlab.com/procps-ng/procps/commit/
  245. # 2184e90d2e7cdb582f9a5b706b47015e56707e4d
  246. if get_free_version_info() < (4, 0, 1):
  247. return pytest.skip("free version too old")
  248. vmstat_value = vmstat('used memory') * 1024
  249. psutil_value = psutil.virtual_memory().used
  250. assert abs(vmstat_value - psutil_value) < TOLERANCE_SYS_MEM
  251. @retry_on_failure()
  252. def test_free(self):
  253. vmstat_value = vmstat('free memory') * 1024
  254. psutil_value = psutil.virtual_memory().free
  255. assert abs(vmstat_value - psutil_value) < TOLERANCE_SYS_MEM
  256. @retry_on_failure()
  257. def test_buffers(self):
  258. vmstat_value = vmstat('buffer memory') * 1024
  259. psutil_value = psutil.virtual_memory().buffers
  260. assert abs(vmstat_value - psutil_value) < TOLERANCE_SYS_MEM
  261. @retry_on_failure()
  262. def test_active(self):
  263. vmstat_value = vmstat('active memory') * 1024
  264. psutil_value = psutil.virtual_memory().active
  265. assert abs(vmstat_value - psutil_value) < TOLERANCE_SYS_MEM
  266. @retry_on_failure()
  267. def test_inactive(self):
  268. vmstat_value = vmstat('inactive memory') * 1024
  269. psutil_value = psutil.virtual_memory().inactive
  270. assert abs(vmstat_value - psutil_value) < TOLERANCE_SYS_MEM
  271. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  272. class TestSystemVirtualMemoryMocks(PsutilTestCase):
  273. def test_warnings_on_misses(self):
  274. # Emulate a case where /proc/meminfo provides few info.
  275. # psutil is supposed to set the missing fields to 0 and
  276. # raise a warning.
  277. content = textwrap.dedent("""\
  278. Active(anon): 6145416 kB
  279. Active(file): 2950064 kB
  280. Inactive(anon): 574764 kB
  281. Inactive(file): 1567648 kB
  282. MemAvailable: -1 kB
  283. MemFree: 2057400 kB
  284. MemTotal: 16325648 kB
  285. SReclaimable: 346648 kB
  286. """).encode()
  287. with mock_open_content({'/proc/meminfo': content}) as m:
  288. with warnings.catch_warnings(record=True) as ws:
  289. warnings.simplefilter("always")
  290. ret = psutil.virtual_memory()
  291. assert m.called
  292. assert len(ws) == 1
  293. w = ws[0]
  294. assert "memory stats couldn't be determined" in str(w.message)
  295. assert "cached" in str(w.message)
  296. assert "shared" in str(w.message)
  297. assert "active" in str(w.message)
  298. assert "inactive" in str(w.message)
  299. assert "buffers" in str(w.message)
  300. assert "available" in str(w.message)
  301. assert ret.cached == 0
  302. assert ret.active == 0
  303. assert ret.inactive == 0
  304. assert ret.shared == 0
  305. assert ret.buffers == 0
  306. assert ret.available == 0
  307. assert ret.slab == 0
  308. @retry_on_failure()
  309. def test_avail_old_percent(self):
  310. # Make sure that our calculation of avail mem for old kernels
  311. # is off by max 15%.
  312. mems = {}
  313. with open_binary('/proc/meminfo') as f:
  314. for line in f:
  315. fields = line.split()
  316. mems[fields[0]] = int(fields[1]) * 1024
  317. a = calculate_avail_vmem(mems)
  318. if b'MemAvailable:' in mems:
  319. b = mems[b'MemAvailable:']
  320. diff_percent = abs(a - b) / a * 100
  321. assert diff_percent < 15
  322. def test_avail_old_comes_from_kernel(self):
  323. # Make sure "MemAvailable:" coluimn is used instead of relying
  324. # on our internal algorithm to calculate avail mem.
  325. content = textwrap.dedent("""\
  326. Active: 9444728 kB
  327. Active(anon): 6145416 kB
  328. Active(file): 2950064 kB
  329. Buffers: 287952 kB
  330. Cached: 4818144 kB
  331. Inactive(file): 1578132 kB
  332. Inactive(anon): 574764 kB
  333. Inactive(file): 1567648 kB
  334. MemAvailable: 6574984 kB
  335. MemFree: 2057400 kB
  336. MemTotal: 16325648 kB
  337. Shmem: 577588 kB
  338. SReclaimable: 346648 kB
  339. """).encode()
  340. with mock_open_content({'/proc/meminfo': content}) as m:
  341. with warnings.catch_warnings(record=True) as ws:
  342. ret = psutil.virtual_memory()
  343. assert m.called
  344. assert ret.available == 6574984 * 1024
  345. w = ws[0]
  346. assert "inactive memory stats couldn't be determined" in str(
  347. w.message
  348. )
  349. def test_avail_old_missing_fields(self):
  350. # Remove Active(file), Inactive(file) and SReclaimable
  351. # from /proc/meminfo and make sure the fallback is used
  352. # (free + cached),
  353. content = textwrap.dedent("""\
  354. Active: 9444728 kB
  355. Active(anon): 6145416 kB
  356. Buffers: 287952 kB
  357. Cached: 4818144 kB
  358. Inactive(file): 1578132 kB
  359. Inactive(anon): 574764 kB
  360. MemFree: 2057400 kB
  361. MemTotal: 16325648 kB
  362. Shmem: 577588 kB
  363. """).encode()
  364. with mock_open_content({"/proc/meminfo": content}) as m:
  365. with warnings.catch_warnings(record=True) as ws:
  366. ret = psutil.virtual_memory()
  367. assert m.called
  368. assert ret.available == 2057400 * 1024 + 4818144 * 1024
  369. w = ws[0]
  370. assert "inactive memory stats couldn't be determined" in str(
  371. w.message
  372. )
  373. def test_avail_old_missing_zoneinfo(self):
  374. # Remove /proc/zoneinfo file. Make sure fallback is used
  375. # (free + cached).
  376. content = textwrap.dedent("""\
  377. Active: 9444728 kB
  378. Active(anon): 6145416 kB
  379. Active(file): 2950064 kB
  380. Buffers: 287952 kB
  381. Cached: 4818144 kB
  382. Inactive(file): 1578132 kB
  383. Inactive(anon): 574764 kB
  384. Inactive(file): 1567648 kB
  385. MemFree: 2057400 kB
  386. MemTotal: 16325648 kB
  387. Shmem: 577588 kB
  388. SReclaimable: 346648 kB
  389. """).encode()
  390. with mock_open_content({"/proc/meminfo": content}):
  391. with mock_open_exception("/proc/zoneinfo", FileNotFoundError):
  392. with warnings.catch_warnings(record=True) as ws:
  393. ret = psutil.virtual_memory()
  394. assert ret.available == 2057400 * 1024 + 4818144 * 1024
  395. w = ws[0]
  396. assert (
  397. "inactive memory stats couldn't be determined"
  398. in str(w.message)
  399. )
  400. def test_virtual_memory_mocked(self):
  401. # Emulate /proc/meminfo because neither vmstat nor free return slab.
  402. content = textwrap.dedent("""\
  403. MemTotal: 100 kB
  404. MemFree: 2 kB
  405. MemAvailable: 3 kB
  406. Buffers: 4 kB
  407. Cached: 5 kB
  408. SwapCached: 6 kB
  409. Active: 7 kB
  410. Inactive: 8 kB
  411. Active(anon): 9 kB
  412. Inactive(anon): 10 kB
  413. Active(file): 11 kB
  414. Inactive(file): 12 kB
  415. Unevictable: 13 kB
  416. Mlocked: 14 kB
  417. SwapTotal: 15 kB
  418. SwapFree: 16 kB
  419. Dirty: 17 kB
  420. Writeback: 18 kB
  421. AnonPages: 19 kB
  422. Mapped: 20 kB
  423. Shmem: 21 kB
  424. Slab: 22 kB
  425. SReclaimable: 23 kB
  426. SUnreclaim: 24 kB
  427. KernelStack: 25 kB
  428. PageTables: 26 kB
  429. NFS_Unstable: 27 kB
  430. Bounce: 28 kB
  431. WritebackTmp: 29 kB
  432. CommitLimit: 30 kB
  433. Committed_AS: 31 kB
  434. VmallocTotal: 32 kB
  435. VmallocUsed: 33 kB
  436. VmallocChunk: 34 kB
  437. HardwareCorrupted: 35 kB
  438. AnonHugePages: 36 kB
  439. ShmemHugePages: 37 kB
  440. ShmemPmdMapped: 38 kB
  441. CmaTotal: 39 kB
  442. CmaFree: 40 kB
  443. HugePages_Total: 41 kB
  444. HugePages_Free: 42 kB
  445. HugePages_Rsvd: 43 kB
  446. HugePages_Surp: 44 kB
  447. Hugepagesize: 45 kB
  448. DirectMap46k: 46 kB
  449. DirectMap47M: 47 kB
  450. DirectMap48G: 48 kB
  451. """).encode()
  452. with mock_open_content({"/proc/meminfo": content}) as m:
  453. mem = psutil.virtual_memory()
  454. assert m.called
  455. assert mem.total == 100 * 1024
  456. assert mem.free == 2 * 1024
  457. assert mem.buffers == 4 * 1024
  458. # cached mem also includes reclaimable memory
  459. assert mem.cached == (5 + 23) * 1024
  460. assert mem.shared == 21 * 1024
  461. assert mem.active == 7 * 1024
  462. assert mem.inactive == 8 * 1024
  463. assert mem.slab == 22 * 1024
  464. assert mem.available == 3 * 1024
  465. # =====================================================================
  466. # --- system swap memory
  467. # =====================================================================
  468. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  469. class TestSystemSwapMemory(PsutilTestCase):
  470. @staticmethod
  471. def meminfo_has_swap_info():
  472. """Return True if /proc/meminfo provides swap metrics."""
  473. with open("/proc/meminfo") as f:
  474. data = f.read()
  475. return 'SwapTotal:' in data and 'SwapFree:' in data
  476. def test_total(self):
  477. free_value = free_swap().total
  478. psutil_value = psutil.swap_memory().total
  479. assert abs(free_value - psutil_value) < TOLERANCE_SYS_MEM
  480. @retry_on_failure()
  481. def test_used(self):
  482. free_value = free_swap().used
  483. psutil_value = psutil.swap_memory().used
  484. assert abs(free_value - psutil_value) < TOLERANCE_SYS_MEM
  485. @retry_on_failure()
  486. def test_free(self):
  487. free_value = free_swap().free
  488. psutil_value = psutil.swap_memory().free
  489. assert abs(free_value - psutil_value) < TOLERANCE_SYS_MEM
  490. def test_missing_sin_sout(self):
  491. with mock.patch('psutil._common.open', create=True) as m:
  492. with warnings.catch_warnings(record=True) as ws:
  493. warnings.simplefilter("always")
  494. ret = psutil.swap_memory()
  495. assert m.called
  496. assert len(ws) == 1
  497. w = ws[0]
  498. assert (
  499. "'sin' and 'sout' swap memory stats couldn't be determined"
  500. in str(w.message)
  501. )
  502. assert ret.sin == 0
  503. assert ret.sout == 0
  504. def test_no_vmstat_mocked(self):
  505. # see https://github.com/giampaolo/psutil/issues/722
  506. with mock_open_exception("/proc/vmstat", FileNotFoundError) as m:
  507. with warnings.catch_warnings(record=True) as ws:
  508. warnings.simplefilter("always")
  509. ret = psutil.swap_memory()
  510. assert m.called
  511. assert len(ws) == 1
  512. w = ws[0]
  513. assert (
  514. "'sin' and 'sout' swap memory stats couldn't "
  515. "be determined and were set to 0"
  516. in str(w.message)
  517. )
  518. assert ret.sin == 0
  519. assert ret.sout == 0
  520. def test_meminfo_against_sysinfo(self):
  521. # Make sure the content of /proc/meminfo about swap memory
  522. # matches sysinfo() syscall, see:
  523. # https://github.com/giampaolo/psutil/issues/1015
  524. if not self.meminfo_has_swap_info():
  525. return pytest.skip("/proc/meminfo has no swap metrics")
  526. with mock.patch('psutil._pslinux.cext.linux_sysinfo') as m:
  527. swap = psutil.swap_memory()
  528. assert not m.called
  529. import psutil._psutil_linux as cext
  530. _, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo()
  531. total *= unit_multiplier
  532. free *= unit_multiplier
  533. assert swap.total == total
  534. assert abs(swap.free - free) < TOLERANCE_SYS_MEM
  535. def test_emulate_meminfo_has_no_metrics(self):
  536. # Emulate a case where /proc/meminfo provides no swap metrics
  537. # in which case sysinfo() syscall is supposed to be used
  538. # as a fallback.
  539. with mock_open_content({"/proc/meminfo": b""}) as m:
  540. psutil.swap_memory()
  541. assert m.called
  542. # =====================================================================
  543. # --- system CPU
  544. # =====================================================================
  545. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  546. class TestSystemCPUTimes(PsutilTestCase):
  547. def test_fields(self):
  548. fields = psutil.cpu_times()._fields
  549. kernel_ver = re.findall(r'\d+\.\d+\.\d+', os.uname()[2])[0]
  550. kernel_ver_info = tuple(map(int, kernel_ver.split('.')))
  551. if kernel_ver_info >= (2, 6, 11):
  552. assert 'steal' in fields
  553. else:
  554. assert 'steal' not in fields
  555. if kernel_ver_info >= (2, 6, 24):
  556. assert 'guest' in fields
  557. else:
  558. assert 'guest' not in fields
  559. if kernel_ver_info >= (3, 2, 0):
  560. assert 'guest_nice' in fields
  561. else:
  562. assert 'guest_nice' not in fields
  563. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  564. class TestSystemCPUCountLogical(PsutilTestCase):
  565. @pytest.mark.skipif(
  566. not os.path.exists("/sys/devices/system/cpu/online"),
  567. reason="/sys/devices/system/cpu/online does not exist",
  568. )
  569. def test_against_sysdev_cpu_online(self):
  570. with open("/sys/devices/system/cpu/online") as f:
  571. value = f.read().strip()
  572. if "-" in str(value):
  573. value = int(value.split('-')[1]) + 1
  574. assert psutil.cpu_count() == value
  575. @pytest.mark.skipif(
  576. not os.path.exists("/sys/devices/system/cpu"),
  577. reason="/sys/devices/system/cpu does not exist",
  578. )
  579. def test_against_sysdev_cpu_num(self):
  580. ls = os.listdir("/sys/devices/system/cpu")
  581. count = len([x for x in ls if re.search(r"cpu\d+$", x) is not None])
  582. assert psutil.cpu_count() == count
  583. @pytest.mark.skipif(
  584. not shutil.which("nproc"), reason="nproc utility not available"
  585. )
  586. def test_against_nproc(self):
  587. num = int(sh("nproc --all"))
  588. assert psutil.cpu_count(logical=True) == num
  589. @pytest.mark.skipif(
  590. not shutil.which("lscpu"), reason="lscpu utility not available"
  591. )
  592. def test_against_lscpu(self):
  593. out = sh("lscpu -p")
  594. num = len([x for x in out.split('\n') if not x.startswith('#')])
  595. assert psutil.cpu_count(logical=True) == num
  596. def test_emulate_fallbacks(self):
  597. import psutil._pslinux
  598. original = psutil._pslinux.cpu_count_logical()
  599. # Here we want to mock os.sysconf("SC_NPROCESSORS_ONLN") in
  600. # order to cause the parsing of /proc/cpuinfo and /proc/stat.
  601. with mock.patch(
  602. 'psutil._pslinux.os.sysconf', side_effect=ValueError
  603. ) as m:
  604. assert psutil._pslinux.cpu_count_logical() == original
  605. assert m.called
  606. # Let's have open() return empty data and make sure None is
  607. # returned ('cause we mimic os.cpu_count()).
  608. with mock.patch('psutil._common.open', create=True) as m:
  609. assert psutil._pslinux.cpu_count_logical() is None
  610. assert m.call_count == 2
  611. # /proc/stat should be the last one
  612. assert m.call_args[0][0] == '/proc/stat'
  613. # Let's push this a bit further and make sure /proc/cpuinfo
  614. # parsing works as expected.
  615. with open('/proc/cpuinfo', 'rb') as f:
  616. cpuinfo_data = f.read()
  617. fake_file = io.BytesIO(cpuinfo_data)
  618. with mock.patch(
  619. 'psutil._common.open', return_value=fake_file, create=True
  620. ) as m:
  621. assert psutil._pslinux.cpu_count_logical() == original
  622. # Finally, let's make /proc/cpuinfo return meaningless data;
  623. # this way we'll fall back on relying on /proc/stat
  624. with mock_open_content({"/proc/cpuinfo": b""}) as m:
  625. assert psutil._pslinux.cpu_count_logical() == original
  626. assert m.called
  627. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  628. class TestSystemCPUCountCores(PsutilTestCase):
  629. @pytest.mark.skipif(
  630. not shutil.which("lscpu"), reason="lscpu utility not available"
  631. )
  632. def test_against_lscpu(self):
  633. out = sh("lscpu -p")
  634. core_ids = set()
  635. for line in out.split('\n'):
  636. if not line.startswith('#'):
  637. fields = line.split(',')
  638. core_ids.add(fields[1])
  639. assert psutil.cpu_count(logical=False) == len(core_ids)
  640. @pytest.mark.skipif(
  641. platform.machine() not in {"x86_64", "i686"}, reason="x86_64/i686 only"
  642. )
  643. def test_method_2(self):
  644. meth_1 = psutil._pslinux.cpu_count_cores()
  645. with mock.patch('glob.glob', return_value=[]) as m:
  646. meth_2 = psutil._pslinux.cpu_count_cores()
  647. assert m.called
  648. if meth_1 is not None:
  649. assert meth_1 == meth_2
  650. def test_emulate_none(self):
  651. with mock.patch('glob.glob', return_value=[]) as m1:
  652. with mock.patch('psutil._common.open', create=True) as m2:
  653. assert psutil._pslinux.cpu_count_cores() is None
  654. assert m1.called
  655. assert m2.called
  656. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  657. class TestSystemCPUFrequency(PsutilTestCase):
  658. @pytest.mark.skipif(not HAS_CPU_FREQ, reason="not supported")
  659. @pytest.mark.skipif(
  660. AARCH64, reason="aarch64 does not always expose frequency"
  661. )
  662. def test_emulate_use_second_file(self):
  663. # https://github.com/giampaolo/psutil/issues/981
  664. def path_exists_mock(path):
  665. if path.startswith("/sys/devices/system/cpu/cpufreq/policy"):
  666. return False
  667. else:
  668. return orig_exists(path)
  669. orig_exists = os.path.exists
  670. with mock.patch(
  671. "os.path.exists", side_effect=path_exists_mock, create=True
  672. ):
  673. assert psutil.cpu_freq()
  674. @pytest.mark.skipif(not HAS_CPU_FREQ, reason="not supported")
  675. @pytest.mark.skipif(
  676. AARCH64 or RISCV64,
  677. reason=f"{platform.machine()} does not report mhz in /proc/cpuinfo",
  678. )
  679. def test_emulate_use_cpuinfo(self):
  680. # Emulate a case where /sys/devices/system/cpu/cpufreq* does not
  681. # exist and /proc/cpuinfo is used instead.
  682. def path_exists_mock(path):
  683. if path.startswith('/sys/devices/system/cpu/'):
  684. return False
  685. else:
  686. return os_path_exists(path)
  687. os_path_exists = os.path.exists
  688. try:
  689. with mock.patch("os.path.exists", side_effect=path_exists_mock):
  690. reload_module(psutil._pslinux)
  691. ret = psutil.cpu_freq()
  692. assert ret, ret
  693. assert ret.max == 0.0
  694. assert ret.min == 0.0
  695. for freq in psutil.cpu_freq(percpu=True):
  696. assert freq.max == 0.0
  697. assert freq.min == 0.0
  698. finally:
  699. reload_module(psutil._pslinux)
  700. reload_module(psutil)
  701. @pytest.mark.skipif(not HAS_CPU_FREQ, reason="not supported")
  702. def test_emulate_data(self):
  703. def open_mock(name, *args, **kwargs):
  704. if name.endswith('/scaling_cur_freq') and name.startswith(
  705. "/sys/devices/system/cpu/cpufreq/policy"
  706. ):
  707. return io.BytesIO(b"500000")
  708. elif name.endswith('/scaling_min_freq') and name.startswith(
  709. "/sys/devices/system/cpu/cpufreq/policy"
  710. ):
  711. return io.BytesIO(b"600000")
  712. elif name.endswith('/scaling_max_freq') and name.startswith(
  713. "/sys/devices/system/cpu/cpufreq/policy"
  714. ):
  715. return io.BytesIO(b"700000")
  716. elif name == '/proc/cpuinfo':
  717. return io.BytesIO(b"cpu MHz : 500")
  718. else:
  719. return orig_open(name, *args, **kwargs)
  720. orig_open = open
  721. with mock.patch("builtins.open", side_effect=open_mock):
  722. with mock.patch('os.path.exists', return_value=True):
  723. freq = psutil.cpu_freq()
  724. assert freq.current == 500.0
  725. # when /proc/cpuinfo is used min and max frequencies are not
  726. # available and are set to 0.
  727. if freq.min != 0.0:
  728. assert freq.min == 600.0
  729. if freq.max != 0.0:
  730. assert freq.max == 700.0
  731. @pytest.mark.skipif(not HAS_CPU_FREQ, reason="not supported")
  732. def test_emulate_multi_cpu(self):
  733. def open_mock(name, *args, **kwargs):
  734. n = name
  735. if n.endswith('/scaling_cur_freq') and n.startswith(
  736. "/sys/devices/system/cpu/cpufreq/policy0"
  737. ):
  738. return io.BytesIO(b"100000")
  739. elif n.endswith('/scaling_min_freq') and n.startswith(
  740. "/sys/devices/system/cpu/cpufreq/policy0"
  741. ):
  742. return io.BytesIO(b"200000")
  743. elif n.endswith('/scaling_max_freq') and n.startswith(
  744. "/sys/devices/system/cpu/cpufreq/policy0"
  745. ):
  746. return io.BytesIO(b"300000")
  747. elif n.endswith('/scaling_cur_freq') and n.startswith(
  748. "/sys/devices/system/cpu/cpufreq/policy1"
  749. ):
  750. return io.BytesIO(b"400000")
  751. elif n.endswith('/scaling_min_freq') and n.startswith(
  752. "/sys/devices/system/cpu/cpufreq/policy1"
  753. ):
  754. return io.BytesIO(b"500000")
  755. elif n.endswith('/scaling_max_freq') and n.startswith(
  756. "/sys/devices/system/cpu/cpufreq/policy1"
  757. ):
  758. return io.BytesIO(b"600000")
  759. elif name == '/proc/cpuinfo':
  760. return io.BytesIO(b"cpu MHz : 100\ncpu MHz : 400")
  761. else:
  762. return orig_open(name, *args, **kwargs)
  763. orig_open = open
  764. with mock.patch("builtins.open", side_effect=open_mock):
  765. with mock.patch('os.path.exists', return_value=True):
  766. with mock.patch(
  767. 'psutil._pslinux.cpu_count_logical', return_value=2
  768. ):
  769. freq = psutil.cpu_freq(percpu=True)
  770. assert freq[0].current == 100.0
  771. if freq[0].min != 0.0:
  772. assert freq[0].min == 200.0
  773. if freq[0].max != 0.0:
  774. assert freq[0].max == 300.0
  775. assert freq[1].current == 400.0
  776. if freq[1].min != 0.0:
  777. assert freq[1].min == 500.0
  778. if freq[1].max != 0.0:
  779. assert freq[1].max == 600.0
  780. @pytest.mark.skipif(not HAS_CPU_FREQ, reason="not supported")
  781. def test_emulate_no_scaling_cur_freq_file(self):
  782. # See: https://github.com/giampaolo/psutil/issues/1071
  783. def open_mock(name, *args, **kwargs):
  784. if name.endswith('/scaling_cur_freq'):
  785. raise FileNotFoundError
  786. if name.endswith('/cpuinfo_cur_freq'):
  787. return io.BytesIO(b"200000")
  788. elif name == '/proc/cpuinfo':
  789. return io.BytesIO(b"cpu MHz : 200")
  790. else:
  791. return orig_open(name, *args, **kwargs)
  792. orig_open = open
  793. with mock.patch("builtins.open", side_effect=open_mock):
  794. with mock.patch('os.path.exists', return_value=True):
  795. with mock.patch(
  796. 'psutil._pslinux.cpu_count_logical', return_value=1
  797. ):
  798. freq = psutil.cpu_freq()
  799. assert freq.current == 200
  800. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  801. class TestSystemCPUStats(PsutilTestCase):
  802. # XXX: fails too often.
  803. # def test_ctx_switches(self):
  804. # vmstat_value = vmstat("context switches")
  805. # psutil_value = psutil.cpu_stats().ctx_switches
  806. # assert abs(vmstat_value - psutil_value) < 500
  807. def test_interrupts(self):
  808. vmstat_value = vmstat("interrupts")
  809. psutil_value = psutil.cpu_stats().interrupts
  810. assert abs(vmstat_value - psutil_value) < 500
  811. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  812. class TestLoadAvg(PsutilTestCase):
  813. @pytest.mark.skipif(not HAS_GETLOADAVG, reason="not supported")
  814. def test_getloadavg(self):
  815. psutil_value = psutil.getloadavg()
  816. with open("/proc/loadavg") as f:
  817. proc_value = f.read().split()
  818. assert abs(float(proc_value[0]) - psutil_value[0]) < 1
  819. assert abs(float(proc_value[1]) - psutil_value[1]) < 1
  820. assert abs(float(proc_value[2]) - psutil_value[2]) < 1
  821. # =====================================================================
  822. # --- system network
  823. # =====================================================================
  824. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  825. class TestSystemNetIfAddrs(PsutilTestCase):
  826. def test_ips(self):
  827. for name, addrs in psutil.net_if_addrs().items():
  828. for addr in addrs:
  829. if addr.family == psutil.AF_LINK:
  830. assert addr.address == get_mac_address(name)
  831. elif addr.family == socket.AF_INET:
  832. assert addr.address == get_ipv4_address(name)
  833. assert addr.netmask == get_ipv4_netmask(name)
  834. if addr.broadcast is not None:
  835. assert addr.broadcast == get_ipv4_broadcast(name)
  836. else:
  837. assert get_ipv4_broadcast(name) == '0.0.0.0'
  838. elif addr.family == socket.AF_INET6:
  839. # IPv6 addresses can have a percent symbol at the end.
  840. # E.g. these 2 are equivalent:
  841. # "fe80::1ff:fe23:4567:890a"
  842. # "fe80::1ff:fe23:4567:890a%eth0"
  843. # That is the "zone id" portion, which usually is the name
  844. # of the network interface.
  845. address = addr.address.split('%')[0]
  846. assert address in get_ipv6_addresses(name)
  847. # XXX - not reliable when having virtual NICs installed by Docker.
  848. # @pytest.mark.skipif(not shutil.which("ip"),
  849. # reason="'ip' utility not available")
  850. # def test_net_if_names(self):
  851. # out = sh("ip addr").strip()
  852. # nics = [x for x in psutil.net_if_addrs().keys() if ':' not in x]
  853. # found = 0
  854. # for line in out.split('\n'):
  855. # line = line.strip()
  856. # if re.search(r"^\d+:", line):
  857. # found += 1
  858. # name = line.split(':')[1].strip()
  859. # assert name in nics
  860. # assert len(nics) == found
  861. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  862. class TestSystemNetIfStats(PsutilTestCase):
  863. @pytest.mark.skipif(
  864. not shutil.which("ifconfig"), reason="ifconfig utility not available"
  865. )
  866. def test_against_ifconfig(self):
  867. for name, stats in psutil.net_if_stats().items():
  868. try:
  869. out = sh(f"ifconfig {name}")
  870. except RuntimeError:
  871. pass
  872. else:
  873. assert stats.isup == ('RUNNING' in out), out
  874. assert stats.mtu == int(
  875. re.findall(r'(?i)MTU[: ](\d+)', out)[0]
  876. )
  877. def test_mtu(self):
  878. for name, stats in psutil.net_if_stats().items():
  879. with open(f"/sys/class/net/{name}/mtu") as f:
  880. assert stats.mtu == int(f.read().strip())
  881. @pytest.mark.skipif(
  882. not shutil.which("ifconfig"), reason="ifconfig utility not available"
  883. )
  884. def test_flags(self):
  885. # first line looks like this:
  886. # "eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500"
  887. matches_found = 0
  888. for name, stats in psutil.net_if_stats().items():
  889. try:
  890. out = sh(f"ifconfig {name}")
  891. except RuntimeError:
  892. pass
  893. else:
  894. match = re.search(r"flags=(\d+)?<(.*?)>", out)
  895. if match and len(match.groups()) >= 2:
  896. matches_found += 1
  897. ifconfig_flags = set(match.group(2).lower().split(","))
  898. psutil_flags = set(stats.flags.split(","))
  899. assert ifconfig_flags == psutil_flags
  900. else:
  901. # ifconfig has a different output on CentOS 6
  902. # let's try that
  903. match = re.search(r"(.*) MTU:(\d+) Metric:(\d+)", out)
  904. if match and len(match.groups()) >= 3:
  905. matches_found += 1
  906. ifconfig_flags = set(match.group(1).lower().split())
  907. psutil_flags = set(stats.flags.split(","))
  908. assert ifconfig_flags == psutil_flags
  909. if not matches_found:
  910. return pytest.fail("no matches were found")
  911. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  912. class TestSystemNetIOCounters(PsutilTestCase):
  913. @pytest.mark.skipif(
  914. not shutil.which("ifconfig"), reason="ifconfig utility not available"
  915. )
  916. @retry_on_failure()
  917. def test_against_ifconfig(self):
  918. def ifconfig(nic):
  919. ret = {}
  920. out = sh(f"ifconfig {nic}")
  921. ret['packets_recv'] = int(
  922. re.findall(r'RX packets[: ](\d+)', out)[0]
  923. )
  924. ret['packets_sent'] = int(
  925. re.findall(r'TX packets[: ](\d+)', out)[0]
  926. )
  927. ret['errin'] = int(re.findall(r'errors[: ](\d+)', out)[0])
  928. ret['errout'] = int(re.findall(r'errors[: ](\d+)', out)[1])
  929. ret['dropin'] = int(re.findall(r'dropped[: ](\d+)', out)[0])
  930. ret['dropout'] = int(re.findall(r'dropped[: ](\d+)', out)[1])
  931. ret['bytes_recv'] = int(
  932. re.findall(r'RX (?:packets \d+ +)?bytes[: ](\d+)', out)[0]
  933. )
  934. ret['bytes_sent'] = int(
  935. re.findall(r'TX (?:packets \d+ +)?bytes[: ](\d+)', out)[0]
  936. )
  937. return ret
  938. nio = psutil.net_io_counters(pernic=True, nowrap=False)
  939. for name, stats in nio.items():
  940. try:
  941. ifconfig_ret = ifconfig(name)
  942. except RuntimeError:
  943. continue
  944. assert (
  945. abs(stats.bytes_recv - ifconfig_ret['bytes_recv']) < 1024 * 10
  946. )
  947. assert (
  948. abs(stats.bytes_sent - ifconfig_ret['bytes_sent']) < 1024 * 10
  949. )
  950. assert (
  951. abs(stats.packets_recv - ifconfig_ret['packets_recv']) < 1024
  952. )
  953. assert (
  954. abs(stats.packets_sent - ifconfig_ret['packets_sent']) < 1024
  955. )
  956. assert abs(stats.errin - ifconfig_ret['errin']) < 10
  957. assert abs(stats.errout - ifconfig_ret['errout']) < 10
  958. assert abs(stats.dropin - ifconfig_ret['dropin']) < 10
  959. assert abs(stats.dropout - ifconfig_ret['dropout']) < 10
  960. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  961. class TestSystemNetConnections(PsutilTestCase):
  962. @mock.patch('psutil._pslinux.socket.inet_ntop', side_effect=ValueError)
  963. @mock.patch('psutil._pslinux.supports_ipv6', return_value=False)
  964. def test_emulate_ipv6_unsupported(self, supports_ipv6, inet_ntop):
  965. # see: https://github.com/giampaolo/psutil/issues/623
  966. with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
  967. try:
  968. s.bind(("::1", 0))
  969. except OSError:
  970. pass
  971. psutil.net_connections(kind='inet6')
  972. def test_emulate_unix(self):
  973. content = textwrap.dedent("""\
  974. 0: 00000003 000 000 0001 03 462170 @/tmp/dbus-Qw2hMPIU3n
  975. 0: 00000003 000 000 0001 03 35010 @/tmp/dbus-tB2X8h69BQ
  976. 0: 00000003 000 000 0001 03 34424 @/tmp/dbus-cHy80Y8O
  977. 000000000000000000000000000000000000000000000000000000
  978. """)
  979. with mock_open_content({"/proc/net/unix": content}) as m:
  980. psutil.net_connections(kind='unix')
  981. assert m.called
  982. # =====================================================================
  983. # --- system disks
  984. # =====================================================================
  985. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  986. class TestSystemDiskPartitions(PsutilTestCase):
  987. @pytest.mark.skipif(
  988. not hasattr(os, 'statvfs'), reason="os.statvfs() not available"
  989. )
  990. @skip_on_not_implemented()
  991. def test_against_df(self):
  992. # test psutil.disk_usage() and psutil.disk_partitions()
  993. # against "df -a"
  994. def df(path):
  995. out = sh(f'df -P -B 1 "{path}"').strip()
  996. lines = out.split('\n')
  997. lines.pop(0)
  998. line = lines.pop(0)
  999. dev, total, used, free = line.split()[:4]
  1000. if dev == 'none':
  1001. dev = ''
  1002. total, used, free = int(total), int(used), int(free)
  1003. return dev, total, used, free
  1004. for part in psutil.disk_partitions(all=False):
  1005. usage = psutil.disk_usage(part.mountpoint)
  1006. _, total, used, free = df(part.mountpoint)
  1007. assert usage.total == total
  1008. assert abs(usage.free - free) < TOLERANCE_DISK_USAGE
  1009. assert abs(usage.used - used) < TOLERANCE_DISK_USAGE
  1010. def test_zfs_fs(self):
  1011. # Test that ZFS partitions are returned.
  1012. with open("/proc/filesystems") as f:
  1013. data = f.read()
  1014. if 'zfs' in data:
  1015. for part in psutil.disk_partitions():
  1016. if part.fstype == 'zfs':
  1017. return
  1018. # No ZFS partitions on this system. Let's fake one.
  1019. fake_file = io.StringIO("nodev\tzfs\n")
  1020. with mock.patch(
  1021. 'psutil._common.open', return_value=fake_file, create=True
  1022. ) as m1:
  1023. with mock.patch(
  1024. 'psutil._pslinux.cext.disk_partitions',
  1025. return_value=[('/dev/sdb3', '/', 'zfs', 'rw')],
  1026. ) as m2:
  1027. ret = psutil.disk_partitions()
  1028. assert m1.called
  1029. assert m2.called
  1030. assert ret
  1031. assert ret[0].fstype == 'zfs'
  1032. def test_emulate_realpath_fail(self):
  1033. # See: https://github.com/giampaolo/psutil/issues/1307
  1034. try:
  1035. with mock.patch(
  1036. 'os.path.realpath', return_value='/non/existent'
  1037. ) as m:
  1038. with pytest.raises(FileNotFoundError):
  1039. psutil.disk_partitions()
  1040. assert m.called
  1041. finally:
  1042. psutil.PROCFS_PATH = "/proc"
  1043. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  1044. class TestSystemDiskIoCounters(PsutilTestCase):
  1045. def test_emulate_kernel_2_4(self):
  1046. # Tests /proc/diskstats parsing format for 2.4 kernels, see:
  1047. # https://github.com/giampaolo/psutil/issues/767
  1048. content = " 3 0 1 hda 2 3 4 5 6 7 8 9 10 11 12"
  1049. with mock_open_content({'/proc/diskstats': content}):
  1050. with mock.patch(
  1051. 'psutil._pslinux.is_storage_device', return_value=True
  1052. ):
  1053. ret = psutil.disk_io_counters(nowrap=False)
  1054. assert ret.read_count == 1
  1055. assert ret.read_merged_count == 2
  1056. assert ret.read_bytes == 3 * SECTOR_SIZE
  1057. assert ret.read_time == 4
  1058. assert ret.write_count == 5
  1059. assert ret.write_merged_count == 6
  1060. assert ret.write_bytes == 7 * SECTOR_SIZE
  1061. assert ret.write_time == 8
  1062. assert ret.busy_time == 10
  1063. def test_emulate_kernel_2_6_full(self):
  1064. # Tests /proc/diskstats parsing format for 2.6 kernels,
  1065. # lines reporting all metrics:
  1066. # https://github.com/giampaolo/psutil/issues/767
  1067. content = " 3 0 hda 1 2 3 4 5 6 7 8 9 10 11"
  1068. with mock_open_content({"/proc/diskstats": content}):
  1069. with mock.patch(
  1070. 'psutil._pslinux.is_storage_device', return_value=True
  1071. ):
  1072. ret = psutil.disk_io_counters(nowrap=False)
  1073. assert ret.read_count == 1
  1074. assert ret.read_merged_count == 2
  1075. assert ret.read_bytes == 3 * SECTOR_SIZE
  1076. assert ret.read_time == 4
  1077. assert ret.write_count == 5
  1078. assert ret.write_merged_count == 6
  1079. assert ret.write_bytes == 7 * SECTOR_SIZE
  1080. assert ret.write_time == 8
  1081. assert ret.busy_time == 10
  1082. def test_emulate_kernel_2_6_limited(self):
  1083. # Tests /proc/diskstats parsing format for 2.6 kernels,
  1084. # where one line of /proc/partitions return a limited
  1085. # amount of metrics when it bumps into a partition
  1086. # (instead of a disk). See:
  1087. # https://github.com/giampaolo/psutil/issues/767
  1088. with mock_open_content({"/proc/diskstats": " 3 1 hda 1 2 3 4"}):
  1089. with mock.patch(
  1090. 'psutil._pslinux.is_storage_device', return_value=True
  1091. ):
  1092. ret = psutil.disk_io_counters(nowrap=False)
  1093. assert ret.read_count == 1
  1094. assert ret.read_bytes == 2 * SECTOR_SIZE
  1095. assert ret.write_count == 3
  1096. assert ret.write_bytes == 4 * SECTOR_SIZE
  1097. assert ret.read_merged_count == 0
  1098. assert ret.read_time == 0
  1099. assert ret.write_merged_count == 0
  1100. assert ret.write_time == 0
  1101. assert ret.busy_time == 0
  1102. def test_emulate_include_partitions(self):
  1103. # Make sure that when perdisk=True disk partitions are returned,
  1104. # see:
  1105. # https://github.com/giampaolo/psutil/pull/1313#issuecomment-408626842
  1106. content = textwrap.dedent("""\
  1107. 3 0 nvme0n1 1 2 3 4 5 6 7 8 9 10 11
  1108. 3 0 nvme0n1p1 1 2 3 4 5 6 7 8 9 10 11
  1109. """)
  1110. with mock_open_content({"/proc/diskstats": content}):
  1111. with mock.patch(
  1112. 'psutil._pslinux.is_storage_device', return_value=False
  1113. ):
  1114. ret = psutil.disk_io_counters(perdisk=True, nowrap=False)
  1115. assert len(ret) == 2
  1116. assert ret['nvme0n1'].read_count == 1
  1117. assert ret['nvme0n1p1'].read_count == 1
  1118. assert ret['nvme0n1'].write_count == 5
  1119. assert ret['nvme0n1p1'].write_count == 5
  1120. def test_emulate_exclude_partitions(self):
  1121. # Make sure that when perdisk=False partitions (e.g. 'sda1',
  1122. # 'nvme0n1p1') are skipped and not included in the total count.
  1123. # https://github.com/giampaolo/psutil/pull/1313#issuecomment-408626842
  1124. content = textwrap.dedent("""\
  1125. 3 0 nvme0n1 1 2 3 4 5 6 7 8 9 10 11
  1126. 3 0 nvme0n1p1 1 2 3 4 5 6 7 8 9 10 11
  1127. """)
  1128. with mock_open_content({"/proc/diskstats": content}):
  1129. with mock.patch(
  1130. 'psutil._pslinux.is_storage_device', return_value=False
  1131. ):
  1132. ret = psutil.disk_io_counters(perdisk=False, nowrap=False)
  1133. assert ret is None
  1134. def is_storage_device(name):
  1135. return name == 'nvme0n1'
  1136. content = textwrap.dedent("""\
  1137. 3 0 nvme0n1 1 2 3 4 5 6 7 8 9 10 11
  1138. 3 0 nvme0n1p1 1 2 3 4 5 6 7 8 9 10 11
  1139. """)
  1140. with mock_open_content({"/proc/diskstats": content}):
  1141. with mock.patch(
  1142. 'psutil._pslinux.is_storage_device',
  1143. create=True,
  1144. side_effect=is_storage_device,
  1145. ):
  1146. ret = psutil.disk_io_counters(perdisk=False, nowrap=False)
  1147. assert ret.read_count == 1
  1148. assert ret.write_count == 5
  1149. def test_emulate_use_sysfs(self):
  1150. def exists(path):
  1151. return path == '/proc/diskstats'
  1152. wprocfs = psutil.disk_io_counters(perdisk=True)
  1153. with mock.patch(
  1154. 'psutil._pslinux.os.path.exists', create=True, side_effect=exists
  1155. ):
  1156. wsysfs = psutil.disk_io_counters(perdisk=True)
  1157. assert len(wprocfs) == len(wsysfs)
  1158. def test_emulate_not_impl(self):
  1159. def exists(path):
  1160. return False
  1161. with mock.patch(
  1162. 'psutil._pslinux.os.path.exists', create=True, side_effect=exists
  1163. ):
  1164. with pytest.raises(NotImplementedError):
  1165. psutil.disk_io_counters()
  1166. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  1167. class TestRootFsDeviceFinder(PsutilTestCase):
  1168. def setUp(self):
  1169. dev = os.stat("/").st_dev
  1170. self.major = os.major(dev)
  1171. self.minor = os.minor(dev)
  1172. def test_call_methods(self):
  1173. finder = RootFsDeviceFinder()
  1174. if os.path.exists("/proc/partitions"):
  1175. finder.ask_proc_partitions()
  1176. else:
  1177. with pytest.raises(FileNotFoundError):
  1178. finder.ask_proc_partitions()
  1179. if os.path.exists(f"/sys/dev/block/{self.major}:{self.minor}/uevent"):
  1180. finder.ask_sys_dev_block()
  1181. else:
  1182. with pytest.raises(FileNotFoundError):
  1183. finder.ask_sys_dev_block()
  1184. finder.ask_sys_class_block()
  1185. @pytest.mark.skipif(GITHUB_ACTIONS, reason="unsupported on GITHUB_ACTIONS")
  1186. def test_comparisons(self):
  1187. finder = RootFsDeviceFinder()
  1188. assert finder.find() is not None
  1189. a = b = c = None
  1190. if os.path.exists("/proc/partitions"):
  1191. a = finder.ask_proc_partitions()
  1192. if os.path.exists(f"/sys/dev/block/{self.major}:{self.minor}/uevent"):
  1193. b = finder.ask_sys_class_block()
  1194. c = finder.ask_sys_dev_block()
  1195. base = a or b or c
  1196. if base and a:
  1197. assert base == a
  1198. if base and b:
  1199. assert base == b
  1200. if base and c:
  1201. assert base == c
  1202. @pytest.mark.skipif(
  1203. not shutil.which("findmnt"), reason="findmnt utility not available"
  1204. )
  1205. @pytest.mark.skipif(GITHUB_ACTIONS, reason="unsupported on GITHUB_ACTIONS")
  1206. def test_against_findmnt(self):
  1207. psutil_value = RootFsDeviceFinder().find()
  1208. findmnt_value = sh("findmnt -o SOURCE -rn /")
  1209. assert psutil_value == findmnt_value
  1210. def test_disk_partitions_mocked(self):
  1211. with mock.patch(
  1212. 'psutil._pslinux.cext.disk_partitions',
  1213. return_value=[('/dev/root', '/', 'ext4', 'rw')],
  1214. ) as m:
  1215. part = psutil.disk_partitions()[0]
  1216. assert m.called
  1217. if not GITHUB_ACTIONS:
  1218. assert part.device != "/dev/root"
  1219. assert part.device == RootFsDeviceFinder().find()
  1220. else:
  1221. assert part.device == "/dev/root"
  1222. # =====================================================================
  1223. # --- misc
  1224. # =====================================================================
  1225. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  1226. class TestMisc(PsutilTestCase):
  1227. def test_boot_time(self):
  1228. vmstat_value = vmstat('boot time')
  1229. psutil_value = psutil.boot_time()
  1230. assert int(vmstat_value) == int(psutil_value)
  1231. def test_no_procfs_on_import(self):
  1232. my_procfs = self.get_testfn()
  1233. os.mkdir(my_procfs)
  1234. with open(os.path.join(my_procfs, 'stat'), 'w') as f:
  1235. f.write('cpu 0 0 0 0 0 0 0 0 0 0\n')
  1236. f.write('cpu0 0 0 0 0 0 0 0 0 0 0\n')
  1237. f.write('cpu1 0 0 0 0 0 0 0 0 0 0\n')
  1238. try:
  1239. orig_open = open
  1240. def open_mock(name, *args, **kwargs):
  1241. if name.startswith('/proc'):
  1242. raise FileNotFoundError
  1243. return orig_open(name, *args, **kwargs)
  1244. with mock.patch("builtins.open", side_effect=open_mock):
  1245. reload_module(psutil)
  1246. with pytest.raises(OSError):
  1247. psutil.cpu_times()
  1248. with pytest.raises(OSError):
  1249. psutil.cpu_times(percpu=True)
  1250. with pytest.raises(OSError):
  1251. psutil.cpu_percent()
  1252. with pytest.raises(OSError):
  1253. psutil.cpu_percent(percpu=True)
  1254. with pytest.raises(OSError):
  1255. psutil.cpu_times_percent()
  1256. with pytest.raises(OSError):
  1257. psutil.cpu_times_percent(percpu=True)
  1258. psutil.PROCFS_PATH = my_procfs
  1259. assert psutil.cpu_percent() == 0
  1260. assert sum(psutil.cpu_times_percent()) == 0
  1261. # since we don't know the number of CPUs at import time,
  1262. # we awkwardly say there are none until the second call
  1263. per_cpu_percent = psutil.cpu_percent(percpu=True)
  1264. assert sum(per_cpu_percent) == 0
  1265. # ditto awkward length
  1266. per_cpu_times_percent = psutil.cpu_times_percent(percpu=True)
  1267. assert sum(map(sum, per_cpu_times_percent)) == 0
  1268. # much user, very busy
  1269. with open(os.path.join(my_procfs, 'stat'), 'w') as f:
  1270. f.write('cpu 1 0 0 0 0 0 0 0 0 0\n')
  1271. f.write('cpu0 1 0 0 0 0 0 0 0 0 0\n')
  1272. f.write('cpu1 1 0 0 0 0 0 0 0 0 0\n')
  1273. assert psutil.cpu_percent() != 0
  1274. assert sum(psutil.cpu_percent(percpu=True)) != 0
  1275. assert sum(psutil.cpu_times_percent()) != 0
  1276. assert (
  1277. sum(map(sum, psutil.cpu_times_percent(percpu=True))) != 0
  1278. )
  1279. finally:
  1280. shutil.rmtree(my_procfs)
  1281. reload_module(psutil)
  1282. assert psutil.PROCFS_PATH == '/proc'
  1283. def test_cpu_steal_decrease(self):
  1284. # Test cumulative cpu stats decrease. We should ignore this.
  1285. # See issue #1210.
  1286. content = textwrap.dedent("""\
  1287. cpu 0 0 0 0 0 0 0 1 0 0
  1288. cpu0 0 0 0 0 0 0 0 1 0 0
  1289. cpu1 0 0 0 0 0 0 0 1 0 0
  1290. """).encode()
  1291. with mock_open_content({"/proc/stat": content}) as m:
  1292. # first call to "percent" functions should read the new stat file
  1293. # and compare to the "real" file read at import time - so the
  1294. # values are meaningless
  1295. psutil.cpu_percent()
  1296. assert m.called
  1297. psutil.cpu_percent(percpu=True)
  1298. psutil.cpu_times_percent()
  1299. psutil.cpu_times_percent(percpu=True)
  1300. content = textwrap.dedent("""\
  1301. cpu 1 0 0 0 0 0 0 0 0 0
  1302. cpu0 1 0 0 0 0 0 0 0 0 0
  1303. cpu1 1 0 0 0 0 0 0 0 0 0
  1304. """).encode()
  1305. with mock_open_content({"/proc/stat": content}):
  1306. # Increase "user" while steal goes "backwards" to zero.
  1307. cpu_percent = psutil.cpu_percent()
  1308. assert m.called
  1309. cpu_percent_percpu = psutil.cpu_percent(percpu=True)
  1310. cpu_times_percent = psutil.cpu_times_percent()
  1311. cpu_times_percent_percpu = psutil.cpu_times_percent(percpu=True)
  1312. assert cpu_percent != 0
  1313. assert sum(cpu_percent_percpu) != 0
  1314. assert sum(cpu_times_percent) != 0
  1315. assert sum(cpu_times_percent) != 100.0
  1316. assert sum(map(sum, cpu_times_percent_percpu)) != 0
  1317. assert sum(map(sum, cpu_times_percent_percpu)) != 100.0
  1318. assert cpu_times_percent.steal == 0
  1319. assert cpu_times_percent.user != 0
  1320. def test_boot_time_mocked(self):
  1321. with mock.patch('psutil._common.open', create=True) as m:
  1322. with pytest.raises(RuntimeError):
  1323. psutil._pslinux.boot_time()
  1324. assert m.called
  1325. def test_users(self):
  1326. # Make sure the C extension converts ':0' and ':0.0' to
  1327. # 'localhost'.
  1328. for user in psutil.users():
  1329. assert user.host not in {":0", ":0.0"}
  1330. def test_procfs_path(self):
  1331. tdir = self.get_testfn()
  1332. os.mkdir(tdir)
  1333. try:
  1334. psutil.PROCFS_PATH = tdir
  1335. with pytest.raises(OSError):
  1336. psutil.virtual_memory()
  1337. with pytest.raises(OSError):
  1338. psutil.cpu_times()
  1339. with pytest.raises(OSError):
  1340. psutil.cpu_times(percpu=True)
  1341. with pytest.raises(OSError):
  1342. psutil.boot_time()
  1343. with pytest.raises(OSError):
  1344. psutil.net_connections()
  1345. with pytest.raises(OSError):
  1346. psutil.net_io_counters()
  1347. with pytest.raises(OSError):
  1348. psutil.net_if_stats()
  1349. with pytest.raises(OSError):
  1350. psutil.disk_partitions()
  1351. with pytest.raises(psutil.NoSuchProcess):
  1352. psutil.Process()
  1353. finally:
  1354. psutil.PROCFS_PATH = "/proc"
  1355. @retry_on_failure()
  1356. @pytest.mark.xdist_group(name="serial")
  1357. def test_issue_687(self):
  1358. # In case of thread ID:
  1359. # - pid_exists() is supposed to return False
  1360. # - Process(tid) is supposed to work
  1361. # - pids() should not return the TID
  1362. # See: https://github.com/giampaolo/psutil/issues/687
  1363. p = psutil.Process()
  1364. nthreads = len(p.threads())
  1365. with ThreadTask():
  1366. threads = p.threads()
  1367. assert len(threads) == nthreads + 1
  1368. tid = sorted(threads, key=lambda x: x.id)[1].id
  1369. assert p.pid != tid
  1370. pt = psutil.Process(tid)
  1371. pt.as_dict()
  1372. assert tid not in psutil.pids()
  1373. def test_pid_exists_no_proc_status(self):
  1374. # Internally pid_exists relies on /proc/{pid}/status.
  1375. # Emulate a case where this file is empty in which case
  1376. # psutil is supposed to fall back on using pids().
  1377. with mock_open_content({"/proc/%s/status": ""}) as m:
  1378. assert psutil.pid_exists(os.getpid())
  1379. assert m.called
  1380. # =====================================================================
  1381. # --- sensors
  1382. # =====================================================================
  1383. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  1384. @pytest.mark.skipif(not HAS_BATTERY, reason="no battery")
  1385. class TestSensorsBattery(PsutilTestCase):
  1386. @pytest.mark.skipif(
  1387. not shutil.which("acpi"), reason="acpi utility not available"
  1388. )
  1389. def test_percent(self):
  1390. out = sh("acpi -b")
  1391. acpi_value = int(out.split(",")[1].strip().replace('%', ''))
  1392. psutil_value = psutil.sensors_battery().percent
  1393. assert abs(acpi_value - psutil_value) < 1
  1394. def test_emulate_power_plugged(self):
  1395. # Pretend the AC power cable is connected.
  1396. def open_mock(name, *args, **kwargs):
  1397. if name.endswith(('AC0/online', 'AC/online')):
  1398. return io.BytesIO(b"1")
  1399. else:
  1400. return orig_open(name, *args, **kwargs)
  1401. orig_open = open
  1402. with mock.patch("builtins.open", side_effect=open_mock) as m:
  1403. assert psutil.sensors_battery().power_plugged is True
  1404. assert (
  1405. psutil.sensors_battery().secsleft
  1406. == psutil.POWER_TIME_UNLIMITED
  1407. )
  1408. assert m.called
  1409. def test_emulate_power_plugged_2(self):
  1410. # Same as above but pretend /AC0/online does not exist in which
  1411. # case code relies on /status file.
  1412. def open_mock(name, *args, **kwargs):
  1413. if name.endswith(('AC0/online', 'AC/online')):
  1414. raise FileNotFoundError
  1415. if name.endswith("/status"):
  1416. return io.StringIO("charging")
  1417. else:
  1418. return orig_open(name, *args, **kwargs)
  1419. orig_open = open
  1420. with mock.patch("builtins.open", side_effect=open_mock) as m:
  1421. assert psutil.sensors_battery().power_plugged is True
  1422. assert m.called
  1423. def test_emulate_power_not_plugged(self):
  1424. # Pretend the AC power cable is not connected.
  1425. def open_mock(name, *args, **kwargs):
  1426. if name.endswith(('AC0/online', 'AC/online')):
  1427. return io.BytesIO(b"0")
  1428. else:
  1429. return orig_open(name, *args, **kwargs)
  1430. orig_open = open
  1431. with mock.patch("builtins.open", side_effect=open_mock) as m:
  1432. assert psutil.sensors_battery().power_plugged is False
  1433. assert m.called
  1434. def test_emulate_power_not_plugged_2(self):
  1435. # Same as above but pretend /AC0/online does not exist in which
  1436. # case code relies on /status file.
  1437. def open_mock(name, *args, **kwargs):
  1438. if name.endswith(('AC0/online', 'AC/online')):
  1439. raise FileNotFoundError
  1440. if name.endswith("/status"):
  1441. return io.StringIO("discharging")
  1442. else:
  1443. return orig_open(name, *args, **kwargs)
  1444. orig_open = open
  1445. with mock.patch("builtins.open", side_effect=open_mock) as m:
  1446. assert psutil.sensors_battery().power_plugged is False
  1447. assert m.called
  1448. def test_emulate_power_undetermined(self):
  1449. # Pretend we can't know whether the AC power cable not
  1450. # connected (assert fallback to False).
  1451. def open_mock(name, *args, **kwargs):
  1452. if name.startswith((
  1453. '/sys/class/power_supply/AC0/online',
  1454. '/sys/class/power_supply/AC/online',
  1455. )):
  1456. raise FileNotFoundError
  1457. if name.startswith("/sys/class/power_supply/BAT0/status"):
  1458. return io.BytesIO(b"???")
  1459. else:
  1460. return orig_open(name, *args, **kwargs)
  1461. orig_open = open
  1462. with mock.patch("builtins.open", side_effect=open_mock) as m:
  1463. assert psutil.sensors_battery().power_plugged is None
  1464. assert m.called
  1465. def test_emulate_energy_full_0(self):
  1466. # Emulate a case where energy_full files returns 0.
  1467. with mock_open_content(
  1468. {"/sys/class/power_supply/BAT0/energy_full": b"0"}
  1469. ) as m:
  1470. assert psutil.sensors_battery().percent == 0
  1471. assert m.called
  1472. def test_emulate_energy_full_not_avail(self):
  1473. # Emulate a case where energy_full file does not exist.
  1474. # Expected fallback on /capacity.
  1475. with mock_open_exception(
  1476. "/sys/class/power_supply/BAT0/energy_full",
  1477. FileNotFoundError,
  1478. ):
  1479. with mock_open_exception(
  1480. "/sys/class/power_supply/BAT0/charge_full",
  1481. FileNotFoundError,
  1482. ):
  1483. with mock_open_content(
  1484. {"/sys/class/power_supply/BAT0/capacity": b"88"}
  1485. ):
  1486. assert psutil.sensors_battery().percent == 88
  1487. def test_emulate_no_power(self):
  1488. # Emulate a case where /AC0/online file nor /BAT0/status exist.
  1489. with mock_open_exception(
  1490. "/sys/class/power_supply/AC/online", FileNotFoundError
  1491. ):
  1492. with mock_open_exception(
  1493. "/sys/class/power_supply/AC0/online", FileNotFoundError
  1494. ):
  1495. with mock_open_exception(
  1496. "/sys/class/power_supply/BAT0/status",
  1497. FileNotFoundError,
  1498. ):
  1499. assert psutil.sensors_battery().power_plugged is None
  1500. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  1501. class TestSensorsBatteryEmulated(PsutilTestCase):
  1502. def test_it(self):
  1503. def open_mock(name, *args, **kwargs):
  1504. if name.endswith("/energy_now"):
  1505. return io.StringIO("60000000")
  1506. elif name.endswith("/power_now"):
  1507. return io.StringIO("0")
  1508. elif name.endswith("/energy_full"):
  1509. return io.StringIO("60000001")
  1510. else:
  1511. return orig_open(name, *args, **kwargs)
  1512. orig_open = open
  1513. with mock.patch('os.listdir', return_value=["BAT0"]) as mlistdir:
  1514. with mock.patch("builtins.open", side_effect=open_mock) as mopen:
  1515. assert psutil.sensors_battery() is not None
  1516. assert mlistdir.called
  1517. assert mopen.called
  1518. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  1519. class TestSensorsTemperatures(PsutilTestCase):
  1520. def test_emulate_class_hwmon(self):
  1521. def open_mock(name, *args, **kwargs):
  1522. if name.endswith('/name'):
  1523. return io.StringIO("name")
  1524. elif name.endswith('/temp1_label'):
  1525. return io.StringIO("label")
  1526. elif name.endswith('/temp1_input'):
  1527. return io.BytesIO(b"30000")
  1528. elif name.endswith('/temp1_max'):
  1529. return io.BytesIO(b"40000")
  1530. elif name.endswith('/temp1_crit'):
  1531. return io.BytesIO(b"50000")
  1532. else:
  1533. return orig_open(name, *args, **kwargs)
  1534. orig_open = open
  1535. with mock.patch("builtins.open", side_effect=open_mock):
  1536. # Test case with /sys/class/hwmon
  1537. with mock.patch(
  1538. 'glob.glob', return_value=['/sys/class/hwmon/hwmon0/temp1']
  1539. ):
  1540. temp = psutil.sensors_temperatures()['name'][0]
  1541. assert temp.label == 'label'
  1542. assert temp.current == 30.0
  1543. assert temp.high == 40.0
  1544. assert temp.critical == 50.0
  1545. def test_emulate_class_thermal(self):
  1546. def open_mock(name, *args, **kwargs):
  1547. if name.endswith('0_temp'):
  1548. return io.BytesIO(b"50000")
  1549. elif name.endswith('temp'):
  1550. return io.BytesIO(b"30000")
  1551. elif name.endswith('0_type'):
  1552. return io.StringIO("critical")
  1553. elif name.endswith('type'):
  1554. return io.StringIO("name")
  1555. else:
  1556. return orig_open(name, *args, **kwargs)
  1557. def glob_mock(path):
  1558. if path in {
  1559. '/sys/class/hwmon/hwmon*/temp*_*',
  1560. '/sys/class/hwmon/hwmon*/device/temp*_*',
  1561. }:
  1562. return []
  1563. elif path == '/sys/class/thermal/thermal_zone*':
  1564. return ['/sys/class/thermal/thermal_zone0']
  1565. elif path == '/sys/class/thermal/thermal_zone0/trip_point*':
  1566. return [
  1567. '/sys/class/thermal/thermal_zone1/trip_point_0_type',
  1568. '/sys/class/thermal/thermal_zone1/trip_point_0_temp',
  1569. ]
  1570. return []
  1571. orig_open = open
  1572. with mock.patch("builtins.open", side_effect=open_mock):
  1573. with mock.patch('glob.glob', create=True, side_effect=glob_mock):
  1574. temp = psutil.sensors_temperatures()['name'][0]
  1575. assert temp.label == ''
  1576. assert temp.current == 30.0
  1577. assert temp.high == 50.0
  1578. assert temp.critical == 50.0
  1579. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  1580. class TestSensorsFans(PsutilTestCase):
  1581. def test_emulate_data(self):
  1582. def open_mock(name, *args, **kwargs):
  1583. if name.endswith('/name'):
  1584. return io.StringIO("name")
  1585. elif name.endswith('/fan1_label'):
  1586. return io.StringIO("label")
  1587. elif name.endswith('/fan1_input'):
  1588. return io.StringIO("2000")
  1589. else:
  1590. return orig_open(name, *args, **kwargs)
  1591. orig_open = open
  1592. with mock.patch("builtins.open", side_effect=open_mock):
  1593. with mock.patch(
  1594. 'glob.glob', return_value=['/sys/class/hwmon/hwmon2/fan1']
  1595. ):
  1596. fan = psutil.sensors_fans()['name'][0]
  1597. assert fan.label == 'label'
  1598. assert fan.current == 2000
  1599. # =====================================================================
  1600. # --- test process
  1601. # =====================================================================
  1602. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  1603. class TestProcess(PsutilTestCase):
  1604. @retry_on_failure()
  1605. def test_parse_smaps_vs_memory_maps(self):
  1606. sproc = self.spawn_subproc()
  1607. uss, pss, swap = psutil._pslinux.Process(sproc.pid)._parse_smaps()
  1608. maps = psutil.Process(sproc.pid).memory_maps(grouped=False)
  1609. assert (
  1610. abs(uss - sum(x.private_dirty + x.private_clean for x in maps))
  1611. < 4096
  1612. )
  1613. assert abs(pss - sum(x.pss for x in maps)) < 4096
  1614. assert abs(swap - sum(x.swap for x in maps)) < 4096
  1615. def test_parse_smaps_mocked(self):
  1616. # See: https://github.com/giampaolo/psutil/issues/1222
  1617. content = textwrap.dedent("""\
  1618. fffff0 r-xp 00000000 00:00 0 [vsyscall]
  1619. Size: 1 kB
  1620. Rss: 2 kB
  1621. Pss: 3 kB
  1622. Shared_Clean: 4 kB
  1623. Shared_Dirty: 5 kB
  1624. Private_Clean: 6 kB
  1625. Private_Dirty: 7 kB
  1626. Referenced: 8 kB
  1627. Anonymous: 9 kB
  1628. LazyFree: 10 kB
  1629. AnonHugePages: 11 kB
  1630. ShmemPmdMapped: 12 kB
  1631. Shared_Hugetlb: 13 kB
  1632. Private_Hugetlb: 14 kB
  1633. Swap: 15 kB
  1634. SwapPss: 16 kB
  1635. KernelPageSize: 17 kB
  1636. MMUPageSize: 18 kB
  1637. Locked: 19 kB
  1638. VmFlags: rd ex
  1639. """).encode()
  1640. with mock_open_content({f"/proc/{os.getpid()}/smaps": content}) as m:
  1641. p = psutil._pslinux.Process(os.getpid())
  1642. uss, pss, swap = p._parse_smaps()
  1643. assert m.called
  1644. assert uss == (6 + 7 + 14) * 1024
  1645. assert pss == 3 * 1024
  1646. assert swap == 15 * 1024
  1647. def test_open_files_mode(self):
  1648. def get_test_file(fname):
  1649. p = psutil.Process()
  1650. giveup_at = time.time() + GLOBAL_TIMEOUT
  1651. while True:
  1652. for file in p.open_files():
  1653. if file.path == os.path.abspath(fname):
  1654. return file
  1655. elif time.time() > giveup_at:
  1656. break
  1657. raise RuntimeError("timeout looking for test file")
  1658. testfn = self.get_testfn()
  1659. with open(testfn, "w"):
  1660. assert get_test_file(testfn).mode == "w"
  1661. with open(testfn):
  1662. assert get_test_file(testfn).mode == "r"
  1663. with open(testfn, "a"):
  1664. assert get_test_file(testfn).mode == "a"
  1665. with open(testfn, "r+"):
  1666. assert get_test_file(testfn).mode == "r+"
  1667. with open(testfn, "w+"):
  1668. assert get_test_file(testfn).mode == "r+"
  1669. with open(testfn, "a+"):
  1670. assert get_test_file(testfn).mode == "a+"
  1671. safe_rmpath(testfn)
  1672. with open(testfn, "x"):
  1673. assert get_test_file(testfn).mode == "w"
  1674. safe_rmpath(testfn)
  1675. with open(testfn, "x+"):
  1676. assert get_test_file(testfn).mode == "r+"
  1677. def test_open_files_file_gone(self):
  1678. # simulates a file which gets deleted during open_files()
  1679. # execution
  1680. p = psutil.Process()
  1681. files = p.open_files()
  1682. with open(self.get_testfn(), 'w'):
  1683. # give the kernel some time to see the new file
  1684. call_until(lambda: len(p.open_files()) != len(files))
  1685. with mock.patch(
  1686. 'psutil._pslinux.os.readlink',
  1687. side_effect=FileNotFoundError,
  1688. ) as m:
  1689. assert p.open_files() == []
  1690. assert m.called
  1691. # also simulate the case where os.readlink() returns EINVAL
  1692. # in which case psutil is supposed to 'continue'
  1693. with mock.patch(
  1694. 'psutil._pslinux.os.readlink',
  1695. side_effect=OSError(errno.EINVAL, ""),
  1696. ) as m:
  1697. assert p.open_files() == []
  1698. assert m.called
  1699. def test_open_files_fd_gone(self):
  1700. # Simulate a case where /proc/{pid}/fdinfo/{fd} disappears
  1701. # while iterating through fds.
  1702. # https://travis-ci.org/giampaolo/psutil/jobs/225694530
  1703. p = psutil.Process()
  1704. files = p.open_files()
  1705. with open(self.get_testfn(), 'w'):
  1706. # give the kernel some time to see the new file
  1707. call_until(lambda: len(p.open_files()) != len(files))
  1708. with mock.patch(
  1709. "builtins.open", side_effect=FileNotFoundError
  1710. ) as m:
  1711. assert p.open_files() == []
  1712. assert m.called
  1713. def test_open_files_enametoolong(self):
  1714. # Simulate a case where /proc/{pid}/fd/{fd} symlink
  1715. # points to a file with full path longer than PATH_MAX, see:
  1716. # https://github.com/giampaolo/psutil/issues/1940
  1717. p = psutil.Process()
  1718. files = p.open_files()
  1719. with open(self.get_testfn(), 'w'):
  1720. # give the kernel some time to see the new file
  1721. call_until(lambda: len(p.open_files()) != len(files))
  1722. patch_point = 'psutil._pslinux.os.readlink'
  1723. with mock.patch(
  1724. patch_point, side_effect=OSError(errno.ENAMETOOLONG, "")
  1725. ) as m:
  1726. with mock.patch("psutil._pslinux.debug"):
  1727. assert p.open_files() == []
  1728. assert m.called
  1729. # --- mocked tests
  1730. def test_terminal_mocked(self):
  1731. with mock.patch(
  1732. 'psutil._pslinux._psposix.get_terminal_map', return_value={}
  1733. ) as m:
  1734. assert psutil._pslinux.Process(os.getpid()).terminal() is None
  1735. assert m.called
  1736. def test_cmdline_mocked(self):
  1737. # see: https://github.com/giampaolo/psutil/issues/639
  1738. p = psutil.Process()
  1739. fake_file = io.StringIO('foo\x00bar\x00')
  1740. with mock.patch(
  1741. 'psutil._common.open', return_value=fake_file, create=True
  1742. ) as m:
  1743. assert p.cmdline() == ['foo', 'bar']
  1744. assert m.called
  1745. fake_file = io.StringIO('foo\x00bar\x00\x00')
  1746. with mock.patch(
  1747. 'psutil._common.open', return_value=fake_file, create=True
  1748. ) as m:
  1749. assert p.cmdline() == ['foo', 'bar', '']
  1750. assert m.called
  1751. def test_cmdline_spaces_mocked(self):
  1752. # see: https://github.com/giampaolo/psutil/issues/1179
  1753. p = psutil.Process()
  1754. fake_file = io.StringIO('foo bar ')
  1755. with mock.patch(
  1756. 'psutil._common.open', return_value=fake_file, create=True
  1757. ) as m:
  1758. assert p.cmdline() == ['foo', 'bar']
  1759. assert m.called
  1760. fake_file = io.StringIO('foo bar ')
  1761. with mock.patch(
  1762. 'psutil._common.open', return_value=fake_file, create=True
  1763. ) as m:
  1764. assert p.cmdline() == ['foo', 'bar', '']
  1765. assert m.called
  1766. def test_cmdline_mixed_separators(self):
  1767. # https://github.com/giampaolo/psutil/issues/
  1768. # 1179#issuecomment-552984549
  1769. p = psutil.Process()
  1770. fake_file = io.StringIO('foo\x20bar\x00')
  1771. with mock.patch(
  1772. 'psutil._common.open', return_value=fake_file, create=True
  1773. ) as m:
  1774. assert p.cmdline() == ['foo', 'bar']
  1775. assert m.called
  1776. def test_readlink_path_deleted_mocked(self):
  1777. with mock.patch(
  1778. 'psutil._pslinux.os.readlink', return_value='/home/foo (deleted)'
  1779. ):
  1780. assert psutil.Process().exe() == "/home/foo"
  1781. assert psutil.Process().cwd() == "/home/foo"
  1782. def test_threads_mocked(self):
  1783. # Test the case where os.listdir() returns a file (thread)
  1784. # which no longer exists by the time we open() it (race
  1785. # condition). threads() is supposed to ignore that instead
  1786. # of raising NSP.
  1787. def open_mock_1(name, *args, **kwargs):
  1788. if name.startswith(f"/proc/{os.getpid()}/task"):
  1789. raise FileNotFoundError
  1790. return orig_open(name, *args, **kwargs)
  1791. orig_open = open
  1792. with mock.patch("builtins.open", side_effect=open_mock_1) as m:
  1793. ret = psutil.Process().threads()
  1794. assert m.called
  1795. assert ret == []
  1796. # ...but if it bumps into something != ENOENT we want an
  1797. # exception.
  1798. def open_mock_2(name, *args, **kwargs):
  1799. if name.startswith(f"/proc/{os.getpid()}/task"):
  1800. raise PermissionError
  1801. return orig_open(name, *args, **kwargs)
  1802. with mock.patch("builtins.open", side_effect=open_mock_2):
  1803. with pytest.raises(psutil.AccessDenied):
  1804. psutil.Process().threads()
  1805. def test_exe_mocked(self):
  1806. with mock.patch(
  1807. 'psutil._pslinux.readlink', side_effect=FileNotFoundError
  1808. ) as m:
  1809. # de-activate guessing from cmdline()
  1810. with mock.patch(
  1811. 'psutil._pslinux.Process.cmdline', return_value=[]
  1812. ):
  1813. ret = psutil.Process().exe()
  1814. assert m.called
  1815. assert ret == ""
  1816. def test_cwd_mocked(self):
  1817. # https://github.com/giampaolo/psutil/issues/2514
  1818. with mock.patch(
  1819. 'psutil._pslinux.readlink', side_effect=FileNotFoundError
  1820. ) as m:
  1821. ret = psutil.Process().cwd()
  1822. assert m.called
  1823. assert ret == ""
  1824. def test_issue_1014(self):
  1825. # Emulates a case where smaps file does not exist. In this case
  1826. # wrap_exception decorator should not raise NoSuchProcess.
  1827. with mock_open_exception(
  1828. f"/proc/{os.getpid()}/smaps", FileNotFoundError
  1829. ) as m:
  1830. p = psutil.Process()
  1831. with pytest.raises(FileNotFoundError):
  1832. p.memory_maps()
  1833. assert m.called
  1834. def test_issue_2418(self):
  1835. p = psutil.Process()
  1836. with mock_open_exception(
  1837. f"/proc/{os.getpid()}/statm", FileNotFoundError
  1838. ):
  1839. with mock.patch("os.path.exists", return_value=False):
  1840. with pytest.raises(psutil.NoSuchProcess):
  1841. p.memory_info()
  1842. @pytest.mark.skipif(not HAS_RLIMIT, reason="not supported")
  1843. def test_rlimit_zombie(self):
  1844. # Emulate a case where rlimit() raises ENOSYS, which may
  1845. # happen in case of zombie process:
  1846. # https://travis-ci.org/giampaolo/psutil/jobs/51368273
  1847. with mock.patch(
  1848. "resource.prlimit", side_effect=OSError(errno.ENOSYS, "")
  1849. ) as m1:
  1850. with mock.patch(
  1851. "psutil._pslinux.Process._is_zombie", return_value=True
  1852. ) as m2:
  1853. p = psutil.Process()
  1854. p.name()
  1855. with pytest.raises(psutil.ZombieProcess) as cm:
  1856. p.rlimit(psutil.RLIMIT_NOFILE)
  1857. assert m1.called
  1858. assert m2.called
  1859. assert cm.value.pid == p.pid
  1860. assert cm.value.name == p.name()
  1861. def test_stat_file_parsing(self):
  1862. args = [
  1863. "0", # pid
  1864. "(cat)", # name
  1865. "Z", # status
  1866. "1", # ppid
  1867. "0", # pgrp
  1868. "0", # session
  1869. "0", # tty
  1870. "0", # tpgid
  1871. "0", # flags
  1872. "0", # minflt
  1873. "0", # cminflt
  1874. "0", # majflt
  1875. "0", # cmajflt
  1876. "2", # utime
  1877. "3", # stime
  1878. "4", # cutime
  1879. "5", # cstime
  1880. "0", # priority
  1881. "0", # nice
  1882. "0", # num_threads
  1883. "0", # itrealvalue
  1884. "6", # starttime
  1885. "0", # vsize
  1886. "0", # rss
  1887. "0", # rsslim
  1888. "0", # startcode
  1889. "0", # endcode
  1890. "0", # startstack
  1891. "0", # kstkesp
  1892. "0", # kstkeip
  1893. "0", # signal
  1894. "0", # blocked
  1895. "0", # sigignore
  1896. "0", # sigcatch
  1897. "0", # wchan
  1898. "0", # nswap
  1899. "0", # cnswap
  1900. "0", # exit_signal
  1901. "6", # processor
  1902. "0", # rt priority
  1903. "0", # policy
  1904. "7", # delayacct_blkio_ticks
  1905. ]
  1906. content = " ".join(args).encode()
  1907. with mock_open_content({f"/proc/{os.getpid()}/stat": content}):
  1908. p = psutil.Process()
  1909. assert p.name() == 'cat'
  1910. assert p.status() == psutil.STATUS_ZOMBIE
  1911. assert p.ppid() == 1
  1912. assert p.create_time() == 6 / CLOCK_TICKS + psutil.boot_time()
  1913. cpu = p.cpu_times()
  1914. assert cpu.user == 2 / CLOCK_TICKS
  1915. assert cpu.system == 3 / CLOCK_TICKS
  1916. assert cpu.children_user == 4 / CLOCK_TICKS
  1917. assert cpu.children_system == 5 / CLOCK_TICKS
  1918. assert cpu.iowait == 7 / CLOCK_TICKS
  1919. assert p.cpu_num() == 6
  1920. def test_status_file_parsing(self):
  1921. content = textwrap.dedent("""\
  1922. Uid:\t1000\t1001\t1002\t1003
  1923. Gid:\t1004\t1005\t1006\t1007
  1924. Threads:\t66
  1925. Cpus_allowed:\tf
  1926. Cpus_allowed_list:\t0-7
  1927. voluntary_ctxt_switches:\t12
  1928. nonvoluntary_ctxt_switches:\t13""").encode()
  1929. with mock_open_content({f"/proc/{os.getpid()}/status": content}):
  1930. p = psutil.Process()
  1931. assert p.num_ctx_switches().voluntary == 12
  1932. assert p.num_ctx_switches().involuntary == 13
  1933. assert p.num_threads() == 66
  1934. uids = p.uids()
  1935. assert uids.real == 1000
  1936. assert uids.effective == 1001
  1937. assert uids.saved == 1002
  1938. gids = p.gids()
  1939. assert gids.real == 1004
  1940. assert gids.effective == 1005
  1941. assert gids.saved == 1006
  1942. assert p._proc._get_eligible_cpus() == list(range(8))
  1943. def test_net_connections_enametoolong(self):
  1944. # Simulate a case where /proc/{pid}/fd/{fd} symlink points to
  1945. # a file with full path longer than PATH_MAX, see:
  1946. # https://github.com/giampaolo/psutil/issues/1940
  1947. with mock.patch(
  1948. 'psutil._pslinux.os.readlink',
  1949. side_effect=OSError(errno.ENAMETOOLONG, ""),
  1950. ) as m:
  1951. p = psutil.Process()
  1952. with mock.patch("psutil._pslinux.debug"):
  1953. assert p.net_connections() == []
  1954. assert m.called
  1955. def test_create_time_monotonic(self):
  1956. p = psutil.Process()
  1957. assert p._proc.create_time() != p._proc.create_time(monotonic=True)
  1958. assert p._get_ident()[1] == p._proc.create_time(monotonic=True)
  1959. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  1960. class TestProcessAgainstStatus(PsutilTestCase):
  1961. """/proc/pid/stat and /proc/pid/status have many values in common.
  1962. Whenever possible, psutil uses /proc/pid/stat (it's faster).
  1963. For all those cases we check that the value found in
  1964. /proc/pid/stat (by psutil) matches the one found in
  1965. /proc/pid/status.
  1966. """
  1967. @classmethod
  1968. def setUpClass(cls):
  1969. cls.proc = psutil.Process()
  1970. def read_status_file(self, linestart):
  1971. with psutil._psplatform.open_text(
  1972. f"/proc/{self.proc.pid}/status"
  1973. ) as f:
  1974. for line in f:
  1975. line = line.strip()
  1976. if line.startswith(linestart):
  1977. value = line.partition('\t')[2]
  1978. try:
  1979. return int(value)
  1980. except ValueError:
  1981. return value
  1982. raise ValueError(f"can't find {linestart!r}")
  1983. def test_name(self):
  1984. value = self.read_status_file("Name:")
  1985. assert self.proc.name() == value
  1986. def test_status(self):
  1987. value = self.read_status_file("State:")
  1988. value = value[value.find('(') + 1 : value.rfind(')')]
  1989. value = value.replace(' ', '-')
  1990. assert self.proc.status() == value
  1991. def test_ppid(self):
  1992. value = self.read_status_file("PPid:")
  1993. assert self.proc.ppid() == value
  1994. def test_num_threads(self):
  1995. value = self.read_status_file("Threads:")
  1996. assert self.proc.num_threads() == value
  1997. def test_uids(self):
  1998. value = self.read_status_file("Uid:")
  1999. value = tuple(map(int, value.split()[1:4]))
  2000. assert self.proc.uids() == value
  2001. def test_gids(self):
  2002. value = self.read_status_file("Gid:")
  2003. value = tuple(map(int, value.split()[1:4]))
  2004. assert self.proc.gids() == value
  2005. @retry_on_failure()
  2006. def test_num_ctx_switches(self):
  2007. value = self.read_status_file("voluntary_ctxt_switches:")
  2008. assert self.proc.num_ctx_switches().voluntary == value
  2009. value = self.read_status_file("nonvoluntary_ctxt_switches:")
  2010. assert self.proc.num_ctx_switches().involuntary == value
  2011. def test_cpu_affinity(self):
  2012. value = self.read_status_file("Cpus_allowed_list:")
  2013. if '-' in str(value):
  2014. min_, max_ = map(int, value.split('-'))
  2015. assert self.proc.cpu_affinity() == list(range(min_, max_ + 1))
  2016. def test_cpu_affinity_eligible_cpus(self):
  2017. value = self.read_status_file("Cpus_allowed_list:")
  2018. with mock.patch("psutil._pslinux.per_cpu_times") as m:
  2019. self.proc._proc._get_eligible_cpus()
  2020. if '-' in str(value):
  2021. assert not m.called
  2022. else:
  2023. assert m.called
  2024. # =====================================================================
  2025. # --- test utils
  2026. # =====================================================================
  2027. @pytest.mark.skipif(not LINUX, reason="LINUX only")
  2028. class TestUtils(PsutilTestCase):
  2029. def test_readlink(self):
  2030. with mock.patch("os.readlink", return_value="foo (deleted)") as m:
  2031. assert psutil._psplatform.readlink("bar") == "foo"
  2032. assert m.called