Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

introduce the network status alert system #3532

Merged
merged 4 commits into from
Sep 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/device-registry/.env.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
SESSION_SECRET=test_secret
REDIS_SERVER=127.0.0.1
REDIS_SERVER_DEV=127.0.0.1
REDIS_PORT=4674
82 changes: 82 additions & 0 deletions src/device-registry/bin/jobs/check-network-status-job.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
const constants = require("@config/constants");
const log4js = require("log4js");
const logger = log4js.getLogger(
`${constants.ENVIRONMENT} -- /bin/jobs/check-network-status-job`
);
const DeviceModel = require("@models/Device");
const cron = require("node-cron");
const { logText } = require("@utils/log");

const BATCH_SIZE = 1000; // Define the size of each batch

const checkNetworkStatus = async () => {
try {
let totalDevices = 0;
let offlineDevicesCount = 0;
let pageNumber = 0;

Check warning on line 16 in src/device-registry/bin/jobs/check-network-status-job.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/jobs/check-network-status-job.js#L13-L16

Added lines #L13 - L16 were not covered by tests

while (true) {

Check warning on line 18 in src/device-registry/bin/jobs/check-network-status-job.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/jobs/check-network-status-job.js#L18

Added line #L18 was not covered by tests
// Fetch a batch of devices
const devices = await DeviceModel("airqo")

Check warning on line 20 in src/device-registry/bin/jobs/check-network-status-job.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/jobs/check-network-status-job.js#L20

Added line #L20 was not covered by tests
.find({}, "isOnline _id")
.lean()
.limit(BATCH_SIZE)
.skip(pageNumber * BATCH_SIZE);

if (devices.length === 0) break; // Exit loop if no more devices

totalDevices += devices.length;

Check warning on line 28 in src/device-registry/bin/jobs/check-network-status-job.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/jobs/check-network-status-job.js#L28

Added line #L28 was not covered by tests

// Count offline devices in the current batch
offlineDevicesCount += devices.filter(
(device) => device.isOnline === false

Check warning on line 32 in src/device-registry/bin/jobs/check-network-status-job.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/jobs/check-network-status-job.js#L31-L32

Added lines #L31 - L32 were not covered by tests
).length;

pageNumber++; // Move to the next batch

Check warning on line 35 in src/device-registry/bin/jobs/check-network-status-job.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/jobs/check-network-status-job.js#L35

Added line #L35 was not covered by tests
}
Comment on lines +18 to +36
Copy link
Contributor

@coderabbitai coderabbitai bot Sep 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Optimize device counting with database aggregation

Fetching all devices in batches and counting offline ones in application code can be resource-intensive. Using a database aggregation pipeline to perform counting directly in MongoDB can enhance performance and reduce memory usage.

For example:

const result = await DeviceModel("airqo").aggregate([
  {
    $group: {
      _id: null,
      totalDevices: { $sum: 1 },
      offlineDevicesCount: {
        $sum: {
          $cond: [{ $eq: ["$isOnline", false] }, 1, 0],
        },
      },
    },
  },
]);

if (result.length === 0 || result[0].totalDevices === 0) {
  logText("No devices found");
  logger.info("No devices found.");
  return;
}

const { totalDevices, offlineDevicesCount } = result[0];
const offlinePercentage = (offlineDevicesCount / totalDevices) * 100;

// Proceed with existing logic...
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 18-18: src/device-registry/bin/jobs/check-network-status-job.js#L18
Added line #L18 was not covered by tests


[warning] 20-20: src/device-registry/bin/jobs/check-network-status-job.js#L20
Added line #L20 was not covered by tests


[warning] 28-28: src/device-registry/bin/jobs/check-network-status-job.js#L28
Added line #L28 was not covered by tests


[warning] 31-32: src/device-registry/bin/jobs/check-network-status-job.js#L31-L32
Added lines #L31 - L32 were not covered by tests


[warning] 35-35: src/device-registry/bin/jobs/check-network-status-job.js#L35
Added line #L35 was not covered by tests

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

create a new Github issue for this suggestion please.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Baalmart, the GitHub issue has been created as per your request: #3538.

🔗 Analysis chain

@Baalmart, here's a script to create the GitHub issue as requested.

🐰

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Create a new GitHub issue for the suggestion
gh issue create \
  --title "Optimize device counting with database aggregation in check-network-status-job.js" \
  --body "During the code review for [PR #3532](https://github.com/airqo-platform/AirQo-api/pull/3532), a suggestion was made to optimize device counting with database aggregation in \`check-network-status-job.js\`. See the [discussion](https://github.com/airqo-platform/AirQo-api/pull/3532#discussion_r1779453499) for details. Requested by @Baalmart." \
  --assignee Baalmart

Length of output: 534


if (totalDevices === 0) {
logText("No devices found");
logger.info("No devices found.");
return;

Check warning on line 41 in src/device-registry/bin/jobs/check-network-status-job.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/jobs/check-network-status-job.js#L39-L41

Added lines #L39 - L41 were not covered by tests
}

const offlinePercentage = (offlineDevicesCount / totalDevices) * 100;

Check warning on line 44 in src/device-registry/bin/jobs/check-network-status-job.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/jobs/check-network-status-job.js#L44

Added line #L44 was not covered by tests

if (offlinePercentage > 60) {
logText(

Check warning on line 47 in src/device-registry/bin/jobs/check-network-status-job.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/jobs/check-network-status-job.js#L47

Added line #L47 was not covered by tests
`⚠️💔😥 More than 60% of devices are offline: ${offlinePercentage.toFixed(
2
)}%`
);

logger.warn(

Check warning on line 53 in src/device-registry/bin/jobs/check-network-status-job.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/jobs/check-network-status-job.js#L53

Added line #L53 was not covered by tests
`⚠️💔😥 More than 60% of devices are offline: ${offlinePercentage.toFixed(
2
)}%`
);
} else {
// logText(
// `✅ Network status is acceptable: ${offlinePercentage.toFixed(
// 2
// )}% offline`
// );
// logger.info(
// `✅ Network status is acceptable: ${offlinePercentage.toFixed(
// 2
// )}% offline`
// );
}
} catch (error) {
logText(`Error checking network status: ${error.message}`);
logger.error(`Error checking network status: ${error.message}`);
logger.error(`Stack trace: ${error.stack}`);

Check warning on line 73 in src/device-registry/bin/jobs/check-network-status-job.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/jobs/check-network-status-job.js#L71-L73

Added lines #L71 - L73 were not covered by tests
}
};
Comment on lines +12 to +75
Copy link
Contributor

