Skip to content

Commit 72c3599

Browse files
blhsingvoidspace
authored andcommitted
bpo-37972: unittest.mock._Call now passes on __getitem__ to the __getattr__ chaining so that call() can be subscriptable (GH-15565)
* bpo-37972: unittest.mock._Call now passes on __getitem__ to the __getattr__ chaining so that call() can be subscriptable * 📜🤖 Added by blurb_it. * Update 2019-08-28-21-40-12.bpo-37972.kP-n4L.rst added name of the contributor * bpo-37972: made all dunder methods chainable for _Call * bpo-37972: delegate only attributes of tuple instead to __getattr__
1 parent 1abf543 commit 72c3599

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

Lib/unittest/mock.py

+6
Original file line numberDiff line numberDiff line change
@@ -2462,6 +2462,12 @@ def __getattr__(self, attr):
24622462
return _Call(name=name, parent=self, from_kall=False)
24632463

24642464

2465+
def __getattribute__(self, attr):
2466+
if attr in tuple.__dict__:
2467+
raise AttributeError
2468+
return tuple.__getattribute__(self, attr)
2469+
2470+
24652471
def count(self, /, *args, **kwargs):
24662472
return self.__getattr__('count')(*args, **kwargs)
24672473

Lib/unittest/test/testmock/testhelpers.py

+20
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,26 @@ def test_call_with_name(self):
334334
self.assertEqual(_Call((('bar', 'barz'),),)[0], '')
335335
self.assertEqual(_Call((('bar', 'barz'), {'hello': 'world'}),)[0], '')
336336

337+
def test_dunder_call(self):
338+
m = MagicMock()
339+
m().foo()['bar']()
340+
self.assertEqual(
341+
m.mock_calls,
342+
[call(), call().foo(), call().foo().__getitem__('bar'), call().foo().__getitem__()()]
343+
)
344+
m = MagicMock()
345+
m().foo()['bar'] = 1
346+
self.assertEqual(
347+
m.mock_calls,
348+
[call(), call().foo(), call().foo().__setitem__('bar', 1)]
349+
)
350+
m = MagicMock()
351+
iter(m().foo())
352+
self.assertEqual(
353+
m.mock_calls,
354+
[call(), call().foo(), call().foo().__iter__()]
355+
)
356+
337357

338358
class SpecSignatureTest(unittest.TestCase):
339359

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Subscripts to the `unittest.mock.call` objects now receive the same chaining mechanism as any other custom attributes, so that the following usage no longer raises a `TypeError`:
2+
3+
call().foo().__getitem__('bar')
4+
5+
Patch by blhsing

0 commit comments

Comments
 (0)