Skip to content

Commit

Permalink
✅ add tests for validator
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Jan 31, 2025
1 parent bc802df commit 225dbbf
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
4 changes: 2 additions & 2 deletions nonebot/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,15 +387,15 @@ def field_validator(
field: str,
/,
*fields: str,
mode: Literal["after"],
mode: Literal["after"] = ...,
check_fields: Optional[bool] = None,
): ...

def field_validator(
field: str,
/,
*fields: str,
mode: Literal["before", "after"],
mode: Literal["before", "after"] = "after",
check_fields: Optional[bool] = None,
):
if mode == "before":
Expand Down
52 changes: 52 additions & 0 deletions tests/test_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
from nonebot.compat import (
DEFAULT_CONFIG,
FieldInfo,
field_validator,
PydanticUndefined,
Required,
TypeAdapter,
custom_validation,
model_dump,
model_validator,
type_validate_json,
type_validate_python,
)

Check failure on line 19 in tests/test_compat.py

View workflow job for this annotation

GitHub Actions / Ruff Lint

Ruff (I001)

tests/test_compat.py:1:1: I001 Import block is un-sorted or un-formatted
Expand All @@ -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 TestModel(foo=1, bar="test").foo == 1
assert TestModel(foo=1, bar=123).bar == "123"

Check failure on line 55 in tests/test_compat.py

View workflow job for this annotation

GitHub Actions / Pyright Lint (pydantic-v1)

Argument of type "Literal[123]" cannot be assigned to parameter "bar" of type "str" in function "__init__"   "Literal[123]" is not assignable to "str" (reportArgumentType)

Check failure on line 55 in tests/test_compat.py

View workflow job for this annotation

GitHub Actions / Pyright Lint (pydantic-v2)

Argument of type "Literal[123]" cannot be assigned to parameter "bar" of type "str" in function "__init__"   "Literal[123]" is not assignable to "str" (reportArgumentType)

with pytest.raises(ValidationError):
TestModel(foo=0, bar="test")


def test_type_adapter():
t = TypeAdapter(Annotated[int, FieldInfo(ge=1)])

Expand All @@ -53,6 +81,30 @@ class TestModel(BaseModel):
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")

Check failure on line 97 in tests/test_compat.py

View workflow job for this annotation

GitHub Actions / Pyright Lint (pydantic-v2)

Argument of type "(self: Self@TestModel) -> None" cannot be assigned to parameter of type "_AnyModelAfterValidator[_ModelType@model_validator]"   Type "(self: Self@TestModel) -> None" is not assignable to type "_AnyModelAfterValidator[_ModelType@model_validator]"     Type "(self: Self@TestModel) -> None" is not assignable to type "ModelAfterValidator[_ModelType@model_validator]"       Function accepts too many positional parameters; expected 1 but received 2         Function return type "None" is incompatible with type "_ModelType@model_validator"           Type "None" is not assignable to type "Self@TestModel"     Type "(self: Self@TestModel) -> None" is not assignable to type "ModelAfterValidatorWithoutInfo[_ModelType@model_validator]"       Function return type "None" is incompatible with type "_ModelType@model_validator"         Type "None" is not assignable to type "Self@TestModel" (reportArgumentType)
def test_validator_after(self):
if self.bar == "test":
raise ValueError("bar should not be test")

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 = []

Expand Down

0 comments on commit 225dbbf

Please sign in to comment.