Skip to content

Commit 58ae07b

Browse files
committed
Fix minItems for all-optional array structs
1 parent a1ebbcd commit 58ae07b

2 files changed

Lines changed: 16 additions & 1 deletion

File tree

‎src/msgspec/_json_schema.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -411,9 +411,10 @@ def to_schema(self, t: mi.Type, check_ref: bool = True) -> dict[str, Any]:
411411

412412
if t.array_like:
413413
n_trailing_defaults = 0
414-
for n_trailing_defaults, f in enumerate(reversed(t.fields)):
414+
for f in reversed(t.fields):
415415
if f.required:
416416
break
417+
n_trailing_defaults += 1
417418
schema["type"] = "array"
418419
schema["prefixItems"] = fields
419420
schema["minItems"] = len(fields) - n_trailing_defaults

‎tests/unit/test_schema.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,20 @@ class Example(
411411
assert msgspec.json.schema(Example) == sol
412412

413413

414+
@pytest.mark.parametrize(
415+
"tag, min_items, payload",
416+
[(False, 0, b"[]"), (True, 1, b'["Example"]')],
417+
)
418+
def test_struct_array_like_all_fields_optional(tag, min_items, payload):
419+
class Example(msgspec.Struct, array_like=True, tag=tag):
420+
a: int = 1
421+
b: list[int] = msgspec.field(default_factory=list)
422+
423+
schema = msgspec.json.schema(Example)["$defs"]["Example"]
424+
assert msgspec.json.decode(payload, type=Example) == Example()
425+
assert schema["minItems"] == min_items
426+
427+
414428
def test_struct_no_fields():
415429
class Example(msgspec.Struct):
416430
pass

0 commit comments

Comments
 (0)