Skip to content

Commit

Permalink
Pytest: use bare assert statements (#2453)
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo authored Oct 3, 2024
1 parent 7d21555 commit 00c0fe8
Show file tree
Hide file tree
Showing 18 changed files with 1,778 additions and 1,904 deletions.
1 change: 1 addition & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ XXXX-XX-XX

**Enhancements**

- 2446_: use pytest instead of unittest.
- 2448_: add ``make install-sysdeps`` target to install the necessary system
dependencies (python-dev, gcc, etc.) on all supported UNIX flavors.
- 2449_: add ``make install-pydeps-test`` and ``make install-pydeps-dev``
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ fix-black:
@git ls-files '*.py' | xargs $(PYTHON) -m black

fix-ruff:
@git ls-files '*.py' | xargs $(PYTHON) -m ruff check --no-cache --fix $(ARGS)
@git ls-files '*.py' | xargs $(PYTHON) -m ruff check --no-cache --fix --output-format=concise $(ARGS)

fix-toml: ## Fix pyproject.toml
@git ls-files '*.toml' | xargs toml-sort
Expand Down
56 changes: 29 additions & 27 deletions psutil/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
from socket import AF_INET6
from socket import SOCK_STREAM

import pytest

import psutil
from psutil import AIX
from psutil import LINUX
Expand Down Expand Up @@ -982,29 +984,29 @@ def pyrun(self, *args, **kwds):
return sproc

def _check_proc_exc(self, proc, exc):
self.assertIsInstance(exc, psutil.Error)
self.assertEqual(exc.pid, proc.pid)
self.assertEqual(exc.name, proc._name)
assert isinstance(exc, psutil.Error)
assert exc.pid == proc.pid
assert exc.name == proc._name
if exc.name:
self.assertNotEqual(exc.name, "")
assert exc.name
if isinstance(exc, psutil.ZombieProcess):
self.assertEqual(exc.ppid, proc._ppid)
assert exc.ppid == proc._ppid
if exc.ppid is not None:
self.assertGreaterEqual(exc.ppid, 0)
assert exc.ppid >= 0
str(exc)
repr(exc)

def assertPidGone(self, pid):
with self.assertRaises(psutil.NoSuchProcess) as cm:
with pytest.raises(psutil.NoSuchProcess) as cm:
try:
psutil.Process(pid)
except psutil.ZombieProcess:
raise AssertionError("wasn't supposed to raise ZombieProcess")
self.assertEqual(cm.exception.pid, pid)
self.assertEqual(cm.exception.name, None)
assert cm.value.pid == pid
assert cm.value.name is None
assert not psutil.pid_exists(pid), pid
self.assertNotIn(pid, psutil.pids())
self.assertNotIn(pid, [x.pid for x in psutil.process_iter()])
assert pid not in psutil.pids()
assert pid not in [x.pid for x in psutil.process_iter()]

def assertProcessGone(self, proc):
self.assertPidGone(proc.pid)
Expand All @@ -1030,21 +1032,21 @@ def assertProcessZombie(self, proc):
clone = psutil.Process(proc.pid)
# Cloned zombie on Open/NetBSD has null creation time, see:
# https://github.com/giampaolo/psutil/issues/2287
self.assertEqual(proc, clone)
assert proc == clone
if not (OPENBSD or NETBSD):
self.assertEqual(hash(proc), hash(clone))
assert hash(proc) == hash(clone)
# Its status always be querable.
self.assertEqual(proc.status(), psutil.STATUS_ZOMBIE)
assert proc.status() == psutil.STATUS_ZOMBIE
# It should be considered 'running'.
assert proc.is_running()
assert psutil.pid_exists(proc.pid)
# as_dict() shouldn't crash.
proc.as_dict()
# It should show up in pids() and process_iter().
self.assertIn(proc.pid, psutil.pids())
self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
assert proc.pid in psutil.pids()
assert proc.pid in [x.pid for x in psutil.process_iter()]
psutil._pmap = {}
self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
assert proc.pid in [x.pid for x in psutil.process_iter()]
# Call all methods.
ns = process_namespace(proc)
for fun, name in ns.iter(ns.all, clear_cache=True):
Expand All @@ -1055,26 +1057,26 @@ def assertProcessZombie(self, proc):
self._check_proc_exc(proc, exc)
if LINUX:
# https://github.com/giampaolo/psutil/pull/2288
with self.assertRaises(psutil.ZombieProcess) as cm:
with pytest.raises(psutil.ZombieProcess) as cm:
proc.cmdline()
self._check_proc_exc(proc, cm.exception)
with self.assertRaises(psutil.ZombieProcess) as cm:
self._check_proc_exc(proc, cm.value)
with pytest.raises(psutil.ZombieProcess) as cm:
proc.exe()
self._check_proc_exc(proc, cm.exception)
with self.assertRaises(psutil.ZombieProcess) as cm:
self._check_proc_exc(proc, cm.value)
with pytest.raises(psutil.ZombieProcess) as cm:
proc.memory_maps()
self._check_proc_exc(proc, cm.exception)
self._check_proc_exc(proc, cm.value)
# Zombie cannot be signaled or terminated.
proc.suspend()
proc.resume()
proc.terminate()
proc.kill()
assert proc.is_running()
assert psutil.pid_exists(proc.pid)
self.assertIn(proc.pid, psutil.pids())
self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
assert proc.pid in psutil.pids()
assert proc.pid in [x.pid for x in psutil.process_iter()]
psutil._pmap = {}
self.assertIn(proc.pid, [x.pid for x in psutil.process_iter()])
assert proc.pid in [x.pid for x in psutil.process_iter()]

# Its parent should 'see' it (edit: not true on BSD and MACOS).
# descendants = [x.pid for x in psutil.Process().children(
Expand Down Expand Up @@ -1188,7 +1190,7 @@ def _call_ntimes(self, fun, times):
del x, ret
gc.collect(generation=1)
mem2 = self._get_mem()
self.assertEqual(gc.garbage, [])
assert gc.garbage == []
diff = mem2 - mem1 # can also be negative
return diff

Expand Down
60 changes: 22 additions & 38 deletions psutil/tests/test_aix.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ def test_virtual_memory(self):
re_pattern += r"(?P<%s>\S+)\s+" % (field,)
matchobj = re.search(re_pattern, out)

self.assertIsNotNone(
matchobj, "svmon command returned unexpected output"
)
assert matchobj is not None

KB = 1024
total = int(matchobj.group("size")) * KB
Expand All @@ -42,16 +40,10 @@ def test_virtual_memory(self):
# we're seeing differences of ~1.2 MB. 2 MB is still a good tolerance
# when compared to GBs.
TOLERANCE_SYS_MEM = 2 * KB * KB # 2 MB
self.assertEqual(psutil_result.total, total)
self.assertAlmostEqual(
psutil_result.used, used, delta=TOLERANCE_SYS_MEM
)
self.assertAlmostEqual(
psutil_result.available, available, delta=TOLERANCE_SYS_MEM
)
self.assertAlmostEqual(
psutil_result.free, free, delta=TOLERANCE_SYS_MEM
)
assert psutil_result.total == total
assert abs(psutil_result.used - used) < TOLERANCE_SYS_MEM
assert abs(psutil_result.available - available) < TOLERANCE_SYS_MEM
assert abs(psutil_result.free - free) < TOLERANCE_SYS_MEM

def test_swap_memory(self):
out = sh('/usr/sbin/lsps -a')
Expand All @@ -67,16 +59,14 @@ def test_swap_memory(self):
out,
)

