Skip to content

Commit 4594565

Browse files
miss-islingtonelenaoat
authored andcommitted
bpo-38669: patch.object now raises a helpful error (GH17510)
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 <[email protected]>
1 parent 184a381 commit 4594565

File tree

3 files changed

+9
-0
lines changed

3 files changed

+9
-0
lines changed

Lib/unittest/mock.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1587,6 +1587,10 @@ def _patch_object(
15871587
When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
15881588
for choosing which methods to wrap.
15891589
"""
1590+
if type(target) is str:
1591+
raise TypeError(
1592+
f"{target!r} must be the actual object to be patched, not a str"
1593+
)
15901594
getter = lambda: target
15911595
return _patch(
15921596
getter, attribute, new, spec, create,

Lib/unittest/test/testmock/testpatch.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,10 @@ def test():
105105
self.assertEqual(Something.attribute, sentinel.Original,
106106
"patch not restored")
107107

108+
def test_patchobject_with_string_as_target(self):
109+
msg = "'Something' must be the actual object to be patched, not a str"
110+
with self.assertRaisesRegex(TypeError, msg):
111+
patch.object('Something', 'do_something')
108112

109113
def test_patchobject_with_none(self):
110114
class Something(object):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Raise :exc:`TypeError` when passing target as a string with :meth:`unittest.mock.patch.object`.

0 commit comments

Comments
 (0)