Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for response.raw attribute. #23

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions httmock.py
Original file line number Diff line number Diff line change
@@ -10,6 +10,10 @@
import urlparse
except ImportError:
import urllib.parse as urlparse
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Won't you need a third fallback here for from StringIO import StringIO on Python 2 platforms that do not support cStringIO?


if sys.version_info >= (3, 0, 0):
basestring = str
@@ -27,7 +31,7 @@ def getheaders(self, name):


def response(status_code=200, content='', headers=None, reason=None, elapsed=0,
request=None):
request=None, stream=False):
res = requests.Response()
res.status_code = status_code
if isinstance(content, dict):
@@ -41,6 +45,10 @@ def response(status_code=200, content='', headers=None, reason=None, elapsed=0,
res.reason = reason
res.elapsed = datetime.timedelta(elapsed)
res.request = request
if stream:
res.raw = StringIO(content if content is not None else '')
else:
res.raw = StringIO('')
if hasattr(request, 'url'):
res.url = request.url
if isinstance(request.url, bytes):
@@ -106,7 +114,7 @@ def __enter__(self):
self._real_session_send = requests.Session.send

def _fake_send(session, request, **kwargs):
response = self.intercept(request)
response = self.intercept(request, stream=kwargs['stream'])
if isinstance(response, requests.Response):
# this is pasted from requests to handle redirects properly:
kwargs.setdefault('stream', session.stream)
@@ -145,7 +153,7 @@ def _fake_send(session, request, **kwargs):
def __exit__(self, exc_type, exc_val, exc_tb):
requests.Session.send = self._real_session_send

def intercept(self, request):
def intercept(self, request, stream):
url = urlparse.urlsplit(request.url)
res = first_of(self.handlers, url, request)
if isinstance(res, requests.Response):
@@ -156,9 +164,10 @@ def intercept(self, request):
res.get('headers'),
res.get('reason'),
res.get('elapsed', 0),
request)
request,
stream=stream)
elif isinstance(res, basestring):
return response(content=res)
return response(content=res, stream=stream)
elif res is None:
return None
else:
14 changes: 14 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
@@ -63,6 +63,11 @@ def test_method_fallback(self):
r = requests.get('http://example.com/')
self.assertEqual(r.content, 'Hello from example.com')

def test_stream(self):
with HTTMock(any_mock):
r = requests.get('http://example.com/', stream=True)
self.assertEqual(r.raw.read(), 'Hello from example.com')

def test_netloc_fallback(self):
with HTTMock(google_mock, facebook_mock):
r = requests.get('http://google.com/')
@@ -187,6 +192,14 @@ def test_response_headers(self):
r = response(200, None, {'Content-Type': 'application/json'})
self.assertEqual(r.headers['content-type'], 'application/json')

def test_response_stream_raw(self):
r = response(200, 'content', {'Content-Type': 'application/json'}, stream=True)
self.assertEqual(r.raw.read(), 'content')

def test_response_nostream_raw(self):
r = response(200, 'content', {'Content-Type': 'application/json'})
self.assertEqual(r.raw.read(), '')

def test_response_cookies(self):
@all_requests
def response_content(url, request):
@@ -224,3 +237,4 @@ def get_mock(url, request):
response = requests.get('http://example.com/')
self.assertEqual(len(response.history), 1)
self.assertEqual(response.content, 'Hello from Google')