optional join separator for error messages on colander.Invalid:asdict
, if not supplied return list of string instead of single string.
This commit is contained in:
@@ -179,13 +179,15 @@ class Invalid(Exception):
|
|||||||
return str(self.pos)
|
return str(self.pos)
|
||||||
return str(self.node.name)
|
return str(self.node.name)
|
||||||
|
|
||||||
def asdict(self, translate=None):
|
def asdict(self, translate=None, separator='; '):
|
||||||
""" Return a dictionary containing a basic
|
""" Return a dictionary containing a basic
|
||||||
(non-language-translated) error report for this exception.
|
(non-language-translated) error report for this exception.
|
||||||
|
|
||||||
If ``translate`` is supplied, it must be a callable taking a
|
If ``translate`` is supplied, it must be a callable taking a
|
||||||
translation string as its sole argument and returning a localized,
|
translation string as its sole argument and returning a localized,
|
||||||
interpolated string.
|
interpolated string.
|
||||||
|
|
||||||
|
If ``separator`` is supplied, error messages are joined with that.
|
||||||
"""
|
"""
|
||||||
paths = self.paths()
|
paths = self.paths()
|
||||||
errors = {}
|
errors = {}
|
||||||
@@ -198,7 +200,12 @@ class Invalid(Exception):
|
|||||||
keyname and keyparts.append(keyname)
|
keyname and keyparts.append(keyname)
|
||||||
if translate:
|
if translate:
|
||||||
msgs = [translate(msg) for msg in msgs]
|
msgs = [translate(msg) for msg in msgs]
|
||||||
errors['.'.join(keyparts)] = '; '.join(interpolate(msgs))
|
msgs = interpolate(msgs)
|
||||||
|
if separator:
|
||||||
|
msgs = separator.join(msgs)
|
||||||
|
else:
|
||||||
|
msgs = list(msgs)
|
||||||
|
errors['.'.join(keyparts)] = msgs
|
||||||
return errors
|
return errors
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
|
@@ -136,6 +136,14 @@ class TestInvalid(unittest.TestCase):
|
|||||||
result,
|
result,
|
||||||
{'': ("Number 1 must be lower than number 2; "
|
{'': ("Number 1 must be lower than number 2; "
|
||||||
"They can't be the same, either")})
|
"They can't be the same, either")})
|
||||||
|
try:
|
||||||
|
schema.deserialize(dict(number1=2, number2=2))
|
||||||
|
except c.Invalid as e:
|
||||||
|
result = e.asdict(separator=None)
|
||||||
|
self.assertEqual(
|
||||||
|
result,
|
||||||
|
{'': ["Number 1 must be lower than number 2",
|
||||||
|
"They can't be the same, either"]})
|
||||||
|
|
||||||
def test___str__(self):
|
def test___str__(self):
|
||||||
from colander import Positional
|
from colander import Positional
|
||||||
|
Reference in New Issue
Block a user