Run ``cmd`` in a subprocess, failing the test with its captured output if it exits with a nonzero status. Output that a subprocess merely inherits is lost in pytest-xdist workers when a test fails, making CI failures hard to debug. Routing a build/compile/run step through this help
(cmd, cwd=None, **kwargs)
| 2871 | |
| 2872 | |
| 2873 | def run_subprocess(cmd, cwd=None, **kwargs): |
| 2874 | """Run ``cmd`` in a subprocess, failing the test with its captured output |
| 2875 | if it exits with a nonzero status. |
| 2876 | |
| 2877 | Output that a subprocess merely inherits is lost in pytest-xdist workers |
| 2878 | when a test fails, making CI failures hard to debug. Routing a |
| 2879 | build/compile/run step through this helper captures the child's stdout and |
| 2880 | stderr and folds them into the failure message so they reach the report. |
| 2881 | Returns the ``subprocess.CompletedProcess`` for callers that want to |
| 2882 | inspect the output. Extra keyword arguments are passed to |
| 2883 | ``subprocess.run``. |
| 2884 | """ |
| 2885 | import subprocess |
| 2886 | |
| 2887 | import pytest |
| 2888 | |
| 2889 | res = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, |
| 2890 | errors="replace", **kwargs) |
| 2891 | if res.returncode != 0: |
| 2892 | cmd_str = cmd if isinstance(cmd, str) else " ".join(map(str, cmd)) |
| 2893 | in_dir = f" in {cwd}" if cwd is not None else "" |
| 2894 | pytest.fail( |
| 2895 | f"`{cmd_str}` failed (exit {res.returncode}){in_dir}\n" |
| 2896 | f"----- stdout -----\n{res.stdout}\n" |
| 2897 | f"----- stderr -----\n{res.stderr}", |
| 2898 | pytrace=False) |
| 2899 | return res |
searching dependent graphs…