Created
April 27, 2017 18:45
-
-
Save jbiason/b02113ebe867e02281f1c3d602eae1c9 to your computer and use it in GitHub Desktop.
Mocking requests.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is the "mockator": | |
def _mock_requests_method(responses, url, *dummy1, **dummy2): | |
"""Check the URL and return the expected response.""" | |
if url not in responses: | |
raise AssertionError('URL doesnt exist: {}', url) | |
(status, text) = responses[url] | |
response = Response() | |
response.status_code = status | |
response.raw = StringIO.StringIO(text) | |
return response | |
# This is how you mock Requests in the test: | |
@patch('yourmodule.requests.get') # same for posts | |
def test_something(self, mocked_get): | |
mocked_get.side_effect = functools.partial(_mock_requests_method, | |
{'some/url': (200, 'Response for some/url'), | |
'some/other/url': (404, 'Response for some/other/url')} | |
) | |
# and the rest of your test. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment