Skip to content

Commit 654dfca

Browse files
committed
Adds signature checking for mock autospec object method calls
Mock can accept an spec object / class as argument, making sure that accessing attributes that do not exist in the spec will cause an AttributeError to be raised, but there is no guarantee that the spec's methods signatures are respected in any way. This creates the possibility to have faulty code with passing unittests and assertions. Example: import mock class Something(object): def foo(self, a, b, c, d): pass m = mock.Mock(spec=Something) m.foo() Adds the autospec argument to Mock, and its mock_add_spec method. Passes the spec's attribute with the same name to the child mock (spec-ing the child), if the mock's autospec is True. Sets _mock_check_sig if the given spec is callable. Adds unit tests to validate the fact that the autospec method signatures are respected.
1 parent ff48739 commit 654dfca

2 files changed

Lines changed: 81 additions & 7 deletions

File tree

Lib/unittest/mock.py

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ def checksig(_mock_self, *args, **kwargs):
102102
_copy_func_details(func, checksig)
103103
type(mock)._mock_check_sig = checksig
104104

105+
return sig
106+
105107

106108
def _copy_func_details(func, funcopy):
107109
# we explicitly don't copy func.__dict__ into this copy as it would
@@ -372,7 +374,8 @@ def __new__(cls, *args, **kw):
372374
def __init__(
373375
self, spec=None, wraps=None, name=None, spec_set=None,
374376
parent=None, _spec_state=None, _new_name='', _new_parent=None,
375-
_spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
377+
_spec_as_instance=False, _eat_self=None, unsafe=False,
378+
autospec=None, **kwargs
376379
):
377380
if _new_parent is None:
378381
_new_parent = parent
@@ -382,10 +385,15 @@ def __init__(
382385
__dict__['_mock_name'] = name
383386
__dict__['_mock_new_name'] = _new_name
384387
__dict__['_mock_new_parent'] = _new_parent
388+
__dict__['_autospec'] = autospec
385389

386390
if spec_set is not None:
387391
spec = spec_set
388392
spec_set = True
393+
if autospec is not None:
394+
# autospec is even stricter than spec_set.
395+
spec = autospec
396+
autospec = True
389397
if _eat_self is None:
390398
_eat_self = parent is not None
391399

@@ -426,12 +434,18 @@ def attach_mock(self, mock, attribute):
426434
setattr(self, attribute, mock)
427435

428436

429-
def mock_add_spec(self, spec, spec_set=False):
437+
def mock_add_spec(self, spec, spec_set=False, autospec=None):
430438
"""Add a spec to a mock. `spec` can either be an object or a
431439
list of strings. Only attributes on the `spec` can be fetched as
432440
attributes from the mock.
433441
434-
If `spec_set` is True then only attributes on the spec can be set."""
442+
If `spec_set` is True then only attributes on the spec can be set.
443+
If `autospec` is True then only attributes on the spec can be accessed
444+
and set, and if a method in the `spec` is called, it's signature is
445+
checked.
446+
"""
447+
if autospec is not None:
448+
self.__dict__['_autospec'] = autospec
435449
self._mock_add_spec(spec, spec_set)
436450

437451

@@ -445,9 +459,9 @@ def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
445459
_spec_class = spec
446460
else:
447461
_spec_class = _get_class(spec)
448-
res = _get_signature_object(spec,
449-
_spec_as_instance, _eat_self)
450-
_spec_signature = res and res[1]
462+
463+
_spec_signature = _check_signature(spec, self, _eat_self,
464+
_spec_as_instance)
451465

452466
spec = dir(spec)
453467

@@ -592,9 +606,20 @@ def __getattr__(self, name):
592606
# execution?
593607
wraps = getattr(self._mock_wraps, name)
594608

609+
kwargs = {}
610+
if self.__dict__.get('_autospec') is not None:
611+
# get the mock's spec attribute with the same name and
612+
# pass it to the child.
613+
spec_class = self.__dict__.get('_spec_class')
614+
spec = getattr(spec_class, name, None)
615+
is_type = isinstance(spec_class, type)
616+
eat_self = _must_skip(spec_class, name, is_type)
617+
kwargs['_eat_self'] = eat_self
618+
kwargs['autospec'] = spec
619+
595620
result = self._get_child_mock(
596621
parent=self, name=name, wraps=wraps, _new_name=name,
597-
_new_parent=self
622+
_new_parent=self, **kwargs
598623
)
599624
self._mock_children[name] = result
600625

Lib/unittest/test/testmock/testmock.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,48 @@ def test_only_allowed_methods_exist(self):
510510
)
511511

512512

513+
def _check_autospeced_something(self, something):
514+
for method_name in ['meth', 'cmeth', 'smeth']:
515+
mock_method = getattr(something, method_name)
516+
517+
# check that the methods are callable with correct args.
518+
mock_method(sentinel.a, sentinel.b, sentinel.c)
519+
mock_method(sentinel.a, sentinel.b, sentinel.c, d=sentinel.d)
520+
mock_method.assert_has_calls([
521+
call(sentinel.a, sentinel.b, sentinel.c),
522+
call(sentinel.a, sentinel.b, sentinel.c, d=sentinel.d)])
523+
524+
# assert that TypeError is raised if the method signature is not
525+
# respected.
526+
self.assertRaises(TypeError, mock_method)
527+
self.assertRaises(TypeError, mock_method, sentinel.a)
528+
self.assertRaises(TypeError, mock_method, a=sentinel.a)
529+
self.assertRaises(TypeError, mock_method, sentinel.a, sentinel.b,
530+
sentinel.c, e=sentinel.e)
531+
532+
# assert that AttributeError is raised if the method does not exist.
533+
self.assertRaises(AttributeError, getattr, something, 'foolish')
534+
535+
536+
def test_mock_autospec_all_members(self):
537+
for spec in [Something, Something()]:
538+
mock = Mock(autospec=spec)
539+
self._check_autospeced_something(mock)
540+
541+
542+
def test_mock_spec_function(self):
543+
def foo(lish):
544+
pass
545+
546+
mock = Mock(spec=foo)
547+
548+
mock(sentinel.lish)
549+
mock.assert_called_once_with(sentinel.lish)
550+
self.assertRaises(TypeError, mock)
551+
self.assertRaises(TypeError, sentinel.foo, sentinel.lish)
552+
self.assertRaises(TypeError, mock, foo=sentinel.foo)
553+
554+
513555
def test_from_spec(self):
514556
class Something(object):
515557
x = 3
@@ -1376,6 +1418,13 @@ def test_mock_add_spec_magic_methods(self):
13761418
self.assertRaises(TypeError, lambda: mock['foo'])
13771419

13781420

1421+
def test_mock_add_spec_autospec_all_members(self):
1422+
for spec in [Something, Something()]:
1423+
mock = Mock()
1424+
mock.mock_add_spec(spec, autospec=True)
1425+
self._check_autospeced_something(mock)
1426+
1427+
13791428
def test_adding_child_mock(self):
13801429
for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
13811430
mock = Klass()

0 commit comments

Comments
 (0)