Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force MagicMock to copy function signature?

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?

like image 481
George Shuklin Avatar asked Dec 06 '16 17:12

George Shuklin


People also ask

What is the difference between mock and MagicMock?

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.

What is Side_effect in mock Python?

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 Assert_called_once_with?

assert_called_once_with() is used to check if the method is called with a particular set of arguments.


1 Answers

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)
like image 148
Markus W. Avatar answered Oct 17 '22 20:10

Markus W.