[Python-checkins] bpo-41403: Improve error message for invalid mock target (GH-30833) (GH-30834)
iritkatriel
webhook-mailer at python.org
Sun Jan 23 14:34:51 EST 2022
https://github.com/python/cpython/commit/e3ade66ec575e0cb4882cfdff155ef962e67c837
commit: e3ade66ec575e0cb4882cfdff155ef962e67c837
branch: 3.10
author: Irit Katriel <1055913+iritkatriel at users.noreply.github.com>
committer: iritkatriel <1055913+iritkatriel at users.noreply.github.com>
date: 2022-01-23T19:34:43Z
summary:
bpo-41403: Improve error message for invalid mock target (GH-30833) (GH-30834)
(cherry picked from commit f7955a82e36d4c32ebdd7b7707cdf0e6ffa7a418)
files:
A Misc/NEWS.d/next/Library/2022-01-23-18-04-45.bpo-41403.SgoHqV.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 6226bd4bc0c19..7152f86ed9694 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -1602,9 +1602,9 @@ def stop(self):
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
diff --git a/Lib/unittest/test/testmock/testpatch.py b/Lib/unittest/test/testmock/testpatch.py
index 233a5afffaed4..8ab63a1317d3d 100644
--- a/Lib/unittest/test/testmock/testpatch.py
+++ b/Lib/unittest/test/testmock/testpatch.py
@@ -1933,8 +1933,13 @@ def test(mock):
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
index 0000000000000..ede159b25641f
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2022-01-23-18-04-45.bpo-41403.SgoHqV.rst
@@ -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.
More information about the Python-checkins
mailing list