Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/* ============================================================================
* Copyright (c) Palo Alto Networks
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* ========================================================================== */

import { sampleFromSchema } from "./createSchemaExample";
import { SchemaObject } from "./types";

describe("sampleFromSchema", () => {
describe("const support", () => {
it("should return default string value when const is not present", () => {
const schema: SchemaObject = {
type: "string",
};
const context = { type: "request" as const };

const result = sampleFromSchema(schema, context);

expect(result).toBe("string");
});

it("should return const value when const is present", () => {
const schema: SchemaObject = {
type: "string",
const: "example",
};
const context = { type: "request" as const };

const result = sampleFromSchema(schema, context);

expect(result).toBe("example");
});

it("should handle anyOf with const values", () => {
const schema: SchemaObject = {
type: "string",
anyOf: [
{
type: "string",
const: "dog",
},
{
type: "string",
const: "cat",
},
],
};
const context = { type: "request" as const };

const result = sampleFromSchema(schema, context);

expect(result).toBe("dog");
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,16 @@ export const sampleFromSchema = (
try {
// deep copy schema before processing
let schemaCopy = JSON.parse(JSON.stringify(schema));
let { type, example, allOf, properties, items, oneOf, anyOf } = schemaCopy;
let {
type,
example,
allOf,
properties,
items,
oneOf,
anyOf,
const: constant,
} = schemaCopy;

if (example !== undefined) {
return example;
Expand Down Expand Up @@ -218,6 +227,10 @@ export const sampleFromSchema = (
return undefined;
}

if (constant) {
return constant;
}

return primitive(schemaCopy);
} catch (err) {
console.error(
Expand Down