今天我寫了一個測試方法的測試和錯字。我的測試失敗了,但我不明白爲什麼。是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)
。但是這個例子讓我回到了問題:使用屬性是否安全?如果我有一天會再次錯字怎麼辦?
你應該在'do_some_work'中設置'currentFailObject.action = action'嗎?目前沒有什麼東西能讓你的(樣本)代碼把'currentFailObject'的'action'屬性改爲''act'' – 2015-03-31 15:30:21