Skip to content

Commit 1398dca

Browse files
authored
bpo-41403: Improve error message for invalid mock target (GH-30833) (GH-30835)
(cherry picked from commit f7955a8)
1 parent 94d6434 commit 1398dca

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
@@ -1557,9 +1557,9 @@ def stop(self):
15571557
def _get_target(target):
15581558
try:
15591559
target, attribute = target.rsplit('.', 1)
1560-
except (TypeError, ValueError):
1561-
raise TypeError("Need a valid target to patch. You supplied: %r" %
1562-
(target,))
1560+
except (TypeError, ValueError, AttributeError):
1561+
raise TypeError(
1562+
f"Need a valid target to patch. You supplied: {target!r}")
15631563
getter = lambda: _importer(target)
15641564
return getter, attribute
15651565

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)