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

Add Live search tests #2425

Merged
merged 8 commits into from
Nov 1, 2024

Conversation

shashwatahalder01
Copy link
Contributor

@shashwatahalder01 shashwatahalder01 commented Nov 1, 2024

All Submissions:

  • My code follow the WordPress' coding standards
  • My code satisfies feature requirements
  • My code is tested
  • My code passes the PHPCS tests
  • My code has proper inline documentation
  • I've included related pull request(s) (optional)
  • I've included developer documentation (optional)
  • I've added proper labels to this pull request

Changes proposed in this Pull Request:

Related Pull Request(s)

  • Full PR Link

Closes

  • Closes #

How to test the changes in this Pull Request:

  • Steps or issue link

Changelog entry

Title

Detailed Description of the pull request. What was previous behaviour
and what will be changed in this PR.

Before Changes

Describe the issue before changes with screenshots(s).

After Changes

Describe the issue after changes with screenshot(s).

Feature Video (optional)

Link of detailed video if this PR is for a feature.

PR Self Review Checklist:

  • Code is not following code style guidelines
  • Bad naming: make sure you would understand your code if you read it a few months from now.
  • KISS: Keep it simple, Sweetie (not stupid!).
  • DRY: Don't Repeat Yourself.
  • Code that is not readable: too many nested 'if's are a bad sign.
  • Performance issues
  • Complicated constructions that need refactoring or comments: code should almost always be self-explanatory.
  • Grammar errors.

FOR PR REVIEWER ONLY:

As a reviewer, your feedback should be focused on the idea, not the person. Seek to understand, be respectful, and focus on constructive dialog.

As a contributor, your responsibility is to learn from suggestions and iterate your pull request should it be needed based on feedback. Seek to collaborate and produce the best possible contribution to the greater whole.

  • Correct — Does the change do what it’s supposed to? ie: code 100% fulfilling the requirements?
  • Secure — Would a nefarious party find some way to exploit this change? ie: everything is sanitized/escaped appropriately for any SQL or XSS injection possibilities?
  • Readable — Will your future self be able to understand this change months down the road?
  • Elegant — Does the change fit aesthetically within the overall style and architecture?

Summary by CodeRabbit

  • New Features

    • Enhanced user role permissions for admins and vendors, including live search capabilities for customers.
    • Introduced a new LiveSearch class for improved product searching functionality.
    • Added new API endpoints for managing widgets and sidebars within the application.
  • Bug Fixes

    • Adjusted permissions for various features, ensuring proper access levels for different user roles.
  • Documentation

    • Updated comments and structure in the selectors for better readability and organization.
    • Enhanced configurability of the dbData object for improved widget management.
  • Tests

    • Added a comprehensive test suite for live search functionality, validating various search scenarios.
  • Chores

    • Restructured widget and sidebar management in the database configuration for better organization.

Copy link
Contributor

coderabbitai bot commented Nov 1, 2024

Walkthrough

This pull request introduces extensive modifications to user permissions and capabilities across various features in the feature-map.yml file, particularly affecting admin, vendor, and customer roles. Key changes include restricting admin capabilities on the "Plugins" page, enhancing vendor permissions in product management, and enabling live search functionalities for customers. Additionally, a new LiveSearch class has been created to facilitate live search operations, and several new API endpoints and utility methods for managing widgets and sidebars have been added. The test suite for live search functionality has also been established.

Changes

File Path Change Summary
tests/pw/feature-map/feature-map.yml Updated permissions for admin, vendor, and customer roles across multiple sections, including disabling admin actions on "Plugins" and enhancing vendor capabilities.
tests/pw/pages/basePage.ts Added methods for typing and selecting options with load state; updated existing methods to include a clear parameter.
tests/pw/pages/liveSearchPage.ts Added LiveSearch class with a method for performing live searches.
tests/pw/pages/selectors.ts Renamed sections for consistency; added new selectors for vendor verification and live search functionalities.
tests/pw/tests/e2e/liveSearch.spec.ts Introduced a new test suite for live search functionality, including setup and multiple test cases.
tests/pw/tests/e2e/privacyPolicy.spec.ts Modified setup and teardown processes, commenting out some option updates.
tests/pw/utils/apiEndPoints.ts Added new API endpoints for managing widgets and sidebars.
tests/pw/utils/apiUtils.ts Introduced new methods in ApiUtils for widget and sidebar management.
tests/pw/utils/dbData.ts Restructured dbData object to enhance widget management; added sections for live search and sidebar configurations.
tests/pw/utils/testData.ts Added a new categories object in predefined test data for better organization.

Possibly related PRs

Suggested labels

QA approved

Poem

🐰 In the meadow where features bloom,
Permissions shift, dispelling gloom.
Vendors thrive, while admins pause,
Live search springs with joyful cause.
With every change, our code does dance,
A hop, a skip, a testing chance! 🌼


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
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: 10

🧹 Outside diff range and nitpick comments (7)
tests/pw/pages/liveSearchPage.ts (1)

9-12: Remove unnecessary constructor.

The constructor can be removed as it only calls super without additional initialization. TypeScript will automatically create this constructor.

export class LiveSearch extends BasePage {
-    constructor(page: Page) {
-        super(page);
-    }
🧰 Tools
🪛 Biome

[error] 10-12: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

tests/pw/tests/e2e/liveSearch.spec.ts (1)

8-48: Consider adding more test scenarios for comprehensive coverage.

The test suite would benefit from additional test cases:

  1. Empty search results scenario
  2. Search with special characters
  3. Error handling cases (e.g., network issues)
  4. Performance testing with large result sets

Example test case structure:

test('should handle empty search results gracefully', async () => {
    const nonExistentProduct = 'xyznonexistent123';
    const results = await customer.searchByLiveSearch(nonExistentProduct);
    expect(results).toHaveLength(0);
});

test('should handle special characters in search', async () => {
    const specialCharsProduct = '!@#$%^&*()';
    const results = await customer.searchByLiveSearch(specialCharsProduct);
    // Verify proper escaping and handling
});
tests/pw/utils/apiEndPoints.ts (2)

631-634: Fix parameter naming inconsistency in getSingleWidgetType.

The route parameter uses widget-types while the function parameter uses widgetId. Consider renaming for consistency:

-        getSingleWidgetType: (widgetId: string) => `${SERVER_URL}/wp/v2/widget-types/${widgetId}`,
+        getSingleWidgetType: (widgetTypeId: string) => `${SERVER_URL}/wp/v2/widget-types/${widgetTypeId}`,

635-638: Fix parameter casing inconsistency in sidebar endpoints.

The parameter uses camelCase inconsistently. Consider standardizing to sidebarId:

-        getSingleSidebar: (sideBarId: string) => `${SERVER_URL}/wp/v2/sidebars/${sideBarId}`,
-        updateSidebar: (sideBarId: string) => `${SERVER_URL}/wp/v2/sidebars/${sideBarId}`,
+        getSingleSidebar: (sidebarId: string) => `${SERVER_URL}/wp/v2/sidebars/${sidebarId}`,
+        updateSidebar: (sidebarId: string) => `${SERVER_URL}/wp/v2/sidebars/${sidebarId}`,
tests/pw/feature-map/feature-map.yml (1)

775-776: Fix comment formatting.

The comment formatting is inconsistent. The indentation of the commented admin section doesn't align with other sections in the file.

Apply this diff to fix the formatting:

-      #   admin:
-      #   admin can set Dokan live search settings [duplicate]: true
+  admin:
+      #admin can set Dokan live search settings [duplicate]: true
tests/pw/utils/dbData.ts (1)

784-785: Document the live search options.

Consider adding JSDoc comments to document:

