如何重写在pytest 4中调用原始的pytest固定装置 [英] How to override a pytest fixture calling the original in pytest 4

查看:210
本文介绍了如何重写在pytest 4中调用原始的pytest固定装置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在定义一个pytest固定装置,以覆盖 django_db_setup固定装置.

I am defining a pytest fixture that to overrides the django_db_setup fixture.

为安全起见,我所做的更改还设置了其他拆卸项,因为使用此治具的集成测试可能会产生进程,有时还需要进行清理以防止所有事物崩溃.

The change I have sets up additional teardown for safety, as there are integration tests that use this fixture which may spawn processes and cleanup is sometimes required to keep all things from breaking.

这似乎是合理的,并且在pytest文档中也建议使用.但是,我不想复制粘贴与django_db_setup完全相同的逻辑,因为我对已经存在的内容感到满意.但是,将其作为功能运行会引发弃用警告:

This seems reasonable, and is also suggested in pytest docs. However, I don't want to copy paste the same exact logic of django_db_setup since I'm happy with what is already there. Running it as a function, however, raises a deprecation warning:

/usr/local/lib/python3.6/dist-packages/_pytest/fixtures.py:799:

 RemovedInPytest4Warning: Fixture "django_db_setup" called directly.
 Fixtures are not meant to be called directly, are created automatically
 when test functions request them as parameters. See
 https://docs.pytest.org/en/latest/fixture.html for more information.

在pytest 4中处理这种情况的推荐方法是什么?是鼓励我们从要覆盖的灯具中复制粘贴代码,还是有另一种继承"灯具的方法,并在调用之前或之后注入自定义行为?

What would be the recommended way to deal with this situation in pytest 4? Are we encouraged to copy-paste code from fixtures we want to override, or is there another way to "inherit" a fixture, and inject e.g custom behavior before as well as after it is called?

推荐答案

要在调用初始夹具之前注入自定义行为,您可以创建具有此行为的单独夹具,并在夹具参数列表中的初始夹具之前使用它来替代之前覆盖的夹具.定义:

To inject custom behavior before the initial fixture is called you can create separate fixture with this behavior and use it before the initial fixture in parameter list of fixture that overrides previously defined:

@pytest.fixture(scope='session')
def inject_before():
    print('inject_before')

@pytest.fixture(scope='session')
def django_db_setup(inject_before, django_db_setup):
    print('inject_after')

这篇关于如何重写在pytest 4中调用原始的pytest固定装置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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