@coderabbitai coderabbitai bot Sep 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Consider adding unit tests for the checkNetworkStatus function

The checkNetworkStatus function is a critical part of the new network status alert system but currently lacks unit tests. Adding tests will improve reliability and help catch potential issues early.

Would you like assistance in writing these tests or should we open a GitHub issue to track this task?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 13-16: src/device-registry/bin/jobs/check-network-status-job.js#L13-L16
Added lines #L13 - L16 were not covered by tests


[warning] 18-18: src/device-registry/bin/jobs/check-network-status-job.js#L18
Added line #L18 was not covered by tests


[warning] 20-20: src/device-registry/bin/jobs/check-network-status-job.js#L20
Added line #L20 was not covered by tests


[warning] 28-28: src/device-registry/bin/jobs/check-network-status-job.js#L28
Added line #L28 was not covered by tests


[warning] 31-32: src/device-registry/bin/jobs/check-network-status-job.js#L31-L32
Added lines #L31 - L32 were not covered by tests


[warning] 35-35: src/device-registry/bin/jobs/check-network-status-job.js#L35
Added line #L35 was not covered by tests


[warning] 39-41: src/device-registry/bin/jobs/check-network-status-job.js#L39-L41
Added lines #L39 - L41 were not covered by tests


[warning] 44-44: src/device-registry/bin/jobs/check-network-status-job.js#L44
Added line #L44 was not covered by tests


[warning] 47-47: src/device-registry/bin/jobs/check-network-status-job.js#L47
Added line #L47 was not covered by tests


[warning] 53-53: src/device-registry/bin/jobs/check-network-status-job.js#L53
Added line #L53 was not covered by tests


[warning] 71-73: src/device-registry/bin/jobs/check-network-status-job.js#L71-L73
Added lines #L71 - L73 were not covered by tests

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please create a new Github issue for this suggestion.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Baalmart, I've created a new GitHub issue to track the addition of unit tests for the checkNetworkStatus function. You can find it here: #3535

🔗 Analysis chain
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Create a new GitHub issue to track the addition of unit tests for the checkNetworkStatus function
gh issue create \
  --title "Add unit tests for checkNetworkStatus function" \
  --body "The \`checkNetworkStatus\` function introduced in PR [#3532](https://github.com/airqo-platform/AirQo-api/pull/3532) currently lacks unit tests.

This issue was raised during code review: https://github.com/airqo-platform/AirQo-api/pull/3532#discussion_r1779453498

Requested by @Baalmart." \
  --assignee Baalmart

Length of output: 446


