-
-
Notifications
You must be signed in to change notification settings - Fork 853
Expand file tree
/
Copy pathtest_field.py
More file actions
262 lines (185 loc) · 7.34 KB
/
test_field.py
File metadata and controls
262 lines (185 loc) · 7.34 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
from decimal import Decimal
from typing import Any, Literal
import pytest
from pydantic import ValidationError
from sqlmodel import Field, Session, SQLModel, create_engine
from sqlmodel._compat import PYDANTIC_MINOR_VERSION
def test_decimal():
class Model(SQLModel):
dec: Decimal = Field(max_digits=4, decimal_places=2)
Model(dec=Decimal("3.14"))
Model(dec=Decimal("69.42"))
with pytest.raises(ValidationError):
Model(dec=Decimal("3.142"))
with pytest.raises(ValidationError):
Model(dec=Decimal("0.069"))
with pytest.raises(ValidationError):
Model(dec=Decimal("420"))
def test_discriminator():
# Example adapted from
# [Pydantic docs](https://pydantic-docs.helpmanual.io/usage/types/#discriminated-unions-aka-tagged-unions):
class Cat(SQLModel):
pet_type: Literal["cat"]
meows: int
class Dog(SQLModel):
pet_type: Literal["dog"]
barks: float
class Lizard(SQLModel):
pet_type: Literal["reptile", "lizard"]
scales: bool
class Model(SQLModel):
pet: Cat | Dog | Lizard = Field(..., discriminator="pet_type")
n: int
Model(pet={"pet_type": "dog", "barks": 3.14}, n=1) # type: ignore[arg-type]
with pytest.raises(ValidationError):
Model(pet={"pet_type": "dog"}, n=1) # type: ignore[arg-type]
def test_repr():
class Model(SQLModel):
id: int | None = Field(primary_key=True)
foo: str = Field(repr=False)
instance = Model(id=123, foo="bar")
assert "foo=" not in repr(instance)
def test_strict_true():
class Model(SQLModel):
id: int | None = Field(default=None, primary_key=True)
val: int
val_strict: int = Field(strict=True)
class ModelDB(Model, table=True):
pass
Model(val=123, val_strict=456)
Model(val="123", val_strict=456)
with pytest.raises(ValidationError):
Model(val=123, val_strict="456")
engine = create_engine("sqlite://", echo=True)
SQLModel.metadata.create_all(engine)
model = ModelDB(val=123, val_strict=456)
with Session(engine) as session:
session.add(model)
session.commit()
session.refresh(model)
assert model.val == 123
assert model.val_strict == 456
def test_strict_table_model():
class Model(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
val_strict: int = Field(strict=True)
engine = create_engine("sqlite://", echo=True)
SQLModel.metadata.create_all(engine)
model = Model(val_strict=456)
with Session(engine) as session:
session.add(model)
session.commit()
session.refresh(model)
assert model.val_strict == 456
@pytest.mark.parametrize("strict", [None, False])
def test_strict_false(strict: int | None):
class Model(SQLModel):
val: int = Field(strict=strict)
Model(val=123)
Model(val="123")
def test_strict_via_schema_extra(): # Current workaround. Remove after some time
with pytest.warns(
DeprecationWarning,
match="Pass `strict` parameter directly to Field instead of passing it via `schema_extra`",
):
class Model(SQLModel):
val: int
val_strict: int = Field(schema_extra={"strict": True})
Model(val=123, val_strict=456)
Model(val="123", val_strict=456)
with pytest.raises(ValidationError):
Model(val=123, val_strict="456")
def test_examples():
class Model(SQLModel):
name: str = Field(examples=["Alice", "Bob"])
model_schema = Model.model_json_schema()
assert model_schema["properties"]["name"]["examples"] == ["Alice", "Bob"]
def test_examples_via_schema_extra(): # Current workaround. Remove after some time
with pytest.warns(
DeprecationWarning,
match="Pass `examples` parameter directly to Field instead of passing it via `schema_extra`",
):
class Model(SQLModel):
name: str = Field(schema_extra={"examples": ["Alice", "Bob"]})
model_schema = Model.model_json_schema()
assert model_schema["properties"]["name"]["examples"] == ["Alice", "Bob"]
def test_deprecated():
class Model(SQLModel):
old_field: str = Field(deprecated=True)
another_old_field: str = Field(deprecated="This field is deprecated")
model_schema = Model.model_json_schema()
assert model_schema["properties"]["old_field"]["deprecated"] is True
assert model_schema["properties"]["another_old_field"]["deprecated"] is True
def test_deprecated_via_schema_extra(): # Current workaround. Remove after some time
with pytest.warns(
DeprecationWarning,
match="Pass `deprecated` parameter directly to Field instead of passing it via `schema_extra`",
):
class Model(SQLModel):
old_field: str = Field(schema_extra={"deprecated": True})
another_old_field: str = Field(
schema_extra={"deprecated": "This field is deprecated"}
)
model_schema = Model.model_json_schema()
assert model_schema["properties"]["old_field"]["deprecated"] is True
assert model_schema["properties"]["another_old_field"]["deprecated"] is True
@pytest.mark.skipif(
PYDANTIC_MINOR_VERSION < (2, 12),
reason="exlude_if requires Pydantic 2.12+",
)
def test_exclude_if():
def is_empty_string(value: Any) -> bool:
return value == ""
class Model(SQLModel):
name: str = Field(exclude_if=is_empty_string)
age: int
model1 = Model(name="Alice", age=30)
model2 = Model(name="", age=25)
dict1 = model1.model_dump()
dict2 = model2.model_dump()
assert "name" in dict1
assert dict1["name"] == "Alice"
assert "name" not in dict2
@pytest.mark.skipif(
PYDANTIC_MINOR_VERSION < (2, 12),
reason="exlude_if requires Pydantic 2.12+",
)
def test_exclude_if_via_schema_extra():
def is_empty_string(value: Any) -> bool:
return value == ""
with pytest.warns(
DeprecationWarning,
match="Pass `exclude_if` parameter directly to Field instead of passing it via `schema_extra`",
):
class Model(SQLModel):
name: str = Field(schema_extra={"exclude_if": is_empty_string})
age: int
model1 = Model(name="Alice", age=30)
model2 = Model(name="", age=25)
dict1 = model1.model_dump()
dict2 = model2.model_dump()
assert "name" in dict1
assert dict1["name"] == "Alice"
assert "name" not in dict2
def test_field_title_generator():
def upper(value: str, _: Any) -> str:
return value.upper()
class Model(SQLModel):
name: str = Field(field_title_generator=upper)
age: int
model_schema = Model.model_json_schema()
assert model_schema["properties"]["name"]["title"] == "NAME"
assert model_schema["properties"]["age"]["title"] == "Age"
def test_field_title_generator_via_schema_extra():
def upper(value: str, _: Any) -> str:
return value.upper()
with pytest.warns(
DeprecationWarning,
match="Pass `field_title_generator` parameter directly to Field instead of passing it via `schema_extra`",
):
class Model(SQLModel):
name: str = Field(schema_extra={"field_title_generator": upper})
age: int
model_schema = Model.model_json_schema()
assert model_schema["properties"]["name"]["title"] == "NAME"
assert model_schema["properties"]["age"]["title"] == "Age"