Coverage for tests/test_validation.py: 100%
33 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-07 05:42 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-07 05:42 +0000
1from typing import Optional 1uopqrst
3import pytest 1uopqrst
4from pydantic.error_wrappers import ValidationError 1uopqrst
5from sqlmodel import SQLModel 1uopqrst
7from .conftest import needs_pydanticv1, needs_pydanticv2 1uopqrst
10@needs_pydanticv1 1uopqrst
11def test_validation_pydantic_v1(clear_sqlmodel): 1opqrst
12 """Test validation of implicit and explicit None values.
14 # For consistency with pydantic, validators are not to be called on
15 # arguments that are not explicitly provided.
17 https://github.com/tiangolo/sqlmodel/issues/230
18 https://github.com/samuelcolvin/pydantic/issues/1223
20 """
21 from pydantic import validator 1mabcdef
23 class Hero(SQLModel): 1mabcdef
24 name: Optional[str] = None 1mabcdef
25 secret_name: Optional[str] = None 1mabcdef
26 age: Optional[int] = None 1mabcdef
28 @validator("name", "secret_name", "age") 1mabcdef
29 def reject_none(cls, v): 1abcdef
30 assert v is not None 1mabcdef
31 return v 1mabcdef
33 Hero.validate({"age": 25}) 1mabcdef
35 with pytest.raises(ValidationError): 1mabcdef
36 Hero.validate({"name": None, "age": 25}) 1mabcdef
39@needs_pydanticv2 1uopqrst
40def test_validation_pydantic_v2(clear_sqlmodel): 1opqrst
41 """Test validation of implicit and explicit None values.
43 # For consistency with pydantic, validators are not to be called on
44 # arguments that are not explicitly provided.
46 https://github.com/tiangolo/sqlmodel/issues/230
47 https://github.com/samuelcolvin/pydantic/issues/1223
49 """
50 from pydantic import field_validator 1nghijkl
52 class Hero(SQLModel): 1nghijkl
53 name: Optional[str] = None 1nghijkl
54 secret_name: Optional[str] = None 1nghijkl
55 age: Optional[int] = None 1nghijkl
57 @field_validator("name", "secret_name", "age") 1nghijkl
58 def reject_none(cls, v): 1ghijkl
59 assert v is not None 1nghijkl
60 return v 1nghijkl
62 Hero.model_validate({"age": 25}) 1nghijkl
64 with pytest.raises(ValidationError): 1nghijkl
65 Hero.model_validate({"name": None, "age": 25}) 1nghijkl