Python3 Unittest模拟请求模块 [英] Python3 Unittest Mocking Requests Module
问题描述
我很愿意在Java的Mockito库中使用依赖注入,但是对使用Python3的unittest.mock
模块却没有什么经验.我试图断言Request
实例的prepare
方法被调用.但是,对断言self.assertTrue(mock_request.prepare.called)
的测试失败.有人可以建议我如何通过此考试吗?
I am comfortable using dependancy injection with Java's Mockito library, but have little experience using Python3's unittest.mock
module. I am trying to assert that the Request
instance's prepare
method gets called. However the test fails on the assertion self.assertTrue(mock_request.prepare.called)
. Can someone please advise me on how to get this test passing?
import requests
import unittest
from unittest import mock
class Engine(object):
def get(self, **kwargs):
session = requests.Session()
req = requests.Request('GET', 'http://www.google.com', params=kwargs).prepare()
response = session.send(req, timeout=1)
class TestEngine(unittest.TestCase):
@mock.patch('requests.Session')
@mock.patch('requests.Request')
def test_get(self, mock_request, mock_session):
e = Engine()
e.get()
self.assertTrue(mock_request.called)
self.assertTrue(mock_request.prepare.called)
if __name__ == '__main__':
unittest.main()
推荐答案
您的代码永远不会直接访问Request
上的prepare
.在调用Request()
的返回值上访问该方法,因此请使用
Your code never accesses prepare
on Request
directly. The method is accessed on the return value of a call to Request()
, so test for that instead by using the Mock.return_value
attribute:
self.assertTrue(mock_request.return_value.prepare.called)
调试模拟问题时,发现打印 Mock.mock_calls
属性(用于顶级模拟对象);为您的测试打印mock_request.mock_calls
产生:
When debugging mock issues, I find it helpful to print out the Mock.mock_calls
attribute for the top-level mock object; for your test printing mock_request.mock_calls
produces:
[call('GET', 'http://www.google.com', params={}), call().prepare()]
显示确实已访问call().prepare()
(并且通常可以通过Mock.return_value
属性访问call()
的结果,如上所示).
showing that call().prepare()
was indeed accessed (and the result of a call()
is usually accessible via the Mock.return_value
attribute, as shown above).
这篇关于Python3 Unittest模拟请求模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!