Skip to content

🧪Announcements/fixes#2820

Open
shohan0120 wants to merge 3 commits intodevelopfrom
announcements/fixes
Open

🧪Announcements/fixes#2820
shohan0120 wants to merge 3 commits intodevelopfrom
announcements/fixes

Conversation

@shohan0120
Copy link
Contributor

@shohan0120 shohan0120 commented Jul 30, 2025

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

  • Bug Fixes

    • Improved authentication handling in announcements API tests to resolve authorization errors.
    • Enhanced error handling and type checks in test setup and utility methods to prevent runtime failures.
    • Fixed issues with undefined announcement IDs and missing notices, ensuring tests skip gracefully when data is unavailable.
    • Addressed schema validation and response handling for batch update operations.
  • Chores

    • Updated default base URL for test environments to a new domain.
    • Added a test run summary file for tracking test results.
  • Refactor

    • Improved robustness and type safety in utility methods and test setup procedures.

- Fix authentication errors (401/403) by adding adminAuth headers
- Resolve undefined announcement IDs in test setup
- Add type safety to getAllItems method to prevent crashes
- Update updateBatchAnnouncements return type for consistency
- Add graceful handling for missing announcement notices
- Fix schema validation references
- Add comprehensive changelog

Test Results:
- Before: 7 failed, 14 passed
- After: 0 failed, 7 passed, 3 skipped

Files changed:
- tests/pw/tests/api/announcements.spec.ts
- tests/pw/utils/apiUtils.ts
- CHANGELOG-announcements-fixes.md (new)

Ready for CI/CD deployment and GitHub Actions.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 30, 2025

Walkthrough

This update refines the Dokan announcements API test suite and supporting utilities. Key changes include improved authentication handling, robust error management, type safety enhancements, and updated return types for certain utilities. Default test URLs are updated, and test setup scripts now better handle auxiliary failures. Minor schema and logic adjustments further stabilize test execution.

Changes

Cohort / File(s) Change Summary
Announcements API Test Suite
tests/pw/tests/api/announcements.spec.ts
Ensured admin authentication for all announcement API calls, improved error handling for notice ID retrieval, conditionally skipped tests when prerequisites are missing, updated batch update logic, and removed certain schema validations and restore operations.
API Utilities
tests/pw/utils/apiUtils.ts
Added array type checks in getAllItems, changed updateBatchAnnouncements to return both API response and body, and ensured announcement IDs are stringified before use. Improved type safety and response handling.
Test Setup Enhancements
tests/pw/tests/e2e/_auth.setup.ts
Wrapped vendor creation and related operations in try-catch blocks, improved error logging, added type assertions for login calls, and handled nonce retrieval failures gracefully. Enhanced robustness of test setup.
Database Utilities
tests/pw/utils/dbUtils.ts
Added safety checks for user meta retrieval and updated merging logic in updateUserMeta to prevent errors when current meta is absent.
Test Configuration
tests/pw/api.config.ts, tests/pw/e2e.config.ts
Changed default base URL from http://localhost:9999 to https://dokan-atutomation.test if BASE_URL is unset. No other configuration changes.
Test Results Tracking
test-results/.last-run.json
Added a JSON file summarizing test run results, indicating no failed tests despite an overall "failed" status.
Changelog
CHANGELOG-announcements-fixes.md
Added a detailed changelog describing the fixes and improvements made to the announcements API test suite and utilities.

Sequence Diagram(s)

sequenceDiagram
    participant TestSuite as Announcements Test
    participant ApiUtils as API Utilities
    participant Server as Dokan API Server

    TestSuite->>ApiUtils: createAnnouncement(auth: admin)
    ApiUtils->>Server: POST /announcements (admin auth)
    Server-->>ApiUtils: Announcement ID

    TestSuite->>ApiUtils: getAllAnnouncements(auth: admin)
    ApiUtils->>Server: GET /announcements (admin auth)
    Server-->>ApiUtils: [Announcement objects]

    TestSuite->>ApiUtils: updateBatchAnnouncements(action, ids, auth: admin)
    ApiUtils->>Server: POST /announcements/batch (admin auth)
    Server-->>ApiUtils: [APIResponse, responseBody]
    ApiUtils-->>TestSuite: [APIResponse, responseBody]

    TestSuite->>ApiUtils: getAnnouncementNotice(id, auth: vendor)
    ApiUtils->>Server: GET /announcements/{id}/notice (vendor auth)
    Server-->>ApiUtils: Notice object or error
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Possibly related PRs

  • Add Api tests, Fix coverage issue #2376: Both PRs modify the announcements.spec.ts file, focusing on announcement API tests, authentication, and handling of announcement notices, indicating a direct connection in improving the robustness and coverage of announcement API tests.

