fix ValidationError.json() (#922)

This commit is contained in:
Samuel Colvin
2019-10-23 10:27:55 +01:00
committed by GitHub
parent 6b5adcc977
commit cb262daddd
6 changed files with 9 additions and 2 deletions
+1
View File
@@ -0,0 +1 @@
Fix JSON serialization errors on `ValidationError.json()` by using `pydantic_encoder`
+2 -1
View File
@@ -1,6 +1,7 @@
import json
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Sequence, Tuple, Type, Union
from .json import pydantic_encoder
from .utils import Representation
if TYPE_CHECKING:
@@ -53,7 +54,7 @@ class ValidationError(Representation, ValueError):
return self._error_cache
def json(self, *, indent: Union[None, int, str] = 2) -> str:
return json.dumps(self.errors(), indent=indent)
return json.dumps(self.errors(), indent=indent, default=pydantic_encoder)
def __str__(self) -> str:
errors = self.errors()
+2
View File
@@ -443,6 +443,7 @@ def test_const_list_with_wrong_value():
'type': 'value_error.const',
},
]
assert exc_info.value.json().startswith('[')
with pytest.raises(ValidationError) as exc_info:
Model(a=[SubModel(b=3), SubModel(b=1), SubModel(b=2)], b=[SubModel(b=3), SubModel(b=1)])
@@ -464,6 +465,7 @@ def test_const_list_with_wrong_value():
'type': 'value_error.const',
},
]
assert exc_info.value.json().startswith('[')
def test_const_validation_json_serializable():
+1
View File
@@ -247,6 +247,7 @@ def test_postgres_dsns():
with pytest.raises(ValidationError) as exc_info:
Model(a='http://example.org')
assert exc_info.value.errors()[0]['type'] == 'value_error.url.scheme'
assert exc_info.value.json().startswith('[')
def test_redis_dsns():
+1
View File
@@ -1270,6 +1270,7 @@ def test_decimal_validation(type_, value, result):
with pytest.raises(ValidationError) as exc_info:
model(foo=value)
assert exc_info.value.errors() == result
assert exc_info.value.json().startswith('[')
else:
assert model(foo=value).foo == result
+2 -1
View File
@@ -86,5 +86,6 @@ def test_valid():
],
)
def test_error_types(card_number: Any, error_message: str):
with pytest.raises(ValidationError, match=error_message):
with pytest.raises(ValidationError, match=error_message) as exc_info:
PaymentCard(card_number=card_number)
assert exc_info.value.json().startswith('[')