Coverage for tests/test_pydantic/test_field.py: 100%
39 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-07 05:42 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-07 05:42 +0000
1from decimal import Decimal 1opqrstu
2from typing import Optional, Union 1opqrstu
4import pytest 1opqrstu
5from pydantic import ValidationError 1opqrstu
6from sqlmodel import Field, SQLModel 1opqrstu
7from typing_extensions import Literal 1opqrstu
10def test_decimal(): 1opqrstu
11 class Model(SQLModel): 1hijklmn
12 dec: Decimal = Field(max_digits=4, decimal_places=2) 1hijklmn
14 Model(dec=Decimal("3.14")) 1hijklmn
15 Model(dec=Decimal("69.42")) 1hijklmn
17 with pytest.raises(ValidationError): 1hijklmn
18 Model(dec=Decimal("3.142")) 1hijklmn
19 with pytest.raises(ValidationError): 1hijklmn
20 Model(dec=Decimal("0.069")) 1hijklmn
21 with pytest.raises(ValidationError): 1hijklmn
22 Model(dec=Decimal("420")) 1hijklmn
25def test_discriminator(): 1opqrstu
26 # Example adapted from
27 # [Pydantic docs](https://pydantic-docs.helpmanual.io/usage/types/#discriminated-unions-aka-tagged-unions):
29 class Cat(SQLModel): 1abcdefg
30 pet_type: Literal["cat"] 1abcdefg
31 meows: int 1abcdefg
33 class Dog(SQLModel): 1abcdefg
34 pet_type: Literal["dog"] 1abcdefg
35 barks: float 1abcdefg
37 class Lizard(SQLModel): 1abcdefg
38 pet_type: Literal["reptile", "lizard"] 1abcdefg
39 scales: bool 1abcdefg
41 class Model(SQLModel): 1abcdefg
42 pet: Union[Cat, Dog, Lizard] = Field(..., discriminator="pet_type") 1abcdefg
43 n: int 1abcdefg
45 Model(pet={"pet_type": "dog", "barks": 3.14}, n=1) # type: ignore[arg-type] 1abcdefg
47 with pytest.raises(ValidationError): 1abcdefg
48 Model(pet={"pet_type": "dog"}, n=1) # type: ignore[arg-type] 1abcdefg
51def test_repr(): 1opqrstu
52 class Model(SQLModel): 1vwxyzAB
53 id: Optional[int] = Field(primary_key=True) 1vwxyzAB
54 foo: str = Field(repr=False) 1vwxyzAB
56 instance = Model(id=123, foo="bar") 1vwxyzAB
57 assert "foo=" not in repr(instance) 1vwxyzAB