Coverage for tests/test_validation.py: 100%

33 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-10-27 00:03 +0000

1from typing import Optional 1klmnopqrst

2 

3import pytest 1klmnopqrst

4from pydantic.error_wrappers import ValidationError 1klmnopqrst

5from sqlmodel import SQLModel 1klmnopqrst

6 

7from .conftest import needs_pydanticv1, needs_pydanticv2 1klmnopqrst

8 

9 

10@needs_pydanticv1 1klmnopqrst

11def test_validation_pydantic_v1(clear_sqlmodel): 1klmnopqrst

12 """Test validation of implicit and explicit None values. 

13 

14 # For consistency with pydantic, validators are not to be called on 

15 # arguments that are not explicitly provided. 

16 

17 https://github.com/tiangolo/sqlmodel/issues/230 

18 https://github.com/samuelcolvin/pydantic/issues/1223 

19 

20 """ 

21 from pydantic import validator 1abcd

22 

23 class Hero(SQLModel): 1abcd

24 name: Optional[str] = None 1abcd

25 secret_name: Optional[str] = None 1abcd

26 age: Optional[int] = None 1abcd

27 

28 @validator("name", "secret_name", "age") 1abcd

29 def reject_none(cls, v): 1abcd

30 assert v is not None 1abcd

31 return v 1abcd

32 

33 Hero.validate({"age": 25}) 1abcd

34 

35 with pytest.raises(ValidationError): 1abcd

36 Hero.validate({"name": None, "age": 25}) 1abcd

37 

38 

39@needs_pydanticv2 1klmnopqrst

40def test_validation_pydantic_v2(clear_sqlmodel): 1klmnopqrst

41 """Test validation of implicit and explicit None values. 

42 

43 # For consistency with pydantic, validators are not to be called on 

44 # arguments that are not explicitly provided. 

45 

46 https://github.com/tiangolo/sqlmodel/issues/230 

47 https://github.com/samuelcolvin/pydantic/issues/1223 

48 

49 """ 

50 from pydantic import field_validator 1efghij

51 

52 class Hero(SQLModel): 1efghij

53 name: Optional[str] = None 1efghij

54 secret_name: Optional[str] = None 1efghij

55 age: Optional[int] = None 1efghij

56 

57 @field_validator("name", "secret_name", "age") 1efghij

58 def reject_none(cls, v): 1efghij

59 assert v is not None 1efghij

60 return v 1efghij

61 

62 Hero.model_validate({"age": 25}) 1efghij

63 

64 with pytest.raises(ValidationError): 1efghij

65 Hero.model_validate({"name": None, "age": 25}) 1efghij