`Validator`s pubilc API

Offen
#1,422 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Maintainer antworten meist innerhalb von 6 Tagen

Dieses Issue hat noch niemand übernommen.

Bewertung

Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Anfängerfreundlichkeit
25/100
Issue-Typ
Feature
Klarheit
Größtenteils klar
Aktivitätsstatus
Veraltet
Tech-Stack
python

Rechercherichtung

Beginne mit dem Validator-Protokoll, validators.extend, Draft202012Validator und dem im Issue gezeigten Validator für benutzerdefinierte Eigenschaften. Vergleiche die öffentliche API mit der Verwendung von validator.descend und ermittle, wie pfadbezogene benutzerdefinierte Fehler funktionieren sollen. Erledigt ist die Aufgabe, wenn der unterstützte Ansatz oder die erforderliche API-/Dokumentationsänderung eindeutig feststeht.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

Hello, I'm struggling to enforce some custom validation on properties through extending a Validator and maybe someone can help me out or clarify how extending should work. Note that I want to add validation for a JSONSchema authored by a user - so it's more "meta validation".

Essentially I want to do something like enforcing that if a property is marked as "required" it should not specify a default, and conversely if it specify a default it should not appear in the required array at its level".

I can get something that seems to be working at a high level below:

from jsonschema import Draft202012Validator, validators, exceptions
from jsonschema.protocols import Validator

validate_properties = Draft202012Validator.VALIDATORS["properties"]

def custom_properties_validator(validator, properties, instance, schema):
    # Maintain old behaviour
    yield from validate_properties(validator, properties, instance, schema)

    # Extend behaviour
    if not validator.is_type(instance, "object"):
        return

    current_properties = instance.get("properties", {})
    required_properties = instance.get("required", [])

    for prop_name, prop_schema in current_properties.items():
        is_required = prop_name in required_properties
        has_default = "default" in prop_schema

        if not is_required and not has_default:
            yield exceptions.ValidationError(
                f"Primitive property '{prop_name}' is not required and must have a 'default' value."
            )
        if has_default and is_required:
            yield exceptions.ValidationError(
                f"Primitive property '{prop_name}' has a 'default' value and must not be in the 'required' list."
            )

if __name__ == "__main__":
    user_schema = {
        "type": "object",
        "title": "test",
        "properties": {
            "test": {"type": "string"},
        },
        "required": []
    }

    my_validator: Validator = validators.extend(
        Draft202012Validator,
        {"properties": custom_properties_validator},
    )
    errors = list(my_validator(Draft202012Validator.META_SCHEMA).iter_errors(user_schema))
    print(f"Found {len(errors)} validation errors:")
    for i, error in enumerate(errors, 1):
        path_str = " -> ".join(map(str, error.path))
        print(f"  {i}. JSONPath: {error.json_path}")
        print(f"  {i}. Path: {path_str}")
        print(f"     Error: {error.message}")

But there's a big caveat as in I can't really know what's the path of the property I am failing to validate!

I can kinda start to cheat my way into it by doing something more like

        if not is_required and not has_default:
            for err in validator.descend(
                    required_properties,
                    {"contains": {"const": prop_name}},
                    path="properties",
            ):
                err.message = f"'{prop_name}' is not required and must have a 'default' value."
                yield err

in the custom validation steps, but

  • I can only descend one level - maybe I can call it twice in this case but it will seem even hackyer
  • I am using descend, which is not documented in the validator protocol public API

Is my only way around this implementing the schema-walking part myself so that I can keep track of my own custom errors? Or am I simply making use of the library in an improper way?

Vorherrschende Sprache
Python
Sterne
5k
Forks
718
Ø Merge
5 T. 9 Std.
Gemergte PRs (30 T.)
5

Entwicklungsumgebung

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus python-jsonschema/jsonschema

Alle Issues in python-jsonschema/jsonschema

Ähnliche Issues

Weitere Issues zu Python

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.