【发布时间】:2020-08-06 15:15:18
【问题描述】:
我正在尝试为调用对象的类方法的函数编写测试——该类方法继续返回该类的新实例。
在 stackoverflow 和其他地方都有很多修补类属性的示例,但我很难理解如何修补属性/值以便我可以测试我的功能。我已经提到了this的答案。
本质上,我正在尝试修补 Foo 实例的属性 xxxx(在 myFn 内),以便我可以测试/断言调用 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()
非常感谢任何人的帮助!
【问题讨论】:
标签: python unit-testing mocking patch