Skip to content

Commit cd90a52

Browse files
elenaoatcjw296
authored andcommitted
bpo-38669: patch.object now raises a helpful error (GH17034)
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.
1 parent 28c9163 commit cd90a52

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
@@ -1601,6 +1601,10 @@ def _patch_object(
16011601
When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
16021602
for choosing which methods to wrap.
16031603
"""
1604+
if type(target) is str:
1605+
raise TypeError(
1606+
f"{target!r} must be the actual object to be patched, not a str"
1607+
)
16041608
getter = lambda: target
16051609
return _patch(
16061610
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)