我有一个带有 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 方法,这在某种程度上违背了目的。 (我应该注意到 params
和 config
固定装置在别处使用,所以我不想将它们折叠到 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/