forked from dotnet/SqlClient
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChannelDbConnectionPoolTest.cs
More file actions
2451 lines (2160 loc) · 105 KB
/
Copy pathChannelDbConnectionPoolTest.cs
File metadata and controls
2451 lines (2160 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.Common;
using System.Threading;
using System.Threading.RateLimiting;
using System.Threading.Tasks;
using System.Transactions;
using Microsoft.Data.Common;
using Microsoft.Data.Common.ConnectionString;
using Microsoft.Data.ProviderBase;
using Microsoft.Data.SqlClient.ConnectionPool;
using Microsoft.Data.SqlClient.Diagnostics;
using Microsoft.Data.SqlClient.Tests.Common;
using Microsoft.Extensions.Time.Testing;
using Xunit;
namespace Microsoft.Data.SqlClient.UnitTests.ConnectionPool
{
/// <summary>
/// Unit tests for <see cref="ChannelDbConnectionPool"/> covering connection acquisition,
/// timeouts, reuse, pool clearing, blocking-period behavior, and timeout-budget propagation.
/// </summary>
[Collection(AppContextSwitchTestCollection.Name)]
public class ChannelDbConnectionPoolTest
{
private static readonly SqlConnectionFactory SuccessfulConnectionFactory = new SuccessfulSqlConnectionFactory();
private static readonly SqlConnectionFactory TimeoutConnectionFactory = new TimeoutSqlConnectionFactory();
/// <summary>
/// Creates a <see cref="ChannelDbConnectionPool"/> with configurable test dependencies so
/// individual tests can focus on the behavior under test without repeating setup logic.
/// </summary>
/// <param name="connectionFactory">The factory used to create physical connections.</param>
/// <param name="identity">Optional pool identity override.</param>
/// <param name="dbConnectionPoolGroup">Optional pool group override.</param>
/// <param name="poolGroupOptions">Optional pool options override.</param>
/// <param name="connectionPoolProviderInfo">Optional provider info override.</param>
/// <param name="connectionCreationRateLimiter">Optional concurrency limiter controlling physical connection creation.</param>
/// <param name="timeProvider">Optional time provider so tests can drive the blocking-period exit timer deterministically.</param>
/// <returns>A configured <see cref="ChannelDbConnectionPool"/> instance for testing.</returns>
private ChannelDbConnectionPool ConstructPool(SqlConnectionFactory connectionFactory,
DbConnectionPoolIdentity? identity = null,
DbConnectionPoolGroup? dbConnectionPoolGroup = null,
DbConnectionPoolGroupOptions? poolGroupOptions = null,
DbConnectionPoolProviderInfo? connectionPoolProviderInfo = null,
ConcurrencyLimiter? connectionCreationRateLimiter = null,
TimeProvider? timeProvider = null)
{
poolGroupOptions ??= new DbConnectionPoolGroupOptions(
poolByIdentity: false,
minPoolSize: 0,
maxPoolSize: 50,
creationTimeout: 15,
loadBalanceTimeout: 0,
hasTransactionAffinity: true,
idleTimeout: 0
);
dbConnectionPoolGroup ??= new DbConnectionPoolGroup(
new SqlConnectionOptions("Data Source=localhost;"),
new ConnectionPoolKey("TestDataSource", credential: null, accessToken: null, accessTokenCallback: null, sspiContextProvider: null),
poolGroupOptions
);
return new ChannelDbConnectionPool(
connectionFactory,
dbConnectionPoolGroup,
identity ?? DbConnectionPoolIdentity.NoIdentity,
connectionPoolProviderInfo ?? new DbConnectionPoolProviderInfo(),
connectionCreationRateLimiter,
timeProvider
);
}
/// <summary>
/// Verifies that requesting connections from an empty pool causes the pool to create new
/// physical connections until the requested count is reached.
/// </summary>
[Theory]
[InlineData(1)]
[InlineData(5)]
[InlineData(10)]
public void GetConnectionEmptyPool_ShouldCreateNewConnection(int numConnections)
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
// Act
for (int i = 0; i < numConnections; i++)
{
var completed = pool.TryGetConnection(
new SqlConnection(),
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection
);
// Assert
Assert.True(completed);
Assert.NotNull(internalConnection);
}
// Assert
Assert.Equal(numConnections, pool.Count);
}
/// <summary>
/// Verifies that asynchronous requests against an empty pool create new physical
/// connections and complete through the provided task completion source.
/// </summary>
[Theory]
[InlineData(1)]
[InlineData(5)]
[InlineData(10)]
public async Task GetConnectionAsyncEmptyPool_ShouldCreateNewConnection(int numConnections)
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
// Act
for (int i = 0; i < numConnections; i++)
{
var tcs = new TaskCompletionSource<DbConnectionInternal>();
var completed = pool.TryGetConnection(
new SqlConnection(),
tcs,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection
);
// Assert
Assert.False(completed);
Assert.Null(internalConnection);
Assert.NotNull(await tcs.Task);
}
// Assert
Assert.Equal(numConnections, pool.Count);
}
/// <summary>
/// Verifies that a synchronous request against an exhausted pool fails with the pooled-open
/// timeout once the caller's timeout budget has already expired.
/// </summary>
[Fact]
public void GetConnectionMaxPoolSize_ShouldTimeoutAfterPeriod()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
for (int i = 0; i < pool.PoolGroupOptions.MaxPoolSize; i++)
{
var completed = pool.TryGetConnection(
new SqlConnection(),
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection
);
// Assert
Assert.True(completed);
Assert.NotNull(internalConnection);
}
// Build a timer backed by a fake time provider, then advance virtual time past
// the timer's expiration so the pool's CancellationTokenSource is created
// already-cancelled and the timeout path fires deterministically without any
// wall-clock wait.
var fakeTime = new FakeTimeProvider();
TimeoutTimer expiredTimer = TimeoutTimer.StartNew(TimeSpan.FromSeconds(1), fakeTime);
fakeTime.Advance(TimeSpan.FromSeconds(2));
// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() =>
{
pool.TryGetConnection(
new SqlConnection(),
taskCompletionSource: null,
expiredTimer,
out DbConnectionInternal? extraConnection);
});
Assert.Equal(
"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.",
ex.Message);
Assert.Equal(pool.PoolGroupOptions.MaxPoolSize, pool.Count);
}
/// <summary>
/// Verifies that an asynchronous request against an exhausted pool completes with the
/// pooled-open timeout once the caller's timeout budget has already expired.
/// </summary>
[Fact]
public async Task GetConnectionAsyncMaxPoolSize_ShouldTimeoutAfterPeriod()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
for (int i = 0; i < pool.PoolGroupOptions.MaxPoolSize; i++)
{
var completed = pool.TryGetConnection(
new SqlConnection(),
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection
);
// Assert
Assert.True(completed);
Assert.NotNull(internalConnection);
}
// Build a timer backed by a fake time provider then advance past expiration so
// the pool's CTS is created already-cancelled.
var fakeTime = new FakeTimeProvider();
TimeoutTimer expiredTimer = TimeoutTimer.StartNew(TimeSpan.FromSeconds(1), fakeTime);
fakeTime.Advance(TimeSpan.FromSeconds(2));
// Act & Assert
TaskCompletionSource<DbConnectionInternal> taskCompletionSource = new();
pool.TryGetConnection(
new SqlConnection(),
taskCompletionSource,
expiredTimer,
out _);
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => taskCompletionSource.Task);
Assert.Equal(
"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.",
ex.Message);
Assert.Equal(pool.PoolGroupOptions.MaxPoolSize, pool.Count);
}
/// <summary>
/// Verifies that a waiting synchronous caller reuses a connection that is returned to an
/// exhausted pool instead of creating a new physical connection.
/// </summary>
[Fact]
public async Task GetConnectionMaxPoolSize_ShouldReuseAfterConnectionReleased()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
SqlConnection firstOwningConnection = new();
pool.TryGetConnection(
firstOwningConnection,
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? firstConnection
);
// The owning connections must stay reachable for the duration of the test. If they were
// collected, their internal connections would become emancipated and the pool would be
// entitled to reclaim them, which would defeat the pool-exhaustion this test relies on.
List<SqlConnection> owningConnections = new();
for (int i = 1; i < pool.PoolGroupOptions.MaxPoolSize; i++)
{
SqlConnection owningConnection = new();
owningConnections.Add(owningConnection);
var completed = pool.TryGetConnection(
owningConnection,
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection
);
// Assert
Assert.True(completed);
Assert.NotNull(internalConnection);
}
// Act
var task = Task.Run(() =>
{
pool.TryGetConnection(
new SqlConnection(""),
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? extraConnection
);
return extraConnection;
});
pool.ReturnInternalConnection(firstConnection!, firstOwningConnection);
var extraConnection = await task;
// Assert
Assert.Equal(firstConnection, extraConnection);
GC.KeepAlive(owningConnections);
}
/// <summary>
/// Verifies that a waiting asynchronous caller reuses a connection that is returned to an
/// exhausted pool instead of creating a new physical connection.
/// </summary>
[Fact]
public async Task GetConnectionAsyncMaxPoolSize_ShouldReuseAfterConnectionReleased()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
SqlConnection firstOwningConnection = new();
pool.TryGetConnection(
firstOwningConnection,
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? firstConnection
);
for (int i = 1; i < pool.PoolGroupOptions.MaxPoolSize; i++)
{
var completed = pool.TryGetConnection(
new SqlConnection(),
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection
);
// Assert
Assert.True(completed);
Assert.NotNull(internalConnection);
}
TaskCompletionSource<DbConnectionInternal> taskCompletionSource = new();
// Act
pool.TryGetConnection(
new SqlConnection(""),
taskCompletionSource,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? recycledConnection
);
pool.ReturnInternalConnection(firstConnection!, firstOwningConnection);
recycledConnection = await taskCompletionSource.Task;
// Assert
Assert.Equal(firstConnection, recycledConnection);
}
/// <summary>
/// Verifies that synchronous waiters are served in request order when the pool is full,
/// ensuring the first queued request receives the next returned connection.
/// </summary>
[Fact]
[ActiveIssue("https://github.com/dotnet/SqlClient/issues/3730")]
public async Task GetConnectionMaxPoolSize_ShouldRespectOrderOfRequest()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
SqlConnection firstOwningConnection = new();
pool.TryGetConnection(
firstOwningConnection,
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? firstConnection
);
// The owning connections must stay reachable for the duration of the test. If they were
// collected, their internal connections would become emancipated and the pool would be
// entitled to reclaim them, which would defeat the pool exhaustion this test relies on.
List<SqlConnection> owningConnections = new();
for (int i = 1; i < pool.PoolGroupOptions.MaxPoolSize; i++)
{
SqlConnection owningConnection = new();
owningConnections.Add(owningConnection);
var completed = pool.TryGetConnection(
owningConnection,
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection
);
// Assert
Assert.True(completed);
Assert.NotNull(internalConnection);
}
// Use ManualResetEventSlim to synchronize the tasks
// and force the request queueing order.
using ManualResetEventSlim mresQueueOrder = new();
using CountdownEvent allRequestsQueued = new(2);
// Act
var recycledTask = Task.Run(() =>
{
mresQueueOrder.Set();
allRequestsQueued.Signal();
pool.TryGetConnection(
new SqlConnection(""),
null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? recycledConnection
);
return recycledConnection;
});
var failedTask = Task.Run(() =>
{
// Force this request to be second in the queue.
mresQueueOrder.Wait();
allRequestsQueued.Signal();
pool.TryGetConnection(
new SqlConnection("Timeout=1"),
null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(1)),
out DbConnectionInternal? failedConnection
);
return failedConnection;
});
allRequestsQueued.Wait();
pool.ReturnInternalConnection(firstConnection!, firstOwningConnection);
var recycledConnection = await recycledTask;
// Assert
Assert.Equal(firstConnection, recycledConnection);
await Assert.ThrowsAsync<InvalidOperationException>(async () => await failedTask);
GC.KeepAlive(owningConnections);
}
/// <summary>
/// Verifies that asynchronous waiters are served in request order when the pool is full,
/// ensuring the first queued request receives the next returned connection.
/// </summary>
[Fact]
[ActiveIssue("https://github.com/dotnet/SqlClient/issues/3730")]
public async Task GetConnectionAsyncMaxPoolSize_ShouldRespectOrderOfRequest()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
SqlConnection firstOwningConnection = new();
pool.TryGetConnection(
firstOwningConnection,
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? firstConnection
);
// The owning connections must stay reachable for the duration of the test. If they were
// collected, their internal connections would become emancipated and the pool would be
// entitled to reclaim them, which would defeat the pool exhaustion this test relies on.
List<SqlConnection> owningConnections = new();
for (int i = 1; i < pool.PoolGroupOptions.MaxPoolSize; i++)
{
SqlConnection owningConnection = new();
owningConnections.Add(owningConnection);
var completed = pool.TryGetConnection(
owningConnection,
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection
);
// Assert
Assert.True(completed);
Assert.NotNull(internalConnection);
}
TaskCompletionSource<DbConnectionInternal> recycledTaskCompletionSource = new();
TaskCompletionSource<DbConnectionInternal> failedCompletionSource = new();
// Act
pool.TryGetConnection(
new SqlConnection(""),
recycledTaskCompletionSource,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? recycledConnection
);
// Gives time for the recycled connection to be queued before the failed request is initiated.
await Task.Delay(1000);
pool.TryGetConnection(
new SqlConnection("Timeout=1"),
failedCompletionSource,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(1)),
out DbConnectionInternal? failedConnection
);
pool.ReturnInternalConnection(firstConnection!, firstOwningConnection);
recycledConnection = await recycledTaskCompletionSource.Task;
// Assert
Assert.Equal(firstConnection, recycledConnection);
await Assert.ThrowsAsync<InvalidOperationException>(async () => failedConnection = await failedCompletionSource.Task);
GC.KeepAlive(owningConnections);
}
/// <summary>
/// Verifies that a connection returned to the idle channel is reused by a subsequent
/// request instead of allocating a new internal connection.
/// </summary>
[Fact]
public void ConnectionsAreReused()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
SqlConnection owningConnection = new();
// Act: Get the first connection
var completed1 = pool.TryGetConnection(
owningConnection,
null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection1
);
// Assert: First connection should succeed
Assert.True(completed1);
Assert.NotNull(internalConnection1);
// Act: Return the first connection to the pool
pool.ReturnInternalConnection(internalConnection1, owningConnection);
// Act: Get the second connection (should reuse the first one)
var completed2 = pool.TryGetConnection(
owningConnection,
null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection2
);
// Assert: Second connection should succeed and reuse the first connection
Assert.True(completed2);
Assert.NotNull(internalConnection2);
Assert.Same(internalConnection1, internalConnection2);
}
/// <summary>
/// Verifies that synchronous connection creation failures propagate the pooled-open timeout
/// exception from the connection factory.
/// </summary>
[Fact]
public void GetConnectionTimeout_ShouldThrowTimeoutException()
{
// Arrange
var pool = ConstructPool(TimeoutConnectionFactory);
// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() =>
{
var completed = pool.TryGetConnection(
new SqlConnection(),
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection
);
});
// Use the resource-backed message rather than a hardcoded English
// string so the assertion stays meaningful under any localized build.
Assert.Equal(ADP.PooledOpenTimeout().Message, ex.Message);
}
/// <summary>
/// Verifies that asynchronous connection creation failures propagate the pooled-open timeout
/// exception through the caller's task completion source.
/// </summary>
[Fact]
public async Task GetConnectionAsyncTimeout_ShouldThrowTimeoutException()
{
// Arrange
var pool = ConstructPool(TimeoutConnectionFactory);
TaskCompletionSource<DbConnectionInternal> taskCompletionSource = new();
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () =>
{
var completed = pool.TryGetConnection(
new SqlConnection(),
taskCompletionSource,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection
);
await taskCompletionSource.Task;
});
// Use the resource-backed message rather than a hardcoded English
// string so the assertion stays meaningful under any localized build.
Assert.Equal(ADP.PooledOpenTimeout().Message, ex.Message);
}
/// <summary>
/// Verifies that an expired caller timeout prevents physical connection creation.
/// </summary>
[Fact]
public void GetConnectionExpiredTimeout_DoesNotAttemptPhysicalConnection()
{
// Arrange
var connectionFactory = new CountingTimeoutConnectionFactory();
var pool = ConstructPool(connectionFactory);
// Act
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>
pool.TryGetConnection(
new SqlConnection(),
taskCompletionSource: null,
TimeoutTimer.StartExpired(),
out _));
// Assert
Assert.Equal(ADP.PooledOpenTimeout().Message, exception.Message);
Assert.Equal(0, connectionFactory.CreateCount);
}
/// <summary>
/// Verifies under concurrent synchronous load that the pool never grows beyond its
/// configured maximum size and continues to serve requests safely.
/// </summary>
[Fact]
public void StressTest()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
ConcurrentBag<Task> tasks = new();
// Act
for (int i = 1; i < pool.PoolGroupOptions.MaxPoolSize * 3; i++)
{
var t = Task.Run(() =>
{
SqlConnection owningObject = new();
var completed = pool.TryGetConnection(
owningObject,
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection
);
if (completed)
{
pool.ReturnInternalConnection(internalConnection!, owningObject);
}
Assert.True(completed);
Assert.NotNull(internalConnection);
});
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
// Assert
Assert.True(pool.Count <= pool.PoolGroupOptions.MaxPoolSize, "Pool size exceeded max pool size after stress test.");
}
/// <summary>
/// Verifies under concurrent asynchronous load that the pool never grows beyond its
/// configured maximum size and continues to serve requests safely.
/// </summary>
[Fact]
public void StressTestAsync()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
ConcurrentBag<Task> tasks = new();
// Act
for (int i = 1; i < pool.PoolGroupOptions.MaxPoolSize * 3; i++)
{
var t = Task.Run(async () =>
{
SqlConnection owningObject = new();
TaskCompletionSource<DbConnectionInternal> taskCompletionSource = new();
var completed = pool.TryGetConnection(
owningObject,
taskCompletionSource,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? internalConnection
);
internalConnection = await taskCompletionSource.Task;
pool.ReturnInternalConnection(internalConnection, owningObject);
Assert.NotNull(internalConnection);
});
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
// Assert
Assert.True(pool.Count <= pool.PoolGroupOptions.MaxPoolSize, "Pool size exceeded max pool size after stress test.");
}
#region Property Tests
/// <summary>
/// Verifies that the pool exposes the <see cref="SqlConnectionFactory"/> instance it was
/// constructed with.
/// </summary>
[Fact]
public void TestConnectionFactory()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
// Act & Assert
Assert.Equal(SuccessfulConnectionFactory, pool.ConnectionFactory);
}
/// <summary>
/// Verifies that a newly constructed pool starts with zero tracked connections.
/// </summary>
[Fact]
public void TestCount()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
// Act & Assert
Assert.Equal(0, pool.Count);
}
/// <summary>
/// Verifies that a newly constructed pool reports no blocking-period error by default.
/// </summary>
[Fact]
public void TestErrorOccurred()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
// Act & Assert
Assert.False(pool.ErrorOccurred);
}
/// <summary>
/// Verifies that the pool assigns a positive instance identifier at construction time.
/// </summary>
[Fact]
public void TestId()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
// Act & Assert
Assert.True(pool.Id >= 1);
}
/// <summary>
/// Verifies that the pool exposes the identity object it was constructed with.
/// </summary>
[Fact]
public void TestIdentity()
{
// Arrange
var identity = DbConnectionPoolIdentity.GetCurrent();
var pool = ConstructPool(SuccessfulConnectionFactory, identity);
// Act & Assert
Assert.Equal(identity, pool.Identity);
}
/// <summary>
/// Verifies that a newly constructed pool begins in the running state.
/// </summary>
[Fact]
public void TestIsRunning()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
// Act & Assert
Assert.True(pool.IsRunning);
}
/// <summary>
/// Verifies that the pool exposes the configured load-balance timeout from its pool group
/// options.
/// </summary>
[Fact]
public void TestLoadBalanceTimeout()
{
// Arrange
var poolGroupOptions = new DbConnectionPoolGroupOptions(
poolByIdentity: false,
minPoolSize: 0,
maxPoolSize: 50,
creationTimeout: 15,
loadBalanceTimeout: 500,
hasTransactionAffinity: true,
idleTimeout: 0
);
var pool = ConstructPool(SuccessfulConnectionFactory, poolGroupOptions: poolGroupOptions);
// Act & Assert
Assert.Equal(poolGroupOptions.LoadBalanceTimeout, pool.LoadBalanceTimeout);
}
/// <summary>
/// Verifies that the pool exposes the exact <see cref="DbConnectionPoolGroup"/> instance it
/// was constructed with.
/// </summary>
[Fact]
public void TestPoolGroup()
{
// Arrange
var dbConnectionPoolGroup = new DbConnectionPoolGroup(
new SqlConnectionOptions("Data Source=localhost;"),
new ConnectionPoolKey("TestDataSource", credential: null, accessToken: null, accessTokenCallback: null, sspiContextProvider: null),
new DbConnectionPoolGroupOptions(
poolByIdentity: false,
minPoolSize: 0,
maxPoolSize: 50,
creationTimeout: 15,
loadBalanceTimeout: 500,
hasTransactionAffinity: true,
idleTimeout: 0));
var pool = ConstructPool(SuccessfulConnectionFactory, dbConnectionPoolGroup: dbConnectionPoolGroup);
// Act & Assert
Assert.Equal(dbConnectionPoolGroup, pool.PoolGroup);
}
/// <summary>
/// Verifies that the pool exposes the exact <see cref="DbConnectionPoolGroupOptions"/>
/// instance it was constructed with.
/// </summary>
[Fact]
public void TestPoolGroupOptions()
{
// Arrange
var poolGroupOptions = new DbConnectionPoolGroupOptions(
poolByIdentity: false,
minPoolSize: 0,
maxPoolSize: 50,
creationTimeout: 15,
loadBalanceTimeout: 500,
hasTransactionAffinity: true,
idleTimeout: 0);
var pool = ConstructPool(SuccessfulConnectionFactory, poolGroupOptions: poolGroupOptions);
// Act & Assert
Assert.Equal(poolGroupOptions, pool.PoolGroupOptions);
}
/// <summary>
/// Verifies that the pool exposes the provider info object it was constructed with.
/// </summary>
[Fact]
public void TestProviderInfo()
{
// Arrange
var connectionPoolProviderInfo = new DbConnectionPoolProviderInfo();
var pool = ConstructPool(SuccessfulConnectionFactory, connectionPoolProviderInfo: connectionPoolProviderInfo);
// Act & Assert
Assert.Equal(connectionPoolProviderInfo, pool.ProviderInfo);
}
/// <summary>
/// Verifies that the pool state getter reports <see cref="DbConnectionPoolState.Running"/>
/// immediately after construction.
/// </summary>
[Fact]
public void TestStateGetter()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
// Act & Assert
Assert.Equal(DbConnectionPoolState.Running, pool.State);
}
/// <summary>
/// Verifies that the pool state remains <see cref="DbConnectionPoolState.Running"/> after
/// construction when no shutdown has been requested.
/// </summary>
[Fact]
public void TestStateSetter()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
// Act & Assert
Assert.Equal(DbConnectionPoolState.Running, pool.State);
}
/// <summary>
/// Verifies that the pool exposes whether load balancing is enabled based on its configured
/// pool group options.
/// </summary>
[Fact]
public void TestUseLoadBalancing()
{
// Arrange
var poolGroupOptions = new DbConnectionPoolGroupOptions(
poolByIdentity: false,
minPoolSize: 0,
maxPoolSize: 50,
creationTimeout: 15,
loadBalanceTimeout: 500,
hasTransactionAffinity: true,
idleTimeout: 0);
var pool = ConstructPool(SuccessfulConnectionFactory, poolGroupOptions: poolGroupOptions);
// Act & Assert
Assert.Equal(poolGroupOptions.UseLoadBalancing, pool.UseLoadBalancing);
}
#endregion
#region Replace Connection Tests
/// <summary>
/// Verifies that <see cref="ChannelDbConnectionPool.ReplaceConnection(System.Data.Common.DbConnection, Microsoft.Data.ProviderBase.DbConnectionInternal, Microsoft.Data.ProviderBase.TimeoutTimer)"/>
/// replaces a checked-out connection with a new, distinct connection instance.
/// </summary>
[Fact]
public void TestReplaceConnection()
{
// Arrange
var fakeTime = new FakeTimeProvider();
var pool = ConstructPool(SuccessfulConnectionFactory, timeProvider: fakeTime);
SqlConnection owner = new();
pool.TryGetConnection(
owner,
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out DbConnectionInternal? oldConnection);
Assert.NotNull(oldConnection);
var newConnection = pool.ReplaceConnection(owner, oldConnection, TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)));
Assert.NotNull(newConnection);
Assert.NotSame(oldConnection, newConnection);
}
#endregion
#region Pool Clear Tests
/// <summary>
/// Verifies that clearing an empty pool is a no-op and leaves the pool in a valid state.
/// </summary>
[Fact]
public void Clear_EmptyPool_DoesNotThrow()
{
// Arrange
var pool = ConstructPool(SuccessfulConnectionFactory);
// Act
pool.Clear();
// Assert
Assert.Equal(0, pool.Count);
}
/// <summary>
/// Verifies that clearing a pool with only idle connections destroys them immediately and
/// leaves the pool empty.
/// </summary>
[Fact]
public void Clear_MultipleIdleConnections_AllAreDestroyed()
{
// Arrange
int numConnections = 5;
var pool = ConstructPool(SuccessfulConnectionFactory);
var owningConnections = new SqlConnection[numConnections];
var internalConnections = new DbConnectionInternal?[numConnections];
for (int i = 0; i < numConnections; i++)
{
owningConnections[i] = new SqlConnection();
pool.TryGetConnection(
owningConnections[i],
taskCompletionSource: null,
TimeoutTimer.StartNew(TimeSpan.FromSeconds(15)),
out internalConnections[i]
);
Assert.Equal(0, internalConnections[i]!.ClearGeneration);
}
// Return all connections to the pool
for (int i = 0; i < numConnections; i++)
{
pool.ReturnInternalConnection(internalConnections[i]!, owningConnections[i]);
}
// Act
pool.Clear();
// Assert
Assert.Equal(0, pool.Count);
}
/// <summary>
/// Verifies that clearing the pool does not immediately destroy a connection that is still
/// checked out by a caller.
/// </summary>
[Fact]