bpo-38669: patch.object now raises a helpful error (GH17034)

This means a clearer message is now shown when patch.object is called with two string arguments, rather than a class and a string argument.
This commit is contained in:
Elena Oat 2019-12-08 12:14:38 -08:00 committed by Chris Withers
parent 28c91631c2
commit cd90a52983
3 changed files with 9 additions and 0 deletions

View File

@ -1601,6 +1601,10 @@ def _patch_object(
When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
for choosing which methods to wrap.
"""
if type(target) is str:
raise TypeError(
f"{target!r} must be the actual object to be patched, not a str"
)
getter = lambda: target
return _patch(
getter, attribute, new, spec, create,

View File

@ -105,6 +105,10 @@ class PatchTest(unittest.TestCase):
self.assertEqual(Something.attribute, sentinel.Original,
"patch not restored")
def test_patchobject_with_string_as_target(self):
msg = "'Something' must be the actual object to be patched, not a str"
with self.assertRaisesRegex(TypeError, msg):
patch.object('Something', 'do_something')
def test_patchobject_with_none(self):
class Something(object):

View File

@ -0,0 +1 @@
Raise :exc:`TypeError` when passing target as a string with :meth:`unittest.mock.patch.object`.