将fixture传递给pytes中的测试类

2024-05-15 04:36:22 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑下面的伪代码来演示我的问题:

import pytest


@pytest.fixture
def param1():
    # return smth
    yield "wilma"


@pytest.fixture
def param2():
    # return smth
    yield "fred"


@pytest.fixture
def bar(param1, param2):
    #do smth
    return [Bar(param1, param2), Bar(param1, param2)]


@pytest.fixture
def first_bar(bar):
    return bar[0]


class Test_first_bar:

    # FIXME: how do I do that?
    #def setup_smth???(self, first_bar):
    #    self.bar = first_bar


    def test_first_bar_has_wilma(self):
        # some meaningful check number 1
        assert self.bar.wilma == "wilma"


    def test_first_bar_some_other_check(self):
        # some meaningful check number 2
        assert self.bar.fred == "fred"

基本上,我想将first_barfixture传递给我的Test_first_bar类,以便在其所有测试方法中重用该对象。我该如何着手处理这种情况?在

Python3,如果这很重要的话。在


Tags: selfreturnpytestdefcheckbarsomefred
1条回答
网友
1楼 · 发布于 2024-05-15 04:36:22

在这里,您可以将fixture定义为autouse。你的类的所有测试都会自动调用它。在这里,我不明白什么是[Bar(param1, param2), Bar(param1, param2)]。好吧,这不是重点,如果其余代码运行良好,那么您可以尝试下面的解决方案。我已经用静态变量替换了代码,以验证它是否正常工作,并且在我的工作环境中运行良好。在

import pytest

@pytest.fixture
def param1():
    # return smth
    yield "wilma"


@pytest.fixture
def param2():
    # return smth
    yield "fred"


@pytest.fixture
def bar(param1, param2):
    # do smth
    return [Bar(param1, param2), Bar(param1, param2)]


@pytest.fixture(scope='function', autouse=True)
def first_bar(bar, request):
    request.instance.bar = bar[0]

class Test_first_bar:

    def test_first_bar_has_wilma(self,request):
        print request.instance.bar

    def test_first_bar_some_other_check(self,request):
        print request.instance.bar

如果不想将fixture设为autouse,那么可以在测试之前调用它。就像

^{pr2}$

相关问题 更多 >

    热门问题