diff options
author | Irit Katriel <1055913+iritkatriel@users.noreply.github.com> | 2022-01-23 18:42:41 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-01-23 18:42:41 (GMT) |
commit | f7955a82e36d4c32ebdd7b7707cdf0e6ffa7a418 (patch) | |
tree | be80eeca8d122c5b8a256c1c9675b05c9623e214 | |
parent | ca78130d7eb5265759697639e42487ec6d0a4caf (diff) | |
download | cpython-f7955a82e36d4c32ebdd7b7707cdf0e6ffa7a418.zip cpython-f7955a82e36d4c32ebdd7b7707cdf0e6ffa7a418.tar.gz cpython-f7955a82e36d4c32ebdd7b7707cdf0e6ffa7a418.tar.bz2 |
bpo-41403: Improve error message for invalid mock target (GH-30833)
-rw-r--r-- | Lib/unittest/mock.py | 6 | ||||
-rw-r--r-- | Lib/unittest/test/testmock/testpatch.py | 9 | ||||
-rw-r--r-- | Misc/NEWS.d/next/Library/2022-01-23-18-04-45.bpo-41403.SgoHqV.rst | 3 |
3 files changed, 13 insertions, 5 deletions
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index 9f99a5a..9137501 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -1589,9 +1589,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}") return partial(pkgutil.resolve_name, target), attribute diff --git a/Lib/unittest/test/testmock/testpatch.py b/Lib/unittest/test/testmock/testpatch.py index 233a5af..8ab63a1 100644 --- a/Lib/unittest/test/testmock/testpatch.py +++ b/Lib/unittest/test/testmock/testpatch.py @@ -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 index 0000000..ede159b --- /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. |