如何在 Pytest 中从另一个灯具调用一个夹具



我有一个返回某种类型的对象的夹具,我在另一个文件中定义了另一个夹具,它基本上使用该对象来做其他事情。但是我无法从我的第一个装置中归还物体。

file-1

def fixture_1(s, **kwargs):
    def hook(s, **kwargs):
        p_b = s.get()
        p = p_b.build()
        yield p
    return hook

file-2 conftest.py

@pytest.fixture(scope='module')
def fixture_1(s, **kwargs):
    def hook(s, **kwargs):
        #Default implementation is no-op.
        pass
    return hook
@pytest.fixture(scope='module')
def fixture_2(s,b_p):
    some_p = fixture_1(s)
    current_status = s.start(some_p)
    print(current_status)
    yield current_status

我想基本上检索file-1 fixture_1中返回的对象p并在file-2 fixture_2装置中使用它。

看来你用错了pytest灯具(看你的参数名称(。

我建议你通过 https://docs.pytest.org/en/latest/fixture.html

对于您的问题,有两种解决方案:

###
# file_1
def not_really_a_fixture(s, **kwargs): # just some hook generator
    def hook(s, **kwargs):
        p_b = s.get()
        p = p_b.build()
        yield p
    return hook

###
# conftest.py
from file_1 import not_really_a_fixture
@pytest.fixture(scope='module')
def fixture_2(s,b_p): # s and b_p should be names of fixtures that need to run before this
    some_p = not_really_a_fixture(s)
    current_status = s.start(some_p)
    print(current_status)
    yield current_status

和:

###
# file_1
@pytest.fixture(scope='module')
def fixture_1(s): # s is name of another fixture
    # there is no point in having **kwargs as arg in pytest fixture
    def hook(s, **kwargs):
        #Default implementation is no-op.
        pass
    return hook
###
# conftest.py
from file_1 import fixture_1
@pytest.fixture(scope='module')
def fixture_2(s,b_p,fixture_1): # s and b_p should be names of fixtures that need to run before this
    # in fixture_1 is value returned by fixture_1, that means your hook func
    current_status = s.start(fixture_1)
    print(current_status)
    yield current_status

包含简单示例

Py.test 支持开箱即用地调用其他夹具

将夹具放在 conftest.py 或测试文件中:

conftest.py:

@pytest.fixture(scope="session")
def fixture_A():
    some_obj = create_obj()
    return some_obj  # or use yield some_obj in case you want to destruct
@pytest.fixture(scope="session")
def fixture_B(fixture_A):
   this_is_some_obj = fixture_A
   # do something
   another = {}
   return this_is_some_obj, another

test_example.py:

@pytest.fixture(scope="session")
def fixture_C(fixture_B):
   return fixtureB
def test_finally_the_test(fixture_C):
    some_obj, another = fixture_C
 

值得一提的是,上述夹具将被调用一次(即使多个测试使用这些夹具( - 这是由于每个夹具的"会话"范围就好像这些灯具是单例(如果与OOP相比(

另一个注意pytest知道运行夹具的顺序(它检查依赖关系 - 这里没有什么特别的事情要做(

例如,test()可以调用fixture_2()可以调用fixture_1(),如下所示:

import pytest
@pytest.fixture
def fixture_1():
    return "fixture_1"
@pytest.fixture
def fixture_2(fixture_1):
    return fixture_1
def test(fixture_2):
    print(fixture_2)
    assert True

输出:

$ pytest -q -rP
.                                [100%]
=============== PASSES ================ 
________________ test _________________ 
-------- Captured stdout call --------- 
fixture_1
1 passed in 0.10s

相关内容

  • 没有找到相关文章

最新更新