pytest 夹具的多个副本 [英] Multiple copies of a pytest fixture

查看:38
本文介绍了pytest 夹具的多个副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像下面这样的简单装置(使用 pytest-django,但它也适用于 pytest):

Let's say I have a simple fixture like the following (using pytest-django, but it applies to pytest as well):

@pytest.fixture
def my_thing(request, db):
    thing = MyModel.objects.create()
    request.addfinalizer(lambda: thing.delete())
    return thing

当我的测试需要 MyModel 的单个实例时,这很有效.但是如果我需要两个(或三个或四个)呢?我希望每个实例都是不同的,但以相同的方式设置.

This works great when my tests need a single instance of MyModel. But what about if I need two (or three or four)? I want each instance to be distinct, but to be set up in the same way.

我可以复制/粘贴代码并重命名夹具函数,但这似乎不雅.

I could copy/paste the code and rename the fixture function, but that seems inelegant.

同样,我也尝试过:

@pytest.fixture
def my_thing_1(my_thing):
    return my_thing

@pytest.fixture
def my_thing_2(my_thing):
    return my_thing

然而,这些似乎都返回相同的 MyModel 实例.

However, each of these appears to return the same instance of MyModel.

有没有办法使用 pytest 的内置功能来做我想做的事?或者,我可以将我的装置的设置/拆卸移到辅助函数中,这样我就不会重复太多代码.

Is there a way to do what I want using pytest's built-in functionality? Alternately, I could move the setup/teardown of my fixture out into helper functions so I'm not duplicating too much code.

还是我对整件事的看法是错误的?

Or am I going about this whole thing the wrong way?

推荐答案

我的方法可能是创建一个可以生成对象的夹具:

My approach would probably to create a fixture which can generate your objects:

@pytest.fixture
def thing(request, db):
    class ThingFactory(object):
        def get(self):
            thing = MyModel.objects.create()
            request.addfinalizer(thing.delete)
            return thing
    return ThingFactory()

def test_thing(thing):
    thing1 = thing.get()
    thing2 = thing.get()

显然你可以让 .get() 接受一个参数等.

Obviously you can make .get() take an argument etc.

(PS:还要注意终结器中不需要 lambda)

(PS: Also note there's no need for the lambda in the finalizer)

这篇关于pytest 夹具的多个副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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