定义一个pytest固定装置,为测试函数提供多个参数 [英] Define a pytest fixture providing multiple arguments to test function

查看:100
本文介绍了定义一个pytest固定装置,为测试函数提供多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用pytest,我可以这样定义一个固定装置:

With pytest, I can define a fixture like so:

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

并在这样的测试中使用它:

And use it in a test like so:

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

一切都很好.但是我想做的是定义一个单一的夹具函数,该函数扩展"为测试函数提供多个参数.像这样:

That's all very well. But what I want to do is define a single fixture function that "expands" to provide multiple arguments to a test function. Something like this:

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

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

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

I want to define the two objects foo and bar together (not as separate fixtures) because they are related in some fashion. I may sometimes also want to define a fixture that depends on another fixture, but have the second fixture incorporate the result of the first and return it along with its own addition:

@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定义为独立的固定装置,因为我需要将两者都从单个请求中派生.)

This example may seem silly, but in some cases foo is something like a Request object, and the bar object needs to be linked to that same request object. (That is, I can't define foo and bar as independent fixtures because I need both to be derived from a single request.)

本质上,我想做的是将夹具函数的名称与test-function参数的名称脱钩,以便我可以定义由特定的 set触发"的夹具.测试函数签名中的参数名称,而不是单个名称与Fixture函数名称相同的参数.

In essence, what I want to do is decouple the name of the fixture function from the name of the test-function argument, so that I can define a fixture which is "triggered" by a particular set of argument names in a test function signature, not just a single argument whose name is the same as that of the fixture function.

当然,我总是可以将夹具的结果返回一个元组,然后自己在测试函数中解压缩它.但是,鉴于pytest提供了各种神奇的技巧,可以自动将名称与参数匹配,因此似乎也可以神奇地处理它并不是不可想象的. pytest有可能发生这种情况吗?

Of course, I can always just return a tuple as the result of the fixture and then unpack it myself inside the test function. But given that pytest provides various magical tricks for automatically matching names to arguments, it seems like it's not unthinkable that it could magically handle this as well. Is such a thing possible with pytest?

推荐答案

您现在可以使用有关更多详细信息,请参见文档(我是作者方式)

See the documentation for more details (I'm the author by the way)

这篇关于定义一个pytest固定装置,为测试函数提供多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