I have defined the following class:
class Config:
def __init__(self) -> None:
self._entries = dict()
@property
def entries(self):
return self._entries
def __contains__(self, key: any) -> bool:
"""
Returns True if specified key is in the existing config
entries, else returns False.
"""
return key in self.entries
I then have another class that is calling Config.__contains__ through:
def some_function():
config_obj = Config()
if entry in config_obj:
# Do something.
Now, I want to unit-test some_function and mock Config.__contains__. To do so, I have defined this test function:
from unittest.mock import MagicMock
def test_some_function()
# given
mocked_config_obj = Config()
mocked_config_obj.__contains__ = MagicMock(return_value=True)
# when
some_function()
# then
mocked_config_obj.__contains__.assert_called_once() # Fails
Ideally, if entry in config_obj should call mocked_config_obj.__contains__, but it's not. What am I missing here?
You're never actually mocking anything. You've created a
MagicMockobject and assigned it to a variable namedmocked_config_obj, but you never patch the module containingsome_functionto use that mocked object.Assuming that we have module
config.pythat implements theConfigclass:And module
some_module.pythat implementsSomeClass, which usesconfig.Config:Then we could write a test like this:
That arranges for
config_obj = Config()to receive a mock object, which we can then test for calls oncesome_functionreturns.