Skip to content

Commit 7be7fcc

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 <[email protected]>
1 parent 692f2c6 commit 7be7fcc

File tree

3 files changed

+8
-4
lines changed

3 files changed

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

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
class CastError(OpenAPIError):
88
"""Schema cast operation error"""
99

10-
value: str
10+
value: object
1111
type: str
1212

1313
def __str__(self) -> str:

tests/unit/casting/test_schema_casters.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,15 @@ 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

3939
with pytest.raises(CastError):
4040
caster_factory(schema)(value)

0 commit comments

Comments
 (0)