Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@nobodyiam
Copy link
Member

@nobodyiam nobodyiam commented May 4, 2025

  1. use Awaitility to make the unit tests more stable
  2. use Mockito to mock some necessary objects
  3. fix the potential concurrent race issue of remotingContextList

Summary by CodeRabbit

  • Tests
    • Improved reliability of heartbeat and command handler tests by replacing static waits and latches with asynchronous waiting using Awaitility.
    • Enhanced concurrency handling in tests with thread-safe collections and realistic mocking.
    • Updated test dependencies to include Awaitility and Mockito for more robust asynchronous and mocking support.

@coderabbitai
Copy link

coderabbitai bot commented May 4, 2025

Walkthrough

This change updates the Maven pom.xml to add two new test-scoped dependencies: awaitility and mockito-core. Correspondingly, two test classes (RuntimeClientHeartBeatTest and RpcCommandHandlerTest) are refactored to leverage Awaitility for asynchronous waiting, replacing static sleeps and latches. Additionally, mocking is improved in RpcCommandHandlerTest by introducing Mockito for realistic context simulation, and thread safety is enhanced by using a concurrent list. No changes are made to exported or public entity declarations.

Changes

File(s) Change Summary
pom.xml Added test-scoped dependencies: awaitility (4.3.0) and mockito-core (4.11.0).
src/test/java/com/alipay/remoting/rpc/heartbeat/RuntimeClientHeartBeatTest.java Refactored test to use Awaitility for asynchronous waiting instead of Thread.sleep; updated logging; clarified control flow for heartbeat enable/disable states.
src/test/java/com/alipay/remoting/rpc/protocol/RpcCommandHandlerTest.java Replaced CountDownLatch with Awaitility for async verification; switched to thread-safe CopyOnWriteArrayList; introduced Mockito-based mocks for context; improved concurrency handling and test setup.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Method
    participant Client as Client
    participant Heartbeat as Heartbeat Processor

    Test->>Client: Register heartbeat processor
    Test->>Client: Establish connection
    Test->>Heartbeat: Wait (Awaitility) until heartbeat received
    Test->>Client: Disable heartbeat
    Test->>Heartbeat: Wait (Awaitility) to confirm no new heartbeats
    Test->>Client: Enable heartbeat
    Test->>Heartbeat: Wait (Awaitility) for heartbeats to resume
Loading
sequenceDiagram
    participant Test as Test Method
    participant Handler as RpcCommandHandler
    participant Context as RemotingContext (mocked)
    participant List as remotingContextList (thread-safe)

    Test->>List: Clear list
    Test->>Handler: Send command (with mocked Context)
    Handler->>List: Add context on command handling
    Test->>List: Wait (Awaitility) until expected contexts present
Loading

Possibly related PRs

  • Release 1.6.11 #365: Updates the same RuntimeClientHeartBeatTest class, changing assertion style and project version, indicating overlapping test maintenance.

Suggested labels

cla:yes, size/XS

Suggested reviewers

  • xmtsui
  • EvenLjj

Poem

In the warren where tests once slept,
Awaitility hopped in, and promises were kept.
Mock bunnies pranced with Mockito’s might,
Heartbeats and handlers, all tested right.
No more waiting with sleepy delay,
Async assurance now leads the way!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1aa6eb2 and fd2790d.

📒 Files selected for processing (3)
  • pom.xml (1 hunks)
  • src/test/java/com/alipay/remoting/rpc/heartbeat/RuntimeClientHeartBeatTest.java (2 hunks)
  • src/test/java/com/alipay/remoting/rpc/protocol/RpcCommandHandlerTest.java (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: build (8)
  • GitHub Check: build (11)
  • GitHub Check: build (17)
  • GitHub Check: build (21)
🔇 Additional comments (13)
pom.xml (1)

137-148: Good addition of test libraries for improving test stability.

The addition of Awaitility and Mockito as test dependencies aligns perfectly with the PR's objective of making tests more stable. Awaitility (4.3.0) provides elegant ways to handle asynchronous conditions in tests, while Mockito (4.11.0) enables proper object mocking.

src/test/java/com/alipay/remoting/rpc/protocol/RpcCommandHandlerTest.java (7)

25-32: Good addition of necessary imports for mocking and concurrency utilities.

These imports support the enhanced testing approach using proper mocking and thread-safe collections.


41-42: Good adoption of Awaitility for asynchronous testing.

Using the static import for Awaitility makes the test code more readable by directly using the await() method.


51-51: Thread safety improvement with CopyOnWriteArrayList.

Excellent change from ArrayList to CopyOnWriteArrayList for remotingContextList, which addresses the potential race condition mentioned in the PR objectives. This thread-safe collection is optimized for scenarios with frequent reads and infrequent writes, making it perfect for test result collection.


57-66: Proper mocking implementation improves test realism.

The use of Mockito to create realistic ChannelHandlerContext and Channel mocks is a significant improvement over using null. This makes the test both more robust and more representative of real runtime conditions.


71-73: Good practice to clear test state before execution.

Explicitly clearing the remotingContextList before the test helps avoid false positives from previous test runs and ensures test isolation.


87-92: Excellent replacement of fixed waiting with Awaitility.

This change replaces what was likely a CountDownLatch with a more robust Awaitility waiting mechanism. The clear polling interval and timeout settings make the test more reliable and less prone to timing issues.


115-115: Improved assertion semantics.

Changed from assertNotNull to assertNotSame, which better reflects the intended test verification - ensuring we're working with a new context instance rather than just checking for non-null.

src/test/java/com/alipay/remoting/rpc/heartbeat/RuntimeClientHeartBeatTest.java (5)

39-42: Good imports for time handling and Awaitility.

These imports support the enhanced asynchronous testing approach.


100-115: Excellent refactoring of heartbeat verification with Awaitility.

The initial verification phase now uses Awaitility for a more reliable check that heartbeats are being sent. This replaces what was likely a static Thread.sleep followed by an assertion, providing a more robust way to handle the asynchronous nature of heartbeats.


116-117: Improved logging with parameterized messages.

Using parameterized logging is cleaner and more efficient than string concatenation.


118-135: Great implementation of heartbeat disable testing phase.

This section clearly separates test phases and uses Awaitility's during() method to verify that no heartbeats are received during the disabled period. The brief Thread.sleep is an appropriate choice to allow in-flight heartbeats to complete.


136-146: Well-structured re-enable phase with clear verification.

The final phase of the test cleanly resets the counter and uses Awaitility to verify heartbeats resume after re-enabling, making the test more reliable and less dependent on fixed timing.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • 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.

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

@nobodyiam nobodyiam requested review from EvenLjj and chuailiwu and removed request for chuailiwu May 11, 2025 03:06
Copy link
Collaborator

@chuailiwu chuailiwu left a comment

Choose a reason for hiding this comment

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

LGTM

@chuailiwu chuailiwu merged commit 48255c0 into sofastack:master Jun 9, 2025
5 checks passed
@nobodyiam nobodyiam deleted the fix-unit-tests branch June 10, 2025 01:28
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.

2 participants