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