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



我开始使用py。现在测试一个新项目。我们正在提供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

但是我不能将测试结果放入日志文件中,而是在测试后通过stdout得到标准输出:

======================================= 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的任务是捕获输出并将其呈现给操作符。因此,与其试图让pytest按照您想要的方式进行日志记录,不如将日志记录构建到您的测试中。

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

下面是一个使用这样一个函数的小测试文件:
# 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)

有关向终端和日志文件发送实时日志的更多示例,请查看我对在py中进行日志记录的回答。测试测试.

参考:pytest文档中的实时日志部分

最新更新