Validate that oneOf and anyOf compositions define a discriminator
IN
6d ago+269+269+012345678901234567890123456789-6-6-0123456789
What
Adds a new style rule for the concern raised in #806: a schema that composes alternative models with oneOf or anyOf should define a discriminator, so that API consumers can tell the possible object types apart (see the Swagger documentation on inheritance and polymorphism referenced in the issue).
Rule semantics
- Every schema of
components/schemasthat declares a non-emptyoneOforanyOfand has nodiscriminatoris reported:
*ERROR* in Model 'MyComposition', field 'discriminator' -> A schema with a oneOf or anyOf composition should define a discriminator - The discriminator is considered defined when the composing schema carries a
discriminatorobject, as documented by the Swagger reference (the discriminator lives on the schema that carriesoneOf/anyOf). allOfis out of scope: it describes a merged model rather than a set of alternatives, and the referenced documentation limits the use of the discriminator tooneOfandanyOf.- The check is limited to the named schemas of
components/schemas, like the existing model rules; covering inline compositions (e.g. in responses) could be a follow-up.
Config
New option validateModelDiscriminator (boolean, default true), following the repo convention of enabling all rules by default:
- documented in the README options table
- wired through the gradle plugin task and the maven plugin mojo
- usable in the CLI options file (parsed by name, like the other options)
Tests
testModelDiscriminatorValidation(parameterized):oneOfwithout a discriminator is reported when the rule is on and stays silent when the flag is offtestModelDiscriminatorValidationSuccessWhenDiscriminatorIsDefined: aoneOfschema with adiscriminatorproduces no errortestModelDiscriminatorValidationReportsAnyOfComposition:anyOfcompositions are covered tootestModelDiscriminatorValidationIgnoresAllOfComposition:allOfis not reportedValidatorParametersTestcovers the new default;ErrorAggregatorTestcovers the new error; the CLIdefault.jsonfixture was updated accordingly
./gradlew spotlessApply test passes on all modules (lib, cli, gradle-plugin, maven-plugin).
Fixes #806
Summary by cubic
Adds a model validation rule that flags named schemas in components/schemas with a non-empty oneOf or anyOf composition that don't define a discriminator, so consumers can tell the possible object types apart.
New Features
- New
validateModelDiscriminatoroption (defaults totrue) exposed through the CLI, Gradle, and Maven plugins. - Only named schemas in
components/schemasare checked; inline and empty compositions are not reported. allOfis ignored since it describes a merged model rather than a set of alternatives.