繁体   English   中英

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

[英]Is there way to directly reference to a pytest fixture from a simple (non test) function?

有没有办法从一个简单的函数引用(和调用)pytest fixture,它本身不是test_ *函数或者也不是fixture?

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

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

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

def my_simple_function( the, rest of, my, args):
    blah
    blah
    outright.reference.this.pytest.fixture.some_cool_pytest_fixture_name(args)
    blah

注意:

from pytest import record_xml_property as property_handler
 ** E ImportError: cannot import name record_xml_property** 

^^^这个在具有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)

^^^如果以上可以成功,那么我总是可以依赖property_handler作为一个夹具。

当您使用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)


编辑

为了回应Ken的说明,我花了一些时间试图访问pytest中定义的可用夹具列表。 我已经提出了两种方法来访问列表,但是还没有把它推得足够远以获得python列表格式的列表,只有控制台输出。

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

 import pytest from _pytest import python from _pytest import config configs = config._prepareconfig() python.showfixtures(configs) 

如果你深入了解pytest Session对象并查看它的_fixturemanager属性,我认为你可以访问列表,但我无法找到一种方法来创建这些像上面的函数showfixtures一样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM