有没有办法从简单(非测试)函数直接引用 pytest 夹具?

Ken*_*enB 7 python fixtures pytest

有没有办法从一个简单的函数中引用(并调用)一个 pytest 固定装置,它本身既不是 test_* 函数也不是固定装置?

可以使用夹具的已知示例:

1)

def test_mytest( some_cool_pytest_fixture_name, the, rest of, my, args):
    blah
    blah
    some_cool_pytest_fixture_name(args)
    blah

2)
@pytest.fixture()
def my_new_fixture( some_cool_pytest_fixture_name, the, rest of, my, args):
    blah
    blah
    some_cool_pytest_fixture_name(args)
    blah
Run Code Online (Sandbox Code Playgroud)

我希望能够做到这一点:3)

def my_simple_function( the, rest of, my, args):
    blah
    blah
    outright.reference.this.pytest.fixture.some_cool_pytest_fixture_name(args)
    blah
Run Code Online (Sandbox Code Playgroud)

笔记:

from pytest import record_xml_property as property_handler
 ** E ImportError: cannot import name record_xml_property** 
Run Code Online (Sandbox Code Playgroud)

^^^ 这是在具有record_xml_property的系统上

我的愿望是能够做这样的事情:

try: 
     from pytest import record_xml_property as property_handler 
 except: 
     @pytest.fixture() 
     def property_handler(mykey, myval): 
         print('{0}={1}'.format(mykey,myval)
Run Code Online (Sandbox Code Playgroud)

^^^ 如果以上可以成功,那么我总是可以依靠property_handler作为固定装置在我身边。

Nat*_*aul 1

当您使用 pytest 的内置夹具处理时,您不必担心如何管理它的可用性和内存。

因此,当您不使用 pytest 时,您可以将其作为普通函数导入。

from path.to.cool.pytest.fixture import some_cool_pytest_fixture_name

def my_simple_function(the, rest of, my, args):
    some_cool_pytest_fixture_name(args)
Run Code Online (Sandbox Code Playgroud)


编辑

为了回应 Ken 的注释,我花了一些时间尝试访问 pytest 中定义的可用装置列表。我想出了两种访问列表的方法,但还没有将其推得足够远,无法以 python 列表格式获取列表,只有控制台输出。

从命令行,您可以运行pytest --fixtures以列出所有可用的灯具。要从 python 脚本执行相同的操作,您可以运行以下代码

import pytest
from _pytest import python
from _pytest import config
configs = config._prepareconfig()
python.showfixtures(configs)
Run Code Online (Sandbox Code Playgroud)

我认为如果您深入研究 pytest Session 对象并查看其_fixturemanager属性,您可以访问该列表,但我无法找到像showfixtures上面的函数那样创建这些的方法。

  • 只是给找到这个答案的人一个注释,我相信直接调用固定装置现在已经被废弃:https://docs.pytest.org/en/latest/deprecations.html#calling-fixtures-directly(我正在寻找一个相同用例的解决方案,尚未找到) (10认同)