Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error for in_(a_string) with a non-string value #383

Merged
merged 4 commits into from
May 25, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
3 changes: 3 additions & 0 deletions changelog.d/383.change.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
``in_()`` validators now raise a ValueError with a useful message

This comment was marked as spam.

This comment was marked as spam.

even if the options are a string and the value is not a string.
By contrast, e.g. ``1 in "abc"`` raises an unhelpful TypeError.
7 changes: 6 additions & 1 deletion src/attr/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,12 @@ class _InValidator(object):
options = attrib()

def __call__(self, inst, attr, value):
if value not in self.options:
try:
in_options = value in self.options
except TypeError as e: # e.g. `1 in "abc"`
in_options = False

if not in_options:
raise ValueError(
"'{name}' must be in {options!r} (got {value!r})"
.format(name=attr.name, options=self.options, value=value)
Expand Down
13 changes: 13 additions & 0 deletions tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,19 @@ def test_fail(self):
"'test' must be in [1, 2, 3] (got None)",
) == e.value.args

def test_fail_with_string(self):
"""
Raise ValueError if the value is outside our options when the
options are specified as a string and the value is not a string.
"""
v = in_("abc")
a = simple_attr("test")
with pytest.raises(ValueError) as e:
v(None, a, None)
assert (
"'test' must be in 'abc' (got None)",
) == e.value.args

def test_repr(self):
"""
Returned validator has a useful `__repr__`.
Expand Down