Created
February 7, 2023 09:41
-
-
Save fruch/e25033ebd3f65fc30822d510329bc166 to your computer and use it in GitHub Desktop.
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
class DB: | |
def query(self, *args, **kwargs): | |
print("DB: ", args, kwargs) | |
return {"Data for real DB"} | |
class API: | |
def __init__(self): | |
self.db = DB() | |
def call(self): | |
return self.db.query("do this", "do that") | |
def test_0_real_call(): | |
api = API() | |
assert {'Data for real DB'} == api.call() | |
def test_1_magic_mock(): | |
""" | |
magic mock would answer any call and property with a new MagicMock | |
""" | |
from unittest.mock import MagicMock | |
api = API() | |
api.db = MagicMock() | |
assert not {'Data for real DB'} == api.call() | |
assert isinstance(api.call(), MagicMock) | |
def test_1_magic_mock_return_specific(): | |
""" | |
magic mock can answer specific answers if needed | |
""" | |
from unittest.mock import MagicMock | |
api = API() | |
api.db = MagicMock() | |
api.db.query.return_value = {"Data for real DB"} | |
assert {'Data for real DB'} == api.call() | |
assert not isinstance(api.call(), MagicMock) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment