Coverage for tests/pydantic_specific/sync/test_cast.py: 100%

57 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-13 05:19 +0000

1from typing import Annotated 1klabmcndoefghij

2 

3import pytest 1klabmcndoefghij

4from annotated_types import Ge 1klabmcndoefghij

5from pydantic import BaseModel, Field 1klabmcndoefghij

6 

7from fast_depends import inject 1klabmcndoefghij

8from fast_depends.exceptions import ValidationError 1klabmcndoefghij

9from tests.marks import pydanticV2 1klabmcndoefghij

10 

11 

12def test_pydantic_types_casting(): 1klabmcndoefghij

13 class SomeModel(BaseModel): 1klabmcndoefghij

14 field: int 1klabmcndoe

15 

16 @inject 1klabmcndoefghij

17 def some_func(a: SomeModel): 1klabmcndoefghij

18 return a.field 1klabmcndoefghij

19 

20 assert isinstance(some_func({"field": "31"}), int) 1klabmcndoefghij

21 

22 

23def test_pydantic_field_types_casting(): 1klabmcndoefghij

24 @inject 1klabmcndoefghij

25 def some_func(a: int = Field(..., alias="b")) -> float: 1klabmcndoefghij

26 assert isinstance(a, int) 1klabmcndoefghij

27 return a 1klabmcndoefghij

28 

29 @inject 1klabmcndoefghij

30 def another_func(a=Field(..., alias="b")) -> float: 1klabmcndoefghij

31 assert isinstance(a, str) 1klabmcndoefghij

32 return a 1klabmcndoefghij

33 

34 assert isinstance(some_func(b="2", c=3), float) 1klabmcndoefghij

35 assert isinstance(another_func(b="2"), float) 1klabmcndoefghij

36 

37 

38def test_annotated(): 1klabmcndoefghij

39 A = Annotated[int, Field(..., alias="b")] 1klabmcndoefghij

40 

41 @inject 1klabmcndoefghij

42 def some_func(a: A) -> float: 1klabmcndoefghij

43 assert isinstance(a, int) 1klabmcndoefghij

44 return a 1klabmcndoefghij

45 

46 assert isinstance(some_func(b="2"), float) 1klabmcndoefghij

47 

48 

49def test_generator(): 1klabmcndoefghij

50 @inject 1klabmcndoefghij

51 def simple_func(a: str) -> int: 1klabmcndoefghij

52 for _ in range(2): 1klabmcndoefghij

53 yield a 1klabmcndoefghij

54 

55 for i in simple_func("1"): 1klabmcndoefghij

56 assert i == 1 1klabmcndoefghij

57 

58 

59def test_validation_error(): 1klabmcndoefghij

60 @inject 1klabmcndoefghij

61 def some_func(a, b: str = Field(..., max_length=1)): 1klabmcndoefghij

62 return 1 1klabmcndoefghij

63 

64 assert some_func(1, "a") == 1 1klabmcndoefghij

65 

66 with pytest.raises(ValidationError): 1klabmcndoefghij

67 assert some_func() 1klabmcndoefghij

68 

69 with pytest.raises(ValidationError): 1klabmcndoefghij

70 assert some_func(1, "dsdas") 1klabmcndoefghij

71 

72 

73@pydanticV2 1klabmcndoefghij

74def test_multi_annotated(): 1klabmcndoefghij

75 from pydantic.functional_validators import AfterValidator 1abcdefghij

76 

77 @inject() 1abcdefghij

78 def f(a: Annotated[int, Ge(10), AfterValidator(lambda x: x + 10)]) -> int: 1abcdefghij

79 return a 1abcdefghij

80 

81 with pytest.raises(ValidationError): 1abcdefghij

82 f(1) 1abcdefghij

83 

84 assert f(10) == 20 1abcdefghij