使用夹具

时间:2017-09-15 13:12:29

标签: python unit-testing testing pytest

我有一个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

有没有办法让这个更干净?我不确定这个混乱的代码是否比重复的类似测试更好。

1 个答案:

答案 0 :(得分:1)

参数化参数而不是方法调用的结果怎么样?

e.g。

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