Coverage for tests/test_validation.py: 100%
33 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 typing import Optional 1rmnopq
3import pytest 1rmnopq
4from pydantic.error_wrappers import ValidationError 1rmnopq
5from sqlmodel import SQLModel 1rmnopq
7from .conftest import needs_pydanticv1, needs_pydanticv2 1rmnopq
10@needs_pydanticv1 1rmnopq
11def test_validation_pydantic_v1(clear_sqlmodel): 1mnopq
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 1kabcde
23 class Hero(SQLModel): 1kabcde
24 name: Optional[str] = None 1kabcde
25 secret_name: Optional[str] = None 1kabcde
26 age: Optional[int] = None 1kabcde
28 @validator("name", "secret_name", "age") 1kabcde
29 def reject_none(cls, v): 1abcde
30 assert v is not None 1kabcde
31 return v 1kabcde
33 Hero.validate({"age": 25}) 1kabcde
35 with pytest.raises(ValidationError): 1kabcde
36 Hero.validate({"name": None, "age": 25}) 1kabcde
39@needs_pydanticv2 1rmnopq
40def test_validation_pydantic_v2(clear_sqlmodel): 1mnopq
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 1lfghij
52 class Hero(SQLModel): 1lfghij
53 name: Optional[str] = None 1lfghij
54 secret_name: Optional[str] = None 1lfghij
55 age: Optional[int] = None 1lfghij
57 @field_validator("name", "secret_name", "age") 1lfghij
58 def reject_none(cls, v): 1fghij
59 assert v is not None 1lfghij
60 return v 1lfghij
62 Hero.model_validate({"age": 25}) 1lfghij
64 with pytest.raises(ValidationError): 1lfghij
65 Hero.model_validate({"name": None, "age": 25}) 1lfghij