-
-
Notifications
You must be signed in to change notification settings - Fork 837
Expand file tree
/
Copy pathtest_field.py
More file actions
91 lines (62 loc) · 2.37 KB
/
test_field.py
File metadata and controls
91 lines (62 loc) · 2.37 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
from decimal import Decimal
from typing import Literal
import pytest
from pydantic import ValidationError
from sqlmodel import Field, SQLModel
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_regex():
with pytest.warns(DeprecationWarning, match="The `regex` parameter is deprecated"):
class DateModel(SQLModel):
date_1: str = Field(regex=r"^\d{2}-\d{2}-\d{4}$")
DateModel(date_1="12-31-2024")
with pytest.raises(ValidationError):
DateModel(date_1="incorrect")
def test_pattern():
class DateModel(SQLModel):
date_1: str = Field(pattern=r"^\d{2}-\d{2}-\d{4}$")
DateModel(date_1="12-31-2024")
with pytest.raises(ValidationError):
DateModel(date_1="incorrect")
def test_pattern_via_schema_extra():
with pytest.warns(
UserWarning,
match="Pass `pattern` parameter directly to Field instead of passing it via `schema_extra`",
):
class DateModel(SQLModel):
date_1: str = Field(schema_extra={"pattern": r"^\d{2}-\d{2}-\d{4}$"})
with pytest.raises(ValidationError):
DateModel(date_1="incorrect")