Skip to content

Commit

Permalink
feat: write tests and refactor scripts (#3012)
Browse files Browse the repository at this point in the history
Co-authored-by: akshatnema <[email protected]>%0ACo-authored-by: Ansh Goyal <[email protected]>
  • Loading branch information
vishvamsinh28 and anshgoyalevil authored Jul 1, 2024
1 parent 57d7207 commit 09d1652
Show file tree
Hide file tree
Showing 9 changed files with 172 additions and 36 deletions.
8 changes: 4 additions & 4 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module.exports = {
verbose: true, // display individual test results with the test suite hierarchy
collectCoverage: true, // collect test coverage information\
collectCoverageFrom: ['scripts/**/*.js']
};
verbose: true, // display individual test results with the test suite hierarchy
collectCoverage: true, // collect test coverage information\
collectCoverageFrom: ['scripts/**/*.js']
};
16 changes: 2 additions & 14 deletions scripts/adopters/index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,6 @@
const { promises: { readFile, writeFile } } = require('fs');
const { convertToJson } = require('../utils');
const { resolve } = require('path');
const writeJSON = require('../utils/readAndWriteJson.js')

module.exports = async function buildAdoptersList() {
try {
const AdoptersContent = await readFile('config/adopters.yml', 'utf-8');
const jsonContent = convertToJson(AdoptersContent);

await writeFile(
resolve(__dirname, '../../config', 'adopters.json'),
JSON.stringify(jsonContent)
);
} catch (err) {
console.error(err);
throw err;
}
writeJSON('config/adopters.yml',resolve(__dirname, '../../config', 'adopters.json'));
};
23 changes: 8 additions & 15 deletions scripts/finance/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { promises: { readFile, writeFile, mkdir } } = require('fs');
const { convertToJson } = require('../utils');
const { resolve, dirname } = require('path');
const { promises: { mkdir } } = require('fs');
const { resolve } = require('path');
const writeJSON = require('../utils/readAndWriteJson.js')

module.exports = async function buildFinanceInfoList() {
try {
Expand All @@ -9,25 +9,18 @@ module.exports = async function buildFinanceInfoList() {
const expensesPath = resolve(currentDir, 'config', 'finance', '2024', 'Expenses.yml');
const expensesLinkPath = resolve(currentDir, 'config', 'finance', '2024', 'ExpensesLink.yml');

const ExpensesContent = await readFile(expensesPath, 'utf-8');
const ExpensesLinkContent = await readFile(expensesLinkPath, 'utf-8');

const Expenses = convertToJson(ExpensesContent);
const ExpensesLink = convertToJson(ExpensesLinkContent);

// Ensure the directory exists before writing the files
const jsonDirectory = resolve(currentDir, 'config', 'finance', 'json-data', '2024');
await mkdir(jsonDirectory, { recursive: true });

// Write Expenses to a JSON files
// Write Expenses and ExpensesLink to JSON files
const expensesJsonPath = resolve(jsonDirectory, 'Expenses.json');
await writeFile(expensesJsonPath, JSON.stringify(Expenses, null, 2));
await writeJSON(expensesPath, expensesJsonPath);

const expensesLinkJsonPath = resolve(jsonDirectory, 'ExpensesLink.json');
await writeFile(expensesLinkJsonPath, JSON.stringify(ExpensesLink, null, 2));
await writeJSON(expensesLinkPath, expensesLinkJsonPath);

} catch (err) {
console.error(err);
throw err;
throw new Error(err);
}
};
};
5 changes: 2 additions & 3 deletions scripts/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@ function convertToJson(contentYAMLorJSON) {
const yamlContent = yaml.parse(contentYAMLorJSON);
return yamlContent;
} catch (yamlError) {
// If parsing as YAML also fails, return null or handle the error as needed
console.error('Error parsing content as JSON or YAML:', jsonError.message, yamlError.message);
return null;
// If parsing as YAML also fails, throw an error
throw new Error(`Invalid content format:\nJSON Parse Error: ${jsonError}\nYAML Parse Error: ${yamlError}`);
}
}
}
Expand Down
28 changes: 28 additions & 0 deletions scripts/utils/readAndWriteJson.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const { promises: { readFile, writeFile } } = require('fs');
const { convertToJson } = require("../utils");

