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

Tests to verify error handling and access restrictions during Facility Creation #9119

Conversation

ghost
Copy link

@ghost ghost commented Nov 14, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Introduced new test cases for facility creation to validate access restrictions for non-admin users and district admins.
    • Added a method to verify error notifications for enhanced error handling.
  • Bug Fixes

    • Ensured appropriate error messages are displayed for users based on their roles during facility creation attempts.

@ghost ghost self-requested a review as a code owner November 14, 2024 18:22
Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

Walkthrough

The changes introduced in this pull request enhance the Cypress end-to-end tests for facility creation by adding new test cases and methods to improve error handling. Two test cases are implemented: one for district admin error handling when creating a facility outside their district and another for access restrictions for non-admin users. Additionally, a new method to verify error notifications is added to the FacilityPage class, ensuring that the test suite maintains its structure while improving functionality.

Changes

File Path Change Summary
cypress/e2e/facility_spec/FacilityCreation.cy.ts Added two test cases: error handling for district admins creating a facility outside their district and access restriction for non-admin users.
cypress/pageobject/Facility/FacilityCreation.ts Added method verifyErrorNotification(message: string) and updated submitForm() to enhance error message verification.

Assessment against linked issues

Objective Addressed Explanation
Ensure error for district admin creating facility outside their district (#9108)
Verify non-admin users are restricted from accessing facility creation (#9108)
Follow POM structure and reuse existing functions (#9108)
Add tests in facilitycreation.cy.ts and new page objects in facilitycreation.ts (#9108)

Possibly related issues

  • None identified as related to the current changes.

Possibly related PRs

Suggested labels

tested

Suggested reviewers

  • rithviknishad
  • khavinshankar

Poem

In the land of tests, where bunnies play,
New checks for errors have come our way.
Non-admins hop, but can't create,
District admins learn their fate.
With each new case, our suite does grow,
Hopping along, we’ll steal the show! 🐇✨

Warning

Rate limit exceeded

@nihal467 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 4 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between e433a09 and 4971f81.

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

cypress/pageobject/Facility/FacilityCreation.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Failed to load parser '@typescript-eslint/parser' declared in '.eslintrc.json': Cannot find module '@typescript-eslint/parser'
Require stack:

  • /.eslintrc.json
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Function.resolve (node:internal/modules/helpers:145:19)
    at Object.resolve (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2346:46)
    at ConfigArrayFactory._loadParser (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3325:39)
    at ConfigArrayFactory._normalizeObjectConfigDataBody (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3099:43)
    at _normalizeObjectConfigDataBody.next ()
    at ConfigArrayFactory._normalizeObjectConfigData (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3040:20)
    at _normalizeObjectConfigData.next ()
    at ConfigArrayFactory.loadInDirectory (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2886:28)
    at CascadingConfigArrayFactory._loadConfigInAncestors (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3871:46)

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e433a09 and 4971f81.

📒 Files selected for processing (1)
  • cypress/pageobject/Facility/FacilityCreation.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cypress/pageobject/Facility/FacilityCreation.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Nov 14, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 4971f81
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/673bac6432ef4f0008c7c7d8
😎 Deploy Preview https://deploy-preview-9119--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (2)
cypress/pageobject/Facility/FacilityCreation.ts (2)

305-307: LGTM with suggestions for enhancement

The implementation is consistent with existing patterns and serves the PR's objectives. Consider these enhancements:

  1. Add TypeScript type information:
-  verifyErrorNotification(message: string) {
+  verifyErrorNotification(message: string): void {
  1. Consider consolidating notification verification to reduce duplication:
+  private verifyNotification(message: string, type: 'success' | 'error'): void {
+    cy.verifyNotification(message);
+  }
+
-  verifySuccessNotification(message: string) {
-    cy.verifyNotification(message);
-  }
+  verifySuccessNotification(message: string): void {
+    this.verifyNotification(message, 'success');
+  }
+
-  verifyErrorNotification(message: string) {
-    cy.verifyNotification(message);
-  }
+  verifyErrorNotification(message: string): void {
+    this.verifyNotification(message, 'error');
+  }
  1. Add error message constants to improve maintainability:
export const ERROR_MESSAGES = {
  DISTRICT_ACCESS_DENIED: 'You are not authorized to create facility outside your district',
  NON_ADMIN_ACCESS_DENIED: 'You do not have permission to access this page'
} as const;

305-307: Consider enhancing error handling architecture

To better support the PR's focus on error handling and access control, consider these architectural improvements:

  1. Create a dedicated error handling section in the class:
// Error Handling Methods
/**
 * Verifies access control and error notifications
 */
interface IAccessControl {
  verifyErrorNotification(message: string): void;
  verifyAccessDenied(): void;
  verifyDistrictAccessDenied(): void;
}

// Implementation examples:
verifyAccessDenied(): void {
  cy.url().should('include', '/403');
  this.verifyErrorNotification(ERROR_MESSAGES.NON_ADMIN_ACCESS_DENIED);
}

verifyDistrictAccessDenied(): void {
  this.verifyErrorNotification(ERROR_MESSAGES.DISTRICT_ACCESS_DENIED);
}
  1. Add JSDoc documentation for error scenarios:
/**
 * Verifies error notifications during facility creation
 * @param message - The expected error message
 * @example
 * // Verify district access error
 * facilityPage.verifyErrorNotification(ERROR_MESSAGES.DISTRICT_ACCESS_DENIED);
 */
verifyErrorNotification(message: string): void {
  cy.verifyNotification(message);
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between da5d576 and 660e73a.

📒 Files selected for processing (2)
  • cypress/e2e/facility_spec/FacilityCreation.cy.ts (2 hunks)
  • cypress/pageobject/Facility/FacilityCreation.ts (1 hunks)

cypress/e2e/facility_spec/FacilityCreation.cy.ts Outdated Show resolved Hide resolved
Comment on lines 342 to 351
it("Access Restriction for Non-Admin Users to facility creation page", () => {
nonAdminUsers.forEach((user) => {
loginPage.login(user.username, user.password);
cy.visit("/facility/create");

facilityPage.verifyErrorNotification(
"You don't have permission to perform this action. Contact the admin",
);
});
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test reliability and API verification

The test efficiently checks multiple users but could be improved in several ways:

  1. Add session cleanup between users
  2. Verify API requests
  3. Create a custom command for the repetitive login/verification flow
   it("Access Restriction for Non-Admin Users to facility creation page", () => {
+    cy.intercept('GET', '**/api/v1/facility/create/').as('accessFacility');
     nonAdminUsers.forEach((user) => {
       loginPage.login(user.username, user.password);
       cy.visit("/facility/create");
+      cy.wait('@accessFacility').then((interception) => {
+        expect(interception.response.statusCode).to.equal(403);
+      });
       facilityPage.verifyErrorNotification(
         "You don't have permission to perform this action. Contact the admin",
       );
+      cy.clearCookies();  // Clean up session
+      cy.clearLocalStorage();
     });
   });

Consider creating a custom command for better reusability:

// In cypress/support/commands.ts
Cypress.Commands.add('verifyNoFacilityAccess', (username: string, password: string) => {
  cy.intercept('GET', '**/api/v1/facility/create/').as('accessFacility');
  loginPage.login(username, password);
  cy.visit("/facility/create");
  cy.wait('@accessFacility').its('response.statusCode').should('eq', 403);
  facilityPage.verifyErrorNotification(
    "You don't have permission to perform this action. Contact the admin"
  );
  cy.clearCookies();
  cy.clearLocalStorage();
});

// In test file
it("Access Restriction for Non-Admin Users to facility creation page", () => {
  nonAdminUsers.forEach((user) => {
    cy.verifyNoFacilityAccess(user.username, user.password);
  });
});

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 660e73a and e433a09.

📒 Files selected for processing (2)
  • cypress/e2e/facility_spec/FacilityCreation.cy.ts (1 hunks)
  • cypress/pageobject/Facility/FacilityCreation.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cypress/pageobject/Facility/FacilityCreation.ts
🧰 Additional context used
📓 Learnings (1)
cypress/e2e/facility_spec/FacilityCreation.cy.ts (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9145
File: cypress/e2e/facility_spec/FacilityCreation.cy.ts:177-180
Timestamp: 2024-11-18T10:44:30.303Z
Learning: In `cypress/e2e/facility_spec/FacilityCreation.cy.ts`, when testing bed and staff capacity individually for additional error verification, we prefer to use separate method calls to handle bed and staff capacity, rather than using `facilityPage.createNewFacility(testFacilityData)` which also handles bed management.

Comment on lines +337 to +351
it("Access Restriction for Non-Admin Users to facility creation page", () => {
const nonAdminLoginMethods = [
loginPage.loginAsDevDoctor.bind(loginPage),
loginPage.loginAsStaff.bind(loginPage),
];

nonAdminLoginMethods.forEach((loginMethod) => {
loginMethod();
cy.visit("/facility/create");
facilityPage.verifyErrorNotification(
"You don't have permission to perform this action. Contact the admin",
);
cy.clearCookies();
});
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve test structure and API verification

While the test case handles session cleanup well, it needs improvements in several areas:

  1. Add API request verification
  2. Decouple login methods
  3. Verify HTTP status code
  4. Align error message with PR objectives

Apply these improvements:

 it("Access Restriction for Non-Admin Users to facility creation page", () => {
+  cy.intercept('GET', '**/api/v1/facility/create/').as('accessFacility');
+
-  const nonAdminLoginMethods = [
-    loginPage.loginAsDevDoctor.bind(loginPage),
-    loginPage.loginAsStaff.bind(loginPage),
+  // Load test users from fixture
+  cy.fixture('users').then((data) => {
+    const { nonAdminUsers } = data;
+
+    nonAdminUsers.forEach(({ username, password }) => {
+      loginPage.login(username, password);
+      cy.visit("/facility/create");
+
+      // Verify API response
+      cy.wait('@accessFacility').then((interception) => {
+        expect(interception.response.statusCode).to.equal(403);
+      });
+
+      facilityPage.verifyErrorNotification(
+        "You don't have permission to perform this action. Contact the admin"
+      );
+
+      cy.clearCookies();
+    });
   });
-
-  nonAdminLoginMethods.forEach((loginMethod) => {
-    loginMethod();
-    cy.visit("/facility/create");
-    facilityPage.verifyErrorNotification(
-      "You don't have permission to perform this action. Contact the admin",
-    );
-    cy.clearCookies();
-  });
 });

Create a fixture file cypress/fixtures/users.json:

{
  "nonAdminUsers": [
    {
      "username": "dummynurse1",
      "password": "Coronasafe@123",
      "role": "Nurse"
    },
    {
      "username": "devdoctor",
      "password": "Coronasafe@123",
      "role": "Doctor"
    }
  ]
}

Comment on lines +320 to +335
it("Should display error when district admin tries to create facility in a different district", () => {
facilityPage.visitCreateFacilityPage();
facilityPage.fillFacilityName(facilityName);
facilityPage.selectFacilityType(facilityType);
facilityPage.fillPincode("682001");
facilityPage.selectStateOnPincode("Kerala");
facilityPage.selectDistrictOnPincode("Kottayam");
facilityPage.selectLocalBody("Arpookara");
facilityPage.selectWard("5");
facilityPage.fillAddress(facilityAddress);
facilityPage.fillPhoneNumber(facilityNumber);
facilityPage.submitForm();
facilityPage.verifyErrorNotification(
"You do not have permission to perform this action.",
);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test reliability with API verification and data management

The test case needs improvements to meet the PR objectives and enhance reliability:

  1. Add API request verification
  2. Add test data cleanup
  3. Move test data to fixtures

Apply these improvements:

 it("Should display error when district admin tries to create facility in a different district", () => {
+  cy.intercept('POST', '**/api/v1/facility/').as('createFacility');
+
+  // Load test data from fixture
+  cy.fixture('facility_data').then((data) => {
+    const { facilityName, facilityType, differentDistrict } = data;
+
     facilityPage.visitCreateFacilityPage();
     facilityPage.fillFacilityName(facilityName);
     facilityPage.selectFacilityType(facilityType);
     facilityPage.fillPincode("682001");
     facilityPage.selectStateOnPincode("Kerala");
-    facilityPage.selectDistrictOnPincode("Kottayam");
-    facilityPage.selectLocalBody("Arpookara");
+    facilityPage.selectDistrictOnPincode(differentDistrict.name);
+    facilityPage.selectLocalBody(differentDistrict.localBody);
     facilityPage.selectWard("5");
     facilityPage.fillAddress(facilityAddress);
     facilityPage.fillPhoneNumber(facilityNumber);
     facilityPage.submitForm();
+
+    // Verify API response
+    cy.wait('@createFacility').then((interception) => {
+      expect(interception.response.statusCode).to.equal(403);
+      expect(interception.response.body).to.have.property('detail', 
+        'You do not have permission to perform this action.');
+    });
+
     facilityPage.verifyErrorNotification(
       "You do not have permission to perform this action.",
     );
+
+    // Cleanup
+    cy.clearCookies();
+    cy.clearLocalStorage();
   });
 });

Committable suggestion skipped: line range outside the PR's diff.

@nihal467 nihal467 added tested reviewed reviewed by a core member and removed needs testing needs review labels Nov 18, 2024
@khavinshankar khavinshankar merged commit 5eb31eb into ohcnetwork:develop Nov 19, 2024
21 checks passed
Copy link

@Alokih Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
reviewed reviewed by a core member tested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add Cypress Test to Verify Error Message During New Facility Creation based on user restriction
2 participants