Skip to content

Commit 41973c9

Browse files
miss-islingtonelenaoat
authored andcommitted
bpo-38669: patch.object now raises a helpful error (GH17511)
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 9baa870 commit 41973c9

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
@@ -1492,6 +1492,10 @@ def _patch_object(
14921492
When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
14931493
for choosing which methods to wrap.
14941494
"""
1495+
if type(target) is str:
1496+
raise TypeError(
1497+
f"{target!r} must be the actual object to be patched, not a str"
1498+
)
14951499
getter = lambda: target
14961500
return _patch(
14971501
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
@@ -112,6 +112,10 @@ def test():
112112
self.assertEqual(Something.attribute, sentinel.Original,
113113
"patch not restored")
114114

115+
def test_patchobject_with_string_as_target(self):
116+
msg = "'Something' must be the actual object to be patched, not a str"
117+
with self.assertRaisesRegex(TypeError, msg):
118+
patch.object('Something', 'do_something')
115119

116120
def test_patchobject_with_none(self):
117121
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)