gpt4 book ai didi

python - 参数化pytest fixture

转载 作者:行者123 更新时间:2023-11-28 22:41:04 24 4
gpt4 key购买 nike

据我从有关 pytest fixture 参数化的文档中了解到 - 它使用给定的参数创建 fixture 的副本,从而调用每个需要此 fixture 的不同副本的测试。

我的需求有点不同。假设有一个 fixture :

@pytest.fixture
def sample_foo():
return Foo(file_path='file/path/test.json')

def test1(sample_foo):
pass

def test2(sample_foo):
pass

问题是测试test1test2需要类的相同实例 Foo但具有不同的值 file_path

所以现在我这样做:

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')

这看起来有点重复代码。我可以为每个文件创建一个单独的固定装置,但这看起来更糟。看起来每个测试都需要它自己的唯一文件,所以也许这可以通过查看请求 fixture 的测试函数的名称来找出文件的名称来解决。但这并不能保证。

最佳答案

你需要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)

也许你可以直接

def test(file_path):    
sample_foo = Foo(file_path)

关于python - 参数化pytest fixture ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32999470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com