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 Api tests, Fix coverage issue #2376

Merged
merged 1 commit into from
Sep 23, 2024

Conversation

shashwatahalder01
Copy link
Contributor

@shashwatahalder01 shashwatahalder01 commented Sep 23, 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

    • Added support for retrieving, creating, and deleting announcement notices.
    • Introduced functionality for linked products and reverse withdrawal transactions.
    • New payload structure for reverse withdrawal transactions.
    • New schema for linked products to enhance data structure.
  • Bug Fixes

    • Corrected a typographical error in the payloads object.
  • Documentation

    • Updated coverage tags for various API endpoints to reflect new functionalities and improvements.

@shashwatahalder01 shashwatahalder01 self-assigned this Sep 23, 2024
Copy link
Contributor

coderabbitai bot commented Sep 23, 2024

Walkthrough

The changes encompass the addition of new test cases, coverage tags, and modifications to existing schemas and endpoints across several files. New functionality related to announcements, linked products, reverse withdrawals, and shipping classes has been introduced. Additionally, corrections were made to variable names and schema definitions to enhance data structure and type definitions.

Changes

Files Change Summary
tests/pw/tests/api/announcements.spec.ts, tests/pw/tests/api/products.spec.ts, tests/pw/tests/api/reverseWithdrawal.spec.ts, tests/pw/tests/api/withdraws.spec.ts New coverage tags added for various API endpoints and new test cases introduced for announcements, linked products, and reverse withdrawals.
tests/pw/tests/api/shippingStatus.spec.ts Modifications to regex patterns for order and shipment IDs, and a new coverage tag for a DELETE method added.
tests/pw/utils/apiEndPoints.ts New endpoints for creating reverse withdrawals and retrieving linked products added; existing shipping class endpoints reorganized.
tests/pw/utils/payloads.ts Correction of a variable name and addition of a new object for reverse withdrawal transactions.
tests/pw/utils/schemas.ts Updates to productSchema and new linkedProductSchema introduced, enhancing type definitions and data structure.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant API
    participant Database

    User->>API: Request to create reverse withdrawal
    API->>Database: Store reverse withdrawal transaction
    Database-->>API: Confirm transaction stored
    API-->>User: Return success response
Loading

🐰 In the code, we hop and play,
New tests and tags brighten the day!
With schemas refined, our paths align,
For linked products and withdrawals, we shine!
So let’s celebrate with joy and cheer,
CodeRabbit's magic is finally here! 🥕✨


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

Outside diff range and nitpick comments (7)
tests/pw/tests/api/shippingStatus.spec.ts (2)

1-7: LGTM! Coverage tags updated correctly.

The changes to the coverage tags are good:

  1. Simplified regex patterns improve readability.
  2. Added DELETE method coverage tag for completeness.

Consider moving the comment about the DELETE method not existing in the Dokan API to the same line as the coverage tag for better readability:

-//COVERAGE_TAG: DELETE /dokan/v1/shipping-status/orders/(?P<order_id>[\d]+)/shipment/(?P<id>[\d]+)
-// delete method doesn't exists on dokan
+//COVERAGE_TAG: DELETE /dokan/v1/shipping-status/orders/(?P<order_id>[\d]+)/shipment/(?P<id>[\d]+) // delete method doesn't exist in Dokan API

DELETE operations detected without corresponding test cases.

The codebase includes the following DELETE methods:

  • delete_item_permissions_check and delete_item in ProductAttributeTermsController.php
  • delete_item_permissions_check in ProductAttributeController.php
  • delete_item_permissions_check and delete_item in WithdrawController.php

It's recommended to add test cases for these DELETE operations to ensure comprehensive coverage and validate their behavior.

Analysis chain

Line range hint 9-71: Verify DELETE operation status and consider adding a test case if applicable.

The test cases cover GET, POST, and PUT operations as mentioned in the coverage tags. However, there's no test case for the DELETE operation.

Could you please confirm if the DELETE operation is truly not implemented in the Dokan API? If it is implemented or planned for the near future, consider adding a test case for it. If it's not implemented and not planned, the current set of test cases is complete.

