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