我创建了一个
pytest.ini
文件,
addopts = --resultlog=log.txt
这会创建一个日志文件,但我想每次运行测试时都创建一个新的日志文件。
--result-log
参数已弃用并计划在版本 6.0 中删除(请参阅弃用和删除:结果日志)。 issue #4488 中讨论了可能的替换实现,因此请留意下一个主要版本的更新 - 下面的代码将停止与 pytest==6.0
一起使用。
您可以在
resultlog
hookimpl 中修改
pytest_configure
。示例:将以下代码放入项目根目录下的 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
not 显式传递(因此您必须从 addopts = --resultlog=log.txt
中删除 pytest.ini
),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
通过将日志文件命名为测试执行开始的时间,您可以拥有不同的 pytest 运行日志。
pytest tests --log-file $(date '+%F_%H:%M:%S')
这将为每次测试运行创建一个日志文件。测试运行的名称将是时间戳。
$(date '+%F_%H:%M:%S')
是 bash 命令,用于以 DATE_Hr:Min:Sec
格式获取当前时间戳。
扩展@SilentGuy的有用解决方案,如这个类似问题中的回答,您可以通过以下方式将用户名和时间戳添加到文件名:
pytest . -vv | tee ./logs/$(whoami)_"$(date +%Y%m%d_%H%M%S)".log
哪里
.
运行 test/
-vv
返回非常详细的结果whoami
解析为您在 linux/windows 上的用户名