mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
fix ValidationError.json() (#922)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
Fix JSON serialization errors on `ValidationError.json()` by using `pydantic_encoder`
|
||||
@@ -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()
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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('[')
|
||||
|
||||
Reference in New Issue
Block a user