Skip to content

Commit 14f2a12

Browse files
tirkarthiidanw206
andauthored
[3.9] bpo-42532: Check if NonCallableMock's spec_arg is not None instead of call its __bool__ function (GH-23613) (GH-23676)
Check if NonCallableMock's spec_arg is not None instead of call its __bool__ function (cherry picked from commit c598a04) Co-authored-by: idanw206 <[email protected]>
1 parent 3dcdbde commit 14f2a12

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

Lib/unittest/mock.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,7 @@ def __new__(cls, /, *args, **kw):
406406
# Check if spec is an async object or function
407407
bound_args = _MOCK_SIG.bind_partial(cls, *args, **kw).arguments
408408
spec_arg = bound_args.get('spec_set', bound_args.get('spec'))
409-
if spec_arg and _is_async_obj(spec_arg):
409+
if spec_arg is not None and _is_async_obj(spec_arg):
410410
bases = (AsyncMockMixin, cls)
411411
new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
412412
instance = _safe_super(NonCallableMock, cls).__new__(new)

Lib/unittest/test/testmock/testmock.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2156,6 +2156,16 @@ def trace(frame, event, arg): # pragma: no cover
21562156
obj = mock(spec=Something)
21572157
self.assertIsInstance(obj, Something)
21582158

2159+
def test_bool_not_called_when_passing_spec_arg(self):
2160+
class Something:
2161+
def __init__(self):
2162+
self.obj_with_bool_func = unittest.mock.MagicMock()
2163+
2164+
obj = Something()
2165+
with unittest.mock.patch.object(obj, 'obj_with_bool_func', autospec=True): pass
2166+
2167+
self.assertEqual(obj.obj_with_bool_func.__bool__.call_count, 0)
2168+
21592169

21602170
if __name__ == '__main__':
21612171
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Remove unexpected call of ``__bool__`` when passing a ``spec_arg`` argument to a Mock.

0 commit comments

Comments
 (0)