Skip to content

Commit 3596331

Browse files
committed
bpo-41403: Improve error message for invalid mock target (GH-30833)
(cherry picked from commit f7955a8)
1 parent a7a4ca4 commit 3596331

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
@@ -1602,9 +1602,9 @@ def stop(self):
16021602
def _get_target(target):
16031603
try:
16041604
target, attribute = target.rsplit('.', 1)
1605-
except (TypeError, ValueError):
1606-
raise TypeError("Need a valid target to patch. You supplied: %r" %
1607-
(target,))
1605+
except (TypeError, ValueError, AttributeError):
1606+
raise TypeError(
1607+
f"Need a valid target to patch. You supplied: {target!r}")
16081608
getter = lambda: _importer(target)
16091609
return getter, attribute
16101610

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)