Skip to content

Commit

Permalink
feat: add tests for finace and case studies (#3037)
Browse files Browse the repository at this point in the history
Co-authored-by: Ansh Goyal <[email protected]>
  • Loading branch information
vishvamsinh28 and anshgoyalevil authored Jul 12, 2024
1 parent d74cbac commit 0a999d9
Show file tree
Hide file tree
Showing 7 changed files with 245 additions and 26 deletions.
22 changes: 8 additions & 14 deletions scripts/casestudies/index.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,19 @@
const { readdir, writeFile, readFile } = require('fs').promises;
const { convertToJson } = require('../utils');
const { resolve } = require('path');
const { convertToJson } = require('../../scripts/utils');

const dirWithCaseStudy = 'config/casestudies';
module.exports = async function buildCaseStudiesList() {
let files = await readdir(dirWithCaseStudy);
let caseStudiesList = [];
module.exports = async function buildCaseStudiesList(dirWithCaseStudy, writeFilePath) {
try {
let files = await readdir(dirWithCaseStudy);
let caseStudiesList = [];
for (let file of files) {
const caseStudyFileName = [dirWithCaseStudy, file].join('/');
const caseStudyContent = await readFile(caseStudyFileName, 'utf-8');
const jsonContent = convertToJson(caseStudyContent);

caseStudiesList.push(jsonContent);
await writeFile(
resolve(__dirname, '../../config', 'case-studies.json'),
JSON.stringify(caseStudiesList)
)
await writeFile(writeFilePath, JSON.stringify(caseStudiesList))
}
} catch (err) {
console.log(err);
throw err
throw new Error(err);
}
};
};
21 changes: 12 additions & 9 deletions scripts/finance/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
const { promises: { mkdir } } = require('fs');
const { resolve } = require('path');
const writeJSON = require('../utils/readAndWriteJson.js')
const writeJSON = require('../utils/readAndWriteJson.js');

module.exports = async function buildFinanceInfoList() {
module.exports = async function buildFinanceInfoList({
currentDir,
configDir,
financeDir,
year,
jsonDataDir
}) {
try {
const currentDir = resolve(__dirname, '../../');

const expensesPath = resolve(currentDir, 'config', 'finance', '2024', 'Expenses.yml');
const expensesLinkPath = resolve(currentDir, 'config', 'finance', '2024', 'ExpensesLink.yml');
const expensesPath = resolve(currentDir, configDir, financeDir, year, 'Expenses.yml');
const expensesLinkPath = resolve(currentDir, configDir, financeDir, year, 'ExpensesLink.yml');

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

// Write Expenses and ExpensesLink to JSON files
Expand All @@ -19,8 +23,7 @@ module.exports = async function buildFinanceInfoList() {

const expensesLinkJsonPath = resolve(jsonDirectory, 'ExpensesLink.json');
await writeJSON(expensesLinkPath, expensesLinkJsonPath);

} catch (err) {
throw new Error(err);
}
};
};
16 changes: 13 additions & 3 deletions scripts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ const rssFeed = require('./build-rss');
const buildPostList = require('./build-post-list');
const buildCaseStudiesList = require('./casestudies');
const buildAdoptersList = require('./adopters')
const buildFinanceInfoList = require('./finance')
const buildFinanceInfoList = require('./finance');
const { resolve } = require('path');

async function start() {
await buildPostList();
Expand All @@ -12,9 +13,18 @@ async function start() {
'AsyncAPI Initiative Blog',
'rss.xml'
);
await buildCaseStudiesList();
await buildCaseStudiesList(
'config/casestudies',
resolve(__dirname, '../config', 'case-studies.json')
);
await buildAdoptersList();
await buildFinanceInfoList();
await buildFinanceInfoList({
currentDir: '.',
configDir: 'config',
financeDir: 'finance',
year: '2024',
jsonDataDir: 'json-data'
});
}

module.exports = start;
Expand Down
80 changes: 80 additions & 0 deletions tests/casestudies/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
const fs = require('fs').promises;
const path = require('path');
const buildCaseStudiesList = require('../../scripts/casestudies/index');
const { yaml1,yaml2,json1,json2 } = require("../fixtures/caseStudyData");

describe('buildCaseStudiesList', () => {
const tempDir = path.join(__dirname, 'temp-test-dir');
const tempConfigDir = path.join(tempDir, 'config', 'casestudies');
const tempOutputFile = path.join(tempDir, 'case-studies.json');

beforeAll(async () => {
// Create temporary directories
await fs.mkdir(tempConfigDir, { recursive: true });
});

afterAll(async () => {
// Clean up temporary directories
await fs.rm(tempDir, { recursive: true, force: true });
});

beforeEach(async () => {
// Clear the config directory before each test
const files = await fs.readdir(tempConfigDir);
await Promise.all(files.map(file => fs.unlink(path.join(tempConfigDir, file))));
});

it('should read YAML files and create a JSON file with case studies', async () => {
// Create sample YAML files

await fs.writeFile(path.join(tempConfigDir, 'casestudy1.yml'), yaml1);
await fs.writeFile(path.join(tempConfigDir, 'casestudy2.yml'), yaml2);

// Run the function
await buildCaseStudiesList(tempConfigDir, tempOutputFile);

// Read the output JSON file
const outputContent = await fs.readFile(tempOutputFile, 'utf-8');
const outputJson = JSON.parse(outputContent);

expect(outputJson).toHaveLength(2);
expect(outputJson[0]).toEqual(json1);
expect(outputJson[1]).toEqual(json2);
});


it('should throw an error with incorrect parameters', async () => {
try {
await buildCaseStudiesList('invalid-dir', tempOutputFile);
} catch (error) {
expect(error).toBeInstanceOf(Error);
expect(error.message).toMatch(/ENOENT/); // Error for directory not found
}
});

it('should throw an error when the output file path is invalid', async () => {
try {
// Call the function with an invalid output file path
await buildCaseStudiesList(tempConfigDir, '/invalid-path/case-studies.json');
} catch (error) {
expect(error).toBeInstanceOf(Error);
}
});

it('should throw an error when YAML content is invalid', async () => {
// Create an invalid YAML file
const invalidYaml = `
invalid: yaml: content
`;
await fs.writeFile(path.join(tempConfigDir, 'invalid.yml'), invalidYaml);

try {
await buildCaseStudiesList(tempConfigDir, tempOutputFile);
} catch (error) {
expect(error).toBeInstanceOf(Error);
expect(error.message).toContain("Invalid content format"); // Error for invalid YAML content
}
});


});
105 changes: 105 additions & 0 deletions tests/finance/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
const fs = require('fs');
const path = require('path');
const buildFinanceInfoList = require('../../scripts/finance/index');
const { expensesYaml, expensesLinkYaml, expensesjson, expensesLinkjson } = require("../fixtures/financeData")

describe('buildFinanceInfoList', () => {
const testDir = path.resolve(__dirname, 'test-finance-info');
const configDir = 'config';
const financeDir = 'finance';
const year = '2024';
const jsonDataDir = 'json-data';

beforeAll(() => {
// Create test directory structure
fs.mkdirSync(path.resolve(testDir, configDir, financeDir, year), { recursive: true });

fs.writeFileSync(path.resolve(testDir, configDir, financeDir, year, 'Expenses.yml'), expensesYaml);
fs.writeFileSync(path.resolve(testDir, configDir, financeDir, year, 'ExpensesLink.yml'), expensesLinkYaml);
});

afterAll(() => {
// Clean up test directory
fs.rmSync(testDir, { recursive: true, force: true });
});

it('should create JSON files from YAML files', async () => {
await buildFinanceInfoList({
currentDir: testDir,
configDir,
financeDir,
year,
jsonDataDir
});

const jsonDir = path.resolve(testDir, configDir, financeDir, jsonDataDir, year);

// Check if JSON directory was created
expect(fs.existsSync(jsonDir)).toBe(true);

// Check if JSON files were created
const expensesJsonPath = path.resolve(jsonDir, 'Expenses.json');
const expensesLinkJsonPath = path.resolve(jsonDir, 'ExpensesLink.json');

expect(fs.existsSync(expensesJsonPath)).toBe(true);
expect(fs.existsSync(expensesLinkJsonPath)).toBe(true);

// Check contents of JSON files
const expensesJson = JSON.parse(fs.readFileSync(expensesJsonPath, 'utf8'));
const expensesLinkJson = JSON.parse(fs.readFileSync(expensesLinkJsonPath, 'utf8'));

expect(expensesJson).toEqual(expensesjson);
expect(expensesLinkJson).toEqual(expensesLinkjson);
});

it('should throw an error if YAML files are not found', async () => {
try {
await buildFinanceInfoList({
currentDir: testDir,
configDir,
financeDir,
year: '2023', // Non-existent year
jsonDataDir
});
} catch (error) {
expect(error).toBeInstanceOf(Error);
expect(error.message).toMatch(/ENOENT/); // Expecting a "no such file or directory" error
}
});

it('should throw an error if JSON directory creation fails', async () => {
try {
await buildFinanceInfoList({
currentDir: testDir,
configDir,
financeDir,
year,
jsonDataDir: 'nonexistent-dir' // Invalid JSON data directory path
});
} catch (error) {
expect(error).toBeInstanceOf(Error);
expect(error.message).toMatch(/ENOENT/); // Expecting a "no such file or directory" error
}
});

it('should throw an error if YAML content is invalid', async () => {
// Write invalid YAML content
const invalidYaml = `
invalid yaml content
`;
fs.writeFileSync(path.resolve(testDir, configDir, financeDir, year, 'InvalidExpenses.yml'), invalidYaml);

try {
await buildFinanceInfoList({
currentDir: testDir,
configDir,
financeDir,
year,
jsonDataDir
});
} catch (error) {
expect(error).toBeInstanceOf(Error);
expect(error.message).toMatch(/YAMLException/); // Expecting a YAML parsing error
}
});
});
21 changes: 21 additions & 0 deletions tests/fixtures/caseStudyData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
module.exports = {
yaml1: `
title: case study 1
description: random data
`,

yaml2:`
title: case study 2
description: again random data
`,

json1: {
title: 'case study 1',
description: 'random data'
},

json2: {
title: 'case study 2',
description: 'again random data'
}
}
6 changes: 6 additions & 0 deletions tests/fixtures/financeData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
expensesYaml: 'expenses:\n - name: Test Expense\n amount: 100',
expensesLinkYaml: 'links:\n - name: Test Link\n url: http://asyncapi.com',
expensesjson: { expenses: [{ name: 'Test Expense', amount: 100 }] },
expensesLinkjson: { links: [{ name: 'Test Link', url: 'http://asyncapi.com' }] }
}

0 comments on commit 0a999d9

Please sign in to comment.