Skip to content

Commit

Permalink
Add pattern support to param
Browse files Browse the repository at this point in the history
  • Loading branch information
sunfkny committed Nov 12, 2024
1 parent 8786c68 commit 82d7bd6
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
15 changes: 14 additions & 1 deletion ninja/params/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
from abc import ABC, abstractmethod
from collections import defaultdict
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, TypeVar
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Optional,
Pattern,
Tuple,
Type,
TypeVar,
Union,
)

from django.conf import settings
from django.http import HttpRequest
Expand Down Expand Up @@ -204,6 +215,7 @@ def __init__(
examples: Optional[Dict[str, Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: Optional[bool] = True,
pattern: Union[str, Pattern[str], None] = None,
# param_name: str = None,
# param_type: Any = None,
**extra: Any,
Expand Down Expand Up @@ -237,6 +249,7 @@ def __init__(
le=le,
min_length=min_length,
max_length=max_length,
pattern=pattern,
json_schema_extra=json_schema_extra,
**extra,
)
Expand Down
5 changes: 5 additions & 0 deletions tests/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,11 @@ def get_path_param_le_ge_int(request, item_id: int = Path(..., le=3, ge=1)):
return item_id


@router.get("/path/param-pattern/{item_id}")
def get_path_param_pattern(request, item_id: str = Path(..., pattern="^foo")):
return item_id


@router.get("/path/param-django-str/{str:item_id}")
def get_path_param_django_str(request, item_id):
return item_id
Expand Down
16 changes: 16 additions & 0 deletions tests/test_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,20 @@ def test_text_get():
}


response_not_valid_pattern = {
"detail": [
{
"ctx": {
"pattern": "^foo",
},
"loc": ["path", "item_id"],
"msg": "String should match pattern '^foo'",
"type": "string_pattern_mismatch",
}
]
}


@pytest.mark.parametrize(
"path,expected_status,expected_response",
[
Expand Down Expand Up @@ -249,6 +263,8 @@ def test_text_get():
("/path/param-le-ge-int/3", 200, 3),
("/path/param-le-ge-int/4", 422, response_less_than_equal_3),
("/path/param-le-ge-int/2.7", 422, response_not_valid_int_float),
("/path/param-pattern/foo", 200, "foo"),
("/path/param-pattern/fo", 422, response_not_valid_pattern),
],
)
def test_get_path(path, expected_status, expected_response):
Expand Down

0 comments on commit 82d7bd6

Please sign in to comment.