我正在尝试为一个调用对象的类方法的函数编写测试——这个类方法继续返回该类的一个新实例。
在 stackoverflow 和其他地方有很多修补类属性的示例,但我很难理解如何修补属性/值以便我可以测试我的函数。我提到了 this回答。
本质上,我正在尝试修补 Foo 实例(在 myFn 中)的属性 xxxx
,以便我可以测试/断言其对 some_other_function()的调用的后续值
下面的代码是独立的“可运行”问题:我收到一个 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)
关于python - 从类方法中模拟/修补计算属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63286643/