From 3d79c2494946f975ee820168a7bddf95dc4c2630 Mon Sep 17 00:00:00 2001 From: dewijones92 Date: Fri, 4 Mar 2022 00:31:00 +0000 Subject: [PATCH] fix(examples): allow string created by regex pattern (#7829) Co-authored-by: Tim Lai --- package.json | 1 + src/core/plugins/samples/fn.js | 8 +++++++- test/unit/core/plugins/samples/fn.js | 17 +++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 6b726893..b9883106 100644 --- a/package.json +++ b/package.json @@ -74,6 +74,7 @@ "js-yaml": "=4.1.0", "lodash": "^4.17.21", "prop-types": "^15.8.1", + "randexp": "^0.5.3", "randombytes": "^2.1.0", "react": "=17.0.2", "react-copy-to-clipboard": "5.0.4", diff --git a/src/core/plugins/samples/fn.js b/src/core/plugins/samples/fn.js index 41b1cd19..d66b504e 100644 --- a/src/core/plugins/samples/fn.js +++ b/src/core/plugins/samples/fn.js @@ -1,11 +1,17 @@ import XML from "xml" +import RandExp from "randexp" import isEmpty from "lodash/isEmpty" import { objectify, isFunc, normalizeArray, deeplyStripKey } from "core/utils" import memoizeN from "../../../helpers/memoizeN" +const generateStringFromRegex = (pattern) => { + const randexp = new RandExp(pattern) + return randexp.gen() +} + const primitives = { - "string": () => "string", + "string": (schema) => schema.pattern ? generateStringFromRegex(schema.pattern) : "string", "string_email": () => "user@example.com", "string_date-time": () => new Date().toISOString(), "string_date": () => new Date().toISOString().substring(0, 10), diff --git a/test/unit/core/plugins/samples/fn.js b/test/unit/core/plugins/samples/fn.js index 7166db8d..a456a4bf 100644 --- a/test/unit/core/plugins/samples/fn.js +++ b/test/unit/core/plugins/samples/fn.js @@ -153,6 +153,23 @@ describe("sampleFromSchema", () => { expect(sampleFromSchema(definition, { includeReadOnly: true })).toEqual(expected) }) + + + it("regex pattern test", function () { + let definition = { + type: "object", + properties: { + macAddress: { + type: "string", + pattern: "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$" + } + } + } + const resp = sampleFromSchema(definition) + + expect(new RegExp("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$", "g").test(resp.macAddress)).toBe(true) + }) + it("returns object without deprecated fields for parameter", function () { let definition = { type: "object",