2015-03-31 57 views
1

今天我寫了一個測試方法的測試和錯字。我的測試失敗了,但我不明白爲什麼。是Python特性還是其他特殊行爲?Python屬性和單元測試TestCase

from unittest import TestCase 


class FailObject(object): 
    def __init__(self): 
     super(FailObject, self).__init__() 
     self.__action = None 

    @property 
    def action(self): 
     return self.__action 

    @action.setter 
    def action(self, value): 
     self.__action = value 


def do_some_work(fcells, fvalues, action, value): 
    currentFailObject = FailObject() 
    rects = [currentFailObject] 
    return rects 


class TestModiAction(TestCase): 
    def testSetFailObjectAction(self): 
     rect = FailObject # IMPORTANT PART 
     rect.action = "SOME_ACTION" # No fail! 
     self.assertEquals("SOME_ACTION", rect.action) 

    def testSimple(self): 
     fcells = [] 
     fvalues = [] 
     rects = do_some_work(fcells, fvalues, 'act', 0.56) 

     rect = rects[0] 
     self.assertEquals('act', rect.action) 

當我運行這個測試用例用鼻子測試:如果我修正了實例創建錯字在testSetFailObjectAction所有測試工作,如預期

.F 
====================================================================== 
FAIL: testSimple (test.ufsim.office.core.ui.cubeeditor.TestProperty.TestModiAction) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "TestProperty.py", line 36, in testSimple 
    self.assertEquals('act', rect.action) 
AssertionError: 'act' != 'SOME_ACTION' 

---------------------------------------------------------------------- 
Ran 2 tests in 0.022s 

FAILED (failures=1) 

。但是這個例子讓我回到了問題:使用屬性是否安全?如果我有一天會再次錯字怎麼辦?

+0

你應該在'do_some_work'中設置'currentFailObject.action = action'嗎?目前沒有什麼東西能讓你的(樣本)代碼把'currentFailObject'的'action'屬性改爲''act'' – 2015-03-31 15:30:21

回答

0

好的,這是Python的默認行爲。在testSetFailObjectAction我們添加新的靜態類變量,隱藏我們的屬性。沒有辦法保護自己免受像這樣的錯誤。

唯一的建議是使用特質庫。

1

您可以使用從mockpatchPropertyMock到這樣的工作:

@patch(__name__."FailObject.action", new_callable=PropertyMock, return_value="SOME_ACTION") 
def testSetFailObjectAction(self, mock_action): 
    self.assertEquals("SOME_ACTION", FailObject().action) 
    self.assertTrue(mock_action.called) 
    #This fail 
    self.assertEquals("SOME_ACTION", FailObject.action) 

通過patch更換物業action只是爲了測試背景下,您還可以檢查屬性已被使用。