【发布时间】: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