Skip to content

Commit

Permalink
Improve error message heuristics with jsonschema>=4.8
Browse files Browse the repository at this point in the history
Before version 4.8, jsonschema did some wild guessing when producing
error messages for schemas with several equivalent subschemas. In
version 4.8 it is no longer done, causing error messages that are more
correct but also more generic.

This change restores guessing the potential root cause without claiming
that it's the only possible root cause. Also the traits schema is
simplified to make it less ambiguous.

See python-jsonschema/jsonschema#991 for details.

Change-Id: Ia75cecd2bfbc602b8b2b85bdda20fdc04c5eadf4
(cherry picked from commit 62f9c61)
  • Loading branch information
dtantsur committed Aug 30, 2022
1 parent 4bcdd4d commit 41b01ca
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 11 deletions.
12 changes: 7 additions & 5 deletions ironic/api/controllers/v1/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,13 @@
CUSTOM_TRAIT_PATTERN = "^%s[A-Z0-9_]+$" % os_traits.CUSTOM_NAMESPACE
CUSTOM_TRAIT_REGEX = re.compile(CUSTOM_TRAIT_PATTERN)

TRAITS_SCHEMA = {'anyOf': [
{'type': 'string', 'minLength': 1, 'maxLength': 255,
'pattern': CUSTOM_TRAIT_PATTERN},
{'type': 'string', 'enum': STANDARD_TRAITS},
]}
TRAITS_SCHEMA = {
'type': 'string', 'minLength': 1, 'maxLength': 255,
'anyOf': [
{'pattern': CUSTOM_TRAIT_PATTERN},
{'enum': STANDARD_TRAITS},
]
}

LOCAL_LINK_BASE_SCHEMA = {
'type': 'object',
Expand Down
17 changes: 11 additions & 6 deletions ironic/common/args.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,12 +211,17 @@ def _validate_schema(name, value, schema):
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as e:

# The error message includes the whole schema which can be very
# large and unhelpful, so truncate it to be brief and useful
error_msg = ' '.join(str(e).split("\n")[:3])[:-1]
raise exception.InvalidParameterValue(
_('Schema error for %s: %s') % (name, error_msg))
error_msg = _('Schema error for %s: %s') % (name, e.message)
# Sometimes the root message is too generic, try to find a possible
# root cause:
cause = None
current = e
while current.context:
current = jsonschema.exceptions.best_match(current.context)
cause = current.message
if cause is not None:
error_msg += _('. Possible root cause: %s') % cause
raise exception.InvalidParameterValue(error_msg)
return value


Expand Down
5 changes: 5 additions & 0 deletions releasenotes/notes/jsonschema-4.8-1146d103b877cffd.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
fixes:
- |
Fixes API error messages with jsonschema>=4.8. A possible root cause is
now detected for generic schema errors.

0 comments on commit 41b01ca

Please sign in to comment.