I want to check in my test if a function is called with an argument of a specific class.
class Foo:
...
I found mock.ANY, but there I cannot pass any class. What is want is:
test_mock.assert_called_with("expected string", ANY(spec=Foo))
With Mock you can mock magic methods but you have to define them. MagicMock has "default implementations of most of the magic methods.". If you don't need to test any magic methods, Mock is adequate and doesn't bring a lot of extraneous things into your tests.
side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT , the return value of this function is used as the return value.
MagicMock. MagicMock objects provide a simple mocking interface that allows you to set the return value or other behavior of the function or object creation call that you patched. This allows you to fully define the behavior of the call and avoid creating real objects, which can be onerous.
I solved it with a custom matcher.
class TypeMatcher:
def __init__(self, expected_type):
self.expected_type = expected_type
def __eq__(self, other):
return isinstance(other, self.expected_type)
And then test it like this:
test_mock.assert_called_with("expected string", TypeMatcher(Foo))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With