Skip to content

Commit 66725ad

Browse files
Eisha KaushalEisha Kaushal
authored andcommitted
alert.js and mongo.js tests
1 parent 1a514df commit 66725ad

File tree

8 files changed

+600
-48
lines changed

8 files changed

+600
-48
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
const mongoose = require('mongoose');
2+
const alert = require('../../chronos_npm_package/controllers/alert');
3+
const axios = require('axios');
4+
const MockAdapter = require('axios-mock-adapter');
5+
6+
const mockAxios = new MockAdapter(axios);
7+
8+
const consoleLogSpy = jest.spyOn(console, 'log');
9+
jest.spyOn(console, 'error').mockImplementation(() => {});
10+
// jest.mock('axios', () => {
11+
// return {
12+
// post: jest.fn(),
13+
// };
14+
// });
15+
16+
17+
18+
describe('alert.sendSlack', () => {
19+
beforeEach(() => {
20+
mockAxios.reset();
21+
jest.clearAllMocks();
22+
});
23+
24+
test('should send Slack message with the correct data', async () => {
25+
const code = 500;
26+
const slackSettings = {
27+
webhook: 'https://example.com/slack-webhook',
28+
};
29+
const message = 'Internal server error';
30+
const expectedData = { text: `${code}, ${message}, ${Date.now()}` };
31+
mockAxios.onPost(slackSettings.webhook).reply(200, 'Status Code >= 400...\nError message sent');
32+
await alert.sendSlack(code, message, slackSettings);
33+
34+
expect(mockAxios.onPost).toHaveBeenCalledWith(slackSettings.webhook, expectedData, expect.any(Object));
35+
expect(consoleLogSpy).toHaveBeenCalledWith('Status Code >= 400...\nError message sent');
36+
});
37+
});
Lines changed: 219 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,236 @@
1-
//const mongoose = require('mongoose');
1+
const mongoose = require('mongoose');
22
const mongo = require('../../chronos_npm_package/controllers/mongo');
3-
const ServicesModel = require( '../../chronos_npm_package/models/ServicesModel');
4-
require('dotenv').config();
3+
const ServicesModel = require('../../chronos_npm_package/models/ServicesModel');
4+
const CommunicationModel = require('../../chronos_npm_package/models/CommunicationModel');
5+
const { connectDB, dropDB, dropCollections } = require('./testdbsetup');
6+
const alert = require('../../chronos_npm_package/controllers/alert');
7+
const ContainerInfo = require('../../chronos_npm_package/models/ContainerInfo');
58

6-
jest.mock('mongoose', () => {
7-
return {
8-
connect: jest.fn().mockResolvedValue(undefined),
9-
};
9+
//require('dotenv').config();
10+
11+
//const db = process.env.DB_URI;
12+
13+
beforeAll(async () => {
14+
await connectDB();
15+
});
16+
17+
afterAll(async () => {
18+
await dropDB();
1019
});
1120

21+
const db =
22+
'mongodb+srv://admin:[email protected]/test?retryWrites=true&w=majority';
23+
1224
jest.spyOn(console, 'log').mockImplementation(() => {});
1325

14-
describe('mongo.connect', () => {
15-
beforeEach(() => {
16-
jest.clearAllMocks();
17-
});
26+
jest.mock('../../chronos_npm_package/controllers/alert');
1827

19-
test('should connect to MongoDB database', async () => {
20-
const databaseURI = 'mongodb://localhost:27017/testdb';
21-
await mongo.connect({ databaseURI });
22-
expect(mongoose.connect).toHaveBeenCalledWith(databaseURI);
23-
expect(console.log).toHaveBeenCalledWith(expect.stringContaining('MongoDB database connected at'));
24-
});
28+
jest.useFakeTimers();
29+
30+
jest.spyOn(global, 'setInterval');
2531

26-
test('should handle connection error', async () => {
27-
const errorMessage = 'Connection failed';
28-
const databaseURI = 'mongodb://localhost:27017/testdb';
32+
jest.mock('../../chronos_npm_package/controllers/healthHelpers', () => {
33+
return [
34+
{
35+
time: Date.now(),
36+
metric: 'testMetric',
37+
value: 10,
38+
category: 'testCategory',
39+
},
40+
{
41+
time: Date.now(),
42+
metric: 'testMetric2',
43+
value: 12,
44+
category: 'testCategory2',
45+
},
46+
];
47+
});
2948

30-
jest.spyOn(mongoose, 'connect').mockRejectedValueOnce(new Error(errorMessage));
49+
jest.mock('../../chronos_npm_package/controllers/mongo', () => ({
50+
...jest.requireActual('../../chronos_npm_package/controllers/mongo'),
51+
addMetrics: jest.fn(),
52+
getSavedMetricsLength: jest.fn(),
53+
}));
3154

32-
await mongo.connect({ databaseURI });
33-
expect(mongoose.connect).toHaveBeenCalledWith(databaseURI);
34-
expect(console.log).toHaveBeenCalledWith(expect.stringContaining(errorMessage));
55+
const HealthModel = {
56+
insertMany: jest.fn(() => Promise.resolve()),
57+
};
3558

36-
});
59+
const HealthModelFunc = jest.fn(() => HealthModel);
60+
61+
describe('mongo.connect', () => {
62+
beforeEach(() => {
63+
jest.clearAllMocks();
64+
});
65+
66+
test('should connect to MongoDB database', async () => {
67+
await mongo.connect({ database: { URI: db } });
68+
69+
//expect(mongoose.connect).toHaveBeenCalledWith(db);
70+
expect(console.log).toHaveBeenCalledWith(
71+
expect.stringContaining('MongoDB database connected at')
72+
);
73+
});
74+
75+
test('should handle connection errors', async () => {
76+
const testDb = 'test';
77+
await mongo.connect({ database: { URI: testDb } });
78+
79+
expect(console.log).toHaveBeenCalledWith(
80+
expect.stringContaining('Error connecting to MongoDB:'),
81+
expect.any(String)
82+
);
83+
});
3784
});
3885

3986
describe('mongo.services', () => {
40-
beforeEach(() => {
41-
jest.clearAllMocks();
42-
});
87+
beforeEach(() => {
88+
jest.clearAllMocks();
89+
});
90+
91+
afterEach(async () => {
92+
await dropCollections();
93+
});
4394

44-
test('should create a new document', async () => {
95+
test('should create a new document', async () => {
96+
await mongo.services({ microservice: 'test2', interval: 'test2' });
97+
const savedService = await ServicesModel.findOne({ microservice: 'test2', interval: 'test2' });
98+
expect(savedService).toBeDefined(); // The document should be defined if it exists
99+
});
100+
});
101+
102+
describe('mongo.communications', () => {
103+
afterEach(async () => {
104+
await dropCollections();
105+
});
45106

107+
test('should record request cycle and save communication to the database', async () => {
108+
const req = {};
109+
const res = {
110+
statusCode: 200,
111+
statusMessage: 'OK',
112+
getHeaders: () => ({ 'x-correlation-id': 'correlation-id-123' }),
113+
on: jest.fn((event, callback) => {
114+
if (event === 'finish') {
115+
callback();
116+
}
117+
}),
118+
};
119+
const middleware = mongo.communications({ microservice: 'test3', slack: null, email: null });
120+
await middleware(req, res, () => {});
121+
const savedCommunication = await CommunicationModel.findOne({ microservice: 'test3' });
122+
expect(savedCommunication).toBeDefined(); // The document should be defined if it exists
123+
});
124+
125+
test('should send an alert', async () => {
126+
const req = {};
127+
const res = {
128+
statusCode: 400,
129+
statusMessage: 'Not Found',
130+
getHeaders: () => ({ 'x-correlation-id': 'correlation-id-123' }),
131+
on: jest.fn((event, callback) => {
132+
if (event === 'finish') {
133+
callback();
134+
}
135+
}),
136+
};
137+
const middleware = mongo.communications({
138+
microservice: 'test4',
139+
slack: 'slackTest',
140+
email: 'emailTest',
46141
});
47-
});
142+
await middleware(req, res, () => {});
143+
expect(alert.sendSlack).toHaveBeenCalledTimes(1);
144+
expect(alert.sendEmail).toHaveBeenCalledTimes(1);
145+
expect(alert.sendSlack).toHaveBeenCalledWith(res.statusCode, res.statusMessage, 'slackTest');
146+
expect(alert.sendEmail).toHaveBeenCalledWith(res.statusCode, res.statusMessage, 'emailTest');
147+
});
148+
});
149+
150+
describe('mongo.health', () => {
151+
beforeEach(() => {
152+
jest.clearAllMocks();
153+
jest.useFakeTimers();
154+
});
155+
156+
afterEach(() => {
157+
jest.clearAllTimers();
158+
});
159+
160+
test('should collect data after the set interval', async () => {
161+
await mongo.health({ microservice: 'mongo.health test', interval: 1000, mode: 'testMode' });
162+
jest.advanceTimersByTime(1000);
163+
expect(setInterval).toHaveBeenCalledWith(expect.any(Function), 1000);
164+
expect(collectHealthData).toHaveBeenCalled();
165+
});
166+
167+
test('should save metrics to database', async () => {
168+
const mockData = [
169+
{
170+
time: Date.now(),
171+
metric: 'testMetric',
172+
value: 10,
173+
category: 'testCategory',
174+
},
175+
{
176+
time: Date.now(),
177+
metric: 'testMetric2',
178+
value: 12,
179+
category: 'testCategory2',
180+
},
181+
];
182+
await mongo.health({ microservice: 'mongo.health test', interval: 1000, mode: 'testMode' });
183+
jest.advanceTimersByTime(1000);
184+
expect(collectHealthData).toHaveReturnedWith(mockData);
185+
expect(HealthModelFunc).toHaveBeenCalled();
186+
expect(HealthModel).toHaveBeenCalled();
187+
});
188+
});
189+
190+
describe('mongo.docker', () => {
191+
beforeEach(async () => {
192+
jest.clearAllMocks();
193+
jest.useFakeTimers();
194+
});
195+
196+
afterEach(async () => {
197+
await dropCollections();
198+
jest.clearAllTimers();
199+
});
200+
201+
test('should collect docker container information', async () => {
202+
const microservice = 'mongo.docker test';
203+
const mockContainerData = {
204+
containername: microservice,
205+
containerId: '234',
206+
platform: 'testPlatform',
207+
startime: Date.now(),
208+
};
209+
const mockReadDockerContainerData = {
210+
...mockContainerData,
211+
memoryusage: 234,
212+
memorylimit: 234,
213+
memorypercent: 32,
214+
cpupercent: 45,
215+
networkreceived: 345,
216+
networksent: 345,
217+
processcount: 343,
218+
restartcount: 12,
219+
time: Date.now(),
220+
};
221+
222+
jest.mock('../../chronos_npm_package/controllers/dockerHelper', () => ({
223+
getDockerContainer: jest.fn(() => Promise.resolve(mockContainerData)),
224+
readDockerContainer: jest.fn(() => Promise.resolve(mockReadDockerContainerData)),
225+
}));
226+
227+
await mongo.docker({ microservice: microservice, interval: 1000, mode: 'testMode' });
228+
expect(getDockerContainer).toHaveBeenCalledWith(microservice);
229+
jest.advanceTimersByTime(1000);
230+
expect(readDockerContainer).toHaveBeenCalledWith(mockContainerData);
231+
const savedContainerInfo = await ContainerInfo.findOne({ containername: microservice });
232+
expect(savedContainerInfo).toBeDefined();
233+
expect(savedContainerInfo).toMatchObject(mockReadDockerContainerData);
234+
});
235+
});
236+

__backend-tests__/jest.config.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
module.exports = {
2-
testEnvironment: 'node', // Use the Node.js environment for testing
3-
roots: ['<rootDir>/controllers'], // Set the root directory for test files (adjust this path to your test folder)
4-
5-
testRegex: '(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
6-
7-
// Code coverage settings
8-
collectCoverage: true,
9-
coverageDirectory: 'coverage',
2+
testEnvironment: 'node', // Use the Node.js environment for testing
3+
roots: ['<rootDir>/controllers'], // Set the root directory for test files
104

11-
// Specify the test path patterns to ignore (frontend tests)
12-
testPathIgnorePatterns: ['/node_modules/', '/__tests__/'],
13-
};
14-
5+
testRegex: '(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
6+
7+
// Code coverage settings
8+
collectCoverage: true,
9+
coverageDirectory: 'coverage',
10+
11+
// Specify the test path patterns to ignore frontend tests
12+
testPathIgnorePatterns: ['/node_modules/', '/__tests__/'],
13+
};
14+

__backend-tests__/mockdbsetup.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const mongoose = require("mongoose");
2+
const { MongoMemoryServer } = require("mongodb-memory-server");
3+
4+
let mongo = null;
5+
6+
const connectDB = async () => {
7+
mongo = await MongoMemoryServer.create();
8+
const uri = mongo.getUri();
9+
10+
await mongoose.connect(uri, {
11+
useNewUrlParser: true,
12+
useUnifiedTopology: true,
13+
});
14+
};
15+
16+
const dropDB = async () => {
17+
if (mongo) {
18+
await mongoose.connection.dropDatabase();
19+
await mongoose.connection.close();
20+
await mongo.stop();
21+
}
22+
};
23+
24+
const dropCollections = async () => {
25+
if (mongo) {
26+
const collections = await mongoose.connection.db.collections();
27+
for (let collection of collections) {
28+
await collection.deleteMany();
29+
}
30+
}
31+
};
32+
33+
34+
module.exports = { connectDB, dropDB, dropCollections}

chronos_npm_package/controllers/mongo.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ mongo.health = async ({ microservice, interval, mode }) => {
133133
*/
134134
mongo.docker = ({ microservice, interval, mode }) => {
135135
// Create collection using name of microservice
136-
const containerInfo = ContainerInfoFunc(`${microservice}-containerinfo`);
136+
const containerInfo = ContainerInfoFunc(`${microservice}`);
137137
dockerHelper
138138
.getDockerContainer(microservice)
139139
.then(containerData => {
@@ -144,7 +144,7 @@ mongo.docker = ({ microservice, interval, mode }) => {
144144
return containerInfo.create(data);
145145
})
146146
.then(_ =>
147-
console.log(`Docker data recorded in MongoDB collection ${microservice}-containerinfo`)
147+
console.log(`Docker data recorded in MongoDB collection ${microservice}`)
148148
)
149149
.catch(err => {
150150
throw new Error(err);

electron/models/DockerModel.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,6 @@ const DockerSchema = new Schema({
5454
});
5555

5656
const DockerModelFunc = (serviceName: any) =>
57-
mongoose.model<any>(`${serviceName}-containerinfos`, DockerSchema);
57+
mongoose.model<any>(`${serviceName}`, DockerSchema);
5858

5959
export default DockerModelFunc;

0 commit comments

Comments
 (0)