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 1 commit
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 = {
randomEnabled: false,
Copy link
Member

Choose a reason for hiding this comment

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

These boolean properties might be confusing as they come with double boolean logic. Let's use string enum of [random, constant].

Suggested change
randomEnabled: false,
mode: 'constant',

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ok makes sense. Actually nice as there could be more modes in the future.

random: Math.random,
minInt: 0,
Copy link
Member

Choose a reason for hiding this comment

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

Let's align with json-schema-faker here:

Suggested change
minInt: 0,
minInteger: -100000000,

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ok

maxInt: 2147483647,
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
maxInt: 2147483647,
maxInteger: +100000000,

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ok

minLen: 4,
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
minLen: 4,
minLength: 0,

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@char0n this will generate samples with empty strings by default? Is that what we want as a default behavior?

maxLen: 10,
Copy link
Member

@char0n char0n Apr 12, 2024

Choose a reason for hiding this comment

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

No upper boundary

Suggested change
maxLen: 10,
maxLength: Number.MAX_SAFE_INTEGER,

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@char0n this will generate samples with extremely long strings by default? Is that what we want as a default behavior?

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
maxRandExp: 100,
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
maxRandExp: 100,
defaultRandExpMax: 10,

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah 10 is fine which is what I initially thought of, but note that it will change the default behavior of randExp which is 100. But I think it's for the better to keep samples shorter and more readable.

}

data = { ...this.#defaults }

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

registerMany(nameValueMap) {
Object.keys(nameValueMap).forEach(name => {
char0n marked this conversation as resolved.
Show resolved Hide resolved
this.data[name] = nameValueMap[name]
})
}

unregister(name) {
if (typeof name === "undefined") {
this.data = {}
Expand Down
34 changes: 24 additions & 10 deletions src/core/plugins/json-schema-2020-12-samples/fn/core/random.js
Expand Up @@ -3,19 +3,22 @@
*/
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.
*/
export 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("maxRandExp")
RandExp.prototype.randInt = randInt

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

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

export const string = () => optionAPI("randomEnabled") ? randexp(`[a-z]{${optionAPI("minLen")},${optionAPI("maxLen")}}`) : "string"

export const integer = () => optionAPI("randomEnabled") ? randInt(optionAPI("minInt"), optionAPI("maxInt")) : 0

export const string = () => "string"
export const number = () => integer()

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

export const date = () => {
if (!optionAPI("randomEnabled")) {
return new Date()
}

export const number = () => 0
let earliest = new Date(optionAPI("minDateTime"))
let 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("randomEnabled", true)
optionAPI("random", () => 0)
optionAPI("minInt", 4)
optionAPI("minLen", 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("randomEnabled", true)
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