Merge branch 'develop' into 915-be-add-new-endpoint-for-refreshing-access-token
This commit is contained in:
commit
af685f3c8b
216 files changed
+34332
-31888
No files matched your search
@@ -1,375 +1,373 @@
|
||||
import {
|
||||
createCheck,
|
||||
getChecks,
|
||||
getTeamChecks,
|
||||
deleteChecks,
|
||||
deleteChecksByTeamId,
|
||||
updateChecksTTL,
|
||||
createCheck,
|
||||
getChecks,
|
||||
getTeamChecks,
|
||||
deleteChecks,
|
||||
deleteChecksByTeamId,
|
||||
updateChecksTTL,
|
||||
} from "../../controllers/checkController.js";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { errorMessages, successMessages } from "../../utils/messages.js";
|
||||
import sinon from "sinon";
|
||||
describe("Check Controller - createCheck", () => {
|
||||
let req, res, next, handleError;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
params: {},
|
||||
body: {},
|
||||
db: {
|
||||
createCheck: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
handleError = sinon.stub();
|
||||
});
|
||||
let req, res, next, handleError;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
params: {},
|
||||
body: {},
|
||||
db: {
|
||||
createCheck: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
handleError = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore(); // Restore the original methods after each test
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore(); // Restore the original methods after each test
|
||||
});
|
||||
|
||||
it("should reject with a validation if params are invalid", async () => {
|
||||
await createCheck(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject with a validation if params are invalid", async () => {
|
||||
await createCheck(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should reject with a validation error if body is invalid", async () => {
|
||||
req.params = {
|
||||
monitorId: "monitorId",
|
||||
};
|
||||
await createCheck(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject with a validation error if body is invalid", async () => {
|
||||
req.params = {
|
||||
monitorId: "monitorId",
|
||||
};
|
||||
await createCheck(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should call next with error if data retrieval fails", async () => {
|
||||
req.params = {
|
||||
monitorId: "monitorId",
|
||||
};
|
||||
req.body = {
|
||||
monitorId: "monitorId",
|
||||
status: true,
|
||||
responseTime: 100,
|
||||
statusCode: 200,
|
||||
message: "message",
|
||||
};
|
||||
req.db.createCheck.rejects(new Error("error"));
|
||||
await createCheck(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
});
|
||||
it("should call next with error if data retrieval fails", async () => {
|
||||
req.params = {
|
||||
monitorId: "monitorId",
|
||||
};
|
||||
req.body = {
|
||||
monitorId: "monitorId",
|
||||
status: true,
|
||||
responseTime: 100,
|
||||
statusCode: 200,
|
||||
message: "message",
|
||||
};
|
||||
req.db.createCheck.rejects(new Error("error"));
|
||||
await createCheck(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
});
|
||||
|
||||
it("should return a success message if check is created", async () => {
|
||||
req.params = {
|
||||
monitorId: "monitorId",
|
||||
};
|
||||
req.db.createCheck.resolves({ id: "123" });
|
||||
req.body = {
|
||||
monitorId: "monitorId",
|
||||
status: true,
|
||||
responseTime: 100,
|
||||
statusCode: 200,
|
||||
message: "message",
|
||||
};
|
||||
await createCheck(req, res, next);
|
||||
expect(res.status.calledWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledWith({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_CREATE,
|
||||
data: { id: "123" },
|
||||
})
|
||||
).to.be.true;
|
||||
expect(next.notCalled).to.be.true;
|
||||
});
|
||||
it("should return a success message if check is created", async () => {
|
||||
req.params = {
|
||||
monitorId: "monitorId",
|
||||
};
|
||||
req.db.createCheck.resolves({ id: "123" });
|
||||
req.body = {
|
||||
monitorId: "monitorId",
|
||||
status: true,
|
||||
responseTime: 100,
|
||||
statusCode: 200,
|
||||
message: "message",
|
||||
};
|
||||
await createCheck(req, res, next);
|
||||
expect(res.status.calledWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledWith({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_CREATE,
|
||||
data: { id: "123" },
|
||||
})
|
||||
).to.be.true;
|
||||
expect(next.notCalled).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("Check Controller - getChecks", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
params: {},
|
||||
query: {},
|
||||
db: {
|
||||
getChecks: sinon.stub(),
|
||||
getChecksCount: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
params: {},
|
||||
query: {},
|
||||
db: {
|
||||
getChecks: sinon.stub(),
|
||||
getChecksCount: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should reject with a validation error if params are invalid", async () => {
|
||||
await getChecks(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject with a validation error if params are invalid", async () => {
|
||||
await getChecks(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should return a success message if checks are found", async () => {
|
||||
req.params = {
|
||||
monitorId: "monitorId",
|
||||
};
|
||||
req.db.getChecks.resolves([{ id: "123" }]);
|
||||
req.db.getChecksCount.resolves(1);
|
||||
await getChecks(req, res, next);
|
||||
expect(res.status.calledWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledWith({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_GET,
|
||||
data: { checksCount: 1, checks: [{ id: "123" }] },
|
||||
})
|
||||
).to.be.true;
|
||||
expect(next.notCalled).to.be.true;
|
||||
});
|
||||
it("should return a success message if checks are found", async () => {
|
||||
req.params = {
|
||||
monitorId: "monitorId",
|
||||
};
|
||||
req.db.getChecks.resolves([{ id: "123" }]);
|
||||
req.db.getChecksCount.resolves(1);
|
||||
await getChecks(req, res, next);
|
||||
expect(res.status.calledWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledWith({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_GET,
|
||||
data: { checksCount: 1, checks: [{ id: "123" }] },
|
||||
})
|
||||
).to.be.true;
|
||||
expect(next.notCalled).to.be.true;
|
||||
});
|
||||
|
||||
it("should call next with error if data retrieval fails", async () => {
|
||||
req.params = {
|
||||
monitorId: "monitorId",
|
||||
};
|
||||
req.db.getChecks.rejects(new Error("error"));
|
||||
await getChecks(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
});
|
||||
it("should call next with error if data retrieval fails", async () => {
|
||||
req.params = {
|
||||
monitorId: "monitorId",
|
||||
};
|
||||
req.db.getChecks.rejects(new Error("error"));
|
||||
await getChecks(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Check Controller - getTeamChecks", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
params: {},
|
||||
query: {},
|
||||
db: {
|
||||
getTeamChecks: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
params: {},
|
||||
query: {},
|
||||
db: {
|
||||
getTeamChecks: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should reject with a validation error if params are invalid", async () => {
|
||||
await getTeamChecks(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject with a validation error if params are invalid", async () => {
|
||||
await getTeamChecks(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should return 200 and check data on successful validation and data retrieval", async () => {
|
||||
req.params = { teamId: "1" };
|
||||
const checkData = [{ id: 1, name: "Check 1" }];
|
||||
req.db.getTeamChecks.resolves(checkData);
|
||||
it("should return 200 and check data on successful validation and data retrieval", async () => {
|
||||
req.params = { teamId: "1" };
|
||||
const checkData = [{ id: 1, name: "Check 1" }];
|
||||
req.db.getTeamChecks.resolves(checkData);
|
||||
|
||||
await getTeamChecks(req, res, next);
|
||||
expect(req.db.getTeamChecks.calledOnceWith(req)).to.be.true;
|
||||
expect(res.status.calledOnceWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_GET,
|
||||
data: checkData,
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
await getTeamChecks(req, res, next);
|
||||
expect(req.db.getTeamChecks.calledOnceWith(req)).to.be.true;
|
||||
expect(res.status.calledOnceWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_GET,
|
||||
data: checkData,
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
|
||||
it("should call next with error if data retrieval fails", async () => {
|
||||
req.params = { teamId: "1" };
|
||||
req.db.getTeamChecks.rejects(new Error("Retrieval Error"));
|
||||
await getTeamChecks(req, res, next);
|
||||
expect(req.db.getTeamChecks.calledOnceWith(req)).to.be.true;
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(res.status.notCalled).to.be.true;
|
||||
expect(res.json.notCalled).to.be.true;
|
||||
});
|
||||
it("should call next with error if data retrieval fails", async () => {
|
||||
req.params = { teamId: "1" };
|
||||
req.db.getTeamChecks.rejects(new Error("Retrieval Error"));
|
||||
await getTeamChecks(req, res, next);
|
||||
expect(req.db.getTeamChecks.calledOnceWith(req)).to.be.true;
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(res.status.notCalled).to.be.true;
|
||||
expect(res.json.notCalled).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("Check Controller - deleteChecks", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
params: {},
|
||||
db: {
|
||||
deleteChecks: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
params: {},
|
||||
db: {
|
||||
deleteChecks: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should reject with an error if param validation fails", async () => {
|
||||
await deleteChecks(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject with an error if param validation fails", async () => {
|
||||
await deleteChecks(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should call next with error if data retrieval fails", async () => {
|
||||
req.params = { monitorId: "1" };
|
||||
req.db.deleteChecks.rejects(new Error("Deletion Error"));
|
||||
await deleteChecks(req, res, next);
|
||||
expect(req.db.deleteChecks.calledOnceWith(req.params.monitorId)).to.be.true;
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(res.status.notCalled).to.be.true;
|
||||
expect(res.json.notCalled).to.be.true;
|
||||
});
|
||||
it("should call next with error if data retrieval fails", async () => {
|
||||
req.params = { monitorId: "1" };
|
||||
req.db.deleteChecks.rejects(new Error("Deletion Error"));
|
||||
await deleteChecks(req, res, next);
|
||||
expect(req.db.deleteChecks.calledOnceWith(req.params.monitorId)).to.be.true;
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(res.status.notCalled).to.be.true;
|
||||
expect(res.json.notCalled).to.be.true;
|
||||
});
|
||||
|
||||
it("should delete checks successfully", async () => {
|
||||
req.params = { monitorId: "123" };
|
||||
req.db.deleteChecks.resolves(1);
|
||||
await deleteChecks(req, res, next);
|
||||
expect(req.db.deleteChecks.calledOnceWith(req.params.monitorId)).to.be.true;
|
||||
expect(res.status.calledOnceWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_DELETE,
|
||||
data: { deletedCount: 1 },
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
it("should delete checks successfully", async () => {
|
||||
req.params = { monitorId: "123" };
|
||||
req.db.deleteChecks.resolves(1);
|
||||
await deleteChecks(req, res, next);
|
||||
expect(req.db.deleteChecks.calledOnceWith(req.params.monitorId)).to.be.true;
|
||||
expect(res.status.calledOnceWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_DELETE,
|
||||
data: { deletedCount: 1 },
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("Check Controller - deleteChecksByTeamId", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
params: {},
|
||||
db: {
|
||||
deleteChecksByTeamId: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
params: {},
|
||||
db: {
|
||||
deleteChecksByTeamId: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should reject with an error if param validation fails", async () => {
|
||||
await deleteChecksByTeamId(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject with an error if param validation fails", async () => {
|
||||
await deleteChecksByTeamId(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should call next with error if data retrieval fails", async () => {
|
||||
req.params = { teamId: "1" };
|
||||
req.db.deleteChecksByTeamId.rejects(new Error("Deletion Error"));
|
||||
await deleteChecksByTeamId(req, res, next);
|
||||
expect(req.db.deleteChecksByTeamId.calledOnceWith(req.params.teamId)).to.be
|
||||
.true;
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(res.status.notCalled).to.be.true;
|
||||
expect(res.json.notCalled).to.be.true;
|
||||
});
|
||||
it("should call next with error if data retrieval fails", async () => {
|
||||
req.params = { teamId: "1" };
|
||||
req.db.deleteChecksByTeamId.rejects(new Error("Deletion Error"));
|
||||
await deleteChecksByTeamId(req, res, next);
|
||||
expect(req.db.deleteChecksByTeamId.calledOnceWith(req.params.teamId)).to.be.true;
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(res.status.notCalled).to.be.true;
|
||||
expect(res.json.notCalled).to.be.true;
|
||||
});
|
||||
|
||||
it("should delete checks successfully", async () => {
|
||||
req.params = { teamId: "123" };
|
||||
req.db.deleteChecksByTeamId.resolves(1);
|
||||
await deleteChecksByTeamId(req, res, next);
|
||||
expect(req.db.deleteChecksByTeamId.calledOnceWith(req.params.teamId)).to.be
|
||||
.true;
|
||||
expect(res.status.calledOnceWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_DELETE,
|
||||
data: { deletedCount: 1 },
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
it("should delete checks successfully", async () => {
|
||||
req.params = { teamId: "123" };
|
||||
req.db.deleteChecksByTeamId.resolves(1);
|
||||
await deleteChecksByTeamId(req, res, next);
|
||||
expect(req.db.deleteChecksByTeamId.calledOnceWith(req.params.teamId)).to.be.true;
|
||||
expect(res.status.calledOnceWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_DELETE,
|
||||
data: { deletedCount: 1 },
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("Check Controller - updateCheckTTL", () => {
|
||||
let stub, req, res, next;
|
||||
beforeEach(() => {
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
let stub, req, res, next;
|
||||
beforeEach(() => {
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
|
||||
req = {
|
||||
body: {},
|
||||
headers: { authorization: "Bearer token" },
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "my_secret" }),
|
||||
},
|
||||
db: {
|
||||
updateChecksTTL: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
req = {
|
||||
body: {},
|
||||
headers: { authorization: "Bearer token" },
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "my_secret" }),
|
||||
},
|
||||
db: {
|
||||
updateChecksTTL: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
stub.restore();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
stub.restore();
|
||||
});
|
||||
|
||||
it("should reject if body validation fails", async () => {
|
||||
await updateChecksTTL(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject if body validation fails", async () => {
|
||||
await updateChecksTTL(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should throw a JwtError if verification fails", async () => {
|
||||
stub.restore();
|
||||
req.body = {
|
||||
ttl: 1,
|
||||
};
|
||||
await updateChecksTTL(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
|
||||
});
|
||||
it("should throw a JwtError if verification fails", async () => {
|
||||
stub.restore();
|
||||
req.body = {
|
||||
ttl: 1,
|
||||
};
|
||||
await updateChecksTTL(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
|
||||
});
|
||||
|
||||
it("should call next with error if data retrieval fails", async () => {
|
||||
req.body = {
|
||||
ttl: 1,
|
||||
};
|
||||
req.db.updateChecksTTL.rejects(new Error("Update Error"));
|
||||
await updateChecksTTL(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
});
|
||||
it("should call next with error if data retrieval fails", async () => {
|
||||
req.body = {
|
||||
ttl: 1,
|
||||
};
|
||||
req.db.updateChecksTTL.rejects(new Error("Update Error"));
|
||||
await updateChecksTTL(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
});
|
||||
|
||||
it("should update TTL successfully", async () => {
|
||||
req.body = {
|
||||
ttl: 1,
|
||||
};
|
||||
req.db.updateChecksTTL.resolves();
|
||||
await updateChecksTTL(req, res, next);
|
||||
expect(req.db.updateChecksTTL.calledOnceWith("123", 1 * 86400)).to.be.true;
|
||||
expect(res.status.calledOnceWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_UPDATE_TTL,
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
it("should update TTL successfully", async () => {
|
||||
req.body = {
|
||||
ttl: 1,
|
||||
};
|
||||
req.db.updateChecksTTL.resolves();
|
||||
await updateChecksTTL(req, res, next);
|
||||
expect(req.db.updateChecksTTL.calledOnceWith("123", 1 * 86400)).to.be.true;
|
||||
expect(res.status.calledOnceWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.CHECK_UPDATE_TTL,
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,9 @@ import {
|
||||
fetchMonitorCertificate,
|
||||
} from "../../controllers/controllerUtils.js";
|
||||
import { expect } from "chai";
|
||||
import sslChecker from "ssl-checker";
|
||||
import { afterEach } from "node:test";
|
||||
import exp from "constants";
|
||||
|
||||
describe("controllerUtils - handleValidationError", () => {
|
||||
it("should set status to 422", () => {
|
||||
@@ -109,102 +112,40 @@ describe("controllerUtils - handleError", () => {
|
||||
});
|
||||
|
||||
describe("controllerUtils - fetchMonitorCertificate", () => {
|
||||
const originalTls = {
|
||||
connect: sinon.stub().callsFake((options, callback) => {
|
||||
// Create socket stub with sinon stubs for all methods
|
||||
socket = {
|
||||
getPeerX509Certificate: sinon.stub().returns({
|
||||
subject: "CN=fake-cert",
|
||||
validTo: "Dec 31 23:59:59 2023 GMT",
|
||||
}),
|
||||
end: sinon.stub(),
|
||||
on: sinon.stub(),
|
||||
};
|
||||
|
||||
// Use process.nextTick to ensure async behavior
|
||||
process.nextTick(() => {
|
||||
callback.call(socket); // Ensure correct 'this' binding
|
||||
});
|
||||
|
||||
return socket;
|
||||
}),
|
||||
};
|
||||
|
||||
let tls, monitor, socket;
|
||||
let sslChecker, monitor;
|
||||
beforeEach(() => {
|
||||
monitor = { url: "https://www.google.com" };
|
||||
tls = {
|
||||
connect: sinon.stub().callsFake((options, callback) => {
|
||||
// Create socket stub with sinon stubs for all methods
|
||||
socket = {
|
||||
getPeerX509Certificate: sinon.stub().returns({
|
||||
subject: "CN=fake-cert",
|
||||
validTo: "Dec 31 23:59:59 2023 GMT",
|
||||
}),
|
||||
end: sinon.stub(),
|
||||
on: sinon.stub(),
|
||||
};
|
||||
|
||||
// Use process.nextTick to ensure async behavior
|
||||
process.nextTick(() => {
|
||||
callback.call(socket); // Ensure correct 'this' binding
|
||||
});
|
||||
|
||||
return socket;
|
||||
}),
|
||||
monitor = {
|
||||
url: "https://www.google.com",
|
||||
};
|
||||
sslChecker = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
tls = { ...originalTls };
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should resolve with the certificate when the connection is successful", async () => {
|
||||
const certificate = await fetchMonitorCertificate(tls, monitor);
|
||||
expect(certificate.validTo).to.equal("Dec 31 23:59:59 2023 GMT");
|
||||
expect(socket.end.calledOnce).to.be.true;
|
||||
});
|
||||
|
||||
it("should reject with an error when the connection fails", async () => {
|
||||
tls.connect = sinon.stub().throws(new Error("Connection error"));
|
||||
it("should reject with an error if a URL does not parse", async () => {
|
||||
monitor.url = "invalidurl";
|
||||
try {
|
||||
await fetchMonitorCertificate(tls, monitor);
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("Connection error");
|
||||
}
|
||||
});
|
||||
|
||||
it("should reject with an error if monitorURL is invalid", async () => {
|
||||
monitor.url = "invalid-url";
|
||||
try {
|
||||
await fetchMonitorCertificate(tls, monitor);
|
||||
await fetchMonitorCertificate(sslChecker, monitor);
|
||||
} catch (error) {
|
||||
expect(error).to.be.an("error");
|
||||
expect(error.message).to.equal("Invalid URL");
|
||||
}
|
||||
});
|
||||
it("should do a thing", async () => {
|
||||
tls = {
|
||||
connect: sinon.stub().callsFake((options, callback) => {
|
||||
// Create socket stub with sinon stubs for all methods
|
||||
socket = {
|
||||
getPeerX509Certificate: sinon.stub().throws(new Error("Certificate error")),
|
||||
end: sinon.stub(),
|
||||
on: sinon.stub(),
|
||||
};
|
||||
|
||||
// Use process.nextTick to ensure async behavior
|
||||
process.nextTick(() => {
|
||||
callback.call(socket); // Ensure correct 'this' binding
|
||||
});
|
||||
|
||||
return socket;
|
||||
}),
|
||||
};
|
||||
it("should reject with an error if sslChecker throws an error", async () => {
|
||||
sslChecker.rejects(new Error("Test error"));
|
||||
try {
|
||||
await fetchMonitorCertificate(tls, monitor);
|
||||
await fetchMonitorCertificate(sslChecker, monitor);
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("Certificate error");
|
||||
expect(error).to.be.an("error");
|
||||
expect(error.message).to.equal("Test error");
|
||||
}
|
||||
});
|
||||
it("should return a certificate if sslChecker resolves", async () => {
|
||||
sslChecker.resolves({ validTo: "2022-01-01" });
|
||||
const result = await fetchMonitorCertificate(sslChecker, monitor);
|
||||
expect(result).to.deep.equal({ validTo: "2022-01-01" });
|
||||
});
|
||||
});
|
||||
@@ -1,203 +1,203 @@
|
||||
import {
|
||||
issueInvitation,
|
||||
inviteVerifyController,
|
||||
issueInvitation,
|
||||
inviteVerifyController,
|
||||
} from "../../controllers/inviteController.js";
|
||||
import jwt from "jsonwebtoken";
|
||||
import sinon from "sinon";
|
||||
import joi from "joi";
|
||||
describe("inviteController - issueInvitation", () => {
|
||||
let req, res, next, stub;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: { authorization: "Bearer token" },
|
||||
body: {
|
||||
email: "test@test.com",
|
||||
role: ["admin"],
|
||||
teamId: "123",
|
||||
},
|
||||
db: { requestInviteToken: sinon.stub() },
|
||||
settingsService: { getSettings: sinon.stub() },
|
||||
emailService: { buildAndSendEmail: sinon.stub() },
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
let req, res, next, stub;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: { authorization: "Bearer token" },
|
||||
body: {
|
||||
email: "test@test.com",
|
||||
role: ["admin"],
|
||||
teamId: "123",
|
||||
},
|
||||
db: { requestInviteToken: sinon.stub() },
|
||||
settingsService: { getSettings: sinon.stub() },
|
||||
emailService: { buildAndSendEmail: sinon.stub() },
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should reject with an error if role validation fails", async () => {
|
||||
stub = sinon.stub(jwt, "decode").callsFake(() => {
|
||||
return { role: ["bad_role"], firstname: "first_name", teamId: "1" };
|
||||
});
|
||||
await issueInvitation(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0]).to.be.instanceOf(joi.ValidationError);
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
stub.restore();
|
||||
});
|
||||
it("should reject with an error if role validation fails", async () => {
|
||||
stub = sinon.stub(jwt, "decode").callsFake(() => {
|
||||
return { role: ["bad_role"], firstname: "first_name", teamId: "1" };
|
||||
});
|
||||
await issueInvitation(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0]).to.be.instanceOf(joi.ValidationError);
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
stub.restore();
|
||||
});
|
||||
|
||||
it("should reject with an error if body validation fails", async () => {
|
||||
stub = sinon.stub(jwt, "decode").callsFake(() => {
|
||||
return { role: ["admin"], firstname: "first_name", teamId: "1" };
|
||||
});
|
||||
req.body = {};
|
||||
await issueInvitation(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
stub.restore();
|
||||
});
|
||||
it("should reject with an error if body validation fails", async () => {
|
||||
stub = sinon.stub(jwt, "decode").callsFake(() => {
|
||||
return { role: ["admin"], firstname: "first_name", teamId: "1" };
|
||||
});
|
||||
req.body = {};
|
||||
await issueInvitation(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
stub.restore();
|
||||
});
|
||||
|
||||
it("should reject with an error if DB operations fail", async () => {
|
||||
stub = sinon.stub(jwt, "decode").callsFake(() => {
|
||||
return { role: ["admin"], firstname: "first_name", teamId: "1" };
|
||||
});
|
||||
req.db.requestInviteToken.throws(new Error("DB error"));
|
||||
await issueInvitation(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
stub.restore();
|
||||
});
|
||||
it("should reject with an error if DB operations fail", async () => {
|
||||
stub = sinon.stub(jwt, "decode").callsFake(() => {
|
||||
return { role: ["admin"], firstname: "first_name", teamId: "1" };
|
||||
});
|
||||
req.db.requestInviteToken.throws(new Error("DB error"));
|
||||
await issueInvitation(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
stub.restore();
|
||||
});
|
||||
|
||||
it("should send an invite successfully", async () => {
|
||||
const token = "token";
|
||||
const decodedToken = {
|
||||
role: "admin",
|
||||
firstname: "John",
|
||||
teamId: "team123",
|
||||
};
|
||||
const inviteToken = { token: "inviteToken" };
|
||||
const clientHost = "http://localhost";
|
||||
it("should send an invite successfully", async () => {
|
||||
const token = "token";
|
||||
const decodedToken = {
|
||||
role: "admin",
|
||||
firstname: "John",
|
||||
teamId: "team123",
|
||||
};
|
||||
const inviteToken = { token: "inviteToken" };
|
||||
const clientHost = "http://localhost";
|
||||
|
||||
stub = sinon.stub(jwt, "decode").callsFake(() => {
|
||||
return decodedToken;
|
||||
});
|
||||
req.db.requestInviteToken.resolves(inviteToken);
|
||||
req.settingsService.getSettings.returns({ clientHost });
|
||||
req.emailService.buildAndSendEmail.resolves();
|
||||
await issueInvitation(req, res, next);
|
||||
expect(res.status.calledWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledWith({
|
||||
success: true,
|
||||
msg: "Invite sent",
|
||||
data: inviteToken,
|
||||
})
|
||||
).to.be.true;
|
||||
stub.restore();
|
||||
});
|
||||
stub = sinon.stub(jwt, "decode").callsFake(() => {
|
||||
return decodedToken;
|
||||
});
|
||||
req.db.requestInviteToken.resolves(inviteToken);
|
||||
req.settingsService.getSettings.returns({ clientHost });
|
||||
req.emailService.buildAndSendEmail.resolves();
|
||||
await issueInvitation(req, res, next);
|
||||
expect(res.status.calledWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledWith({
|
||||
success: true,
|
||||
msg: "Invite sent",
|
||||
data: inviteToken,
|
||||
})
|
||||
).to.be.true;
|
||||
stub.restore();
|
||||
});
|
||||
|
||||
it("should send an email successfully", async () => {
|
||||
const token = "token";
|
||||
const decodedToken = {
|
||||
role: "admin",
|
||||
firstname: "John",
|
||||
teamId: "team123",
|
||||
};
|
||||
const inviteToken = { token: "inviteToken" };
|
||||
const clientHost = "http://localhost";
|
||||
it("should send an email successfully", async () => {
|
||||
const token = "token";
|
||||
const decodedToken = {
|
||||
role: "admin",
|
||||
firstname: "John",
|
||||
teamId: "team123",
|
||||
};
|
||||
const inviteToken = { token: "inviteToken" };
|
||||
const clientHost = "http://localhost";
|
||||
|
||||
stub = sinon.stub(jwt, "decode").callsFake(() => {
|
||||
return decodedToken;
|
||||
});
|
||||
req.db.requestInviteToken.resolves(inviteToken);
|
||||
req.settingsService.getSettings.returns({ clientHost });
|
||||
req.emailService.buildAndSendEmail.resolves();
|
||||
stub = sinon.stub(jwt, "decode").callsFake(() => {
|
||||
return decodedToken;
|
||||
});
|
||||
req.db.requestInviteToken.resolves(inviteToken);
|
||||
req.settingsService.getSettings.returns({ clientHost });
|
||||
req.emailService.buildAndSendEmail.resolves();
|
||||
|
||||
await issueInvitation(req, res, next);
|
||||
expect(req.emailService.buildAndSendEmail.calledOnce).to.be.true;
|
||||
expect(
|
||||
req.emailService.buildAndSendEmail.calledWith(
|
||||
"employeeActivationTemplate",
|
||||
{
|
||||
name: "John",
|
||||
link: "http://localhost/register/inviteToken",
|
||||
},
|
||||
"test@test.com",
|
||||
"Welcome to Uptime Monitor"
|
||||
)
|
||||
).to.be.true;
|
||||
stub.restore();
|
||||
});
|
||||
await issueInvitation(req, res, next);
|
||||
expect(req.emailService.buildAndSendEmail.calledOnce).to.be.true;
|
||||
expect(
|
||||
req.emailService.buildAndSendEmail.calledWith(
|
||||
"employeeActivationTemplate",
|
||||
{
|
||||
name: "John",
|
||||
link: "http://localhost/register/inviteToken",
|
||||
},
|
||||
"test@test.com",
|
||||
"Welcome to Uptime Monitor"
|
||||
)
|
||||
).to.be.true;
|
||||
stub.restore();
|
||||
});
|
||||
|
||||
it("should continue executing if sending an email fails", async () => {
|
||||
const token = "token";
|
||||
req.emailService.buildAndSendEmail.rejects(new Error("Email error"));
|
||||
const decodedToken = {
|
||||
role: "admin",
|
||||
firstname: "John",
|
||||
teamId: "team123",
|
||||
};
|
||||
const inviteToken = { token: "inviteToken" };
|
||||
const clientHost = "http://localhost";
|
||||
it("should continue executing if sending an email fails", async () => {
|
||||
const token = "token";
|
||||
req.emailService.buildAndSendEmail.rejects(new Error("Email error"));
|
||||
const decodedToken = {
|
||||
role: "admin",
|
||||
firstname: "John",
|
||||
teamId: "team123",
|
||||
};
|
||||
const inviteToken = { token: "inviteToken" };
|
||||
const clientHost = "http://localhost";
|
||||
|
||||
stub = sinon.stub(jwt, "decode").callsFake(() => {
|
||||
return decodedToken;
|
||||
});
|
||||
req.db.requestInviteToken.resolves(inviteToken);
|
||||
req.settingsService.getSettings.returns({ clientHost });
|
||||
await issueInvitation(req, res, next);
|
||||
expect(res.status.calledWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledWith({
|
||||
success: true,
|
||||
msg: "Invite sent",
|
||||
data: inviteToken,
|
||||
})
|
||||
).to.be.true;
|
||||
stub.restore();
|
||||
});
|
||||
stub = sinon.stub(jwt, "decode").callsFake(() => {
|
||||
return decodedToken;
|
||||
});
|
||||
req.db.requestInviteToken.resolves(inviteToken);
|
||||
req.settingsService.getSettings.returns({ clientHost });
|
||||
await issueInvitation(req, res, next);
|
||||
expect(res.status.calledWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledWith({
|
||||
success: true,
|
||||
msg: "Invite sent",
|
||||
data: inviteToken,
|
||||
})
|
||||
).to.be.true;
|
||||
stub.restore();
|
||||
});
|
||||
});
|
||||
|
||||
describe("inviteController - inviteVerifyController", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: { token: "token" },
|
||||
db: {
|
||||
getInviteToken: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: { token: "token" },
|
||||
db: {
|
||||
getInviteToken: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should reject with an error if body validation fails", async () => {
|
||||
req.body = {};
|
||||
await inviteVerifyController(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject with an error if body validation fails", async () => {
|
||||
req.body = {};
|
||||
await inviteVerifyController(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should reject with an error if DB operations fail", async () => {
|
||||
req.db.getInviteToken.throws(new Error("DB error"));
|
||||
await inviteVerifyController(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
});
|
||||
it("should reject with an error if DB operations fail", async () => {
|
||||
req.db.getInviteToken.throws(new Error("DB error"));
|
||||
await inviteVerifyController(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
});
|
||||
|
||||
it("should return 200 and invite data when validation and invite retrieval are successful", async () => {
|
||||
req.db.getInviteToken.resolves({ invite: "data" });
|
||||
await inviteVerifyController(req, res, next);
|
||||
expect(res.status.calledWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledWith({
|
||||
status: "success",
|
||||
msg: "Invite verified",
|
||||
data: { invite: "data" },
|
||||
})
|
||||
).to.be.true;
|
||||
expect(next.called).to.be.false;
|
||||
});
|
||||
it("should return 200 and invite data when validation and invite retrieval are successful", async () => {
|
||||
req.db.getInviteToken.resolves({ invite: "data" });
|
||||
await inviteVerifyController(req, res, next);
|
||||
expect(res.status.calledWith(200)).to.be.true;
|
||||
expect(
|
||||
res.json.calledWith({
|
||||
status: "success",
|
||||
msg: "Invite verified",
|
||||
data: { invite: "data" },
|
||||
})
|
||||
).to.be.true;
|
||||
expect(next.called).to.be.false;
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,10 @@
|
||||
import {
|
||||
createMaintenanceWindows,
|
||||
getMaintenanceWindowById,
|
||||
getMaintenanceWindowsByTeamId,
|
||||
getMaintenanceWindowsByMonitorId,
|
||||
deleteMaintenanceWindow,
|
||||
editMaintenanceWindow,
|
||||
createMaintenanceWindows,
|
||||
getMaintenanceWindowById,
|
||||
getMaintenanceWindowsByTeamId,
|
||||
getMaintenanceWindowsByMonitorId,
|
||||
deleteMaintenanceWindow,
|
||||
editMaintenanceWindow,
|
||||
} from "../../controllers/maintenanceWindowController.js";
|
||||
|
||||
import jwt from "jsonwebtoken";
|
||||
@@ -12,405 +12,399 @@ import { successMessages } from "../../utils/messages.js";
|
||||
import sinon from "sinon";
|
||||
|
||||
describe("maintenanceWindowController - createMaintenanceWindows", () => {
|
||||
let req, res, next, stub;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: {
|
||||
monitors: ["66ff52e7c5911c61698ac724"],
|
||||
name: "window",
|
||||
active: true,
|
||||
start: "2024-10-11T05:27:13.747Z",
|
||||
end: "2024-10-11T05:27:14.747Z",
|
||||
repeat: "123",
|
||||
},
|
||||
headers: {
|
||||
authorization: "Bearer token",
|
||||
},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
|
||||
},
|
||||
db: {
|
||||
createMaintenanceWindow: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
let req, res, next, stub;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: {
|
||||
monitors: ["66ff52e7c5911c61698ac724"],
|
||||
name: "window",
|
||||
active: true,
|
||||
start: "2024-10-11T05:27:13.747Z",
|
||||
end: "2024-10-11T05:27:14.747Z",
|
||||
repeat: "123",
|
||||
},
|
||||
headers: {
|
||||
authorization: "Bearer token",
|
||||
},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
|
||||
},
|
||||
db: {
|
||||
createMaintenanceWindow: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should reject with an error if body validation fails", async () => {
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
req.body = {};
|
||||
await createMaintenanceWindows(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
stub.restore();
|
||||
});
|
||||
it("should reject with an error if body validation fails", async () => {
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
req.body = {};
|
||||
await createMaintenanceWindows(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
stub.restore();
|
||||
});
|
||||
|
||||
it("should reject with an error if jwt.verify fails", async () => {
|
||||
stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError());
|
||||
await createMaintenanceWindows(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
|
||||
stub.restore();
|
||||
});
|
||||
it("should reject with an error if jwt.verify fails", async () => {
|
||||
stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError());
|
||||
await createMaintenanceWindows(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
|
||||
stub.restore();
|
||||
});
|
||||
|
||||
it("should reject with an error DB operations fail", async () => {
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
req.db.createMaintenanceWindow.throws(new Error("DB error"));
|
||||
await createMaintenanceWindows(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
stub.restore();
|
||||
});
|
||||
it("should return success message if all operations are successful", async () => {
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
await createMaintenanceWindows(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(201);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_CREATE,
|
||||
})
|
||||
).to.be.true;
|
||||
stub.restore();
|
||||
});
|
||||
it("should return success message if all operations are successful with active set to undefined", async () => {
|
||||
req.body.active = undefined;
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
await createMaintenanceWindows(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(201);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_CREATE,
|
||||
})
|
||||
).to.be.true;
|
||||
stub.restore();
|
||||
});
|
||||
it("should reject with an error DB operations fail", async () => {
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
req.db.createMaintenanceWindow.throws(new Error("DB error"));
|
||||
await createMaintenanceWindows(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
stub.restore();
|
||||
});
|
||||
it("should return success message if all operations are successful", async () => {
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
await createMaintenanceWindows(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(201);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_CREATE,
|
||||
})
|
||||
).to.be.true;
|
||||
stub.restore();
|
||||
});
|
||||
it("should return success message if all operations are successful with active set to undefined", async () => {
|
||||
req.body.active = undefined;
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
await createMaintenanceWindows(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(201);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_CREATE,
|
||||
})
|
||||
).to.be.true;
|
||||
stub.restore();
|
||||
});
|
||||
});
|
||||
|
||||
describe("maintenanceWindowController - getMaintenanceWindowById", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: {},
|
||||
params: {
|
||||
id: "123",
|
||||
},
|
||||
headers: {
|
||||
authorization: "Bearer token",
|
||||
},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
|
||||
},
|
||||
db: {
|
||||
getMaintenanceWindowById: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: {},
|
||||
params: {
|
||||
id: "123",
|
||||
},
|
||||
headers: {
|
||||
authorization: "Bearer token",
|
||||
},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
|
||||
},
|
||||
db: {
|
||||
getMaintenanceWindowById: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
|
||||
it("should reject if param validation fails", async () => {
|
||||
req.params = {};
|
||||
await getMaintenanceWindowById(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject if param validation fails", async () => {
|
||||
req.params = {};
|
||||
await getMaintenanceWindowById(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should reject if DB operations fail", async () => {
|
||||
req.db.getMaintenanceWindowById.throws(new Error("DB error"));
|
||||
await getMaintenanceWindowById(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
});
|
||||
it("should return success message with data if all operations are successful", async () => {
|
||||
req.db.getMaintenanceWindowById.returns({ id: "123" });
|
||||
await getMaintenanceWindowById(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID,
|
||||
data: { id: "123" },
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
it("should reject if DB operations fail", async () => {
|
||||
req.db.getMaintenanceWindowById.throws(new Error("DB error"));
|
||||
await getMaintenanceWindowById(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
});
|
||||
it("should return success message with data if all operations are successful", async () => {
|
||||
req.db.getMaintenanceWindowById.returns({ id: "123" });
|
||||
await getMaintenanceWindowById(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID,
|
||||
data: { id: "123" },
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", () => {
|
||||
let req, res, next, stub;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: {},
|
||||
params: {},
|
||||
query: {},
|
||||
headers: {
|
||||
authorization: "Bearer token",
|
||||
},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
|
||||
},
|
||||
db: {
|
||||
getMaintenanceWindowsByTeamId: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
it("should reject if query validation fails", async () => {
|
||||
req.query = {
|
||||
invalid: 1,
|
||||
};
|
||||
await getMaintenanceWindowsByTeamId(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject if jwt.verify fails", async () => {
|
||||
stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError());
|
||||
await getMaintenanceWindowsByTeamId(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
|
||||
stub.restore();
|
||||
});
|
||||
let req, res, next, stub;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: {},
|
||||
params: {},
|
||||
query: {},
|
||||
headers: {
|
||||
authorization: "Bearer token",
|
||||
},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
|
||||
},
|
||||
db: {
|
||||
getMaintenanceWindowsByTeamId: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
it("should reject if query validation fails", async () => {
|
||||
req.query = {
|
||||
invalid: 1,
|
||||
};
|
||||
await getMaintenanceWindowsByTeamId(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject if jwt.verify fails", async () => {
|
||||
stub = sinon.stub(jwt, "verify").throws(new jwt.JsonWebTokenError());
|
||||
await getMaintenanceWindowsByTeamId(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.instanceOf(jwt.JsonWebTokenError);
|
||||
stub.restore();
|
||||
});
|
||||
|
||||
it("should reject with an error if DB operations fail", async () => {
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
req.db.getMaintenanceWindowsByTeamId.throws(new Error("DB error"));
|
||||
await getMaintenanceWindowsByTeamId(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
stub.restore();
|
||||
});
|
||||
it("should reject with an error if DB operations fail", async () => {
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
req.db.getMaintenanceWindowsByTeamId.throws(new Error("DB error"));
|
||||
await getMaintenanceWindowsByTeamId(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
stub.restore();
|
||||
});
|
||||
|
||||
it("should return success message with data if all operations are successful", async () => {
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
req.db.getMaintenanceWindowsByTeamId.returns([{ id: "123" }]);
|
||||
await getMaintenanceWindowsByTeamId(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM,
|
||||
data: [{ id: jwt.verify().teamId }],
|
||||
})
|
||||
).to.be.true;
|
||||
stub.restore();
|
||||
});
|
||||
it("should return success message with data if all operations are successful", async () => {
|
||||
stub = sinon.stub(jwt, "verify").callsFake(() => {
|
||||
return { teamId: "123" };
|
||||
});
|
||||
req.db.getMaintenanceWindowsByTeamId.returns([{ id: "123" }]);
|
||||
await getMaintenanceWindowsByTeamId(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM,
|
||||
data: [{ id: jwt.verify().teamId }],
|
||||
})
|
||||
).to.be.true;
|
||||
stub.restore();
|
||||
});
|
||||
});
|
||||
|
||||
describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: {},
|
||||
params: {
|
||||
monitorId: "123",
|
||||
},
|
||||
query: {},
|
||||
headers: {
|
||||
authorization: "Bearer token",
|
||||
},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
|
||||
},
|
||||
db: {
|
||||
getMaintenanceWindowsByMonitorId: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: {},
|
||||
params: {
|
||||
monitorId: "123",
|
||||
},
|
||||
query: {},
|
||||
headers: {
|
||||
authorization: "Bearer token",
|
||||
},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
|
||||
},
|
||||
db: {
|
||||
getMaintenanceWindowsByMonitorId: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should reject if param validation fails", async () => {
|
||||
req.params = {};
|
||||
await getMaintenanceWindowsByMonitorId(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject if param validation fails", async () => {
|
||||
req.params = {};
|
||||
await getMaintenanceWindowsByMonitorId(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should reject with an error if DB operations fail", async () => {
|
||||
req.db.getMaintenanceWindowsByMonitorId.throws(new Error("DB error"));
|
||||
await getMaintenanceWindowsByMonitorId(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
});
|
||||
it("should reject with an error if DB operations fail", async () => {
|
||||
req.db.getMaintenanceWindowsByMonitorId.throws(new Error("DB error"));
|
||||
await getMaintenanceWindowsByMonitorId(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
});
|
||||
|
||||
it("should return success message with data if all operations are successful", async () => {
|
||||
const data = [{ monitorId: "123" }];
|
||||
req.db.getMaintenanceWindowsByMonitorId.returns(data);
|
||||
await getMaintenanceWindowsByMonitorId(req, res, next);
|
||||
expect(
|
||||
req.db.getMaintenanceWindowsByMonitorId.calledOnceWith(
|
||||
req.params.monitorId
|
||||
)
|
||||
);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_MONITOR,
|
||||
data: data,
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
it("should return success message with data if all operations are successful", async () => {
|
||||
const data = [{ monitorId: "123" }];
|
||||
req.db.getMaintenanceWindowsByMonitorId.returns(data);
|
||||
await getMaintenanceWindowsByMonitorId(req, res, next);
|
||||
expect(req.db.getMaintenanceWindowsByMonitorId.calledOnceWith(req.params.monitorId));
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_MONITOR,
|
||||
data: data,
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("maintenanceWindowController - deleteMaintenanceWindow", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: {},
|
||||
params: {
|
||||
id: "123",
|
||||
},
|
||||
query: {},
|
||||
headers: {
|
||||
authorization: "Bearer token",
|
||||
},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
|
||||
},
|
||||
db: {
|
||||
deleteMaintenanceWindowById: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: {},
|
||||
params: {
|
||||
id: "123",
|
||||
},
|
||||
query: {},
|
||||
headers: {
|
||||
authorization: "Bearer token",
|
||||
},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
|
||||
},
|
||||
db: {
|
||||
deleteMaintenanceWindowById: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should reject if param validation fails", async () => {
|
||||
req.params = {};
|
||||
await deleteMaintenanceWindow(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject if param validation fails", async () => {
|
||||
req.params = {};
|
||||
await deleteMaintenanceWindow(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should reject with an error if DB operations fail", async () => {
|
||||
req.db.deleteMaintenanceWindowById.throws(new Error("DB error"));
|
||||
await deleteMaintenanceWindow(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
});
|
||||
it("should reject with an error if DB operations fail", async () => {
|
||||
req.db.deleteMaintenanceWindowById.throws(new Error("DB error"));
|
||||
await deleteMaintenanceWindow(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
});
|
||||
|
||||
it("should return success message if all operations are successful", async () => {
|
||||
await deleteMaintenanceWindow(req, res, next);
|
||||
expect(req.db.deleteMaintenanceWindowById.calledOnceWith(req.params.id));
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_DELETE,
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
it("should return success message if all operations are successful", async () => {
|
||||
await deleteMaintenanceWindow(req, res, next);
|
||||
expect(req.db.deleteMaintenanceWindowById.calledOnceWith(req.params.id));
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_DELETE,
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("maintenanceWindowController - editMaintenanceWindow", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: {
|
||||
active: true,
|
||||
name: "test",
|
||||
},
|
||||
params: {
|
||||
id: "123",
|
||||
},
|
||||
query: {},
|
||||
headers: {
|
||||
authorization: "Bearer token",
|
||||
},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
|
||||
},
|
||||
db: {
|
||||
editMaintenanceWindowById: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
body: {
|
||||
active: true,
|
||||
name: "test",
|
||||
},
|
||||
params: {
|
||||
id: "123",
|
||||
},
|
||||
query: {},
|
||||
headers: {
|
||||
authorization: "Bearer token",
|
||||
},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub().returns({ jwtSecret: "jwtSecret" }),
|
||||
},
|
||||
db: {
|
||||
editMaintenanceWindowById: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should reject if param validation fails", async () => {
|
||||
req.params = {};
|
||||
await editMaintenanceWindow(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject if param validation fails", async () => {
|
||||
req.params = {};
|
||||
await editMaintenanceWindow(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should reject if body validation fails", async () => {
|
||||
req.body = { invalid: 1 };
|
||||
await editMaintenanceWindow(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject if body validation fails", async () => {
|
||||
req.body = { invalid: 1 };
|
||||
await editMaintenanceWindow(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
|
||||
it("should reject with an error if DB operations fail", async () => {
|
||||
req.db.editMaintenanceWindowById.throws(new Error("DB error"));
|
||||
await editMaintenanceWindow(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
});
|
||||
it("should reject with an error if DB operations fail", async () => {
|
||||
req.db.editMaintenanceWindowById.throws(new Error("DB error"));
|
||||
await editMaintenanceWindow(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("DB error");
|
||||
});
|
||||
|
||||
it("should return success message with data if all operations are successful", async () => {
|
||||
const data = { id: "123" };
|
||||
req.db.editMaintenanceWindowById.returns(data);
|
||||
it("should return success message with data if all operations are successful", async () => {
|
||||
const data = { id: "123" };
|
||||
req.db.editMaintenanceWindowById.returns(data);
|
||||
|
||||
await editMaintenanceWindow(req, res, next);
|
||||
expect(
|
||||
req.db.editMaintenanceWindowById.calledOnceWith(req.params.id, req.body)
|
||||
);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_EDIT,
|
||||
data: data,
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
await editMaintenanceWindow(req, res, next);
|
||||
expect(req.db.editMaintenanceWindowById.calledOnceWith(req.params.id, req.body));
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(
|
||||
res.json.calledOnceWith({
|
||||
success: true,
|
||||
msg: successMessages.MAINTENANCE_WINDOW_EDIT,
|
||||
data: data,
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
getMonitorsAndSummaryByTeamId,
|
||||
getMonitorsByTeamId,
|
||||
createMonitor,
|
||||
checkEndpointResolution,
|
||||
deleteMonitor,
|
||||
deleteAllMonitors,
|
||||
editMonitor,
|
||||
@@ -16,9 +17,7 @@ import jwt from "jsonwebtoken";
|
||||
import sinon from "sinon";
|
||||
import { successMessages } from "../../utils/messages.js";
|
||||
import logger from "../../utils/logger.js";
|
||||
import * as monitorController from "../../controllers/monitorController.js";
|
||||
import { fetchMonitorCertificate } from "../../controllers/controllerUtils.js";
|
||||
|
||||
import dns from "dns";
|
||||
const SERVICE_NAME = "monitorController";
|
||||
|
||||
describe("Monitor Controller - getAllMonitors", () => {
|
||||
@@ -460,6 +459,50 @@ describe("Monitor Controller - createMonitor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Monitor Controllor - checkEndpointResolution", () => {
|
||||
let req, res, next, dnsResolveStub;
|
||||
beforeEach(() => {
|
||||
req = { query: { monitorURL: 'https://example.com' } };
|
||||
res = { status: sinon.stub().returnsThis(), json: sinon.stub() };
|
||||
next = sinon.stub();
|
||||
dnsResolveStub = sinon.stub(dns, 'resolve');
|
||||
});
|
||||
afterEach(() => {
|
||||
dnsResolveStub.restore();
|
||||
});
|
||||
it('should resolve the URL successfully', async () => {
|
||||
dnsResolveStub.callsFake((hostname, callback) => callback(null));
|
||||
await checkEndpointResolution(req, res, next);
|
||||
expect(res.status.calledWith(200)).to.be.true;
|
||||
expect(res.json.calledWith({
|
||||
success: true,
|
||||
msg: 'URL resolved successfully',
|
||||
})).to.be.true;
|
||||
expect(next.called).to.be.false;
|
||||
});
|
||||
it("should return an error if DNS resolution fails", async () => {
|
||||
const dnsError = new Error("DNS resolution failed");
|
||||
dnsError.code = 'ENOTFOUND';
|
||||
dnsResolveStub.callsFake((hostname, callback) => callback(dnsError));
|
||||
await checkEndpointResolution(req, res, next);
|
||||
expect(next.calledOnce).to.be.true;
|
||||
const errorPassedToNext = next.getCall(0).args[0];
|
||||
expect(errorPassedToNext).to.be.an.instanceOf(Error);
|
||||
expect(errorPassedToNext.message).to.include('DNS resolution failed');
|
||||
expect(errorPassedToNext.code).to.equal('ENOTFOUND');
|
||||
expect(errorPassedToNext.status).to.equal(500);
|
||||
});
|
||||
it('should reject with an error if query validation fails', async () => {
|
||||
req.query.monitorURL = 'invalid-url';
|
||||
await checkEndpointResolution(req, res, next);
|
||||
expect(next.calledOnce).to.be.true;
|
||||
const error = next.getCall(0).args[0];
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
expect(error.message).to.equal('"monitorURL" must be a valid uri');
|
||||
});
|
||||
});
|
||||
|
||||
describe("Monitor Controller - deleteMonitor", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -1,166 +1,166 @@
|
||||
import { afterEach } from "node:test";
|
||||
import {
|
||||
getMetrics,
|
||||
getJobs,
|
||||
addJob,
|
||||
obliterateQueue,
|
||||
getMetrics,
|
||||
getJobs,
|
||||
addJob,
|
||||
obliterateQueue,
|
||||
} from "../../controllers/queueController.js";
|
||||
import { successMessages } from "../../utils/messages.js";
|
||||
import sinon from "sinon";
|
||||
|
||||
describe("Queue Controller - getMetrics", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: {},
|
||||
params: {},
|
||||
body: {},
|
||||
db: {},
|
||||
jobQueue: {
|
||||
getMetrics: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
it("should throw an error if getMetrics throws an error", async () => {
|
||||
req.jobQueue.getMetrics.throws(new Error("getMetrics error"));
|
||||
await getMetrics(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("getMetrics error");
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: {},
|
||||
params: {},
|
||||
body: {},
|
||||
db: {},
|
||||
jobQueue: {
|
||||
getMetrics: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
it("should throw an error if getMetrics throws an error", async () => {
|
||||
req.jobQueue.getMetrics.throws(new Error("getMetrics error"));
|
||||
await getMetrics(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("getMetrics error");
|
||||
});
|
||||
|
||||
it("should return a success message and data if getMetrics is successful", async () => {
|
||||
const data = { data: "metrics" };
|
||||
req.jobQueue.getMetrics.returns(data);
|
||||
await getMetrics(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({
|
||||
success: true,
|
||||
msg: successMessages.QUEUE_GET_METRICS,
|
||||
data,
|
||||
});
|
||||
});
|
||||
it("should return a success message and data if getMetrics is successful", async () => {
|
||||
const data = { data: "metrics" };
|
||||
req.jobQueue.getMetrics.returns(data);
|
||||
await getMetrics(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({
|
||||
success: true,
|
||||
msg: successMessages.QUEUE_GET_METRICS,
|
||||
data,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Queue Controller - getJobs", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: {},
|
||||
params: {},
|
||||
body: {},
|
||||
db: {},
|
||||
jobQueue: {
|
||||
getJobStats: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
it("should reject with an error if getJobs throws an error", async () => {
|
||||
req.jobQueue.getJobStats.throws(new Error("getJobs error"));
|
||||
await getJobs(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("getJobs error");
|
||||
});
|
||||
it("should return a success message and data if getJobs is successful", async () => {
|
||||
const data = { data: "jobs" };
|
||||
req.jobQueue.getJobStats.returns(data);
|
||||
await getJobs(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({
|
||||
success: true,
|
||||
msg: successMessages.QUEUE_GET_METRICS,
|
||||
data,
|
||||
});
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: {},
|
||||
params: {},
|
||||
body: {},
|
||||
db: {},
|
||||
jobQueue: {
|
||||
getJobStats: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
it("should reject with an error if getJobs throws an error", async () => {
|
||||
req.jobQueue.getJobStats.throws(new Error("getJobs error"));
|
||||
await getJobs(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("getJobs error");
|
||||
});
|
||||
it("should return a success message and data if getJobs is successful", async () => {
|
||||
const data = { data: "jobs" };
|
||||
req.jobQueue.getJobStats.returns(data);
|
||||
await getJobs(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({
|
||||
success: true,
|
||||
msg: successMessages.QUEUE_GET_METRICS,
|
||||
data,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Queue Controller - addJob", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: {},
|
||||
params: {},
|
||||
body: {},
|
||||
db: {},
|
||||
jobQueue: {
|
||||
addJob: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
it("should reject with an error if addJob throws an error", async () => {
|
||||
req.jobQueue.addJob.throws(new Error("addJob error"));
|
||||
await addJob(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("addJob error");
|
||||
});
|
||||
it("should return a success message if addJob is successful", async () => {
|
||||
req.jobQueue.addJob.resolves();
|
||||
await addJob(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({
|
||||
success: true,
|
||||
msg: successMessages.QUEUE_ADD_JOB,
|
||||
});
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: {},
|
||||
params: {},
|
||||
body: {},
|
||||
db: {},
|
||||
jobQueue: {
|
||||
addJob: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
it("should reject with an error if addJob throws an error", async () => {
|
||||
req.jobQueue.addJob.throws(new Error("addJob error"));
|
||||
await addJob(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("addJob error");
|
||||
});
|
||||
it("should return a success message if addJob is successful", async () => {
|
||||
req.jobQueue.addJob.resolves();
|
||||
await addJob(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({
|
||||
success: true,
|
||||
msg: successMessages.QUEUE_ADD_JOB,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Queue Controller - obliterateQueue", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: {},
|
||||
params: {},
|
||||
body: {},
|
||||
db: {},
|
||||
jobQueue: {
|
||||
obliterate: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
it("should reject with an error if obliterateQueue throws an error", async () => {
|
||||
req.jobQueue.obliterate.throws(new Error("obliterateQueue error"));
|
||||
await obliterateQueue(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("obliterateQueue error");
|
||||
});
|
||||
it("should return a success message if obliterateQueue is successful", async () => {
|
||||
req.jobQueue.obliterate.resolves();
|
||||
await obliterateQueue(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({
|
||||
success: true,
|
||||
msg: successMessages.QUEUE_OBLITERATE,
|
||||
});
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: {},
|
||||
params: {},
|
||||
body: {},
|
||||
db: {},
|
||||
jobQueue: {
|
||||
obliterate: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
it("should reject with an error if obliterateQueue throws an error", async () => {
|
||||
req.jobQueue.obliterate.throws(new Error("obliterateQueue error"));
|
||||
await obliterateQueue(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("obliterateQueue error");
|
||||
});
|
||||
it("should return a success message if obliterateQueue is successful", async () => {
|
||||
req.jobQueue.obliterate.resolves();
|
||||
await obliterateQueue(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({
|
||||
success: true,
|
||||
msg: successMessages.QUEUE_OBLITERATE,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,105 +1,103 @@
|
||||
import { afterEach } from "node:test";
|
||||
import {
|
||||
getAppSettings,
|
||||
updateAppSettings,
|
||||
getAppSettings,
|
||||
updateAppSettings,
|
||||
} from "../../controllers/settingsController.js";
|
||||
|
||||
import { successMessages } from "../../utils/messages.js";
|
||||
import sinon from "sinon";
|
||||
|
||||
describe("Settings Controller - getAppSettings", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: {},
|
||||
params: {},
|
||||
body: {},
|
||||
db: {},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
it("should throw an error if getSettings throws an error", async () => {
|
||||
req.settingsService.getSettings.throws(new Error("getSettings error"));
|
||||
await getAppSettings(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("getSettings error");
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: {},
|
||||
params: {},
|
||||
body: {},
|
||||
db: {},
|
||||
settingsService: {
|
||||
getSettings: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
it("should throw an error if getSettings throws an error", async () => {
|
||||
req.settingsService.getSettings.throws(new Error("getSettings error"));
|
||||
await getAppSettings(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("getSettings error");
|
||||
});
|
||||
|
||||
it("should return a success message and data if getSettings is successful", async () => {
|
||||
const data = { data: "settings" };
|
||||
req.settingsService.getSettings.returns(data);
|
||||
await getAppSettings(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({
|
||||
success: true,
|
||||
msg: successMessages.GET_APP_SETTINGS,
|
||||
data,
|
||||
});
|
||||
});
|
||||
it("should return a success message and data if getSettings is successful", async () => {
|
||||
const data = { data: "settings" };
|
||||
req.settingsService.getSettings.returns(data);
|
||||
await getAppSettings(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({
|
||||
success: true,
|
||||
msg: successMessages.GET_APP_SETTINGS,
|
||||
data,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Settings Controller - updateAppSettings", () => {
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: {},
|
||||
params: {},
|
||||
body: {},
|
||||
db: {
|
||||
updateAppSettings: sinon.stub(),
|
||||
},
|
||||
settingsService: {
|
||||
reloadSettings: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
it("should reject with an error if body validation fails", async () => {
|
||||
req.body = { invalid: 1 };
|
||||
await updateAppSettings(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject with an error if updateAppSettings throws an error", async () => {
|
||||
req.db.updateAppSettings.throws(new Error("updateAppSettings error"));
|
||||
await updateAppSettings(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("updateAppSettings error");
|
||||
});
|
||||
it("should reject with an error if reloadSettings throws an error", async () => {
|
||||
req.settingsService.reloadSettings.throws(
|
||||
new Error("reloadSettings error")
|
||||
);
|
||||
await updateAppSettings(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("reloadSettings error");
|
||||
});
|
||||
it("should return a success message and data if updateAppSettings is successful", async () => {
|
||||
const data = { data: "settings" };
|
||||
req.settingsService.reloadSettings.returns(data);
|
||||
await updateAppSettings(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({
|
||||
success: true,
|
||||
msg: successMessages.UPDATE_APP_SETTINGS,
|
||||
data,
|
||||
});
|
||||
});
|
||||
let req, res, next;
|
||||
beforeEach(() => {
|
||||
req = {
|
||||
headers: {},
|
||||
params: {},
|
||||
body: {},
|
||||
db: {
|
||||
updateAppSettings: sinon.stub(),
|
||||
},
|
||||
settingsService: {
|
||||
reloadSettings: sinon.stub(),
|
||||
},
|
||||
};
|
||||
res = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
json: sinon.stub(),
|
||||
};
|
||||
next = sinon.stub();
|
||||
});
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
it("should reject with an error if body validation fails", async () => {
|
||||
req.body = { invalid: 1 };
|
||||
await updateAppSettings(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].status).to.equal(422);
|
||||
});
|
||||
it("should reject with an error if updateAppSettings throws an error", async () => {
|
||||
req.db.updateAppSettings.throws(new Error("updateAppSettings error"));
|
||||
await updateAppSettings(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("updateAppSettings error");
|
||||
});
|
||||
it("should reject with an error if reloadSettings throws an error", async () => {
|
||||
req.settingsService.reloadSettings.throws(new Error("reloadSettings error"));
|
||||
await updateAppSettings(req, res, next);
|
||||
expect(next.firstCall.args[0]).to.be.an("error");
|
||||
expect(next.firstCall.args[0].message).to.equal("reloadSettings error");
|
||||
});
|
||||
it("should return a success message and data if updateAppSettings is successful", async () => {
|
||||
const data = { data: "settings" };
|
||||
req.settingsService.reloadSettings.returns(data);
|
||||
await updateAppSettings(req, res, next);
|
||||
expect(res.status.firstCall.args[0]).to.equal(200);
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({
|
||||
success: true,
|
||||
msg: successMessages.UPDATE_APP_SETTINGS,
|
||||
data,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,218 @@
|
||||
import sinon from "sinon";
|
||||
import EmailService from "../../service/emailService.js";
|
||||
|
||||
describe("EmailService - Constructor", () => {
|
||||
let settingsServiceMock;
|
||||
let fsMock;
|
||||
let pathMock;
|
||||
let compileMock;
|
||||
let mjml2htmlMock;
|
||||
let nodemailerMock;
|
||||
let loggerMock;
|
||||
|
||||
beforeEach(() => {
|
||||
settingsServiceMock = {
|
||||
getSettings: sinon.stub().returns({
|
||||
systemEmailHost: "smtp.example.com",
|
||||
systemEmailPort: 465,
|
||||
systemEmailAddress: "test@example.com",
|
||||
systemEmailPassword: "password",
|
||||
}),
|
||||
};
|
||||
|
||||
fsMock = {
|
||||
readFileSync: sinon.stub().returns("<mjml><body></body></mjml>"),
|
||||
};
|
||||
|
||||
pathMock = {
|
||||
join: sinon.stub().callsFake((...args) => args.join("/")),
|
||||
};
|
||||
|
||||
compileMock = sinon.stub().returns(() => "<mjml><body></body></mjml>");
|
||||
|
||||
mjml2htmlMock = sinon.stub().returns({ html: "<html></html>" });
|
||||
|
||||
nodemailerMock = {
|
||||
createTransport: sinon.stub().returns({
|
||||
sendMail: sinon.stub().resolves({ messageId: "12345" }),
|
||||
}),
|
||||
};
|
||||
|
||||
loggerMock = {
|
||||
error: sinon.stub(),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should initialize template loaders and email transporter", () => {
|
||||
const emailService = new EmailService(
|
||||
settingsServiceMock,
|
||||
fsMock,
|
||||
pathMock,
|
||||
compileMock,
|
||||
mjml2htmlMock,
|
||||
nodemailerMock,
|
||||
loggerMock
|
||||
);
|
||||
|
||||
// Verify that the settingsService is assigned correctly
|
||||
expect(emailService.settingsService).to.equal(settingsServiceMock);
|
||||
|
||||
// Verify that the template loaders are initialized
|
||||
expect(emailService.templateLookup.welcomeEmailTemplate).to.be.a("function");
|
||||
expect(emailService.templateLookup.employeeActivationTemplate).to.be.a("function");
|
||||
|
||||
// Verify that the email transporter is initialized
|
||||
expect(nodemailerMock.createTransport.calledOnce).to.be.true;
|
||||
const emailConfig = nodemailerMock.createTransport.getCall(0).args[0];
|
||||
expect(emailConfig).to.deep.equal({
|
||||
host: "smtp.example.com",
|
||||
port: 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: "test@example.com",
|
||||
pass: "password",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should have undefined templates if FS fails", () => {
|
||||
fsMock = {
|
||||
readFileSync: sinon.stub().throws(new Error("File read error")),
|
||||
};
|
||||
const emailService = new EmailService(
|
||||
settingsServiceMock,
|
||||
fsMock,
|
||||
pathMock,
|
||||
compileMock,
|
||||
mjml2htmlMock,
|
||||
nodemailerMock,
|
||||
loggerMock
|
||||
);
|
||||
expect(loggerMock.error.called).to.be.true;
|
||||
const errorCalls = loggerMock.error.getCalls();
|
||||
const errorCall = errorCalls.find(
|
||||
(call) => call.args[0] === "Error loading Email templates"
|
||||
);
|
||||
expect(errorCall).to.not.be.undefined;
|
||||
expect(emailService.settingsService).to.equal(settingsServiceMock);
|
||||
expect(emailService.templateLookup.welcomeEmailTemplate).to.be.undefined;
|
||||
expect(emailService.templateLookup.employeeActivationTemplate).to.be.undefined;
|
||||
});
|
||||
});
|
||||
|
||||
describe("EmailService - buildAndSendEmail", () => {
|
||||
let settingsServiceMock;
|
||||
let fsMock;
|
||||
let pathMock;
|
||||
let compileMock;
|
||||
let mjml2htmlMock;
|
||||
let nodemailerMock;
|
||||
let loggerMock;
|
||||
let emailService;
|
||||
beforeEach(() => {
|
||||
settingsServiceMock = {
|
||||
getSettings: sinon.stub().returns({
|
||||
systemEmailHost: "smtp.example.com",
|
||||
systemEmailPort: 465,
|
||||
systemEmailAddress: "test@example.com",
|
||||
systemEmailPassword: "password",
|
||||
}),
|
||||
};
|
||||
|
||||
fsMock = {
|
||||
readFileSync: sinon.stub().returns("<mjml><body></body></mjml>"),
|
||||
};
|
||||
|
||||
pathMock = {
|
||||
join: sinon.stub().callsFake((...args) => args.join("/")),
|
||||
};
|
||||
|
||||
compileMock = sinon.stub().returns(() => "<mjml><body></body></mjml>");
|
||||
|
||||
mjml2htmlMock = sinon.stub().returns({ html: "<html></html>" });
|
||||
|
||||
nodemailerMock = {
|
||||
createTransport: sinon.stub().returns({
|
||||
sendMail: sinon.stub().resolves({ messageId: "12345" }),
|
||||
}),
|
||||
};
|
||||
|
||||
loggerMock = {
|
||||
error: sinon.stub(),
|
||||
};
|
||||
|
||||
emailService = new EmailService(
|
||||
settingsServiceMock,
|
||||
fsMock,
|
||||
pathMock,
|
||||
compileMock,
|
||||
mjml2htmlMock,
|
||||
nodemailerMock,
|
||||
loggerMock
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should build and send email successfully", async () => {
|
||||
const messageId = await emailService.buildAndSendEmail(
|
||||
"welcomeEmailTemplate",
|
||||
{},
|
||||
"recipient@example.com",
|
||||
"Welcome"
|
||||
);
|
||||
|
||||
expect(messageId).to.equal("12345");
|
||||
expect(nodemailerMock.createTransport().sendMail.calledOnce).to.be.true;
|
||||
});
|
||||
|
||||
it("should log error if building HTML fails", async () => {
|
||||
mjml2htmlMock.throws(new Error("MJML error"));
|
||||
|
||||
const messageId = await emailService.buildAndSendEmail(
|
||||
"welcomeEmailTemplate",
|
||||
{},
|
||||
"recipient@example.com",
|
||||
"Welcome"
|
||||
);
|
||||
expect(loggerMock.error.calledOnce).to.be.true;
|
||||
expect(loggerMock.error.getCall(0).args[0]).to.equal("Error building Email HTML");
|
||||
});
|
||||
|
||||
it("should log error if sending email fails", async () => {
|
||||
nodemailerMock.createTransport().sendMail.rejects(new Error("SMTP error"));
|
||||
await emailService.buildAndSendEmail(
|
||||
"welcomeEmailTemplate",
|
||||
{},
|
||||
"recipient@example.com",
|
||||
"Welcome"
|
||||
);
|
||||
expect(loggerMock.error.calledOnce).to.be.true;
|
||||
expect(loggerMock.error.getCall(0).args[0]).to.equal("Error sending Email");
|
||||
});
|
||||
|
||||
it("should log error if both building HTML and sending email fail", async () => {
|
||||
mjml2htmlMock.throws(new Error("MJML error"));
|
||||
nodemailerMock.createTransport().sendMail.rejects(new Error("SMTP error"));
|
||||
|
||||
const messageId = await emailService.buildAndSendEmail(
|
||||
"welcomeEmailTemplate",
|
||||
{},
|
||||
"recipient@example.com",
|
||||
"Welcome"
|
||||
);
|
||||
|
||||
expect(messageId).to.be.undefined;
|
||||
expect(loggerMock.error.calledTwice).to.be.true;
|
||||
expect(loggerMock.error.getCall(0).args[0]).to.equal("Error building Email HTML");
|
||||
expect(loggerMock.error.getCall(1).args[0]).to.equal("Error sending Email");
|
||||
});
|
||||
|
||||
it("should log an error if buildHtml fails", async () => {});
|
||||
});
|
||||
@@ -0,0 +1,861 @@
|
||||
import sinon from "sinon";
|
||||
import NetworkService from "../../service/networkService.js";
|
||||
import { errorMessages, successMessages } from "../../utils/messages.js";
|
||||
import exp from "constants";
|
||||
describe("NetworkService - Constructor", function () {
|
||||
let dbMock, emailServiceMock, axiosMock, pingMock, loggerMock, httpMock;
|
||||
|
||||
beforeEach(function () {
|
||||
dbMock = sinon.stub();
|
||||
emailServiceMock = sinon.stub();
|
||||
axiosMock = sinon.stub();
|
||||
pingMock = sinon.stub();
|
||||
loggerMock = sinon.stub();
|
||||
httpMock = sinon.stub();
|
||||
});
|
||||
|
||||
it("should correctly initialize properties", function () {
|
||||
const networkService = new NetworkService(
|
||||
dbMock,
|
||||
emailServiceMock,
|
||||
axiosMock,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock
|
||||
);
|
||||
|
||||
expect(networkService.db).to.equal(dbMock);
|
||||
expect(networkService.emailService).to.equal(emailServiceMock);
|
||||
expect(networkService.TYPE_PING).to.equal("ping");
|
||||
expect(networkService.TYPE_HTTP).to.equal("http");
|
||||
expect(networkService.TYPE_PAGESPEED).to.equal("pagespeed");
|
||||
expect(networkService.SERVICE_NAME).to.equal("NetworkService");
|
||||
expect(networkService.NETWORK_ERROR).to.equal(5000);
|
||||
expect(networkService.axios).to.equal(axiosMock);
|
||||
expect(networkService.ping).to.equal(pingMock);
|
||||
expect(networkService.logger).to.equal(loggerMock);
|
||||
expect(networkService.http).to.equal(httpMock);
|
||||
});
|
||||
});
|
||||
|
||||
describe("NetworkService - handleNotification", () => {
|
||||
let dbMock, emailServiceMock, loggerMock, networkService;
|
||||
|
||||
beforeEach(function () {
|
||||
dbMock = {
|
||||
getNotificationsByMonitorId: sinon.stub(),
|
||||
};
|
||||
emailServiceMock = {
|
||||
buildAndSendEmail: sinon.stub().resolves(),
|
||||
};
|
||||
loggerMock = {
|
||||
error: sinon.stub(),
|
||||
};
|
||||
|
||||
networkService = new NetworkService(
|
||||
dbMock,
|
||||
emailServiceMock,
|
||||
null,
|
||||
null,
|
||||
loggerMock,
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
it("should send email notifications when monitor is down", async function () {
|
||||
const monitor = { _id: "monitor1", name: "Test Monitor", url: "http://test.com" };
|
||||
const notifications = [{ type: "email", address: "test@example.com" }];
|
||||
dbMock.getNotificationsByMonitorId.resolves(notifications);
|
||||
|
||||
await networkService.handleNotification(monitor, false);
|
||||
|
||||
expect(emailServiceMock.buildAndSendEmail.calledOnce).to.be.true;
|
||||
expect(
|
||||
emailServiceMock.buildAndSendEmail.calledWith(
|
||||
"serverIsDownTemplate",
|
||||
{ monitorName: monitor.name, monitorUrl: monitor.url },
|
||||
"test@example.com",
|
||||
"Monitor Test Monitor is down"
|
||||
)
|
||||
).to.be.true;
|
||||
});
|
||||
|
||||
it("should send email notifications when monitor is up", async function () {
|
||||
const monitor = { _id: "monitor1", name: "Test Monitor", url: "http://test.com" };
|
||||
const notifications = [{ type: "email", address: "test@example.com" }];
|
||||
dbMock.getNotificationsByMonitorId.resolves(notifications);
|
||||
|
||||
await networkService.handleNotification(monitor, true);
|
||||
|
||||
expect(emailServiceMock.buildAndSendEmail.calledOnce).to.be.true;
|
||||
expect(
|
||||
emailServiceMock.buildAndSendEmail.calledWith(
|
||||
"serverIsUpTemplate",
|
||||
{ monitorName: monitor.name, monitorUrl: monitor.url },
|
||||
"test@example.com",
|
||||
"Monitor Test Monitor is up"
|
||||
)
|
||||
).to.be.true;
|
||||
});
|
||||
|
||||
it("should log an error if an exception is thrown", async function () {
|
||||
const monitor = { _id: "monitor1", name: "Test Monitor", url: "http://test.com" };
|
||||
dbMock.getNotificationsByMonitorId.rejects(new Error("Database error"));
|
||||
|
||||
await networkService.handleNotification(monitor, true);
|
||||
|
||||
expect(loggerMock.error.calledOnce).to.be.true;
|
||||
expect(
|
||||
loggerMock.error.calledWith("Database error", {
|
||||
method: "handleNotification",
|
||||
service: networkService.SERVICE_NAME,
|
||||
monitorId: monitor._id,
|
||||
})
|
||||
).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("NetworkService - handleStatusUpdate", function () {
|
||||
let dbMock,
|
||||
emailServiceMock,
|
||||
axiosMock,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock,
|
||||
networkService,
|
||||
monitorMock;
|
||||
|
||||
beforeEach(function () {
|
||||
dbMock = { getMonitorById: sinon.stub() };
|
||||
emailServiceMock = sinon.stub();
|
||||
axiosMock = sinon.stub();
|
||||
pingMock = sinon.stub();
|
||||
loggerMock = { error: sinon.stub() };
|
||||
httpMock = sinon.stub();
|
||||
networkService = new NetworkService(
|
||||
dbMock,
|
||||
emailServiceMock,
|
||||
axiosMock,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock
|
||||
);
|
||||
monitorMock = {
|
||||
status: sinon.stub(),
|
||||
save: sinon.stub(),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should return if getMonitorById throws an error", async function () {
|
||||
dbMock.getMonitorById.throws(new Error("Database error"));
|
||||
|
||||
const res = await networkService.handleStatusUpdate(
|
||||
{ data: { _id: "monitor1" } },
|
||||
true
|
||||
);
|
||||
expect(res).to.be.undefined;
|
||||
});
|
||||
|
||||
it("should log an error if monitor is null", async function () {
|
||||
dbMock.getMonitorById.resolves(null);
|
||||
|
||||
await networkService.handleStatusUpdate({ data: { _id: "monitor1" } }, true);
|
||||
|
||||
expect(loggerMock.error.calledOnce).to.be.true;
|
||||
expect(loggerMock.error.calledWith("Null Monitor: monitor1")).to.be.true;
|
||||
});
|
||||
|
||||
it("should update monitor status if different", async function () {
|
||||
monitorMock.status = false;
|
||||
dbMock.getMonitorById.resolves(monitorMock);
|
||||
|
||||
await networkService.handleStatusUpdate({ data: { _id: "monitor1" } }, true);
|
||||
|
||||
expect(monitorMock.save.calledOnce).to.be.true;
|
||||
expect(monitorMock.status).to.be.true;
|
||||
});
|
||||
|
||||
it("should not update monitor status if same", async function () {
|
||||
monitorMock.status = true;
|
||||
dbMock.getMonitorById.resolves(monitorMock);
|
||||
|
||||
await networkService.handleStatusUpdate({ data: { _id: "monitor1" } }, true);
|
||||
|
||||
expect(monitorMock.save.called).to.be.false;
|
||||
});
|
||||
|
||||
it("should log an error if exception is thrown during status update", async function () {
|
||||
monitorMock.status = false;
|
||||
dbMock.getMonitorById.resolves(monitorMock);
|
||||
monitorMock.save.rejects(new Error("Save error"));
|
||||
|
||||
await networkService.handleStatusUpdate({ data: { _id: "monitor1" } }, true);
|
||||
|
||||
expect(loggerMock.error.calledOnce).to.be.true;
|
||||
expect(loggerMock.error.calledWith("Save error")).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("NetworkService - measureResponseTime", () => {
|
||||
let mockOperation,
|
||||
dbMock,
|
||||
emailServiceMock,
|
||||
axiosMock,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock,
|
||||
networkService;
|
||||
|
||||
beforeEach(() => {
|
||||
mockOperation = sinon.stub();
|
||||
dbMock = { getMonitorById: sinon.stub() };
|
||||
emailServiceMock = sinon.stub();
|
||||
axiosMock = sinon.stub();
|
||||
pingMock = sinon.stub();
|
||||
loggerMock = { error: sinon.stub() };
|
||||
httpMock = sinon.stub();
|
||||
networkService = new NetworkService(
|
||||
dbMock,
|
||||
emailServiceMock,
|
||||
axiosMock,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should return response time and response on successful operation", async () => {
|
||||
const fakeResponse = { data: "test" };
|
||||
mockOperation.resolves(fakeResponse);
|
||||
|
||||
const result = await networkService.measureResponseTime(mockOperation);
|
||||
expect(result).to.have.property("responseTime").that.is.a("number");
|
||||
expect(result).to.have.property("response").that.deep.equals(fakeResponse);
|
||||
});
|
||||
|
||||
it("should throw an error with response time and additional properties on operation failure", async () => {
|
||||
const fakeError = new Error("Operation failed");
|
||||
mockOperation.rejects(fakeError);
|
||||
|
||||
try {
|
||||
await networkService.measureResponseTime(mockOperation);
|
||||
} catch (error) {
|
||||
expect(error).to.have.property("responseTime").that.is.a("number");
|
||||
expect(error).to.have.property("service", networkService.SERVICE_NAME);
|
||||
expect(error).to.have.property("method", "measureResponseTime");
|
||||
expect(error.message).to.equal("Operation failed");
|
||||
}
|
||||
});
|
||||
it("should throw an error with response time set properties on operation failure", async () => {
|
||||
const fakeError = new Error("Operation failed");
|
||||
fakeError.service = "test";
|
||||
fakeError.method = "testMethod";
|
||||
mockOperation.rejects(fakeError);
|
||||
|
||||
try {
|
||||
await networkService.measureResponseTime(mockOperation);
|
||||
} catch (error) {
|
||||
expect(error).to.have.property("responseTime").that.is.a("number");
|
||||
expect(error).to.have.property("service", "test");
|
||||
expect(error).to.have.property("method", "testMethod");
|
||||
expect(error.message).to.equal("Operation failed");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("networkService - handlePing", () => {
|
||||
let job,
|
||||
dbMock,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock,
|
||||
networkService,
|
||||
logAndStoreCheckStub,
|
||||
handleStatusUpdateStub;
|
||||
beforeEach(function () {
|
||||
job = {
|
||||
data: {
|
||||
url: "http://example.com",
|
||||
_id: "12345",
|
||||
},
|
||||
};
|
||||
|
||||
dbMock = { getMonitorById: sinon.stub() };
|
||||
pingMock = { promise: { probe: sinon.stub() } };
|
||||
loggerMock = { error: sinon.stub() };
|
||||
httpMock = sinon.stub();
|
||||
networkService = new NetworkService(
|
||||
dbMock,
|
||||
null,
|
||||
null,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock
|
||||
);
|
||||
logAndStoreCheckStub = sinon.stub(networkService, "logAndStoreCheck");
|
||||
handleStatusUpdateStub = sinon.stub(networkService, "handleStatusUpdate");
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should handle a successful ping response", async function () {
|
||||
const response = { alive: true };
|
||||
const responseTime = 0;
|
||||
pingMock.promise.probe.resolves(response);
|
||||
logAndStoreCheckStub.resolves();
|
||||
await networkService.handlePing(job);
|
||||
expect(
|
||||
logAndStoreCheckStub.calledOnceWith(
|
||||
{
|
||||
monitorId: job.data._id,
|
||||
status: true,
|
||||
responseTime,
|
||||
message: successMessages.PING_SUCCESS,
|
||||
},
|
||||
networkService.db.createCheck
|
||||
)
|
||||
).to.be.true;
|
||||
expect(handleStatusUpdateStub.calledOnceWith(job, true)).to.be.true;
|
||||
});
|
||||
it("should handle a successful ping response and isAlive === false", async function () {
|
||||
const response = { alive: false };
|
||||
const responseTime = 0;
|
||||
pingMock.promise.probe.resolves(response);
|
||||
logAndStoreCheckStub.resolves();
|
||||
|
||||
await networkService.handlePing(job);
|
||||
console.log(logAndStoreCheckStub.getCall(0).args[0]);
|
||||
expect(
|
||||
logAndStoreCheckStub.calledOnceWith(
|
||||
{
|
||||
monitorId: job.data._id,
|
||||
status: false,
|
||||
responseTime,
|
||||
message: errorMessages.PING_CANNOT_RESOLVE,
|
||||
},
|
||||
networkService.db.createCheck
|
||||
)
|
||||
).to.be.true;
|
||||
expect(handleStatusUpdateStub.calledOnceWith(job, false)).to.be.true;
|
||||
});
|
||||
|
||||
it("should handle a failed ping response", async function () {
|
||||
const error = new Error("Ping failed");
|
||||
error.responseTime = 0;
|
||||
|
||||
pingMock.promise.probe.rejects(error);
|
||||
|
||||
await networkService.handlePing(job);
|
||||
|
||||
expect(handleStatusUpdateStub.calledOnceWith(job, false)).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("NetworkService - handleHttp", () => {
|
||||
let networkService,
|
||||
axiosMock,
|
||||
dbMock,
|
||||
httpMock,
|
||||
jobMock,
|
||||
loggerMock,
|
||||
logAndStoreCheckStub,
|
||||
handleStatusUpdateStub;
|
||||
|
||||
beforeEach(() => {
|
||||
axiosMock = {
|
||||
get: sinon.stub(),
|
||||
};
|
||||
dbMock = {
|
||||
createCheck: sinon.stub().resolves(),
|
||||
};
|
||||
httpMock = {
|
||||
STATUS_CODES: {
|
||||
200: "OK",
|
||||
500: "Internal Server Error",
|
||||
},
|
||||
};
|
||||
loggerMock = {
|
||||
error: sinon.stub(),
|
||||
};
|
||||
networkService = new NetworkService(
|
||||
dbMock,
|
||||
null,
|
||||
axiosMock,
|
||||
null,
|
||||
loggerMock,
|
||||
httpMock
|
||||
);
|
||||
jobMock = {
|
||||
data: {
|
||||
url: "http://example.com",
|
||||
_id: "monitorId123",
|
||||
},
|
||||
};
|
||||
sinon.stub(networkService, "measureResponseTime").callsFake(async (operation) => {
|
||||
const response = await operation();
|
||||
return { responseTime: 100, response };
|
||||
});
|
||||
logAndStoreCheckStub = sinon.stub(networkService, "logAndStoreCheck").resolves();
|
||||
handleStatusUpdateStub = sinon.stub(networkService, "handleStatusUpdate").resolves();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should handle a successful HTTP response", async () => {
|
||||
const responseMock = { status: 200 };
|
||||
axiosMock.get.resolves(responseMock);
|
||||
|
||||
await networkService.handleHttp(jobMock);
|
||||
|
||||
expect(networkService.logAndStoreCheck.calledOnce).to.be.true;
|
||||
const checkData = networkService.logAndStoreCheck.getCall(0).args[0];
|
||||
expect(checkData).to.include({
|
||||
monitorId: jobMock.data._id,
|
||||
status: true,
|
||||
statusCode: 200,
|
||||
message: "OK",
|
||||
});
|
||||
expect(networkService.handleStatusUpdate.calledOnceWith(jobMock, true)).to.be.true;
|
||||
});
|
||||
|
||||
it("should handle an HTTP error response", async () => {
|
||||
const errorMock = { response: { status: 500 }, responseTime: 200 };
|
||||
axiosMock.get.rejects(errorMock);
|
||||
|
||||
await networkService.handleHttp(jobMock);
|
||||
|
||||
expect(networkService.logAndStoreCheck.calledOnce).to.be.true;
|
||||
const checkData = networkService.logAndStoreCheck.getCall(0).args[0];
|
||||
expect(checkData).to.include({
|
||||
monitorId: jobMock.data._id,
|
||||
status: false,
|
||||
statusCode: 500,
|
||||
message: "Internal Server Error",
|
||||
});
|
||||
expect(networkService.handleStatusUpdate.calledOnceWith(jobMock, false)).to.be.true;
|
||||
});
|
||||
it("should handle an HTTP error response with undefined status", async () => {
|
||||
const errorMock = { response: { status: undefined }, responseTime: 200 };
|
||||
axiosMock.get.rejects(errorMock);
|
||||
|
||||
await networkService.handleHttp(jobMock);
|
||||
|
||||
expect(networkService.logAndStoreCheck.calledOnce).to.be.true;
|
||||
const checkData = networkService.logAndStoreCheck.getCall(0).args[0];
|
||||
expect(checkData).to.include({
|
||||
monitorId: jobMock.data._id,
|
||||
status: false,
|
||||
statusCode: 5000,
|
||||
message: "Network Error",
|
||||
});
|
||||
expect(networkService.handleStatusUpdate.calledOnceWith(jobMock, false)).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("networkService - handlePagespeed", () => {
|
||||
let dbMock,
|
||||
axiosMock,
|
||||
jobMock,
|
||||
emailServiceMock,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock,
|
||||
networkService,
|
||||
logAndStoreCheckStub,
|
||||
handleStatusUpdateStub;
|
||||
beforeEach(() => {
|
||||
jobMock = {
|
||||
data: {
|
||||
_id: "12345",
|
||||
url: "http://example.com",
|
||||
},
|
||||
};
|
||||
dbMock = { getMonitorById: sinon.stub() };
|
||||
axiosMock = { get: sinon.stub() };
|
||||
|
||||
emailServiceMock = sinon.stub();
|
||||
pingMock = { promise: { probe: sinon.stub() } };
|
||||
loggerMock = { error: sinon.stub() };
|
||||
httpMock = {
|
||||
STATUS_CODES: {
|
||||
200: "OK",
|
||||
500: "Internal Server Error",
|
||||
},
|
||||
};
|
||||
networkService = new NetworkService(
|
||||
dbMock,
|
||||
emailServiceMock,
|
||||
axiosMock,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock
|
||||
);
|
||||
logAndStoreCheckStub = sinon.stub(networkService, "logAndStoreCheck").resolves();
|
||||
handleStatusUpdateStub = sinon.stub(networkService, "handleStatusUpdate").resolves();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should handle a successful PageSpeed response", async () => {
|
||||
const responseMock = {
|
||||
status: 200,
|
||||
data: {
|
||||
lighthouseResult: {
|
||||
categories: {
|
||||
accessibility: { score: 0.9 },
|
||||
"best-practices": { score: 0.8 },
|
||||
seo: { score: 0.7 },
|
||||
performance: { score: 0.6 },
|
||||
},
|
||||
audits: {
|
||||
"cumulative-layout-shift": { score: 0.1 },
|
||||
"speed-index": { score: 0.2 },
|
||||
"first-contentful-paint": { score: 0.3 },
|
||||
"largest-contentful-paint": { score: 0.4 },
|
||||
"total-blocking-time": { score: 0.5 },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
axiosMock.get.resolves(responseMock);
|
||||
|
||||
await networkService.handlePagespeed(jobMock);
|
||||
expect(networkService.logAndStoreCheck.calledOnce).to.be.true;
|
||||
const checkData = networkService.logAndStoreCheck.getCall(0).args[0];
|
||||
expect(checkData).to.include({
|
||||
monitorId: jobMock.data._id,
|
||||
status: true,
|
||||
statusCode: 200,
|
||||
message: "OK",
|
||||
accessibility: 90,
|
||||
bestPractices: 80,
|
||||
seo: 70,
|
||||
performance: 60,
|
||||
});
|
||||
expect(networkService.handleStatusUpdate.calledOnceWith(jobMock, true)).to.be.true;
|
||||
});
|
||||
|
||||
it("should handle a successful PageSpeed response with missing data", async () => {
|
||||
const responseMock = {
|
||||
status: 200,
|
||||
data: {
|
||||
lighthouseResult: {
|
||||
categories: {},
|
||||
audits: {
|
||||
"cumulative-layout-shift": { score: 0.1 },
|
||||
"speed-index": { score: 0.2 },
|
||||
"first-contentful-paint": { score: 0.3 },
|
||||
"largest-contentful-paint": { score: 0.4 },
|
||||
"total-blocking-time": { score: 0.5 },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
axiosMock.get.resolves(responseMock);
|
||||
|
||||
await networkService.handlePagespeed(jobMock);
|
||||
expect(networkService.logAndStoreCheck.calledOnce).to.be.true;
|
||||
const checkData = networkService.logAndStoreCheck.getCall(0).args[0];
|
||||
expect(checkData).to.include({
|
||||
monitorId: jobMock.data._id,
|
||||
status: true,
|
||||
statusCode: 200,
|
||||
message: "OK",
|
||||
accessibility: 0,
|
||||
bestPractices: 0,
|
||||
seo: 0,
|
||||
performance: 0,
|
||||
});
|
||||
expect(networkService.handleStatusUpdate.calledOnceWith(jobMock, true)).to.be.true;
|
||||
});
|
||||
|
||||
it("should handle an error PageSpeed response", async () => {
|
||||
const errorMock = { response: { status: 500 } };
|
||||
axiosMock.get.rejects(errorMock);
|
||||
|
||||
await networkService.handlePagespeed(jobMock);
|
||||
|
||||
expect(networkService.logAndStoreCheck.calledOnce).to.be.true;
|
||||
const checkData = networkService.logAndStoreCheck.getCall(0).args[0];
|
||||
expect(checkData).to.include({
|
||||
monitorId: jobMock.data._id,
|
||||
status: false,
|
||||
statusCode: 500,
|
||||
message: "Internal Server Error",
|
||||
accessibility: 0,
|
||||
bestPractices: 0,
|
||||
seo: 0,
|
||||
performance: 0,
|
||||
});
|
||||
expect(networkService.handleStatusUpdate.calledOnceWith(jobMock, false)).to.be.true;
|
||||
});
|
||||
it("should handle an error PageSpeed response with unknown status", async () => {
|
||||
const errorMock = { response: { status: undefined } };
|
||||
axiosMock.get.rejects(errorMock);
|
||||
|
||||
await networkService.handlePagespeed(jobMock);
|
||||
|
||||
expect(networkService.logAndStoreCheck.calledOnce).to.be.true;
|
||||
const checkData = networkService.logAndStoreCheck.getCall(0).args[0];
|
||||
expect(checkData).to.include({
|
||||
monitorId: jobMock.data._id,
|
||||
status: false,
|
||||
statusCode: 5000,
|
||||
message: "Network Error",
|
||||
accessibility: 0,
|
||||
bestPractices: 0,
|
||||
seo: 0,
|
||||
performance: 0,
|
||||
});
|
||||
expect(networkService.handleStatusUpdate.calledOnceWith(jobMock, false)).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("networkService - handleHardware", () => {
|
||||
let dbMock,
|
||||
axiosMock,
|
||||
jobMock,
|
||||
emailServiceMock,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock,
|
||||
networkService,
|
||||
logAndStoreCheckStub,
|
||||
handleStatusUpdateStub;
|
||||
beforeEach(() => {
|
||||
jobMock = {
|
||||
data: {
|
||||
_id: "12345",
|
||||
url: "http://example.com",
|
||||
},
|
||||
};
|
||||
dbMock = { getMonitorById: sinon.stub() };
|
||||
axiosMock = { get: sinon.stub() };
|
||||
|
||||
emailServiceMock = sinon.stub();
|
||||
pingMock = { promise: { probe: sinon.stub() } };
|
||||
loggerMock = { error: sinon.stub() };
|
||||
httpMock = {
|
||||
STATUS_CODES: {
|
||||
200: "OK",
|
||||
500: "Internal Server Error",
|
||||
},
|
||||
};
|
||||
networkService = new NetworkService(
|
||||
dbMock,
|
||||
emailServiceMock,
|
||||
axiosMock,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock
|
||||
);
|
||||
logAndStoreCheckStub = sinon.stub(networkService, "logAndStoreCheck").resolves();
|
||||
handleStatusUpdateStub = sinon.stub(networkService, "handleStatusUpdate").resolves();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should handle a successful Hardware response", async () => {
|
||||
const responseMock = {
|
||||
monitorId: jobMock.data._id,
|
||||
cpu: {
|
||||
physical_core: 1,
|
||||
logical_core: 1,
|
||||
frequency: 266,
|
||||
temperature: null,
|
||||
free_percent: null,
|
||||
usage_percent: null,
|
||||
},
|
||||
memory: {
|
||||
total_bytes: 4,
|
||||
available_bytes: 4,
|
||||
used_bytes: 2,
|
||||
usage_percent: 0.5,
|
||||
},
|
||||
disk: [
|
||||
{
|
||||
read_speed_bytes: 3,
|
||||
write_speed_bytes: 3,
|
||||
total_bytes: 10,
|
||||
free_bytes: 2,
|
||||
usage_percent: 0.8,
|
||||
},
|
||||
],
|
||||
host: {
|
||||
os: "Linux",
|
||||
platform: "Ubuntu",
|
||||
kernel_version: "24.04",
|
||||
},
|
||||
};
|
||||
axiosMock.get.resolves(responseMock);
|
||||
|
||||
await networkService.handleHardware(jobMock);
|
||||
expect(networkService.logAndStoreCheck.calledOnce).to.be.true;
|
||||
const hardwareData = networkService.logAndStoreCheck.getCall(0).args[0];
|
||||
expect(hardwareData.cpu).to.include({
|
||||
...responseMock.cpu,
|
||||
});
|
||||
expect(networkService.handleStatusUpdate.calledOnceWith(jobMock, true)).to.be.true;
|
||||
});
|
||||
|
||||
it("should handle an error Hardware response", async () => {
|
||||
logAndStoreCheckStub.throws(new Error("Hardware error"));
|
||||
try {
|
||||
await networkService.handleHardware(jobMock);
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("Hardware error");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("NetworkService - getStatus", () => {
|
||||
let dbMock, emailServiceMock, axiosMock, pingMock, loggerMock, httpMock, networkService;
|
||||
|
||||
beforeEach(() => {
|
||||
dbMock = { getMonitorById: sinon.stub() };
|
||||
emailServiceMock = sinon.stub();
|
||||
axiosMock = sinon.stub();
|
||||
pingMock = sinon.stub();
|
||||
loggerMock = { error: sinon.stub() };
|
||||
httpMock = sinon.stub();
|
||||
networkService = new NetworkService(
|
||||
dbMock,
|
||||
emailServiceMock,
|
||||
axiosMock,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should return true if the job type is ping and handlePing is successful", async () => {
|
||||
const job = { data: { type: networkService.TYPE_PING } };
|
||||
sinon.stub(networkService, "handlePing").resolves(true);
|
||||
const result = await networkService.getStatus(job);
|
||||
expect(result).to.be.true;
|
||||
});
|
||||
it("should return false if the job type is ping and handlePing is not successful", async () => {
|
||||
const job = { data: { type: networkService.TYPE_PING } };
|
||||
sinon.stub(networkService, "handlePing").resolves(false);
|
||||
const result = await networkService.getStatus(job);
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
it("should return true if the job type is http and handleHttp is successful", async () => {
|
||||
const job = { data: { type: networkService.TYPE_HTTP } };
|
||||
sinon.stub(networkService, "handleHttp").resolves(true);
|
||||
const result = await networkService.getStatus(job);
|
||||
expect(result).to.be.true;
|
||||
});
|
||||
it("should return false if the job type is http and handleHttp is not successful", async () => {
|
||||
const job = { data: { type: networkService.TYPE_HTTP } };
|
||||
sinon.stub(networkService, "handleHttp").resolves(false);
|
||||
const result = await networkService.getStatus(job);
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
it("should return true if the job type is pagespeed and handlePagespeed is successful", async () => {
|
||||
const job = { data: { type: networkService.TYPE_PAGESPEED } };
|
||||
sinon.stub(networkService, "handlePagespeed").resolves(true);
|
||||
const result = await networkService.getStatus(job);
|
||||
expect(result).to.be.true;
|
||||
});
|
||||
it("should return false if the job type is pagespeed and handlePagespeed is not successful", async () => {
|
||||
const job = { data: { type: networkService.TYPE_PAGESPEED } };
|
||||
sinon.stub(networkService, "handlePagespeed").resolves(false);
|
||||
const result = await networkService.getStatus(job);
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
it("should return true if the job type is hardware and handleHardware is successful", async () => {
|
||||
const job = { data: { type: networkService.TYPE_HARDWARE } };
|
||||
sinon.stub(networkService, "handleHardware").resolves(true);
|
||||
const result = await networkService.getStatus(job);
|
||||
expect(result).to.be.true;
|
||||
});
|
||||
it("should return false if the job type is hardware and handleHardware is not successful", async () => {
|
||||
const job = { data: { type: networkService.TYPE_HARDWARE } };
|
||||
sinon.stub(networkService, "handleHardware").resolves(false);
|
||||
const result = await networkService.getStatus(job);
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
it("should log an error and return false if the job type is unknown", async () => {
|
||||
const job = { data: { type: "unknown" } };
|
||||
const result = await networkService.getStatus(job);
|
||||
expect(result).to.be.false;
|
||||
expect(loggerMock.error.calledOnce).to.be.true;
|
||||
expect(loggerMock.error.calledWith(`Unsupported type: unknown`)).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("NetworkService - logAndStoreCheck", async () => {
|
||||
let dbMock, emailServiceMock, axiosMock, pingMock, loggerMock, httpMock, networkService;
|
||||
|
||||
beforeEach(() => {
|
||||
dbMock = { getMonitorById: sinon.stub() };
|
||||
emailServiceMock = sinon.stub();
|
||||
axiosMock = sinon.stub();
|
||||
pingMock = sinon.stub();
|
||||
loggerMock = { error: sinon.stub() };
|
||||
httpMock = sinon.stub();
|
||||
networkService = new NetworkService(
|
||||
dbMock,
|
||||
emailServiceMock,
|
||||
axiosMock,
|
||||
pingMock,
|
||||
loggerMock,
|
||||
httpMock
|
||||
);
|
||||
});
|
||||
const data = { monitorId: "12345" };
|
||||
const writeToDB = sinon.stub();
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should log an error if `writeToDb` throws an error", async () => {
|
||||
writeToDB.rejects(new Error("Database error"));
|
||||
await networkService.logAndStoreCheck(data, writeToDB);
|
||||
expect(loggerMock.error.calledOnce).to.be.true;
|
||||
expect(loggerMock.error.calledWith(`Error writing check for ${data.monitorId}`)).to.be
|
||||
.true;
|
||||
});
|
||||
|
||||
it("should return the status of the inserted check if successful", async () => {
|
||||
writeToDB.resolves({ status: true });
|
||||
const result = await networkService.logAndStoreCheck(data, writeToDB);
|
||||
expect(result).to.be.true;
|
||||
});
|
||||
|
||||
it("should thrown an error if the check is not inserted (null)", async () => {
|
||||
writeToDB.resolves(null);
|
||||
await networkService.logAndStoreCheck(data, writeToDB);
|
||||
expect(loggerMock.error.calledOnce).to.be.true;
|
||||
expect(loggerMock.error.calledWith(`Error writing check for ${data.monitorId}`)).to.be
|
||||
.true;
|
||||
});
|
||||
it("should thrown an error if the check is not inserted (undefined)", async () => {
|
||||
writeToDB.resolves(undefined);
|
||||
await networkService.logAndStoreCheck(data, writeToDB);
|
||||
expect(loggerMock.error.calledOnce).to.be.true;
|
||||
expect(loggerMock.error.calledWith(`Error writing check for ${data.monitorId}`)).to.be
|
||||
.true;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import sinon from "sinon";
|
||||
import SettingsService from "../../service/settingsService.js";
|
||||
import { expect } from "chai";
|
||||
import NetworkService from "../../service/networkService.js";
|
||||
const SERVICE_NAME = "SettingsService";
|
||||
|
||||
describe("SettingsService", () => {
|
||||
let sandbox, mockAppSettings;
|
||||
beforeEach(function () {
|
||||
sandbox = sinon.createSandbox();
|
||||
sandbox.stub(process.env, "CLIENT_HOST").value("http://localhost");
|
||||
sandbox.stub(process.env, "JWT_SECRET").value("secret");
|
||||
sandbox.stub(process.env, "REFRESH_TOKEN_SECRET").value("refreshSecret");
|
||||
sandbox.stub(process.env, "DB_TYPE").value("postgres");
|
||||
sandbox
|
||||
.stub(process.env, "DB_CONNECTION_STRING")
|
||||
.value("postgres://user:pass@localhost/db");
|
||||
sandbox.stub(process.env, "REDIS_HOST").value("localhost");
|
||||
sandbox.stub(process.env, "REDIS_PORT").value("6379");
|
||||
sandbox.stub(process.env, "TOKEN_TTL").value("3600");
|
||||
sandbox.stub(process.env, "REFRESH_TOKEN_TTL").value("86400");
|
||||
sandbox.stub(process.env, "PAGESPEED_API_KEY").value("apiKey");
|
||||
sandbox.stub(process.env, "SYSTEM_EMAIL_HOST").value("smtp.mailtrap.io");
|
||||
sandbox.stub(process.env, "SYSTEM_EMAIL_PORT").value("2525");
|
||||
sandbox.stub(process.env, "SYSTEM_EMAIL_ADDRESS").value("test@example.com");
|
||||
sandbox.stub(process.env, "SYSTEM_EMAIL_PASSWORD").value("password");
|
||||
});
|
||||
|
||||
mockAppSettings = {
|
||||
settingOne: 123,
|
||||
settingTwo: 456,
|
||||
};
|
||||
|
||||
afterEach(function () {
|
||||
sandbox.restore();
|
||||
sinon.restore();
|
||||
});
|
||||
describe("constructor", () => {
|
||||
it("should construct a new SettingsService", () => {
|
||||
const settingsService = new SettingsService(mockAppSettings);
|
||||
expect(settingsService.appSettings).to.equal(mockAppSettings);
|
||||
});
|
||||
});
|
||||
describe("loadSettings", () => {
|
||||
it("should load settings from DB when environment variables are not set", async () => {
|
||||
const dbSettings = { logLevel: "debug", apiBaseUrl: "http://localhost" };
|
||||
const appSettings = { findOne: sinon.stub().returns(dbSettings) };
|
||||
const settingsService = new SettingsService(appSettings);
|
||||
settingsService.settings = {};
|
||||
const result = await settingsService.loadSettings();
|
||||
expect(result).to.deep.equal(dbSettings);
|
||||
});
|
||||
it("should throw an error if settings are not found", async function () {
|
||||
const appSettings = { findOne: sinon.stub().returns(null) };
|
||||
const settingsService = new SettingsService(appSettings);
|
||||
settingsService.settings = null;
|
||||
|
||||
try {
|
||||
await settingsService.loadSettings();
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("Settings not found");
|
||||
expect(error.service).to.equal(SERVICE_NAME);
|
||||
expect(error.method).to.equal("loadSettings");
|
||||
}
|
||||
});
|
||||
|
||||
it("should add its method and service name to error if not present", async () => {
|
||||
const appSettings = { findOne: sinon.stub().throws(new Error("Test error")) };
|
||||
const settingsService = new SettingsService(appSettings);
|
||||
try {
|
||||
await settingsService.loadSettings();
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("Test error");
|
||||
expect(error.service).to.equal(SERVICE_NAME);
|
||||
expect(error.method).to.equal("loadSettings");
|
||||
}
|
||||
});
|
||||
it("should not add its method and service name to error if present", async () => {
|
||||
const error = new Error("Test error");
|
||||
error.method = "otherMethod";
|
||||
error.service = "OTHER_SERVICE";
|
||||
const appSettings = { findOne: sinon.stub().throws(error) };
|
||||
const settingsService = new SettingsService(appSettings);
|
||||
try {
|
||||
await settingsService.loadSettings();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
expect(error.message).to.equal("Test error");
|
||||
expect(error.service).to.equal("OTHER_SERVICE");
|
||||
expect(error.method).to.equal("otherMethod");
|
||||
}
|
||||
});
|
||||
it("should merge DB settings with environment variables", async function () {
|
||||
const dbSettings = { logLevel: "debug", apiBaseUrl: "http://localhost" };
|
||||
const appSettings = { findOne: sinon.stub().returns(dbSettings) };
|
||||
const settingsService = new SettingsService(appSettings);
|
||||
const result = await settingsService.loadSettings();
|
||||
expect(result).to.deep.equal(settingsService.settings);
|
||||
expect(settingsService.settings.logLevel).to.equal("debug");
|
||||
expect(settingsService.settings.apiBaseUrl).to.equal("http://localhost");
|
||||
});
|
||||
});
|
||||
describe("reloadSettings", () => {
|
||||
it("should call loadSettings", async () => {
|
||||
const dbSettings = { logLevel: "debug", apiBaseUrl: "http://localhost" };
|
||||
const appSettings = { findOne: sinon.stub().returns(dbSettings) };
|
||||
const settingsService = new SettingsService(appSettings);
|
||||
settingsService.settings = {};
|
||||
const result = await settingsService.reloadSettings();
|
||||
expect(result).to.deep.equal(dbSettings);
|
||||
});
|
||||
});
|
||||
describe("getSettings", () => {
|
||||
it("should return the current settings", () => {
|
||||
const dbSettings = { logLevel: "debug", apiBaseUrl: "http://localhost" };
|
||||
const appSettings = { findOne: sinon.stub().returns(dbSettings) };
|
||||
const settingsService = new SettingsService(appSettings);
|
||||
settingsService.settings = dbSettings;
|
||||
const result = settingsService.getSettings();
|
||||
expect(result).to.deep.equal(dbSettings);
|
||||
});
|
||||
it("should throw an error if settings have not been loaded", () => {
|
||||
const appSettings = { findOne: sinon.stub().returns(null) };
|
||||
const settingsService = new SettingsService(appSettings);
|
||||
settingsService.settings = null;
|
||||
|
||||
try {
|
||||
settingsService.getSettings();
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("Settings have not been loaded");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -62,7 +62,6 @@ describe("calculatePercentile", () => {
|
||||
const percentile = 100;
|
||||
const result = calculatePercentile(checks, percentile);
|
||||
const expected = 50;
|
||||
console.log(result);
|
||||
expect(result).to.equal(expected);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user