【问题标题】:Pytest parametrized test that uses fixture使用夹具的 Pytest 参数化测试
【发布时间】:2018-02-24 16:45:23
【问题描述】:

我有一个带有 pytest.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)

但对于参数化测试,使用该夹具确实很尴尬。您必须直接调用所有夹具方法,这在某种程度上违背了目的。 (我应该注意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

有什么方法可以让这个更干净吗?我不确定这个凌乱的代码是否比重复的类似测试更好。

【问题讨论】:

    标签: python unit-testing testing pytest


    【解决方案1】:

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

    例如

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 2015-11-23
      相关资源
      最近更新 更多