如何将pytest的结果/日志保存到文件中?

non*_*bot 7 python logging pytest

我无法尝试将pytest中显示的结果保存到文件中(txt,log,无所谓).在下面的测试示例中,我想将控制台中显示的内容捕获到某种文本/日志文件中:

import pytest
import os

def test_func1():
    assert True


def test_func2():
    assert 0 == 1

if __name__ == '__main__':

    pytest.main(args=['-sv', os.path.abspath(__file__)])
Run Code Online (Sandbox Code Playgroud)

控制台输出我想保存到文本文件:

test-mbp:hi_world ua$ python test_out.py
================================================= test session starts =================================================
platform darwin -- Python 2.7.6 -- py-1.4.28 -- pytest-2.7.1 -- /usr/bin/python
rootdir: /Users/tester/PycharmProjects/hi_world, inifile: 
plugins: capturelog
collected 2 items 

test_out.py::test_func1 PASSED
test_out.py::test_func2 FAILED

====================================================== FAILURES =======================================================
_____________________________________________________ test_func2 ______________________________________________________

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

test_out.py:9: AssertionError
========================================= 1 failed, 1 passed in 0.01 seconds ==========================================
test-mbp:hi_world ua$ 
Run Code Online (Sandbox Code Playgroud)

Mic*_*ott 12

看起来你的所有测试输出都是stdout,所以你只需要在那里"重定向"你的python调用输出:

python test_out.py >myoutput.log
Run Code Online (Sandbox Code Playgroud)

您还可以将输出"发球"到多个位置.例如,您可能希望登录该文件,还可以在控制台上看到输出.上面的例子然后变成:

python test_out.py | tee myoutput.log
Run Code Online (Sandbox Code Playgroud)

  • 这是根据OP要求的正确答案,但另一个有用的答案是“pytest --junitxml=./output.xml”。这会输出一个 junit xml 文件,可以在 junit 查看器中打开,例如 [xunit-viewer](https://github.com/lukejpreston/xunit-viewer) (2认同)