Skip to content

Commit

Permalink
more tests refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo committed Jan 7, 2024
1 parent 2e2668d commit 20ba266
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 59 deletions.
69 changes: 40 additions & 29 deletions psutil/tests/__init__.py
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 <unistd.h>
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 <unistd.h>
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):
Expand All @@ -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


# ===================================================================
Expand Down Expand Up @@ -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
Expand Down
30 changes: 13 additions & 17 deletions psutil/tests/test_process.py
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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")
Expand All @@ -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):
Expand Down Expand Up @@ -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)
Expand Down
19 changes: 6 additions & 13 deletions psutil/tests/test_unicode.py
Expand Up @@ -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
Expand Down Expand Up @@ -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')
Expand All @@ -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()
Expand All @@ -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.
Expand Down

0 comments on commit 20ba266

Please sign in to comment.