-
-
Notifications
You must be signed in to change notification settings - Fork 845
Expand file tree
/
Copy pathtest_generic.py
More file actions
83 lines (70 loc) · 2.17 KB
/
test_generic.py
File metadata and controls
83 lines (70 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from typing import Generic, List, Optional, TypeVar
import pydantic
import pytest
from sqlmodel import SQLModel
from tests.conftest import needs_pydanticv2
# Example adapted from
# https://docs.pydantic.dev/2.10/concepts/models/#generic-models
DataT = TypeVar("DataT")
class DataModel(SQLModel):
numbers: List[int]
people: List[str]
class Response(SQLModel, Generic[DataT]):
data: Optional[DataT] = None
@needs_pydanticv2
@pytest.mark.parametrize(
["data_type", "data_value"],
[
(int, 1),
(str, "value"),
(DataModel, DataModel(numbers=[1, 2, 3], people=[])),
(DataModel, {"numbers": [1, 2, 3], "people": []}),
],
)
def test_valid_generics(data_type, data_value):
# Should be able to create a model without an error.
response = Response[data_type](data=data_value)
assert Response[data_type](**response.model_dump()) == response
@needs_pydanticv2
@pytest.mark.parametrize(
["data_type", "data_value", "error_loc", "error_type"],
[
(
str,
1,
("data",),
"string_type",
),
(
int,
"some-string",
("data",),
"int_parsing",
),
(
DataModel,
"some-string",
("data",),
"model_attributes_type",
),
(
DataModel,
{"numbers": [1, 2, "unexpected string"], "people": []},
("data", "numbers", 2),
"int_parsing",
),
],
)
def test_invalid_generics(data_type, data_value, error_loc, error_type):
with pytest.raises(pydantic.ValidationError) as raised:
Response[data_type](data=data_value)
[error_dict] = raised.value.errors()
assert error_dict["loc"] == error_loc
assert error_dict["type"] == error_type
@needs_pydanticv2
def test_generic_json_schema():
schema = Response[DataModel].model_json_schema()
# Should have referenced the schema in $defs
assert schema["properties"]["data"]["anyOf"][0] == {"$ref": "#/$defs/DataModel"}
# Schema in $defs should match DataModel's schema.
assert schema["$defs"]["DataModel"] == DataModel.model_json_schema()