I want to mock few not important functions for the test subject (other function) - time.sleep(), etc.
I can replace them with simple mock, and this will work. But I want it to report errors if they were called with incorrect number of arguments, without named arguments, etc.
Is any way to say mock 'raise exception if your argument list is different from given function'?
Example of function I want to mock:
def mockme(arg1, arg2):
pass
What I want:
>>> m = mock.CallableMock(signature=mockme)
>>> m(1,2)
<MagicMock name='mockme()' id='140435553563920'>
>>> m(1,2,3)
TypeError: <MagicMock name='mockme()' id='140435553563920'> takes exactly 2 arguments (3 given)
Any idea how to make this?
So what is the difference between them? MagicMock is a subclass of Mock . It contains all magic methods pre-created and ready to use (e.g. __str__ , __len__ , etc.). Therefore, you should use MagicMock when you need magic methods, and Mock if you don't need them.
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.
assert_called_once_with() is used to check if the method is called with a particular set of arguments.
Have a look at unittest.mock.create_autospec, that should do exactly what you want
def some (a,b):
pass
some_mock=mock.create_autospec(some)
some_mock(1)
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