Merge "Allow specifying an exception to raise"

This commit is contained in:
Jenkins 2014-12-16 00:57:29 +00:00 committed by Gerrit Code Review
commit 3a9d7ea222
2 changed files with 33 additions and 3 deletions

View File

@ -118,6 +118,14 @@ class _Context(object):
class _MatcherResponse(object):
def __init__(self, **kwargs):
self._exc = kwargs.pop('exc', None)
# If the user is asking for an exception to be thrown then prevent them
# specifying any sort of body or status response as it won't be used.
# This may be protecting the user too much but can be removed later.
if self._exc and kwargs:
raise TypeError('Cannot provide other arguments with exc.')
_check_body_arguments(**kwargs)
self._params = kwargs
@ -136,6 +144,10 @@ class _MatcherResponse(object):
raise TypeError('Text should be a callback or string data')
def get_response(self, request):
# if an error was requested then raise that instead of doing response
if self._exc:
raise self._exc
context = _Context(self._params.get('headers', {}).copy(),
self._params.get('status_code', _DEFAULT_STATUS),
self._params.get('reason'))

View File

@ -21,6 +21,10 @@ import requests_mock
from requests_mock.tests import base
class MyExc(Exception):
pass
class SessionAdapterTests(base.TestCase):
PREFIX = "mock"
@ -315,9 +319,6 @@ class SessionAdapterTests(base.TestCase):
def test_requests_in_history_on_exception(self):
class MyExc(Exception):
pass
def _test_cb(request, ctx):
raise MyExc()
@ -436,3 +437,20 @@ class SessionAdapterTests(base.TestCase):
self.assertEqual(1, m.call_count)
self.assertEqual(dict_resp, resp.json())
def test_raises_exception(self):
self.adapter.register_uri('GET', self.url, exc=MyExc)
self.assertRaises(MyExc,
self.session.get,
self.url)
self.assertEqual(self.url, self.adapter.last_request.url)
def test_raises_exception_with_body_args_fails(self):
self.assertRaises(TypeError,
self.adapter.register_uri,
'GET',
self.url,
exc=MyExc,
text='fail')