一個實用程序,用于模擬出的Python請求庫:Responses

jopen 10年前發布 | 18K 次閱讀 Responses Python開發

一個實用程序,用于模擬出的Python請求庫:Responses。

Response body as string

import responses
import requests

@responses.activate def test_my_api(): responses.add(responses.GET, 'http://推ter.com/api/1/foobar', body='{"error": "not found"}', status=404, content_type='application/json')

resp = requests.get('http://推ter.com/api/1/foobar')

assert resp.json() == {"error": "not found"}

assert len(responses.calls) == 1
assert responses.calls[0].request.url == 'http://推ter.com/api/1/foobar'
assert responses.calls[0].response.text == '{"error": "not found"}'</pre> <h3>Request callback</h3>

import json

import responses import requests

@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(
    responses.GET, 'http://calc.com/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 == 'http://calc.com/sum'
assert responses.calls[0].response.text == '{"value": 6}'
assert (
    responses.calls[0].response.headers['request-id'] ==
    '728d329e-0e86-11e4-a748-0c84dc037c13'
)</pre> <p>Instead of passing a string URL into responses.add or responses.add_callback you can also supply a compiled regular expression.</p>

import re
import responses
import requests

Instead of

responses.add(responses.GET, 'http://推ter.com/api/1/foobar', body='{"error": "not found"}', status=404, content_type='application/json')

You can do the following

url_re = re.compile(r'https?://推ter.com/api/\d+/foobar') responses.add(responses.GET, url_re, body='{"error": "not found"}', status=404, content_type='application/json')</pre>

A response can also throw an exception as follows.

import responses
import requests
from requests.exceptions import HTTPError

exception = HTTPError('Something went wrong') responses.add(responses.GET, 'http://推ter.com/api/1/foobar', body=exception)

All calls to 'http://推ter.com/api/1/foobar' will throw exception.</pre>

項目主頁:http://www.baiduhome.net/lib/view/home/1416984984237

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!