Test run_subprocess.
(tmp_path, capsys, kind, do_raise)
| 43 | @pytest.mark.parametrize("kind", ("stdout", "stderr")) |
| 44 | @pytest.mark.parametrize("do_raise", (True, False)) |
| 45 | def test_run_subprocess(tmp_path, capsys, kind, do_raise): |
| 46 | """Test run_subprocess.""" |
| 47 | fname = tmp_path / "subp.py" |
| 48 | extra = "" |
| 49 | if do_raise: |
| 50 | extra = """ |
| 51 | raise RuntimeError('This is a test') |
| 52 | """ |
| 53 | raise_context = pytest.raises(subprocess.CalledProcessError) |
| 54 | else: |
| 55 | extra = "" |
| 56 | raise_context = nullcontext() |
| 57 | with open(fname, "w") as fid: |
| 58 | fid.write( |
| 59 | f"""\ |
| 60 | import sys |
| 61 | import time |
| 62 | print('foo', file=sys.{kind}) |
| 63 | print('bar', file=sys.{kind}) |
| 64 | """ |
| 65 | + extra |
| 66 | ) |
| 67 | with catch_logging() as log, raise_context: |
| 68 | stdout, stderr = run_subprocess([sys.executable, str(fname)], verbose=True) |
| 69 | if do_raise: |
| 70 | exc = raise_context.excinfo.value |
| 71 | stdout = exc.stdout |
| 72 | stderr = exc.stderr |
| 73 | log = log.getvalue() |
| 74 | log = "\n".join(log.split("\n")[1:]) # get rid of header |
| 75 | log = log.replace("\r\n", "\n") # Windows |
| 76 | orig_log = log |
| 77 | stdout = stdout.replace("\r\n", "\n") |
| 78 | stderr = stderr.replace("\r\n", "\n") |
| 79 | if do_raise: # remove traceback |
| 80 | |
| 81 | def remove_traceback(log): |
| 82 | return "\n".join( |
| 83 | line |
| 84 | for line in log.split("\n") |
| 85 | if not line.strip().startswith( |
| 86 | ("File ", "raise ", "RuntimeError: ", "Traceback ") |
| 87 | ) |
| 88 | ) |
| 89 | |
| 90 | log = remove_traceback(log) |
| 91 | stderr = remove_traceback(stderr) |
| 92 | want = "foo\nbar\n" |
| 93 | assert log == want, orig_log |
| 94 | if kind == "stdout": |
| 95 | std = stdout |
| 96 | other = stderr |
| 97 | else: |
| 98 | std = stderr |
| 99 | other = stdout |
| 100 | assert std == want |
| 101 | assert other == "" |
| 102 | stdout, stderr = capsys.readouterr() |
nothing calls this directly
no test coverage detected