Skip to content

Commit

Permalink
New: buffer for blueprint and swagger. Fixes #30
Browse files Browse the repository at this point in the history
  • Loading branch information
pustovitDmytro committed Aug 27, 2022
1 parent f20884e commit 6483141
Show file tree
Hide file tree
Showing 7 changed files with 158 additions and 19 deletions.
4 changes: 3 additions & 1 deletion src/handlebars.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import { DEFAULT_JSON_OFFSET } from './constants';


handleBars.registerHelper('json', (data) => {
const text = JSON.stringify(data, null, DEFAULT_JSON_OFFSET);
const text = Buffer.isBuffer(data)
? inspect(data)
: JSON.stringify(data, null, DEFAULT_JSON_OFFSET);

return new handleBars.SafeString(text);
});
Expand Down
2 changes: 2 additions & 0 deletions src/modules/Action.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ export default class Action {
}

get resBody() {
if (Buffer.isBuffer(this._response.body)) return Buffer.from('BINARY DATA');

return this._response.body;
}

Expand Down
11 changes: 10 additions & 1 deletion src/reporters/Swagger.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { inspect } from 'util';
import fs from 'fs-extra';
import dP from 'dot-prop';
import { DEFAULT_JSON_OFFSET } from '../constants';
Expand Down Expand Up @@ -32,6 +33,14 @@ export default class SwaggerReporter extends Base {

if (body === null) result.nullable = true;

if (Buffer.isBuffer(body)) {
return {
type : 'string',
format : 'binary',
example : inspect(body)
};
}

if (body && result.type === 'object') {
for (const [ key, value ] of Object.entries(body)) {
dP.set(result, `properties.${key}`, this._renderBody(value));
Expand Down Expand Up @@ -67,7 +76,7 @@ export default class SwaggerReporter extends Base {

_generate(groups, map, actions) {
const paths = {};
const origins = [ ...new Set(actions.map(a => a.request.origin)) ];
const origins = [ ...new Set(actions?.map(a => a.request.origin)) ];

for (const [ path, methods ] of Object.entries(groups)) {
for (const [ method, actionIds ] of Object.entries(methods)) {
Expand Down
4 changes: 4 additions & 0 deletions src/requests/Express.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ function chronicleMiddleware(req, res, next) {
parsedBody = JSON.parse(body);
}

if (body && type === 'mimetype') {
parsedBody = Buffer.from(body);
}

action.response = {
body : parsedBody,
headers : res.getHeaders(),
Expand Down
139 changes: 139 additions & 0 deletions tests/features/buffer.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { assert } from 'chai';
import nativeAxios from 'axios';
import Test from '../Test';
import chronicle, { reporters, supertest, middlewares } from '../entry';
import { mockAppUrl } from '../constants';


const factory = new Test(chronicle);
const request = supertest(factory.mockApp);
const expressMiddleWare = middlewares.express(chronicle);

suite('Feature: Buffer');

/* eslint-disable promise/prefer-await-to-callbacks*/
/* eslint-disable no-param-reassign*/
function binaryParser(res, callback) {
res.setEncoding('binary');
res.data = '';
res.on('data', function (chunk) {
res.data += chunk;
});
res.on('end', function () {
callback(null, Buffer.from(res.data, 'binary'));
});
}
/* eslint-enable */

const SAMPLE_FILE = 'example of text file\nnew line';

before(async function () {
await factory.cleanup();
await factory.setActions(chronicle, [ {
'context' : {
'group' : 'Features',
'title' : 'Buffer'
},
'url' : 'http://127.0.0.1:62887/file.txt',
'method' : 'GET',
'resBody' : Buffer.from('SOME_LONG_BINARY_CONTENT')
} ]);

await factory.setTmpFolder();
factory.mockApp.use(expressMiddleWare(req => {
return {
group : 'Format',
title : req.url
};
}));
await factory.startMockApp();
});

test('Express middleware for get txt Buffer', async function () {
const response = await nativeAxios.post(`${mockAppUrl}/format/Buffer`);
const body = response.data;

assert.isString(body);
assert.equal(body, SAMPLE_FILE);

const context = { title: '/format/Buffer', group: 'Format' };

const action = factory.findAction(context);

assert.exists(action);
const actionBody = action.resBody;

assert.ok(Buffer.isBuffer(actionBody), actionBody);
assert.equal(actionBody.toString(), 'BINARY DATA');
});

test('Positive: capture Buffer from supertest', async function () {
const context = { title: 'supertest buf', group: 'BUFF' };

await request
.with(context)
.post('/format/:format')
.params({ format: 'Buffer' })
.expect(200)
.parse(binaryParser)
.expect((res) => {
assert.ok(Buffer.isBuffer(res.body));
assert.equal(
res.body.toString(),
SAMPLE_FILE
);
});

const action = factory.findAction(context);

assert.exists(action);
const actionBody = action.resBody;

assert.ok(Buffer.isBuffer(actionBody));
assert.equal(actionBody.toString(), 'BINARY DATA');
});

test('Positive: save Buffer in api-blueprint', async function () {
const seed = factory.findAction({
'group' : 'Features',
'title' : 'Buffer'
});
const action = seed.data;

const groups = { [action.context.group]: { [action.context.title]: [ action.id ] } };
const Reporter = reporters['api-blueprint'];

const reporter = new Reporter();
const map = new Map([ [ action.id, action ] ]);

await reporter._init();
assert.match(reporter._generate(groups, map), /\+ Body\s*<Buffer 42 49 4e 41 52 59 20 44 41 54 41>/);
});

test('Positive: save Buffer in swagger', async function () {
const seed = factory.findAction({
'group' : 'Features',
'title' : 'Buffer'
});
const action = seed.data;

const groups = { [action.context.group]: { [action.context.title]: [ action.id ] } };
const Reporter = reporters.swagger;

const reporter = new Reporter();
const map = new Map([ [ action.id, action ] ]);

await reporter._init();
const report = reporter._generate(groups, map);

const body = JSON.parse(report).paths.Features.buffer.responses['200'];

assert.deepEqual(
body.content,
{ 'application/json': { 'schema': { 'type': 'string', 'format': 'binary', 'example': '<Buffer 42 49 4e 41 52 59 20 44 41 54 41>' } } },
JSON.stringify(body)
);
});
after(async function () {
await factory.cleanup();
});
1 change: 0 additions & 1 deletion tests/features/query.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ test('Positive: save query in api-blueprint', async function () {
const map = new Map([ [ action.id, action ] ]);

await reporter._init();
console.log(reporter._generate(groups, map));
assert.match(reporter._generate(groups, map), /\+ Request\s*\+ Parameters\s*status: ACTIVE/);
});

Expand Down
16 changes: 0 additions & 16 deletions tests/requests/express.client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,22 +44,6 @@ test('Express middleware for get json array', async function () {
});
});

test('Express middleware for get txt Buffer', async function () {
const response = await axios.post(`${mockAppUrl}/format/Buffer`);
const body = response.data;

assert.isString(body);
assert.equal(body, 'example of text file\nnew line');

const context = { title: '/format/Buffer', group: 'Format' };

factory.ensureAction(context, {
method : 'POST',
path : '/format/Buffer',
body
});
});

after(async function () {
await factory.cleanup();
});

0 comments on commit 6483141

Please sign in to comment.