Files
WebApi/webapi/imports/schemas/classify.py
T

77 lines
2.6 KiB
Python

"""Classifies pydantic validation errors into a few report categories using
only each error's `type` and message, so no per-field rules are needed."""
from dataclasses import dataclass
from enum import Enum
from typing import Any
class ErrorCategory(str, Enum):
MISSING = "missing"
OUT_OF_CATALOG = "out_of_catalog"
TYPE_INVALID = "type_invalid"
UNKNOWN = "unknown"
_BY_PYDANTIC_TYPE: dict[str, ErrorCategory] = {
"missing": ErrorCategory.MISSING,
"enum": ErrorCategory.OUT_OF_CATALOG,
"int_parsing": ErrorCategory.TYPE_INVALID,
"int_type": ErrorCategory.TYPE_INVALID,
"float_parsing": ErrorCategory.TYPE_INVALID,
"float_type": ErrorCategory.TYPE_INVALID,
"bool_parsing": ErrorCategory.TYPE_INVALID,
"bool_type": ErrorCategory.TYPE_INVALID,
"date_parsing": ErrorCategory.TYPE_INVALID,
"date_type": ErrorCategory.TYPE_INVALID,
"datetime_parsing": ErrorCategory.TYPE_INVALID,
"datetime_type": ErrorCategory.TYPE_INVALID,
"string_type": ErrorCategory.TYPE_INVALID,
"string_too_long": ErrorCategory.TYPE_INVALID,
"string_pattern_mismatch": ErrorCategory.TYPE_INVALID,
}
_BY_MESSAGE_SUBSTRING: tuple[tuple[str, ErrorCategory], ...] = (
("no está en el catálogo", ErrorCategory.OUT_OF_CATALOG),
("es requerido", ErrorCategory.MISSING),
("required", ErrorCategory.MISSING),
)
@dataclass(frozen=True)
class ValidationError:
field: str
category: ErrorCategory
message: str
raw_value: Any = None
def classify_error(error: dict) -> ValidationError:
"""`error` is one entry of pydantic's `ValidationError.errors()`."""
loc = error.get("loc") or ()
field = str(loc[0]) if loc else "<entre campos>"
etype = error.get("type", "")
# pydantic prefixes errors raised inside validators with "Value error, ",
# which is noise in the report.
message = str(error.get("msg", "")).removeprefix("Value error, ")
raw_value = error.get("input")
category = _BY_PYDANTIC_TYPE.get(etype)
if category is None:
category = _classify_by_message(message, etype)
return ValidationError(field=field, category=category, message=message, raw_value=raw_value)
def _classify_by_message(message: str, etype: str) -> ErrorCategory:
lowered = message.lower()
for fragment, mapped in _BY_MESSAGE_SUBSTRING:
if fragment in lowered:
return mapped
# "value_error" is what pydantic reports for errors raised by our own
# validators (e.g. a bad date string). If it is not a missing value, it
# is almost always a format problem.
if etype == "value_error":
return ErrorCategory.TYPE_INVALID
return ErrorCategory.UNKNOWN