Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: handle allowedParams #828

Merged
merged 3 commits into from
Nov 19, 2019
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
- Prism has values for path/query params bolded and in color [#743](https://github.com/stoplightio/prism/pull/743)
- The CLI now displays a timestamp for all the logged operations [#779](https://github.com/stoplightio/prism/pull/779)
- Prism has now support for OpenAPI 3.0 callbacks [#716](https://github.com/stoplightio/prism/pull/716)
- Prism body validator will now show allowed enum parameters in error messages [#828](https://github.com/stoplightio/prism/pull/828)

## Fixed

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ describe('body params validation', () => {
{
code: 'enum',
location: ['body', 'status'],
message: 'should be equal to one of the allowed values',
message: 'should be equal to one of the allowed values: placed, approved, delivered',
severity: 'Error',
},
],
Expand Down Expand Up @@ -495,7 +495,7 @@ describe('body params validation', () => {
location: ['body', 'status'],
severity: 'Error',
code: 'enum',
message: 'should be equal to one of the allowed values',
message: 'should be equal to one of the allowed values: open, close',
},
],
});
Expand Down
100 changes: 68 additions & 32 deletions packages/http/src/mocker/callback/__tests__/callbacks.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ describe('runCallback()', () => {
info: jest.fn(),
};


beforeEach(() => {
jest.clearAllMocks();
});
Expand All @@ -32,15 +31,17 @@ describe('runCallback()', () => {
method: 'get',
path: 'http://example.com/{$method}/{$statusCode}/{$response.body#/id}/{$request.header.content-type}',
id: '1',
responses: [{ code: '200', contents: [ { mediaType: 'application/json' } ] }],
responses: [{ code: '200', contents: [{ mediaType: 'application/json' }] }],
request: {
body: {
contents: [{
mediaType: 'application/json',
examples: [{ key: 'e1', value: { about: 'something' }}]
}],
contents: [
{
mediaType: 'application/json',
examples: [{ key: 'e1', value: { about: 'something' } }],
},
],
},
}
},
},
request: {
body: '',
Expand All @@ -52,12 +53,20 @@ describe('runCallback()', () => {
},
response: {
statusCode: 200,
body: { id: 5 }
body: { id: 5 },
},
})(logger)();

expect(fetch).toHaveBeenCalledWith('http://example.com/get/200/5/weird/content', { method: 'get', body: '{"about":"something"}', headers: { 'content-type': 'application/json' } });
expect(logger.info).toHaveBeenNthCalledWith(1, { name: 'CALLBACK' }, 'test callback: Making request to http://example.com/get/200/5/weird/content...');
expect(fetch).toHaveBeenCalledWith('http://example.com/get/200/5/weird/content', {
method: 'get',
body: '{"about":"something"}',
headers: { 'content-type': 'application/json' },
});
expect(logger.info).toHaveBeenNthCalledWith(
1,
{ name: 'CALLBACK' },
'test callback: Making request to http://example.com/get/200/5/weird/content...'
);
expect(logger.info).toHaveBeenNthCalledWith(2, { name: 'CALLBACK' }, 'test callback: Request finished');
expect(logger.error).not.toHaveBeenCalled();
expect(logger.warn).not.toHaveBeenCalled();
Expand All @@ -66,7 +75,7 @@ describe('runCallback()', () => {

describe('callback response is incorrect', () => {
it('logs violations', async () => {
const headers = { 'content-type': 'application/json', 'test': 'test' };
const headers = { 'content-type': 'application/json', test: 'test' };
((fetch as unknown) as jest.Mock).mockResolvedValue({
status: 200,
headers: { get: (n: string) => headers[n], raw: () => mapValues(headers, (h: string) => h.split(' ')) },
Expand All @@ -79,24 +88,35 @@ describe('runCallback()', () => {
method: 'get',
path: 'http://example.com/{$method}/{$statusCode}/{$response.body#/id}/{$request.header.content-type}',
id: '1',
responses: [{
code: '200',
headers: [
{ name: 'test', style: HttpParamStyles.Simple, deprecated: true, schema: { type: 'string', enum: ['a'] } },
],
contents: [{
mediaType: 'application/json',
schema: { type: 'object', properties: { test: { type: 'string', maxLength: 3, } } },
}],
}],
responses: [
{
code: '200',
headers: [
{
name: 'test',
style: HttpParamStyles.Simple,
deprecated: true,
schema: { type: 'string', enum: ['a'] },
},
],
contents: [
{
mediaType: 'application/json',
schema: { type: 'object', properties: { test: { type: 'string', maxLength: 3 } } },
},
],
},
],
request: {
body: {
contents: [{
mediaType: 'application/json',
examples: [{ key: 'e1', value: { about: 'something' }}],
}],
contents: [
{
mediaType: 'application/json',
examples: [{ key: 'e1', value: { about: 'something' } }],
},
],
},
}
},
},
request: {
body: '',
Expand All @@ -108,14 +128,30 @@ describe('runCallback()', () => {
},
response: {
statusCode: 200,
body: { id: 5 }
body: { id: 5 },
},
})(logger)();

expect(fetch).toHaveBeenCalledWith('http://example.com/get/200/5/weird/content', { method: 'get', body: '{"about":"something"}', headers: { 'content-type': 'application/json' } });
expect(logger.warn).toHaveBeenNthCalledWith(1, { name: 'VALIDATOR' }, 'Violation: header.test Header param test is deprecated');
expect(logger.error).toHaveBeenNthCalledWith(1, { name: 'VALIDATOR' }, 'Violation: body.test should NOT be longer than 3 characters');
expect(logger.error).toHaveBeenNthCalledWith(2, { name: 'VALIDATOR' }, 'Violation: header.test should be equal to one of the allowed values');
expect(fetch).toHaveBeenCalledWith('http://example.com/get/200/5/weird/content', {
method: 'get',
body: '{"about":"something"}',
headers: { 'content-type': 'application/json' },
});
expect(logger.warn).toHaveBeenNthCalledWith(
1,
{ name: 'VALIDATOR' },
'Violation: header.test Header param test is deprecated'
);
expect(logger.error).toHaveBeenNthCalledWith(
1,
{ name: 'VALIDATOR' },
'Violation: body.test should NOT be longer than 3 characters'
);
expect(logger.error).toHaveBeenNthCalledWith(
2,
{ name: 'VALIDATOR' },
'Violation: header.test should be equal to one of the allowed values: a'
);
});
});

Expand Down Expand Up @@ -146,7 +182,7 @@ describe('runCallback()', () => {
},
response: {
statusCode: 200,
body: { id: 5 }
body: { id: 5 },
},
})(logger)();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,6 @@ Array [
]
`;

exports[`convertAjvErrors() message field is missing converts properly 1`] = `
Array [
Object {
"code": "required",
"message": "",
"path": Array [
"b",
],
"severity": 0,
},
]
`;

exports[`validateAgainstSchema() has validation errors returns validation errors 1`] = `
Array [
Object {
Expand Down
13 changes: 7 additions & 6 deletions packages/http/src/validator/validators/__tests__/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { DiagnosticSeverity } from '@stoplight/types';
import * as convertAjvErrorsModule from '../utils';
import { convertAjvErrors, validateAgainstSchema } from '../utils';
import { ErrorObject } from 'ajv';

describe('convertAjvErrors()', () => {
const errorObjectFixture = {
const errorObjectFixture: ErrorObject = {
dataPath: 'a.b',
keyword: 'required',
message: 'c is required',
schemaPath: '..',
params: '',
params: {},
};

describe('all fields defined', () => {
Expand All @@ -20,16 +21,16 @@ describe('convertAjvErrors()', () => {
describe('keyword field is missing', () => {
it('converts properly', () => {
expect(
convertAjvErrors([Object.assign({}, errorObjectFixture, { keyword: undefined })], DiagnosticSeverity.Error),
convertAjvErrors([Object.assign({}, errorObjectFixture, { keyword: undefined })], DiagnosticSeverity.Error)
).toMatchSnapshot();
});
});

describe('message field is missing', () => {
it('converts properly', () => {
expect(
convertAjvErrors([Object.assign({}, errorObjectFixture, { message: undefined })], DiagnosticSeverity.Error),
).toMatchSnapshot();
convertAjvErrors([Object.assign({}, errorObjectFixture, { message: undefined })], DiagnosticSeverity.Error)[0]
).toHaveProperty('message', '');
});
});

Expand Down Expand Up @@ -75,7 +76,7 @@ describe('validateAgainstSchema()', () => {
schemaPath: '#/type',
},
],
DiagnosticSeverity.Error,
DiagnosticSeverity.Error
);
});
});
Expand Down
19 changes: 11 additions & 8 deletions packages/http/src/validator/validators/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,25 @@ import { option } from 'fp-ts/lib/Option';
import { sequenceT } from 'fp-ts/lib/Apply';
import * as Ajv from 'ajv';
import { JSONSchema } from '../../';
// @ts-ignore
import * as AjvOAI from 'ajv-oai';

const ajv = new AjvOAI({ allErrors: true, messages: true, schemaId: 'auto' }) as Ajv.Ajv;
const ajv = new AjvOAI({ allErrors: true, messages: true, schemaId: 'auto' });

export const convertAjvErrors = (errors: Ajv.ErrorObject[] | undefined | null, severity: DiagnosticSeverity) => {
if (!errors) {
return [];
}

return errors.map<IPrismDiagnostic & { path: Segment[] }>(error => ({
path: error.dataPath.split('.').slice(1),
code: error.keyword || '',
message: error.message || '',
severity,
}));
return errors.map<IPrismDiagnostic & { path: Segment[] }>(error => {
const allowedParameters = 'allowedValues' in error.params ? `: ${error.params.allowedValues.join(', ')}` : '';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


return {
path: error.dataPath.split('.').slice(1),
code: error.keyword || '',
message: `${error.message || ''}${allowedParameters}`,
severity,
};
});
};

export const validateAgainstSchema = (value: any, schema: JSONSchema, prefix?: string): IPrismDiagnostic[] => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@ HTTP/1.1 422 Unprocessable Entity
content-type: application/problem+json
Connection: keep-alive

{"type":"https://stoplight.io/prism/errors#UNPROCESSABLE_ENTITY","title":"Invalid request body payload","status":422,"detail":"Your request is not valid and no HTTP validation response was found in the spec, so Prism is generating this error for you.","validation":[{"location":["body"],"severity":"Error","code":"required","message":"should have required property 'id'"},{"location":["body","status"],"severity":"Error","code":"enum","message":"should be equal to one of the allowed values"}]}
{"type":"https://stoplight.io/prism/errors#UNPROCESSABLE_ENTITY","title":"Invalid request body payload","status":422,"detail":"Your request is not valid and no HTTP validation response was found in the spec, so Prism is generating this error for you.","validation":[{"location":["body"],"severity":"Error","code":"required","message":"should have required property 'id'"},{"location":["body","status"],"severity":"Error","code":"enum","message":"should be equal to one of the allowed values: open, close"}]}
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ HTTP/1.1 422 Unprocessable Entity
content-type: application/problem+json
Connection: keep-alive

{"type":"https://stoplight.io/prism/errors#UNPROCESSABLE_ENTITY","title":"Invalid request body payload","status":422,"detail":"Your request is not valid and no HTTP validation response was found in the spec, so Prism is generating this error for you.","validation":[{"location":["body"],"severity":"Error","code":"required","message":"should have required property 'id'"},{"location":["body","status"],"severity":"Error","code":"enum","message":"should be equal to one of the allowed values"}]}
{"type":"https://stoplight.io/prism/errors#UNPROCESSABLE_ENTITY","title":"Invalid request body payload","status":422,"detail":"Your request is not valid and no HTTP validation response was found in the spec, so Prism is generating this error for you.","validation":[{"location":["body"],"severity":"Error","code":"required","message":"should have required property 'id'"},{"location":["body","status"],"severity":"Error","code":"enum","message":"should be equal to one of the allowed values: open, close"}]}
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ HTTP/1.1 422 Unprocessable Entity
content-type: application/problem+json
Connection: keep-alive

{"type":"https://stoplight.io/prism/errors#UNPROCESSABLE_ENTITY","title":"Invalid request body payload","status":422,"detail":"Your request is not valid and no HTTP validation response was found in the spec, so Prism is generating this error for you.","validation":[{"location":["body"],"severity":"Error","code":"required","message":"should have required property 'id'"},{"location":["body","status"],"severity":"Error","code":"enum","message":"should be equal to one of the allowed values"}]}
{"type":"https://stoplight.io/prism/errors#UNPROCESSABLE_ENTITY","title":"Invalid request body payload","status":422,"detail":"Your request is not valid and no HTTP validation response was found in the spec, so Prism is generating this error for you.","validation":[{"location":["body"],"severity":"Error","code":"required","message":"should have required property 'id'"},{"location":["body","status"],"severity":"Error","code":"enum","message":"should be equal to one of the allowed values: open, close"}]}
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@ HTTP/1.1 422 Unprocessable Entity
content-type: application/problem+json
Connection: keep-alive

{"type":"https://stoplight.io/prism/errors#UNPROCESSABLE_ENTITY","title":"Invalid request body payload","status":422,"detail":"Your request is not valid and no HTTP validation response was found in the spec, so Prism is generating this error for you.","validation":[{"location":["body"],"severity":"Error","code":"required","message":"should have required property 'id'"},{"location":["body","status"],"severity":"Error","code":"enum","message":"should be equal to one of the allowed values"}]}
{"type":"https://stoplight.io/prism/errors#UNPROCESSABLE_ENTITY","title":"Invalid request body payload","status":422,"detail":"Your request is not valid and no HTTP validation response was found in the spec, so Prism is generating this error for you.","validation":[{"location":["body"],"severity":"Error","code":"required","message":"should have required property 'id'"},{"location":["body","status"],"severity":"Error","code":"enum","message":"should be equal to one of the allowed values: open, close"}]}
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ curl -i http://localhost:4010/path
====expect====
HTTP/1.1 500 Internal Server Error

{"type":"https://stoplight.io/prism/errors#VIOLATIONS","title":"Request/Response not valid","status":500,"detail":"Your request/response is not valid and the --errors flag is set, so Prism is generating this error for you.","validation":[{"location":["response","body"],"severity":"Error","code":"enum","message":"should be equal to one of the allowed values"}]}
{"type":"https://stoplight.io/prism/errors#VIOLATIONS","title":"Request/Response not valid","status":500,"detail":"Your request/response is not valid and the --errors flag is set, so Prism is generating this error for you.","validation":[{"location":["response","body"],"severity":"Error","code":"enum","message":"should be equal to one of the allowed values: placed, approved, delivered"}]}