4

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.

Glueon
  • 3,727
  • 4
  • 23
  • 32
  • Could you tell if test are way too different? Or the only difference is between Foo() instances? Depending on that few approaches are possible – Furious Duck Oct 09 '15 at 14:50
  • @AlexanderPetrovich well it depends. Currently json file contains a series of sample responses from an HTTP server. So when I test any function of `Foo` internally it performs some http request. Responses are taken from this json. – Glueon Oct 09 '15 at 20:29

1 Answers1

7

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) 
sax
  • 3,708
  • 19
  • 22