From 5050d877078e1a5cff9d020d7dd33cfe6212bd20 Mon Sep 17 00:00:00 2001 From: osoken Date: Sun, 24 Mar 2024 22:39:30 +0900 Subject: [PATCH] fix(app): fix error handling for invalid timestamp --- birdxplorer/routers/data.py | 13 ++++++++----- tests/routers/test_data.py | 5 +++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/birdxplorer/routers/data.py b/birdxplorer/routers/data.py index d887c0d..20327a2 100644 --- a/birdxplorer/routers/data.py +++ b/birdxplorer/routers/data.py @@ -2,7 +2,7 @@ from typing import List, Union from dateutil.parser import parse as dateutil_parse -from fastapi import APIRouter, Query +from fastapi import APIRouter, HTTPException, Query from ..models import ( BaseModel, @@ -29,10 +29,13 @@ def str_to_twitter_timestamp(s: str) -> TwitterTimestamp: return TwitterTimestamp.from_int(int(s)) except ValueError: pass - tmp = dateutil_parse(s) - if tmp.tzinfo is None: - tmp = tmp.replace(tzinfo=timezone.utc) - return TwitterTimestamp.from_int(int(tmp.timestamp() * 1000)) + try: + tmp = dateutil_parse(s) + if tmp.tzinfo is None: + tmp = tmp.replace(tzinfo=timezone.utc) + return TwitterTimestamp.from_int(int(tmp.timestamp() * 1000)) + except ValueError: + raise HTTPException(status_code=422, detail=f"Invalid TwitterTimestamp string: {s}") def ensure_twitter_timestamp(t: Union[str, TwitterTimestamp]) -> TwitterTimestamp: diff --git a/tests/routers/test_data.py b/tests/routers/test_data.py index 7a2af1e..21ef02e 100644 --- a/tests/routers/test_data.py +++ b/tests/routers/test_data.py @@ -76,3 +76,8 @@ def test_posts_get_created_at_end_filter_accepts_integer(client: TestClient, pos assert response.status_code == 200 res_json = response.json() assert res_json == {"data": [json.loads(post_samples[i].model_dump_json()) for i in (0, 1)]} + + +def test_posts_get_timestamp_out_of_range(client: TestClient, post_samples: List[Post]) -> None: + response = client.get("/api/v1/data/posts/?createdAtStart=1153921700&createdAtEnd=1153921700") + assert response.status_code == 422