我想在测试函数中放置一些日志语句来检查一些状态变量。
我有以下代码片段:
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__'块的日志消息才会传输到控制台。
'__name__ == __main__'
有没有办法强制pytest从测试方法向控制台发出日志记录?
pytest
对我有用,这是我得到的输出:[snip -> 示例不正确]
编辑:您似乎必须将-s选项传递给 py.test,这样它就不会捕获标准输出。在这里(py.test 未安装),使用 python pytest.py -s pyt.py.
-s
python pytest.py -s pyt.py
-s对于您的代码,您args只需要传入main:
args
main
pytest.main(args=['-s', os.path.abspath(__file__)])
请参阅有关捕获输出的 py.test 文档。