Feature: 添加 pydantic validator 兼容函数 (#3291)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Tarrailt
2025-01-31 23:48:22 +08:00
committed by GitHub
parent b16ddf380e
commit 3c616e758a
2 changed files with 114 additions and 1 deletions

View File

@ -11,7 +11,9 @@ from nonebot.compat import (
Required,
TypeAdapter,
custom_validation,
field_validator,
model_dump,
model_validator,
type_validate_json,
type_validate_python,
)
@ -30,6 +32,32 @@ def test_field_info():
assert FieldInfo(test="test").extra["test"] == "test"
def test_field_validator():
class TestModel(BaseModel):
foo: int
bar: str
@field_validator("foo")
@classmethod
def test_validator(cls, v: Any) -> Any:
if v > 0:
return v
raise ValueError("test must be greater than 0")
@field_validator("bar", mode="before")
@classmethod
def test_validator_before(cls, v: Any) -> Any:
if not isinstance(v, str):
v = str(v)
return v
assert type_validate_python(TestModel, {"foo": 1, "bar": "test"}).foo == 1
assert type_validate_python(TestModel, {"foo": 1, "bar": 123}).bar == "123"
with pytest.raises(ValidationError):
TestModel(foo=0, bar="test")
def test_type_adapter():
t = TypeAdapter(Annotated[int, FieldInfo(ge=1)])
@ -53,6 +81,35 @@ def test_model_dump():
assert model_dump(TestModel(test1=1, test2=2), exclude={"test1"}) == {"test2": 2}
def test_model_validator():
class TestModel(BaseModel):
foo: int
bar: str
@model_validator(mode="before")
@classmethod
def test_validator_before(cls, data: Any) -> Any:
if isinstance(data, dict):
if "foo" not in data:
data["foo"] = 1
return data
@model_validator(mode="after")
@classmethod
def test_validator_after(cls, data: Any) -> Any:
if isinstance(data, dict):
if data["bar"] == "test":
raise ValueError("bar should not be test")
elif data.bar == "test":
raise ValueError("bar should not be test")
return data
assert type_validate_python(TestModel, {"bar": "aaa"}).foo == 1
with pytest.raises(ValidationError):
type_validate_python(TestModel, {"foo": 1, "bar": "test"})
def test_custom_validation():
called = []