Skip to content

Refuse to cast str or bytes to array #421

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

Merged
merged 1 commit into from
Sep 13, 2022
Merged
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
4 changes: 4 additions & 0 deletions openapi_core/casting/schemas/casters.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ def items_caster(self) -> BaseSchemaCaster:
return self.casters_factory.create(self.schema / "items")

def cast(self, value: Any) -> List[Any]:
# str and bytes are not arrays according to the OpenAPI spec
if isinstance(value, (str, bytes)):
raise CastError(value, self.schema["type"])

try:
return list(map(self.items_caster, value))
except (ValueError, TypeError):
Expand Down
3 changes: 2 additions & 1 deletion openapi_core/casting/schemas/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from dataclasses import dataclass
from typing import Any

from openapi_core.exceptions import OpenAPIError

Expand All @@ -7,7 +8,7 @@
class CastError(OpenAPIError):
"""Schema cast operation error"""

value: str
value: Any
type: str

def __str__(self) -> str:
Expand Down
10 changes: 6 additions & 4 deletions tests/unit/casting/test_schema_casters.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,17 @@ def test_array_invalid_type(self, caster_factory):
with pytest.raises(CastError):
caster_factory(schema)(value)

def test_array_invalid_value(self, caster_factory):
@pytest.mark.parametrize("value", [3.14, "foo", b"foo"])
def test_array_invalid_value(self, value, caster_factory):
spec = {
"type": "array",
"items": {
"type": "number",
"oneOf": [{"type": "number"}, {"type": "string"}],
},
}
schema = Spec.from_dict(spec)
value = 3.14

with pytest.raises(CastError):
with pytest.raises(
CastError, match=f"Failed to cast value to array type: {value}"
):
caster_factory(schema)(value)