  • The purpose of these settings
  • Valid values for live_search_option
  • Expected structure for dashboard_menu_manager
+/**
+ * Live search configuration
+ * @property {('old_live_search'|'suggestion_box')} live_search_option - The type of live search to use
+ * @property {Array} dashboard_menu_manager - Menu configuration for live search
+ */
 liveSearchSettings: {
     live_search_option: 'suggestion_box', // old_live_search,  suggestion_box
     dashboard_menu_manager: [],
 },
tests/pw/pages/basePage.ts (1)

302-306: Consider making delay and load state configurable.

The implementation is solid, combining load state waiting with text input efficiently. However, consider making the keystroke delay and load state type configurable parameters for better flexibility.

-async typeByPageAndWaitForLoadState(selector: string, text: string, clear = true): Promise<void> {
+async typeByPageAndWaitForLoadState(
+  selector: string,
+  text: string,
+  options: {
+    clear?: boolean;
+    delay?: number;
+    state?: 'load' | 'domcontentloaded' | 'networkidle';
+  } = {}
+): Promise<void> {
+  const { clear = true, delay = 200, state = 'domcontentloaded' } = options;
   if (clear) await this.clearInputField(selector);
-  await Promise.all([this.waitForLoadState(), this.page.locator(selector).pressSequentially(text, { delay: 200 })]);
+  await Promise.all([
+    this.waitForLoadState(state),
+    this.page.locator(selector).pressSequentially(text, { delay })
+  ]);
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 476a85d and 046a48e.

📒 Files selected for processing (10)
  • tests/pw/feature-map/feature-map.yml (1 hunks)
  • tests/pw/pages/basePage.ts (3 hunks)
  • tests/pw/pages/liveSearchPage.ts (1 hunks)
  • tests/pw/pages/selectors.ts (3 hunks)
  • tests/pw/tests/e2e/liveSearch.spec.ts (1 hunks)
  • tests/pw/tests/e2e/privacyPolicy.spec.ts (1 hunks)
  • tests/pw/utils/apiEndPoints.ts (1 hunks)
  • tests/pw/utils/apiUtils.ts (1 hunks)
  • tests/pw/utils/dbData.ts (3 hunks)
  • tests/pw/utils/testData.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/pw/utils/testData.ts
🧰 Additional context used
🪛 Biome
tests/pw/pages/liveSearchPage.ts

[error] 10-12: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

🔇 Additional comments (12)
tests/pw/pages/liveSearchPage.ts (2)

1-8: LGTM! Well-organized imports and selector definition.

The imports are properly structured, and the selector constant improves code maintainability.


14-29: 🛠️ Refactor suggestion

Add input validation and improve method documentation.

The method implementation looks solid but could benefit from the following improvements:

  1. Add input validation for the productName parameter
  2. Document the purpose of typing a space character
  3. Consider making the delay configurable
  4. Add JSDoc documentation for better maintainability

Here's a suggested improvement:

+/**
+ * Performs a live search for a product with optional category filtering
+ * @param productName - The name of the product to search for
+ * @param autoload - Whether to use autoload mode (default: false)
+ * @param categoryName - Optional category to filter results
+ * @throws {Error} If productName is empty
+ */
 async searchByLiveSearch(productName: string, autoload = false, categoryName?: string) {
+    if (!productName?.trim()) {
+        throw new Error('Product name cannot be empty');
+    }
+
     await this.gotoUntilNetworkidle(data.subUrls.frontend.myAccount);

     if (!autoload) {

Let's verify if similar search implementations exist in the codebase:

tests/pw/tests/e2e/privacyPolicy.spec.ts (2)

Line range hint 1-48: LGTM for the test implementation.

The test suite is well-structured with:

  • Clear separation of concerns
  • Proper test categorization using tags
  • Good coverage of both customer and admin scenarios
  • Appropriate use of page object pattern

19-20: Clarify the reason for commenting out widget setup.

The commented-out widget configuration could affect test isolation and the initial state of the tests. If these configurations are no longer needed, they should be removed. If they are still needed but temporarily disabled, please add a comment explaining why and create a tracking issue.

Let's verify if these widget configurations are still required:

tests/pw/tests/e2e/liveSearch.spec.ts (2)

1-7: LGTM! Well-organized imports.

The imports are properly structured and include all necessary dependencies for the test suite.


39-47: 🛠️ Refactor suggestion

Refactor duplicate database configuration.

The last two tests contain duplicate database update code. Consider moving this to a shared setup function.

Extract the database configuration:

+async function enableAutoloadContent() {
+    await dbUtils.updateOptionValue(dbData.dokan.optionName.liveSearch, { live_search_option: 'old_live_search' });
+}

 test('customer can search product using live search (autoload content)', { tag: ['@pro', '@customer'] }, async () => {
-    await dbUtils.updateOptionValue(dbData.dokan.optionName.liveSearch, { live_search_option: 'old_live_search' });
+    await enableAutoloadContent();
     await customer.searchByLiveSearch(data.predefined.simpleProduct.product1.name, true);
 });

Also, consider adding:

  1. Data cleanup between tests to ensure test isolation
  2. Retry logic or wait conditions to handle potential timing issues with search results
✅ Verification successful

Refactoring suggestion is valid, but test isolation is already handled

The suggestion to extract duplicate database configuration is valid and would improve code maintainability. However, the concerns about test isolation and wait conditions are already addressed:

  1. Test isolation is handled through afterAll which resets the live search settings to their original state
  2. The searchByLiveSearch implementation in liveSearchPage.ts includes proper wait conditions:
    • Uses waitForResponse for AJAX calls
    • Has visibility checks with toBeVisible
    • Includes network idle state checks

You can proceed with the refactoring suggestion for the duplicate database configuration, but the additional concerns are already properly handled.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if searchByLiveSearch has proper wait conditions
ast-grep --pattern 'class LiveSearch {
  $$$
  async searchByLiveSearch($$$) {
    $$$
    await $$$
    $$$
  }
  $$$
}'

Length of output: 123


Script:

#!/bin/bash
# Let's try to find the searchByLiveSearch method using ripgrep
rg -A 10 "searchByLiveSearch" 

# Also search for any test setup/cleanup patterns in the same file
rg -A 5 "beforeAll|beforeEach|afterAll|afterEach" "tests/pw/tests/e2e/liveSearch.spec.ts"

Length of output: 3683

tests/pw/utils/apiEndPoints.ts (1)

624-629: LGTM: Widget endpoints follow REST API best practices.

The implementation provides a complete set of CRUD operations with consistent URL structure and proper parameter typing.

tests/pw/feature-map/feature-map.yml (1)

778-781: LGTM: Live search permissions are properly configured.

The customer permissions for live search features are well-defined and comprehensive, covering both basic and advanced search capabilities:

  • Search with suggestion box (with/without category)
  • Search with autoload content (with/without category)

All permissions are appropriately set to true to enable these features.

Let's verify if the live search feature is properly integrated with the frontend:

tests/pw/utils/dbData.ts (1)

1304-1353: LGTM! Well-structured widget and sidebar configuration.

The configuration provides a clean separation between:

  • Widget definitions
  • Sidebar locations
  • Widget assignments
  • Widget-specific settings
tests/pw/pages/basePage.ts (1)

309-310: LGTM! Good addition of the clear parameter.

The addition of the optional clear parameter provides good flexibility while maintaining backward compatibility.

tests/pw/pages/selectors.ts (2)

2248-2254: LGTM! Live search settings selectors look good.

The selectors for live search settings are well-structured and follow the existing patterns in the codebase.


Line range hint 6902-7758: LGTM! Live search widget selectors are properly implemented.

The selectors for the live search widget functionality are well-organized and follow best practices:

  • Clear naming conventions
  • Proper use of template literals for dynamic selectors
  • Consistent structure with rest of the codebase

});

test.afterAll(async () => {
await dbUtils.updateOptionValue(dbData.dokan.optionName.privacyPolicy, { enable_privacy: 'on' });
await dbUtils.updateOptionValue(dbData.dokan.optionName.appearance, { contact_seller: 'on' });
await dbUtils.setOptionValue('sidebars_widgets', dbData.widget.emptySideBarsWidgets);
await dbUtils.setOptionValue('sidebars_widgets', dbData.emptySideBarsWidgets); // todo: remove in future
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Address the temporary solution in teardown.

The TODO comment suggests this is a temporary change. This should be properly tracked and resolved to maintain test reliability.

Consider:

  1. Creating a tracking issue for this temporary solution
  2. Adding a reference to the tracking issue in the TODO comment
  3. Documenting why the data structure was changed from dbData.widget.emptySideBarsWidgets to dbData.emptySideBarsWidgets

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 046a48e and 78e0d89.

📒 Files selected for processing (5)
  • tests/pw/feature-map/feature-map.yml (1 hunks)
  • tests/pw/pages/basePage.ts (3 hunks)
  • tests/pw/pages/selectors.ts (3 hunks)
  • tests/pw/utils/apiUtils.ts (1 hunks)
  • tests/pw/utils/testData.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/pw/feature-map/feature-map.yml
  • tests/pw/utils/testData.ts
🔇 Additional comments (15)
tests/pw/pages/selectors.ts (2)

2248-2254: LGTM! Live search settings selectors are well-structured.

The selectors for live search settings are properly organized and follow consistent naming conventions. The scoping to parent elements helps maintain selector specificity.


7796-7802: LGTM! Live search widget selectors are well-implemented.

The frontend live search widget selectors:

  • Use appropriate locator strategies (CSS for static elements, XPath for dynamic content)
  • Follow consistent naming conventions
  • Properly handle dynamic content with template literals
tests/pw/pages/basePage.ts (3)

314-317: Consider aligning typeAndWaitForLoadState with typeByPageAndWaitForLoadState.

This method has inconsistent behavior compared to typeByPageAndWaitForLoadState. The previous review comment is still applicable.


697-697: Efficient use of fill('') in clearInputField.

Using fill('') is a reliable and concise way to clear input fields. This improves the method's efficiency.


837-840: Great addition of a configurable load state parameter.

The update to selectByValueAndWaitForLoadState by adding the state parameter enhances flexibility and maintains consistency with other methods.

tests/pw/utils/apiUtils.ts (10)

1769-1772: getAllWidgets Method Implementation Looks Good

The getAllWidgets function correctly retrieves all widgets with optional authentication and follows consistent coding patterns.


1775-1778: getSingleWidget Method Implementation Looks Good

The getSingleWidget function properly fetches a single widget by its ID, maintaining consistency with similar methods.


1781-1784: createWidget Method Implementation Looks Good

The createWidget function accurately creates a new widget using the provided payload, aligning with the existing API utility patterns.


1787-1790: updateWidget Method Implementation Looks Good

The updateWidget function effectively updates an existing widget identified by its ID, using the appropriate HTTP method.


1793-1796: Unnecessary Payload in DELETE Request

The deleteWidget method includes a payload parameter and sends it in the DELETE request body. According to HTTP specifications, DELETE requests typically do not include a request body. This may lead to unexpected behavior or compatibility issues.

Consider removing the payload parameter:

-async deleteWidget(widgetId: string, payload: object, auth?: auth): Promise<[APIResponse, responseBody]> {
-    const [response, responseBody] = await this.delete(endPoints.wp.deleteWidget(widgetId), { data: payload, headers: auth });
+async deleteWidget(widgetId: string, auth?: auth): Promise<[APIResponse, responseBody]> {
+    const [response, responseBody] = await this.delete(endPoints.wp.deleteWidget(widgetId), { headers: auth });
     return [response, responseBody];
}

1801-1804: getAllWidgetTypes Method Implementation Looks Good

The getAllWidgetTypes function successfully retrieves all widget types and adheres to the established coding conventions.


1807-1810: Method Naming Consistency: Use Singular Form

The getSingleWidgetTypes method is intended to retrieve a single widget type, but the method name is pluralized. For clarity and consistency, the method name should be getSingleWidgetType.


1815-1818: getAllSidebars Method Implementation Looks Good

The getAllSidebars function correctly retrieves all sidebars, maintaining consistency with other retrieval methods.


1821-1824: getSingleSidebar Method Implementation Looks Good

The getSingleSidebar function properly fetches a sidebar by its ID, following the established patterns.


1827-1830: Inconsistent HTTP Method in updateSidebar

The updateSidebar method uses the POST HTTP method for an update operation. Consistency and RESTful conventions suggest using PUT or PATCH for updates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
QA approved This PR is approved by the QA team Test Automation
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant