pytest.main() 捕获标准输出

pytest.main() capture standard output

我有一种方法可以用来获取我们拥有的所有测试。

def get_test_names_from_file():

    get_test_names = pytest.main(['--collect-only', '-q'])
    print(type(get_test_names))

    return 'here is the methods return: ' + str(get_test_names)

当我调用此方法时,它 return 是一个存在的代码 here is the methods return: 0,这很好。我想不通的是如何将生成的标准转化为我可以使用的格式。

调用方法时的标准输出:

test_a.py::TestA::test_general_a
test_a.py::TestA::test_python_a
test_a.py::TestA::test_python_learning_a
test_b.py::TestB::test_b

如何捕获此输出以便我可以 return 它?我已尽最大努力阅读文档,但似乎无法找到一种方法来做到这一点。

感谢您的宝贵时间。

编辑: 我能够使用子进程得到一些工作,但我更喜欢使用 pytest 而不是混合和匹配:

def get_test_names_from_file():

    pytest_command_string = 'pytest --collect-only -q'
    pytest_command = subprocess.Popen(pytest_command_string.split(), shell=False, stdout=subprocess.PIPE)
    pytest_command_out = pytest_command.communicate()[0]

    print(type(pytest_command_out))
    return pytest_command_out

您可以为此使用 py.io

类似于:

capture = py.io.StdCapture()
pytest.main(['--collect-only', '-q'])
std, err = capture.reset()
print(std)

将为您提供所需的标准输出。