python - 使用 fixture 的 Pytest 参数化测试

标签 python unit-testing testing pytest

我有一个带有 pytest.fixture 的测试套件,它依赖于其他 fixture,如下所示:

@pytest.fixture
def params():
    return {'foo': 'bar', 'baz': 1}

@pytest.fixture
def config():
    return ['foo', 'bar', 'baz']

@pytest.client
def client(params, config):
    return MockClient(params, config)

对于正常测试,我只是传入 client 并且它工作正常:

def test_foo(client):
    assert client.method_with_args(arg1, arg2)

但是对于参数化测试,使用那个 fixture 真的很尴尬。您必须直接调用所有 fixture 方法,这在某种程度上违背了目的。 (我应该注意到 paramsconfig 固定装置在别处使用,所以我不想将它们折叠到 client 中)。

@pytest.mark.parametrize('thing,expected', [
    (client(params(), config()).method_with_args(arg1, arg2), 100),
    (client(params(), config()).method_with_args(arg2, arg4), 200),
])
def test_parameters(thing, expected):
    assert thing == expected

有什么办法可以使它更干净吗?我不确定这种困惑的代码是否比重复的类似测试更好。

最佳答案

如何参数化参数而不是方法调用的结果?

例如

@pytest.mark.parametrize('args,expected', [
    ((arg1, arg2), 100),
    ((arg2, arg4), 200),
])
def test_parameters(client, args, expected):
    assert client.method_with_args(*args) == expected

关于python - 使用 fixture 的 Pytest 参数化测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46240454/

相关文章:

python - 如何可靠地检测条码的 4 个角?

AngularJS + Karma + Jasmine + Karma-Coverage : Empty coverage report

database - Mock 框架可以为我做这个吗?

默认循环计数器的 Pythonic 方式

python - 如何在 Django 中翻译表单的标签和验证消息

PHPUnit 4.8模拟mysql数据库接口(interface)

java - 类的每个方法的 JUnitParams

javascript 测试函数总是返回 false

测试损坏的 IP

python - 为什么 Homebrew 不在 OS X 10.8 上创建 python 绑定(bind)文件?