Closes issue 17660. You no longer need to explicitly pass create=True when patching builtin names.
diff --git a/NEWS b/NEWS
index af528f3..b64189f 100644
--- a/NEWS
+++ b/NEWS
@@ -1,6 +1,9 @@
- Issue #17826: setting an iterable side_effect on a mock function created by
create_autospec now works. Patch by Kushal Das.
+- Issue #17826: setting an iterable side_effect on a mock function created by
+ create_autospec now works. Patch by Kushal Das.
+
- Issue #20968: unittest.mock.MagicMock now supports division.
Patch by Johannes Baiter.
diff --git a/mock.py b/mock.py
index d47c3f1..d7c0024 100644
--- a/mock.py
+++ b/mock.py
@@ -56,6 +56,11 @@
import inspect
import pprint
import sys
+try:
+ import builtins
+except ImportError:
+ import __builtin__ as builtins
+from types import ModuleType
import six
from six import wraps
@@ -116,6 +121,8 @@
del _next
+_builtins = {name for name in dir(builtins) if not name.startswith('_')}
+
BaseExceptions = (BaseException,)
if 'java' in sys.platform:
# jython
@@ -1302,6 +1309,9 @@
else:
local = True
+ if name in _builtins and isinstance(target, ModuleType):
+ self.create = True
+
if not self.create and original is DEFAULT:
raise AttributeError(
"%s does not have the attribute %r" % (target, name)
diff --git a/tests/testpatch.py b/tests/testpatch.py
index 10ca8ed..0a23eeb 100644
--- a/tests/testpatch.py
+++ b/tests/testpatch.py
@@ -380,7 +380,7 @@
def test_patchobject_wont_create_by_default(self):
try:
- @patch.object(SomeClass, 'frooble', sentinel.Frooble)
+ @patch.object(SomeClass, 'ord', sentinel.Frooble)
def test():
self.fail('Patching non existent attributes should fail')
@@ -389,7 +389,27 @@
pass
else:
self.fail('Patching non existent attributes should fail')
- self.assertFalse(hasattr(SomeClass, 'frooble'))
+ self.assertFalse(hasattr(SomeClass, 'ord'))
+
+
+ def test_patch_builtins_without_create(self):
+ @patch(__name__+'.ord')
+ def test_ord(mock_ord):
+ mock_ord.return_value = 101
+ return ord('c')
+
+ @patch(__name__+'.open')
+ def test_open(mock_open):
+ m = mock_open.return_value
+ m.read.return_value = 'abcd'
+
+ fobj = open('doesnotexists.txt')
+ data = fobj.read()
+ fobj.close()
+ return data
+
+ self.assertEqual(test_ord(), 101)
+ self.assertEqual(test_open(), 'abcd')
def test_patch_with_static_methods(self):