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:
OCHIAI, Gouji
2016-02-19 19:13:57 +09:00
parent 85d2fa51fe
commit 96d69de5d2
2 changed files with 17 additions and 2 deletions

View File

@@ -179,13 +179,15 @@ class Invalid(Exception):
return str(self.pos)
return str(self.node.name)
def asdict(self, translate=None):
def asdict(self, translate=None, separator='; '):
""" Return a dictionary containing a basic
(non-language-translated) error report for this exception.
If ``translate`` is supplied, it must be a callable taking a
translation string as its sole argument and returning a localized,
interpolated string.
If ``separator`` is supplied, error messages are joined with that.
"""
paths = self.paths()
errors = {}
@@ -198,7 +200,12 @@ class Invalid(Exception):
keyname and keyparts.append(keyname)
if translate:
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
def __str__(self):

View File

@@ -136,6 +136,14 @@ class TestInvalid(unittest.TestCase):
result,
{'': ("Number 1 must be lower than number 2; "
"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):
from colander import Positional