From 65c1e82f46e74a7bdef8bff2fb9fedb234e66b7f Mon Sep 17 00:00:00 2001 From: Tobias Klockau Date: Mon, 25 Nov 2024 12:56:35 +0100 Subject: [PATCH] feat: validate_schema for literal error --- .../validate_schema/validate_schema.py | 9 +++++++++ .../validate_schema/test_validate_schema.py | 17 ++++++++++++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/raillabel_providerkit/validation/validate_schema/validate_schema.py b/raillabel_providerkit/validation/validate_schema/validate_schema.py index c3320a4..82ea0cb 100644 --- a/raillabel_providerkit/validation/validate_schema/validate_schema.py +++ b/raillabel_providerkit/validation/validate_schema/validate_schema.py @@ -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 @@ -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: diff --git a/tests/test_raillabel_providerkit/validation/validate_schema/test_validate_schema.py b/tests/test_raillabel_providerkit/validation/validate_schema/test_validate_schema.py index ab65ccb..f3fc990 100644 --- a/tests/test_raillabel_providerkit/validation/validate_schema/test_validate_schema.py +++ b/tests/test_raillabel_providerkit/validation/validate_schema/test_validate_schema.py @@ -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] @@ -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"])