Coverage for tests/test_datetime_custom_encoder.py: 100%
37 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-12-04 08:29 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-12-04 08:29 +0000
1from datetime import datetime, timezone 1nopqrst
3from fastapi import FastAPI 1nopqrst
4from fastapi.testclient import TestClient 1nopqrst
5from pydantic import BaseModel 1nopqrst
7from .utils import needs_pydanticv1, needs_pydanticv2 1nopqrst
10@needs_pydanticv2 1nopqrst
11def test_pydanticv2(): 1nopqrst
12 from pydantic import field_serializer 1abcdefg
14 class ModelWithDatetimeField(BaseModel): 1abcdefg
15 dt_field: datetime 1abcdefg
17 @field_serializer("dt_field") 1abcdefg
18 def serialize_datetime(self, dt_field: datetime): 1abcdefg
19 return dt_field.replace(microsecond=0, tzinfo=timezone.utc).isoformat() 1abcdefg
21 app = FastAPI() 1abcdefg
22 model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8)) 1abcdefg
24 @app.get("/model", response_model=ModelWithDatetimeField) 1abcdefg
25 def get_model(): 1abcdefg
26 return model 1abcdefg
28 client = TestClient(app) 1abcdefg
29 with client: 1abcdefg
30 response = client.get("/model") 1abcdefg
31 assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"} 1abcdefg
34# TODO: remove when deprecating Pydantic v1
35@needs_pydanticv1 1nopqrst
36def test_pydanticv1(): 1nopqrst
37 class ModelWithDatetimeField(BaseModel): 1hijklm
38 dt_field: datetime 1hijklm
40 class Config: 1hijklm
41 json_encoders = { 1hijklm
42 datetime: lambda dt: dt.replace(
43 microsecond=0, tzinfo=timezone.utc
44 ).isoformat()
45 }
47 app = FastAPI() 1hijklm
48 model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8)) 1hijklm
50 @app.get("/model", response_model=ModelWithDatetimeField) 1hijklm
51 def get_model(): 1hijklm
52 return model 1hijklm
54 client = TestClient(app) 1hijklm
55 with client: 1hijklm
56 response = client.get("/model") 1hijklm
57 assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"} 1hijklm