[英]Partially mock a method in unittest `setUp`
I am trying to understand the mock/patch framework, but have a problem. 我试图了解模拟/补丁框架,但是有问题。 Here are my simplified codes:
这是我的简化代码:
file_a.py
class A:
def f(self):
b = B()
b.g()
b.h()
file_b.py
class B:
def g(self):
return network_requests(...)
def h(self):
return "This is should not be mocked."
file_test.py
class SomeTests:
def setUp(self):
with patch('file_b.B', autospec=True) as mock:
mock.g.return_value = "Mocked value"
mock.side_effect = lambda : B()
self.a = A()
def test(self):
self.a.f()
Essentially I want to mock only Bg
inside the test, but not Bh
. 本质上,我只想模拟测试中的
Bg
,而不模拟Bh
。 I got some idea from https://docs.python.org/3/library/unittest.mock-examples.html#partial-mocking , but Bg
is still not mocked. 我从https://docs.python.org/3/library/unittest.mock-examples.html#partial-mocking
Bg
了一些想法,但是仍然没有嘲笑Bg
。
Thank you! 谢谢!
In the example that you linked the key problem is 在您链接的示例中,关键问题是
Unfortunately
datetime.date
is written in C不幸的是
datetime.date
用C编写
That is why you need to mock the module and wrap what you don't want to mock (You cannot patch C methods directly). 这就是为什么您需要模拟模块并包装您不想模拟的内容(您不能直接修补C方法)。
Is all other cases (patch python objects) you can use just : 是所有其他情况(修补python对象)都可以使用:
with patch('file_b.B.g', autospec=True) as mock_g:
mock_g.return_value = "Mocked value"
Anyway take care that your patch will be active just in the with
context, out of it you will find the original reference. 无论如何,请注意您的补丁仅在
with
上下文中处于活动状态,从中您可以找到原始参考。 To have a better control of the context it you can use also decorators, start()
and stop()
. 为了更好地控制上下文,您还可以使用装饰器
start()
和stop()
。
I strongly encourage you read carefully patch
and where to patch . 我强烈建议您仔细阅读
patch
以及在何处进行补丁 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.