Skip to content

Commit

Permalink
Fix ActionJsonSchema not setting correctly defaults when schema uses …
Browse files Browse the repository at this point in the history
…oneOf.
  • Loading branch information
mauvilsa committed Sep 4, 2023
1 parent 4148f4e commit 6ed515b
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Fixed
- AST resolver ``kwargs.pop()`` with conflicting defaults not setting the
conditional default (`#362
<https://github.com/omni-us/jsonargparse/issues/362>`__).
- ``ActionJsonSchema`` not setting correctly defaults when schema uses
``oneOf``.


v4.24.0 (2023-08-23)
Expand Down
14 changes: 9 additions & 5 deletions jsonargparse/_jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,15 @@ def _extend_jsonvalidator_with_default(validator_class):
validate_properties = validator_class.VALIDATORS["properties"]

def set_defaults(validator, properties, instance, schema):
for prop, subschema in properties.items():
if "default" in subschema:
instance.setdefault(prop, subschema["default"])

yield from validate_properties(validator, properties, instance, schema)
valid = True
for validation in validate_properties(validator, properties, instance, schema):
if isinstance(validation, jsonschema.exceptions.ValidationError):
valid = False
yield validation
if valid:
for prop, subschema in properties.items():
if "default" in subschema:
instance.setdefault(prop, subschema["default"])

jsonschema = import_jsonschema("ActionJsonSchema")[0]
return jsonschema.validators.extend(validator_class, {"properties": set_defaults})
Expand Down
31 changes: 31 additions & 0 deletions jsonargparse_tests/test_jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,37 @@ def test_schema_object_parse_config(parser, tmp_path):
assert op2_val == cfg["op2"]


def test_schema_oneof_add_defaults(parser):
schema = {
"oneOf": [
{
"type": "object",
"properties": {
"kind": {"type": "string", "enum": ["x"]},
"pc": {"type": "integer", "default": 1},
"px": {"type": "string", "default": "dx"},
},
},
{
"type": "object",
"properties": {
"kind": {"type": "string", "enum": ["y"]},
"pc": {"type": "integer", "default": 2},
"py": {"type": "string", "default": "dy"},
},
},
]
}
parser.add_argument("--data", action=ActionJsonSchema(schema=schema))
parser.add_argument("--cfg", action=ActionConfigFile)

cfg = parser.parse_args(['--data={"kind": "x"}'])
assert cfg.data == {"kind": "x", "pc": 1, "px": "dx"}

cfg = parser.parse_args(['--data={"kind": "y", "pc": 3}'])
assert cfg.data == {"kind": "y", "pc": 3, "py": "dy"}


# other tests


Expand Down

0 comments on commit 6ed515b

Please sign in to comment.