Suggested labels

QA approved, Test Automation

Poem

🐇
In the warren where the tests all hop,
We fixed the bugs that made them stop.
With headers set and types in line,
Announcements now behave just fine.
The CI burrow runs with cheer—
Robust and stable, far and near!
🥕

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch announcements/fixes

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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.

@shohan0120 shohan0120 requested a review from mrabbani July 30, 2025 09:35
@shohan0120 shohan0120 changed the title Announcements/fixes 🧪Announcements/fixes Jul 30, 2025
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

🧹 Nitpick comments (1)
CHANGELOG-announcements-fixes.md (1)

1-157: Excellent comprehensive changelog documentation!

The changelog provides thorough documentation of the fixes with clear problem/solution structure, impact analysis, and verification results. The format is professional and will be valuable for future reference.

Minor improvement - add language specifications to fenced code blocks to resolve markdown linting warnings:

-```
+```text
❌ 7 failed tests
❌ 14 passed tests  
❌ Authentication errors (401/403)
❌ Undefined ID errors
❌ TypeError crashes
❌ Schema validation failures
-```
+```

-```
+```text
✅ 0 failed tests
✅ 7 passed tests
✅ 3 skipped tests (gracefully handled)
✅ All authentication working
✅ All API calls successful
✅ No crashes or errors
-```
+```
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 93c4270 and 5a1263a.

📒 Files selected for processing (8)
  • CHANGELOG-announcements-fixes.md (1 hunks)
  • test-results/.last-run.json (1 hunks)
  • tests/pw/api.config.ts (1 hunks)
  • tests/pw/e2e.config.ts (1 hunks)
  • tests/pw/tests/api/announcements.spec.ts (1 hunks)
  • tests/pw/tests/e2e/_auth.setup.ts (4 hunks)
  • tests/pw/utils/apiUtils.ts (2 hunks)
  • tests/pw/utils/dbUtils.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
tests/pw/utils/dbUtils.ts (1)
tests/pw/utils/helpers.ts (1)
  • helpers (7-547)
tests/pw/tests/api/announcements.spec.ts (3)
tests/pw/utils/payloads.ts (1)
  • payloads (9-5094)
tests/pw/utils/apiEndPoints.ts (1)
  • endPoints (6-649)
tests/pw/pages/announcementsPage.ts (2)
  • AnnouncementsPage (12-151)
  • updateAnnouncement (83-108)
CHANGELOG-announcements-fixes.md (1)
tests/pw/pages/announcementsPage.ts (10)
  • AnnouncementsPage (12-151)
  • updateAnnouncement (83-108)
  • vendorAnnouncementsRenderProperly (126-133)
  • editAnnouncement (74-80)
  • adminAnnouncementsRenderProperly (20-43)
  • updateAnnouncementFields (46-64)
  • announcementBulkAction (111-121)
  • vendorViewAnnouncement (136-143)
  • vendorDeleteAnnouncement (146-150)
  • addAnnouncement (67-71)
🪛 markdownlint-cli2 (0.17.2)
CHANGELOG-announcements-fixes.md

89-89: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


99-99: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🔇 Additional comments (12)
tests/pw/utils/apiUtils.ts (2)

133-133: LGTM! Excellent defensive programming.

The type check prevents potential runtime errors when the API response is not an array. This addresses the issue mentioned in the changelog about TypeErrors from assuming responses are always arrays.


1058-1064: Good consistency improvements with explicit type conversion.

The changes improve consistency with other batch methods by:

  1. Returning both APIResponse and responseBody (consistent with other batch methods)
  2. Explicitly converting IDs to strings to prevent type mismatches

Note that this is a breaking change - callers expecting only responseBody will need to be updated to handle the new tuple return type.

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

51-56: Excellent defensive programming improvement!

The safety check prevents potential runtime errors when the database query returns empty results or fails. This aligns well with the broader robustness improvements across the test suite.


77-77: LGTM! Proper handling of null currentMetaValue.

The condition correctly prevents attempting to merge when currentMetaValue is null or undefined (which can now happen due to the safety check in getUserMeta). Using updatedMetaValue directly as the fallback is the appropriate behavior.

tests/pw/tests/e2e/_auth.setup.ts (4)

25-25: Good type safety improvement.

The explicit type assertion ensures the login method receives the correct interface type, improving TypeScript type checking and preventing potential runtime errors.


39-64: Excellent error handling and resilience improvement!

The nested try-catch structure is well-designed:

  • Main vendor creation failure falls back to existing vendor ID
  • Individual operations (store review, map location) can fail without stopping the flow
  • Clear logging helps with debugging
  • Tests can continue even when auxiliary setup steps fail

