假设我有一个这样的课程.
class SomeProductionProcess(CustomCachedSingleTon):
def loaddata():
"""
Uses an iterator over a large file in Production for the Data pipeline.
"""
pass
Run Code Online (Sandbox Code Playgroud)
现在在测试时我想改变loaddata()方法内部的逻辑.这将是一个简单的自定义逻辑,不处理大数据.
我们如何loaddata()使用Python Mock UnitTest框架在测试时提供自定义实现?
我正在使用Python的mock库.我知道如何通过遵循文档来模拟类实例方法:
>>> def some_function():
... instance = module.Foo()
... return instance.method()
...
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... result = some_function()
... assert result == 'the result'
Run Code Online (Sandbox Code Playgroud)
但是,尝试模拟类实例变量但不起作用(instance.labels在以下示例中):
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... instance.labels = [1, 1, 2, 2]
... result = some_function()
... assert result == 'the result'
Run Code Online (Sandbox Code Playgroud)
基本上,我想instance.labels下some_function得到我想要的价值.任何提示?
我想要什么:
确保Foo在with语句中创建的所有实例都foo通过wraps=Foo.foo. 我想要这个的原因是我可以跟踪创建的所有实例call_count的方法。现在我这么说似乎有点不可能......fooFoo
>>> from mock import patch
...
... class Foo(object):
...
... def foo(self):
... return "foo"
...
... with patch("__main__.Foo.foo", wraps=Foo.foo) as m:
... foo = Foo()
... print(foo.foo())
Traceback (most recent call last):
File "a.py", line 12, in <module>
print(foo.foo())
File "/disk/software/lib/python27/mock/mock.py", line 1062, in __call__
return _mock_self._mock_call(*args, **kwargs)
File "/disk/software/lib/python27/mock/mock.py", line 1132, in _mock_call
return self._mock_wraps(*args, **kwargs)
TypeError: unbound method foo() must be …Run Code Online (Sandbox Code Playgroud)