【发布时间】:2014-09-13 13:40:27
【问题描述】:
我现在开始为一个新项目使用 py.test。我们正在配置 Linux 服务器,我需要编写一个脚本来检查这些服务器的设置和配置。我认为 py.test 是实现这些测试的好方法,到目前为止它工作得很好。
我现在面临的问题是,在这些测试结束时我需要一个日志文件,显示每个测试的一些日志消息和测试结果。对于我使用记录器的日志消息:
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,因为这里经常提到它,但我肯定做错了什么,因为我只是不明白。也许只是缺乏了解这是如何真正起作用的。希望你能给我一些提示。如果这里有什么遗漏,请告诉我。
提前感谢您的帮助,
斯蒂芬
【问题讨论】:
-
py.test在产生非常有用的输出方面非常出色,但输出在第一刻看起来很混乱。日志记录也是一种相当原始的通信方式,我不希望它有太大的改进。如果您的用户不支持py.test所说的样式,我建议将输出保存到单元测试xml(使用--junit-xml xunit.xml选项)并将其发送给您,或者放弃并搜索其他解决方案。跨度> -
感谢约翰的回答,我找到了一种适合我的方法。但你是对的,也许这不是 py.test 的真正用途。但它节省了我在编写和运行测试方面的大量工作,所以我对一个让我保留 py.test 的解决方案感到满意
标签: python testing logging pytest