]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-38669: patch.object now raises a helpful error (GH17034)
authorElena Oat <oat.elena@gmail.com>
Sun, 8 Dec 2019 20:14:38 +0000 (12:14 -0800)
committerChris Withers <chris@withers.org>
Sun, 8 Dec 2019 20:14:38 +0000 (20:14 +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.

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 b06e29cf01c95b355ffd22f178e7c5b7ee0bad64..cd5a2aeb6084d719bea4c961480f4a3256af09ca 100644 (file)
@@ -1601,6 +1601,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 0632d95e58fec0577367797d2b03e22269c00634..e065a2c35fbeec54886ed0e4f92ba9d6894e0053 100644 (file)
@@ -105,6 +105,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