据我从有关 pytest 夹具参数化的文档中了解到 - 它使用给定的参数创建夹具的副本,从而调用每个需要具有不同副本的夹具的测试。
我的需求有点不同。假设有一个夹具:
@pytest.fixture
def sample_foo():
return Foo(file_path='file/path/test.json')
def test1(sample_foo):
pass
def test2(sample_foo):
pass
Run Code Online (Sandbox Code Playgroud)
问题是 testtest1并test2需要相同的类实例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')
Run Code Online (Sandbox Code Playgroud)
这看起来有点像代码重复。我可以为每个文件创建一个单独的装置,但这看起来更糟。看起来每个测试都需要它自己的唯一文件,所以也许可以通过查看请求夹具的测试函数的名称来找出文件的名称来解决这个问题。但这并不能保证。
你需要夹具参数
Fixture 函数可以被参数化,在这种情况下,它们将被多次调用,每次执行一组相关测试,即依赖于该 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)
Run Code Online (Sandbox Code Playgroud)
也许你可以直接
def test(file_path):
sample_foo = Foo(file_path)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1037 次 |
| 最近记录: |