Pytest-从另一个灯具调用灯具

时间:2019-05-31 23:09:08

标签: python pytest fixtures

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

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

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

1 个答案:

答案 0 :(得分:1)

您似乎在使用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