To verify the implementation status, you can run the following command:

If the search returns results, it might indicate that the DELETE method is implemented, and we should add a test case for it.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any DELETE method implementation in the codebase
rg --type php 'function\s+delete_item' -g 'includes/REST/*.php'

Length of output: 568

tests/pw/tests/api/reverseWithdrawal.spec.ts (1)

63-69: LGTM: Well-structured test case added

The new test case for creating a reverse withdrawal transaction is well-structured and follows the established patterns in the file. It correctly uses apiUtils methods, validates the response, and uses appropriate authentication.

Consider adding a comment explaining the purpose of this test case, similar to other tests in the file. This would improve readability and maintainability. For example:

// Test creating a reverse withdrawal transaction with valid data
test('create a reverse withdrawal transaction', { tag: ['@lite'] }, async () => {
    // ... (rest of the test case)
});
tests/pw/tests/api/announcements.spec.ts (1)

Line range hint 91-112: Existing tests align well with new coverage tags.

The existing test cases for announcement notices (get, update, delete) align perfectly with the newly added coverage tags. This ensures good test coverage for these endpoints.

For consistency, consider renaming the "update an announcement notice" test to "create/update an announcement notice" since it uses a POST request, which could be used for both creating and updating.

Consider applying this minor change for improved clarity:

