diff --git a/src/core/plugins/json-schema-2020-12/samples-extensions/fn.js b/src/core/plugins/json-schema-2020-12/samples-extensions/fn.js index 08cf3ec7..03c4d5b0 100644 --- a/src/core/plugins/json-schema-2020-12/samples-extensions/fn.js +++ b/src/core/plugins/json-schema-2020-12/samples-extensions/fn.js @@ -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) { diff --git a/test/unit/core/plugins/json-schema-2020-12/samples-extensions/fn.js b/test/unit/core/plugins/json-schema-2020-12/samples-extensions/fn.js index f6fc96e0..48f3a383 100644 --- a/test/unit/core/plugins/json-schema-2020-12/samples-extensions/fn.js +++ b/test/unit/core/plugins/json-schema-2020-12/samples-extensions/fn.js @@ -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",