pytest.main()捕获标准输出

时间:2018-06-08 14:36:32

标签: python pytest

我有一个方法,我用来获得我们所有的测试。

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)

当我调用此方法时,它返回一个存在的代码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

如何捕获此输出以便我可以返回它?我已尽力阅读文档,似乎无法找到实现此目的的方法。

感谢您的时间。

编辑: 我能够使用subprocess工作,但我更喜欢使用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

1 个答案:

答案 0 :(得分:1)

您可以使用py.io

类似的东西:

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

为您提供您正在寻找的标准输出。

相关问题