mocking/patching 来自类方法的计算属性的值

mocking/patching the value of a computed attribute from a classmethod

我正在尝试为调用对象的 class 方法的函数编写测试 -- 这个 class 方法继续 return [=29] 的新实例=].

在 Whosebug 和其他地方有很多修补 class 属性的示例,但我很难理解如何修补 attribute/value 以便我可以测试我的功能。我已经提到 this 答案。

本质上,我正在尝试修补 Foo 实例(在 myFn 中)的属性 xxxx,以便我可以 test/assert 从其对 some_other_function()[= 的调用中获得后续值15=]

下面的代码是独立的 'runnable' 问题:我收到一个 AttributeError: Foo 没有属性 'xxxx'

import time
import unittest
from unittest.mock import patch, PropertyMock

class Foo(object):
    def __init__(self, xxxx):
        """long running task"""
        time.sleep(5)
        self.xxxx = xxxx

    @classmethod
    def get(cls):
        """also a long running task"""
        time.sleep(5)
        xxxx = 555
        return cls(xxxx)

def myFn():
    v = Foo.get().xxxx
    # the patched `xxxx` should be 666 at this point
    return some_other_function(v)

class Test(unittest.TestCase):

    @patch('__main__.Foo', autospec=True)
    def test_myFn(self, mock_Foo):
        with patch('__main__.Foo.xxxx', new_callable=PropertyMock, return_value=666):
            x = myFn()
            self.assertEqual(x, 666)

if __name__ == '__main__':
    unittest.main()

非常感谢大家的帮助!

您应该使用 create 参数,该参数将强制创建不存在的属性:

def test_myFn(self):
    with patch('__main__.xxxx', new_callable=PropertyMock, create=True, return_value=666):
        x = myFn()
        self.assertEqual(666,x)