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

1from datetime import datetime, timezone 1abcde

2 

3from fastapi import FastAPI 1abcde

4from fastapi.testclient import TestClient 1abcde

5from pydantic import BaseModel 1abcde

6 

7from .utils import needs_pydanticv1, needs_pydanticv2 1abcde

8 

9 

10@needs_pydanticv2 1abcde

11def test_pydanticv2(): 1abcde

12 from pydantic import field_serializer 1abcde

13 

14 class ModelWithDatetimeField(BaseModel): 1abcde

15 dt_field: datetime 1abcde

16 

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

20 

21 app = FastAPI() 1abcde

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

23 

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

25 def get_model(): 1abcde

26 return model 1abcde

27 

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

32 

33 

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

39 

40 class Config: 1abcde

41 json_encoders = { 1abcde

42 datetime: lambda dt: dt.replace( 

43 microsecond=0, tzinfo=timezone.utc 

44 ).isoformat() 

45 } 

46 

47 app = FastAPI() 1abcde

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

49 

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

51 def get_model(): 1abcde

52 return model 1abcde

53 

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