[英]How to write pytest tests that run in 2 stages, each stage sequentially?
[英]How to create new log file for each run of tests in pytest?
我创建了一个pytest.ini
文件,
addopts = --resultlog=log.txt
这会创建一个日志文件,但我想在每次运行测试时创建一个新的日志文件。
我是pytest的新手,如果我在阅读文档时遗漏了任何内容,请原谅我。
谢谢
--result-log
参数已弃用并计划在6.0版中删除(请参阅“ Deprecations and Removals:Result log” )。 问题#4488中讨论了可能的替换实现,因此请注意下一个主要版本 - 下面的代码将停止使用pytest==6.0
。
您可以修改resultlog
在pytest_configure
hookimpl。 示例:将以下代码放在项目根目录的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
通过将日志文件命名为测试执行开始的时间,您可以拥有不同的pytest运行日志。
pytest tests --log-file $(date '+%F_%H:%M:%S')
这将为每次测试运行创建一个日志文件。 测试运行的名称将是时间戳。
$(date '+%F_%H:%M:%S')
是用于获取DATE_Hr:Min:Sec
格式的当前时间戳的bash命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.