如何将 pytest 与子进程一起使用?

How to use pytest with subprocess?

以下是测试。如果 subprocess.run 导致错误,如何使此测试失败?

import pytest
import subprocess

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

subprocess.run return一个CompletedProcess instance,你可以检查一下。

我不确定“导致错误”到底是什么意思——如果进程的 return 代码不为零,您可以检查 returncode。 如果输出的是特定错误消息,请改为检查 stdout or stderr

例如:

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

注意。您似乎没有在测试函数中使用参数化参数 input_json 。只是一个观察。