用于模拟“urllib3”python库的实用程序库。
urllib3-mock的Python项目详细描述
用于模拟urllib3python库的实用程序库。
这是responses库的改编。
响应体为字符串
fromurllib3_mockimportResponsesimportrequestsresponses=Responses('requests.packages.urllib3')@responses.activatedeftest_my_api():responses.add('GET','/api/1/foobar',body='{"error": "not found"}',status=404,content_type='application/json')resp=requests.get('http://twitter.com/api/1/foobar')assertresp.json()=={"error":"not found"}assertlen(responses.calls)==1assertresponses.calls[0].request.url=='/api/1/foobar'assertresponses.calls[0].request.host=='twitter.com'assertresponses.calls[0].request.scheme=='http'
请求回拨
importjsonfromurllib3_mockimportResponsesimportrequestsresponses=Responses('requests.packages.urllib3')@responses.activatedeftest_calc_api():defrequest_callback(request):payload=json.loads(request.body)resp_body={'value':sum(payload['numbers'])}headers={'request-id':'728d329e-0e86-11e4-a748-0c84dc037c13'}return(200,headers,json.dumps(resp_body))responses.add_callback('POST','/sum',callback=request_callback,content_type='application/json')resp=requests.post('http://calc.com/sum',json.dumps({'numbers':[1,2,3]}),headers={'content-type':'application/json'},)assertresp.json()=={'value':6}assertlen(responses.calls)==1assertresponses.calls[0].request.url=='/sum'assertresponses.calls[0].request.host=='calc.com'assert(responses.calls[0].response.headers['request-id']=='728d329e-0e86-11e4-a748-0c84dc037c13')
而不是将字符串url传递到响应中。add或响应。add\u callback 您还可以提供已编译的正则表达式。
importrefromurllib3_mockimportResponsesimportrequestsresponses=Responses('requests.packages.urllib3')# Instead ofresponses.add('GET','/api/1/foobar',body='{"error": "not found"}',status=404,content_type='application/json')# You can do the followingurl_re=re.compile(r'/api/\d+/foobar')responses.add('GET',url_re,body='{"error": "not found"}',status=404,content_type='application/json')
响应还可以引发异常,如下所示。
fromurllib3_mockimportResponsesfromrequests.packages.urllib3.exceptionsimportHTTPErrorexception=HTTPError('Something went wrong')responses=Responses('requests.packages.urllib3')responses.add('GET','/api/1/foobar',body=exception)# All calls to 'http://twitter.com/api/1/foobar' will throw exception.