Dud*_*poo 3 python logging pytest python-3.x
我创建了一个pytest.ini文件,
addopts = --resultlog=log.txt
Run Code Online (Sandbox Code Playgroud)
这会创建一个日志文件,但我想在每次运行测试时创建一个新的日志文件。
我是 pytest 的新手,如果我在阅读文档时遗漏了任何内容,请原谅我。
谢谢
--result-log参数已弃用并计划在 6.0 版中删除(请参阅弃用和删除:结果日志)。问题 #4488 中讨论了可能的替换实现,因此请注意下一个主要版本的碰撞 - 下面的代码将停止使用pytest==6.0.
您可以修改resultlog在pytest_configurehookimpl。示例:将以下代码放入conftest.py项目根目录中的文件中:
import datetime
def pytest_configure(config):
if not config.option.resultlog:
timestamp = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d_%H-%M-%S')
config.option.resultlog = 'log.' + timestamp
Run Code Online (Sandbox Code Playgroud)
现在,如果--result-log是不明确的传递(所以你必须删除addopts = --resultlog=log.txt从你的pytest.ini),pytest将创建一个时间戳结尾的日志文件。传递--result-log日志文件名将覆盖此行为。
回答我自己的问题。由于 hoefling 提到的--result-log已被弃用,我必须找到一种方法来做到这一点而不使用该标志。我是这样做的,
测试.py
from datetime import datetime
import logging
log = logging.getLogger(__name__)
def pytest_assertrepr_compare(op, left, right):
""" This function will print log everytime the assert fails"""
log.error('Comparing Foo instances: vals: %s != %s \n' % (left, right))
return ["Comparing Foo instances:", " vals: %s != %s" % (left, right)]
def pytest_configure(config):
""" Create a log file if log_file is not mentioned in *.ini file"""
if not config.option.log_file:
timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d_%H-%M-%S')
config.option.log_file = 'log.' + timestamp
Run Code Online (Sandbox Code Playgroud)
pytest.ini
[pytest]
log_cli = true
log_cli_level = CRITICAL
log_cli_format = %(message)s
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
Run Code Online (Sandbox Code Playgroud)
测试我的代码.py
import logging
log = logging.getLogger(__name__)
def test_my_code():
****test code
Run Code Online (Sandbox Code Playgroud)