Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[3.7] bpo-38669: patch.object now raises a helpful error (GH17034) #17511

Merged
merged 1 commit into from
Dec 9, 2019
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.
Jump to
Jump to file
Failed to load files.
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 @@ -1492,6 +1492,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 @@ -112,6 +112,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`.