Skip to content
Open
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
10 changes: 8 additions & 2 deletions dargs/json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,19 @@ def _convert_single_argument(argument: Argument) -> dict:
if allof:
data["allOf"] = allof
else:
data["items"] = {
repeated_value = {
"type": "object",
"properties": properties,
"required": required,
}
if allof:
data["items"]["allOf"] = allof
repeated_value["allOf"] = allof
# Repeated lists validate through ``items`` while repeated mappings
# validate every dynamically named entry through ``additionalProperties``.
if "array" in data["type"]:
data["items"] = repeated_value
if "object" in data["type"]:
data["additionalProperties"] = repeated_value
return data


Expand Down
19 changes: 18 additions & 1 deletion tests/test_json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
import json
import unittest

from jsonschema import validate
from jsonschema import ValidationError, validate

from dargs import Argument
from dargs.json_schema import _convert_types, generate_json_schema

from .dpmdargs import example_json_str, gen_args
Expand All @@ -28,3 +29,19 @@ def test_convert_types(self) -> None:
self.assertEqual(_convert_types(dict), "object")
with self.assertRaises(ValueError):
_convert_types(set)

def test_repeat_dict_validates_each_entry(self) -> None:
"""Each value in a dict-style repeated argument uses the item schema."""
argument = Argument(
"base",
dict,
[Argument("sub1", int), Argument("sub2", str)],
repeat=True,
)
schema = generate_json_schema(argument)

validate({"item1": {"sub1": 1, "sub2": "valid"}}, schema)
with self.assertRaises(ValidationError):
validate({"item1": {"sub1": 1, "sub2": None}}, schema)
with self.assertRaises(ValidationError):
validate({"item1": {"sub1": 1}}, schema)
Loading