Skip to content

Commit d515cc3

Browse files
committed
chronosMethods working but mongo test is not
1 parent 60757b8 commit d515cc3

File tree

2 files changed

+280
-0
lines changed

2 files changed

+280
-0
lines changed

__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}

__backend-tests__/mongo.test.js

Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
const mongoose = require('mongoose');
2+
const mongo = require('../chronos_npm_package/controllers/mongo');
3+
const ServicesModel = require('../chronos_npm_package/models/ServicesModel');
4+
const CommunicationModel = require('../chronos_npm_package/models/CommunicationModel');
5+
const { connectDB, dropDB, dropCollections } = require('./mockdbsetup');
6+
const alert = require('../chronos_npm_package/controllers/alert');
7+
const ContainerInfoFunc = require('../chronos_npm_package/models/ContainerInfo');
8+
const dockerHelper = require('../chronos_npm_package/controllers/dockerHelper');
9+
10+
require('dotenv').config();
11+
12+
const db = process.env.DB_URI;
13+
14+
beforeAll(async () => {
15+
await connectDB();
16+
});
17+
18+
afterAll(async () => {
19+
await dropDB();
20+
});
21+
22+
jest.spyOn(console, 'log').mockImplementation(() => {});
23+
24+
jest.mock('../chronos_npm_package/controllers/alert');
25+
26+
jest.useFakeTimers();
27+
28+
jest.spyOn(global, 'setInterval');
29+
30+
jest.mock('../chronos_npm_package/controllers/healthHelpers', () => {
31+
return [
32+
{
33+
time: Date.now(),
34+
metric: 'testMetric',
35+
value: 10,
36+
category: 'testCategory',
37+
},
38+
{
39+
time: Date.now(),
40+
metric: 'testMetric2',
41+
value: 12,
42+
category: 'testCategory2',
43+
},
44+
];
45+
});
46+
47+
jest.mock('../chronos_npm_package/controllers/mongo', () => ({
48+
...jest.requireActual('../chronos_npm_package/controllers/mongo'),
49+
addMetrics: jest.fn(),
50+
getSavedMetricsLength: jest.fn(),
51+
}));
52+
53+
const HealthModel = {
54+
insertMany: jest.fn(() => Promise.resolve()),
55+
};
56+
57+
jest.mock('../chronos_npm_package/controllers/dockerHelper', () => ({
58+
...jest.requireActual('../chronos_npm_package/controllers/dockerHelper'),
59+
getDockerContainer: jest.fn(),
60+
readDockerContainer: jest.fn(),
61+
}));
62+
63+
// jest.mock('../../chronos_npm_package/models/ContainerInfo', () => {
64+
// const mockContainerInfoInstance = {
65+
// create: jest.fn(),
66+
// };
67+
// return jest.fn(() => mockContainerInfoInstance);
68+
// });
69+
70+
const HealthModelFunc = jest.fn(() => HealthModel);
71+
72+
describe('mongo.connect', () => {
73+
beforeEach(() => {
74+
jest.clearAllMocks();
75+
});
76+
77+
test('should connect to MongoDB database', async () => {
78+
await mongo.connect({ database: { URI: db } });
79+
80+
//expect(mongoose.connect).toHaveBeenCalledWith(db);
81+
expect(console.log).toHaveBeenCalledWith(
82+
expect.stringContaining('MongoDB database connected at')
83+
);
84+
});
85+
86+
test('should handle connection errors', async () => {
87+
const testDb = 'test';
88+
await mongo.connect({ database: { URI: testDb } });
89+
90+
expect(console.log).toHaveBeenCalledWith(
91+
expect.stringContaining('Error connecting to MongoDB:'),
92+
expect.any(String)
93+
);
94+
});
95+
});
96+
97+
describe('mongo.services', () => {
98+
beforeEach(() => {
99+
jest.clearAllMocks();
100+
});
101+
102+
afterEach(async () => {
103+
await dropCollections();
104+
});
105+
106+
test('should create a new document', async () => {
107+
await mongo.services({ microservice: 'test2', interval: 'test2' });
108+
const savedService = await ServicesModel.findOne({ microservice: 'test2', interval: 'test2' });
109+
expect(savedService).toBeDefined(); // The document should be defined if it exists
110+
});
111+
});
112+
113+
describe('mongo.communications', () => {
114+
beforeEach(() => {
115+
jest.clearAllMocks();
116+
});
117+
118+
afterEach(async () => {
119+
await dropCollections();
120+
});
121+
122+
test('should record request cycle and save communication to the database', async () => {
123+
const req = {};
124+
const res = {
125+
statusCode: 200,
126+
statusMessage: 'OK',
127+
getHeaders: () => ({ 'x-correlation-id': 'correlation-id-123' }),
128+
on: jest.fn((event, callback) => {
129+
if (event === 'finish') {
130+
callback();
131+
}
132+
}),
133+
};
134+
const middleware = mongo.communications({ microservice: 'test3', slack: null, email: null });
135+
await middleware(req, res, () => {});
136+
const savedCommunication = await CommunicationModel.findOne({ microservice: 'test3' });
137+
expect(savedCommunication).toBeDefined(); // The document should be defined if it exists
138+
});
139+
140+
test('should send an alert', async () => {
141+
const req = {};
142+
const res = {
143+
statusCode: 400,
144+
statusMessage: 'Not Found',
145+
getHeaders: () => ({ 'x-correlation-id': 'correlation-id-123' }),
146+
on: jest.fn((event, callback) => {
147+
if (event === 'finish') {
148+
callback();
149+
}
150+
}),
151+
};
152+
const middleware = mongo.communications({
153+
microservice: 'test4',
154+
slack: 'slackTest',
155+
email: 'emailTest',
156+
});
157+
await middleware(req, res, () => {});
158+
expect(alert.sendSlack).toHaveBeenCalledTimes(1);
159+
expect(alert.sendEmail).toHaveBeenCalledTimes(1);
160+
expect(alert.sendSlack).toHaveBeenCalledWith(res.statusCode, res.statusMessage, 'slackTest');
161+
expect(alert.sendEmail).toHaveBeenCalledWith(res.statusCode, res.statusMessage, 'emailTest');
162+
});
163+
});
164+
165+
describe('mongo.health', () => {
166+
beforeEach(() => {
167+
jest.clearAllMocks();
168+
jest.useFakeTimers();
169+
});
170+
171+
afterEach(() => {
172+
jest.clearAllTimers();
173+
});
174+
175+
test('should collect data after the set interval', async () => {
176+
await mongo.health({ microservice: 'mongo.health test', interval: 1000, mode: 'testMode' });
177+
jest.advanceTimersByTime(1000);
178+
expect(setInterval).toHaveBeenCalledWith(expect.any(Function), 1000);
179+
expect(collectHealthData).toHaveBeenCalled();
180+
});
181+
182+
test('should save metrics to database', async () => {
183+
const mockData = [
184+
{
185+
time: Date.now(),
186+
metric: 'testMetric',
187+
value: 10,
188+
category: 'testCategory',
189+
},
190+
{
191+
time: Date.now(),
192+
metric: 'testMetric2',
193+
value: 12,
194+
category: 'testCategory2',
195+
},
196+
];
197+
await mongo.health({ microservice: 'mongo.health test', interval: 1000, mode: 'testMode' });
198+
jest.advanceTimersByTime(1000);
199+
expect(collectHealthData).toHaveReturnedWith(mockData);
200+
expect(HealthModelFunc).toHaveBeenCalled();
201+
expect(HealthModel).toHaveBeenCalled();
202+
});
203+
});
204+
205+
describe('mongo.docker', () => {
206+
beforeEach(async () => {
207+
jest.clearAllMocks();
208+
jest.useFakeTimers();
209+
});
210+
211+
afterEach(async () => {
212+
await dropCollections();
213+
jest.clearAllTimers();
214+
});
215+
216+
test('should collect docker container information', async () => {
217+
const microservice = 'mongo.docker test';
218+
const mockContainerData = {
219+
containername: microservice,
220+
containerId: '234',
221+
platform: 'testPlatform',
222+
startime: Date.now(),
223+
};
224+
const mockReadDockerContainerData = {
225+
...mockContainerData,
226+
memoryusage: 234,
227+
memorylimit: 234,
228+
memorypercent: 32,
229+
cpupercent: 45,
230+
networkreceived: 345,
231+
networksent: 345,
232+
processcount: 343,
233+
restartcount: 12,
234+
time: Date.now(),
235+
};
236+
237+
dockerHelper.getDockerContainer.mockResolvedValue(mockContainerData);
238+
dockerHelper.readDockerContainer.mockResolvedValue(mockReadDockerContainerData);
239+
240+
await mongo.docker({ microservice: microservice, interval: 1000, mode: 'testMode' });
241+
expect(dockerHelper.getDockerContainer).toHaveBeenCalledWith(microservice);
242+
jest.advanceTimersByTime(1000);
243+
expect(dockerHelper.readDockerContainer).toHaveBeenCalledWith(mockContainerData);
244+
//expect(mockContainerInfoInstance.create).toHaveBeenCalledWith(mockReadDockerContainerData);
245+
});
246+
});

0 commit comments

Comments
 (0)