小编典典

在pytest测试中记录

python

我想在测试函数中放入一些日志记录语句,以检查一些状态变量。

我有以下代码片段:

import pytest,os
import logging

logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()

#############################################################################

def setup_module(module):
    ''' Setup for the entire module '''
    mylogger.info('Inside Setup')
    # Do the actual setup stuff here
    pass

def setup_function(func):
    ''' Setup for test functions '''
    if func == test_one:
        mylogger.info(' Hurray !!')

def test_one():
    ''' Test One '''
    mylogger.info('Inside Test 1')
    #assert 0 == 1
    pass

def test_two():
    ''' Test Two '''
    mylogger.info('Inside Test 2')
    pass

if __name__ == '__main__':
    mylogger.info(' About to start the tests ')
    pytest.main(args=[os.path.abspath(__file__)])
    mylogger.info(' Done executing the tests ')

我得到以下输出:

[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py
INFO:root: About to start the tests 
======================================================== test session starts =========================================================
platform darwin -- Python 2.6.2 -- pytest-2.0.0
collected 2 items

minitest.py ..

====================================================== 2 passed in 0.01 seconds ======================================================
INFO:root: Done executing the tests

请注意,只有来自'__name__ == __main__'块的日志记录消息才被传输到控制台。

是否有一种方法也可以强制pytest从测试方法向控制台发出日志记录?


阅读 213

收藏
2020-12-20

共1个答案

小编典典

为我工作,这是我得到的输出:[snip-> example was not正确]

编辑:看来您必须将-s选项传递给py.test,以便它不会捕获stdout。在这里(未安装py.test)就足够了 python pytest.py -s pyt.py

对于你的代码,你需要的是通过-sargsmain

 pytest.main(args=['-s', os.path.abspath(__file__)])

请参阅py.test文档以获取输出

2020-12-20