Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use pytest.skip instead of unittest.SkipTest #2461

Merged
merged 6 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions psutil/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@
'unittest', 'skip_on_access_denied', 'skip_on_not_implemented',
'retry_on_failure', 'TestMemoryLeak', 'PsutilTestCase',
'process_namespace', 'system_namespace', 'print_sysinfo',
'is_win_secure_system_proc',
'is_win_secure_system_proc', 'fake_pytest',
# fs utils
'chdir', 'safe_rmpath', 'create_py_exe', 'create_c_exe', 'get_testfn',
# os
Expand Down Expand Up @@ -878,7 +878,7 @@ def create_c_exe(path, c_code=None):
"""Create a compiled C executable in the given location."""
assert not os.path.exists(path), path
if not which("gcc"):
raise unittest.SkipTest("gcc is not installed")
raise pytest.skip("gcc is not installed")
if c_code is None:
c_code = textwrap.dedent("""
#include <unistd.h>
Expand Down Expand Up @@ -974,6 +974,11 @@ def warns(warning, match=None):
return unittest.TestCase().assertWarnsRegex(warning, match)
return unittest.TestCase().assertWarns(warning)

@staticmethod
def skip(reason=""):
"""Mimics `unittest.SkipTest`."""
raise unittest.SkipTest(reason)

class mark:

@staticmethod
Expand Down Expand Up @@ -1689,7 +1694,7 @@ def wrapper(*args, **kwargs):
if only_if is not None:
if not only_if:
raise
raise unittest.SkipTest("raises AccessDenied")
raise pytest.skip("raises AccessDenied")

return wrapper

Expand All @@ -1712,7 +1717,7 @@ def wrapper(*args, **kwargs):
"%r was skipped because it raised NotImplementedError"
% fun.__name__
)
raise unittest.SkipTest(msg)
raise pytest.skip(msg)

return wrapper

Expand Down
5 changes: 2 additions & 3 deletions psutil/tests/test_bsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import os
import re
import time
import unittest

import psutil
from psutil import BSD
Expand Down Expand Up @@ -267,7 +266,7 @@ def test_cpu_frequency_against_sysctl(self):
try:
sysctl_result = int(sysctl(sensor))
except RuntimeError:
raise unittest.SkipTest("frequencies not supported by kernel")
raise pytest.skip("frequencies not supported by kernel")
assert psutil.cpu_freq().current == sysctl_result

sensor = "dev.cpu.0.freq_levels"
Expand Down Expand Up @@ -471,7 +470,7 @@ def test_sensors_temperatures_against_sysctl(self):
try:
sysctl_result = int(float(sysctl(sensor)[:-1]))
except RuntimeError:
raise unittest.SkipTest("temperatures not supported by kernel")
raise pytest.skip("temperatures not supported by kernel")
assert (
abs(
psutil.sensors_temperatures()["coretemp"][cpu].current
Expand Down
3 changes: 1 addition & 2 deletions psutil/tests/test_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

import platform
import signal
import unittest

import psutil
from psutil import AIX
Expand Down Expand Up @@ -237,7 +236,7 @@ def test_cpu_count(self):
@pytest.mark.skipif(not HAS_CPU_FREQ, reason="not supported")
def test_cpu_freq(self):
if psutil.cpu_freq() is None:
raise unittest.SkipTest("cpu_freq() returns None")
raise pytest.skip("cpu_freq() returns None")
self.assert_ntuple_of_nums(psutil.cpu_freq(), type_=(float, int, long))

def test_disk_io_counters(self):
Expand Down
17 changes: 8 additions & 9 deletions psutil/tests/test_linux.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import struct
import textwrap
import time
import unittest
import warnings

import psutil
Expand Down Expand Up @@ -216,7 +215,7 @@ def vmstat(stat):
def get_free_version_info():
out = sh(["free", "-V"]).strip()
if 'UNKNOWN' in out:
raise unittest.SkipTest("can't determine free version")
raise pytest.skip("can't determine free version")
return tuple(map(int, re.findall(r'\d+', out.split()[-1])))


Expand Down Expand Up @@ -286,9 +285,9 @@ def test_used(self):
# https://gitlab.com/procps-ng/procps/commit/
# 2184e90d2e7cdb582f9a5b706b47015e56707e4d
if get_free_version_info() < (3, 3, 12):
raise unittest.SkipTest("free version too old")
raise pytest.skip("free version too old")
if get_free_version_info() >= (4, 0, 0):
raise unittest.SkipTest("free version too recent")
raise pytest.skip("free version too recent")
cli_value = free_physmem().used
psutil_value = psutil.virtual_memory().used
assert abs(cli_value - psutil_value) < TOLERANCE_SYS_MEM
Expand All @@ -304,7 +303,7 @@ def test_shared(self):
free = free_physmem()
free_value = free.shared
if free_value == 0:
raise unittest.SkipTest("free does not support 'shared' column")
raise pytest.skip("free does not support 'shared' column")
psutil_value = psutil.virtual_memory().shared
assert (
abs(free_value - psutil_value) < TOLERANCE_SYS_MEM
Expand All @@ -317,7 +316,7 @@ def test_available(self):
out = sh(["free", "-b"])
lines = out.split('\n')
if 'available' not in lines[0]:
raise unittest.SkipTest("free does not support 'available' column")
raise pytest.skip("free does not support 'available' column")
else:
free_value = int(lines[1].split()[-1])
psutil_value = psutil.virtual_memory().available
Expand All @@ -344,9 +343,9 @@ def test_used(self):
# https://gitlab.com/procps-ng/procps/commit/
# 2184e90d2e7cdb582f9a5b706b47015e56707e4d
if get_free_version_info() < (3, 3, 12):
raise unittest.SkipTest("free version too old")
raise pytest.skip("free version too old")
if get_free_version_info() >= (4, 0, 0):
raise unittest.SkipTest("free version too recent")
raise pytest.skip("free version too recent")
vmstat_value = vmstat('used memory') * 1024
psutil_value = psutil.virtual_memory().used
assert abs(vmstat_value - psutil_value) < TOLERANCE_SYS_MEM
Expand Down Expand Up @@ -651,7 +650,7 @@ def test_meminfo_against_sysinfo(self):
# matches sysinfo() syscall, see:
# https://github.com/giampaolo/psutil/issues/1015
if not self.meminfo_has_swap_info():
return unittest.skip("/proc/meminfo has no swap metrics")
raise pytest.skip("/proc/meminfo has no swap metrics")
with mock.patch('psutil._pslinux.cext.linux_sysinfo') as m:
swap = psutil.swap_memory()
assert not m.called
Expand Down
11 changes: 5 additions & 6 deletions psutil/tests/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import socket
import stat
import sys
import unittest

import psutil
import psutil.tests
Expand Down Expand Up @@ -346,7 +345,7 @@ def check(ret):
# def test_setup_script(self):
# setup_py = os.path.join(ROOT_DIR, 'setup.py')
# if CI_TESTING and not os.path.exists(setup_py):
# raise unittest.SkipTest("can't find setup.py")
# raise pytest.skip("can't find setup.py")
# module = import_module_by_path(setup_py)
# self.assertRaises(SystemExit, module.setup)
# self.assertEqual(module.get_version(), psutil.__version__)
Expand Down Expand Up @@ -891,7 +890,7 @@ def test_cache_clear(self):
@pytest.mark.skipif(not HAS_NET_IO_COUNTERS, reason="not supported")
def test_cache_clear_public_apis(self):
if not psutil.disk_io_counters() or not psutil.net_io_counters():
raise unittest.SkipTest("no disks or NICs available")
raise pytest.skip("no disks or NICs available")
psutil.disk_io_counters()
psutil.net_io_counters()
caches = wrap_numbers.cache_info()
Expand Down Expand Up @@ -1001,7 +1000,7 @@ def test_pmap(self):

def test_procsmem(self):
if 'uss' not in psutil.Process().memory_full_info()._fields:
raise unittest.SkipTest("not supported")
raise pytest.skip("not supported")
self.assert_stdout('procsmem.py')

def test_killall(self):
Expand Down Expand Up @@ -1030,13 +1029,13 @@ def test_cpu_distribution(self):
@pytest.mark.skipif(not HAS_SENSORS_TEMPERATURES, reason="not supported")
def test_temperatures(self):
if not psutil.sensors_temperatures():
raise unittest.SkipTest("no temperatures")
raise pytest.skip("no temperatures")
self.assert_stdout('temperatures.py')

@pytest.mark.skipif(not HAS_SENSORS_FANS, reason="not supported")
def test_fans(self):
if not psutil.sensors_fans():
raise unittest.SkipTest("no fans")
raise pytest.skip("no fans")
self.assert_stdout('fans.py')

@pytest.mark.skipif(not HAS_SENSORS_BATTERY, reason="not supported")
Expand Down
9 changes: 4 additions & 5 deletions psutil/tests/test_posix.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import re
import subprocess
import time
import unittest

import psutil
from psutil import AIX
Expand Down Expand Up @@ -141,7 +140,7 @@ def df(device):
out = sh("df -k %s" % device).strip()
except RuntimeError as err:
if "device busy" in str(err).lower():
raise unittest.SkipTest("df returned EBUSY")
raise pytest.skip("df returned EBUSY")
raise
line = out.split('\n')[1]
fields = line.split()
Expand Down Expand Up @@ -370,7 +369,7 @@ def test_nic_names(self):
def test_users(self):
out = sh("who -u")
if not out.strip():
raise unittest.SkipTest("no users on this system")
raise pytest.skip("no users on this system")
lines = out.split('\n')
users = [x.split()[0] for x in lines]
terminals = [x.split()[1] for x in lines]
Expand All @@ -386,7 +385,7 @@ def test_users(self):
def test_users_started(self):
out = sh("who -u")
if not out.strip():
raise unittest.SkipTest("no users on this system")
raise pytest.skip("no users on this system")
tstamp = None
# '2023-04-11 09:31' (Linux)
started = re.findall(r"\d\d\d\d-\d\d-\d\d \d\d:\d\d", out)
Expand All @@ -410,7 +409,7 @@ def test_users_started(self):
started = [x.capitalize() for x in started]

if not tstamp:
raise unittest.SkipTest(
raise pytest.skip(
"cannot interpret tstamp in who output\n%s" % (out)
)

Expand Down
19 changes: 9 additions & 10 deletions psutil/tests/test_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import textwrap
import time
import types
import unittest

import psutil
from psutil import AIX
Expand Down Expand Up @@ -329,7 +328,7 @@ def test_terminal(self):
tty = os.path.realpath(sh('tty'))
except RuntimeError:
# Note: happens if pytest is run without the `-s` opt.
raise unittest.SkipTest("can't rely on `tty` CLI")
raise pytest.skip("can't rely on `tty` CLI")
else:
assert terminal == tty

Expand Down Expand Up @@ -543,7 +542,7 @@ def test_num_threads(self):
try:
step1 = p.num_threads()
except psutil.AccessDenied:
raise unittest.SkipTest("on OpenBSD this requires root access")
raise pytest.skip("on OpenBSD this requires root access")
else:
step1 = p.num_threads()

Expand All @@ -564,7 +563,7 @@ def test_threads(self):
try:
step1 = p.threads()
except psutil.AccessDenied:
raise unittest.SkipTest("on OpenBSD this requires root access")
raise pytest.skip("on OpenBSD this requires root access")
else:
step1 = p.threads()

Expand All @@ -586,7 +585,7 @@ def test_threads_2(self):
try:
p.threads()
except psutil.AccessDenied:
raise unittest.SkipTest("on OpenBSD this requires root access")
raise pytest.skip("on OpenBSD this requires root access")
assert (
abs(p.cpu_times().user - sum([x.user_time for x in p.threads()]))
< 0.1
Expand Down Expand Up @@ -761,7 +760,7 @@ def test_cmdline(self):

if NETBSD and p.cmdline() == []:
# https://github.com/giampaolo/psutil/issues/2250
raise unittest.SkipTest("OPENBSD: returned EBUSY")
raise pytest.skip("OPENBSD: returned EBUSY")

# XXX - most of the times the underlying sysctl() call on Net
# and Open BSD returns a truncated string.
Expand Down Expand Up @@ -795,14 +794,14 @@ def test_long_cmdline(self):
try:
assert p.cmdline() == cmdline
except psutil.ZombieProcess:
raise unittest.SkipTest("OPENBSD: process turned into zombie")
raise pytest.skip("OPENBSD: process turned into zombie")
elif QEMU_USER:
assert p.cmdline()[2:] == cmdline
else:
ret = p.cmdline()
if NETBSD and ret == []:
# https://github.com/giampaolo/psutil/issues/2250
raise unittest.SkipTest("OPENBSD: returned EBUSY")
raise pytest.skip("OPENBSD: returned EBUSY")
assert ret == cmdline

def test_name(self):
Expand Down Expand Up @@ -968,7 +967,7 @@ def test_username(self):
# When running as a service account (most likely to be
# NetworkService), these user name calculations don't produce
# the same result, causing the test to fail.
raise unittest.SkipTest('running as service account')
raise pytest.skip('running as service account')
assert username == getpass_user
if 'USERDOMAIN' in os.environ:
assert domain == os.environ['USERDOMAIN']
Expand Down Expand Up @@ -1234,7 +1233,7 @@ def test_children_duplicates(self):
# this is the one, now let's make sure there are no duplicates
pid = sorted(table.items(), key=lambda x: x[1])[-1][0]
if LINUX and pid == 0:
raise unittest.SkipTest("PID 0")
raise pytest.skip("PID 0")
p = psutil.Process(pid)
try:
c = p.children(recursive=True)
Expand Down
7 changes: 3 additions & 4 deletions psutil/tests/test_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import socket
import sys
import time
import unittest

import psutil
from psutil import AIX
Expand Down Expand Up @@ -380,13 +379,13 @@ def test_cpu_count_logical(self):
with open("/proc/cpuinfo") as fd:
cpuinfo_data = fd.read()
if "physical id" not in cpuinfo_data:
raise unittest.SkipTest("cpuinfo doesn't include physical id")
raise pytest.skip("cpuinfo doesn't include physical id")

def test_cpu_count_cores(self):
logical = psutil.cpu_count()
cores = psutil.cpu_count(logical=False)
if cores is None:
raise unittest.SkipTest("cpu_count_cores() is None")
raise pytest.skip("cpu_count_cores() is None")
if WINDOWS and sys.getwindowsversion()[:2] <= (6, 1): # <= Vista
assert cores is None
else:
Expand Down Expand Up @@ -612,7 +611,7 @@ def check_ls(ls):

ls = psutil.cpu_freq(percpu=True)
if FREEBSD and not ls:
raise unittest.SkipTest("returns empty list on FreeBSD")
raise pytest.skip("returns empty list on FreeBSD")

assert ls, ls
check_ls([psutil.cpu_freq(percpu=False)])
Expand Down
Loading
Loading