调用模拟时设置Python属性?

时间:2018-08-14 00:35:39

标签: python-3.x mocking

如何模拟设置属性的函数?诀窍在于,所讨论的函数不是@property实例,它要复杂得多。这是一个示例:

class ToTest:
    def __init__(self):
        self.__MyProp:ComplexObject = None
        return

    def funcToTest(self):
        oldValue = copy.deepcopy(self.__MyProp)

        calculateNewValue()

        if oldValue == self.__MyProp
            return True
        else:
            return False

    def calculateNewValue():
        #very complex calculation
        #set self.__MyProp
        return

Class ToTest_Test(unittest.TestCase):

    def test_funcToTest(self):

        ExpectedComplexObject = ComplexObject()
        with patch.object(ToTest, "calculateNewValue") as mock:
            #What do I do here?
            #Thought1 - only sets return value:
            mock.return_result = ExpectedComplexObject

            #Thought2 - calls the side effect immediately, prematurely setting the property.
            mock.side_effect = settr(toTest, "_ToTest__MyProp", ExpectedComplexObject)

            toTest = ToTest()
            self.assertTrue(toTest.funcToTest())

0 个答案:

没有答案