我想向我的 pytest 固定装置传递一个参数,这样当固定装置 90% 相同时我不需要 10 个不同的固定装置。
我想要实现的最简单的例子:
@pytest.mark.parametrize('foo', [a=1])
def test_args(tmp_path, foo):
assert foo == 3
@pytest.fixture
def foo(tmp_path, a, b=2):
return a + b
Run Code Online (Sandbox Code Playgroud)
有没有办法将 a 和 b 标记为参数而不是其他固定装置?或者也许最好的方法是通过定义一个函数而不是一个固定装置来实现这一点?
我把tmp_path夹具放在那里,以确保参数化是明确的,并允许使用多个夹具。
值得指出的是
@pytest.fixture
def foo(request):
return request.param[0] + request.param[1]
@pytest.mark.parametrize('foo', [(1, 2)], indirect=True)
def test_args(tmp_path, foo):
assert foo == 3
Run Code Online (Sandbox Code Playgroud)
有效,(如文档中所定义),但不是我正在寻找的。我想知道与我给定的代码更相似的东西是否可以工作。我希望能够按名称传递参数、指定参数的默认值等。
我见过这个类似的 stackoverflow 问题,这似乎表明 pytest(?) 支持此功能,但它的答案似乎只是进一步混乱,而且它们似乎都不适合我提出的情况。
我能够通过夹具工厂实现我想要的目标
@pytest.fixture
def foo(tmp_path):
def _foo(a: int, b: int = 2):
return a + b
return _foo
def test_args(tmp_path, foo):
bar = foo(a=1)
assert bar == 3
Run Code Online (Sandbox Code Playgroud)