Skip to content

Instantly share code, notes, and snippets.

@nguyent
Last active October 6, 2022 16:11
Show Gist options
  • Select an option

  • Save nguyent/39447aa1a8ca8ff8cff88add26eab9c5 to your computer and use it in GitHub Desktop.

Select an option

Save nguyent/39447aa1a8ca8ff8cff88add26eab9c5 to your computer and use it in GitHub Desktop.
Extended Mock class which adds a handy `call_dict_contains` method to mocks
import inspect
from functools import cached_property
from typing import AbstractSet, Any, Dict
from mock import MagicMock
class ExtendedMock(MagicMock):
"""
ExtendedMock adds two useful helper methods for testing:
- `call_dict` -- get call params as a dict (args and kwargs)
- `call_dict_contains` -- check if a provided dict is a subset of `call_dict` (all key/val pairs match)
example usage:
`@mock.patch('path.to.patched.func', new_callable=ExtendedMock, spec=True)`
"""
def __init__(self, *args, **kwargs):
super(MagicMock, self).__init__(*args, **kwargs)
self.func = kwargs.get('spec')
@cached_property
def signature(self) -> inspect.Signature:
return inspect.signature(self.func)
@cached_property
def params(self) -> AbstractSet[str]:
return self.signature.parameters.keys()
@property
def call_dict(self) -> Dict[str, Any]:
args = dict(zip(self.params, self.call_args.args))
return {**args, **self.call_args.kwargs}
def call_dict_contains(self, **kwargs) -> bool:
return all(v == self.call_dict[k] for k, v in kwargs.items())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment