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

var*_*nie 8 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"
Run Code Online (Sandbox Code Playgroud)

基本上我想将first_bar夹具传递给我的Test_first_bar类,以便在其所有测试方法中重用该对象。遇到这种情况我该怎么办?

Python 3,如果这很重要。

Cha*_*rat 7

在这里,您可以将您的装置定义为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
Run Code Online (Sandbox Code Playgroud)

如果您不想将夹具制作为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
Run Code Online (Sandbox Code Playgroud)

  • 我收到错误 > E TypeError: test_first_bar_has_wilma() 缺少 1 个必需的位置参数:'request' (9认同)