Skip to content

Commit

Permalink
Merge pull request #35 from stas/store_arg_name
Browse files Browse the repository at this point in the history
Store the argument name inside the exception object.
  • Loading branch information
sloria committed Mar 20, 2015
2 parents 03a0369 + 14abf43 commit c30cb7f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
6 changes: 6 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ def test_validated(self):
with pytest.raises(ValidationError):
arg.validated('foo', 32)

def test_validated_stores_the_arg_name(self):
arg = Arg(validate=lambda t: False)
with pytest.raises(ValidationError) as excinfo:
arg.validated('our_arg_name', True)
assert 'our_arg_name' == excinfo.value.arg_name

def test_validated_with_nonascii_input(self):
arg = Arg(validate=lambda t: False)
text = u'øˆ∆´ƒº'
Expand Down
13 changes: 7 additions & 6 deletions webargs/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,10 @@ class ValidationError(WebargsError):
Store status_code and additonal data.
"""
def __init__(self, error, status_code=400, **data):
def __init__(self, error, status_code=400, arg_name=None, **data):
self.message = text_type(error)
self.status_code = status_code
self.arg_name = arg_name
self.data = data
super(ValidationError, self).__init__(self.message)

Expand Down Expand Up @@ -220,20 +221,20 @@ def _validate(self, name, value):
__type_map__.get(type(ret), type(ret).__name__)
)
if ret is None and self.type in __non_nullable_types__:
raise ValidationError(self.error or msg)
raise ValidationError(self.error or msg, arg_name=name)

try:
ret = self.type(ret)
except (ValueError, TypeError):
raise ValidationError(self.error or msg)
raise ValidationError(self.error or msg, arg_name=name)

# Then call validation functions
for validator in self.validators:
if validator(ret) is False:
msg = u'Validator {0}({1}) is not True'.format(
validator.__name__, ret
)
raise ValidationError(self.error or msg)
raise ValidationError(self.error or msg, arg_name=name)

if self._has_nesting:
# Filter out extra args
Expand Down Expand Up @@ -363,7 +364,7 @@ def parse_arg(self, name, argobj, req, locations=None):
value = argobj.default
if argobj.required:
raise RequiredArgMissingError(
'Required parameter "{0}" not found.'.format(name)
'Required parameter "{0}" not found.'.format(name), arg_name=name
)
return value

Expand Down Expand Up @@ -403,7 +404,7 @@ def parse(self, argmap, req, locations=None, validate=None, force_all=False):
msg = u'Validator {0}({1}) is not True'.format(
validator.__name__, parsed
)
raise ValidationError(self.error or msg)
raise ValidationError(self.error or msg, arg_name=argname)
except ValidationError as error:
if self.error_callback:
self.error_callback(error)
Expand Down

0 comments on commit c30cb7f

Please sign in to comment.