From b1a759399a461996fef72a1f888cc8a60535d500 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Tue, 15 Oct 2024 11:15:25 +0200 Subject: [PATCH] Use `pytest.skip` instead of `unittest.SkipTest` (#2461) --- psutil/tests/__init__.py | 13 +++++++---- psutil/tests/test_bsd.py | 5 ++--- psutil/tests/test_contracts.py | 3 +-- psutil/tests/test_linux.py | 17 +++++++------- psutil/tests/test_misc.py | 11 +++++---- psutil/tests/test_posix.py | 9 ++++---- psutil/tests/test_process.py | 19 ++++++++-------- psutil/tests/test_system.py | 7 +++--- psutil/tests/test_testutils.py | 41 ++++++++++++++++++++++++++++++++++ psutil/tests/test_unicode.py | 9 ++++---- psutil/tests/test_windows.py | 7 +++--- 11 files changed, 89 insertions(+), 52 deletions(-) diff --git a/psutil/tests/__init__.py b/psutil/tests/__init__.py index b2047ab70..dd3d53647 100644 --- a/psutil/tests/__init__.py +++ b/psutil/tests/__init__.py @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 diff --git a/psutil/tests/test_bsd.py b/psutil/tests/test_bsd.py index c836dfd5c..2fd1015d7 100755 --- a/psutil/tests/test_bsd.py +++ b/psutil/tests/test_bsd.py @@ -14,7 +14,6 @@ import os import re import time -import unittest import psutil from psutil import BSD @@ -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" @@ -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 diff --git a/psutil/tests/test_contracts.py b/psutil/tests/test_contracts.py index 2f58cd172..c0ec6a8f7 100755 --- a/psutil/tests/test_contracts.py +++ b/psutil/tests/test_contracts.py @@ -11,7 +11,6 @@ import platform import signal -import unittest import psutil from psutil import AIX @@ -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): diff --git a/psutil/tests/test_linux.py b/psutil/tests/test_linux.py index 72f937890..cdcb468e1 100755 --- a/psutil/tests/test_linux.py +++ b/psutil/tests/test_linux.py @@ -20,7 +20,6 @@ import struct import textwrap import time -import unittest import warnings import psutil @@ -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]))) @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 diff --git a/psutil/tests/test_misc.py b/psutil/tests/test_misc.py index 3a4275c80..ad1922f8e 100755 --- a/psutil/tests/test_misc.py +++ b/psutil/tests/test_misc.py @@ -16,7 +16,6 @@ import socket import stat import sys -import unittest import psutil import psutil.tests @@ -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__) @@ -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() @@ -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): @@ -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") diff --git a/psutil/tests/test_posix.py b/psutil/tests/test_posix.py index ba430154d..6f7f9790f 100755 --- a/psutil/tests/test_posix.py +++ b/psutil/tests/test_posix.py @@ -13,7 +13,6 @@ import re import subprocess import time -import unittest import psutil from psutil import AIX @@ -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() @@ -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] @@ -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) @@ -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) ) diff --git a/psutil/tests/test_process.py b/psutil/tests/test_process.py index a0e5199ec..b8f06a46e 100755 --- a/psutil/tests/test_process.py +++ b/psutil/tests/test_process.py @@ -19,7 +19,6 @@ import textwrap import time import types -import unittest import psutil from psutil import AIX @@ -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 @@ -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() @@ -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() @@ -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 @@ -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. @@ -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): @@ -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'] @@ -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) diff --git a/psutil/tests/test_system.py b/psutil/tests/test_system.py index 46cc15d4e..7d6695408 100755 --- a/psutil/tests/test_system.py +++ b/psutil/tests/test_system.py @@ -17,7 +17,6 @@ import socket import sys import time -import unittest import psutil from psutil import AIX @@ -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: @@ -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)]) diff --git a/psutil/tests/test_testutils.py b/psutil/tests/test_testutils.py index 2f8005d54..e11c8f783 100755 --- a/psutil/tests/test_testutils.py +++ b/psutil/tests/test_testutils.py @@ -15,6 +15,7 @@ import stat import subprocess import textwrap +import unittest import warnings import psutil @@ -25,6 +26,7 @@ from psutil._common import open_binary from psutil._common import open_text from psutil._common import supports_ipv6 +from psutil._compat import PY3 from psutil.tests import CI_TESTING from psutil.tests import COVERAGE from psutil.tests import HAS_NET_CONNECTIONS_UNIX @@ -448,6 +450,13 @@ def fun_2(): class TestFakePytest(PsutilTestCase): + def run_test_class(self, klass): + suite = unittest.TestSuite() + suite.addTest(klass) + runner = unittest.TextTestRunner() + result = runner.run(suite) + return result + def test_raises(self): with fake_pytest.raises(ZeroDivisionError) as cm: 1 / 0 # noqa @@ -478,6 +487,38 @@ def bar(self): assert Foo().bar() == 1 + def test_skipif(self): + class TestCase(unittest.TestCase): + @fake_pytest.mark.skipif(True, reason="reason") + def foo(self): + assert 1 == 1 # noqa + + result = self.run_test_class(TestCase("foo")) + assert result.wasSuccessful() + assert len(result.skipped) == 1 + assert result.skipped[0][1] == "reason" + + class TestCase(unittest.TestCase): + @fake_pytest.mark.skipif(False, reason="reason") + def foo(self): + assert 1 == 1 # noqa + + result = self.run_test_class(TestCase("foo")) + assert result.wasSuccessful() + assert len(result.skipped) == 0 + + @pytest.mark.skipif(not PY3, reason="not PY3") + def test_skip(self): + class TestCase(unittest.TestCase): + def foo(self): + fake_pytest.skip("reason") + assert 1 == 0 # noqa + + result = self.run_test_class(TestCase("foo")) + assert result.wasSuccessful() + assert len(result.skipped) == 1 + assert result.skipped[0][1] == "reason" + def test_main(self): tmpdir = self.get_testfn(dir=HERE) os.mkdir(tmpdir) diff --git a/psutil/tests/test_unicode.py b/psutil/tests/test_unicode.py index 89447dd57..1bea46b5d 100755 --- a/psutil/tests/test_unicode.py +++ b/psutil/tests/test_unicode.py @@ -75,7 +75,6 @@ import os import shutil import traceback -import unittest import warnings from contextlib import closing @@ -175,7 +174,7 @@ def setUpClass(cls): def setUp(self): super().setUp() if self.skip_tests: - raise unittest.SkipTest("can't handle unicode str") + raise pytest.skip("can't handle unicode str") @pytest.mark.xdist_group(name="serial") @@ -256,7 +255,7 @@ def test_proc_open_files(self): assert isinstance(path, str) if BSD and not path: # XXX - see https://github.com/giampaolo/psutil/issues/595 - raise unittest.SkipTest("open_files on BSD is broken") + raise pytest.skip("open_files on BSD is broken") if self.expect_exact_path_match(): assert os.path.normcase(path) == os.path.normcase(self.funky_name) @@ -269,7 +268,7 @@ def test_proc_net_connections(self): if PY3: raise else: - raise unittest.SkipTest("not supported") + raise pytest.skip("not supported") with closing(sock): conn = psutil.Process().net_connections('unix')[0] assert isinstance(conn.laddr, str) @@ -294,7 +293,7 @@ def find_sock(cons): if PY3: raise else: - raise unittest.SkipTest("not supported") + raise pytest.skip("not supported") with closing(sock): cons = psutil.net_connections(kind='unix') conn = find_sock(cons) diff --git a/psutil/tests/test_windows.py b/psutil/tests/test_windows.py index da1da930b..b11b0e706 100755 --- a/psutil/tests/test_windows.py +++ b/psutil/tests/test_windows.py @@ -17,7 +17,6 @@ import subprocess import sys import time -import unittest import warnings import psutil @@ -74,7 +73,7 @@ def powershell(cmd): "Get-CIMInstance Win32_PageFileUsage | Select AllocatedBaseSize") """ if not which("powershell.exe"): - raise unittest.SkipTest("powershell.exe not available") + raise pytest.skip("powershell.exe not available") cmdline = ( 'powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive ' + '-NoProfile -WindowStyle Hidden -Command "%s"' % cmd @@ -440,7 +439,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 psutil.Process().username() == name def test_cmdline(self): @@ -775,7 +774,7 @@ def setUp(self): other_python = self.find_other_interpreter() if other_python is None: - raise unittest.SkipTest( + raise pytest.skip( "could not find interpreter with opposite bitness" ) if IS_64BIT: