From 4c69b9cc34f9efd338b42cf346fec7aa31da0acd Mon Sep 17 00:00:00 2001 From: Simon Blanke Date: Sat, 18 Jan 2025 11:02:57 +0100 Subject: [PATCH] add _run_subprocess-method and capture output line-by-line --- tests/test_empty_output/test_empty_output.py | 33 ++++++++++++++++---- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/tests/test_empty_output/test_empty_output.py b/tests/test_empty_output/test_empty_output.py index adacbde2..65552486 100644 --- a/tests/test_empty_output/test_empty_output.py +++ b/tests/test_empty_output/test_empty_output.py @@ -6,6 +6,27 @@ non_verbose_file = os.path.join(here, "non_verbose.py") +def _run_subprocess(script): + output = [] + process = subprocess.Popen( + [sys.executable, "-u", script], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + bufsize=1, # Line buffered + env={**os.environ, "PYTHONUNBUFFERED": "1"}, + ) + # Read output line by line + while True: + line = process.stdout.readline() + if line: + output.append(line) + if not line and process.poll() is not None: + break + + return "".join(output), process.stderr.read() + + def test_empty_output(): output_verbose = subprocess.run( [sys.executable, "-u", verbose_file], @@ -19,11 +40,11 @@ def test_empty_output(): ["python", non_verbose_file], stdout=subprocess.PIPE ) - verbose_str = output_verbose.stdout - non_verbose_str = output_non_verbose.stdout + stdout_verb, stderr_verb = _run_subprocess(verbose_file) + stdout_non_verb, stderr_non_verb = _run_subprocess(non_verbose_file) - print("\n verbose_str \n", verbose_str, "\n") - print("\n non_verbose_str \n", non_verbose_str, "\n") + print("\n stdout_verb \n", stdout_verb, "\n") + print("\n stderr_verb \n", stderr_verb, "\n") - assert "Results:" in verbose_str - assert not non_verbose_str + assert "Results:" in stdout_verb + assert not stdout_non_verb