Skip to content

Commit

Permalink
Complete error signature of _InValidator (#951)
Browse files Browse the repository at this point in the history
The docstring of _in() says the ValueError would contain these, however
it didn't. Adding said arguments enables uniform processing of
ValueErrors raised by validators. One might for example want to extract
the attr.name and the value that raised the error to show a custom, more
user-friendly error message.
  • Loading branch information
iron3oxide committed Jun 13, 2022
1 parent 985e8ef commit 2257a0c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
3 changes: 3 additions & 0 deletions changelog.d/951.change.rst
@@ -0,0 +1,3 @@
The error signature of _InValidator has been completed,
it now includes the attribute,
options and value as proclaimed in the docstring of _in().
5 changes: 4 additions & 1 deletion src/attr/validators.py
Expand Up @@ -299,7 +299,10 @@ def __call__(self, inst, attr, value):
raise ValueError(
"'{name}' must be in {options!r} (got {value!r})".format(
name=attr.name, options=self.options, value=value
)
),
attr,
self.options,
value,
)

def __repr__(self):
Expand Down
14 changes: 12 additions & 2 deletions tests/test_validators.py
Expand Up @@ -471,7 +471,12 @@ def test_fail(self):
a = simple_attr("test")
with pytest.raises(ValueError) as e:
v(None, a, None)
assert ("'test' must be in [1, 2, 3] (got None)",) == e.value.args
assert (
"'test' must be in [1, 2, 3] (got None)",
a,
[1, 2, 3],
None,
) == e.value.args

def test_fail_with_string(self):
"""
Expand All @@ -482,7 +487,12 @@ def test_fail_with_string(self):
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
assert (
"'test' must be in 'abc' (got None)",
a,
"abc",
None,
) == e.value.args

def test_repr(self):
"""
Expand Down

0 comments on commit 2257a0c

Please sign in to comment.