-
-
Notifications
You must be signed in to change notification settings - Fork 107
fix: prevent IAsyncInitializer from running during test discovery when using InstanceMethodDataSource #4002
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
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
119 changes: 119 additions & 0 deletions
119
TUnit.TestProject/Bugs/3992/InstanceMethodDataSourceWithAsyncInitializerTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| using System.Collections.Concurrent; | ||
| using TUnit.Core.Interfaces; | ||
| using TUnit.TestProject.Attributes; | ||
|
|
||
| namespace TUnit.TestProject.Bugs._3992; | ||
|
|
||
| /// <summary> | ||
| /// Regression test for issue #3992: IAsyncInitializer should not run during test discovery | ||
| /// when using InstanceMethodDataSource with ClassDataSource. | ||
| /// | ||
| /// This test replicates the user's scenario where: | ||
| /// 1. A ClassDataSource fixture implements IAsyncInitializer (e.g., starts Docker containers) | ||
| /// 2. An InstanceMethodDataSource accesses data from that fixture | ||
| /// 3. The fixture should NOT be initialized during discovery - only during execution | ||
| /// | ||
| /// The bug caused Docker containers to start during test discovery (e.g., in IDE or --list-tests), | ||
| /// which was unexpected and resource-intensive. | ||
| /// </summary> | ||
| [EngineTest(ExpectedResult.Pass)] | ||
| public class InstanceMethodDataSourceWithAsyncInitializerTests | ||
| { | ||
| private static int _initializationCount; | ||
| private static int _testExecutionCount; | ||
| private static readonly ConcurrentBag<Guid> _observedInstanceIds = []; | ||
|
|
||
| /// <summary> | ||
| /// Simulates a fixture like ClientServiceFixture that starts Docker containers. | ||
| /// Implements IAsyncInitializer (NOT IAsyncDiscoveryInitializer) because the user | ||
| /// does not want initialization during discovery. | ||
| /// </summary> | ||
| public class SimulatedContainerFixture : IAsyncInitializer | ||
| { | ||
| private readonly List<string> _testCases = []; | ||
|
|
||
| /// <summary> | ||
| /// Unique identifier for this instance to verify sharing behavior. | ||
| /// </summary> | ||
| public Guid InstanceId { get; } = Guid.NewGuid(); | ||
|
|
||
| public bool IsInitialized { get; private set; } | ||
| public IReadOnlyList<string> TestCases => _testCases; | ||
|
|
||
| public Task InitializeAsync() | ||
| { | ||
| Interlocked.Increment(ref _initializationCount); | ||
| Console.WriteLine($"[SimulatedContainerFixture] InitializeAsync called on instance {InstanceId} (count: {_initializationCount})"); | ||
|
|
||
| // Simulate container startup that populates test data | ||
| _testCases.AddRange(["TestCase1", "TestCase2", "TestCase3"]); | ||
| IsInitialized = true; | ||
|
|
||
| return Task.CompletedTask; | ||
| } | ||
| } | ||
|
|
||
| [ClassDataSource<SimulatedContainerFixture>(Shared = SharedType.PerClass)] | ||
| public required SimulatedContainerFixture Fixture { get; init; } | ||
|
|
||
| /// <summary> | ||
| /// This property is accessed by InstanceMethodDataSource during discovery. | ||
| /// With the bug, accessing this would trigger InitializeAsync() during discovery. | ||
| /// After the fix, InitializeAsync() should only be called during test execution. | ||
| /// </summary> | ||
| public IEnumerable<string> TestExecutions => Fixture.TestCases; | ||
|
|
||
| [Test] | ||
| [InstanceMethodDataSource(nameof(TestExecutions))] | ||
| public async Task Test_WithInstanceMethodDataSource_DoesNotInitializeDuringDiscovery(string testCase) | ||
| { | ||
| Interlocked.Increment(ref _testExecutionCount); | ||
|
||
|
|
||
| // Track this instance to verify sharing | ||
| _observedInstanceIds.Add(Fixture.InstanceId); | ||
|
|
||
| // The fixture should be initialized by the time the test runs | ||
| await Assert.That(Fixture.IsInitialized) | ||
| .IsTrue() | ||
| .Because("the fixture should be initialized before test execution"); | ||
|
|
||
| await Assert.That(testCase) | ||
| .IsNotNullOrEmpty() | ||
| .Because("the test case data should be available"); | ||
|
|
||
| Console.WriteLine($"[Test] Executed with testCase='{testCase}', instanceId={Fixture.InstanceId}, " + | ||
| $"initCount={_initializationCount}, execCount={_testExecutionCount}"); | ||
| } | ||
|
|
||
| [After(Class)] | ||
| public static async Task VerifyInitializationAndSharing() | ||
| { | ||
| // With SharedType.PerClass, the fixture should be initialized exactly ONCE | ||
| // during test execution, NOT during discovery. | ||
| // | ||
| // Before the fix: _initializationCount would be 2+ (discovery + execution) | ||
| // After the fix: _initializationCount should be exactly 1 (execution only) | ||
|
|
||
| Console.WriteLine($"[After(Class)] Final counts - init: {_initializationCount}, exec: {_testExecutionCount}"); | ||
| Console.WriteLine($"[After(Class)] Unique instance IDs observed: {_observedInstanceIds.Distinct().Count()}"); | ||
|
|
||
| await Assert.That(_initializationCount) | ||
| .IsEqualTo(1) | ||
| .Because("IAsyncInitializer should only be called once during execution, not during discovery"); | ||
|
|
||
| await Assert.That(_testExecutionCount) | ||
| .IsEqualTo(3) | ||
| .Because("there should be 3 test executions (one per test case)"); | ||
|
|
||
| // Verify that all tests used the SAME fixture instance (SharedType.PerClass) | ||
| var uniqueInstanceIds = _observedInstanceIds.Distinct().ToList(); | ||
| await Assert.That(uniqueInstanceIds) | ||
| .HasCount().EqualTo(1) | ||
| .Because("with SharedType.PerClass, all tests should share the same fixture instance"); | ||
|
|
||
| // Reset for next run | ||
| _initializationCount = 0; | ||
| _testExecutionCount = 0; | ||
| _observedInstanceIds.Clear(); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical Test Design Flaw:
_testCasesstarts as an empty list and is only populated duringInitializeAsync(). After the fix,InitializeAsync()won't be called during discovery, soFixture.TestCaseswill be empty whenInstanceMethodDataSourceevaluatesTestExecutionsat line 64. This means zero test cases will be generated, and the test will never execute.This contradicts the test's purpose - the
After(Class)hook at line 88 expects to verify that exactly 3 tests ran and initialization happened once. But with empty test cases, no tests will run, and the verification will never execute.Solution: Initialize
_testCaseswith default data beforeInitializeAsync(), so test discovery can proceed:Note: If users genuinely need data populated during discovery (like the original issue #3992), they should use
IAsyncDiscoveryInitializerinstead ofIAsyncInitializer(see Bug 3997 test for correct pattern).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@copilot reanalyse