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

add unit tests #56

Merged
merged 2 commits into from
Aug 28, 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
6 changes: 5 additions & 1 deletion library/src/containers/AsyncApi/AsyncApi.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import {
} from '../../types';
import { ThemeInterface, defaultTheme } from '../../theme';
import { ConfigInterface, defaultConfig } from '../../config';
import { parser, beautifier } from '../../helpers';
import { beautifier } from '../../helpers';
import Parser from '../../helpers/parser';
import { parse, parseFromUrl } from 'asyncapi-parser';

import { InfoComponent } from '../Info/Info';
import { SecurityComponent } from '../Security/Security';
Expand All @@ -24,6 +26,8 @@ import { Channels } from '../Channels/Channels';

import { AsyncApiWrapper } from './styled';

const parser = new Parser(parse, parseFromUrl);

interface AsyncAPIState {
validatedSchema: NullableAsyncApi;
error?: ParserError;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { formatErrors } from './Error';
import { formatErrors } from '../Error';
import { ErrorObject } from 'ajv';

// first argument, expected result
Expand Down
37 changes: 37 additions & 0 deletions library/src/helpers/__tests__/async.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"info": {
"version": "1.0.0",
"title": "Not example"
},
"channels": {
"test": {
"publish": {
"message": {
"$ref": "#/components/messages/testMessages"
}
}
}
},
"asyncapi": "2.0.0-rc2",
"components": {
"messages": {
"testMessages": {
"payload": {
"$ref": "#/components/schemas/testSchema"
}
}
},
"schemas": {
"testSchema": {
"type": "object",
"properties": {
"key": {
"not": {
"type": "integer"
}
}
}
}
}
}
}
97 changes: 97 additions & 0 deletions library/src/helpers/__tests__/helpers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import Parser from '../parser';
import validDoc from './async.json';
import {
ParserErrorUnsupportedVersion,
ParserErrorNoJS,
} from 'asyncapi-parser';
import { AsyncAPI, ParserOptions } from '../../types';

const mockParse = (d: AsyncAPI) =>
jest.fn(async (c: string | any, opts?: ParserOptions) => d);

const mockParseErr = <T extends Error>(err: T) =>
jest.fn(async (c: string | any, opts?: ParserOptions) => {
throw err;
});

const mockParseURL = (d: AsyncAPI) =>
jest.fn(async (a: string, b?: RequestInit, c?: ParserOptions) => d);

const mockParseURLErr = <T extends Error>(err: T) =>
jest.fn(async (a: string, b?: RequestInit, c?: ParserOptions) => {
throw err;
});

describe('Parser', () => {
describe('parse', () => {
const parseURL = mockParseURLErr(new Error('not implemented'));
test.each`
error | desc
${new ParserErrorUnsupportedVersion('err')} | ${'ParserErrorUnsupportedVersion is thrown'}
${new ParserErrorNoJS('test error')} | ${'ParserErrorNoJS is thrown'}
${new Error('other error')} | ${'other error'}
${{
message: 'version',
parsedJSON: {
asyncapi: '1',
},
}} | ${'invalid version is returned'}
`(
'should return error when $desc',
async <R extends Error, T extends { error: R; desc: string }>(err: T) => {
const parse = mockParseErr(err.error);
const parser = new Parser(parse, parseURL);
await parser.parse('mocked').then(result => {
expect(result.error).toBeTruthy();
expect(result.data).toBeFalsy();
});
},
);

test('should return no errors and data when doc is valid', async () => {
const doc: AsyncAPI = (validDoc as any) as AsyncAPI;
const parse = mockParse(doc);
const parser = new Parser(parse, parseURL);
await parser.parse('mocked').then(result => {
expect(result.error).toBeFalsy();
expect(result.data).toBeTruthy();
});
});
});

describe('parseURL', () => {
const parse = mockParseErr(new Error('not implemented'));
test.each`
error | desc
${new ParserErrorUnsupportedVersion('err')} | ${'ParserErrorUnsupportedVersion is thrown'}
${new ParserErrorNoJS('test error')} | ${'ParserErrorNoJS is thrown'}
${new Error('other error')} | ${'other error'}
${{
message: 'version',
parsedJSON: {
asyncapi: '1',
},
}} | ${'invalid version is returned'}
`(
'should return error when $desc',
async <R extends Error, T extends { error: R; desc: string }>(err: T) => {
const parseURL = mockParseURLErr(err.error);
const parser = new Parser(parse, parseURL);
await parser.parseFromUrl({ url: 'mocked' }).then(result => {
expect(result.error).toBeTruthy();
expect(result.data).toBeFalsy();
});
},
);

test('should return no errors and data when doc is valid', async () => {
const doc: AsyncAPI = (validDoc as any) as AsyncAPI;
const parseURL = mockParseURL(doc);
const parser = new Parser(parse, parseURL);
await parser.parseFromUrl({ url: 'mocked' }).then(result => {
expect(result.error).toBeFalsy();
expect(result.data).toBeTruthy();
});
});
});
});
1 change: 0 additions & 1 deletion library/src/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
export * from './parser';
export * from './beautifier';
14 changes: 0 additions & 14 deletions library/src/helpers/parser.test.ts

