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

1from decimal import Decimal 1uvwxyzABCD

2from typing import Optional, Union 1uvwxyzABCD

3 

4import pytest 1uvwxyzABCD

5from pydantic import ValidationError 1uvwxyzABCD

6from sqlmodel import Field, SQLModel 1uvwxyzABCD

7from typing_extensions import Literal 1uvwxyzABCD

8 

9 

10def test_decimal(): 1uvwxyzABCD

11 class Model(SQLModel): 1klmnopqrst

12 dec: Decimal = Field(max_digits=4, decimal_places=2) 1klmnopqrst

13 

14 Model(dec=Decimal("3.14")) 1klmnopqrst

15 Model(dec=Decimal("69.42")) 1klmnopqrst

16 

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

23 

24 

25def test_discriminator(): 1uvwxyzABCD

26 # Example adapted from 

27 # [Pydantic docs](https://pydantic-docs.helpmanual.io/usage/types/#discriminated-unions-aka-tagged-unions): 

28 

29 class Cat(SQLModel): 1abcdefghij

30 pet_type: Literal["cat"] 1abcdefghij

31 meows: int 1abcdefghij

32 

33 class Dog(SQLModel): 1abcdefghij

34 pet_type: Literal["dog"] 1abcdefghij

35 barks: float 1abcdefghij

36 

37 class Lizard(SQLModel): 1abcdefghij

38 pet_type: Literal["reptile", "lizard"] 1abcdefghij

39 scales: bool 1abcdefghij

40 

41 class Model(SQLModel): 1abcdefghij

42 pet: Union[Cat, Dog, Lizard] = Field(..., discriminator="pet_type") 1abcdefghij

43 n: int 1abcdefghij

44 

45 Model(pet={"pet_type": "dog", "barks": 3.14}, n=1) # type: ignore[arg-type] 1abcdefghij

46 

47 with pytest.raises(ValidationError): 1abcdefghij

48 Model(pet={"pet_type": "dog"}, n=1) # type: ignore[arg-type] 1abcdefghij

49 

50 

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

55 

56 instance = Model(id=123, foo="bar") 1EFGHIJKLMN

57 assert "foo=" not in repr(instance) 1EFGHIJKLMN