gpt4 book ai didi

Python 属性和单元测试 TestCase

转载 作者:太空宇宙 更新时间:2023-11-04 05:52:39 25 4
gpt4 key购买 nike

今天我写了测试,并在其中一种测试方法中打错了字。我的测试失败了,但我不明白为什么。是 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 中创建实例来修复拼写错误,所有测试都会按预期进行。但是这个例子让我重新思考:使用属性安全吗?如果有一天我再次打字怎么办?

最佳答案

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

关于Python 属性和单元测试 TestCase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29364173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com