self.assertIsNotNone(
matchobj, "lsps command returned unexpected output"
)
assert matchobj is not None

total_mb = int(matchobj.group("size"))
MB = 1024**2
psutil_result = psutil.swap_memory()
# we divide our result by MB instead of multiplying the lsps value by
# MB because lsps may round down, so we round down too
self.assertEqual(int(psutil_result.total / MB), total_mb)
assert int(psutil_result.total / MB) == total_mb

def test_cpu_stats(self):
out = sh('/usr/bin/mpstat -a')
Expand All @@ -90,42 +80,36 @@ def test_cpu_stats(self):
re_pattern += r"(?P<%s>\S+)\s+" % (field,)
matchobj = re.search(re_pattern, out)

self.assertIsNotNone(
matchobj, "mpstat command returned unexpected output"
)
assert matchobj is not None

# numbers are usually in the millions so 1000 is ok for tolerance
CPU_STATS_TOLERANCE = 1000
psutil_result = psutil.cpu_stats()
self.assertAlmostEqual(
psutil_result.ctx_switches,
int(matchobj.group("cs")),
delta=CPU_STATS_TOLERANCE,
assert (
abs(psutil_result.ctx_switches - int(matchobj.group("cs")))
< CPU_STATS_TOLERANCE
)
self.assertAlmostEqual(
psutil_result.syscalls,
int(matchobj.group("sysc")),
delta=CPU_STATS_TOLERANCE,
assert (
abs(psutil_result.syscalls - int(matchobj.group("sysc")))
< CPU_STATS_TOLERANCE
)
self.assertAlmostEqual(
psutil_result.interrupts,
int(matchobj.group("dev")),
delta=CPU_STATS_TOLERANCE,
assert (
abs(psutil_result.interrupts - int(matchobj.group("dev")))
< CPU_STATS_TOLERANCE
)
self.assertAlmostEqual(
psutil_result.soft_interrupts,
int(matchobj.group("soft")),
delta=CPU_STATS_TOLERANCE,
assert (
abs(psutil_result.soft_interrupts - int(matchobj.group("soft")))
< CPU_STATS_TOLERANCE
)

def test_cpu_count_logical(self):
out = sh('/usr/bin/mpstat -a')
mpstat_lcpu = int(re.search(r"lcpu=(\d+)", out).group(1))
psutil_lcpu = psutil.cpu_count(logical=True)
self.assertEqual(mpstat_lcpu, psutil_lcpu)
assert mpstat_lcpu == psutil_lcpu

def test_net_if_addrs_names(self):
out = sh('/etc/ifconfig -l')
ifconfig_names = set(out.split())
psutil_names = set(psutil.net_if_addrs().keys())
self.assertSetEqual(ifconfig_names, psutil_names)
assert ifconfig_names == psutil_names
Loading

0 comments on commit 00c0fe8

Please sign in to comment.