问题
As far as I understood from the documentation about pytest fixture parameterization - it creates copies of the fixture with the given params and thus calls each test which requires this fixture with this different copies.
My needs are a little bit different. Suppose there is a fixture:
@pytest.fixture
def sample_foo():
return Foo(file_path='file/path/test.json')
def test1(sample_foo):
pass
def test2(sample_foo):
pass
The problem is that test test1
and test2
require the same instance of class Foo
but with different values of file_path
So at the moment I do:
def build_foo(path):
return Foo(file_path=path)
def test1():
sample_foo = build_foo('file/path/some.json')
def test2():
sample_foo = build_foo('file/path/another.json')
This looks like a little bit of code duplication. I could create a separate fixtures for each file but that looks even worse. It looks that each test will require it's own unique file, so maybe this can be solved by figuring out the name of the file by looking at the name of the test function requesting the fixture. But that is not guaranteed.
回答1:
you need fixture parameters
Fixture functions can be parametrized in which case they will be called multiple times, each time executing the set of dependent tests, i. e. the tests that depend on this fixture.
def build_foo(path):
return Foo(file_path=path)
@pytest.fixture(params=["file/path/some.json", "file/path/another.json"])
def file_path(request):
return request.param
def test(file_path):
sample_foo = build_foo(file_path)
maybe you can directly
def test(file_path):
sample_foo = Foo(file_path)
来源:https://stackoverflow.com/questions/32999470/parametrize-pytest-fixture