add gitignore
This commit is contained in:
1 parent
e4e75632c5
commit
d8ed9abebf
49 files changed
+590
-9780
No files matched your search
@@ -1,168 +0,0 @@
|
||||
import sinon from "sinon";
|
||||
import EmailService from "../../service/emailService.js";
|
||||
|
||||
describe("EmailService - Constructor", function () {
|
||||
let settingsServiceMock;
|
||||
let fsMock;
|
||||
let pathMock;
|
||||
let compileMock;
|
||||
let mjml2htmlMock;
|
||||
let nodemailerMock;
|
||||
let loggerMock;
|
||||
|
||||
beforeEach(function () {
|
||||
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(function () {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should initialize template loaders and email transporter", function () {
|
||||
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", function () {
|
||||
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;
|
||||
expect(loggerMock.error.firstCall.args[0].message).to.equal("File read error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("EmailService - buildAndSendEmail", function () {
|
||||
let settingsServiceMock;
|
||||
let fsMock;
|
||||
let pathMock;
|
||||
let compileMock;
|
||||
let mjml2htmlMock;
|
||||
let nodemailerMock;
|
||||
let loggerMock;
|
||||
let emailService;
|
||||
|
||||
beforeEach(function () {
|
||||
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(function () {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should build and send email successfully", async function () {
|
||||
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 function () {
|
||||
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].message).to.equal("MJML error");
|
||||
});
|
||||
|
||||
it("should log error if sending email fails", async function () {
|
||||
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].message).to.equal("SMTP error");
|
||||
});
|
||||
|
||||
it("should log error if both building HTML and sending email fail", async function () {
|
||||
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].message).to.equal("MJML error");
|
||||
expect(loggerMock.error.getCall(1).args[0].message).to.equal("SMTP error");
|
||||
});
|
||||
|
||||
it("should log an error if buildHtml fails", async function () {});
|
||||
});
|
||||
@@ -1,813 +0,0 @@
|
||||
import sinon from "sinon";
|
||||
import JobQueue from "../../service/jobQueue.js";
|
||||
import { log } from "console";
|
||||
|
||||
class QueueStub {
|
||||
constructor(queueName, options) {
|
||||
this.queueName = queueName;
|
||||
this.options = options;
|
||||
this.workers = [];
|
||||
this.jobs = [];
|
||||
}
|
||||
|
||||
// Add any methods that are expected to be called on the Queue instance
|
||||
add(job) {
|
||||
this.jobs.push(job);
|
||||
}
|
||||
|
||||
removeRepeatable(id) {
|
||||
const removedJob = this.jobs.find((job) => job.data._id === id);
|
||||
this.jobs = this.jobs.filter((job) => job.data._id !== id);
|
||||
if (removedJob) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
getRepeatableJobs() {
|
||||
return this.jobs;
|
||||
}
|
||||
async getJobs() {
|
||||
return this.jobs;
|
||||
}
|
||||
|
||||
async pause() {
|
||||
return true;
|
||||
}
|
||||
|
||||
async obliterate() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class WorkerStub {
|
||||
constructor(QUEUE_NAME, workerTask) {
|
||||
this.queueName = QUEUE_NAME;
|
||||
this.workerTask = async () => workerTask({ data: { _id: 1 } });
|
||||
}
|
||||
|
||||
async close() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
describe("JobQueue", function () {
|
||||
let settingsService, logger, db, networkService, statusService, notificationService, jobQueue;
|
||||
|
||||
beforeEach(async function () {
|
||||
settingsService = { getSettings: sinon.stub() };
|
||||
statusService = { updateStatus: sinon.stub() };
|
||||
notificationService = { handleNotifications: sinon.stub() };
|
||||
|
||||
logger = { error: sinon.stub(), info: sinon.stub() };
|
||||
db = {
|
||||
getAllMonitors: sinon.stub().returns([]),
|
||||
getMaintenanceWindowsByMonitorId: sinon.stub().returns([]),
|
||||
};
|
||||
networkService = { getStatus: sinon.stub() };
|
||||
jobQueue = await JobQueue.createJobQueue(db, networkService, statusService, notificationService, settingsService, logger, QueueStub, WorkerStub);
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
describe("createJobQueue", function () {
|
||||
it("should create a new JobQueue and add jobs for active monitors", async function () {
|
||||
db.getAllMonitors.returns([
|
||||
{ id: 1, isActive: true },
|
||||
{ id: 2, isActive: true },
|
||||
]);
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
// There should be double the jobs, as one is meant to be instantly executed
|
||||
// And one is meant to be enqueued
|
||||
expect(jobQueue.queue.jobs.length).to.equal(4);
|
||||
});
|
||||
|
||||
it("should reject with an error if an error occurs", async function () {
|
||||
db.getAllMonitors.throws("Error");
|
||||
try {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("JobQueue");
|
||||
expect(error.method).to.equal("createJobQueue");
|
||||
}
|
||||
});
|
||||
|
||||
it("should reject with an error if an error occurs, should not overwrite error data", async function () {
|
||||
const error = new Error("Error");
|
||||
error.service = "otherService";
|
||||
error.method = "otherMethod";
|
||||
db.getAllMonitors.throws(error);
|
||||
|
||||
try {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("otherService");
|
||||
expect(error.method).to.equal("otherMethod");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Constructor", function () {
|
||||
it("should construct a new JobQueue with default port and host if not provided", async function () {
|
||||
settingsService.getSettings.returns({});
|
||||
|
||||
expect(jobQueue.connection.host).to.equal("127.0.0.1");
|
||||
expect(jobQueue.connection.port).to.equal(6379);
|
||||
});
|
||||
|
||||
it("should construct a new JobQueue with provided port and host", async function () {
|
||||
settingsService.getSettings.returns({ redisHost: "localhost", redisPort: 1234 });
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
expect(jobQueue.connection.host).to.equal("localhost");
|
||||
expect(jobQueue.connection.port).to.equal(1234);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isMaintenanceWindow", function () {
|
||||
it("should throw an error if error occurs", async function () {
|
||||
db.getMaintenanceWindowsByMonitorId.throws("Error");
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
try {
|
||||
jobQueue.isInMaintenanceWindow(1);
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("JobQueue");
|
||||
expect(error.method).to.equal("createWorker");
|
||||
}
|
||||
});
|
||||
|
||||
it("should return true if in maintenance window with no repeat", async function () {
|
||||
db.getMaintenanceWindowsByMonitorId.returns([
|
||||
{
|
||||
active: true,
|
||||
start: new Date(Date.now() - 1000).toISOString(),
|
||||
end: new Date(Date.now() + 1000).toISOString(),
|
||||
repeat: 0,
|
||||
},
|
||||
]);
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
const inWindow = await jobQueue.isInMaintenanceWindow(1);
|
||||
expect(inWindow).to.be.true;
|
||||
});
|
||||
|
||||
it("should return true if in maintenance window with repeat", async function () {
|
||||
db.getMaintenanceWindowsByMonitorId.returns([
|
||||
{
|
||||
active: true,
|
||||
start: new Date(Date.now() - 10000).toISOString(),
|
||||
end: new Date(Date.now() - 5000).toISOString(),
|
||||
repeat: 1000,
|
||||
},
|
||||
]);
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
const inWindow = await jobQueue.isInMaintenanceWindow(1);
|
||||
expect(inWindow).to.be.true;
|
||||
});
|
||||
|
||||
it("should return false if in end < start", async function () {
|
||||
db.getMaintenanceWindowsByMonitorId.returns([
|
||||
{
|
||||
active: true,
|
||||
start: new Date(Date.now() - 5000).toISOString(),
|
||||
end: new Date(Date.now() - 10000).toISOString(),
|
||||
repeat: 1000,
|
||||
},
|
||||
]);
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
const inWindow = await jobQueue.isInMaintenanceWindow(1);
|
||||
expect(inWindow).to.be.false;
|
||||
});
|
||||
|
||||
it("should return false if not in maintenance window", async function () {
|
||||
db.getMaintenanceWindowsByMonitorId.returns([
|
||||
{
|
||||
active: false,
|
||||
start: new Date(Date.now() - 5000).toISOString(),
|
||||
end: new Date(Date.now() - 10000).toISOString(),
|
||||
repeat: 1000,
|
||||
},
|
||||
]);
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
const inWindow = await jobQueue.isInMaintenanceWindow(1);
|
||||
expect(inWindow).to.be.false;
|
||||
});
|
||||
});
|
||||
|
||||
describe("createJobHandler", function () {
|
||||
it("resolve to an error if an error is thrown within", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
jobQueue.isInMaintenanceWindow = sinon.stub().throws("Error");
|
||||
try {
|
||||
const handler = jobQueue.createJobHandler();
|
||||
await handler({ data: { _id: 1 } });
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("JobQueue");
|
||||
expect(error.details).to.equal(`Error processing job 1: Error`);
|
||||
}
|
||||
});
|
||||
|
||||
it("should log info if job is in maintenance window", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
jobQueue.isInMaintenanceWindow = sinon.stub().returns(true);
|
||||
const handler = jobQueue.createJobHandler();
|
||||
await handler({ data: { _id: 1 } });
|
||||
expect(logger.info.calledOnce).to.be.true;
|
||||
expect(logger.info.firstCall.args[0].message).to.equal("Monitor 1 is in maintenance window");
|
||||
});
|
||||
|
||||
it("should return if status has not changed", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
jobQueue.isInMaintenanceWindow = sinon.stub().returns(false);
|
||||
statusService.updateStatus = sinon.stub().returns({ statusChanged: false });
|
||||
const handler = jobQueue.createJobHandler();
|
||||
await handler({ data: { _id: 1 } });
|
||||
expect(jobQueue.notificationService.handleNotifications.notCalled).to.be.true;
|
||||
});
|
||||
|
||||
it("should return if status has changed, but prevStatus was undefined (monitor paused)", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
jobQueue.isInMaintenanceWindow = sinon.stub().returns(false);
|
||||
statusService.updateStatus = sinon.stub().returns({ statusChanged: true, prevStatus: undefined });
|
||||
const handler = jobQueue.createJobHandler();
|
||||
await handler({ data: { _id: 1 } });
|
||||
expect(jobQueue.notificationService.handleNotifications.notCalled).to.be.true;
|
||||
});
|
||||
|
||||
it("should call notification service if status changed and monitor was not paused", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
jobQueue.isInMaintenanceWindow = sinon.stub().returns(false);
|
||||
statusService.updateStatus = sinon.stub().returns({ statusChanged: true, prevStatus: false });
|
||||
const handler = jobQueue.createJobHandler();
|
||||
await handler({ data: { _id: 1 } });
|
||||
expect(jobQueue.notificationService.handleNotifications.calledOnce).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("getWorkerStats", function () {
|
||||
it("should throw an error if getRepeatable Jobs fails", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
jobQueue.queue.getRepeatableJobs = async () => {
|
||||
throw new Error("Error");
|
||||
};
|
||||
try {
|
||||
const stats = await jobQueue.getWorkerStats();
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("JobQueue");
|
||||
expect(error.method).to.equal("getWorkerStats");
|
||||
}
|
||||
});
|
||||
|
||||
it("should throw an error if getRepeatable Jobs fails but respect existing error data", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
jobQueue.queue.getRepeatableJobs = async () => {
|
||||
const error = new Error("Existing Error");
|
||||
error.service = "otherService";
|
||||
error.method = "otherMethod";
|
||||
throw error;
|
||||
};
|
||||
try {
|
||||
await jobQueue.getWorkerStats();
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("otherService");
|
||||
expect(error.method).to.equal("otherMethod");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("scaleWorkers", function () {
|
||||
it("should scale workers to 5 if no workers", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
expect(jobQueue.workers.length).to.equal(5);
|
||||
});
|
||||
|
||||
it("should scale workers up", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
jobQueue.scaleWorkers({
|
||||
load: 100,
|
||||
jobs: Array.from({ length: 100 }, (_, i) => i + 1),
|
||||
});
|
||||
expect(jobQueue.workers.length).to.equal(20);
|
||||
});
|
||||
|
||||
it("should scale workers down, even with error of worker.close fails", async function () {
|
||||
WorkerStub.prototype.close = async () => {
|
||||
throw new Error("Error");
|
||||
};
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
await jobQueue.scaleWorkers({
|
||||
load: 100,
|
||||
jobs: Array.from({ length: 100 }, (_, i) => i + 1),
|
||||
});
|
||||
|
||||
const res = await jobQueue.scaleWorkers({
|
||||
load: 0,
|
||||
jobs: [],
|
||||
});
|
||||
expect(jobQueue.workers.length).to.equal(5);
|
||||
});
|
||||
|
||||
it("should scale workers down", async function () {
|
||||
WorkerStub.prototype.close = async () => {
|
||||
return true;
|
||||
};
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
await jobQueue.scaleWorkers({
|
||||
load: 40,
|
||||
jobs: Array.from({ length: 40 }, (_, i) => i + 1),
|
||||
});
|
||||
|
||||
const res = await jobQueue.scaleWorkers({
|
||||
load: 0,
|
||||
jobs: [],
|
||||
});
|
||||
expect(jobQueue.workers.length).to.equal(5);
|
||||
});
|
||||
|
||||
it("should return false if scaling doesn't happen", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
const res = await jobQueue.scaleWorkers({ load: 5 });
|
||||
expect(jobQueue.workers.length).to.equal(5);
|
||||
expect(res).to.be.false;
|
||||
});
|
||||
});
|
||||
|
||||
describe("getJobs", function () {
|
||||
it("should return jobs", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
const jobs = await jobQueue.getJobs();
|
||||
expect(jobs.length).to.equal(0);
|
||||
});
|
||||
|
||||
it("should throw an error if getRepeatableJobs fails", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
try {
|
||||
jobQueue.queue.getRepeatableJobs = async () => {
|
||||
throw new Error("error");
|
||||
};
|
||||
|
||||
await jobQueue.getJobs(true);
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("JobQueue");
|
||||
expect(error.method).to.equal("getJobs");
|
||||
}
|
||||
});
|
||||
|
||||
it("should throw an error if getRepeatableJobs fails but respect existing error data", async function () {
|
||||
const jobQueue = await JobQueue.createJobQueue(
|
||||
db,
|
||||
networkService,
|
||||
statusService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
logger,
|
||||
QueueStub,
|
||||
WorkerStub
|
||||
);
|
||||
try {
|
||||
jobQueue.queue.getRepeatableJobs = async () => {
|
||||
const error = new Error("Existing error");
|
||||
error.service = "otherService";
|
||||
error.method = "otherMethod";
|
||||
throw error;
|
||||
};
|
||||
|
||||
await jobQueue.getJobs(true);
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("otherService");
|
||||
expect(error.method).to.equal("otherMethod");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("getJobStats", function () {
|
||||
it("should return job stats for no jobs", async function () {
|
||||
const jobStats = await jobQueue.getJobStats();
|
||||
expect(jobStats).to.deep.equal({ jobs: [], workers: 5 });
|
||||
});
|
||||
|
||||
it("should return job stats for jobs", async function () {
|
||||
jobQueue.queue.getJobs = async () => {
|
||||
return [{ data: { url: "test" }, getState: async () => "completed" }];
|
||||
};
|
||||
const jobStats = await jobQueue.getJobStats();
|
||||
expect(jobStats).to.deep.equal({
|
||||
jobs: [{ url: "test", state: "completed" }],
|
||||
workers: 5,
|
||||
});
|
||||
});
|
||||
|
||||
it("should reject with an error if mapping jobs fails", async function () {
|
||||
jobQueue.queue.getJobs = async () => {
|
||||
return [
|
||||
{
|
||||
data: { url: "test" },
|
||||
getState: async () => {
|
||||
throw new Error("Mapping Error");
|
||||
},
|
||||
},
|
||||
];
|
||||
};
|
||||
try {
|
||||
await jobQueue.getJobStats();
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("Mapping Error");
|
||||
expect(error.service).to.equal("JobQueue");
|
||||
expect(error.method).to.equal("getJobStats");
|
||||
}
|
||||
});
|
||||
|
||||
it("should reject with an error if mapping jobs fails but respect existing error data", async function () {
|
||||
jobQueue.queue.getJobs = async () => {
|
||||
return [
|
||||
{
|
||||
data: { url: "test" },
|
||||
getState: async () => {
|
||||
const error = new Error("Mapping Error");
|
||||
error.service = "otherService";
|
||||
error.method = "otherMethod";
|
||||
throw error;
|
||||
},
|
||||
},
|
||||
];
|
||||
};
|
||||
try {
|
||||
await jobQueue.getJobStats();
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("Mapping Error");
|
||||
expect(error.service).to.equal("otherService");
|
||||
expect(error.method).to.equal("otherMethod");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("addJob", function () {
|
||||
it("should add a job to the queue", async function () {
|
||||
jobQueue.addJob("test", { url: "test" });
|
||||
expect(jobQueue.queue.jobs.length).to.equal(1);
|
||||
});
|
||||
|
||||
it("should reject with an error if adding fails", async function () {
|
||||
jobQueue.queue.add = async () => {
|
||||
throw new Error("Error adding job");
|
||||
};
|
||||
try {
|
||||
await jobQueue.addJob("test", { url: "test" });
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("Error adding job");
|
||||
expect(error.service).to.equal("JobQueue");
|
||||
expect(error.method).to.equal("addJob");
|
||||
}
|
||||
});
|
||||
|
||||
it("should reject with an error if adding fails but respect existing error data", async function () {
|
||||
jobQueue.queue.add = async () => {
|
||||
const error = new Error("Error adding job");
|
||||
error.service = "otherService";
|
||||
error.method = "otherMethod";
|
||||
throw error;
|
||||
};
|
||||
try {
|
||||
await jobQueue.addJob("test", { url: "test" });
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("Error adding job");
|
||||
expect(error.service).to.equal("otherService");
|
||||
expect(error.method).to.equal("otherMethod");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteJob", function () {
|
||||
it("should delete a job from the queue", async function () {
|
||||
jobQueue.getWorkerStats = sinon.stub().returns({ load: 1, jobs: [{}] });
|
||||
jobQueue.scaleWorkers = sinon.stub();
|
||||
const monitor = { _id: 1 };
|
||||
const job = { data: monitor };
|
||||
jobQueue.queue.jobs = [job];
|
||||
await jobQueue.deleteJob(monitor);
|
||||
// expect(jobQueue.queue.jobs.length).to.equal(0);
|
||||
// expect(logger.info.calledOnce).to.be.true;
|
||||
// expect(jobQueue.getWorkerStats.calledOnce).to.be.true;
|
||||
// expect(jobQueue.scaleWorkers.calledOnce).to.be.true;
|
||||
});
|
||||
|
||||
it("should log an error if job is not found", async function () {
|
||||
jobQueue.getWorkerStats = sinon.stub().returns({ load: 1, jobs: [{}] });
|
||||
jobQueue.scaleWorkers = sinon.stub();
|
||||
const monitor = { _id: 1 };
|
||||
const job = { data: monitor };
|
||||
jobQueue.queue.jobs = [job];
|
||||
await jobQueue.deleteJob({ id_: 2 });
|
||||
expect(logger.error.calledOnce).to.be.true;
|
||||
});
|
||||
|
||||
it("should reject with an error if removeRepeatable fails", async function () {
|
||||
jobQueue.queue.removeRepeatable = async () => {
|
||||
const error = new Error("removeRepeatable error");
|
||||
throw error;
|
||||
};
|
||||
|
||||
try {
|
||||
await jobQueue.deleteJob({ _id: 1 });
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("removeRepeatable error");
|
||||
expect(error.service).to.equal("JobQueue");
|
||||
expect(error.method).to.equal("deleteJob");
|
||||
}
|
||||
});
|
||||
|
||||
it("should reject with an error if removeRepeatable fails but respect existing error data", async function () {
|
||||
jobQueue.queue.removeRepeatable = async () => {
|
||||
const error = new Error("removeRepeatable error");
|
||||
error.service = "otherService";
|
||||
error.method = "otherMethod";
|
||||
throw error;
|
||||
};
|
||||
|
||||
try {
|
||||
await jobQueue.deleteJob({ _id: 1 });
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("removeRepeatable error");
|
||||
expect(error.service).to.equal("otherService");
|
||||
expect(error.method).to.equal("otherMethod");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("getMetrics", function () {
|
||||
it("should return metrics for the job queue", async function () {
|
||||
jobQueue.queue.getWaitingCount = async () => 1;
|
||||
jobQueue.queue.getActiveCount = async () => 2;
|
||||
jobQueue.queue.getCompletedCount = async () => 3;
|
||||
jobQueue.queue.getFailedCount = async () => 4;
|
||||
jobQueue.queue.getDelayedCount = async () => 5;
|
||||
jobQueue.queue.getRepeatableJobs = async () => [1, 2, 3];
|
||||
const metrics = await jobQueue.getMetrics();
|
||||
expect(metrics).to.deep.equal({
|
||||
waiting: 1,
|
||||
active: 2,
|
||||
completed: 3,
|
||||
failed: 4,
|
||||
delayed: 5,
|
||||
repeatableJobs: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it("should log an error if metrics operations fail", async function () {
|
||||
jobQueue.queue.getWaitingCount = async () => {
|
||||
throw new Error("Error");
|
||||
};
|
||||
await jobQueue.getMetrics();
|
||||
expect(logger.error.calledOnce).to.be.true;
|
||||
expect(logger.error.firstCall.args[0].message).to.equal("Error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("obliterate", function () {
|
||||
it("should return true if obliteration is successful", async function () {
|
||||
jobQueue.queue.pause = async () => true;
|
||||
jobQueue.getJobs = async () => [{ key: 1, id: 1 }];
|
||||
jobQueue.queue.removeRepeatableByKey = async () => true;
|
||||
jobQueue.queue.remove = async () => true;
|
||||
jobQueue.queue.obliterate = async () => true;
|
||||
const obliteration = await jobQueue.obliterate();
|
||||
expect(obliteration).to.be.true;
|
||||
});
|
||||
|
||||
it("should throw an error if obliteration fails", async function () {
|
||||
jobQueue.getMetrics = async () => {
|
||||
throw new Error("Error");
|
||||
};
|
||||
|
||||
try {
|
||||
await jobQueue.obliterate();
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("JobQueue");
|
||||
expect(error.method).to.equal("obliterate");
|
||||
}
|
||||
});
|
||||
|
||||
it("should throw an error if obliteration fails but respect existing error data", async function () {
|
||||
jobQueue.getMetrics = async () => {
|
||||
const error = new Error("Error");
|
||||
error.service = "otherService";
|
||||
error.method = "otherMethod";
|
||||
throw error;
|
||||
};
|
||||
|
||||
try {
|
||||
await jobQueue.obliterate();
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("otherService");
|
||||
expect(error.method).to.equal("otherMethod");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,439 +0,0 @@
|
||||
import sinon from "sinon";
|
||||
import NetworkService from "../../service/networkService.js";
|
||||
import { expect } from "chai";
|
||||
import http from "http";
|
||||
import { errorMessages } from "../../utils/messages.js";
|
||||
describe("Network Service", function () {
|
||||
let axios, ping, Docker, logger, networkService;
|
||||
|
||||
beforeEach(function () {
|
||||
axios = {
|
||||
get: sinon.stub().resolves({
|
||||
data: { foo: "bar" },
|
||||
status: 200,
|
||||
}),
|
||||
};
|
||||
Docker = class {
|
||||
listContainers = sinon.stub().resolves([
|
||||
{
|
||||
Names: ["http://test.com"],
|
||||
Id: "http://test.com",
|
||||
},
|
||||
]);
|
||||
getContainer = sinon.stub().returns({
|
||||
inspect: sinon.stub().resolves({ State: { Status: "running" } }),
|
||||
});
|
||||
};
|
||||
ping = {
|
||||
promise: {
|
||||
probe: sinon.stub().resolves({ response: { alive: true }, responseTime: 100, alive: true }),
|
||||
},
|
||||
};
|
||||
logger = { error: sinon.stub() };
|
||||
networkService = new NetworkService(axios, ping, logger, http, Docker);
|
||||
});
|
||||
|
||||
describe("constructor", function () {
|
||||
it("should create a new NetworkService instance", function () {
|
||||
const networkService = new NetworkService();
|
||||
expect(networkService).to.be.an.instanceOf(NetworkService);
|
||||
});
|
||||
});
|
||||
|
||||
describe("timeRequest", function () {
|
||||
it("should time an asynchronous operation", async function () {
|
||||
const operation = sinon.stub().resolves("success");
|
||||
const { response, responseTime } = await networkService.timeRequest(operation);
|
||||
expect(response).to.equal("success");
|
||||
expect(responseTime).to.be.a("number");
|
||||
});
|
||||
|
||||
it("should handle errors if operation throws error", async function () {
|
||||
const error = new Error("Test error");
|
||||
const operation = sinon.stub().throws(error);
|
||||
const { response, responseTime } = await networkService.timeRequest(operation);
|
||||
expect(response).to.be.null;
|
||||
expect(responseTime).to.be.a("number");
|
||||
expect(error.message).to.equal("Test error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("requestPing", function () {
|
||||
it("should return a response object if ping successful", async function () {
|
||||
const pingResult = await networkService.requestPing({
|
||||
data: { url: "http://test.com", _id: "123" },
|
||||
});
|
||||
expect(pingResult.monitorId).to.equal("123");
|
||||
expect(pingResult.type).to.equal("ping");
|
||||
expect(pingResult.responseTime).to.be.a("number");
|
||||
expect(pingResult.status).to.be.true;
|
||||
});
|
||||
|
||||
it("should return a response object if ping unsuccessful", async function () {
|
||||
const error = new Error("Test error");
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const pingResult = await networkService.requestPing({
|
||||
data: { url: "http://test.com", _id: "123" },
|
||||
});
|
||||
expect(pingResult.monitorId).to.equal("123");
|
||||
expect(pingResult.type).to.equal("ping");
|
||||
expect(pingResult.responseTime).to.be.a("number");
|
||||
expect(pingResult.status).to.be.false;
|
||||
expect(pingResult.code).to.equal(networkService.PING_ERROR);
|
||||
});
|
||||
|
||||
it("should throw an error if ping cannot resolve", async function () {
|
||||
const error = new Error("test error");
|
||||
networkService.timeRequest = sinon.stub().throws(error);
|
||||
try {
|
||||
await networkService.requestPing({
|
||||
data: { url: "http://test.com", _id: "123" },
|
||||
});
|
||||
} catch (error) {
|
||||
expect(error).to.exist;
|
||||
expect(error.method).to.equal("requestPing");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("requestHttp", function () {
|
||||
it("should return a response object if http successful", async function () {
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "http" } };
|
||||
const httpResult = await networkService.requestHttp(job);
|
||||
expect(httpResult.monitorId).to.equal("123");
|
||||
expect(httpResult.type).to.equal("http");
|
||||
expect(httpResult.responseTime).to.be.a("number");
|
||||
expect(httpResult.status).to.be.true;
|
||||
});
|
||||
|
||||
it("should return a response object if http unsuccessful", async function () {
|
||||
const error = new Error("Test error");
|
||||
error.response = { status: 404 };
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "http" } };
|
||||
const httpResult = await networkService.requestHttp(job);
|
||||
expect(httpResult.monitorId).to.equal("123");
|
||||
expect(httpResult.type).to.equal("http");
|
||||
expect(httpResult.responseTime).to.be.a("number");
|
||||
expect(httpResult.status).to.be.false;
|
||||
expect(httpResult.code).to.equal(404);
|
||||
});
|
||||
|
||||
it("should return a response object if http unsuccessful with unknown code", async function () {
|
||||
const error = new Error("Test error");
|
||||
error.response = {};
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "http" } };
|
||||
const httpResult = await networkService.requestHttp(job);
|
||||
expect(httpResult.monitorId).to.equal("123");
|
||||
expect(httpResult.type).to.equal("http");
|
||||
expect(httpResult.responseTime).to.be.a("number");
|
||||
expect(httpResult.status).to.be.false;
|
||||
expect(httpResult.code).to.equal(networkService.NETWORK_ERROR);
|
||||
});
|
||||
|
||||
it("should throw an error if an error occurs", async function () {
|
||||
const error = new Error("test error");
|
||||
networkService.timeRequest = sinon.stub().throws(error);
|
||||
try {
|
||||
await networkService.requestHttp({
|
||||
data: { url: "http://test.com", _id: "123" },
|
||||
});
|
||||
} catch (error) {
|
||||
expect(error).to.exist;
|
||||
expect(error.method).to.equal("requestHttp");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("requestPagespeed", function () {
|
||||
it("should return a response object if pagespeed successful", async function () {
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } };
|
||||
const pagespeedResult = await networkService.requestPagespeed(job);
|
||||
expect(pagespeedResult.monitorId).to.equal("123");
|
||||
expect(pagespeedResult.type).to.equal("pagespeed");
|
||||
expect(pagespeedResult.responseTime).to.be.a("number");
|
||||
expect(pagespeedResult.status).to.be.true;
|
||||
});
|
||||
|
||||
it("should return a response object if pagespeed unsuccessful", async function () {
|
||||
const error = new Error("Test error");
|
||||
error.response = { status: 404 };
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } };
|
||||
const pagespeedResult = await networkService.requestPagespeed(job);
|
||||
expect(pagespeedResult.monitorId).to.equal("123");
|
||||
expect(pagespeedResult.type).to.equal("pagespeed");
|
||||
expect(pagespeedResult.responseTime).to.be.a("number");
|
||||
expect(pagespeedResult.status).to.be.false;
|
||||
expect(pagespeedResult.code).to.equal(404);
|
||||
});
|
||||
|
||||
it("should return a response object if pagespeed unsuccessful with an unknown code", async function () {
|
||||
const error = new Error("Test error");
|
||||
error.response = {};
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "pagespeed" } };
|
||||
const pagespeedResult = await networkService.requestPagespeed(job);
|
||||
expect(pagespeedResult.monitorId).to.equal("123");
|
||||
expect(pagespeedResult.type).to.equal("pagespeed");
|
||||
expect(pagespeedResult.responseTime).to.be.a("number");
|
||||
expect(pagespeedResult.status).to.be.false;
|
||||
expect(pagespeedResult.code).to.equal(networkService.NETWORK_ERROR);
|
||||
});
|
||||
|
||||
it("should throw an error if pagespeed cannot resolve", async function () {
|
||||
const error = new Error("test error");
|
||||
networkService.timeRequest = sinon.stub().throws(error);
|
||||
try {
|
||||
await networkService.requestPagespeed({
|
||||
data: { url: "http://test.com", _id: "123" },
|
||||
});
|
||||
} catch (error) {
|
||||
expect(error).to.exist;
|
||||
expect(error.method).to.equal("requestPagespeed");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("requestHardware", function () {
|
||||
it("should return a response object if hardware successful", async function () {
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } };
|
||||
const httpResult = await networkService.requestHardware(job);
|
||||
expect(httpResult.monitorId).to.equal("123");
|
||||
expect(httpResult.type).to.equal("hardware");
|
||||
expect(httpResult.responseTime).to.be.a("number");
|
||||
expect(httpResult.status).to.be.true;
|
||||
});
|
||||
|
||||
it("should return a response object if hardware successful and job has a secret", async function () {
|
||||
const job = {
|
||||
data: {
|
||||
url: "http://test.com",
|
||||
_id: "123",
|
||||
type: "hardware",
|
||||
secret: "my_secret",
|
||||
},
|
||||
};
|
||||
const httpResult = await networkService.requestHardware(job);
|
||||
expect(httpResult.monitorId).to.equal("123");
|
||||
expect(httpResult.type).to.equal("hardware");
|
||||
expect(httpResult.responseTime).to.be.a("number");
|
||||
expect(httpResult.status).to.be.true;
|
||||
});
|
||||
|
||||
it("should return a response object if hardware unsuccessful", async function () {
|
||||
const error = new Error("Test error");
|
||||
error.response = { status: 404 };
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } };
|
||||
const httpResult = await networkService.requestHardware(job);
|
||||
expect(httpResult.monitorId).to.equal("123");
|
||||
expect(httpResult.type).to.equal("hardware");
|
||||
expect(httpResult.responseTime).to.be.a("number");
|
||||
expect(httpResult.status).to.be.false;
|
||||
expect(httpResult.code).to.equal(404);
|
||||
});
|
||||
|
||||
it("should return a response object if hardware unsuccessful with unknown code", async function () {
|
||||
const error = new Error("Test error");
|
||||
error.response = {};
|
||||
networkService.timeRequest = sinon.stub().resolves({ response: null, responseTime: 1, error });
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "hardware" } };
|
||||
const httpResult = await networkService.requestHardware(job);
|
||||
expect(httpResult.monitorId).to.equal("123");
|
||||
expect(httpResult.type).to.equal("hardware");
|
||||
expect(httpResult.responseTime).to.be.a("number");
|
||||
expect(httpResult.status).to.be.false;
|
||||
expect(httpResult.code).to.equal(networkService.NETWORK_ERROR);
|
||||
});
|
||||
|
||||
it("should throw an error if hardware cannot resolve", async function () {
|
||||
const error = new Error("test error");
|
||||
networkService.timeRequest = sinon.stub().throws(error);
|
||||
try {
|
||||
await networkService.requestHardware({
|
||||
data: { url: "http://test.com", _id: "123" },
|
||||
});
|
||||
} catch (error) {
|
||||
expect(error).to.exist;
|
||||
expect(error.method).to.equal("requestHardware");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("requestDocker", function () {
|
||||
it("should return a response object if docker successful", async function () {
|
||||
const job = { data: { url: "http://test.com", _id: "123", type: "docker" } };
|
||||
const dockerResult = await networkService.requestDocker(job);
|
||||
expect(dockerResult.monitorId).to.equal("123");
|
||||
expect(dockerResult.type).to.equal("docker");
|
||||
expect(dockerResult.responseTime).to.be.a("number");
|
||||
expect(dockerResult.status).to.be.true;
|
||||
});
|
||||
|
||||
it("should return a response object with status false if container not running", async function () {
|
||||
Docker = class {
|
||||
listContainers = sinon.stub().resolves([
|
||||
{
|
||||
Names: ["/my_container"],
|
||||
Id: "abc123",
|
||||
},
|
||||
]);
|
||||
getContainer = sinon.stub().returns({
|
||||
inspect: sinon.stub().resolves({ State: { Status: "stopped" } }),
|
||||
});
|
||||
};
|
||||
networkService = new NetworkService(axios, ping, logger, http, Docker);
|
||||
const job = { data: { url: "abc123", _id: "123", type: "docker" } };
|
||||
const dockerResult = await networkService.requestDocker(job);
|
||||
expect(dockerResult.status).to.be.false;
|
||||
expect(dockerResult.code).to.equal(200);
|
||||
});
|
||||
|
||||
it("should handle an error when fetching the container", async function () {
|
||||
Docker = class {
|
||||
listContainers = sinon.stub().resolves([
|
||||
{
|
||||
Names: ["/my_container"],
|
||||
Id: "abc123",
|
||||
},
|
||||
]);
|
||||
getContainer = sinon.stub().returns({
|
||||
inspect: sinon.stub().throws(new Error("test error")),
|
||||
});
|
||||
};
|
||||
networkService = new NetworkService(axios, ping, logger, http, Docker);
|
||||
const job = { data: { url: "abc123", _id: "123", type: "docker" } };
|
||||
const dockerResult = await networkService.requestDocker(job);
|
||||
expect(dockerResult.status).to.be.false;
|
||||
expect(dockerResult.code).to.equal(networkService.NETWORK_ERROR);
|
||||
});
|
||||
|
||||
it("should throw an error if operations fail", async function () {
|
||||
Docker = class {
|
||||
listContainers = sinon.stub().resolves([
|
||||
{
|
||||
Names: ["/my_container"],
|
||||
Id: "abc123",
|
||||
},
|
||||
]);
|
||||
getContainer = sinon.stub().throws(new Error("test error"));
|
||||
};
|
||||
networkService = new NetworkService(axios, ping, logger, http, Docker);
|
||||
const job = { data: { url: "abc123", _id: "123", type: "docker" } };
|
||||
try {
|
||||
await networkService.requestDocker(job);
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("test error");
|
||||
}
|
||||
});
|
||||
|
||||
it("should throw an error if no matching images found", async function () {
|
||||
Docker = class {
|
||||
listContainers = sinon.stub().resolves([]);
|
||||
getContainer = sinon.stub().throws(new Error("test error"));
|
||||
};
|
||||
networkService = new NetworkService(axios, ping, logger, http, Docker);
|
||||
const job = { data: { url: "abc123", _id: "123", type: "docker" } };
|
||||
try {
|
||||
await networkService.requestDocker(job);
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal(errorMessages.DOCKER_NOT_FOUND);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStatus", function () {
|
||||
beforeEach(function () {
|
||||
networkService.requestPing = sinon.stub();
|
||||
networkService.requestHttp = sinon.stub();
|
||||
networkService.requestPagespeed = sinon.stub();
|
||||
networkService.requestHardware = sinon.stub();
|
||||
networkService.requestDocker = sinon.stub();
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should call requestPing if type is ping", async function () {
|
||||
await networkService.getStatus({ data: { type: "ping" } });
|
||||
expect(networkService.requestPing.calledOnce).to.be.true;
|
||||
expect(networkService.requestDocker.notCalled).to.be.true;
|
||||
expect(networkService.requestHttp.notCalled).to.be.true;
|
||||
expect(networkService.requestPagespeed.notCalled).to.be.true;
|
||||
});
|
||||
|
||||
it("should call requestHttp if type is http", async function () {
|
||||
await networkService.getStatus({ data: { type: "http" } });
|
||||
expect(networkService.requestPing.notCalled).to.be.true;
|
||||
expect(networkService.requestDocker.notCalled).to.be.true;
|
||||
expect(networkService.requestHttp.calledOnce).to.be.true;
|
||||
expect(networkService.requestPagespeed.notCalled).to.be.true;
|
||||
});
|
||||
|
||||
it("should call requestPagespeed if type is pagespeed", async function () {
|
||||
await networkService.getStatus({ data: { type: "pagespeed" } });
|
||||
expect(networkService.requestPing.notCalled).to.be.true;
|
||||
expect(networkService.requestDocker.notCalled).to.be.true;
|
||||
expect(networkService.requestHttp.notCalled).to.be.true;
|
||||
expect(networkService.requestPagespeed.calledOnce).to.be.true;
|
||||
});
|
||||
|
||||
it("should call requestHardware if type is hardware", async function () {
|
||||
await networkService.getStatus({ data: { type: "hardware" } });
|
||||
expect(networkService.requestHardware.calledOnce).to.be.true;
|
||||
expect(networkService.requestDocker.notCalled).to.be.true;
|
||||
expect(networkService.requestPing.notCalled).to.be.true;
|
||||
expect(networkService.requestPagespeed.notCalled).to.be.true;
|
||||
});
|
||||
|
||||
it("should call requestDocker if type is Docker", async function () {
|
||||
await networkService.getStatus({ data: { type: "docker" } });
|
||||
expect(networkService.requestDocker.calledOnce).to.be.true;
|
||||
expect(networkService.requestHardware.notCalled).to.be.true;
|
||||
expect(networkService.requestPing.notCalled).to.be.true;
|
||||
expect(networkService.requestPagespeed.notCalled).to.be.true;
|
||||
});
|
||||
|
||||
it("should throw an error if an unknown type is provided", async function () {
|
||||
try {
|
||||
await networkService.getStatus({ data: { type: "unknown" } });
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("NetworkService");
|
||||
expect(error.method).to.equal("getStatus");
|
||||
expect(error.message).to.equal("Unsupported type: unknown");
|
||||
}
|
||||
});
|
||||
|
||||
it("should throw an error if job type is undefined", async function () {
|
||||
try {
|
||||
await networkService.getStatus({ data: { type: undefined } });
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("NetworkService");
|
||||
expect(error.method).to.equal("getStatus");
|
||||
expect(error.message).to.equal("Unsupported type: unknown");
|
||||
}
|
||||
});
|
||||
|
||||
it("should throw an error if job is empty", async function () {
|
||||
try {
|
||||
await networkService.getStatus({});
|
||||
} catch (error) {
|
||||
expect(error.method).to.equal("getStatus");
|
||||
expect(error.message).to.equal("Unsupported type: unknown");
|
||||
}
|
||||
});
|
||||
|
||||
it("should throw an error if job is null", async function () {
|
||||
try {
|
||||
await networkService.getStatus(null);
|
||||
} catch (error) {
|
||||
expect(error.service).to.equal("NetworkService");
|
||||
expect(error.method).to.equal("getStatus");
|
||||
expect(error.message).to.equal("Unsupported type: unknown");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,285 +0,0 @@
|
||||
import sinon from "sinon";
|
||||
import NotificationService from "../../service/notificationService.js";
|
||||
import { expect } from "chai";
|
||||
|
||||
describe("NotificationService", function () {
|
||||
let emailService, db, logger, notificationService;
|
||||
|
||||
beforeEach(function () {
|
||||
db = {
|
||||
getNotificationsByMonitorId: sinon.stub(),
|
||||
};
|
||||
emailService = {
|
||||
buildAndSendEmail: sinon.stub(),
|
||||
};
|
||||
logger = {
|
||||
warn: sinon.stub(),
|
||||
};
|
||||
|
||||
notificationService = new NotificationService(emailService, db, logger);
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
describe("constructor", function () {
|
||||
it("should create a new instance of NotificationService", function () {
|
||||
expect(notificationService).to.be.an.instanceOf(NotificationService);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendEmail", function () {
|
||||
it("should send an email notification with Up Template", async function () {
|
||||
const networkResponse = {
|
||||
monitor: {
|
||||
name: "Test Monitor",
|
||||
url: "http://test.com",
|
||||
},
|
||||
status: true,
|
||||
prevStatus: false,
|
||||
};
|
||||
const address = "test@test.com";
|
||||
await notificationService.sendEmail(networkResponse, address);
|
||||
expect(notificationService.emailService.buildAndSendEmail.calledOnce).to.be.true;
|
||||
expect(
|
||||
notificationService.emailService.buildAndSendEmail.calledWith("serverIsUpTemplate", { monitor: "Test Monitor", url: "http://test.com" })
|
||||
);
|
||||
});
|
||||
|
||||
it("should send an email notification with Down Template", async function () {
|
||||
const networkResponse = {
|
||||
monitor: {
|
||||
name: "Test Monitor",
|
||||
url: "http://test.com",
|
||||
},
|
||||
status: false,
|
||||
prevStatus: true,
|
||||
};
|
||||
const address = "test@test.com";
|
||||
await notificationService.sendEmail(networkResponse, address);
|
||||
expect(notificationService.emailService.buildAndSendEmail.calledOnce).to.be.true;
|
||||
});
|
||||
|
||||
it("should send an email notification with Up Template", async function () {
|
||||
const networkResponse = {
|
||||
monitor: {
|
||||
name: "Test Monitor",
|
||||
url: "http://test.com",
|
||||
},
|
||||
status: true,
|
||||
prevStatus: false,
|
||||
};
|
||||
const address = "test@test.com";
|
||||
await notificationService.sendEmail(networkResponse, address);
|
||||
expect(notificationService.emailService.buildAndSendEmail.calledOnce).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleNotifications", function () {
|
||||
it("should handle notifications based on the network response", async function () {
|
||||
notificationService.sendEmail = sinon.stub();
|
||||
const res = await notificationService.handleNotifications({
|
||||
monitor: {
|
||||
type: "email",
|
||||
address: "www.google.com",
|
||||
},
|
||||
});
|
||||
expect(res).to.be.true;
|
||||
});
|
||||
|
||||
it("should handle hardware notifications", async function () {
|
||||
notificationService.sendEmail = sinon.stub();
|
||||
const res = await notificationService.handleNotifications({
|
||||
monitor: {
|
||||
type: "hardware",
|
||||
address: "www.google.com",
|
||||
},
|
||||
});
|
||||
expect(res).to.be.true;
|
||||
});
|
||||
|
||||
it("should handle an error when getting notifications", async function () {
|
||||
const testError = new Error("Test Error");
|
||||
notificationService.db.getNotificationsByMonitorId.rejects(testError);
|
||||
await notificationService.handleNotifications({ monitorId: "123" });
|
||||
expect(notificationService.logger.warn.calledOnce).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendHardwareEmail", function () {
|
||||
let networkResponse, address, alerts;
|
||||
|
||||
beforeEach(function () {
|
||||
networkResponse = {
|
||||
monitor: {
|
||||
name: "Test Monitor",
|
||||
url: "http://test.com",
|
||||
},
|
||||
status: true,
|
||||
prevStatus: false,
|
||||
};
|
||||
address = "test@test.com";
|
||||
alerts = ["test"];
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should send an email notification with Hardware Template", async function () {
|
||||
emailService.buildAndSendEmail.resolves(true);
|
||||
const res = await notificationService.sendHardwareEmail(networkResponse, address, alerts);
|
||||
expect(res).to.be.true;
|
||||
});
|
||||
|
||||
it("should return false if no alerts are provided", async function () {
|
||||
alerts = [];
|
||||
emailService.buildAndSendEmail.resolves(true);
|
||||
const res = await notificationService.sendHardwareEmail(networkResponse, address, alerts);
|
||||
expect(res).to.be.false;
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleStatusNotifications", function () {
|
||||
let networkResponse;
|
||||
|
||||
beforeEach(function () {
|
||||
networkResponse = {
|
||||
monitor: {
|
||||
name: "Test Monitor",
|
||||
url: "http://test.com",
|
||||
},
|
||||
statusChanged: true,
|
||||
status: true,
|
||||
prevStatus: false,
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should handle status notifications", async function () {
|
||||
db.getNotificationsByMonitorId.resolves([{ type: "email", address: "test@test.com" }]);
|
||||
const res = await notificationService.handleStatusNotifications(networkResponse);
|
||||
expect(res).to.be.true;
|
||||
});
|
||||
|
||||
it("should return false if status hasn't changed", async function () {
|
||||
networkResponse.statusChanged = false;
|
||||
const res = await notificationService.handleStatusNotifications(networkResponse);
|
||||
expect(res).to.be.false;
|
||||
});
|
||||
|
||||
it("should return false if prevStatus is undefined", async function () {
|
||||
networkResponse.prevStatus = undefined;
|
||||
const res = await notificationService.handleStatusNotifications(networkResponse);
|
||||
expect(res).to.be.false;
|
||||
});
|
||||
|
||||
it("should handle an error", async function () {
|
||||
const testError = new Error("Test Error");
|
||||
db.getNotificationsByMonitorId.rejects(testError);
|
||||
try {
|
||||
await notificationService.handleStatusNotifications(networkResponse);
|
||||
} catch (error) {
|
||||
expect(error).to.be.an.instanceOf(Error);
|
||||
expect(error.message).to.equal("Test Error");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleHardwareNotifications", function () {
|
||||
let networkResponse;
|
||||
|
||||
beforeEach(function () {
|
||||
networkResponse = {
|
||||
monitor: {
|
||||
name: "Test Monitor",
|
||||
url: "http://test.com",
|
||||
thresholds: {
|
||||
usage_cpu: 1,
|
||||
usage_memory: 1,
|
||||
usage_disk: 1,
|
||||
},
|
||||
},
|
||||
payload: {
|
||||
data: {
|
||||
cpu: {
|
||||
usage_percent: 0.655,
|
||||
},
|
||||
memory: {
|
||||
usage_percent: 0.783,
|
||||
},
|
||||
disk: [
|
||||
{
|
||||
name: "/dev/sda1",
|
||||
usage_percent: 0.452,
|
||||
},
|
||||
{
|
||||
name: "/dev/sdb1",
|
||||
usage_percent: 0.627,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
describe("it should return false if no thresholds are set", function () {
|
||||
it("should return false if no thresholds are set", async function () {
|
||||
networkResponse.monitor.thresholds = undefined;
|
||||
const res = await notificationService.handleHardwareNotifications(networkResponse);
|
||||
expect(res).to.be.false;
|
||||
});
|
||||
|
||||
it("should return false if metrics are null", async function () {
|
||||
networkResponse.payload.data = null;
|
||||
const res = await notificationService.handleHardwareNotifications(networkResponse);
|
||||
expect(res).to.be.false;
|
||||
});
|
||||
|
||||
it("should return true if request is well formed and thresholds > 0", async function () {
|
||||
db.getNotificationsByMonitorId.resolves([
|
||||
{
|
||||
type: "email",
|
||||
address: "test@test.com",
|
||||
alertThreshold: 1,
|
||||
cpuAlertThreshold: 1,
|
||||
memoryAlertThreshold: 1,
|
||||
diskAlertThreshold: 1,
|
||||
save: sinon.stub().resolves(),
|
||||
},
|
||||
]);
|
||||
const res = await notificationService.handleHardwareNotifications(networkResponse);
|
||||
expect(res).to.be.true;
|
||||
});
|
||||
|
||||
it("should return true if thresholds are exceeded", async function () {
|
||||
db.getNotificationsByMonitorId.resolves([
|
||||
{
|
||||
type: "email",
|
||||
address: "test@test.com",
|
||||
alertThreshold: 1,
|
||||
cpuAlertThreshold: 1,
|
||||
memoryAlertThreshold: 1,
|
||||
diskAlertThreshold: 1,
|
||||
save: sinon.stub().resolves(),
|
||||
},
|
||||
]);
|
||||
networkResponse.monitor.thresholds = {
|
||||
usage_cpu: 0.01,
|
||||
usage_memory: 0.01,
|
||||
usage_disk: 0.01,
|
||||
};
|
||||
const res = await notificationService.handleHardwareNotifications(networkResponse);
|
||||
expect(res).to.be.true;
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,140 +0,0 @@
|
||||
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", function () {
|
||||
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", function () {
|
||||
it("should construct a new SettingsService", function () {
|
||||
const settingsService = new SettingsService(mockAppSettings);
|
||||
expect(settingsService.appSettings).to.equal(mockAppSettings);
|
||||
});
|
||||
});
|
||||
|
||||
describe("loadSettings", function () {
|
||||
it("should load settings from DB when environment variables are not set", async function () {
|
||||
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 function () {
|
||||
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 function () {
|
||||
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) {
|
||||
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", function () {
|
||||
it("should call loadSettings", async function () {
|
||||
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", function () {
|
||||
it("should return the current settings", function () {
|
||||
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", function () {
|
||||
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");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,255 +0,0 @@
|
||||
import sinon from "sinon";
|
||||
import StatusService from "../../service/statusService.js";
|
||||
import { afterEach, describe } from "node:test";
|
||||
|
||||
describe("StatusService", () => {
|
||||
let db, logger, statusService;
|
||||
|
||||
beforeEach(function () {
|
||||
db = {
|
||||
getMonitorById: sinon.stub(),
|
||||
createCheck: sinon.stub(),
|
||||
createPagespeedCheck: sinon.stub(),
|
||||
};
|
||||
logger = {
|
||||
info: sinon.stub(),
|
||||
error: sinon.stub(),
|
||||
};
|
||||
statusService = new StatusService(db, logger);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
describe("constructor", () => {
|
||||
it("should create an instance of StatusService", function () {
|
||||
expect(statusService).to.be.an.instanceOf(StatusService);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStatusString", () => {
|
||||
it("should return 'up' if status is true", function () {
|
||||
expect(statusService.getStatusString(true)).to.equal("up");
|
||||
});
|
||||
|
||||
it("should return 'down' if status is false", function () {
|
||||
expect(statusService.getStatusString(false)).to.equal("down");
|
||||
});
|
||||
|
||||
it("should return 'unknown' if status is undefined or null", function () {
|
||||
expect(statusService.getStatusString(undefined)).to.equal("unknown");
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateStatus", () => {
|
||||
beforeEach(function () {
|
||||
// statusService.insertCheck = sinon.stub().resolves;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
it("should throw an error if an error occurs", async function () {
|
||||
const error = new Error("Test error");
|
||||
statusService.db.getMonitorById = sinon.stub().throws(error);
|
||||
try {
|
||||
await statusService.updateStatus({ monitorId: "test", status: true });
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal("Test error");
|
||||
}
|
||||
// expect(statusService.insertCheck.calledOnce).to.be.true;
|
||||
});
|
||||
|
||||
it("should return {statusChanged: false} if status hasn't changed", async function () {
|
||||
statusService.db.getMonitorById = sinon.stub().returns({ status: true });
|
||||
const result = await statusService.updateStatus({
|
||||
monitorId: "test",
|
||||
status: true,
|
||||
});
|
||||
expect(result).to.deep.equal({ statusChanged: false });
|
||||
// expect(statusService.insertCheck.calledOnce).to.be.true;
|
||||
});
|
||||
|
||||
it("should return {statusChanged: true} if status has changed from down to up", async function () {
|
||||
statusService.db.getMonitorById = sinon.stub().returns({ status: false, save: sinon.stub() });
|
||||
const result = await statusService.updateStatus({
|
||||
monitorId: "test",
|
||||
status: true,
|
||||
});
|
||||
expect(result.statusChanged).to.be.true;
|
||||
expect(result.monitor.status).to.be.true;
|
||||
expect(result.prevStatus).to.be.false;
|
||||
// expect(statusService.insertCheck.calledOnce).to.be.true;
|
||||
});
|
||||
|
||||
it("should return {statusChanged: true} if status has changed from up to down", async function () {
|
||||
statusService.db.getMonitorById = sinon.stub().returns({ status: true, save: sinon.stub() });
|
||||
const result = await statusService.updateStatus({
|
||||
monitorId: "test",
|
||||
status: false,
|
||||
});
|
||||
expect(result.statusChanged).to.be.true;
|
||||
expect(result.monitor.status).to.be.false;
|
||||
expect(result.prevStatus).to.be.true;
|
||||
// expect(statusService.insertCheck.calledOnce).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCheck", () => {
|
||||
it("should build a check object", function () {
|
||||
const check = statusService.buildCheck({
|
||||
monitorId: "test",
|
||||
type: "test",
|
||||
status: true,
|
||||
responseTime: 100,
|
||||
code: 200,
|
||||
message: "Test message",
|
||||
payload: { test: "test" },
|
||||
});
|
||||
expect(check.monitorId).to.equal("test");
|
||||
expect(check.status).to.be.true;
|
||||
expect(check.statusCode).to.equal(200);
|
||||
expect(check.responseTime).to.equal(100);
|
||||
expect(check.message).to.equal("Test message");
|
||||
});
|
||||
|
||||
it("should build a check object for pagespeed type", function () {
|
||||
const check = statusService.buildCheck({
|
||||
monitorId: "test",
|
||||
type: "pagespeed",
|
||||
status: true,
|
||||
responseTime: 100,
|
||||
code: 200,
|
||||
message: "Test message",
|
||||
payload: {
|
||||
lighthouseResult: {
|
||||
categories: {
|
||||
accessibility: { score: 1 },
|
||||
"best-practices": { score: 1 },
|
||||
performance: { score: 1 },
|
||||
seo: { score: 1 },
|
||||
},
|
||||
audits: {
|
||||
"cumulative-layout-shift": { score: 1 },
|
||||
"speed-index": { score: 1 },
|
||||
"first-contentful-paint": { score: 1 },
|
||||
"largest-contentful-paint": { score: 1 },
|
||||
"total-blocking-time": { score: 1 },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(check.monitorId).to.equal("test");
|
||||
expect(check.status).to.be.true;
|
||||
expect(check.statusCode).to.equal(200);
|
||||
expect(check.responseTime).to.equal(100);
|
||||
expect(check.message).to.equal("Test message");
|
||||
expect(check.accessibility).to.equal(100);
|
||||
expect(check.bestPractices).to.equal(100);
|
||||
expect(check.performance).to.equal(100);
|
||||
expect(check.seo).to.equal(100);
|
||||
expect(check.audits).to.deep.equal({
|
||||
cls: { score: 1 },
|
||||
si: { score: 1 },
|
||||
fcp: { score: 1 },
|
||||
lcp: { score: 1 },
|
||||
tbt: { score: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it("should build a check object for pagespeed type with missing data", function () {
|
||||
const check = statusService.buildCheck({
|
||||
monitorId: "test",
|
||||
type: "pagespeed",
|
||||
status: true,
|
||||
responseTime: 100,
|
||||
code: 200,
|
||||
message: "Test message",
|
||||
payload: {
|
||||
lighthouseResult: {
|
||||
categories: {},
|
||||
audits: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(check.monitorId).to.equal("test");
|
||||
expect(check.status).to.be.true;
|
||||
expect(check.statusCode).to.equal(200);
|
||||
expect(check.responseTime).to.equal(100);
|
||||
expect(check.message).to.equal("Test message");
|
||||
expect(check.accessibility).to.equal(0);
|
||||
expect(check.bestPractices).to.equal(0);
|
||||
expect(check.performance).to.equal(0);
|
||||
expect(check.seo).to.equal(0);
|
||||
expect(check.audits).to.deep.equal({
|
||||
cls: 0,
|
||||
si: 0,
|
||||
fcp: 0,
|
||||
lcp: 0,
|
||||
tbt: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("should build a check for hardware type", function () {
|
||||
const check = statusService.buildCheck({
|
||||
monitorId: "test",
|
||||
type: "hardware",
|
||||
status: true,
|
||||
responseTime: 100,
|
||||
code: 200,
|
||||
message: "Test message",
|
||||
payload: { data: { cpu: "cpu", memory: "memory", disk: "disk", host: "host" } },
|
||||
});
|
||||
expect(check.monitorId).to.equal("test");
|
||||
expect(check.status).to.be.true;
|
||||
expect(check.statusCode).to.equal(200);
|
||||
expect(check.responseTime).to.equal(100);
|
||||
expect(check.message).to.equal("Test message");
|
||||
expect(check.cpu).to.equal("cpu");
|
||||
expect(check.memory).to.equal("memory");
|
||||
expect(check.disk).to.equal("disk");
|
||||
expect(check.host).to.equal("host");
|
||||
});
|
||||
|
||||
it("should build a check for hardware type with missing data", function () {
|
||||
const check = statusService.buildCheck({
|
||||
monitorId: "test",
|
||||
type: "hardware",
|
||||
status: true,
|
||||
responseTime: 100,
|
||||
code: 200,
|
||||
message: "Test message",
|
||||
payload: {},
|
||||
});
|
||||
expect(check.monitorId).to.equal("test");
|
||||
expect(check.status).to.be.true;
|
||||
expect(check.statusCode).to.equal(200);
|
||||
expect(check.responseTime).to.equal(100);
|
||||
expect(check.message).to.equal("Test message");
|
||||
expect(check.cpu).to.deep.equal({});
|
||||
expect(check.memory).to.deep.equal({});
|
||||
expect(check.disk).to.deep.equal({});
|
||||
expect(check.host).to.deep.equal({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("insertCheck", () => {
|
||||
it("should log an error if one is thrown", async function () {
|
||||
const testError = new Error("Test error");
|
||||
statusService.db.createCheck = sinon.stub().throws(testError);
|
||||
try {
|
||||
await statusService.insertCheck({ monitorId: "test" });
|
||||
} catch (error) {
|
||||
expect(error.message).to.equal(testError.message);
|
||||
}
|
||||
expect(statusService.logger.error.calledOnce).to.be.true;
|
||||
});
|
||||
|
||||
it("should insert a check into the database", async function () {
|
||||
await statusService.insertCheck({ monitorId: "test", type: "http" });
|
||||
expect(statusService.db.createCheck.calledOnce).to.be.true;
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user