[issue21269] Provide args and kwargs attributes on mock call objects

Karthikeyan Singaravelan report at bugs.python.org
Sat Feb 9 13:13:06 EST 2019


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

args and kwargs property can be introduced on the call object to return the args and kwargs stored in the tuple. Currently wrapping call object with tuple can get a tuple of args and kwargs but a property would be helpful. A first attempt patch on this. Feedback on the API would be helpful.

$ ./python.exe
Python 3.8.0a1+ (heads/master:8a03ff2ff4, Feb  9 2019, 10:42:29)
[Clang 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m(1, a=1)
<Mock name='mock()' id='4325199504'>
>>> m.call_args_list[0]
call(1, a=1)
>>> tuple(m.call_args_list[0]) # wrapping it with tuple can give args and kwargs currently
((1,), {'a': 1})
>>> m.call_args_list[0].args # With patch return args
(1,)
>>> m.call_args_list[0].kwargs # With patch return kwargs
{'a': 1}

A simple patch would be as below : 

➜  cpython git:(master) ✗ git diff | cat
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index ef5c55d6a1..ef1aa1dcea 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -2124,6 +2124,24 @@ class _Call(tuple):
     def index(self, *args, **kwargs):
         return self.__getattr__('index')(*args, **kwargs)

+    @property
+    def args(self):
+        if len(self) == 2:
+            args, kwargs = self
+        else:
+            name, args, kwargs = self
+
+        return args
+
+    @property
+    def kwargs(self):
+        if len(self) == 2:
+            args, kwargs = self
+        else:
+            name, args, kwargs = self
+
+        return kwargs
+
     def __repr__(self):
         if not self._mock_from_kall:
             name = self._mock_name or 'call'

----------
nosy: +cjw296, xtreak
versions: +Python 3.8 -Python 3.5

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


More information about the Python-bugs-list mailing list