[issue25597] unittest.mock does not wrap dunder methods (__getitem__ etc)

Karthikeyan Singaravelan report at bugs.python.org
Mon Sep 9 10:03:32 EDT 2019


Karthikeyan Singaravelan <tir.karthi at gmail.com> added the comment:

This seems to a reasonable change to me since dict.get returns the value then making a contains check dict.__contains__ should return True instead of the fixed return value of False. Below is a patch where the mock_wraps attribute is set with the relevant method that would make sure in the report dict.get would used.


diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index 298b41e0d7..077d22d08e 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -1935,6 +1935,12 @@ _side_effect_methods = {


 def _set_return_value(mock, method, name):
+    # If _mock_wraps is present then attach it so that it's return
+    # value is used when called.
+    if mock._mock_wraps is not None:
+        method._mock_wraps = getattr(mock._mock_wraps, name)
+        return
+
     fixed = _return_values.get(name, DEFAULT)
     if fixed is not DEFAULT:
         method.return_value = fixed

----------
nosy: +cjw296, mariocj89

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue25597>
_______________________________________


More information about the Python-bugs-list mailing list