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

1from datetime import datetime, timezone 1mnopqr

2 

3from fastapi import FastAPI 1mnopqr

4from fastapi.testclient import TestClient 1mnopqr

5from pydantic import BaseModel 1mnopqr

6 

7from .utils import needs_pydanticv1, needs_pydanticv2 1mnopqr

8 

9 

10@needs_pydanticv2 1mnopqr

11def test_pydanticv2(): 1mnopqr

12 from pydantic import field_serializer 1abcdef

13 

14 class ModelWithDatetimeField(BaseModel): 1abcdef

15 dt_field: datetime 1abcdef

16 

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

20 

21 app = FastAPI() 1abcdef

22 model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8)) 1abcdef

23 

24 @app.get("/model", response_model=ModelWithDatetimeField) 1abcdef

25 def get_model(): 1abcdef

26 return model 1abcdef

27 

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

32 

33 

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

39 

40 class Config: 1ghijkl

41 json_encoders = { 1ghijkl

42 datetime: lambda dt: dt.replace( 

43 microsecond=0, tzinfo=timezone.utc 

44 ).isoformat() 

45 } 

46 

47 app = FastAPI() 1ghijkl

48 model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8)) 1ghijkl

49 

50 @app.get("/model", response_model=ModelWithDatetimeField) 1ghijkl

51 def get_model(): 1ghijkl

52 return model 1ghijkl

53 

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