尝试在运行时更新 pytest.ini 文件,但未为同一测试执行实例选取设置

问题描述 投票:0回答:1

`我正在尝试在运行时更新 pytest.ini 文件(希望日志文件夹选取当前日期和时间作为文件名),但在同一测试执行中不会选取设置。 例如,如果我使用下面的代码更新 pytest.ini 文件,它只会更新 pytest.ini 文件,但 pytest 配置不会应用于同一运行。我必须重新运行测试才能获取配置。到那时时间就改变了。

def settings_configure():
config = ConfigParser(interpolation=ExtendedInterpolation())
current_time = datetime.datetime.now()
config['pytest'] = {
    'log_cli': 'true',
    'log_level': 'DEBUG',
    'log_format': '%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(funcName)s:%(lineno)s)',
    'log_date_format': '%Y-%m-%d %H:%M:%S',
    'log_file': "./logs/" + current_time.strftime('%Y_%m_%d') + ".txt",
    'log_file_date_format': '%Y-%m-%d %H:%M:%S',
    'log_file_mode': 'a',
    'addopts': '-rA',
    'logging_on': 'TRUE'
}
with open('pytest.ini', 'w') as configfile:
    config.write(configfile)
config.read('pytest.ini')

我在 pytest_configure 方法下调用上面的函数,如下所示。

def pytest_configure(配置): 返回settings_configure()

如何在运行时更新 pytest.ini 并在同一实例中使用这些配置?

尝试将其用作固定装置和挂钩。没有一个起作用。请帮忙。`

pytest config settings ini
1个回答
0
投票

您可以在执行期间编辑

pytest.ini
,并期望 pytest 接受更改。该文件在测试开始时读取一次,然后与环境变量或命令行选项中的其他设置混合在一起。

但是,有动态配置

logging-plugin
的实验支持。

conftest.py

import pytest

# without trylast=True, this function is run before the logging-pluggin is loaded,
# and so fails to work as expected 
@pytest.hookimpl(trylast=True)
def pytest_configure(config):
    logging_plugin = config.pluginmanager.get_plugin('logging-plugin')
    logging_plugin.set_log_path('custom.log')

测试文件

import logging

log = logging.getLogger('my-test')

def test_foo():
    log.info('testing')

运行方式:

pytest --log-file-level=DEBUG

或者,将

log_file_level
选项添加到您的
pytest.ini
文件中。

没有 pytest 支持

只需添加一个包装脚本来运行添加适当标志的测试。

运行测试.sh

#!/bin/bash
pytest --log-file="logs/$(date +%Y_%m_%d).txt" --log-file-level=DEBUG "$@"
© www.soinside.com 2019 - 2024. All rights reserved.