Skip to content

Instantly share code, notes, and snippets.

@jeffbrl
Created October 17, 2015 21:38
Show Gist options
  • Select an option

  • Save jeffbrl/bff412ad7bdb6b1604c9 to your computer and use it in GitHub Desktop.

Select an option

Save jeffbrl/bff412ad7bdb6b1604c9 to your computer and use it in GitHub Desktop.
Faking an API call using mock object
from api_consumer.api_consumer import ApiConsumer
import unittest
import unittest.mock
import json
class TestApiConsumer(unittest.TestCase):
def setUp(self):
self.ac = ApiConsumer()
def test_get(self):
# replace ApiConsumer's get method with a mock
self.ac.get=unittest.mock.Mock(return_value=b'{\n "userId": 1,\n "id": 1,\n "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",\n "body": "quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto"\n}')
# you can incorrectly spell URL here to provie it is not called
response = self.ac.get('http://jsonplaceholder.typicode.com/posts/1')
print(response)
my_dict = json.loads(response.decode("utf-8"))
self.assertEqual(my_dict['id'], 1)
def test_post(self):
pass
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment