Python 模拟/修补classmethod中计算属性的值

Python 模拟/修补classmethod中计算属性的值,python,unit-testing,mocking,patch,Python,Unit Testing,Mocking,Patch,我试图为一个调用对象的classmethod的函数编写一个测试——这个classmethod继续返回该类的一个新实例 在stackoverflow和其他地方都有很多修补类属性的例子,但是我很难理解如何修补属性/值,以便测试我的函数。我已经提到了答案 本质上,我正在尝试修补Foo实例的属性xxxx(在myFn中),这样我就可以测试/断言它调用some\u other\u函数()的后续值。 下面的代码是问题的“可运行”代码:我得到了一个AttributeError:Foo没有属性“xxxx” imp

我试图为一个调用对象的classmethod的函数编写一个测试——这个classmethod继续返回该类的一个新实例

在stackoverflow和其他地方都有很多修补类属性的例子,但是我很难理解如何修补属性/值,以便测试我的函数。我已经提到了答案

本质上,我正在尝试修补Foo实例的属性
xxxx
(在myFn中),这样我就可以测试/断言它调用
some\u other\u函数()的后续值。

下面的代码是问题的“可运行”代码:我得到了一个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()
非常感谢任何人的帮助

如果属性不存在,则应使用将强制创建该属性的参数:

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

非常感谢。这是我错过的创造