Last active
March 29, 2018 00:47
-
-
Save peketamin/ef9a407568837acc1004ab851c875590 to your computer and use it in GitHub Desktop.
python mock, patch example
This file contains hidden or 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
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 |
This file contains hidden or 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
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() |
This file contains hidden or 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
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