简体   繁体   English

pypytest参数

[英]Parametrize pytest fixture

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. 据我从有关pytest固定装置参数化的文档中了解到的-它使用给定的参数创建固定装置的副本,因此调用需要此固定装置具有不同副本的每个测试。

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 问题是测试test1test2需要类Foo的相同实例,但文件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. 但这并不能保证。

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, ie 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM