diff options
author | Michael Foord <michael@voidspace.org.uk> | 2014-04-14 20:25:20 (GMT) |
---|---|---|
committer | Michael Foord <michael@voidspace.org.uk> | 2014-04-14 20:25:20 (GMT) |
commit | fddcfa27fab71ceb6a9df3f4edf46e94ee1da94f (patch) | |
tree | e2023b0ee586885b354d62492d14b95f5b3a57cb /Lib | |
parent | fba913f77aa53dff416753c987bf590762c98406 (diff) | |
download | cpython-fddcfa27fab71ceb6a9df3f4edf46e94ee1da94f.zip cpython-fddcfa27fab71ceb6a9df3f4edf46e94ee1da94f.tar.gz cpython-fddcfa27fab71ceb6a9df3f4edf46e94ee1da94f.tar.bz2 |
Closes issue 17660. You no longer need to explicitly pass create=True when patching builtin names.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/unittest/mock.py | 7 | ||||
-rw-r--r-- | Lib/unittest/test/testmock/testpatch.py | 24 |
2 files changed, 29 insertions, 2 deletions
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index f1f6522..2dd4ca5 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -27,9 +27,13 @@ __version__ = '1.0' import inspect import pprint import sys +import builtins +from types import ModuleType from functools import wraps, partial +_builtins = {name for name in dir(builtins) if not name.startswith('_')} + BaseExceptions = (BaseException,) if 'java' in sys.platform: # jython @@ -1166,6 +1170,9 @@ class _patch(object): 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/Lib/unittest/test/testmock/testpatch.py b/Lib/unittest/test/testmock/testpatch.py index c1bc34f..d941d8a 100644 --- a/Lib/unittest/test/testmock/testpatch.py +++ b/Lib/unittest/test/testmock/testpatch.py @@ -377,7 +377,7 @@ class PatchTest(unittest.TestCase): 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') @@ -386,7 +386,27 @@ class PatchTest(unittest.TestCase): 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): |