Skip to content

Commit 1aece83

Browse files
anderskp1c2u
authored andcommitted
Refuse to cast str or bytes to array
Although str and bytes act as sequences in Python, they do not count as arrays according to OpenAPI, so we should not allow them to validate as arrays. Signed-off-by: Anders Kaseorg <andersk@mit.edu>
1 parent 692f2c6 commit 1aece83

File tree

3 files changed

+12
-5
lines changed

3 files changed

+12
-5
lines changed

openapi_core/casting/schemas/casters.py

+4
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

+2-1
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

+6-4
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)