Skip to content
This repository has been archived by the owner on Nov 8, 2024. It is now read-only.

Commit

Permalink
Merge pull request #515 from apiaryio/opichals/check-for-examples-rec…
Browse files Browse the repository at this point in the history
…ursively

chore(oas2): recursive generateBody
  • Loading branch information
opichals authored Jul 21, 2020
2 parents eafd062 + 9902c92 commit ee15d1f
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 5 deletions.
14 changes: 9 additions & 5 deletions packages/openapi2-parser/lib/generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,22 @@ faker.option({
random: () => 0,
});

const schemaIsArrayAndHasItems = schema => schema.type && schema.type === 'array' && schema.items;
const schemaIsArrayAndHasItems = schema => schema.type === 'array' && typeof schema.items === 'object';
const isEmptyArray = value => value && Array.isArray(value) && value.length === 0;

function generateBody(schema) {
if (schema.allOf && schema.allOf.length === 1 && schema.allOf[0].examples && schema.allOf[0].examples.length > 0) {
return schema.allOf[0].examples[0];
}

if (schema.examples && schema.examples.length > 0) {
return schema.examples[0];
}

if (schemaIsArrayAndHasItems(schema)) {
return Array.from({ length: Math.min(5, schema.minItems || 1) }, () => generateBody(schema.items));
}

if (schema.allOf && schema.allOf.length === 1) {
return generateBody(schema.allOf[0]);
}

const body = faker.generate(schema);

if (isEmptyArray(body) && schemaIsArrayAndHasItems(schema)) {
Expand Down
53 changes: 53 additions & 0 deletions packages/openapi2-parser/test/generator-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,5 +220,58 @@ describe('bodyFromSchema', () => {
expect(body).to.deep.equal({ name: 'doe' });
});
});

describe('allOf w/length 1', () => {
it('can generate an object', () => {
const schema = {
allOf: [
{
type: 'object',
examples: [{ name: 'doe' }],
},
],
};

const body = generate(schema);

expect(body).to.deep.equal({ name: 'doe' });
});

it('can generate an array', () => {
const schema = {
allOf: [
{
type: 'array',
items: {
type: 'string',
},
examples: [['doe']],
},
],
};

const body = generate(schema);

expect(body).to.deep.equal(['doe']);
});

it('can generate an array with items', () => {
const schema = {
allOf: [
{
type: 'array',
items: {
type: 'string',
examples: ['doe'],
},
},
],
};

const body = generate(schema);

expect(body).to.deep.equal(['doe']);
});
});
});
});

0 comments on commit ee15d1f

Please sign in to comment.