|
| 1 | +using System.Collections.Concurrent; |
| 2 | +using TUnit.Core.Interfaces; |
| 3 | +using TUnit.TestProject.Attributes; |
| 4 | + |
| 5 | +namespace TUnit.TestProject.Bugs._3992; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Regression test for issue #3992: IAsyncInitializer should not run during test discovery |
| 9 | +/// when using InstanceMethodDataSource with ClassDataSource. |
| 10 | +/// |
| 11 | +/// This test replicates the user's scenario where: |
| 12 | +/// 1. A ClassDataSource fixture implements IAsyncInitializer (e.g., starts Docker containers) |
| 13 | +/// 2. An InstanceMethodDataSource returns predefined test case identifiers |
| 14 | +/// 3. The fixture should NOT be initialized during discovery - only during execution |
| 15 | +/// |
| 16 | +/// The key insight is that test case IDENTIFIERS are known ahead of time (predefined), |
| 17 | +/// but the actual fixture initialization (Docker containers, DB connections, etc.) |
| 18 | +/// should only happen when tests actually execute. |
| 19 | +/// |
| 20 | +/// The bug caused Docker containers to start during test discovery (e.g., in IDE or --list-tests), |
| 21 | +/// which was unexpected and resource-intensive. |
| 22 | +/// </summary> |
| 23 | +[EngineTest(ExpectedResult.Pass)] |
| 24 | +public class InstanceMethodDataSourceWithAsyncInitializerTests |
| 25 | +{ |
| 26 | + private static int _initializationCount; |
| 27 | + private static int _testExecutionCount; |
| 28 | + private static readonly ConcurrentBag<Guid> _observedInstanceIds = []; |
| 29 | + |
| 30 | + /// <summary> |
| 31 | + /// Simulates a fixture like ClientServiceFixture that starts Docker containers. |
| 32 | + /// Implements IAsyncInitializer (NOT IAsyncDiscoveryInitializer) because the user |
| 33 | + /// does not want initialization during discovery. |
| 34 | + /// </summary> |
| 35 | + public class SimulatedContainerFixture : IAsyncInitializer |
| 36 | + { |
| 37 | + /// <summary> |
| 38 | + /// Test case identifiers are PREDEFINED - they don't depend on initialization. |
| 39 | + /// This allows discovery to enumerate test cases without initializing the fixture. |
| 40 | + /// </summary> |
| 41 | + private static readonly string[] PredefinedTestCases = ["TestCase1", "TestCase2", "TestCase3"]; |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// Unique identifier for this instance to verify sharing behavior. |
| 45 | + /// </summary> |
| 46 | + public Guid InstanceId { get; } = Guid.NewGuid(); |
| 47 | + |
| 48 | + public bool IsInitialized { get; private set; } |
| 49 | + |
| 50 | + /// <summary> |
| 51 | + /// Returns predefined test case identifiers. These are available during discovery |
| 52 | + /// WITHOUT requiring initialization. |
| 53 | + /// </summary> |
| 54 | + public IEnumerable<string> GetTestCases() => PredefinedTestCases; |
| 55 | + |
| 56 | + public Task InitializeAsync() |
| 57 | + { |
| 58 | + Interlocked.Increment(ref _initializationCount); |
| 59 | + Console.WriteLine($"[SimulatedContainerFixture] InitializeAsync called on instance {InstanceId} (count: {_initializationCount})"); |
| 60 | + |
| 61 | + // Simulate expensive container startup - this should NOT happen during discovery |
| 62 | + IsInitialized = true; |
| 63 | + |
| 64 | + return Task.CompletedTask; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + [ClassDataSource<SimulatedContainerFixture>(Shared = SharedType.PerClass)] |
| 69 | + public required SimulatedContainerFixture Fixture { get; init; } |
| 70 | + |
| 71 | + /// <summary> |
| 72 | + /// This property is accessed by InstanceMethodDataSource during discovery. |
| 73 | + /// It returns predefined test case identifiers that don't require initialization. |
| 74 | + /// The bug was that accessing this would trigger InitializeAsync() during discovery. |
| 75 | + /// After the fix, InitializeAsync() should only be called during test execution. |
| 76 | + /// </summary> |
| 77 | + public IEnumerable<string> TestExecutions => Fixture.GetTestCases(); |
| 78 | + |
| 79 | + [Test] |
| 80 | + [InstanceMethodDataSource(nameof(TestExecutions))] |
| 81 | + public async Task Test_WithInstanceMethodDataSource_DoesNotInitializeDuringDiscovery(string testCase) |
| 82 | + { |
| 83 | + Interlocked.Increment(ref _testExecutionCount); |
| 84 | + |
| 85 | + // Track this instance to verify sharing |
| 86 | + _observedInstanceIds.Add(Fixture.InstanceId); |
| 87 | + |
| 88 | + // The fixture should be initialized by the time the test runs |
| 89 | + await Assert.That(Fixture.IsInitialized) |
| 90 | + .IsTrue() |
| 91 | + .Because("the fixture should be initialized before test execution"); |
| 92 | + |
| 93 | + await Assert.That(testCase) |
| 94 | + .IsNotNullOrEmpty() |
| 95 | + .Because("the test case data should be available"); |
| 96 | + |
| 97 | + Console.WriteLine($"[Test] Executed with testCase='{testCase}', instanceId={Fixture.InstanceId}, " + |
| 98 | + $"initCount={_initializationCount}, execCount={_testExecutionCount}"); |
| 99 | + } |
| 100 | + |
| 101 | + [After(Class)] |
| 102 | + public static async Task VerifyInitializationAndSharing() |
| 103 | + { |
| 104 | + // With SharedType.PerClass, the fixture should be initialized exactly ONCE |
| 105 | + // during test execution, NOT during discovery. |
| 106 | + // |
| 107 | + // Before the fix: _initializationCount would be 2+ (discovery + execution) |
| 108 | + // After the fix: _initializationCount should be exactly 1 (execution only) |
| 109 | + |
| 110 | + Console.WriteLine($"[After(Class)] Final counts - init: {_initializationCount}, exec: {_testExecutionCount}"); |
| 111 | + Console.WriteLine($"[After(Class)] Unique instance IDs observed: {_observedInstanceIds.Distinct().Count()}"); |
| 112 | + |
| 113 | + await Assert.That(_initializationCount) |
| 114 | + .IsEqualTo(1) |
| 115 | + .Because("IAsyncInitializer should only be called once during execution, not during discovery"); |
| 116 | + |
| 117 | + await Assert.That(_testExecutionCount) |
| 118 | + .IsEqualTo(3) |
| 119 | + .Because("there should be 3 test executions (one per test case)"); |
| 120 | + |
| 121 | + // Verify that all tests used the SAME fixture instance (SharedType.PerClass) |
| 122 | + var uniqueInstanceIds = _observedInstanceIds.Distinct().ToList(); |
| 123 | + await Assert.That(uniqueInstanceIds) |
| 124 | + .HasCount().EqualTo(1) |
| 125 | + .Because("with SharedType.PerClass, all tests should share the same fixture instance"); |
| 126 | + |
| 127 | + // Reset for next run |
| 128 | + _initializationCount = 0; |
| 129 | + _testExecutionCount = 0; |
| 130 | + _observedInstanceIds.Clear(); |
| 131 | + } |
| 132 | +} |
0 commit comments