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