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