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

Feat/be/check module tests #1119

Merged

Conversation

ajhollid
Copy link
Collaborator

@ajhollid ajhollid commented Nov 7, 2024

This PR adds tests for the checksModule

  • Minor refactoring of checksModule
    • Add missing try/catch block
    • Remove console.log
    • Fix undefined check
  • Add tests for checksModule

Copy link

@llamapreview llamapreview bot left a comment

Choose a reason for hiding this comment

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

Auto Pull Request Review from LlamaPReview

1. Overview

1.1 PR Summary

  • Business value and requirements alignment: This PR adds tests for the checksModule and includes minor refactoring such as adding a missing try/catch block, removing console.log, and fixing an undefined check.
  • Key components modified: Changes are isolated to Server/db/mongo/modules/checkModule.js and Server/tests/db/checkModule.test.js.
  • Impact assessment: Enhances the reliability and maintainability of the checksModule by adding comprehensive tests.
  • System dependencies and integration impacts: No significant architectural changes. The focus is on improving error handling and adding tests.

1.2 Architecture Changes

  • System design modifications: No significant architectural changes. The focus is on improving error handling and logging.
  • Component interactions: Minor improvements in how errors are handled and logged.
  • Integration points: No new integration points introduced.

2. Detailed Technical Analysis

2.1 Code Logic Deep-Dive

Core Logic Changes

Server/db/mongo/modules/checkModule.js - getTeamChecks
  • Submitted PR Code:
    + try {
    +     const { teamId } = req.params;
    +     let { sortOrder, limit, dateRange, filter, page, rowsPerPage } = req.query;
    +
    +     // Get monitorIDs
    +     const userMonitors = await Monitor.find({ teamId: teamId }).select("_id");
    +
    +     // Build check query
    +     // Default limit to 0 if not provided
    +     limit = limit === undefined ? 0 : limit;
    +     // Default sort order is newest -> oldest
    +     sortOrder = sortOrder === "asc" ? 1 : -1;
    +
    +     const checksQuery = { monitorId: { $in: userMonitors } };
    +
    +     if (filter !== undefined) {
    +         checksQuery.status = false;
    +         switch (filter) {
    +             case "all":
    +                 break;
    +             case "down":
    +                 break;
    +             case "resolve":
    +                 checksQuery.statusCode = 5000;
    +                 break;
    +             default:
    +                 logger.warn({
    +                     message: "invalid filter",
    +                     service: SERVICE_NAME,
    +                     method: "getTeamChecks",
    +                 });
    +                 break;
    +         }
    +     }
    +
    +     if (dateRange !== undefined) {
    +         checksQuery.createdAt = { $gte: dateRangeLookup[dateRange] };
    +     }
    +
    +     // Skip and limit for pagination
    +     let skip = 0;
    +     if (page && rowsPerPage) {
    +         skip = page * rowsPerPage;
    +     }
    +
    +     const checksCount = await Check.countDocuments(checksQuery);
    +
    +     const checks = await Check.find(checksQuery)
    +         .skip(skip)
    +         .limit(rowsPerPage)
    +         .sort({ createdAt: sortOrder })
    +         .select(["monitorId", "status", "responseTime", "statusCode", "message"]);
    +     return { checksCount, checks };
    + } catch (error) {
    +     error.service = SERVICE_NAME;
    +     error.method = "getTeamChecks";
    +     throw error;
    + }
  • Analysis:
    • The function now includes a try/catch block to handle errors gracefully.
    • The default value for limit is correctly set to 0 if not provided.
    • The filter logic handles different cases effectively.
    • Pagination is implemented using skip and limit.
    • Errors are logged with additional context.
  • LlamaPReview Suggested Improvements:
    // No specific improvements needed for this block as it is already well-structured.
  • Improvement rationale:
    • Technical benefits: Cleaner error handling and logging.
    • Business value: Enhanced reliability and easier debugging.
    • Risk assessment: Low risk, as the changes are isolated and well-tested.
