mirror of
https://github.com/python/cpython.git
synced 2025-08-04 00:48:58 +00:00
Closes issue 17660. You no longer need to explicitly pass create=True when patching builtin names.
This commit is contained in:
parent
fba913f77a
commit
fddcfa27fa
3 changed files with 52 additions and 4 deletions
|
@ -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)
|
||||
|
|
|
@ -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):
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue