patrys / httmock

A mocking library for requests

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is it possible to mock connection errors?

dhalperi opened this issue · comments

>>> import requests
>>> requests.get('http://fake.fake')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/requests/api.py", line 55, in get
    return request('get', url, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/requests/sessions.py", line 383, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python2.7/site-packages/requests/sessions.py", line 486, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/requests/adapters.py", line 378, in send
    raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='fake.fake', port=80): Max retries exceeded with url: / (Caused by <class 'socket.gaierror'>: [Errno 8] nodename nor servname provided, or not known)

I want to throw the ConnectionError above.

That's called a side-effect and not something httmock is likely to be able to do. Instead you should look at Mock or support for side-effects in your unit testing library such as pytest or unittest2.

@daenney is right. As the code does not trap any exceptions, you should be able to just raise that exception in your URL handler but it's not a typical use case for the library and if it's the only reason you use httmock then perhaps the mock module would be a better fit.

@daenney @patrys thanks for feedback.

@patrys we use httmock mostly for its intended purpose, but one missing unit test is "our app loads successfully with a reasonable error message when it's unable to connect to the other endpoint" ... hence this desired use case.

I suspect that I may not be the only one who wants this test, but am happy to solve this problem in a one-off way by raising the exception as advised above.

Thanks!
Dan

@dhalperi make a raise, similar to this ?

@urlmatch(netloc=r'(.*\.)?failsite\.com$')
def failsite_mock(url, request):
   raise requests.ConnectionError

def test_my_function(self):
    with HTTMock(failsite_mock):
        my_function('http://failsite.com')