From 20ba2662bbd66e01d2ce0d93b84eb8db9e723542 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Sun, 7 Jan 2024 12:19:40 +0100 Subject: [PATCH] more tests refactoring --- psutil/tests/__init__.py | 69 +++++++++++++++++++++--------------- psutil/tests/test_process.py | 30 +++++++--------- psutil/tests/test_unicode.py | 19 ++++------ 3 files changed, 59 insertions(+), 59 deletions(-) diff --git a/psutil/tests/__init__.py b/psutil/tests/__init__.py index df30e3069..336e17644 100644 --- a/psutil/tests/__init__.py +++ b/psutil/tests/__init__.py @@ -100,7 +100,7 @@ 'process_namespace', 'system_namespace', 'print_sysinfo', 'is_win_secure_system_proc', # fs utils - 'chdir', 'safe_rmpath', 'create_exe', 'get_testfn', + 'chdir', 'safe_rmpath', 'create_py_exe', 'create_c_exe', 'get_testfn', # os 'get_winver', 'kernel_version', # sync primitives @@ -377,7 +377,7 @@ def spawn_testproc(cmd=None, **kwds): pyline = ( "from time import sleep;" + "open(r'%s', 'w').close();" % testfn - + "sleep(60);" + + "[sleep(0.1) for x in range(100)];" # 10 secs ) cmd = [PYTHON_EXE, "-c", pyline] sproc = subprocess.Popen(cmd, **kwds) @@ -853,33 +853,41 @@ def chdir(dirname): os.chdir(curdir) -def create_exe(outpath, c_code=None): - """Creates an executable file in the given location.""" - assert not os.path.exists(outpath), outpath - if c_code: - if not which("gcc"): - raise unittest.SkipTest("gcc is not installed") - if isinstance(c_code, bool): # c_code is True - c_code = textwrap.dedent(""" - #include - int main() { - pause(); - return 1; - } - """) - assert isinstance(c_code, str), c_code - with open(get_testfn(suffix='.c'), "w") as f: - f.write(c_code) - try: - subprocess.check_call(["gcc", f.name, "-o", outpath]) - finally: - safe_rmpath(f.name) +def create_py_exe(path): + """Create a Python executable file in the given location.""" + assert not os.path.exists(path), path + atexit.register(safe_rmpath, path) + shutil.copyfile(PYTHON_EXE, path) + if POSIX: + st = os.stat(path) + os.chmod(path, st.st_mode | stat.S_IEXEC) + return path + + +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") + if c_code is None: + c_code = textwrap.dedent(""" + #include + int main() { + pause(); + return 1; + } + """) else: - # copy python executable - shutil.copyfile(PYTHON_EXE, outpath) - if POSIX: - st = os.stat(outpath) - os.chmod(outpath, st.st_mode | stat.S_IEXEC) + assert isinstance(c_code, str), c_code + + atexit.register(safe_rmpath, path) + with open(get_testfn(suffix='.c'), "w") as f: + f.write(c_code) + try: + subprocess.check_call(["gcc", f.name, "-o", path]) + finally: + safe_rmpath(f.name) + return path def get_testfn(suffix="", dir=None): @@ -891,7 +899,9 @@ def get_testfn(suffix="", dir=None): while True: name = tempfile.mktemp(prefix=TESTFN_PREFIX, suffix=suffix, dir=dir) if not os.path.exists(name): # also include dirs - return os.path.realpath(name) # needed for OSX + path = os.path.realpath(name) # needed for OSX + atexit.register(safe_rmpath, path) + return path # =================================================================== @@ -940,6 +950,7 @@ class PsutilTestCase(TestCase): """ def get_testfn(self, suffix="", dir=None): + suffix += "-" + self.id() # add the test name fname = get_testfn(suffix=suffix, dir=dir) self.addCleanup(safe_rmpath, fname) return fname diff --git a/psutil/tests/test_process.py b/psutil/tests/test_process.py index f03a22da0..fdd90dcbe 100755 --- a/psutil/tests/test_process.py +++ b/psutil/tests/test_process.py @@ -57,7 +57,8 @@ from psutil.tests import ThreadTask from psutil.tests import call_until from psutil.tests import copyload_shared_lib -from psutil.tests import create_exe +from psutil.tests import create_c_exe +from psutil.tests import create_py_exe from psutil.tests import mock from psutil.tests import process_namespace from psutil.tests import reap_children @@ -768,9 +769,8 @@ def test_name(self): @unittest.skipIf(PYPY, "unreliable on PYPY") def test_long_name(self): - testfn = self.get_testfn(suffix="0123456789" * 2) - create_exe(testfn) - cmdline = [testfn, "-c", "time.sleep(10)"] + pyexe = create_py_exe(self.get_testfn(suffix="0123456789" * 2)) + cmdline = [pyexe, "-c", "time.sleep(10)"] p = self.spawn_psproc(cmdline) if OPENBSD: # XXX: for some reason the test process may turn into a @@ -781,14 +781,14 @@ def test_long_name(self): # just compare the first 15 chars. Full explanation: # https://github.com/giampaolo/psutil/issues/2239 try: - self.assertEqual(p.name(), os.path.basename(testfn)) + self.assertEqual(p.name(), os.path.basename(pyexe)) except AssertionError: if p.status() == psutil.STATUS_ZOMBIE: - assert os.path.basename(testfn).startswith(p.name()) + assert os.path.basename(pyexe).startswith(p.name()) else: raise else: - self.assertEqual(p.name(), os.path.basename(testfn)) + self.assertEqual(p.name(), os.path.basename(pyexe)) # XXX @unittest.skipIf(SUNOS, "broken on SUNOS") @@ -798,15 +798,12 @@ def test_prog_w_funky_name(self): # Test that name(), exe() and cmdline() correctly handle programs # with funky chars such as spaces and ")", see: # https://github.com/giampaolo/psutil/issues/628 - funky_path = self.get_testfn(suffix='foo bar )') - create_exe(funky_path) - cmdline = [funky_path, "-c", "time.sleep(10)"] + pyexe = create_py_exe(self.get_testfn(suffix='foo bar )')) + cmdline = [pyexe, "-c", "time.sleep(10)"] p = self.spawn_psproc(cmdline) self.assertEqual(p.cmdline(), cmdline) - self.assertEqual(p.name(), os.path.basename(funky_path)) - self.assertEqual( - os.path.normcase(p.exe()), os.path.normcase(funky_path) - ) + self.assertEqual(p.name(), os.path.basename(pyexe)) + self.assertEqual(os.path.normcase(p.exe()), os.path.normcase(pyexe)) @unittest.skipIf(not POSIX, 'POSIX only') def test_uids(self): @@ -1477,10 +1474,9 @@ def test_weird_environ(self): return execve("/bin/cat", argv, envp); } """) - path = self.get_testfn() - create_exe(path, c_code=code) + cexe = create_c_exe(self.get_testfn(), c_code=code) sproc = self.spawn_testproc( - [path], stdin=subprocess.PIPE, stderr=subprocess.PIPE + [cexe], stdin=subprocess.PIPE, stderr=subprocess.PIPE ) p = psutil.Process(sproc.pid) wait_for_pid(p.pid) diff --git a/psutil/tests/test_unicode.py b/psutil/tests/test_unicode.py index 3ab71b03a..aeac62ce5 100755 --- a/psutil/tests/test_unicode.py +++ b/psutil/tests/test_unicode.py @@ -100,7 +100,7 @@ from psutil.tests import bind_unix_socket from psutil.tests import chdir from psutil.tests import copyload_shared_lib -from psutil.tests import create_exe +from psutil.tests import create_py_exe from psutil.tests import get_testfn from psutil.tests import safe_mkdir from psutil.tests import safe_rmpath @@ -139,7 +139,7 @@ def try_unicode(suffix): testfn = get_testfn(suffix=suffix) try: safe_rmpath(testfn) - create_exe(testfn) + create_py_exe(testfn) sproc = spawn_testproc(cmd=[testfn]) shutil.copyfile(testfn, testfn + '-2') safe_rmpath(testfn + '-2') @@ -165,9 +165,13 @@ class BaseUnicodeTest(PsutilTestCase): def setUpClass(cls): super().setUpClass() cls.skip_tests = False + cls.funky_name = None if cls.funky_suffix is not None: if not try_unicode(cls.funky_suffix): cls.skip_tests = True + else: + cls.funky_name = get_testfn(suffix=cls.funky_suffix) + create_py_exe(cls.funky_name) def setUp(self): super().setUp() @@ -183,17 +187,6 @@ class TestFSAPIs(BaseUnicodeTest): funky_suffix = UNICODE_SUFFIX - @classmethod - def setUpClass(cls): - super().setUpClass() - cls.funky_name = get_testfn(suffix=cls.funky_suffix) - create_exe(cls.funky_name) - - @classmethod - def tearDownClass(cls): - super().tearDownClass() - safe_rmpath(cls.funky_name) - def expect_exact_path_match(self): # Do not expect psutil to correctly handle unicode paths on # Python 2 if os.listdir() is not able either.