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 - 在不妨碍实现的情况下修补方法
基础教程推荐
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
