xeipuuv / gojsonschema

An implementation of JSON Schema, draft v4 v6 & v7 - Go language
2.56k stars 358 forks source link

Schema validation does not return error for invalid schema definition #376

Open NV4RE opened 5 months ago

NV4RE commented 5 months ago

When using the gojsonschema library, I encountered an issue where the schema validation does not return an error if the schema definition itself is not valid. This can lead to confusion and unexpected behavior, as the validation process proceeds without indicating that the schema is malformed.

https://go.dev/play/p/AlvO42OM74F

package main

import (
    "fmt"
    "github.com/xeipuuv/gojsonschema"
)

func main() {
    schemaLoader := gojsonschema.NewStringLoader(`{"i am not": "real schema"}`)
    documentLoader := gojsonschema.NewStringLoader(`{"snake_snake": 3,"foo":{"bar":"baz","animals":["dog","cat","pengiun"],"number":3}}`)

    result, err := gojsonschema.Validate(schemaLoader, documentLoader)
    if err != nil {
        panic(err.Error())
    }

    if result.Valid() {
        fmt.Printf("The document is valid\n")
    } else {
        fmt.Printf("The document is not valid. see errors :\n")
        for _, desc := range result.Errors() {
            fmt.Printf("- %s\n", desc)
        }
    }
}

Expected Behavior The program should return an error indicating that the schema definition is not valid.

Actual Behavior The program does not return an error for the invalid schema definition and proceeds to validate the document against the malformed schema.

Environment gojsonschema version: v1.2.0 Go version: go1.21.5 OS: darwin/arm64

siller174 commented 3 weeks ago

It seems that we can only check by the "type" in the root schema. If it is present, we should return an error.

https://github.com/xeipuuv/gojsonschema/pull/379/files