Skip to content

Commit

Permalink
Print output when a subprocess runner with check=True fails.
Browse files Browse the repository at this point in the history
The raised exception from subprocess.run was suppressing the printed output.
This is now fixed and covered by tests.

Also updates the test to the non-deprecated version of the call.
  • Loading branch information
HexDecimal authored and kvas-it committed May 26, 2023
1 parent 6bc9212 commit 24ca589
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 16 deletions.
28 changes: 16 additions & 12 deletions pytest_console_scripts/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,18 +431,22 @@ def run_subprocess(
)
command = [sys.executable or 'python', *command]

cp = subprocess.run(
command,
input=stdin_input,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
cwd=cwd,
env=env,
check=check,
universal_newlines=universal_newlines,
**options,
)
try:
cp = subprocess.run(
command,
input=stdin_input,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
cwd=cwd,
env=env,
check=check,
universal_newlines=universal_newlines,
**options,
)
except subprocess.CalledProcessError as exc:
RunResult(exc.returncode, exc.stdout, exc.stderr, print_result)
raise
return RunResult(cp.returncode, cp.stdout, cp.stderr, print_result)


Expand Down
17 changes: 13 additions & 4 deletions tests/test_run_scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,29 +229,38 @@ def test_logging(console_script: Path, script_runner: ScriptRunner) -> None:


@pytest.mark.parametrize('fail', [True, False])
@pytest.mark.parametrize('check', [True, False])
def test_print_stdio_on_error(
console_script: Path,
script_runner: ScriptRunner,
tmp_path: Path,
fail: bool,
check: bool,
launch_mode: str,
) -> None:
"""Output of the script is printed when the test fails."""
console_script.write_text('print("12345")\nraise Exception("54321")')
test = tmp_path / f'test_{fail}_{launch_mode}.py'
test = tmp_path / f'test_{fail}_{check}_{launch_mode}.py'
command = [str(console_script), 'arg']
test.write_text(
f"""
import subprocess
def test_fail(script_runner):
ret = script_runner.run(R'''{console_script}''', 'arg')
assert ret.success is {fail}
try:
ret = script_runner.run({command}, check={check})
except subprocess.CalledProcessError as exc:
assert (exc.returncode == 0) is {fail}
else:
assert ret.success is {fail}
"""
)
result = script_runner.run(
['pytest', test, f'--script-launch-mode={launch_mode}']
)
assert result.success != fail
if fail:
assert (f'# Running console script: {console_script} arg\n'
assert (f'# Running console script: {command}\n'
in result.stdout)
assert '# Script return code: 1\n' in result.stdout
assert '# Script stdout:\n12345\n' in result.stdout
Expand Down

0 comments on commit 24ca589

Please sign in to comment.