如何模拟请求和响应? [英] How can I mock requests and the response?
本文介绍了如何模拟请求和响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Python模拟包来模拟Python requests
模块.使我在以下情况下工作的基本要求是什么?
I am trying to use Pythons mock package to mock Pythons requests
module. What are the basic calls to get me working in below scenario?
在我的views.py中,我有一个函数,可以使各种request.get()调用每次具有不同的响应
In my views.py, I have a function that makes variety of requests.get() calls with different response each time
def myview(request):
res1 = requests.get('aurl')
res2 = request.get('burl')
res3 = request.get('curl')
在测试类中,我想做这样的事情,但无法找出确切的方法调用
In my test class I want to do something like this but cannot figure out exact method calls
第1步:
# Mock the requests module
# when mockedRequests.get('aurl') is called then return 'a response'
# when mockedRequests.get('burl') is called then return 'b response'
# when mockedRequests.get('curl') is called then return 'c response'
第2步:
呼叫我的视图
第3步:
验证响应包含"a响应","b响应","c响应"
verify response contains 'a response', 'b response' , 'c response'
如何完成第1步(模拟请求模块)?
How can I complete Step 1 (mocking the requests module)?
推荐答案
这对我有用:
import mock
@mock.patch('requests.get', mock.Mock(side_effect = lambda k:{'aurl': 'a response', 'burl' : 'b response'}.get(k, 'unhandled request %s'%k)))
这篇关于如何模拟请求和响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文