Skip to content

Instantly share code, notes, and snippets.

@peketamin
Last active March 29, 2018 00:47
Show Gist options
  • Save peketamin/ef9a407568837acc1004ab851c875590 to your computer and use it in GitHub Desktop.
Save peketamin/ef9a407568837acc1004ab851c875590 to your computer and use it in GitHub Desktop.
python mock, patch example
from third_party_lib import make_service, make_credentials
class MyClass(object):
@classmethod
def from_json(cls, json):
credentials = make_credentials(json)
return cls(credentials)
def __init__(self, credentials):
self.credentials = credentials
def _service(self):
return make_service(self.credentials)
def a_method(self, credential_id):
request_obj = self._service().get(credential_id)
result = request_obj.execute()
values = result.get('values', [])
return values
import unittest
from unittest.mock import MagicMock, patch
from my_class import MyClass
class TestMyClass(unittest.TestCase):
def test_from_json(self):
with patch('my_class.make_credentials') as mock:
mock.side_effect = Exception('Boom!')
with self.assertRaises(Exception) as ctx:
my_obj = MyClass.from_json('this is not json')
the_exc = ctx.exception
self.assertIsInstance(the_exc, Exception)
self.assertEqual(str(the_exc), 'Boom!')
@patch('my_class.make_credentials')
@patch('third_party_lib.Service')
def test_a_method(self,
mock_service,
mock_make_credentials):
mock_service.return_value.get.return_value.execute.return_value = {'values': [['row_1']]}
my_obj = MyClass.from_json('this is not json')
rows = my_obj.a_method(credential_id=22)
self.assertEqual(rows[0][0], 'row_1')
if __name__ == "__main__":
unittest.main()
class Service(object):
"""some service"""
class Auth(object):
"""some auth"""
def make_service(credentials):
return Service(credentials)
def make_credentials(json):
return Auth(json)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment