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

Commit ee15d1f

Browse files
authored
Merge pull request #515 from apiaryio/opichals/check-for-examples-recursively
chore(oas2): recursive generateBody
2 parents eafd062 + 9902c92 commit ee15d1f

File tree

2 files changed

+62
-5
lines changed

2 files changed

+62
-5
lines changed

packages/openapi2-parser/lib/generator.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,22 @@ faker.option({
1717
random: () => 0,
1818
});
1919

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

2323
function generateBody(schema) {
24-
if (schema.allOf && schema.allOf.length === 1 && schema.allOf[0].examples && schema.allOf[0].examples.length > 0) {
25-
return schema.allOf[0].examples[0];
26-
}
27-
2824
if (schema.examples && schema.examples.length > 0) {
2925
return schema.examples[0];
3026
}
3127

28+
if (schemaIsArrayAndHasItems(schema)) {
29+
return Array.from({ length: Math.min(5, schema.minItems || 1) }, () => generateBody(schema.items));
30+
}
31+
32+
if (schema.allOf && schema.allOf.length === 1) {
33+
return generateBody(schema.allOf[0]);
34+
}
35+
3236
const body = faker.generate(schema);
3337

3438
if (isEmptyArray(body) && schemaIsArrayAndHasItems(schema)) {

packages/openapi2-parser/test/generator-test.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,5 +220,58 @@ describe('bodyFromSchema', () => {
220220
expect(body).to.deep.equal({ name: 'doe' });
221221
});
222222
});
223+
224+
describe('allOf w/length 1', () => {
225+
it('can generate an object', () => {
226+
const schema = {
227+
allOf: [
228+
{
229+
type: 'object',
230+
examples: [{ name: 'doe' }],
231+
},
232+
],
233+
};
234+
235+
const body = generate(schema);
236+
237+
expect(body).to.deep.equal({ name: 'doe' });
238+
});
239+
240+
it('can generate an array', () => {
241+
const schema = {
242+
allOf: [
243+
{
244+
type: 'array',
245+
items: {
246+
type: 'string',
247+
},
248+
examples: [['doe']],
249+
},
250+
],
251+
};
252+
253+
const body = generate(schema);
254+
255+
expect(body).to.deep.equal(['doe']);
256+
});
257+
258+
it('can generate an array with items', () => {
259+
const schema = {
260+
allOf: [
261+
{
262+
type: 'array',
263+
items: {
264+
type: 'string',
265+
examples: ['doe'],
266+
},
267+
},
268+
],
269+
};
270+
271+
const body = generate(schema);
272+
273+
expect(body).to.deep.equal(['doe']);
274+
});
275+
});
223276
});
224277
});

0 commit comments

Comments
 (0)