This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

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

Created on 2020-10-12 18:26 by Indy, last changed 2022-04-11 14:59 by admin.

Files
File name Uploaded Description Edit
mockcase.py Indy, 2020-10-12 18:26
Messages (5)
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 committer) 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):
        super().__init__()
        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 :)
msg398711 - (view) Author: Andrei Kulakov (andrei.avk) * (Python triager) Date: 2021-08-01 16:04
I think this can be closed.
msg398712 - (view) Author: Irit Katriel (iritkatriel) * (Python committer) Date: 2021-08-01 16:15
+ Michael, in case he has something to add.
History
Date User Action Args
2022-04-11 14:59:36adminsetgithub: 86185
2021-08-01 16:15:00iritkatrielsetnosy: + michael.foord
messages: + msg398712
2021-08-01 16:04:41andrei.avksetnosy: + andrei.avk
messages: + msg398711
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