Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Raise :exc:`TypeError` when passing target as a string with :meth:`unittest.mock.patch.object`.