]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-41403: Improve error message for invalid mock target (GH-30833) (GH-30835)
authorIrit Katriel <1055913+iritkatriel@users.noreply.github.com>
Sun, 23 Jan 2022 19:35:15 +0000 (19:35 +0000)
committerGitHub <noreply@github.com>
Sun, 23 Jan 2022 19:35:15 +0000 (19:35 +0000)
(cherry picked from commit f7955a82e36d4c32ebdd7b7707cdf0e6ffa7a418)

Lib/unittest/mock.py
Lib/unittest/test/testmock/testpatch.py
Misc/NEWS.d/next/Library/2022-01-23-18-04-45.bpo-41403.SgoHqV.rst [new file with mode: 0644]

index 5c78274d093578da418f6d799b8462261b917b19..3f5442ed80951d2dc2ee7f159f03662de31d581b 100644 (file)
@@ -1557,9 +1557,9 @@ class _patch(object):
 def _get_target(target):
     try:
         target, attribute = target.rsplit('.', 1)
-    except (TypeError, ValueError):
-        raise TypeError("Need a valid target to patch. You supplied: %r" %
-                        (target,))
+    except (TypeError, ValueError, AttributeError):
+        raise TypeError(
+            f"Need a valid target to patch. You supplied: {target!r}")
     getter = lambda: _importer(target)
     return getter, attribute
 
index 233a5afffaed4a5f6fbb65a398b1b40ce19b4a9f..8ab63a1317d3dfff905d9c0078b946e1c7398fae 100644 (file)
@@ -1933,8 +1933,13 @@ class PatchTest(unittest.TestCase):
 
 
     def test_invalid_target(self):
-        with self.assertRaises(TypeError):
-            patch('')
+        class Foo:
+            pass
+
+        for target in ['', 12, Foo()]:
+            with self.subTest(target=target):
+                with self.assertRaises(TypeError):
+                    patch(target)
 
 
     def test_cant_set_kwargs_when_passing_a_mock(self):
diff --git a/Misc/NEWS.d/next/Library/2022-01-23-18-04-45.bpo-41403.SgoHqV.rst b/Misc/NEWS.d/next/Library/2022-01-23-18-04-45.bpo-41403.SgoHqV.rst
new file mode 100644 (file)
index 0000000..ede159b
--- /dev/null
@@ -0,0 +1,3 @@
+Make :meth:`mock.patch` raise a :exc:`TypeError` with a relevant error
+message on invalid arg. Previously it allowed a cryptic
+:exc:`AttributeError` to escape.