2017-04-14 35 views

回答

0

如果要求沒有被註冊的網址,你會得到一個

requests.exceptions.ConnectionError 

import responses 
import requests 

@responses.activate 
def test_my_api(): 
    resp = requests.get('https://twitter.com/') 
    print resp 

def run_my_api(): 
    resp = requests.get('https://twitter.com/') 
    print resp 

if __name__ == '__main__': 
    print "Without responses..." 
    run_my_api() 
    print "" 
    print "With responses..." 
    test_my_api() 

輸出

Without responses... 
<Response [200]> 

With responses... 
Traceback (most recent call last): 
    File "example.py", line 18, in <module> 
    test_my_api() 
    File "<string>", line 3, in wrapper 
    File "example.py", line 6, in test_my_api 
    resp = requests.get('https://twitter.com/') 
    File "/usr/local/lib/python2.7/site-packages/requests/api.py", line 70, in get 
    return request('get', url, params=params, **kwargs) 
    File "/usr/local/lib/python2.7/site-packages/requests/api.py", line 56, in request 
    return session.request(method=method, url=url, **kwargs) 
    File "/usr/local/lib/python2.7/site-packages/requests/sessions.py", line 488, in request 
    resp = self.send(prep, **send_kwargs) 
    File "/usr/local/lib/python2.7/site-packages/requests/sessions.py", line 609, in send 
    r = adapter.send(request, **kwargs) 
    File "/usr/local/lib/python2.7/site-packages/responses.py", line 294, in unbound_on_send 
    return self._on_request(adapter, request, *a, **kwargs) 
    File "/usr/local/lib/python2.7/site-packages/responses.py", line 239, in _on_request 
    raise response 
requests.exceptions.ConnectionError: Connection refused: GET https://twitter.com/ 

<Response [200]>距離undeco打電話給run_my_api。您可以使用assertRaises或等效項檢查異常。

相關問題