Browse Source

Add missing RequestValidationError.__str__

Fixes #12125.
pull/12972/head
Tamir Duberstein 4 months ago
parent
commit
357e70aa50
Failed to extract signature
  1. 24
      fastapi/exceptions.py
  2. 19
      tests/test_tutorial/test_handling_errors/test_tutorial004.py

24
fastapi/exceptions.py

@ -153,6 +153,24 @@ class ValidationException(Exception):
def errors(self) -> Sequence[Any]:
return self._errors
def __str__(self) -> str:
# Adapted from https://github.com/pydantic/pydantic/blob/c326748b/pydantic/v1/error_wrappers.py#L70-L76.
def display_errors(errors: Sequence[Any]) -> str:
return "\n".join(
f'{_display_error_loc(e)}\n {e["msg"]} (type={e["type"]})'
for e in errors
)
def _display_error_loc(error: Any) -> str:
return " -> ".join(str(e) for e in error["loc"])
errors = self.errors()
no_errors = len(errors)
return (
f'{no_errors} validation error{"" if no_errors == 1 else "s"}\n'
f'{display_errors(errors)}'
)
class RequestValidationError(ValidationException):
def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:
@ -168,9 +186,3 @@ class ResponseValidationError(ValidationException):
def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:
super().__init__(errors)
self.body = body
def __str__(self) -> str:
message = f"{len(self._errors)} validation errors:\n"
for err in self._errors:
message += f" {err}\n"
return message

19
tests/test_tutorial/test_handling_errors/test_tutorial004.py

@ -1,3 +1,4 @@
from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE
from fastapi.testclient import TestClient
from docs_src.handling_errors.tutorial004 import app
@ -8,17 +9,19 @@ client = TestClient(app)
def test_get_validation_error():
response = client.get("/items/foo")
assert response.status_code == 400, response.text
# TODO: remove when deprecating Pydantic v1
if PYDANTIC_VERSION_MINOR_TUPLE < (2, 0):
assert (
# TODO: remove when deprecating Pydantic v1
"path -> item_id" in response.text
or "'loc': ('path', 'item_id')" in response.text
response.text
== """1 validation error
path -> item_id
value is not a valid integer (type=type_error.integer)"""
)
else:
assert (
# TODO: remove when deprecating Pydantic v1
"value is not a valid integer" in response.text
or "Input should be a valid integer, unable to parse string as an integer"
in response.text
response.text
== """1 validation error
path -> item_id
Input should be a valid integer, unable to parse string as an integer (type=int_parsing)"""
)

Loading…
Cancel
Save