Make using create=True with spec=True in patchers an error
diff --git a/mock.py b/mock.py
index a41c33d..75aaf73 100644
--- a/mock.py
+++ b/mock.py
@@ -1229,6 +1229,8 @@
spec = original
if (spec or spec_set) is not None:
+ if original is DEFAULT:
+ raise TypeError("Can't use 'spec' with create=True")
if isinstance(original, ClassTypes):
# If we're patching out a class and there is a spec
inherit = True
@@ -1273,6 +1275,8 @@
"autospec creates the mock for you. Can't specify "
"autospec and new."
)
+ if original is DEFAULT:
+ raise TypeError("Can't use 'spec' with create=True")
spec_set = bool(spec_set)
if autospec is True:
autospec = original
@@ -1302,7 +1306,7 @@
return new
- def __exit__(self, *_):
+ def __exit__(self, *exc_info):
"""Undo the patch."""
if not _is_started(self):
raise RuntimeError('stop called on unstarted patcher')
@@ -1320,7 +1324,7 @@
del self.target
for patcher in reversed(self.additional_patchers):
if _is_started(patcher):
- patcher.__exit__(*_)
+ patcher.__exit__(*exc_info)
start = __enter__
stop = __exit__
diff --git a/tests/testpatch.py b/tests/testpatch.py
index 54d3878..d6ebec3 100644
--- a/tests/testpatch.py
+++ b/tests/testpatch.py
@@ -1682,6 +1682,21 @@
'exception traceback not propgated')
+ def test_create_and_specs(self):
+ for kwarg in ('spec', 'spec_set', 'autospec'):
+ p = patch('%s.doesnotexist' % __name__, create=True,
+ **{kwarg: True})
+ self.assertRaises(TypeError, p.start)
+ self.assertRaises(NameError, lambda: doesnotexist)
+
+ # check that spec with create is innocuous if the original exists
+ p = patch('%s.PTModule' % __name__, create=True,
+ **{kwarg: True})
+ try:
+ p.start()
+ finally:
+ p.stop()
+
if __name__ == '__main__':
unittest2.main()