Skip to content

Commit 3102ddf

Browse files
committed
Test PathEx parameter parsing with custom validator
1 parent 46b3d68 commit 3102ddf

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

tests/main.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
from typing import List, Optional
1+
from typing import Annotated, List, Optional
22
from uuid import UUID
33

4+
import pydantic
45
from django.urls import register_converter
56

6-
from ninja import Field, Path, Query, Router, Schema
7+
from ninja import Field, P, Path, PathEx, Query, Router, Schema
78

89
router = Router()
910

@@ -38,6 +39,29 @@ def get_bool_id(request, item_id: bool):
3839
return item_id
3940

4041

42+
def custom_validator(value: int) -> int:
43+
if value != 42:
44+
raise ValueError("Input should pass this custom validator")
45+
return value
46+
47+
48+
CustomValidatedInt = Annotated[
49+
int,
50+
pydantic.AfterValidator(custom_validator),
51+
pydantic.WithJsonSchema({
52+
"type": "int",
53+
"example": "42",
54+
}),
55+
]
56+
57+
58+
@router.get("/path/param_ex/{item_id}")
59+
def get_path_param_ex_id(
60+
request, item_id: PathEx[CustomValidatedInt, P(description="path_ex description")]
61+
):
62+
return item_id
63+
64+
4165
@router.get("/path/param/{item_id}")
4266
def get_path_param_id(request, item_id: str = Path(None)):
4367
return item_id

tests/test_path.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,17 @@ def test_text_get():
3333
]
3434
}
3535

36+
response_not_valid_custom = {
37+
"detail": [
38+
{
39+
"ctx": {"error": "Input should pass this custom validator"},
40+
"loc": ["path", "item_id"],
41+
"msg": "Value error, Input should pass this custom validator",
42+
"type": "value_error",
43+
}
44+
]
45+
}
46+
3647
response_not_valid_int_float = {
3748
"detail": [
3849
{
@@ -210,6 +221,9 @@ def test_text_get():
210221
("/path/bool/true", 200, True),
211222
("/path/bool/False", 200, False),
212223
("/path/bool/false", 200, False),
224+
("/path/param_ex/True", 422, response_not_valid_int),
225+
("/path/param_ex/0", 422, response_not_valid_custom),
226+
("/path/param_ex/42", 200, 42),
213227
("/path/param/foo", 200, "foo"),
214228
("/path/param-required/foo", 200, "foo"),
215229
("/path/param-minlength/foo", 200, "foo"),

0 commit comments

Comments
 (0)