feat(samples): support multipleOf keyword (#8890)

This change is specific ti JSON Schema 2020-12
and OpenAPI 3.1.0.

Refs #8577
This commit is contained in:
Vladimír Gorej
2023-06-07 11:48:10 +02:00
committed by GitHub
parent 3e81a4f897
commit 68cfe46490
2 changed files with 22 additions and 4 deletions

View File

@@ -80,11 +80,12 @@ const sanitizeRef = (value) =>
const objectContracts = ["maxProperties", "minProperties"]
const arrayContracts = ["minItems", "maxItems"]
const numberContracts = [
const numberConstraints = [
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"multipleOf",
]
const stringContracts = ["minLength", "maxLength"]
@@ -104,7 +105,7 @@ const liftSampleHelper = (oldSchema, target, config = {}) => {
"const",
...objectContracts,
...arrayContracts,
...numberContracts,
...numberConstraints,
...stringContracts,
].forEach((key) => setIfNotDefinedInTarget(key))
@@ -271,7 +272,7 @@ export const sampleFromSchemaGeneric = (
type = "object"
} else if (items || schemaHasAny(arrayContracts)) {
type = "array"
} else if (schemaHasAny(numberContracts)) {
} else if (schemaHasAny(numberConstraints)) {
type = "number"
schema.type = "number"
} else if (!usePlainValue && !schema.enum) {
@@ -695,6 +696,7 @@ export const sampleFromSchemaGeneric = (
value = primitive(schema)
if (typeof value === "number") {
const { minimum, maximum, exclusiveMinimum, exclusiveMaximum } = schema
const { multipleOf } = schema
const epsilon = Number.isInteger(value) ? 1 : Number.EPSILON
let minValue = typeof minimum === "number" ? minimum : null
let maxValue = typeof maximum === "number" ? maximum : null
@@ -711,8 +713,12 @@ export const sampleFromSchemaGeneric = (
? Math.min(maxValue, exclusiveMaximum - epsilon)
: exclusiveMaximum - epsilon
}
value = (minValue > maxValue && value) || minValue || maxValue || value
if (typeof multipleOf === "number" && multipleOf > 0) {
const remainder = value % multipleOf
value = remainder === 0 ? value : value + multipleOf - remainder
}
}
if (typeof value === "string") {
if (schema.maxLength !== null && schema.maxLength !== undefined) {

View File

@@ -1330,6 +1330,18 @@ describe("sampleFromSchema", () => {
expect(sampleFromSchema(definition)).toEqual(expected)
})
it("should handle multipleOf", () => {
const definition = {
type: "number",
minimum: 22,
multipleOf: 3,
}
const expected = 24
expect(sampleFromSchema(definition)).toStrictEqual(expected)
})
it("should handle minLength", () => {
const definition = {
type: "string",