如何将pytest.main消息写入字符串?

时间:2018-02-09 22:45:09

标签: python unit-testing pytest

当我在Python中调用pytest.main(...)时,它会在输出窗口中显示单元测试消息,例如

============================= test session starts =============================
platform win32 -- Python 3.6.4, pytest-3.3.2, py-1.5.2, pluggy-0.6.0
rootdir: xxx, inifile: pytest.ini
plugins: cov-2.5.1, hypothesis-3.38.5
collected 1 item

..\test_example.py F                                      [100%]

================================== FAILURES ===================================
_______________________________ test_something ________________________________

    def test_something():
>       assert 1 == 0
E       assert 1 == 0

..\test_example.py:5: AssertionError
========================== 1 failed in 0.60 seconds ===========================

我的问题很简单,我怎样才能将上面的消息传递给字符串对象。文档没有说明这一点。而pytest.main()返回的只是一个表示错误代码的整数。

https://docs.pytest.org/en/latest/usage.html#calling-pytest-from-python-code

1 个答案:

答案 0 :(得分:0)

我不知道pytest但您可以尝试将标准输出重定向到文件。像这样:

import sys
sys.stdout = open("log.txt", "w")

在此之后,您可以读取文件以获取字符串。你想用字符串做什么?