mirror of
https://github.com/nonebot/nonebot2.git
synced 2025-07-26 07:41:20 +00:00
✨ Feature: 支持子依赖定义 Pydantic 类型校验 (#2310)
This commit is contained in:
@ -1,7 +1,10 @@
|
||||
from dataclasses import dataclass
|
||||
from typing_extensions import Annotated
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from nonebot import on_message
|
||||
from nonebot.adapters import Bot
|
||||
from nonebot.params import Depends
|
||||
|
||||
test_depends = on_message()
|
||||
@ -33,6 +36,14 @@ class ClassDependency:
|
||||
y: int = Depends(gen_async)
|
||||
|
||||
|
||||
class FooBot(Bot):
|
||||
...
|
||||
|
||||
|
||||
async def sub_bot(b: FooBot) -> FooBot:
|
||||
return b
|
||||
|
||||
|
||||
# test parameterless
|
||||
@test_depends.handle(parameterless=[Depends(parameterless)])
|
||||
async def depends(x: int = Depends(dependency)):
|
||||
@ -46,19 +57,46 @@ async def depends_cache(y: int = Depends(dependency, use_cache=True)):
|
||||
return y
|
||||
|
||||
|
||||
# test class dependency
|
||||
async def class_depend(c: ClassDependency = Depends()):
|
||||
return c
|
||||
|
||||
|
||||
# test annotated dependency
|
||||
async def annotated_depend(x: Annotated[int, Depends(dependency)]):
|
||||
return x
|
||||
|
||||
|
||||
# test annotated class dependency
|
||||
async def annotated_class_depend(c: Annotated[ClassDependency, Depends()]):
|
||||
return c
|
||||
|
||||
|
||||
# test dependency priority
|
||||
async def annotated_prior_depend(
|
||||
x: Annotated[int, Depends(lambda: 2)] = Depends(dependency)
|
||||
):
|
||||
return x
|
||||
|
||||
|
||||
# test sub dependency type mismatch
|
||||
async def sub_type_mismatch(b: FooBot = Depends(sub_bot)):
|
||||
return b
|
||||
|
||||
|
||||
# test type validate
|
||||
async def validate(x: int = Depends(lambda: "1", validate=True)):
|
||||
return x
|
||||
|
||||
|
||||
async def validate_fail(x: int = Depends(lambda: "not_number", validate=True)):
|
||||
return x
|
||||
|
||||
|
||||
# test FieldInfo validate
|
||||
async def validate_field(x: int = Depends(lambda: "1", validate=Field(gt=0))):
|
||||
return x
|
||||
|
||||
|
||||
async def validate_field_fail(x: int = Depends(lambda: "0", validate=Field(gt=0))):
|
||||
return x
|
||||
|
Reference in New Issue
Block a user