Skip to content

Instantly share code, notes, and snippets.

@johnboxall
Last active December 18, 2015 02:18
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 johnboxall/5709599 to your computer and use it in GitHub Desktop.
Save johnboxall/5709599 to your computer and use it in GitHub Desktop.
Not sure if httpbin is down or your tests are failing? Use `mock` to stub out your external calls!
import mock
import requests
import unittest
def get():
# Retrieves data from an external service eg. Twitter, Google
try:
return requests.get('http://external-service.com/')
except requests.RequestException:
return None
class Test(unittest.TestCase):
def test(self):
# Ensure `get` handles `RequestException`.
get_mock = mock.MagicMock()
get_mock.side_effect = requests.RequestException()
with mock.patch("requests.get", get_mock):
self.assertEquals(get(), None)
if __name__ == '__main__':
unittest.main(verbosity=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment