kotest / kotest

Powerful, elegant and flexible test framework for Kotlin with assertions, property testing and data driven tests.
https://kotest.io
Apache License 2.0
4.43k stars 648 forks source link

Add `JsonSchema` Support for Multiple Types #4463

Open solonovamax opened 1 day ago

solonovamax commented 1 day ago

Basically just JSON Schema's anyOf and/or oneOf

This feature is similar, although not identical, to #2980. (in certain cases #2980 is a replacement for this, although it does not fit all cases)

an example syntax would look like this:

val stringOrIntegerListSchema = jsonSchema {
    array {
        anyOf(string(), integer())
    }
}

"""[ "foo", "bar", "baz" ]""" shouldMatchSchema stringOrIntegerListSchema // passes
"""[ 1, 2, 3 ]""" shouldMatchSchema stringOrIntegerListSchema // passes
"""[ true, false ]""" shouldMatchSchema stringOrIntegerListSchema // fails

in order to do this, it would either be necessary to add an additional JsonSchemaElement called something like JsonCompositeElement, which composes multiple elements (imo the less desirable choice) or to change the JsonSchema.JsonObjectBuilder.properties field from a MutableMap<String, JsonSchemaElement> to a MutableMap<String, Matcher<JsonSchemaElement>> (imo the better choice)

AlexCue987 commented 15 hours ago

can you share some real life use cases where this feature would be needed?

solonovamax commented 12 hours ago

can you share some real life use cases where this feature would be needed?

I'm trying to make a schema that matches a fabric.mod.json file. A couple of examples from it:

I don't have any control over this schema, and am just generating some json according to this schema and want to validate it.

solonovamax commented 12 hours ago

My serialization code can be found here if that would help: SerialFabricModJson.kt. This should be able to parse all valid fabric.mod.json files and fail on any invalid one.

solonovamax commented 12 hours ago

Also, I sent a message in the kotlinlang's kotest slack channel, if you'd like to discuss this further there in a platform more suitable for Q&A