Title: Override MagicMock special methods
Type: behavior Stage:
Components: Library (Lib), Tests Versions: Python 3.9
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Indy, iritkatriel
Priority: normal Keywords:

Created on 2020-10-12 18:26 by Indy, last changed 2020-10-15 12:18 by Indy.

File name Uploaded Description Edit Indy, 2020-10-12 18:26
Messages (3)
msg378513 - (view) Author: Aristotelis Mikropoulos (Indy) Date: 2020-10-12 18:26
This is more of a question whether the following is intended behavior:
Subclassing unittest.mock.MagicMock and overriding one of the special (double underscore) methods has no effect. The default MagicMock method implementation still stands. This isn't the case with subclassing Mock.
It is understood that the purpose of MagicMock is to offer stub implementations of certain special methods, but isn't defining them yourself in the body of a subclass supposed to override those stubs?
There is an example in the file attached.
msg378654 - (view) Author: Irit Katriel (iritkatriel) * (Python triager) Date: 2020-10-14 23:08
I don't know whether this is intended behaviour of not, but it seems that MagicMock's __init__ is setting the magic methods, every time a mock instance is created. I was able to achieve what you tried to write with this class definition - it sets __len__ after super.__init__ has done what it needs to do.

class MagicMockChild(MagicMock):
    def __init__(self):
        self.__len__ = lambda self : 9

This is not intended to be a satisfying answer, just to show what's going on.
msg378679 - (view) Author: Aristotelis Mikropoulos (Indy) Date: 2020-10-15 12:18
Yep, I had figured out myself that those stub methods are being set during MagicMock's __init__, thanks for answering anyway :)
Date User Action Args
2020-10-15 12:18:04Indysetmessages: + msg378679
2020-10-14 23:08:03iritkatrielsetnosy: + iritkatriel
messages: + msg378654
components: + Library (Lib)
2020-10-12 18:26:39Indycreate