Skip to content

fix: prevent exceptions from manual test #53

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

Merged
merged 2 commits into from
Jun 18, 2025

Conversation

yulcat
Copy link
Contributor

@yulcat yulcat commented Jun 17, 2025

Description

This PR fixes an issue where exceptions could occur during manual test execution. The fix adds null checks for the _tcs (Task Completion Source) field in three key methods of the TestRunnerService class:

  1. RunStarted - Checks if _tcs is null before proceeding
  2. TestFinished - Adds null check before adding results
  3. RunFinished - Ensures _tcs is not null before building and setting the result

These changes prevent potential NullReferenceExceptions that could occur when test callbacks are triggered but no task is waiting for the results, which can happen during manual test execution.

Changes that Break Backward Compatibility

N/A

Documentation

N/A

Created with Palmier

Summary by CodeRabbit

  • Bug Fixes
    • Improved stability by preventing errors during test execution callbacks when certain internal states are uninitialized.

Copy link
Contributor

coderabbitai bot commented Jun 17, 2025

📝 Walkthrough

Walkthrough

Null checks were added for the private field _tcs in the RunStarted, TestFinished, and RunFinished methods of TestRunnerService.cs. These methods now return early if _tcs is null, preventing further execution and potential null reference errors during test run callbacks. Additionally, _tcs is set to null after completing the run in RunFinished.

Changes

File Change Summary
Editor/Services/TestRunnerService.cs Added null checks for _tcs in RunStarted, TestFinished, and RunFinished; reset _tcs to null after run completion.

Poem

In the warren where tests all hop and run,
A check for null keeps bugs on the run.
If _tcs is missing, we quietly retreat,
No exceptions to trip on our nimble feet.
Safe and sound, our code leaps ahead—
A rabbit’s work, with nothing to dread! 🐇


📜 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 516874b and 991b8e3.

📒 Files selected for processing (1)
  • Editor/Services/TestRunnerService.cs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Editor/Services/TestRunnerService.cs
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch feature/fix-test-error
  • Post Copyable Unit Tests in Comment

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

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

🧹 Nitpick comments (1)
Editor/Services/TestRunnerService.cs (1)

170-171: Race condition: _results is not thread-safe
TestFinished is called from Unity’s runner thread, while consumers may await the ExecuteTestsAsync task on a different thread. Concurrent writes/reads to _results without synchronisation can cause data races or InvalidOperationException during enumeration in BuildResultJson.

If you expect heavy parallelism, wrap the list access in a lock or switch to a thread-safe collection (e.g. ConcurrentBag<ITestResultAdaptor>). At minimum, document the thread-affinity assumption.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 219eccc and 516874b.

📒 Files selected for processing (1)
  • Editor/Services/TestRunnerService.cs (3 hunks)

Comment on lines +148 to +150
if (_tcs == null)
return;

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

Good defensive guard, but remember to reset _tcs after the run
Early-returning when _tcs is null prevents the NRE, ✔️.
However, once RunFinished completes _tcs keeps the completed TaskCompletionSource.
If the same TestRunnerService instance later triggers Unity-initiated callbacks (e.g. during a manual run, or while you’re only retrieving the test list) the stale _tcs reference will no longer be null, so the callbacks will start accumulating results into a stale list and may attempt to TrySetResult again, leading to:

  • InvalidOperationException: TaskCompletionSource<T> can only be set once
  • Incorrect aggregation of results from multiple, unrelated runs.

A minimal fix is to clear the field when the run is over:

@@
             var summary = BuildResultJson(_results, result);
             _tcs?.TrySetResult(summary);
+            // Prevent stale state on subsequent, unrelated callbacks
+            _tcs = null;

Optionally, you may also null-out _results for symmetry.

Also applies to: 167-169, 178-180

🤖 Prompt for AI Agents
In Editor/Services/TestRunnerService.cs around lines 148 to 150, after the early
return when _tcs is null, add code to reset _tcs to null once the run finishes
to avoid reusing a completed TaskCompletionSource and causing
InvalidOperationException or incorrect result aggregation. Similarly, apply this
reset pattern to lines 167-169 and 178-180. Optionally, also reset the _results
field to null for consistency after the run completes.

Copy link
Owner

@CoderGamester CoderGamester left a comment

Choose a reason for hiding this comment

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

Good finding and great fix
Approving the PR and merging
thank you @yulcat

@CoderGamester CoderGamester merged commit 10be316 into CoderGamester:main Jun 18, 2025
1 check passed
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