2017-07-03 103 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