Skip to content

Commit

Permalink
feat: validate_schema for literal error
Browse files Browse the repository at this point in the history
  • Loading branch information
tklockau committed Nov 25, 2024
1 parent 216139f commit 65c1e82
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ def _make_errors_readable(errors: ValidationError) -> list[str]:
readable_errors.append(_convert_missing_error_to_string(error))
elif error["type"] == "extra_forbidden":
readable_errors.append(_convert_unexpected_field_error_to_string(error))
elif error["type"] == "literal_error":
readable_errors.append(_convert_literal_error_to_string(error))
else:
raise ValueError

Expand All @@ -40,6 +42,13 @@ def _convert_unexpected_field_error_to_string(error: dict) -> str:
return f"{_build_error_path(error["loc"][:-1])}: found unexpected field '{error["loc"][-1]}'."


def _convert_literal_error_to_string(error: dict) -> str:
return (
f"{_build_error_path(error["loc"])}: value '{error["input"]}' does not match allowed values "
f"({error["ctx"]["expected"]})."
)


def _build_error_path(loc: list[str]) -> str:
path = "$"
for part in loc:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ def test_no_errors__empty():


def test_required_field_missing():
data = {"openlabel": {}}
data = {"openlabel": {"metadata": {}}}

actual = validate_schema(data)
assert len(actual) == 1
assert "$.openlabel" in actual[0]
assert "$.openlabel.metadata" in actual[0]
assert "required" in actual[0]
assert "metadata" in actual[0]
assert "schema_version" in actual[0]
assert "missing" in actual[0]


Expand All @@ -34,5 +34,16 @@ def test_unsupported_field():
assert "UNSUPPORTED_FIELD" in actual[0]


def test_unexpected_value():
data = {"openlabel": {"metadata": {"schema_version": "SOMETHING UNSUPPORTED"}}}

actual = validate_schema(data)
assert len(actual) == 1
assert "$.openlabel.metadata.schema_version" in actual[0]
assert "value" in actual[0]
assert "SOMETHING UNSUPPORTED" in actual[0]
assert "'1.0.0'" in actual[0]


if __name__ == "__main__":
pytest.main([__file__, "-v"])

0 comments on commit 65c1e82

Please sign in to comment.