Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
bpo-41403: Improve error message for invalid mock target
  • Loading branch information
iritkatriel committed Jan 23, 2022
commit d7d4e0b0b65101247275179dd88cf8a74b71f0b0
2 changes: 1 addition & 1 deletion Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1589,7 +1589,7 @@ def stop(self):
def _get_target(target):
try:
target, attribute = target.rsplit('.', 1)
except (TypeError, ValueError):
except (TypeError, ValueError, AttributeError):
raise TypeError("Need a valid target to patch. You supplied: %r" %
(target,))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
raise TypeError("Need a valid target to patch. You supplied: %r" %
(target,))
raise TypeError(f"Need a valid target to patch. You supplied: {target}")

since there is a change of nearby lines anyway. Plus, "b'%r' is deprecated, but will not be removed during the 3.x series" in the docs.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be {target!r} I suppose?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, yes. I was optimistic seeing string-only nature of target:

`target` should be a string in the form `'package.module.ClassName'`. The

Like, once it was an object requiring some special formatting but now it's just a string. However, I forgot that %r additionally escapes non-ascii code points.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, also this bpo is about the case where the error is that you passed in some non-string object.

return partial(pkgutil.resolve_name, target), attribute
Expand Down
9 changes: 7 additions & 2 deletions Lib/unittest/test/testmock/testpatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down