今天我写了测试,并在其中一种测试方法中打错了字。我的测试失败了,但我不明白为什么。是 Python 属性的特殊行为还是其他?
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)
当我用 Nose 测试运行这个测试用例时:
.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)
如果我通过在 testSetFailObjectAction 中创建实例来修复拼写错误,所有测试都会按预期进行。但是这个例子让我重新思考:使用属性安全吗?如果有一天我再次打字怎么办?
请您参考如下方法:
您可以使用 patch和 PropertyMock来自 mock对于这种工作:
@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 属性,您还可以检查该属性是否已被使用。
