2017-07-03 104 views
1

考虑下面的伪代码展示了我的问题:通夹具,测试类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夹具传递给我的Test_first_bar类,以重新使用该对象在其所有的测试方法。我应该如何处理这种情况?

Python 3,如果有问题。

回答

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 
+0

嘿!太好了,谢谢你的时间。 – varnie