Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert called with argument of specific type

Tags:

python

mocking

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))
like image 596
Kewitschka Avatar asked May 28 '19 09:05

Kewitschka


People also ask

What is the difference between mock and MagicMock?

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.

What is mock side effect?

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.

What is MagicMock Python?

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.


1 Answers

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))
like image 128
Kewitschka Avatar answered Oct 20 '22 13:10

Kewitschka