Server/db/mongo/modules/checkModule.js - createCheck
  • Submitted PR Code:
    + try {
    +     const { monitorId, status } = req.body;
    +
    +     // Find the monitor by ID
    +     const monitor = await Monitor.findById(monitorId);
    +     if (!monitor) {
    +         return undefined;
    +     }
    +
    +     // Update uptime percentage
    +     if (monitor.uptimePercentage === undefined) {
    +         monitor.uptimePercentage = status === true ? 1 : 0;
    +     } else {
    +         const n = await Check.countDocuments({ monitorId: monitorId });
    +         monitor.uptimePercentage = (monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n;
    +     }
    +
    +     await monitor.save();
    +
    +     const check = new Check({
    +         monitorId: monitorId,
    +         status: status,
    +         responseTime: req.body.responseTime,
    +         statusCode: req.body.statusCode,
    +         message: req.body.message,
    +     });
    +
    +     await check.save();
    +     return check;
    + } catch (error) {
    +     error.service = SERVICE_NAME;
    +     error.method = "createCheck";
    +     throw error;
    + }
  • Analysis:
    • The function now includes a try/catch block to handle errors gracefully.
    • The logic correctly updates the uptime percentage and saves the check.
    • Errors are logged with additional context.
  • LlamaPReview Suggested Improvements:
    // No specific improvements needed for this block as it is already well-structured.
  • Improvement rationale:
    • Technical benefits: Cleaner error handling and logging.
    • Business value: Enhanced reliability and easier debugging.
    • Risk assessment: Low risk, as the changes are isolated and well-tested.

2.2 Implementation Quality

  • Code organization and structure: The code is well-organized and modular.
  • Design patterns usage: Adheres to best practices for error handling and logging.
  • Error handling approach: Comprehensive error handling with try/catch blocks.
  • Resource management: Efficient use of database queries with pagination.

3. Critical Findings

3.1 Potential Issues

  • 🔴 Critical Issues

    • No critical issues identified.
  • 🟡 Warnings

    • Input Validation: Ensure all inputs such as page and rowsPerPage are validated to prevent injection attacks.
      • Impact: Potential security risks if inputs are not validated.
      • Recommendation: Add input validation to ensure integers and valid ranges.
    • Error Handling: Consider handling different types of errors separately for better error reporting.
      • Impact: Enhanced error logging and easier debugging.
      • Recommendation: Add specific error handling for different error types.

3.2 Code Quality Concerns

  • Maintainability aspects: The code is well-structured and easy to maintain.
  • Readability issues: No significant readability issues identified.
  • Performance bottlenecks: No apparent bottlenecks introduced.

4. Security Assessment

4.1 Security Considerations

  • Input Validation: Ensure all inputs are validated to prevent injection attacks.
  • Data Handling: Ensure sensitive data is not exposed in logs.
  • Error Logging: Avoid logging sensitive information in error messages.

4.2 Vulnerability Analysis

  • Potential security risks: Input validation issues could lead to injection attacks.
  • Mitigation strategies: Validate all inputs and sanitize them before processing.
  • Security testing requirements: Ensure comprehensive security testing is performed.

5. Testing Strategy

5.1 Test Coverage

  • Unit test analysis: Comprehensive unit tests for checksModule functions.
  • Integration test requirements: Not explicitly mentioned, but unit tests cover a wide range of scenarios.
  • Edge cases coverage: Various edge cases are covered in the tests.

5.2 Test Recommendations

Suggested Test Cases

// Example of a test case for input validation
describe("getTeamChecks input validation", () => {
    it("should throw an error for invalid pagination parameters", async () => {
        const req = {
            params: { teamId: "test123" },
            query: { page: "invalid", rowsPerPage: "invalid" },
        };
        try {
            await getTeamChecks(req);
        } catch (error) {
            expect(error.message).to.equal("Invalid pagination parameters");
        }
    });
});
  • Coverage improvements: Ensure all edge cases are covered, including invalid inputs.
  • Performance testing needs: Test under high load to ensure scalability.

6. Documentation & Maintenance

  • Documentation updates needed: Ensure all changes are documented for future reference.
  • Long-term maintenance considerations: The code is well-structured and easy to maintain.
  • Technical debt and monitoring requirements: No significant technical debt introduced. Ensure comprehensive monitoring is in place.

7. Deployment & Operations

  • Deployment impact and strategy: The changes are isolated and should not affect existing functionality.
  • Key operational considerations: Ensure a rollback plan is in place for any issues during deployment.

8. Summary & Recommendations

8.1 Key Action Items

  1. Critical changes required:

    • None identified.
  2. Important improvements suggested:

    • Ensure all inputs such as page and rowsPerPage are validated to prevent injection attacks.
    • Consider handling different types of errors separately for better error reporting.
  3. Best practices to implement:

    • Adhere to best practices for error handling and logging.
    • Ensure comprehensive security testing is performed.
  4. Cross-cutting concerns to address:

    • Input validation and error handling.

8.2 Future Considerations

  • Technical evolution path: Continue to enhance error handling and logging.
  • Business capability evolution: Enhance the reliability and maintainability of the checksModule.
  • System integration impacts: No significant architectural changes. The focus is on improving error handling and adding tests.

This structured review ensures completeness by incorporating insights from all sources and presents information in a practical, actionable format, adhering to professional review standards.

@ajhollid ajhollid merged commit 1592523 into feat/be/uptime-percentage-stats Nov 8, 2024
1 check passed
@ajhollid ajhollid deleted the feat/be/check-module-tests branch November 11, 2024 03:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant