Python属性和UnitTestCase

Python属性和UnitTestCase,python,unit-testing,Python,Unit Testing,今天我写了一个测试并输入了一个测试方法。我的测试失败了,但我不明白为什么。这是Python属性的特殊行为还是其他什么 from unittest import TestCase class FailObject(object): def __init__(self): super(FailObject, self).__init__() self.__action = None @property def action(self):

今天我写了一个测试并输入了一个测试方法。我的测试失败了,但我不明白为什么。这是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中通过实例创建修复了打字错误,那么所有测试都会按预期工作。但这个例子让我回到问题上来:使用属性安全吗?如果有一天我会再次打字怎么办?

好的,这是Python的默认行为。在testSetFailObjectAction中,我们添加了隐藏属性的新静态类变量。没有办法保护自己不犯这样的错误

唯一的建议是使用特征库。

您可以使用和从这类工作:

@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
,还可以检查该属性是否已被使用。

您是否应该在
中设置
currentFailObject.action=action
?当前,没有任何内容会使您的(示例)代码更改为
currentFailObject
action
属性
'act'