一个用于模拟 `urllib3` Python 库的实用程序库。
项目描述
用于模拟 urllib3 Python 库的实用程序库。
这是对响应库的改编。
响应正文为字符串
from urllib3_mock import Responses
import requests
responses = Responses('requests.packages.urllib3')
@responses.activate
def test_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')
assert resp.json() == {"error": "not found"}
assert len(responses.calls) == 1
assert responses.calls[0].request.url == '/api/1/foobar'
assert responses.calls[0].request.host == 'twitter.com'
assert responses.calls[0].request.scheme == 'http'
请求回调
import json
from urllib3_mock import Responses
import requests
responses = Responses('requests.packages.urllib3')
@responses.activate
def test_calc_api():
def request_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'},
)
assert resp.json() == {'value': 6}
assert len(responses.calls) == 1
assert responses.calls[0].request.url == '/sum'
assert responses.calls[0].request.host == 'calc.com'
assert (
responses.calls[0].response.headers['request-id'] ==
'728d329e-0e86-11e4-a748-0c84dc037c13'
)
除了将字符串 URL 传递给response.add或response.add_callback 之外 ,您还可以提供已编译的正则表达式。
import re
from urllib3_mock import Responses
import requests
responses = Responses('requests.packages.urllib3')
# Instead of
responses.add('GET', '/api/1/foobar',
body='{"error": "not found"}', status=404,
content_type='application/json')
# You can do the following
url_re = re.compile(r'/api/\d+/foobar')
responses.add('GET', url_re,
body='{"error": "not found"}', status=404,
content_type='application/json')
响应也可以抛出异常,如下所示。
from urllib3_mock import Responses
from requests.packages.urllib3.exceptions import HTTPError
exception = 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.
项目详情
关
urllib3_mock -0.3.3-py2.py3-none-any.whl 的哈希值
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 702c90042920d771c9902b7b5b542551cc57f259078f4eada47ab4e8cdd11f1a |
|
| MD5 | 2aed73bd3b24204f1ce09c467d397402 |
|
| 布莱克2-256 | 64ec4c723737b2c7733b6b7257d6990aa813144e2bb96e75ceaf2791ee815277 |