-    test('update an announcement notice', { tag: ['@pro'] }, async () => {
+    test('create/update an announcement notice', { tag: ['@pro'] }, async () => {
tests/pw/tests/api/products.spec.ts (1)

144-150: LGTM: New test case added for linked products.

The new test case for retrieving linked products is well-structured and follows the general pattern of other tests in the file. It correctly uses the PRODUCT_ID environment variable and performs appropriate assertions.

For consistency with other tests in this file, consider moving the apiUtils initialization to a beforeAll hook within a test.describe block, similar to the structure used for other API version tests. This would also allow for proper cleanup in an afterAll hook.

Here's a suggested refactor:

test.describe('linked products api test v2', () => {
  let apiUtils: ApiUtils;

  test.beforeAll(async () => {
    apiUtils = new ApiUtils(await request.newContext());
  });

  test.afterAll(async () => {
    await apiUtils.dispose();
  });

  test('get all linked products', { tag: ['@pro', '@v2'] }, async () => {
    const [response, responseBody] = await apiUtils.get(endPoints.getAllLinkedProducts(PRODUCT_ID));
    expect(response.ok()).toBeTruthy();
    expect(responseBody).toBeTruthy();
    expect(responseBody).toMatchSchema(schemas.productsSchema.linkedProductsSchema);
  });
});

This structure ensures proper setup and teardown of resources for the test case.

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

3953-3958: LGTM: createReverseWithdrawal object is well-structured.

The object properties are clearly defined and include helpful comments for the trn_type options.

Consider using a number type for the credit property instead of a string, unless string is specifically required by the API:

-        credit: '100',
+        credit: 100,
tests/pw/utils/schemas.ts (1)

Line range hint 2257-2269: Consider coercing numeric and date fields in reverseWithdrawalTransactionsSchema

The fields debit, credit, balance, and trn_date in reverseWithdrawalTransactionsSchema are defined as z.string().or(z.number()) and z.string(). If these fields are expected to represent numeric and date values, consider using z.coerce.number() and z.coerce.date() respectively to ensure consistent data types.

Apply this diff to update the fields:

-                    trn_date: z.string(), // Assuming trn_date is a string representation of a date
+                    trn_date: z.coerce.date(),
-                    debit: z.string().or(z.number()),
+                    debit: z.coerce.number(),
-                    credit: z.string().or(z.number()),
+                    credit: z.coerce.number(),
-                    balance: z.string().or(z.number()),
+                    balance: z.coerce.number(),
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between dcec102 and ab333bf.

Files selected for processing (8)
  • tests/pw/tests/api/announcements.spec.ts (1 hunks)
  • tests/pw/tests/api/products.spec.ts (2 hunks)
  • tests/pw/tests/api/reverseWithdrawal.spec.ts (2 hunks)
  • tests/pw/tests/api/shippingStatus.spec.ts (1 hunks)
  • tests/pw/tests/api/withdraws.spec.ts (1 hunks)
  • tests/pw/utils/apiEndPoints.ts (3 hunks)
  • tests/pw/utils/payloads.ts (1 hunks)
  • tests/pw/utils/schemas.ts (8 hunks)
Additional comments not posted (14)
tests/pw/tests/api/reverseWithdrawal.spec.ts (2)

5-5: LGTM: Coverage tag added correctly

The new coverage tag for the POST endpoint of reverse withdrawal transactions is correctly formatted and placed. This addition improves test coverage tracking.


Line range hint 1-85: Overall assessment: Excellent additions to test coverage

The changes in this file enhance the test suite for reverse withdrawal functionality. The new coverage tag and test case are well-implemented and consistent with the existing code structure. These additions will help ensure the reliability of the reverse withdrawal transaction creation process.

tests/pw/tests/api/announcements.spec.ts (1)

8-10: LGTM! New coverage tags added correctly.

The new coverage tags for announcement notice endpoints (GET, POST, DELETE) have been added correctly and are consistent with the existing tag format. This is a good addition to track API coverage for these endpoints.

To ensure that the test suite covers these new endpoints, please run the following script:

This script will help confirm that corresponding test cases have been implemented for these new endpoints.

Verification successful

Tests for the new announcement notice endpoints are present.

The executed shell script confirmed that test cases for GET, POST, and DELETE announcement notice endpoints are implemented in tests/pw/tests/api/announcements.spec.ts. The test suite adequately covers these new endpoints.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the presence of tests for the new announcement notice endpoints.

# Test: Search for test cases related to the new endpoints
rg --type typescript 'test\(.*announcement notice' tests/pw/tests/api/announcements.spec.ts

Length of output: 128


Script:

#!/bin/bash
# Description: Verify the presence of tests for the new announcement notice endpoints.

# Test: Search for test cases related to the new endpoints using the correct file type.

rg --type ts 'test\(.*announcement notice' tests/pw/tests/api/announcements.spec.ts

Length of output: 311

tests/pw/tests/api/withdraws.spec.ts (2)

Line range hint 114-120: LGTM: Test cases implemented for new withdraw charges endpoints.

The test cases for 'get all withdraw method charges' and 'get withdraw charge details' are well-implemented:

  • They use appropriate API calls to the new endpoints.
  • The responses are checked for successful status codes.
  • The response bodies are validated against the corresponding schemas.

This ensures good coverage for the newly added endpoints.

Also applies to: 122-128


9-10: LGTM: New coverage tags added for withdraw charges endpoints.

The addition of coverage tags for GET /dokan/v1/withdraw/charges and GET /dokan/v1/withdraw/charge is appropriate and aligns with the existing structure of the file.

Let's verify if corresponding test cases exist for these new endpoints:

Verification successful

Action Required: Correct the shell scripts to search for the new withdraw charges test cases.


Action Required: Verify the existence of test cases for the new withdraw charges endpoints by listing all test functions in the file.


Action Required: Extract detailed test case descriptions to verify coverage for new withdraw charges endpoints.


: Coverage tags for GET /dokan/v1/withdraw/charges and GET /dokan/v1/withdraw/charge have corresponding test cases (get all withdraw method charges and get withdraw charge details). The tests adequately cover the newly tagged endpoints.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for test cases related to the new withdraw charges endpoints

# Test: Search for test cases using the new endpoints
rg --type typescript 'test\(.*getAllWithdrawMethodCharges' tests/pw/tests/api/withdraws.spec.ts
rg --type typescript 'test\(.*getWithdrawCharge' tests/pw/tests/api/withdraws.spec.ts

Length of output: 255


Script:

# Description: Corrected shell scripts to check for test cases related to the new withdraw charges endpoints

# Test: Search for test cases using the new endpoints without specifying an unrecognized file type
rg 'test\(.*getAllWithdrawMethodCharges' tests/pw/tests/api/withdraws.spec.ts
rg 'test\(.*getWithdrawCharge' tests/pw/tests/api/withdraws.spec.ts

Length of output: 149


Script:

# Description: List all test function names in withdraws.spec.ts to identify relevant test cases

rg 'test\(' tests/pw/tests/api/withdraws.spec.ts --no-filename --only-matching --unrestricted

Length of output: 161


Script:

# Description: Extract all test case descriptions in withdraws.spec.ts to identify relevant test cases

rg "test\(['\"](.*?)['\"]" tests/pw/tests/api/withdraws.spec.ts --only-matching --no-filename --color never

Length of output: 442

tests/pw/tests/api/products.spec.ts (1)

25-25: LGTM: New coverage tag added correctly.

The new coverage tag for the linked products endpoint is properly formatted and placed alongside other similar tags. This addition helps maintain accurate test coverage documentation.

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

219-219: LGTM: New endpoint added for reverse withdrawal transactions.

The createReverseWithdrawalTransactions endpoint has been correctly added to the endPoints object. It follows the existing naming conventions and URL structure patterns.


304-305: LGTM: New endpoint added for retrieving linked products.

The getAllLinkedProducts endpoint has been correctly added to the endPoints object. It follows the existing naming conventions and properly includes the productId as a parameter. The URL structure with a query parameter is appropriate for this type of request.


514-521: LGTM: Shipping class endpoints reorganized.

The shipping class endpoints have been appropriately moved to the wc object, which is a more suitable location for WooCommerce-specific endpoints. The move maintains consistent naming conventions and URL structures. All necessary CRUD operations and the batch update endpoint are included, providing a complete set of operations for shipping classes.

tests/pw/utils/payloads.ts (2)

3951-3952: LGTM: Random number generation looks good.

The randomNumber property is correctly implemented using faker.js to generate a random integer between 2 and 100.


3951-3958: Overall, the code looks good and is well-structured.

Both the randomNumber property and createReverseWithdrawal object are implemented correctly. The random number generation is straightforward, and the reverse withdrawal object provides a clear structure for creating transactions. The suggested minor improvement for the credit property type is optional and depends on the API requirements.

tests/pw/utils/schemas.ts (3)

1705-1705: Include linkedProductsSchema in exports if necessary

The linkedProductsSchema is defined as z.array(linkedProductSchema). Ensure that this new schema is correctly exported and utilized where necessary in the codebase.


2238-2239: Include required fields in createReverseWithdrawalTransaction schema

The createReverseWithdrawalTransaction schema defines trn_id as z.string().or(z.number()). Verify that all necessary fields for creating a reverse withdrawal transaction are included, and consider adding validation for other required fields if applicable.

Also applies to: 2275-2277


182-186: Verify the attributes field type in linkedProductSchema

The attributes field in linkedProductSchema is defined as z.array(productAttributeSchema).or(z.object({ pa_sizes: z.any() })). Please confirm that this accurately represents the possible data structures returned by the API. If attributes can be both an array and an object, consider using z.union([z.array(productAttributeSchema), z.object({ pa_sizes: z.any() })]) for clarity.

Run the following script to verify the attributes field usage:

tests/pw/utils/schemas.ts Show resolved Hide resolved
tests/pw/utils/schemas.ts Show resolved Hide resolved
tests/pw/utils/schemas.ts Show resolved Hide resolved
tests/pw/utils/schemas.ts Show resolved Hide resolved
tests/pw/utils/schemas.ts Show resolved Hide resolved
@shashwatahalder01 shashwatahalder01 merged commit 4ce4e2d into getdokan:develop Sep 23, 2024
2 checks passed
@shashwatahalder01 shashwatahalder01 deleted the apitests branch September 24, 2024 06:51
@shashwatahalder01 shashwatahalder01 added the QA approved This PR is approved by the QA team label Sep 25, 2024
This was referenced Sep 26, 2024
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