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