python mock - patching a method without obstructing implementation(python mock - 在不妨碍实现的情况下修补方法)
问题描述
是否有一种干净的方法来修补对象,以便在测试用例中获得 assert_call* 帮助程序,而无需实际删除操作?
Is there a clean way to patch an object so that you get the assert_call* helpers in your test case, without actually removing the action?
例如,如何修改 @patch 行以使以下测试通过:
For example, how can I modify the @patch line to get the following test passing:
from unittest import TestCase
from mock import patch
class Potato(object):
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(TestCase):
@patch.object(Potato, 'foo')
def test_something(self, mock):
spud = Potato()
forty_two = spud.foo(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
我可能可以使用 side_effect 来破解它,但我希望有一种更好的方法可以在所有函数、类方法、静态方法、未绑定方法等上以相同的方式工作.
I could probably hack this together using side_effect, but I was hoping there would be a nicer way which works the same way on all of functions, classmethods, staticmethods, unbound methods, etc.
推荐答案
与你的解决方案类似,但使用 wraps:
Similar solution with yours, but using wraps:
def test_something(self):
spud = Potato()
with patch.object(Potato, 'foo', wraps=spud.foo) as mock:
forty_two = spud.foo(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
根据文档:
wraps:要包装的模拟对象的项目.如果 wraps 不是 None 那么调用 Mock 会将调用传递给被包装的对象(返回真实结果).模拟上的属性访问将返回一个 Mock 对象,包装了被包裹的对应属性对象(因此尝试访问不存在的属性将引发 AttributeError).
wraps: Item for the mock object to wrap. If wraps is not None then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn’t exist will raise an AttributeError).
<小时>
class Potato(object):
def spam(self, n):
return self.foo(n=n)
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(TestCase):
def test_something(self):
spud = Potato()
with patch.object(Potato, 'foo', wraps=spud.foo) as mock:
forty_two = spud.spam(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
这篇关于python mock - 在不妨碍实现的情况下修补方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python mock - 在不妨碍实现的情况下修补方法
基础教程推荐
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