This significantly improves test stability and reduces false failures.


72-96: LGTM! Consistent error handling pattern.

The same robust error handling approach as vendor1 with appropriate fallback ID (5). The consistency across vendor setups improves maintainability.


108-115: Good defensive approach for optional setup step.

Gracefully handles dashboard access failures and provides a fallback nonce value. This prevents the entire test setup from failing due to non-critical operations, improving overall test reliability.

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

25-38: Excellent setup improvements addressing key issues!

The changes fix critical problems:

  • Admin authentication ensures valid announcement IDs are generated
  • Comprehensive error handling prevents failures when announcement notices don't exist
  • Clear logging aids debugging
  • Graceful fallback allows tests to continue appropriately

46-81: Systematic authentication fix resolves 401/403 errors.

All announcement API operations now consistently include admin authentication headers. This addresses the "Sorry, you are not allowed to do that" errors mentioned in the changelog and ensures proper access to protected endpoints.


88-93: Comprehensive batch operation fixes.

The changes address multiple issues:

  • Admin authentication for fetching announcements
  • Type safety with string conversion and null checking (|| [])
  • Proper destructuring matching the updated updateBatchAnnouncements return type
  • Improved error resilience

98-116: Excellent graceful test skipping implementation.

The conditional test.skip() calls prevent false failures when announcement notices aren't available. Clear skip messages help understand test results, and the pattern is consistently applied across all notice-related tests.

Comment on lines +1 to +4
{
"status": "failed",
"failedTests": []
} No newline at end of file
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

Consider excluding test artifact files from the repository.

This appears to be a test results artifact file that shouldn't be committed to the repository. Additionally, the status shows "failed" but with an empty failedTests array, which seems inconsistent.

Consider adding test-results/ to your .gitignore file to prevent test artifacts from being committed:

+test-results/

Also, please verify the test status - a "failed" status with no failed tests might indicate a test infrastructure issue that needs investigation.

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

🤖 Prompt for AI Agents
In test-results/.last-run.json at lines 1 to 4, this test results artifact file
should be excluded from the repository to avoid committing transient test data.
Add the test-results/ directory to your .gitignore file to prevent these files
from being tracked. Additionally, investigate why the status is "failed" while
the failedTests array is empty, as this inconsistency may indicate an issue with
the test infrastructure that needs to be resolved.

use: {
/* Base URL */
baseURL: BASE_URL ?? 'http://localhost:9999',
baseURL: BASE_URL ?? 'https://dokan-atutomation.test',
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

Typo in default baseURL will break every API test run

'https://dokan-atutomation.test' contains a misspelling — “atutomation” → “automation”.
Because Playwright falls back to this value whenever BASE_URL is unset, the entire API suite will try to hit a non-resolving domain and instantly fail.

-        baseURL: BASE_URL ?? 'https://dokan-atutomation.test',
+        baseURL: BASE_URL ?? 'https://dokan-automation.test',

(Or keep the previous http://localhost:9999 default if that is still the canonical local target.)

Also consider extracting this fallback into a single shared constant to avoid copy-paste errors across config files.

📝 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
baseURL: BASE_URL ?? 'https://dokan-atutomation.test',
baseURL: BASE_URL ?? 'https://dokan-automation.test',
🤖 Prompt for AI Agents
In tests/pw/api.config.ts at line 62, the default baseURL contains a typo
"atutomation" instead of "automation," causing API tests to fail when BASE_URL
is unset. Correct the URL to "https://dokan-automation.test" or revert to the
previous default "http://localhost:9999" if that is the intended local target.
Additionally, extract this fallback URL into a shared constant to prevent
similar typos across config files.

navigationTimeout: 20 * 1000,
/* Base URL */
baseURL: BASE_URL ?? 'http://localhost:9999',
baseURL: BASE_URL ?? 'https://dokan-atutomation.test',
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

Replicates the same misspelled baseURL; E2E suite will also fail

The same typo appears here; please correct it to the intended host or revert to the original localhost value. Duplicating the literal string in multiple configs invites this class of error—centralising the default in one module/env var will keep them in sync.

-        baseURL: BASE_URL ?? 'https://dokan-atutomation.test',
+        baseURL: BASE_URL ?? 'https://dokan-automation.test',
🤖 Prompt for AI Agents
In tests/pw/e2e.config.ts at line 74, the baseURL value contains a misspelled
host 'https://dokan-atutomation.test'. Correct the typo to the intended host or
revert to the original localhost default. To prevent such errors, centralize the
default baseURL in a single module or environment variable and import it here
instead of duplicating the string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments