如何将 pytest 中每个测试的日志存储在单独的文件中

我在 中有以下代码conftest.py。它将所有测试的结果存储到同一个文件中。我想将日志存储在文件名为 的结果目录中results/test1_<timestamp>.logresults/test2_<timestamp>.log

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
开心每一天1111
浏览 1580回答 1
1回答

心有法竹

您可以使用以下方法配置每个测试的日志记录路径set_log_path(尽管请注意,文档认为它是实验性的):conftest.pyimport osfrom datetime import datetimeimport pytest@pytest.hookimpldef pytest_runtest_setup(item):&nbsp; &nbsp; logging_plugin = item.config.pluginmanager.get_plugin("logging-plugin")&nbsp; &nbsp; timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d_%H-%M-%S')&nbsp; &nbsp; logging_plugin.set_log_path(os.path.join('results', f'{item.name}_{timestamp}.log'))当然,您必须设置正确的根路径(我只是将“结果”放在那里)。这将为每个测试创建一个新的日志文件,并相应配置名称。您还可以使用该项目的其他属性来组成文件名。如果您想要路径中的测试类名称,如评论中所述,您可以执行以下操作:...&nbsp; &nbsp; path = 'results'&nbsp; &nbsp; if item.cls is not None:&nbsp; &nbsp; &nbsp; &nbsp; path = os.path.join(path, item.cls.__name__)&nbsp; &nbsp; logging_plugin.set_log_path(os.path.join(path, f'{item.name}_{timestamp}.log'))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python