如何在pytest中为每次测试运行创建新的日志文件

如何在pytest中为每次测试运行创建新的日志文件

本文介绍了如何在pytest中为每次测试运行创建新的日志文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个 pytest.ini 文件

addopts = --resultlog=log.txt

这将创建一个日志文件,但是我希望每次运行测试时都创建一个新的日志文件.

This creates a log file, but I would like to create a new log file everytime I run the tests.

我是pytest的新手,如果在阅读文档时错过了任何内容,请原谅我.

I am new to the pytest, and pardon me if I have missed out anything while reading the documentation.

谢谢

推荐答案

回答我自己的问题.正如不提倡使用-result-log 一样,我不得不找到一种无需使用该标志的方法.这是我的方法,

Answering my own question.As hoefling mentioned --result-log is deprecated, I had to find a way to do it without using that flag. Here's how I did it,

conftest.py

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.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

test_my_code.py

import logging
log = logging.getLogger(__name__)

def test_my_code():
    ****test code

这篇关于如何在pytest中为每次测试运行创建新的日志文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:06