Python py.test将消息和测试结果/断言记录到单个文件中

Python py.test将消息和测试结果/断言记录到单个文件中,python,testing,logging,pytest,Python,Testing,Logging,Pytest,我现在开始为一个新项目使用py.test。我们正在配置Linux服务器,我需要编写一个脚本来检查这些服务器的设置和配置。我认为py.test是实现这些测试的一种很好的方法,到目前为止,它工作得很好 我现在面临的问题是,在这些测试结束时,我需要一个日志文件来显示每个测试的一些日志消息和测试结果。对于日志消息,我使用logger: logging.basicConfig(filename='config_check.log', level=logging.INFO) pytest.main() lo

我现在开始为一个新项目使用py.test。我们正在配置Linux服务器,我需要编写一个脚本来检查这些服务器的设置和配置。我认为py.test是实现这些测试的一种很好的方法,到目前为止,它工作得很好

我现在面临的问题是,在这些测试结束时,我需要一个日志文件来显示每个测试的一些日志消息和测试结果。对于日志消息,我使用logger:

logging.basicConfig(filename='config_check.log', level=logging.INFO)
pytest.main()
logging.info('all done')
作为示例测试,我有以下内容:

def test_taintedKernel():
    logging.info('checking for tainted kernel')
    output = runcmd('cat /proc/sys/kernel/tainted')
    assert output == '0', 'tainted kernel found'
所以在我的日志文件中,我想要这样的输出:

INFO:root:checking for tainted kernel
ERROR:root:tainted kernel found
INFO:root:next test
INFO:root:successful
INFO:root:all done
但我无法将测试结果写入日志文件,而是在测试后在标准输出上获取标准输出:

======================================= test session starts =======================================
platform linux2 -- Python 2.6.8 -- py-1.4.22 -- pytest-2.6.0
collected 14 items 

test_basicLinux.py .............F

============================================ FAILURES =============================================
_______________________________________ test_taintedKernel ________________________________________

    def test_taintedKernel():
        logging.info('checking for tainted kernel')
        output = runcmd('cat /proc/sys/kernel/tainted')
>       assert output == '0', 'tainted kernel found'
E       AssertionError: tainted kernel found

test_basicLinux.py:107: AssertionError
=============================== 1 failed, 13 passed in 6.07 seconds ===============================
对于我的脚本的用户来说,这可能会非常混乱。我试图进入logger和pytest_capturelog,因为这里经常提到它,但我肯定做了一些错误的事情,因为我不明白。也许只是不了解这到底是怎么回事。希望你能给我一些提示。如果这里缺什么,请告诉我

提前感谢您的帮助


Stephan的工作是捕获输出并将其呈现给操作员。因此,您可以将日志构建到您的测试中,而不是试图让pytest按照您想要的方式进行日志记录

Python的
assert
命令只接受一个真值和一条消息。因此,您可以编写一个小函数,在值为false(这与触发断言失败的条件相同)时进行日志记录,然后调用断言,从而获得所需的日志记录,以及创建控制台输出的断言驱动行为,而不是在测试中使用裸的
assert

下面是一个使用此函数的小测试文件:

# test_foo.py
import logging

def logAssert(test,msg):
    if not test:
        logging.error(msg)
        assert test,msg

def test_foo():
    logging.info("testing foo")
    logAssert( 'foo' == 'foo', "foo is not foo")

def test_foobar():
    logging.info("testing foobar")
    logAssert( 'foobar' == 'foo', "foobar is not foo")
这是与您的非常相似的测试跑步者:

# runtests.py
import logging
import pytest

logging.basicConfig(filename='config_check.log', level=logging.INFO)
logging.info('start')
pytest.main()
logging.info('done')
以下是输出:

# python runtests.py
==== test session starts ========================
platform linux2 -- Python 2.6.6 -- py-1.4.22 -- pytest-2.6.0
collected 2 items

test_foo.py .F

========== FAILURES ============================
________ test_foobar __________________________

    def test_foobar():
        logging.info("testing foobar")
>       logAssert( 'foobar' == 'foo', "foobar is not foo")

test_foo.py:14:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

test = False, msg = 'foobar is not foo'

    def logAssert(test,msg):
        if not test:
            logging.error(msg)
>           assert test,msg
E           AssertionError: foobar is not foo

test_foo.py:6: AssertionError    ==== 1 failed, 1 passed in 0.02 seconds =======
下面是要写入的日志:

# cat config_check.log 
INFO:root:start
INFO:root:testing foo
INFO:root:testing foobar
ERROR:root:foobar is not foo
INFO:root:done

从3.3版开始,
pytest
支持实时记录到终端和文件。测试模块示例:

import logging
import os


def test_taintedKernel():
    logging.info('checking for tainted kernel')
    output = os.system('cat /proc/sys/kernel/tainted')
    assert output == 0, 'tainted kernel found'
可以在
pytest.ini
中配置文件日志记录:

[pytest]
log_file = my.log
log_file_level = DEBUG
log_file_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_file_date_format=%Y-%m-%d %H:%M:%S
运行测试会像往常一样产生以下结果:

$ pytest
======================================================= test session starts ========================================================
...
collected 1 item                                                                                                                   

test_spam.py .                                                                                                               [100%]

===================================================== 1 passed in 0.01 seconds =====================================================
现在检查写入的日志文件:

$ cat my.log
2019-07-12 23:51:41 [    INFO] checking for tainted kernel (test_spam.py:6)
有关向终端和日志文件发送实时日志的更多示例,请查看我对的回答


参考:在
pytest
文档中的部分。

py.test
在生成非常有用的输出方面非常有用,但是,输出在第一时刻看起来非常混乱。日志记录也是一种比较原始的通信方法,我不期望它有多大的改进。如果您的用户不支持
py.test
所讨论的样式,我建议您要么将输出保存到单元测试xml中(使用
--junit xml xunit.xml
选项)并将其发送给您,要么放弃它并搜索其他解决方案。多亏了John的回答,我找到了一种适合我的方法。但你是对的,也许这并不是py.test的真正目的。但它节省了我编写和运行测试的大量工作,所以我很高兴有一个解决方案,让我保留py.test