mercredi 20 mai 2020

Python: what's a function call on a mock object?

I have accidentally stumbled on this kind of notation:

>>> m = mock.Mock()
>>> m().my_value = 5
>>> 
>>> m
<Mock id='139823798337360'>
>>> m()
<Mock name='mock()' id='139823798364240'>

m is an object of type mock, () is a function call. How can you function call an object?

I tried calling a normal object, and unexpectedly i got an exception

>>> class C(object):
...     pass
... 
>>> c = C()
>>> c()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'C' object is not callable

So this must be some kind of Mock magic. What is it and is it used for?

Aucun commentaire:

Enregistrer un commentaire