Skip to content

Commit

Permalink
fix ValidationError.json()
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelcolvin committed Oct 22, 2019
1 parent f5cde39 commit 9e91157
Show file tree
Hide file tree
Showing 6 changed files with 9 additions and 2 deletions.
1 change: 1 addition & 0 deletions changes/922-samuelcolvin.md
@@ -0,0 +1 @@
Fix JSON serialization errors on `ValidationError.json()` by using `pydantic_encoder`
3 changes: 2 additions & 1 deletion pydantic/error_wrappers.py
@@ -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:
Expand Down Expand Up @@ -53,7 +54,7 @@ def errors(self) -> List[Dict[str, Any]]:
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()
Expand Down
2 changes: 2 additions & 0 deletions tests/test_main.py
Expand Up @@ -443,6 +443,7 @@ class Model(BaseModel):
'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)])
Expand All @@ -464,6 +465,7 @@ class Model(BaseModel):
'type': 'value_error.const',
},
]
assert exc_info.value.json().startswith('[')


def test_const_validation_json_serializable():
Expand Down
1 change: 1 addition & 0 deletions tests/test_networks.py
Expand Up @@ -247,6 +247,7 @@ class Model(BaseModel):
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():
Expand Down
1 change: 1 addition & 0 deletions tests/test_types.py
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion tests/test_types_payment_card_number.py
Expand Up @@ -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('[')

0 comments on commit 9e91157

Please sign in to comment.