Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(json-schema-2020-12-samples): support randomness option #9810

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -13,5 +13,7 @@ const optionAPI = (optionName, optionValue) => {

return registry.get(optionName)
}
optionAPI.getDefaults = () => registry.defaults
optionAPI.setDefaults = () => registry.registerMany(registry.defaults)
char0n marked this conversation as resolved.
Show resolved Hide resolved

export default optionAPI
Expand Up @@ -4,7 +4,17 @@
import Registry from "./Registry"

class OptionRegistry extends Registry {
#defaults = {}
#defaults = {
mode: "constant",
random: Math.random,
minInteger: -100000000,
maxInteger: +100000000,
minLength: 4,
maxLength: 10,
minDateTime: new Date("1970-01-01T00:00:00.000Z"),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
minDateTime: new Date("1970-01-01T00:00:00.000Z"),
minDateTime: new Date("1889-12-31T00:00:00.000Z"),

maxDateTime: new Date("2038-01-19T00:00:00.000Z"),
char0n marked this conversation as resolved.
Show resolved Hide resolved
defaultRandExpMax: 10,
}

data = { ...this.#defaults }

Expand Down
Expand Up @@ -8,6 +8,10 @@ class Registry {
this.data[name] = value
}

registerMany(nameValueMap) {
Object.assign(this.data, nameValueMap)
}

unregister(name) {
if (typeof name === "undefined") {
this.data = {}
Expand Down
36 changes: 26 additions & 10 deletions src/core/plugins/json-schema-2020-12-samples/fn/core/random.js
Expand Up @@ -3,19 +3,24 @@
*/
import randomBytes from "randombytes"
import RandExp from "randexp"
import optionAPI from "../api/optionAPI"

/**
* Some of the functions returns constants. This is due to the nature
* of SwaggerUI expectations - provide as stable data as possible.
* Most of the functions return constants by default unless randomness option is enabled.
* This is due to the nature of SwaggerUI expectations - provide as stable data as possible.
*
* In future, we may decide to randomize these function and provide
* true random values.
*/
const randomMode = () => optionAPI("mode") === "random"

const randInt = (min, max) => min + Math.floor(optionAPI("random")() * (1 + (max - min)))

export const bytes = (length) => randomBytes(length)

export const randexp = (pattern) => {
try {
RandExp.prototype.max = optionAPI("defaultRandExpMax")
RandExp.prototype.randInt = randInt

const randexpInstance = new RandExp(pattern)
return randexpInstance.gen()
} catch {
Expand All @@ -24,12 +29,23 @@ export const randexp = (pattern) => {
}
}

export const pick = (list) => {
return list.at(0)
}
export const pick = (list) => randomMode() ? list[Math.floor(optionAPI("random")() * list.length)] : list.at(0)

export const string = () => randomMode() ? randexp(`[a-z]{${optionAPI("minLength")},${optionAPI("maxLength")}}`) : "string"

export const string = () => "string"
export const integer = () => randomMode() ? randInt(optionAPI("minInteger"), optionAPI("maxInteger")) : 0

export const number = () => integer()

export const boolean = () => randomMode() ? optionAPI("random")() > 0.5 : true

export const date = () => {
if (!randomMode()) {
return new Date()
}

export const number = () => 0
const earliest = new Date(optionAPI("minDateTime"))
const latest = new Date(optionAPI("maxDateTime"))

export const integer = () => 0
return new Date(randInt(earliest.getTime(), latest.getTime()))
}
@@ -1,6 +1,8 @@
/**
* @prettier
*/
const dateTimeGenerator = () => new Date().toISOString()
import { date as randomDate } from "../core/random"

const dateTimeGenerator = () => randomDate().toISOString()

export default dateTimeGenerator
@@ -1,6 +1,8 @@
/**
* @prettier
*/
const dateGenerator = () => new Date().toISOString().substring(0, 10)
import { date as randomDate } from "../core/random"

const dateGenerator = () => randomDate().toISOString().substring(0, 10)

export default dateGenerator
@@ -1,6 +1,8 @@
/**
* @prettier
*/
const timeGenerator = () => new Date().toISOString().substring(11)
import { date as randomDate } from "../core/random"

const timeGenerator = () => randomDate().toISOString().substring(11)

export default timeGenerator
@@ -1,9 +1,10 @@
/**
* @prettier
*/
import { boolean as randomBoolean } from "../core/random"

const booleanType = (schema) => {
return typeof schema.default === "boolean" ? schema.default : true
return typeof schema.default === "boolean" ? schema.default : randomBoolean()
}

export default booleanType
90 changes: 90 additions & 0 deletions test/unit/core/plugins/json-schema-2020-12-samples/fn.js
Expand Up @@ -10,8 +10,11 @@ import {
memoizedSampleFromSchema,
mergeJsonSchema,
} from "core/plugins/json-schema-2020-12-samples/fn"
import optionAPI from "core/plugins/json-schema-2020-12-samples/fn/api/optionAPI"

describe("sampleFromSchema", () => {
beforeEach(() => optionAPI.setDefaults())

it("should return appropriate example for primitive types + format", function () {
const sample = (schema) => sampleFromSchema(fromJS(schema))

Expand Down Expand Up @@ -89,6 +92,83 @@ describe("sampleFromSchema", () => {
expect(sample({ type: "null" })).toStrictEqual(null)
})

it("should return appropriate example for primitive types + format with randomness enabled", function () {
optionAPI("mode", "random")
optionAPI("random", () => 0)
optionAPI("minInteger", 4)
optionAPI("minLength", 6)
optionAPI("minDateTime", "2024-01-01T00:00:00.000Z")

const sample = (schema) => sampleFromSchema(fromJS(schema))

expect(sample({ type: "string" })).toStrictEqual("aaaaaa")
expect(sample({ type: "string", pattern: "^abc$" })).toStrictEqual("abc")
expect(sample({ type: "string", format: "email" })).toStrictEqual(
"user@example.com"
)
expect(sample({ type: "string", format: "idn-email" })).toStrictEqual(
"실례@example.com"
)
expect(sample({ type: "string", format: "hostname" })).toStrictEqual(
"example.com"
)
expect(sample({ type: "string", format: "idn-hostname" })).toStrictEqual(
"실례.com"
)
expect(sample({ type: "string", format: "ipv4" })).toStrictEqual(
"198.51.100.42"
)
expect(sample({ type: "string", format: "ipv6" })).toStrictEqual(
"2001:0db8:5b96:0000:0000:426f:8e17:642a"
)
expect(sample({ type: "string", format: "uri" })).toStrictEqual(
"https://example.com/"
)
expect(sample({ type: "string", format: "uri-reference" })).toStrictEqual(
"path/index.html"
)
expect(sample({ type: "string", format: "iri" })).toStrictEqual(
"https://실례.com/"
)
expect(sample({ type: "string", format: "iri-reference" })).toStrictEqual(
"path/실례.html"
)
expect(sample({ type: "string", format: "uuid" })).toStrictEqual(
"3fa85f64-5717-4562-b3fc-2c963f66afa6"
)
expect(sample({ type: "string", format: "uri-template" })).toStrictEqual(
"https://example.com/dictionary/{term:1}/{term}"
)
expect(sample({ type: "string", format: "json-pointer" })).toStrictEqual(
"/a/b/c"
)
expect(
sample({ type: "string", format: "relative-json-pointer" })
).toStrictEqual("1/0")
expect(sample({ type: "string", format: "date-time" })).toStrictEqual("2024-01-01T00:00:00.000Z")
expect(sample({ type: "string", format: "date" })).toStrictEqual("2024-01-01")
expect(sample({ type: "string", format: "time" })).toStrictEqual("00:00:00.000Z")
expect(sample({ type: "string", format: "duration" })).toStrictEqual("P3D")
expect(sample({ type: "string", format: "password" })).toStrictEqual(
"********"
)
expect(sample({ type: "string", format: "regex" })).toStrictEqual(
"^[a-z]+$"
)
expect(sample({ type: "number" })).toStrictEqual(4)
expect(sample({ type: "number", format: "float" })).toStrictEqual(0.1)
expect(sample({ type: "number", format: "double" })).toStrictEqual(0.1)
expect(sample({ type: "integer" })).toStrictEqual(4)
expect(sample({ type: "integer", format: "int32" })).toStrictEqual(
(2 ** 30) >>> 0
)
expect(sample({ type: "integer", format: "int64" })).toStrictEqual(
2 ** 53 - 1
)
expect(sample({ type: "boolean" })).toStrictEqual(false)
expect(sample({ type: "null" })).toStrictEqual(null)
})

it("should return appropriate example given contentEncoding", function () {
const sample = (schema) => sampleFromSchema(fromJS(schema))

Expand Down Expand Up @@ -420,6 +500,16 @@ describe("sampleFromSchema", () => {
)
})

it("should return random enum value when randomness is enabled", function () {
optionAPI("mode", "random")
optionAPI("random", () => 0.5)

const definition = fromJS({enum: ["a", "b", "c"]})
const expected = "b"

expect(sampleFromSchema(definition)).toStrictEqual(expected)
})

it("combine first oneOf or anyOf with schema's definitions", function () {
let definition = {
type: "object",
Expand Down