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

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

Alokih
Copy link

@Alokih Alokih 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.

@Alokih Alokih requested a review from a team as a code owner November 14, 2024 18:22
Copy link

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. A constant for non-admin user credentials is introduced, and two test cases are implemented: one for district admin error handling 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 constant nonAdminUsers and two test cases: error handling for district admins and access restriction for non-admin users.
cypress/pageobject/Facility/FacilityCreation.ts Added method verifyErrorNotification(message: string) 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 PRs

Suggested labels

tested, needs review

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

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/e2e/facility_spec/FacilityCreation.cy.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)

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 660e73a
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67363fd23e98c50008de151c
😎 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

@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)

Comment on lines +62 to +65
const nonAdminUsers = [
{ username: "dummynurse1", password: "Coronasafe@123" },
{ username: "devdoctor", password: "Coronasafe@123" },
];
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider moving credentials to environment variables or test fixtures

While the constant is well-structured, storing credentials directly in test files is not recommended. Consider moving these credentials to:

  1. Cypress environment variables (cypress.env.json)
  2. Test fixtures (cypress/fixtures/users.json)

This approach improves security and makes credential management more maintainable.

-  const nonAdminUsers = [
-    { username: "dummynurse1", password: "Coronasafe@123" },
-    { username: "devdoctor", password: "Coronasafe@123" },
-  ];

And create a fixture file cypress/fixtures/users.json:

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

Then use it in the test:

let nonAdminUsers: Array<{username: string, password: string}>;

before(() => {
  cy.fixture('users').then((users) => {
    nonAdminUsers = users.nonAdminUsers;
  });
});

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

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);
  });
});

Comment on lines +325 to +340
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

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add API request verification using cy.intercept()

The test effectively verifies the UI behavior, but according to the PR objectives, it should also verify the API request. Consider adding cy.intercept() to ensure the backend request is made with the correct payload and the error originates from the API.

   it("Should display error when district admin tries to create facility in a different district", () => {
+    cy.intercept('POST', '**/api/v1/facility/create/').as('createFacility');
     facilityPage.visitCreateFacilityPage();
     facilityPage.fillFacilityName(facilityName);
     // ... existing code ...
     facilityPage.submitForm();
+    cy.wait('@createFacility').then((interception) => {
+      expect(interception.response.statusCode).to.equal(403);
+      expect(interception.response.body.detail).to.include('You do not have permission');
+    });
     facilityPage.verifyErrorNotification(
       "You do not have permission to perform this action.",
     );
   });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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.",
);
});
it("Should display error when district admin tries to create facility in a different district", () => {
cy.intercept('POST', '**/api/v1/facility/create/').as('createFacility');
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();
cy.wait('@createFacility').then((interception) => {
expect(interception.response.statusCode).to.equal(403);
expect(interception.response.body.detail).to.include('You do not have permission');
});
facilityPage.verifyErrorNotification(
"You do not have permission to perform this action.",
);
});

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.

Add Cypress Test to Verify Error Message During New Facility Creation based on user restriction
1 participant