我试图测试从我的一个打包对象中的函数调用回调。但是,mock.patch.object并不允许我从当前的测试用例中模拟一个函数。假设我有以下(简化)代码和测试:
import unittest
from six.moves import cStringIO
from mock import patch
class myclass(object):
def __init__(self, callback):
self.callback = callback
def myfunc(key):
self.callback(key)
# other stuff with key
class MyTest(unittest.TestCase):
def setUp(self):
self.myobj = myobj(self._callback)
self.cache_store = cStringIO()
def _callback(self, key):
self.cache_store.write(key)
self.cache_store.seek(0)
@patch.object('__main__.MyTest', '_callback')
def test_callback_called(self, mock):
self.myobj.myfunc("any string")
self.assertTrue(mock.called)
self.assertEqual(self.cache_store.read(), "any string")
我收到错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/mock/mock.py", line 1297, in patched
arg = patching.__enter__()
File "/usr/local/lib/python3.4/dist-packages/mock/mock.py", line 1369, in __enter__
original, local = self.get_original()
File "/usr/local/lib/python3.4/dist-packages/mock/mock.py", line 1343, in get_original
"%s does not have the attribute %r" % (target, name)
AttributeError: __main__.MyTest does not have the attribute '_callback'
所以我的问题是:如何从当前的测试用例中模拟一个函数?
答案 0 :(得分:0)
我找到了答案:在测试调用中使用patch.object作为上下文管理器。