From 1ecb848f8113cf04220a593a80de5024b8505d2c Mon Sep 17 00:00:00 2001 From: Friedrich Lindenberg Date: Wed, 17 Apr 2024 20:08:28 -0400 Subject: [PATCH 1/3] Handle pydantic validation errors. --- yente/app.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/yente/app.py b/yente/app.py index 033408ba..e896fcfc 100644 --- a/yente/app.py +++ b/yente/app.py @@ -4,6 +4,7 @@ from typing import AsyncGenerator, Dict, Type, Callable, Any, Coroutine, Union from contextlib import asynccontextmanager from elasticsearch import ApiError, TransportError +from pydantic import ValidationError from fastapi import FastAPI from fastapi import Request, Response from fastapi.middleware.cors import CORSMiddleware @@ -87,9 +88,16 @@ async def transport_error_handler(request: Request, exc: TransportError) -> Resp return JSONResponse(status_code=500, content={"detail": exc.message}) +async def validation_error_handler(request: Request, exc: ValidationError) -> Response: + log.warn(f"Validation error: {exc}") + body = {"detail": exc.title, "errors": exc.errors()} + return JSONResponse(status_code=400, content=body) + + HANDLERS: Dict[Union[Type[Exception], int], ExceptionHandler] = { ApiError: api_error_handler, TransportError: transport_error_handler, + ValidationError: validation_error_handler, } From 82f1d56232f68edda6e6af9a09698dcaccc04ed5 Mon Sep 17 00:00:00 2001 From: Friedrich Lindenberg Date: Wed, 17 Apr 2024 20:14:44 -0400 Subject: [PATCH 2/3] add test case --- tests/unit/test_reconcile.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/unit/test_reconcile.py b/tests/unit/test_reconcile.py index c7443cce..d4f69693 100644 --- a/tests/unit/test_reconcile.py +++ b/tests/unit/test_reconcile.py @@ -23,6 +23,12 @@ def test_reconcile_post(): assert res[0]["id"] == "Q18634850", res +def test_reconcile_invalid(): + queries = {"mutti": {"query": 37473874}} + resp = client.post("/reconcile/default", data={"queries": json.dumps(queries)}) + assert resp.status_code == 400, resp.text + + def test_reconcile_suggest_entity_no_prefix(): resp = client.get("/reconcile/default/suggest/entity") assert resp.status_code == 200, resp.text From a71872630287299db9a58c5d03113527f815e675 Mon Sep 17 00:00:00 2001 From: Friedrich Lindenberg Date: Wed, 17 Apr 2024 20:23:26 -0400 Subject: [PATCH 3/3] fix type error --- tests/unit/test_reconcile.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_reconcile.py b/tests/unit/test_reconcile.py index d4f69693..1a93e726 100644 --- a/tests/unit/test_reconcile.py +++ b/tests/unit/test_reconcile.py @@ -43,8 +43,9 @@ def test_reconcile_suggest_entity_prefix(): res = resp.json()["result"] assert len(res) > 0, res assert "Q7747" == res[0]["id"], res - name = ascii_text(res[0]["name"]).lower() - assert "vladimir" in name, name + name = ascii_text(res[0]["name"]) + assert name is not None, res + assert "vladimir" in name.lower(), name def test_reconcile_suggest_entity_prefix_dummy():