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
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-13 05:19 +0000
1from typing import Annotated 1klabmcndoefghij
3import pytest 1klabmcndoefghij
4from annotated_types import Ge 1klabmcndoefghij
5from pydantic import BaseModel, Field 1klabmcndoefghij
7from fast_depends import inject 1klabmcndoefghij
8from fast_depends.exceptions import ValidationError 1klabmcndoefghij
9from tests.marks import pydanticV2 1klabmcndoefghij
12def test_pydantic_types_casting(): 1klabmcndoefghij
13 class SomeModel(BaseModel): 1klabmcndoefghij
14 field: int 1klabmcndoe
16 @inject 1klabmcndoefghij
17 def some_func(a: SomeModel): 1klabmcndoefghij
18 return a.field 1klabmcndoefghij
20 assert isinstance(some_func({"field": "31"}), int) 1klabmcndoefghij
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
29 @inject 1klabmcndoefghij
30 def another_func(a=Field(..., alias="b")) -> float: 1klabmcndoefghij
31 assert isinstance(a, str) 1klabmcndoefghij
32 return a 1klabmcndoefghij
34 assert isinstance(some_func(b="2", c=3), float) 1klabmcndoefghij
35 assert isinstance(another_func(b="2"), float) 1klabmcndoefghij
38def test_annotated(): 1klabmcndoefghij
39 A = Annotated[int, Field(..., alias="b")] 1klabmcndoefghij
41 @inject 1klabmcndoefghij
42 def some_func(a: A) -> float: 1klabmcndoefghij
43 assert isinstance(a, int) 1klabmcndoefghij
44 return a 1klabmcndoefghij
46 assert isinstance(some_func(b="2"), float) 1klabmcndoefghij
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
55 for i in simple_func("1"): 1klabmcndoefghij
56 assert i == 1 1klabmcndoefghij
59def test_validation_error(): 1klabmcndoefghij
60 @inject 1klabmcndoefghij
61 def some_func(a, b: str = Field(..., max_length=1)): 1klabmcndoefghij
62 return 1 1klabmcndoefghij
64 assert some_func(1, "a") == 1 1klabmcndoefghij
66 with pytest.raises(ValidationError): 1klabmcndoefghij
67 assert some_func() 1klabmcndoefghij
69 with pytest.raises(ValidationError): 1klabmcndoefghij
70 assert some_func(1, "dsdas") 1klabmcndoefghij
73@pydanticV2 1klabmcndoefghij
74def test_multi_annotated(): 1klabmcndoefghij
75 from pydantic.functional_validators import AfterValidator 1abcdefghij
77 @inject() 1abcdefghij
78 def f(a: Annotated[int, Ge(10), AfterValidator(lambda x: x + 10)]) -> int: 1abcdefghij
79 return a 1abcdefghij
81 with pytest.raises(ValidationError): 1abcdefghij
82 f(1) 1abcdefghij
84 assert f(10) == 20 1abcdefghij