[Python-checkins] bpo-38669: patch.object now raises a helpful error (GH17510)

Chris Withers webhook-mailer at python.org
Mon Dec 9 01:59:17 EST 2019


https://github.com/python/cpython/commit/4594565b56e9c99d2d3fb7549041bbca5ecba8e2
commit: 4594565b56e9c99d2d3fb7549041bbca5ecba8e2
branch: 3.8
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: Chris Withers <chris at withers.org>
date: 2019-12-09T06:59:04Z
summary:

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 cd90a52983db34896a6335a572d55bdda274778f)

Co-authored-by: Elena Oat <oat.elena at gmail.com>

files:
A Misc/NEWS.d/next/Tests/2019-11-04-02-54-16.bpo-38669.pazXZ8.rst
M Lib/unittest/mock.py
M Lib/unittest/test/testmock/testpatch.py

diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index d6e30679456a5..e92ccf168dbbd 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -1587,6 +1587,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,
diff --git a/Lib/unittest/test/testmock/testpatch.py b/Lib/unittest/test/testmock/testpatch.py
index 0632d95e58fec..e065a2c35fbee 100644
--- a/Lib/unittest/test/testmock/testpatch.py
+++ b/Lib/unittest/test/testmock/testpatch.py
@@ -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):
diff --git a/Misc/NEWS.d/next/Tests/2019-11-04-02-54-16.bpo-38669.pazXZ8.rst b/Misc/NEWS.d/next/Tests/2019-11-04-02-54-16.bpo-38669.pazXZ8.rst
new file mode 100644
index 0000000000000..5060ecf2dc5a4
--- /dev/null
+++ b/Misc/NEWS.d/next/Tests/2019-11-04-02-54-16.bpo-38669.pazXZ8.rst
@@ -0,0 +1 @@
+Raise :exc:`TypeError` when passing target as a string with :meth:`unittest.mock.patch.object`.
\ No newline at end of file



More information about the Python-checkins mailing list