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

chore(oas2): recursive generateBody #515

Merged
merged 3 commits into from
Jul 21, 2020
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
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']);
});
});
});
});