Skip to content

Instantly share code, notes, and snippets.

@electrofelix
Created October 6, 2015 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save electrofelix/40f4c38cf28bb701dba3 to your computer and use it in GitHub Desktop.
Save electrofelix/40f4c38cf28bb701dba3 to your computer and use it in GitHub Desktop.
import json
import mock
import requests
def build_response_mock(status_code, json_body=None, headers=None, **kwargs):
response = requests.Response()
response.status_code = status_code
text = None
if json_body is not None:
text = json.dumps(json_body).encode('utf-8')
if headers is not {}:
response.headers['Content-Length'] = len(text)
if headers is not None:
for k, v in headers.items():
response.headers[k] = v
for k, v in kwargs.items():
setattr(response, k, v)
mock_response = mock.MagicMock(wraps=response)
# replace text property
mock_response.text = text
# for some reason, mock wraps cannot handle attributes which are dicts
# and accessed by key, this can be worked around with the following
#mock_response.headers = response.headers
return mock_response
if __name__ == '__main__':
test_mock = build_response_mock(
200,
{},
headers={'Dummy-Header': None}
)
assert test_mock.headers.get('content-length', None) is not None
assert 'content-length' in test_mock.headers, \
("Use of 'in' to check if 'content-length' is a key in "
"test_mock.headers failed.\ntest_mock.headers.keys(): %s"
% test_mock.headers.keys())
assert test_mock.headers['content-length'] == 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment