测试将消息和测试结果/断言记录到单个fi中

2024-09-26 22:55:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在开始为一个新项目使用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

但我无法将测试结果放入日志文件,而是在测试之后在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,因为这里经常提到它,但我肯定做错了,因为我就是不明白。也许只是不了解这到底是怎么回事。希望你能给我一些提示。如果这里有什么遗漏,请告诉我。

提前谢谢你的帮助

斯蒂芬


Tags: 文件pytestinfoforoutputpytestlogging
2条回答

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)

有关向终端和日志文件发送实时日志的更多示例,请查看我对Logging within py.test tests 的回答。

引用:pytest文档中的Live Logs部分。

相关问题 更多 >

    热门问题