How to use pytest with subprocess?

Viewed 1003

The following is a test. How to make this test fail if the subprocess.run results in an error?

import pytest
import subprocess

@pytest.mark.parametrize("input_json", ["input.json"])
def test_main(input_json):
    subprocess.run(['python', 'main.py', input_json]
1 Answers

subprocess.run returns a CompletedProcess instance, which you can inspect.

I'm not sure what exactly you mean by "results in an error"—if it's the return code of the process being non-zero, you can check returncode. If it's a specific error message being output, check stdout or stderr instead.

For example:

import pytest
import subprocess

@pytest.mark.parametrize("input_json", ["input.json"])
def test_main(input_json):
    completed_process = subprocess.run(['python', 'main.py', 'input_json']
    assert completed_process.returncode == 0

NB. You don't seem to use the parametrized argument input_json within your test function. Just an observation.

Related