This file was deleted.

56 changes: 25 additions & 31 deletions library/src/helpers/parser.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import {
parse as AsyncAPIParse,
parseFromUrl as AsyncAPIParseFromUrl,
ParserErrorUnsupportedVersion,
ParserErrorNoJS,
} from 'asyncapi-parser';
Expand All @@ -12,25 +10,37 @@ import {
AsyncApiProps,
} from '../types';

import { UNSUPPORTED_SCHEMA_VERSION } from '../constants';

type ParserOptions = AsyncApiProps['parserOptions'];

import { UNSUPPORTED_SCHEMA_VERSION } from '../constants';
type ParseDocument = (
Copy link
Member

Choose a reason for hiding this comment

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

ParseSchema and ParseSchemaFromURL

content: string | any,
parserOptions?: ParserOptions,
) => Promise<AsyncAPI>;

type ParseDocumentFromURL = (
url: string,
requestOptions?: RequestInit,
parserOptions?: ParserOptions,
) => Promise<AsyncAPI>;

export default class Parser {
private parseSchema: ParseDocument;
private parseSchemaFromURL: ParseDocumentFromURL;

constructor(parse: ParseDocument, parseURL: ParseDocumentFromURL) {
this.parseSchema = parse;
this.parseSchemaFromURL = parseURL;
}

class Parser {
async parse(
content: string | any,
parserOptions?: ParserOptions,
): Promise<ParserReturn> {
try {
const { _json }: { _json: AsyncAPI } = await AsyncAPIParse(
content,
parserOptions,
);

if (!this.isCorrectSchemaVersion(_json.asyncapi)) {
return { data: null, error: { message: UNSUPPORTED_SCHEMA_VERSION } };
}
return { data: _json as AsyncAPI };
const data: AsyncAPI = await this.parseSchema(content, parserOptions);
return { data };
} catch (err) {
return this.handleError(err);
}
Expand All @@ -41,19 +51,11 @@ class Parser {
parserOptions?: ParserOptions,
): Promise<ParserReturn> {
try {
const data: AsyncAPI = await AsyncAPIParseFromUrl(
const data: AsyncAPI = await this.parseSchemaFromURL(
arg.url,
arg.requestOptions,
parserOptions,
);

if (!this.isCorrectSchemaVersion(data.asyncapi)) {
return {
data: null,
error: { message: UNSUPPORTED_SCHEMA_VERSION },
};
}

return { data };
} catch (err) {
return this.handleError(err);
Expand All @@ -68,10 +70,7 @@ class Parser {
return { data: null, error: { message: err.message } };
}

if (
err.parsedJSON &&
!this.isCorrectSchemaVersion(err.parsedJSON.asyncapi)
) {
if (err.parsedJSON && err.parsedJSON.asyncapi.startsWith('1')) {
Copy link
Member

Choose a reason for hiding this comment

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

Please revert this to isCorrectSchemaVersion function.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

  • isCorrectSchemaVersion only checks the first character e.g. -1.2.3 is not a correct schema version but the function would return true
  • it is oneliner used just in this place

return {
data: null,
error: { message: UNSUPPORTED_SCHEMA_VERSION },
Expand All @@ -83,9 +82,4 @@ class Parser {
error: { message: err.message, validationError: err.errors },
};
};

isCorrectSchemaVersion = (version: string): boolean =>
!version.startsWith('1');
}

export const parser = new Parser();
1 change: 1 addition & 0 deletions library/src/react-app-env.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
declare module 'asyncapi-parser';
declare module 'asyncapi-parser/lib/parser';
declare module 'merge';
declare module 'openapi-sampler';
Loading