Skip to content

Commit

Permalink
Improve error message for top-level schema-validation errors (#681)
Browse files Browse the repository at this point in the history
  • Loading branch information
maddenp-noaa authored Dec 19, 2024
1 parent 71f5847 commit debdecb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/uwtools/config/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ def validate(schema: dict, desc: str, config: dict) -> bool:
log_msg = "%s schema-validation error%s found in %s"
log_method(log_msg, len(errors), "" if len(errors) == 1 else "s", desc)
for error in errors:
log.error("Error at %s:", ".".join(str(k) for k in error.path))
location = ".".join(str(k) for k in error.path) if error.path else "top level"
log.error("Error at %s:", location)
log.error("%s%s", INDENT, error.message)
return not bool(errors)

Expand Down
20 changes: 20 additions & 0 deletions src/uwtools/tests/config/test_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import json
import logging
from pathlib import Path
from textwrap import dedent
from typing import Any
from unittest.mock import Mock, patch

Expand Down Expand Up @@ -174,6 +175,25 @@ def test_validate_fail_bad_number_val(caplog, config, schema):
assert any(x for x in caplog.records if "'string' is not of type 'number'" in x.message)


def test_validate_fail_top_level(caplog):
schema = {
"additionalProperties": False,
"properties": {"n": {"type": "integer"}},
"required": ["n"],
"type": "object",
}
config = {"x": 42}
assert not validator.validate(schema=schema, desc="test", config=config)
expected = """
2 schema-validation errors found in test
Error at top level:
Additional properties are not allowed ('x' was unexpected)
Error at top level:
'n' is a required property
"""
assert all(line in caplog.messages for line in dedent(expected).strip().split("\n"))


def test_validate_internal_no(caplog, schema_file):
with patch.object(validator, "resource_path", return_value=schema_file.parent):
with raises(UWConfigError) as e:
Expand Down

0 comments on commit debdecb

Please sign in to comment.