pytest.main() 捕获标准输出 [英] pytest.main() capture standard output

查看:99
本文介绍了pytest.main() 捕获标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a method I am using to get all of the tests we have.

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)

当我调用这个方法时,它返回一个存在代码这里是方法返回:0,这很好.我无法弄清楚的是如何将生成的标准转换为我可以使用的格式.

When I call this method it returns an exist code here is the methods return: 0 and that's fine. What I can not figure out is how I get the resulting standard out into a format that I can use.

这是调用方法时的标准输出:

Here is the standard out when the method is called:

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

我如何捕获这个输出以便我可以返回它?我已尽力通读文档,但似乎无法找到一种方法来做到这一点.

How do I capture this output so that I can return it? I have done my best to read through the docs, and can't seem to figure out a way to do this.

感谢您抽出宝贵时间.

我能够使用子流程来完成一些工作,但我更喜欢使用 pytest 而不是混合和匹配:

I was able to get something working using subprocess, but i'd prefer to use pytest rather than mix and match:

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 来解决这个问题.

You could use py.io for this.

类似:

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

可以获得您正在寻找的标准输出.

Would get you the standard output you're looking for.

这篇关于pytest.main() 捕获标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