将夹具传递给pytest中的测试类

时间:2017-07-03 18:10:29

标签: python pytest

考虑以下伪代码来证明我的问题:

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_bar fixture传递给我的Test_first_bar类,以便在其所有测试方法中重用该对象。我该如何处理这种情况?

Python 3,如果重要的话。

1 个答案:

答案 0 :(得分:2)

在这里,您可以将灯具定义为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

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

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')
def first_bar(bar, request):
    request.instance.bar = bar[0]

class Test_first_bar:

    @pytest.mark.usefixtures("first_bar")
    def test_first_bar_has_wilma(self,request):
        print request.instance.bar

    @pytest.mark.usefixtures("first_bar")
    def test_first_bar_some_other_check(self,request):
        print request.instance.bar