Skip to content

Commit

Permalink
bpo-38669: patch.object now raises a helpful error (GH17034)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
elenaoat authored and cjw296 committed Dec 8, 2019
1 parent 28c9163 commit cd90a52
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Lib/unittest/mock.py
Expand Up @@ -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,
Expand Down
4 changes: 4 additions & 0 deletions Lib/unittest/test/testmock/testpatch.py
Expand Up @@ -105,6 +105,10 @@ def test():
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):
Expand Down
@@ -0,0 +1 @@
Raise :exc:`TypeError` when passing target as a string with :meth:`unittest.mock.patch.object`.

0 comments on commit cd90a52

Please sign in to comment.