From 02080b366f51c892b08e684b8a23e43d38abf0d7 Mon Sep 17 00:00:00 2001 From: Jesper Friis Date: Wed, 1 May 2024 17:27:03 +0200 Subject: [PATCH] Simplified test_python_bindings.py (#831) Running test_python_bindings.py when building wheels fails randomly on Windows. Tried to simplify stdout redirections. Hopefully that will work better on Windows. --- bindings/python/tests/test_python_bindings.py | 36 ++++++------------- 1 file changed, 11 insertions(+), 25 deletions(-) diff --git a/bindings/python/tests/test_python_bindings.py b/bindings/python/tests/test_python_bindings.py index f3dcfb919..6d2d354c4 100755 --- a/bindings/python/tests/test_python_bindings.py +++ b/bindings/python/tests/test_python_bindings.py @@ -4,6 +4,7 @@ import sys from glob import glob import unittest +from contextlib import redirect_stdout, redirect_stderr import dlite @@ -42,6 +43,7 @@ def __repr__(self): def test(verbosity=1, stream=sys.stdout): + """Run tests with given verbosity level.""" tests = [ test for test in sorted(glob(os.path.join(thisdir, "test_*.py"))) @@ -54,32 +56,16 @@ def test(verbosity=1, stream=sys.stdout): ts = unittest.TestSuite() for test in sorted(tests): ts.addTest(ScriptTestCase(filename=os.path.abspath(test))) - with open(os.devnull, "w") as devnull: - if not verbosity: - stream = devnull - ttr = unittest.TextTestRunner(verbosity=verbosity, stream=stream) - # Redirect stdout and stderr to devnull - # stderr is redicred at file-descriptor level to get rid of - # C-level output - dest_fd = devnull.fileno() - stderr_fd = sys.stderr.fileno() - # copy stderr_fd before it is overwritten - # NOTE: `copied` is inheritable on Windows when duplicating a - # standard stream - with os.fdopen(os.dup(stderr_fd), "wb") as copied: - sys.stdout.flush() - sys.stderr.flush() - try: - sys.stdout = devnull - os.dup2(dest_fd, stderr_fd) # $ exec >&dest - results = ttr.run(ts) - finally: - sys.stdout.flush() - sys.stderr.flush() - sys.stdout = sys.__stdout__ - os.dup2(copied.fileno(), stderr_fd) # $ exec >&copied - return results + ttr = unittest.TextTestRunner(verbosity=verbosity, stream=stream) + + if verbosity < 3: + with open(os.devnull, "w") as devnull: + with redirect_stderr(devnull): + with redirect_stdout(devnull): + return ttr.run(ts) + else: + return ttr.run(ts) if __name__ == "__main__":