Skip to content

Commit f7955a8

Browse files
authored
bpo-41403: Improve error message for invalid mock target (pythonGH-30833)
1 parent ca78130 commit f7955a8

File tree

3 files changed

+13
-5
lines changed

3 files changed

+13
-5
lines changed

Lib/unittest/mock.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1589,9 +1589,9 @@ def stop(self):
15891589
def _get_target(target):
15901590
try:
15911591
target, attribute = target.rsplit('.', 1)
1592-
except (TypeError, ValueError):
1593-
raise TypeError("Need a valid target to patch. You supplied: %r" %
1594-
(target,))
1592+
except (TypeError, ValueError, AttributeError):
1593+
raise TypeError(
1594+
f"Need a valid target to patch. You supplied: {target!r}")
15951595
return partial(pkgutil.resolve_name, target), attribute
15961596

15971597

Lib/unittest/test/testmock/testpatch.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1933,8 +1933,13 @@ def test(mock):
19331933

19341934

19351935
def test_invalid_target(self):
1936-
with self.assertRaises(TypeError):
1937-
patch('')
1936+
class Foo:
1937+
pass
1938+
1939+
for target in ['', 12, Foo()]:
1940+
with self.subTest(target=target):
1941+
with self.assertRaises(TypeError):
1942+
patch(target)
19381943

19391944

19401945
def test_cant_set_kwargs_when_passing_a_mock(self):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Make :meth:`mock.patch` raise a :exc:`TypeError` with a relevant error
2+
message on invalid arg. Previously it allowed a cryptic
3+
:exc:`AttributeError` to escape.

0 commit comments

Comments
 (0)