将固定装置传递给 pytest 中的测试类

2024-05-09

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

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我的固定装置Test_first_bar类以便在其所有测试方法中重用该对象。遇到这样的情况我应该如何处理呢?

Python 3,如果这很重要的话。


在这里,您可以将您的装置定义为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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将固定装置传递给 pytest 中的测试类 的相关文章

随机推荐