Skip to content

Commit 5553fe4

Browse files
authored
Merge pull request #421 from andersk/array-cast
Refuse to cast str or bytes to array
2 parents 28e55ef + 1aece83 commit 5553fe4

File tree

3 files changed

+12
-5
lines changed

3 files changed

+12
-5
lines changed

openapi_core/casting/schemas/casters.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,10 @@ def items_caster(self) -> BaseSchemaCaster:
5454
return self.casters_factory.create(self.schema / "items")
5555

5656
def cast(self, value: Any) -> List[Any]:
57+
# str and bytes are not arrays according to the OpenAPI spec
58+
if isinstance(value, (str, bytes)):
59+
raise CastError(value, self.schema["type"])
60+
5761
try:
5862
return list(map(self.items_caster, value))
5963
except (ValueError, TypeError):

openapi_core/casting/schemas/exceptions.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from dataclasses import dataclass
2+
from typing import Any
23

34
from openapi_core.exceptions import OpenAPIError
45

@@ -7,7 +8,7 @@
78
class CastError(OpenAPIError):
89
"""Schema cast operation error"""
910

10-
value: str
11+
value: Any
1112
type: str
1213

1314
def __str__(self) -> str:

tests/unit/casting/test_schema_casters.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,17 @@ def test_array_invalid_type(self, caster_factory):
2626
with pytest.raises(CastError):
2727
caster_factory(schema)(value)
2828

29-
def test_array_invalid_value(self, caster_factory):
29+
@pytest.mark.parametrize("value", [3.14, "foo", b"foo"])
30+
def test_array_invalid_value(self, value, caster_factory):
3031
spec = {
3132
"type": "array",
3233
"items": {
33-
"type": "number",
34+
"oneOf": [{"type": "number"}, {"type": "string"}],
3435
},
3536
}
3637
schema = Spec.from_dict(spec)
37-
value = 3.14
3838

39-
with pytest.raises(CastError):
39+
with pytest.raises(
40+
CastError, match=f"Failed to cast value to array type: {value}"
41+
):
4042
caster_factory(schema)(value)

0 commit comments

Comments
 (0)