【问题标题】:How to pass variables from a decorator with arguments to a pytest unit test?如何将带有参数的装饰器中的变量传递给 pytest 单元测试?
【发布时间】:2022-01-27 09:42:13
【问题描述】:

假设我正在使用 pytest 进行一些需要配置的单元测试。假设我还想添加一些自定义配置,具体取决于我要创建的单元测试。

所以,我目前有以下内容:

import pytest

def load_configuration(custom_config=None):
    """Loads some default configuration, and if necessary injects some custom configuration"""
    config = some_complicated_stuff()
    if custom_config:
        config.update(custom_config)
    return config


@pytest.fixture(scope="function")
def foo():
    return 69


def test_bar_long_way(foo):
    config = load_configuration(custom_config={"bar": 42})
    assert foo == 69
    assert config[bar] == 42
    # do stuff with foo and config

有没有办法使用装饰器(我们称之为load_config)将该自定义配置注入到单元测试中,而不必在单元测试本身中创建配置?在这个简化的示例中,它很短,但实际上这需要更多的空间。我正在寻找一种让它看起来像这样的方法:

@load_config({"bar": 42})
def test_bar_with_decorator(config, foo):
    assert foo == 69
    assert config["bar"] == 42
    # do stuff with foo and config

我不知道如何创建这个 load_config 装饰器。任何帮助将不胜感激:)。

【问题讨论】:

  • 名称bar 在此处未定义。你指的是字符串"bar" 吗?
  • 是的,当然,wim!谢谢。

标签: python unit-testing pytest decorator


【解决方案1】:
import pytest


def some_complicated_stuff():
    return {"abc": 123}


def load_configuration(custom_config=None):
    """Loads some default configuration, and if necessary injects some custom configuration"""
    config = some_complicated_stuff()
    if custom_config:
        config.update(custom_config)
    return config


@pytest.mark.parametrize('config', [load_configuration({"bar": 42})])
def test_bar_long_way(config):
    assert config["bar"] == 42
    # do stuff with foo and config

parametrize 通常用于运行相同的测试函数,但其​​参数的值不同,但我们只能使用它运行一次。

如果你喜欢更好的装饰器:

def custom_config(config_val):
    return pytest.mark.parametrize('config', [load_configuration(config_val)])


@custom_config({"bar": 42})
def test_bar_long_way(config):
    assert config["bar"] == 42

【讨论】:

    猜你喜欢
    • 2010-12-30
    • 1970-01-01
    • 2018-09-11
    • 2018-07-24
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多