diff --git a/jest.config.js b/jest.config.js index 5358d3250711..496a9fddf929 100644 --- a/jest.config.js +++ b/jest.config.js @@ -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'] -}; \ No newline at end of file + verbose: true, // display individual test results with the test suite hierarchy + collectCoverage: true, // collect test coverage information\ + collectCoverageFrom: ['scripts/**/*.js'] +}; diff --git a/scripts/adopters/index.js b/scripts/adopters/index.js index 0f5eeb427cf5..6a11697ad68f 100644 --- a/scripts/adopters/index.js +++ b/scripts/adopters/index.js @@ -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')); }; diff --git a/scripts/finance/index.js b/scripts/finance/index.js index b0954a8e582d..043125d9bc23 100644 --- a/scripts/finance/index.js +++ b/scripts/finance/index.js @@ -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 { @@ -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); } -}; \ No newline at end of file +}; diff --git a/scripts/utils.js b/scripts/utils.js index 397bdfe62427..c740ae91eaef 100644 --- a/scripts/utils.js +++ b/scripts/utils.js @@ -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}`); } } } diff --git a/scripts/utils/readAndWriteJson.js b/scripts/utils/readAndWriteJson.js new file mode 100644 index 000000000000..3c7f05d2308b --- /dev/null +++ b/scripts/utils/readAndWriteJson.js @@ -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}`); + } +}; \ No newline at end of file diff --git a/tests/adopters/index.test.js b/tests/adopters/index.test.js new file mode 100644 index 000000000000..8218a7f398f4 --- /dev/null +++ b/tests/adopters/index.test.js @@ -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); + }); + +}); diff --git a/tests/fixtures/utilsData.js b/tests/fixtures/utilsData.js new file mode 100644 index 000000000000..f852d21e3a2c --- /dev/null +++ b/tests/fixtures/utilsData.js @@ -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' + }; + \ No newline at end of file diff --git a/tests/readAndWriteJson.test.js b/tests/readAndWriteJson.test.js new file mode 100644 index 000000000000..f201f7e9a280 --- /dev/null +++ b/tests/readAndWriteJson.test.js @@ -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)); + }); + +}); diff --git a/tests/utils.test.js b/tests/utils.test.js new file mode 100644 index 000000000000..baedda3da6e0 --- /dev/null +++ b/tests/utils.test.js @@ -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(); + } + }); +});