首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pytest -从另一个fixture调用fixture

Pytest -从另一个fixture调用fixture
EN

Stack Overflow用户
提问于 2019-06-01 07:09:08
回答 1查看 6.5K关注 0票数 7

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

file-1

代码语言:javascript
复制
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

代码语言:javascript
复制
@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中返回的object p,并在file-2 fixture_2 fixture中使用它。

EN

回答 1

Stack Overflow用户

发布于 2019-10-16 18:52:32

看起来您使用的pytest fixture是错误的(查看您的参数名称)。

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

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

代码语言:javascript
复制
###
# 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

和:

代码语言:javascript
复制
###
# 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
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56402600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档