2022-08-27 23:10:23 +00:00
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
import pytest
|
2023-07-31 13:38:26 +00:00
|
|
|
from pydantic import field_validator
|
2022-08-27 23:10:23 +00:00
|
|
|
from pydantic.error_wrappers import ValidationError
|
|
|
|
from sqlmodel import SQLModel
|
|
|
|
|
|
|
|
|
|
|
|
def test_validation(clear_sqlmodel):
|
|
|
|
"""Test validation of implicit and explict None values.
|
|
|
|
|
|
|
|
# For consistency with pydantic, validators are not to be called on
|
|
|
|
# arguments that are not explicitly provided.
|
|
|
|
|
|
|
|
https://github.com/tiangolo/sqlmodel/issues/230
|
|
|
|
https://github.com/samuelcolvin/pydantic/issues/1223
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
class Hero(SQLModel):
|
|
|
|
name: Optional[str] = None
|
|
|
|
secret_name: Optional[str] = None
|
|
|
|
age: Optional[int] = None
|
|
|
|
|
2023-07-31 13:38:26 +00:00
|
|
|
@field_validator("name", "secret_name", "age")
|
2022-08-27 23:10:23 +00:00
|
|
|
def reject_none(cls, v):
|
|
|
|
assert v is not None
|
|
|
|
return v
|
|
|
|
|
2023-07-31 13:38:26 +00:00
|
|
|
Hero.model_validate({"age": 25})
|
2022-08-27 23:10:23 +00:00
|
|
|
|
|
|
|
with pytest.raises(ValidationError):
|
2023-07-31 13:38:26 +00:00
|
|
|
Hero.model_validate({"name": None, "age": 25})
|