module.exports = async function writeJSON(readPath, writePath) {
let readContent;
let jsonContent;

// Attempt to read the file
try {
readContent = await readFile(readPath, 'utf-8');
} catch (err) {
throw new Error(`Error while reading file\nError: ${err}`);
}

// Attempt to convert content to JSON
try {
jsonContent = convertToJson(readContent);
} catch (err) {
throw new Error(`Error while conversion\nError: ${err}`);
}

// Attempt to write the JSON content to file
try {
await writeFile(writePath, JSON.stringify(jsonContent));
} catch (err) {
throw new Error(`Error while writing file\nError: ${err}`);
}
};
18 changes: 18 additions & 0 deletions tests/adopters/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { resolve } = require('path');
const writeJSON = require('../../scripts/utils/readAndWriteJson.js');
const buildAdoptersList = require('../../scripts/adopters/index');

jest.mock('../../scripts/utils/readAndWriteJson.js');

describe('buildAdoptersList', () => {

test('should call writeJSON with correct arguments', async () => {
const expectedReadPath = 'config/adopters.yml';
const expectedWritePath = resolve(__dirname, '../../config', 'adopters.json');

await buildAdoptersList();

expect(writeJSON).toHaveBeenCalledWith(expectedReadPath, expectedWritePath);
});

});
7 changes: 7 additions & 0 deletions tests/fixtures/utilsData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
jsonString: '{"name": "AsyncAPI", "age": 5}',
yamlString: 'name: AsyncAPI\nage: 5',
jsonObject: { name: "AsyncAPI", age: 5 },
invalidString: 'name: AsyncAPI, age: five'
};

78 changes: 78 additions & 0 deletions tests/readAndWriteJson.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
const { promises: fs } = require('fs');
const { convertToJson } = require('../scripts/utils');
const writeJSON = require("../scripts/utils/readAndWriteJson");
const { yamlString, jsonObject } = require("./fixtures/utilsData");

jest.mock('fs', () => ({
promises: {
readFile: jest.fn(),
writeFile: jest.fn(),
},
}));

jest.mock('../scripts/utils', () => ({
convertToJson: jest.fn(),
}));

describe('writeJSON', () => {
const readPath = 'config/testInput.yaml';
const writePath = 'config/testOutput.json';
const error = new Error('Test error');

beforeEach(() => {
jest.clearAllMocks();
});

test('should read a file, convert it to JSON, and write the JSON to another file', async () => {
fs.readFile.mockResolvedValue(yamlString);
convertToJson.mockReturnValue(jsonObject);

await writeJSON(readPath, writePath);

expect(fs.readFile).toHaveBeenCalledWith(readPath, 'utf-8');
expect(convertToJson).toHaveBeenCalledWith(yamlString);
expect(fs.writeFile).toHaveBeenCalledWith(writePath, JSON.stringify(jsonObject));
});

test('should throw an error if reading the file fails', async () => {
fs.readFile.mockRejectedValue(error);

try {
await writeJSON(readPath, writePath);
} catch (err) {
expect(err.message).toBe(`Error while reading file\nError: ${error}`);
}

expect(fs.readFile).toHaveBeenCalledWith(readPath, 'utf-8');
});

test('should throw an error if converting the file content to JSON fails', async () => {
fs.readFile.mockResolvedValue(yamlString);
convertToJson.mockImplementation(() => {
throw error;
});

try {
await writeJSON(readPath, writePath);
} catch (err) {
expect(err.message).toBe(`Error while conversion\nError: ${error}`);
}

expect(convertToJson).toHaveBeenCalledWith(yamlString);
});

test('should throw an error if writing the file fails', async () => {
fs.readFile.mockResolvedValue(yamlString);
convertToJson.mockReturnValue(jsonObject);
fs.writeFile.mockRejectedValue(error);

try {
await writeJSON(readPath, writePath);
} catch (err) {
expect(err.message).toBe(`Error while writing file\nError: ${error}`);
}

expect(fs.writeFile).toHaveBeenCalledWith(writePath, JSON.stringify(jsonObject));
});

});
25 changes: 25 additions & 0 deletions tests/utils.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const { convertToJson } = require("../scripts/utils");
const { jsonString, yamlString, jsonObject, invalidString } = require("./fixtures/utilsData")

describe('convertToJson', () => {
test('should return JSON object if input is valid JSON string', () => {
expect(convertToJson(jsonString)).toEqual(jsonObject);
});

test('should return JavaScript object if input is valid YAML string', () => {
expect(convertToJson(yamlString)).toEqual(jsonObject);
});

test('should return input if input is already an object', () => {
expect(convertToJson(jsonObject)).toBe(jsonObject);
});

test('should throw an error if input is invalid JSON and invalid YAML', () => {
try {
convertToJson(invalidString);
expect(convertToJson(invalidString)).toBeUndefined();
} catch (error) {
expect(error.message.includes("Invalid content format")).toBeTruthy();
}
});
});

0 comments on commit 09d1652

Please sign in to comment.