Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Hint.coerce_type not recognising falsey statements #126

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 55 additions & 9 deletions sanic_ext/extras/validation/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from dataclasses import _HAS_DEFAULT_FACTORY # type: ignore
from typing import Any, Literal, NamedTuple, Optional, Tuple, Union, get_args

from sanic.utils import str_to_bool

from sanic_ext.utils.typing import UnionType, is_generic, is_optional

MISSING: Tuple[Any, ...] = (_HAS_DEFAULT_FACTORY,)
Expand Down Expand Up @@ -66,6 +68,8 @@ def validate(
else:
raise e
else:
if allow_coerce:
value = self.coerce(value, allow_multiple)
value = _check_nullability(
value,
self.nullable,
Expand Down Expand Up @@ -103,29 +107,37 @@ def validate(
allow_coerce,
)

if allow_coerce:
value = self.coerce(value)

return value

def coerce(self, value):
def coerce(self, value, allow_multiple=False):
if is_generic(self.coerce_type):
args = get_args(self.coerce_type)
if type(None) in args and value is None:
return None
coerce_types = [arg for arg in args if not isinstance(None, arg)]
else:
coerce_types = [self.coerce_type]

if self.nullable:
value = self._do_coerce(value, str_to_none)
if value is None or (
isinstance(value, list)
and allow_multiple
and all(val is None for val in value)
):
return value

for coerce_type in coerce_types:
if isinstance(value, coerce_type):
return value
coercer = self.get_coercer(coerce_type)
try:
if isinstance(value, list):
value = [coerce_type(item) for item in value]
else:
value = coerce_type(value)
value = self._do_coerce(value, coercer, raise_exception=True)
except (ValueError, TypeError):
...
else:
return value

return value

@property
Expand All @@ -135,6 +147,30 @@ def coerce_type(self):
coerce_type = get_args(self.hint)[0]
return coerce_type

@staticmethod
def _do_coerce(value, coercer, raise_exception=False):
try:
if isinstance(value, list):
value = [coercer(item) for item in value]
else:
value = coercer(value)
except (ValueError, TypeError):
if raise_exception:
raise
return value

@staticmethod
def get_coercer(coerce_type):
if coerce_type is bool:
coerce_type = str_to_bool
return coerce_type


def str_to_none(value: Optional[str]):
if value is None or value.lower() in ("null", "none", ""):
return None
raise ValueError(f"Could not convert {value} to None")


def check_data(model, data, schema, allow_multiple=False, allow_coerce=False):
if not isinstance(data, dict):
Expand Down Expand Up @@ -182,7 +218,17 @@ def _check_nullability(
):
if not nullable and value is None:
raise ValueError("Value cannot be None")
if nullable and value is not None:
if (
nullable
and (value is not None)
and (
allow_multiple is False
or (
isinstance(value, list)
and any(val is not None for val in value)
)
)
):
exc = None
for hint in allowed:
try:
Expand Down
67 changes: 66 additions & 1 deletion tests/extra/test_validation_dataclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ def test_modeling_union_type_ModelUnionTypeStrInt():
check_data(models.ModelUnionTypeStrInt, {"foo": 1.1}, schema)


def test_validate_decorator(app):
def test_validate_decorator_json(app):
@dataclass
class Pet:
name: str
Expand All @@ -318,3 +318,68 @@ async def post(self, _, body: Pet):
_, response = app.test_client.post("/method", json={"name": "Snoopy"})
assert response.status == 200
assert response.json["is_pet"]


@pytest.mark.parametrize(
"query_value,expected",
(
("true", True),
("True", True),
("1", True),
("Yes", True),
("y", True),
("false", False),
("False", False),
("0", False),
("No", False),
("n", False),
),
)
def test_validate_decorator_query(app, query_value, expected):
@dataclass
class Query:
flag: bool

@app.get("/function")
@validate(query=Query)
async def handler(_, query: Query):
return json({"is_flagged": query.flag})

class MethodView(HTTPMethodView, attach=app, uri="/method"):
decorators = [validate(query=Query)]

async def get(self, _, query: Query):
return json({"is_flagged": query.flag})

_, response = app.test_client.get(f"/function?flag={query_value}")
assert response.status == 200
assert response.json["is_flagged"] is expected

_, response = app.test_client.get(f"/method?flag={query_value}")
assert response.status == 200
assert response.json["is_flagged"] is expected


@pytest.mark.parametrize(
"query,expected",
(
("?maybe=true", True),
("?maybe=false", False),
("?maybe=null", None),
("?maybe=None", None),
("?maybe=", None),
("", None),
),
)
def test_validate_decorator_query_optional_bool(app, query, expected):
@dataclass
class Query:
maybe: Optional[bool] = None

@app.get("/")
@validate(query=Query)
async def handler(_, query: Query):
return json({"is_flagged": query.maybe})

_, response = app.test_client.get(f"/{query}")
assert response.json["is_flagged"] is expected