Skip to content

Commit

Permalink
bpo-38669: patch.object now raises a helpful error (GH17510)
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.
(cherry picked from commit cd90a52)

Co-authored-by: Elena Oat <oat.elena@gmail.com>
  • Loading branch information
2 people authored and cjw296 committed Dec 9, 2019
1 parent 184a381 commit 4594565
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 @@ -1587,6 +1587,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 4594565

Please sign in to comment.