gpt4 book ai didi

python - 定义一个 pytest fixture ,为测试函数提供多个参数

转载 作者:太空宇宙 更新时间:2023-11-03 11:42:09 26 4
gpt4 key购买 nike

使用 pytest,我可以像这样定义一个 fixture :

@pytest.fixture
def foo():
return "blah"

然后像这样在测试中使用它:

def test_blah(foo):
assert foo == "blah"

一切都很好。但我想要做的是定义一个“扩展”以向测试函数提供多个参数的 fixture 函数。像这样:

@pytest.multifixture("foo,bar")
def foobar():
return "blah", "whatever"

def test_stuff(foo, bar):
assert foo == "blah" and bar == "whatever"

我想一起定义两个对象 foobar (不是作为单独的固定装置),因为它们以某种方式相关。有时我可能还想定义一个依赖于另一个 fixture 的 fixture ,但是让第二个 fixture 包含第一个 fixture 的结果并将其与自己的添加一起返回:

@pytest.fixture
def foo():
return "blah"

@pytest.multifixture("foo,bar")
def foobar():
f = foo()
return f, some_info_related_to(f)

这个例子可能看起来很愚蠢,但在某些情况下 foo 就像一个 Request 对象,而 bar 对象需要链接到同一个请求对象。 (也就是说,我不能将 foobar 定义为独立的固定装置,因为我需要两者都从单个请求派生。)

本质上,我想做的是将 fixture 函数的名称与测试函数参数的名称分离,这样我就可以定义一个由特定 set“触发”的 fixture em> 测试函数签名中的参数名称,而不仅仅是名称与 fixture 函数相同的单个参数。

当然,我总是可以只返回一个元组作为 fixture 的结果,然后自己在测试函数中解压它。但是鉴于 pytest 提供了各种神奇的技巧来自动将名称与参数匹配,它似乎也可以神奇地处理这个问题并不是不可想象的。 pytest 可以实现这样的事情吗?

最佳答案

您现在可以使用 pytest-cases 执行此操作:

from pytest_cases import fixture

@fixture(unpack_into="foo,bar")
def foobar():
return "blah", "whatever"

def test_stuff(foo, bar):
assert foo == "blah" and bar == "whatever"

参见 documentation了解更多详情(顺便说一句,我是作者)

关于python - 定义一个 pytest fixture ,为测试函数提供多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47988664/

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