Skip to content
Merged
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
4 changes: 2 additions & 2 deletions src/lib/core/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ function resolve(obj, data, values, property) {
}

// TODO provide types?
function run(refs, schema, container, synchronous) {
function run(refs, schema, container, synchronous, validateSchema) {
if (Object.prototype.toString.call(schema) !== '[object Object]') {
throw new Error(`Invalid input, expecting object but given ${typeof schema}`);
}
Expand All @@ -100,7 +100,7 @@ function run(refs, schema, container, synchronous) {
refDepthMin,
refDepthMax,
});
const result = traverse(utils.clone(schema), [], resolveSchema);
const result = traverse(utils.clone(schema), [], resolveSchema, undefined, validateSchema);

if (optionAPI('resolveJsonPath')) {
return {
Expand Down
46 changes: 37 additions & 9 deletions src/lib/core/traverse.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ function getMeta({ $comment: comment, title, description }) {
}

// TODO provide types
function traverse(schema, path, resolve, rootSchema) {
function traverse(schema, path, resolve, rootSchema, validateSchema) {
schema = resolve(schema, null, path);

if (schema && (schema.oneOf || schema.anyOf || schema.allOf)) {
Expand All @@ -36,14 +36,42 @@ function traverse(schema, path, resolve, rootSchema) {
// example values have highest precedence
if (optionAPI('useExamplesValue') && Array.isArray(schema.examples)) {
// include `default` value as example too
const fixedExamples = schema.examples
.concat('default' in schema ? [schema.default] : []);

return { value: utils.typecast(null, schema, () => random.pick(fixedExamples)), context };
const fixedExamples = schema.examples.concat(
'default' in schema ? [schema.default] : []);
const randomExample = random.pick(fixedExamples);
if (validateSchema) {
const result = validateSchema(schema, randomExample);
// Use example only if valid
if (result && result.length === 0) {
return {
value: utils.typecast(null, schema, () => randomExample),
context,
};
}
} else {
console.warn('Taking example from schema without validation');
return {
value: utils.typecast(null, schema, () => randomExample),
context,
};
}
}
// If schema contains single example property
if (optionAPI('useExamplesValue') && schema.example) {
return { value: utils.typecast(null, schema, () => schema.example), context };
if (validateSchema) {
const result = validateSchema(schema, schema.example);

// Use example only if valid
if (result && result.length === 0) {
return {
value: utils.typecast(null, schema, () => schema.example),
context,
};
}
} else {
console.warn('Taking example from schema without validation');
return { value: utils.typecast(null, schema, () => schema.example), context };
}
}

if (optionAPI('useDefaultValue') && 'default' in schema) {
Expand All @@ -66,15 +94,15 @@ function traverse(schema, path, resolve, rootSchema) {

// build new object value from not-schema!
if (schema.type && schema.type === 'object') {
const { value, context: innerContext } = traverse(schema, path.concat(['not']), resolve, rootSchema);
const { value, context: innerContext } = traverse(schema, path.concat(['not']), resolve, rootSchema, validateSchema);
return { value: utils.clean(value, schema, false), context: { ...context, items: innerContext } };
}
}

// thunks can return sub-schemas
if (typeof schema.thunk === 'function') {
// result is already cleaned in thunk
const { value, context: innerContext } = traverse(schema.thunk(rootSchema), path, resolve);
const { value, context: innerContext } = traverse(schema.thunk(rootSchema), path, resolve, undefined, validateSchema);
return { value, context: { ...context, items: innerContext } };
}

Expand Down Expand Up @@ -172,7 +200,7 @@ function traverse(schema, path, resolve, rootSchema) {
Object.keys(schema).forEach(prop => {
if (pruneProperties.includes(prop)) return;
if (typeof schema[prop] === 'object' && prop !== 'definitions') {
const { value, context: innerContext } = traverse(schema[prop], path.concat([prop]), resolve, valueCopy);
const { value, context: innerContext } = traverse(schema[prop], path.concat([prop]), resolve, valueCopy, validateSchema);
valueCopy[prop] = utils.clean(value, schema[prop], false);
contextCopy[prop] = innerContext;
} else {
Expand Down
5 changes: 5 additions & 0 deletions src/lib/generators/coreFormat.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import random from '../core/random';

/**
* Added few formats from latest json-schema-faker. see below for source
* https://github.com/json-schema-faker/json-schema-faker/blob/master/src/lib/generators/coreFormat.js
*
*/
const FRAGMENT = '[a-zA-Z][a-zA-Z0-9+-.]*';
const URI_PATTERN = `https?://{hostname}(?:${FRAGMENT})+`;
const PARAM_PATTERN = '(?:\\?([a-z]{1,7}(=\\w{1,5})?&){0,3})?';
Expand Down
12 changes: 6 additions & 6 deletions src/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,18 +93,18 @@ const jsf = (schema, refs, cwd) => {
return jsf.generate(schema, refs);
};

jsf.generateWithContext = (schema, refs) => {
jsf.generateWithContext = (schema, refs, validateSchema) => {
const $refs = getRefs(refs, schema);

return run($refs, schema, container, true);
return run($refs, schema, container, true, validateSchema);
};

jsf.generate = (schema, refs) => renderJS(
jsf.generateWithContext(schema, refs),
jsf.generate = (schema, refs, validateSchema) => renderJS(
jsf.generateWithContext(schema, refs, validateSchema),
);

jsf.generateYAML = (schema, refs) => renderYAML(
jsf.generateWithContext(schema, refs),
jsf.generateYAML = (schema, refs, validateSchema) => renderYAML(
jsf.generateWithContext(schema, refs, validateSchema),
);

jsf.resolveWithContext = (schema, refs, cwd) => {
Expand Down
2 changes: 1 addition & 1 deletion src/lib/types/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ function unique(path, items, value, sample, resolve, traverseCallback) {
items.forEach(walk);

// TODO: find a better solution?
let limit = 100;
let limit = 10;

while (tmp.length !== items.length) {
if (!walk(traverseCallback(value.items || sample, path, resolve))) {
Expand Down
60 changes: 60 additions & 0 deletions tests/unit/core/index.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { expect } from 'chai';
import jsf from '../../../src/lib';

describe('jsf generate', () => {
it('Take example without validation', () => {
const schema = {
type: 'integer',
format: 'int32',
example: 123,
};
jsf.option('useExamplesValue', true);
expect(jsf.generate(schema)).to.eql(123);
});
it('Take example with validation', () => {
const schema = {
type: 'integer',
format: 'int32',
example: 123,
};
jsf.option('useExamplesValue', true);
expect(jsf.generate(schema, undefined, () => { return []; })).to.eql(123);
});
it('Generate fake data when example is not valid', () => {
const schema = {
type: 'integer',
format: 'int32',
example: '123',
};
jsf.option('useExamplesValue', true);
expect(jsf.generate(schema, undefined, () => { return [{ error: 'some' }]; })).to.be.an('number');
});
it('Take one example from examples without validation', () => {
const schema = {
type: 'integer',
format: 'int32',
examples: [123, 456],
};
jsf.option('useExamplesValue', true);
expect([123, 456]).to.include(jsf.generate(schema));
});
it('Take one example from examples with validation', () => {
const schema = {
type: 'integer',
format: 'int32',
examples: [123, 456],
};
jsf.option('useExamplesValue', true);
expect([123, 456]).to.include(jsf.generate(schema, undefined, () => { return []; }));
});
it('Generate fake data when example from examples is not valid', () => {
const schema = {
type: 'integer',
format: 'int32',
examples: ['123', '456'],
};
jsf.option('useExamplesValue', true);
expect(jsf.generate(schema, undefined, () => { return [{ error: 'some' }]; })).to.be.an('number');
});
});