我现在开始为一个新项目使用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,因为这里经常提到它,但我肯定做错了,因为我就是不明白。也许只是不了解这到底是怎么回事。希望你能给我一些提示。如果这里有什么遗漏,请告诉我。
提前谢谢你的帮助
斯蒂芬
pytest的工作是捕获输出并将其呈现给操作员。因此,与其让pytest按照您想要的方式进行日志记录,不如将日志记录构建到您的测试中。
Python的
assert
命令只接受一个真值和一条消息。因此,不要在测试中使用一个空的assert
,您可以编写一个小函数,在值为false(这是触发断言失败的相同条件)时执行日志记录,然后调用断言,以便获得所需的日志记录,以及创建控制台输出的断言驱动行为。下面是一个使用这样一个函数的小测试文件:
这是测试运行程序,与您的非常相似:
输出如下:
下面是日志:
由于版本3.3,
pytest
支持到终端和文件的实时日志记录。测试模块示例:日志记录到文件的配置可以在
pytest.ini
中完成:像往常一样运行测试:
现在检查写入的日志文件:
有关向终端和日志文件发送实时日志的更多示例,请查看我对Logging within py.test tests 的回答。
引用:
pytest
文档中的Live Logs部分。相关问题 更多 >
编程相关推荐