Skip to content

Commit

Permalink
fix test and codesmells
Browse files Browse the repository at this point in the history
  • Loading branch information
jonaslagoni committed Sep 27, 2023
1 parent 936abfb commit 7e252c4
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 50 deletions.
6 changes: 3 additions & 3 deletions lib/generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ class Generator {
err.diagnostics = diagnostics;
throw err;
} else {
this.asyncapi = getProperApiDocument(document, this.templateConfig);
this.asyncapi = document;
}
}
}
Expand Down Expand Up @@ -311,7 +311,7 @@ class Generator {
*/
async generateFromURL(asyncapiURL) {
const doc = await fetchSpec(asyncapiURL);
return this.generateFromString(doc, { path: asyncapiURL });
return this.generate(doc, { path: asyncapiURL });
}

/**
Expand All @@ -338,7 +338,7 @@ class Generator {
*/
async generateFromFile(asyncapiFile) {
const doc = await readFile(asyncapiFile, { encoding: 'utf8' });
return this.generateFromString(doc, { path: asyncapiFile });
return this.generate(doc, { path: asyncapiFile });
}

/**
Expand Down
9 changes: 7 additions & 2 deletions lib/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,20 @@ parser.sanitizeTemplateApiVersion = (apiVersion) => {
return apiVersion;
};

parser.parse = (asyncapi, oldOptions, generator) => {
parser.parse = async (asyncapi, oldOptions, generator) => {
let apiVersion = this.sanitizeTemplateApiVersion(generator.templateConfig.apiVersion);
// Defaulting to apiVersion v1 to convert it to the Parser-API v1 afterwards.
if (!this.usesNewAPI(generator.templateConfig)) {
apiVersion = '1';
}
const options = convertOldOptionsToNew(oldOptions, generator);
const parser = NewParser(apiVersion, {parserOptions: options, includeSchemaParsers: true});
return parser.parse(asyncapi, options);
const { document, diagnostics } = await parser.parse(asyncapi, options);
if (!document) {
return {document, diagnostics};
}
const correctDocument = this.getProperApiDocument(document, this.templateConfig);
return {document: correctDocument, diagnostics};
};

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/templateConfigValidator.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ module.exports.validateTemplateConfig = (templateConfig, templateParams, asyncap
} else {
server = asyncapiDocument.servers()[templateParams.server];
}
isServerProvidedInDocument(server, templateParams.server);
isServerProtocolSupported(server, supportedProtocols, templateParams.server);
isServerProvidedInDocument(server, templateParams.server);
}

isProvidedParameterSupported(parameters, templateParams);
Expand All @@ -57,7 +57,7 @@ function isTemplateCompatible(generator, apiVersion) {
}

if (typeof apiVersion === 'string' && !supportedParserAPIMajorVersions.includes(apiVersion)) {
throw new Error(`The version specified in apiVersion is not supported by this Generator version. Supported versions are: ${supportedParserAPIMajorVersions.toString()}`);
throw new Error(`The version specified in apiVersion is not supported by this Generator version. Supported versions are: ${supportedParserAPIMajorVersions.join(', ')}`);
}
}

Expand Down
14 changes: 7 additions & 7 deletions test/generator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -297,15 +297,15 @@ describe('Generator', () => {
utils.__files = {
[filePath]: 'test content',
};
const generateFromStringMock = jest.fn().mockResolvedValue();
const generateMock = jest.fn().mockResolvedValue();
const gen = new Generator('testTemplate', __dirname);
gen.generateFromString = generateFromStringMock;
gen.generate = generateMock;
await gen.generateFromFile(filePath);
expect(utils.readFile).toHaveBeenCalled();
expect(utils.readFile.mock.calls[0][0]).toBe(filePath);
expect(utils.readFile.mock.calls[0][1]).toStrictEqual({ encoding: 'utf8' });
expect(generateFromStringMock.mock.calls[0][0]).toBe('test content');
expect(generateFromStringMock.mock.calls[0][1]).toStrictEqual({ path: filePath });
expect(generateMock.mock.calls[0][0]).toBe('test content');
expect(generateMock.mock.calls[0][1]).toStrictEqual({ path: filePath });
});
});

Expand All @@ -315,13 +315,13 @@ describe('Generator', () => {
const asyncapiURL = 'http://example.com/fake-asyncapi.yml';
utils.__contentOfFetchedFile = 'fake text';

const generateFromStringMock = jest.fn().mockResolvedValue();
const generateMock = jest.fn().mockResolvedValue();
const gen = new Generator('testTemplate', __dirname);
gen.generateFromString = generateFromStringMock;
gen.generate = generateMock;
await gen.generateFromURL(asyncapiURL);
expect(utils.fetchSpec).toHaveBeenCalled();
expect(utils.fetchSpec.mock.calls[0][0]).toBe(asyncapiURL);
expect(generateFromStringMock.mock.calls[0][0]).toBe('fake text');
expect(generateMock.mock.calls[0][0]).toBe('fake text');
});
});

Expand Down
109 changes: 73 additions & 36 deletions test/templateConfigValidator.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { validateTemplateConfig } = require('../lib/templateConfigValidator');
const fs = require('fs');
const path = require('path');
const { parse } = require('../lib/parser');
const dummyYAML = fs.readFileSync(path.resolve(__dirname, './docs/dummy.yml'), 'utf8');

jest.mock('../lib/utils');
Expand All @@ -9,9 +10,7 @@ describe('Template Configuration Validator', () => {
let asyncapiDocument;

beforeAll(async () => {
const { Parser } = jest.requireActual('@asyncapi/parser');
const parser = new Parser();
const { document } = await parser.parse(dummyYAML);
const { document } = await parse(dummyYAML, {}, {templateConfig: {apiVersion: 'v2'}});
asyncapiDocument = document;
});

Expand Down Expand Up @@ -69,7 +68,7 @@ describe('Template Configuration Validator', () => {
apiVersion: '999999'
};

expect(() => validateTemplateConfig(templateConfig, templateParams)).toThrow('The version specified in apiVersion is not supported by this Generator version. Supported versions are: v1');
expect(() => validateTemplateConfig(templateConfig, templateParams)).toThrow('The version specified in apiVersion is not supported by this Generator version. Supported versions are: v1, v2');
});

it('Validation throw error if required params not provided', () => {
Expand Down Expand Up @@ -112,38 +111,6 @@ describe('Template Configuration Validator', () => {

expect(() => validateTemplateConfig(templateConfig, templateParams, asyncapiDocument)).toThrow('This template doesn\'t have any params.');
});

it('Validation throw error if specified server is not in asyncapi document', () => {
const templateParams = {
server: 'myserver'
};
const templateConfig = {
parameters: {
server: {
description: ''
}
}
};

expect(() => validateTemplateConfig(templateConfig, templateParams, asyncapiDocument)).toThrow('Couldn\'t find server with name myserver.');
});

it('Validation throw error if given protocol is not supported by template', () => {
const templateParams = {
server: 'dummy-mqtt'
};
const templateConfig = {
supportedProtocols: ['myprotocol'],
parameters: {
server: {
description: ''
}
}
};

expect(() => validateTemplateConfig(templateConfig, templateParams, asyncapiDocument)).toThrow('Server \"dummy-mqtt\" uses the mqtt protocol but this template only supports the following ones: myprotocol.');
});

it('Validation throw error if subject in condition files is not string', () => {
const templateParams = {};
const templateConfig = {
Expand Down Expand Up @@ -190,4 +157,74 @@ describe('Template Configuration Validator', () => {

expect(templateConfig.conditionalFiles['my/path/to/file.js']).toBeDefined();
});

it('Validation throw error if specified server is not in asyncapi document', () => {
const templateParams = {
server: 'myserver'
};
const templateConfig = {
parameters: {
server: {
description: ''
}
}
};

expect(() => validateTemplateConfig(templateConfig, templateParams, asyncapiDocument)).toThrow('Couldn\'t find server with name myserver.');
});

it('Validation throw error if given protocol is not supported by template', () => {
const templateParams = {
server: 'dummy-mqtt'
};
const templateConfig = {
supportedProtocols: ['myprotocol'],
parameters: {
server: {
description: ''
}
}
};

expect(() => validateTemplateConfig(templateConfig, templateParams, asyncapiDocument)).toThrow('Server \"dummy-mqtt\" uses the mqtt protocol but this template only supports the following ones: myprotocol.');
});

describe('should work with v2 apiVersion', () => {
let asyncapiDocument;

beforeAll(async () => {
const { document } = await parse(dummyYAML, {}, {templateConfig: {apiVersion: 'v2'}});
asyncapiDocument = document;
});
it('Validation throw error if specified server is not in asyncapi document', () => {
const templateParams = {
server: 'myserver'
};
const templateConfig = {
parameters: {
server: {
description: ''
}
}
};

expect(() => validateTemplateConfig(templateConfig, templateParams, asyncapiDocument)).toThrow('Couldn\'t find server with name myserver.');
});

it('Validation throw error if given protocol is not supported by template', () => {
const templateParams = {
server: 'dummy-mqtt'
};
const templateConfig = {
supportedProtocols: ['myprotocol'],
parameters: {
server: {
description: ''
}
}
};

expect(() => validateTemplateConfig(templateConfig, templateParams, asyncapiDocument)).toThrow('Server \"dummy-mqtt\" uses the mqtt protocol but this template only supports the following ones: myprotocol.');
});
});
});

0 comments on commit 7e252c4

Please sign in to comment.