logText("Network status job is now running.....");
const schedule = "0 */2 * * *";
cron.schedule(schedule, checkNetworkStatus, {
scheduled: true,
timezone: constants.TIMEZONE,
});
2 changes: 1 addition & 1 deletion src/device-registry/bin/jobs/kafka-consumer.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const { Kafka } = require("kafkajs");
const constants = require("@config/constants");
const log4js = require("log4js");
const logger = log4js.getLogger(
`${constants.ENVIRONMENT} -- bin/kafka-consumer`
`${constants.ENVIRONMENT} -- bin/jobs/kafka-consumer`
);
const { logObject } = require("@utils/log");
const createEvent = require("@utils/create-event");
Expand Down
2 changes: 1 addition & 1 deletion src/device-registry/bin/jobs/new-store-readings-job.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const constants = require("@config/constants");
const log4js = require("log4js");
const logger = log4js.getLogger(
`${constants.ENVIRONMENT} -- /bin/new-store-readings-job`
`${constants.ENVIRONMENT} -- /bin/jobs/new-store-readings-job`
);
const EventModel = require("@models/Event");
const DeviceModel = require("@models/Device");
Expand Down
2 changes: 1 addition & 1 deletion src/device-registry/bin/jobs/store-readings-job.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const constants = require("@config/constants");
const log4js = require("log4js");
const logger = log4js.getLogger(
`${constants.ENVIRONMENT} -- /bin/store-readings-job`
`${constants.ENVIRONMENT} -- /bin/jobs/store-readings-job`
);
const EventModel = require("@models/Event");
const ReadingModel = require("@models/Reading");
Expand Down
2 changes: 1 addition & 1 deletion src/device-registry/bin/jobs/store-signals-job.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const constants = require("@config/constants");
const log4js = require("log4js");
const logger = log4js.getLogger(
`${constants.ENVIRONMENT} -- /bin/store-signals-job`
`${constants.ENVIRONMENT} -- /bin/jobs/store-signals-job`
);
const EventModel = require("@models/Event");
const SignalModel = require("@models/Signal");
Expand Down
88 changes: 88 additions & 0 deletions src/device-registry/bin/jobs/test/ut_check-network-status-job.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
require("module-alias/register");
const sinon = require("sinon");
const { expect } = require("chai");
const log4js = require("log4js");
const DeviceModel = require("@models/Device");
const { logText } = require("@utils/log");
const checkNetworkStatus = require("@bin/jobs/check-network-status-job");

describe("checkNetworkStatus", () => {
let loggerStub;
let findStub;

beforeEach(() => {
// Stub the logger methods
loggerStub = sinon.stub(log4js.getLogger(), "info");
sinon.stub(log4js.getLogger(), "warn");
sinon.stub(log4js.getLogger(), "error");

// Stub the DeviceModel find method
findStub = sinon.stub(DeviceModel.prototype, "find").returns({
lean: () => ({
limit: () => ({
skip: () => Promise.resolve([]), // Default to an empty array
}),
}),
});
});

afterEach(() => {
// Restore all stubs
sinon.restore();
});

it("should log 'No devices found' when there are no devices", async () => {
await checkNetworkStatus();

expect(loggerStub.calledWith("No devices found.")).to.be.true;
expect(logText.calledWith("No devices found")).to.be.true;
});

it("should calculate offline percentage correctly and log acceptable status", async () => {
findStub.returns({
lean: () => ({
limit: () => ({
skip: () =>
Promise.resolve([{ isOnline: true }, { isOnline: false }]), // Mock devices
}),
}),
});

await checkNetworkStatus();

expect(
loggerStub.calledWith("✅ Network status is acceptable: 50.00% offline")
).to.be.true;
});

it("should calculate offline percentage correctly and log warning if more than 60% are offline", async () => {
findStub.returns({
lean: () => ({
limit: () => ({
skip: () =>
Promise.resolve([
{ isOnline: false },
{ isOnline: false },
{ isOnline: true },
]), // Mock devices
}),
}),
});

await checkNetworkStatus();

expect(
loggerStub.calledWith("⚠️ More than 60% of devices are offline: 66.67%")
).to.be.true;
});

it("should handle errors gracefully", async () => {
findStub.throws(new Error("Database error"));

await checkNetworkStatus();

expect(
loggerStub.calledWith("Error checking network status: Database error")
).to.be.true;
});
});
1 change: 1 addition & 0 deletions src/device-registry/bin/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const { logText, logObject } = require("@utils/log");
const jsonify = require("@utils/jsonify");
require("@bin/jobs/store-signals-job");
require("@bin/jobs/new-store-readings-job");
require("@bin/jobs/check-network-status-job");

