【发布时间】:2019-07-23 13:57:57
【问题描述】:
我创建了一个pytest.ini 文件,
addopts = --resultlog=log.txt
这会创建一个日志文件,但我想在每次运行测试时创建一个新的日志文件。
我是 pytest 的新手,如果我在阅读文档时遗漏了什么,请原谅我。
谢谢
【问题讨论】:
标签: python python-3.x logging pytest
我创建了一个pytest.ini 文件,
addopts = --resultlog=log.txt
这会创建一个日志文件,但我想在每次运行测试时创建一个新的日志文件。
我是 pytest 的新手,如果我在阅读文档时遗漏了什么,请原谅我。
谢谢
【问题讨论】:
标签: python python-3.x logging pytest
--result-log 参数已弃用并计划在 6.0 版中删除(请参阅Deprecations and Removals: Result log)。 issue #4488 讨论了可能的替代实现,因此请注意下一个主要版本的碰撞 - 下面的代码将停止使用 pytest==6.0。
您可以在pytest_configure hookimpl 中修改resultlog。示例:将以下代码放入项目根目录的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
现在如果--result-log 没有 明确传递(因此您必须从pytest.ini 中删除addopts = --resultlog=log.txt),pytest 将创建一个以时间戳结尾的日志文件。使用日志文件名传递 --result-log 将覆盖此行为。
【讨论】:
回答我自己的问题。
正如 hoefling 提到的 --result-log 已被弃用,我必须找到一种不使用该标志的方法。这是我的做法,
conftest.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
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
test_my_code.py
import logging
log = logging.getLogger(__name__)
def test_my_code():
****test code
【讨论】:
--result-log 不同。前者只保留代码发出的日志,后者将完整的测试运行输出的副本写入文件。
通过将日志文件命名为测试执行开始的时间,您可以拥有不同的 pytest 运行日志。
pytest tests --log-file $(date '+%F_%H:%M:%S')
这将为每次测试运行创建一个日志文件。测试运行的名称将是时间戳。
$(date '+%F_%H:%M:%S') 是 bash 命令,用于获取 DATE_Hr:Min:Sec 格式的当前时间戳。
【讨论】: