Skip to content

Commit

Permalink
fix(app): fix error handling for invalid timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
osoken committed Mar 24, 2024
1 parent 9499b42 commit 5050d87
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
13 changes: 8 additions & 5 deletions birdxplorer/routers/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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:
Expand Down
5 changes: 5 additions & 0 deletions tests/routers/test_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 5050d87

Please sign in to comment.