]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-38669: patch.object now raises a helpful error (GH17511)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Mon, 9 Dec 2019 06:59:23 +0000 (22:59 -0800)
committerChris Withers <chris@withers.org>
Mon, 9 Dec 2019 06:59:23 +0000 (06:59 +0000)
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@gmail.com>
Lib/unittest/mock.py
Lib/unittest/test/testmock/testpatch.py
Misc/NEWS.d/next/Tests/2019-11-04-02-54-16.bpo-38669.pazXZ8.rst [new file with mode: 0644]

index 2b9e7f14a7563586430dd4be3e6ded615516b53e..213e596629965d39b005f7f695c7286ea54ec2bd 100644 (file)
@@ -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,
index 6358154b3e5e6a2a8334c6d588be8be713985f12..7453c4902a6dc115905d8707d61a800ac847516e 100644 (file)
@@ -112,6 +112,10 @@ class PatchTest(unittest.TestCase):
         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 (file)
index 0000000..5060ecf
--- /dev/null
@@ -0,0 +1 @@
+Raise :exc:`TypeError` when passing target as a string with :meth:`unittest.mock.patch.object`.
\ No newline at end of file