if (isEmpty(constants.SESSION_SECRET)) {
throw new Error("SESSION_SECRET environment variable not set");
Expand Down
129 changes: 63 additions & 66 deletions src/device-registry/bin/test/ut_index.js
Original file line number Diff line number Diff line change
@@ -1,85 +1,82 @@
require("module-alias/register");
const { expect } = require("chai");
const sinon = require("sinon");
const proxyquire = require("proxyquire");

// Import the functions to be tested
// const kafkaConsumer = require("@bin/kafka-consumer");
// const createServer = require("@bin/server");
const main = require("@bin/index");

const kafkaConsumer = proxyquire("@bin/kafka-consumer", {
// Replace the original module with a mock version
myModule: {
fetchData: () => {
// Mock implementation without relying on environmental variables
return "Mocked Data";
},
},
});

const createServer = proxyquire("@bin/server", {
// Replace the original module with a mock version
myModule: {
fetchData: () => {
// Mock implementation without relying on environmental variables
return "Mocked Data";
},
},
});
const { expect } = require("chai");
const log4js = require("log4js");
const kafkaConsumer = require("@bin/jobs/kafka-consumer");
const createServer = require("@bin/server");
const constants = require("@config/constants");
const log4jsConfiguration = require("@config/log4js");

describe("Main Function", () => {
describe("Application Initialization", () => {
let loggerStub;
let kafkaConsumerStub;
let createServerStub;

beforeEach(() => {
kafkaConsumerStub = sinon.stub(kafkaConsumer);
// Stub the logger methods
loggerStub = sinon.stub(log4js.getLogger(), "error");

// Stub kafkaConsumer and createServer
kafkaConsumerStub = sinon.stub(kafkaConsumer, "default").resolves();
createServerStub = sinon.stub(createServer);

// Configure log4js for testing
log4js.configure(log4jsConfiguration);

Check warning on line 24 in src/device-registry/bin/test/ut_index.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/test/ut_index.js#L24

Added line #L24 was not covered by tests
});

afterEach(() => {
// Restore all stubs
sinon.restore();
});

it("should call kafkaConsumer and createServer functions", async () => {
try {
// Call the main function
await main();

// Check if the kafkaConsumer and createServer functions are called
expect(kafkaConsumerStub.calledOnce).to.be.true;
expect(createServerStub.calledOnce).to.be.true;
} catch (error) {
throw error;
}
it("should start the Kafka consumer and create the server", async () => {
await main(); // Call the main function

Check warning on line 33 in src/device-registry/bin/test/ut_index.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/test/ut_index.js#L33

Added line #L33 was not covered by tests

expect(kafkaConsumerStub.calledOnce).to.be.true; // Check if kafkaConsumer was called
expect(createServerStub.calledOnce).to.be.true; // Check if createServer was called

Check warning on line 36 in src/device-registry/bin/test/ut_index.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/test/ut_index.js#L35-L36

Added lines #L35 - L36 were not covered by tests
});

it("should catch and log errors if main function throws an error", async () => {
const errorToThrow = new Error("Test error");
const consoleErrorSpy = sinon.spy(console, "error");

// Stub the main function to throw an error
sinon.stub(main, "kafkaConsumer").throws(errorToThrow);

try {
// Call the main function
await main();

// Check if the error is caught and logged
expect(
consoleErrorSpy.calledOnceWithExactly(
"Error starting the application: ",
errorToThrow
)
).to.be.true;
} catch (error) {
throw error;
} finally {
// Restore the stubs and spies
sinon.restore();
consoleErrorSpy.restore();
}
it("should log an error if starting Kafka fails", async () => {
const errorMessage = "Kafka connection error";
kafkaConsumerStub.rejects(new Error(errorMessage)); // Simulate an error from kafkaConsumer

Check warning on line 41 in src/device-registry/bin/test/ut_index.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/test/ut_index.js#L40-L41

Added lines #L40 - L41 were not covered by tests

await main(); // Call the main function

Check warning on line 43 in src/device-registry/bin/test/ut_index.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/test/ut_index.js#L43

Added line #L43 was not covered by tests

expect(

Check warning on line 45 in src/device-registry/bin/test/ut_index.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/test/ut_index.js#L45

Added line #L45 was not covered by tests
loggerStub.calledWithMatch(
sinon.match.string,
sinon.match({ message: errorMessage })
)
).to.be.true;
});

it("should log an error if creating the server fails", async () => {
const errorMessage = "Server creation error";
kafkaConsumerStub.resolves(); // Ensure kafkaConsumer resolves
createServerStub.throws(new Error(errorMessage)); // Simulate an error from createServer

Check warning on line 56 in src/device-registry/bin/test/ut_index.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/test/ut_index.js#L54-L56

Added lines #L54 - L56 were not covered by tests

await main(); // Call the main function

Check warning on line 58 in src/device-registry/bin/test/ut_index.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/test/ut_index.js#L58

Added line #L58 was not covered by tests

expect(

Check warning on line 60 in src/device-registry/bin/test/ut_index.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/test/ut_index.js#L60

Added line #L60 was not covered by tests
loggerStub.calledWithMatch(
sinon.match.string,
sinon.match({ message: errorMessage })
)
).to.be.true;
});

Comment on lines +39 to 67
Copy link
Contributor

@coderabbitai coderabbitai bot Sep 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Excellent addition of error handling test cases!

The new test cases for Kafka connection errors and server creation errors significantly enhance the robustness of the test suite. They ensure that the application properly logs errors in these critical scenarios, which is crucial for maintaining system reliability and ease of debugging.

A suggestion for further improvement:

Consider parameterizing these error tests to reduce code duplication and make it easier to add more error scenarios in the future. Here's an example of how you could refactor this:

const errorScenarios = [
  { name: 'Kafka connection', errorSource: 'kafkaConsumer', errorMessage: 'Kafka connection error' },
  { name: 'Server creation', errorSource: 'createServer', errorMessage: 'Server creation error' }
];

errorScenarios.forEach(({ name, errorSource, errorMessage }) => {
  it(`should log an error if ${name} fails`, async () => {
    if (errorSource === 'kafkaConsumer') {
      kafkaConsumerStub.rejects(new Error(errorMessage));
    } else {
      kafkaConsumerStub.resolves();
      createServerStub.throws(new Error(errorMessage));
    }

    await main();

    expect(
      loggerStub.calledWithMatch(
        sinon.match.string,
        sinon.match({ message: errorMessage })
      )
    ).to.be.true;
  });
});

This approach would make it easier to add new error scenarios and reduce the likelihood of inconsistencies between similar test cases.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 40-41: src/device-registry/bin/test/ut_index.js#L40-L41
Added lines #L40 - L41 were not covered by tests


[warning] 43-43: src/device-registry/bin/test/ut_index.js#L43
Added line #L43 was not covered by tests


[warning] 45-45: src/device-registry/bin/test/ut_index.js#L45
Added line #L45 was not covered by tests


[warning] 54-56: src/device-registry/bin/test/ut_index.js#L54-L56
Added lines #L54 - L56 were not covered by tests


[warning] 58-58: src/device-registry/bin/test/ut_index.js#L58
Added line #L58 was not covered by tests


[warning] 60-60: src/device-registry/bin/test/ut_index.js#L60
Added line #L60 was not covered by tests

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please create a new Github issue for this suggestion

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Baalmart, I've created a new GitHub issue for this suggestion: #3534. This will help track the refactoring of the unit tests to parameterize error scenarios and enhance maintainability.

🔗 Analysis chain
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Create a new GitHub issue for the refactoring suggestion
gh issue create \
  --title "Refactor unit tests to parameterize error scenarios in src/device-registry/bin/test/ut_index.js" \
  --body "As requested by @Baalmart, consider refactoring the unit tests to use parameterized error scenarios to reduce code duplication and enhance maintainability.

See the discussion at PR #3532: https://github.com/airqo-platform/AirQo-api/pull/3532 and the specific comment: https://github.com/airqo-platform/AirQo-api/pull/3532#discussion_r1779453497." \
  --assignee Baalmart

Length of output: 555

// Add more test cases as needed
it("should handle errors thrown during application startup", async () => {
const startupError = new Error("Startup error");

Check warning on line 69 in src/device-registry/bin/test/ut_index.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/test/ut_index.js#L69

Added line #L69 was not covered by tests

// Simulate an error during startup
sinon.stub(console, "error"); // Stub console.error to suppress output during tests
await main().catch(() => {});

Check warning on line 73 in src/device-registry/bin/test/ut_index.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/test/ut_index.js#L72-L73

Added lines #L72 - L73 were not covered by tests

expect(

Check warning on line 75 in src/device-registry/bin/test/ut_index.js

View check run for this annotation

Codecov / codecov/patch

src/device-registry/bin/test/ut_index.js#L75

Added line #L75 was not covered by tests
loggerStub.calledWithMatch(
sinon.match.string,
sinon.match({ message: startupError.message })
)
).to.be.true;
});
});
Loading
Loading