diff --git a/tests/AstrolabeWorkloadExecutor/Program.cs b/tests/AstrolabeWorkloadExecutor/Program.cs index 693bc95ae89..2d672ee87a2 100644 --- a/tests/AstrolabeWorkloadExecutor/Program.cs +++ b/tests/AstrolabeWorkloadExecutor/Program.cs @@ -37,7 +37,7 @@ public static void Main(string[] args) var connectionString = args[0]; var driverWorkload = BsonDocument.Parse(args[1]); - var astrolabeCancellationTokenSource = new CancellationTokenSource(); + using var astrolabeCancellationTokenSource = new CancellationTokenSource(); ConsoleCancelEventHandler cancelHandler = (o, e) => HandleCancel(e, astrolabeCancellationTokenSource); var resultsDir = Environment.GetEnvironmentVariable("RESULTS_DIR") ?? ""; diff --git a/tests/MongoDB.Bson.Tests/IO/BsonStreamAdapterTests.cs b/tests/MongoDB.Bson.Tests/IO/BsonStreamAdapterTests.cs index 1984713ad51..34dcfeabfb2 100644 --- a/tests/MongoDB.Bson.Tests/IO/BsonStreamAdapterTests.cs +++ b/tests/MongoDB.Bson.Tests/IO/BsonStreamAdapterTests.cs @@ -305,7 +305,8 @@ public void CopyToAsync_should_call_wrapped_stream() var subject = new BsonStreamAdapter(mockStream.Object); var mockDestination = new Mock(); var bufferSize = 1; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var task = new TaskCompletionSource().Task; mockStream.Setup(s => s.CopyToAsync(mockDestination.Object, bufferSize, cancellationToken)).Returns(task); @@ -322,7 +323,8 @@ public void CopyToAsync_should_throw_when_subject_is_disposed() var subject = new BsonStreamAdapter(mockStream.Object); var mockDestination = new Mock(); var bufferSize = 1; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; subject.Dispose(); Action action = () => subject.CopyToAsync(mockDestination.Object, bufferSize, cancellationToken); @@ -463,7 +465,8 @@ public void FlushAsync_should_call_wrapped_stream() var mockStream = new Mock(); var subject = new BsonStreamAdapter(mockStream.Object); var task = new TaskCompletionSource().Task; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockStream.Setup(s => s.FlushAsync(cancellationToken)).Returns(task); var result = subject.FlushAsync(cancellationToken); @@ -477,7 +480,8 @@ public void FlushAsync_should_throw_when_subject_is_disposed() { var mockStream = new Mock(); var subject = new BsonStreamAdapter(mockStream.Object); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; subject.Dispose(); Action action = () => subject.FlushAsync(cancellationToken); @@ -608,7 +612,8 @@ public void ReadAsync_should_call_wrapped_stream() var buffer = new byte[3]; var offset = 1; var count = 2; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockStream.Setup(s => s.ReadAsync(buffer, offset, count, cancellationToken)).Returns(task); var result = subject.ReadAsync(buffer, offset, count, cancellationToken); @@ -625,7 +630,8 @@ public void ReadAsync_should_throw_when_subject_is_disposed() var buffer = new byte[3]; var offset = 1; var count = 2; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; subject.Dispose(); Action action = () => subject.ReadAsync(buffer, offset, count, cancellationToken); @@ -1185,7 +1191,8 @@ public void WriteAsync_should_call_wrapped_stream() var buffer = new byte[0]; var offset = 1; var count = 2; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockStream.Setup(s => s.WriteAsync(buffer, offset, count, cancellationToken)).Returns(task); var result = subject.WriteAsync(buffer, offset, count, cancellationToken); @@ -1203,7 +1210,8 @@ public void WriteAsync_should_throw_when_subject_is_disposed() var buffer = new byte[0]; var offset = 1; var count = 2; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; subject.Dispose(); Action action = () => subject.WriteAsync(buffer, offset, count, cancellationToken); diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Async/AsyncQueueTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Async/AsyncQueueTests.cs index 41e7bba86bc..5f51ae64bcd 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Async/AsyncQueueTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Async/AsyncQueueTests.cs @@ -17,7 +17,6 @@ using System.Threading; using System.Threading.Tasks; using FluentAssertions; -using MongoDB.Driver.Core.Async; using Xunit; namespace MongoDB.Driver.Core.Async @@ -88,7 +87,7 @@ public void Dequeue_should_complete_when_an_item_is_added_to_the_queue() [Fact] public void Dequeue_should_cancel_when_cancellation_is_requested() { - var cancellationTokenSource = new CancellationTokenSource(); + using var cancellationTokenSource = new CancellationTokenSource(); var subject = new AsyncQueue(); var result = subject.DequeueAsync(cancellationTokenSource.Token); cancellationTokenSource.Cancel(); diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ChannelChannelSourceTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ChannelChannelSourceTests.cs index 1f98fcdfb06..a3fdc367a5c 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ChannelChannelSourceTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ChannelChannelSourceTests.cs @@ -145,7 +145,8 @@ public void GetChannel_should_return_expected_result( { var mockChannel = new Mock(); var subject = CreateSubject(channel: mockChannel.Object); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var expectedResult = new Mock().Object; mockChannel.Setup(m => m.Fork()).Returns(expectedResult); @@ -169,7 +170,8 @@ public void GetChannel_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var exception = Record.Exception(() => { diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ChannelReadBindingTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ChannelReadBindingTests.cs index 21fdcfd0626..b28f7a525bf 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ChannelReadBindingTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ChannelReadBindingTests.cs @@ -157,7 +157,8 @@ public void GetReadChannelSource_should_return_expected_result( var mockChannel = new Mock(); var mockSession = new Mock(); var subject = CreateSubject(channel: mockChannel.Object, session: mockSession.Object); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var forkedChannel = new Mock().Object; var forkedSession = new Mock().Object; @@ -187,7 +188,8 @@ public void GetReadChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var exception = Record.Exception(() => { diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs index c3387b25b5b..3f5bbde5905 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs @@ -138,7 +138,8 @@ public void GetReadChannelSource_should_return_expected_result( var mockChannel = new Mock(); var mockSession = new Mock(); var subject = CreateSubject(channel: mockChannel.Object, session: mockSession.Object); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var forkedChannel = new Mock().Object; var forkedSession = new Mock().Object; @@ -170,7 +171,8 @@ public void GetWriteChannelSource_should_return_expected_result( var mockChannel = new Mock(); var mockSession = new Mock(); var subject = CreateSubject(channel: mockChannel.Object, session: mockSession.Object); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var forkedChannel = new Mock().Object; var forkedSession = new Mock().Object; @@ -200,7 +202,8 @@ public void GetReadChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var exception = Record.Exception(() => { @@ -224,7 +227,8 @@ public void GetWriteChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var exception = Record.Exception(() => { diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ReadPreferenceBindingTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ReadPreferenceBindingTests.cs index 2e54ab30c80..dc4dd76fce0 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ReadPreferenceBindingTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Bindings/ReadPreferenceBindingTests.cs @@ -142,7 +142,8 @@ public void GetReadChannelSource_should_fork_the_session( { var mockSession = new Mock(); var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary, mockSession.Object); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var selectedServer = new Mock().Object; _mockCluster.Setup(m => m.SelectServer(It.IsAny(), cancellationToken)).Returns(selectedServer); diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Bindings/SingleServerReadBindingTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Bindings/SingleServerReadBindingTests.cs index ec29db85a3c..9aee543a620 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Bindings/SingleServerReadBindingTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Bindings/SingleServerReadBindingTests.cs @@ -131,7 +131,8 @@ public void GetReadChannelSource_should_return_expected_result( { var mockSession = new Mock(); var subject = CreateSubject(session: mockSession.Object); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var forkedSession = new Mock().Object; mockSession.Setup(m => m.Fork()).Returns(forkedSession); @@ -158,7 +159,8 @@ public void GetReadChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var exception = Record.Exception(() => { diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs index a78c7a1514d..4bfd753457c 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs @@ -117,7 +117,8 @@ public void GetReadChannelSource_should_return_expected_result( { var mockSession = new Mock(); var subject = CreateSubject(session: mockSession.Object); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var forkedSession = new Mock().Object; mockSession.Setup(m => m.Fork()).Returns(forkedSession); @@ -144,7 +145,8 @@ public void GetReadChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var exception = Record.Exception(() => { @@ -169,7 +171,8 @@ public void GetWriteChannelSource_should_return_expected_result( { var mockSession = new Mock(); var subject = CreateSubject(session: mockSession.Object); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var forkedSession = new Mock().Object; mockSession.Setup(m => m.Fork()).Returns(forkedSession); @@ -196,7 +199,8 @@ public void GetWriteChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var exception = Record.Exception(() => { diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Clusters/DnsClientWrapperTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Clusters/DnsClientWrapperTests.cs index a9f871925e9..21f4ddc6550 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Clusters/DnsClientWrapperTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Clusters/DnsClientWrapperTests.cs @@ -93,17 +93,17 @@ public void ResolveSrvRecords_should_throw_when_cancellation_is_already_requeste { var subject = CreateSubject(); var service = "_mongodb._tcp.test5.test.build.10gen.cc"; - var cts = new CancellationTokenSource(); - cts.Cancel(); + using var cancellationTokenSource = new CancellationTokenSource(); + cancellationTokenSource.Cancel(); Exception exception; if (async) { - exception = Record.Exception(() => subject.ResolveSrvRecordsAsync(service, cts.Token).GetAwaiter().GetResult()); + exception = Record.Exception(() => subject.ResolveSrvRecordsAsync(service, cancellationTokenSource.Token).GetAwaiter().GetResult()); } else { - exception = Record.Exception(() => subject.ResolveSrvRecords(service, cts.Token)); + exception = Record.Exception(() => subject.ResolveSrvRecords(service, cancellationTokenSource.Token)); } exception.Should().Match(e => e is OperationCanceledException || e.InnerException is OperationCanceledException); @@ -159,17 +159,17 @@ public void ResolveTxtRecords_should_throw_when_cancellation_is_already_requeste { var subject = CreateSubject(); var domainName = "test5.test.build.10gen.cc"; - var cts = new CancellationTokenSource(); - cts.Cancel(); + using var cancellationTokenSource = new CancellationTokenSource(); + cancellationTokenSource.Cancel(); Exception exception; if (async) { - exception = Record.Exception(() => subject.ResolveTxtRecordsAsync(domainName, cts.Token).GetAwaiter().GetResult()); + exception = Record.Exception(() => subject.ResolveTxtRecordsAsync(domainName, cancellationTokenSource.Token).GetAwaiter().GetResult()); } else { - exception = Record.Exception(() => subject.ResolveTxtRecords(domainName, cts.Token)); + exception = Record.Exception(() => subject.ResolveTxtRecords(domainName, cancellationTokenSource.Token)); } exception.Should().Match(e => e is OperationCanceledException || e.InnerException is OperationCanceledException); diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Clusters/DnsMonitorFactoryTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Clusters/DnsMonitorFactoryTests.cs index 8f784cc7a1f..e9045cbd676 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Clusters/DnsMonitorFactoryTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Clusters/DnsMonitorFactoryTests.cs @@ -53,7 +53,8 @@ public void CreateDnsMonitor_should_return_expected_result() var subject = new DnsMonitorFactory(mockEventSubscriber.Object); var cluster = Mock.Of(); var lookupDomainName = "a.b.com"; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var result = subject.CreateDnsMonitor(cluster, lookupDomainName, cancellationToken); diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Clusters/DnsMonitorTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Clusters/DnsMonitorTests.cs index 6996ac5a8eb..636eae81734 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Clusters/DnsMonitorTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Clusters/DnsMonitorTests.cs @@ -72,7 +72,8 @@ public void constructor_should_initialize_instance() mockEventSubscriber .Setup(m => m.TryGetEventHandler(out sdamInformationEventHandler)) .Returns(true); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var subject = new DnsMonitor(cluster, dnsResolver, lookupDomainName, mockEventSubscriber.Object, cancellationToken); @@ -92,7 +93,8 @@ public void constructor_should_throw_when_cluster_is_null() { var dnsResolver = Mock.Of(); var lookupDomainName = "a.b.com"; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var exception = Record.Exception(() => new DnsMonitor(null, dnsResolver, lookupDomainName, null, cancellationToken)); @@ -105,7 +107,8 @@ public void constructor_should_throw_when_dnsResolver_is_null() { var cluster = Mock.Of(); var lookupDomainName = "a.b.com"; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var exception = Record.Exception(() => new DnsMonitor(cluster, null, lookupDomainName, null, cancellationToken)); @@ -118,7 +121,8 @@ public void constructor_should_throw_when_lookupDomainName_is_null() { var cluster = Mock.Of(); var dnsResolver = Mock.Of(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var exception = Record.Exception(() => new DnsMonitor(cluster, dnsResolver, null, null, cancellationToken)); @@ -134,7 +138,8 @@ public void constructor_should_throw_when_lookupDomainName_is_invalid(string loo { var cluster = Mock.Of(); var dnsResolver = Mock.Of(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var exception = Record.Exception(() => new DnsMonitor(cluster, dnsResolver, lookupDomainName, null, cancellationToken)); @@ -379,21 +384,21 @@ public void Monitor_should_call_ProcessDnsResults_with_expected_endPoints(string .SetupSequence(x => x.ShouldDnsMonitorStop()) .Returns(true); List actualEndPoints = null; - var cts = new CancellationTokenSource(); + using var cancellationTokenSource = new CancellationTokenSource(); mockCluster .Setup(x => x.ProcessDnsResults(It.IsAny>())) .Callback((List endPoints) => { actualEndPoints = endPoints; - cts.Cancel(); + cancellationTokenSource.Cancel(); }); var mockDnsResolver = new Mock(); var service = "_mongodb._tcp." + lookupDomainName; var srvRecords = CreateSrvRecords(expectedEndPointStrings); mockDnsResolver - .Setup(m => m.ResolveSrvRecords(service, cts.Token)) + .Setup(m => m.ResolveSrvRecords(service, cancellationTokenSource.Token)) .Returns(srvRecords); - var subject = CreateSubject(cluster: mockCluster.Object, dnsResolver: mockDnsResolver.Object, lookupDomainName: lookupDomainName, cancellationToken: cts.Token); + var subject = CreateSubject(cluster: mockCluster.Object, dnsResolver: mockDnsResolver.Object, lookupDomainName: lookupDomainName, cancellationToken: cancellationTokenSource.Token); subject.Monitor(); @@ -408,13 +413,13 @@ public void Monitor_should_not_call_ProcessDnsResults_when_there_are_no_valid_ho mockCluster .SetupSequence(x => x.ShouldDnsMonitorStop()) .Returns(true); - var cts = new CancellationTokenSource(); + using var cancellationTokenSource = new CancellationTokenSource(); var mockDnsResolver = new Mock(); var lookupDomainName = "a.b.com"; var service = "_mongodb._tcp." + lookupDomainName; var noSrvRecords = new List(); mockDnsResolver - .Setup(m => m.ResolveSrvRecords(service, cts.Token)) + .Setup(m => m.ResolveSrvRecords(service, cancellationTokenSource.Token)) .Returns(noSrvRecords); var mockEventSubscriber = new Mock(); var actualEvents = new List(); @@ -426,7 +431,7 @@ public void Monitor_should_not_call_ProcessDnsResults_when_there_are_no_valid_ho dnsResolver: mockDnsResolver.Object, lookupDomainName: lookupDomainName, eventSubscriber: mockEventSubscriber.Object, - cancellationToken: cts.Token); + cancellationToken: cancellationTokenSource.Token); subject.Monitor(); @@ -439,13 +444,13 @@ public void Monitor_should_not_call_ProcessDnsResults_when_there_are_no_valid_ho [Fact] public void Monitor_should_throw_when_cancellation_is_requested() { - var cts = new CancellationTokenSource(); + using var cancellationTokenSource = new CancellationTokenSource(); var mockCluster = new Mock(); mockCluster .SetupSequence(x => x.ShouldDnsMonitorStop()) - .Returns(() => { cts.Cancel(); return false; }); + .Returns(() => { cancellationTokenSource.Cancel(); return false; }); var lookupDomainName = "a.b.com"; - var subject = CreateSubject(cluster: mockCluster.Object, lookupDomainName: lookupDomainName, cancellationToken: cts.Token); + var subject = CreateSubject(cluster: mockCluster.Object, lookupDomainName: lookupDomainName, cancellationToken: cancellationTokenSource.Token); var exception = Record.Exception(() => subject.Monitor()); exception.Should().BeOfType(); diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Misc/SemaphoreSlimRequestTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Misc/SemaphoreSlimRequestTests.cs index 8fe4506fb4c..7dca0e28f9a 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Misc/SemaphoreSlimRequestTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Misc/SemaphoreSlimRequestTests.cs @@ -84,7 +84,7 @@ public void Dispose_should_release_semaphore() public void Sempahore_should_not_be_released_when_cancellation_is_requested_after_semaphore_is_acquired() { var semaphore = new SemaphoreSlim(1); - var cancellationTokenSource = new CancellationTokenSource(); + using var cancellationTokenSource = new CancellationTokenSource(); var subject = new SemaphoreSlimRequest(semaphore, cancellationTokenSource.Token); cancellationTokenSource.Cancel(); @@ -96,7 +96,7 @@ public void Sempahore_should_not_be_released_when_cancellation_is_requested_afte public void Task_should_be_cancelled_when_cancellationToken_requests_cancellation() { var semaphore = new SemaphoreSlim(1); - var cancellationTokenSource = new CancellationTokenSource(); + using var cancellationTokenSource = new CancellationTokenSource(); semaphore.Wait(); var subject = new SemaphoreSlimRequest(semaphore, cancellationTokenSource.Token); diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Misc/SemaphoreSlimSignalableTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Misc/SemaphoreSlimSignalableTests.cs index 7e6770e820b..7dff7723e8a 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Misc/SemaphoreSlimSignalableTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Misc/SemaphoreSlimSignalableTests.cs @@ -147,7 +147,7 @@ public async Task Wait_should_cancel( const int threadsCount = 4; var semaphore = new SemaphoreSlimSignalable(0); - var cancelationTokenSource = new CancellationTokenSource(); + using var cancelationTokenSource = new CancellationTokenSource(); var tasks = CreateWaitTasks(semaphore, async, isSignaledWait, threadsCount, Timeout.InfiniteTimeSpan, cancelationTokenSource.Token); @@ -164,7 +164,7 @@ public async Task Wait_should_cancel( [Fact] public async Task WaitSignaledAsync_should_not_continue_on_signal_thread() { - var cancelationTokenSource = new CancellationTokenSource(); + using var cancelationTokenSource = new CancellationTokenSource(); var semaphore = new SemaphoreSlimSignalable(0); var waitStartedEvent = new ManualResetEventSlim(false); diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Operations/AggregateExplainOperationTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Operations/AggregateExplainOperationTests.cs index 173e5fd1df5..104028d760b 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Operations/AggregateExplainOperationTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Operations/AggregateExplainOperationTests.cs @@ -413,7 +413,8 @@ public void Execute_should_send_session_id_when_supported( { RequireServer.Check(); var subject = new AggregateExplainOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; VerifySessionIdWasSentWhenSupported(subject, "aggregate", async); } diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Operations/AsyncCursorTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Operations/AsyncCursorTests.cs index 5b4d469966d..469a8f7c530 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Operations/AsyncCursorTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Operations/AsyncCursorTests.cs @@ -409,7 +409,8 @@ public void GetMore_should_use_same_session( var collectionNamespace = new CollectionNamespace(databaseNamespace, "collection"); var cursorId = 1; var subject = CreateSubject(collectionNamespace: collectionNamespace, cursorId: cursorId, channelSource: Optional.Create(channelSource)); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var connectionDescription = CreateConnectionDescriptionSupportingSession(); mockChannelSource.SetupGet(m => m.Session).Returns(session); diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Operations/ChangeStreamCursorTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Operations/ChangeStreamCursorTests.cs index ac56119348e..517f8a217a2 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Operations/ChangeStreamCursorTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Operations/ChangeStreamCursorTests.cs @@ -397,7 +397,8 @@ public void MoveNext_should_call_MoveNext_on_cursor( { var mockCursor = CreateMockCursor(); var subject = CreateSubject(cursor: mockCursor.Object); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; bool result; if (async) @@ -434,7 +435,8 @@ public void MoveNext_should_call_Resume_after_resumable_exception( var mockBinding = new Mock(); var mockOperation = new Mock>(); var subject = CreateSubject(cursor: mockCursor.Object, binding: mockBinding.Object, changeStreamOperation: mockOperation.Object); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var resumableException = CoreExceptionHelper.CreateException(resumableExceptionType); var mockResumedCursor = CreateMockCursor(); @@ -485,7 +487,8 @@ void ProcessBatch_should_deserialize_documents( var subject = CreateSubject(cursor: mockCursor.Object, documentSerializer: mockSerializer.Object); var document = BsonDocument.Parse("{ _id : { resumeAfter : 1 }, operationType : \"insert\", ns : { db : \"db\", coll : \"coll\" }, documentKey : { _id : 1 }, fullDocument : { _id : 1 } }"); var rawDocuments = new[] { ToRawDocument(document) }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockCursor.SetupGet(c => c.Current).Returns(rawDocuments); mockSerializer.Setup(s => s.Deserialize(It.IsAny(), It.IsAny())).Returns(document); @@ -520,7 +523,8 @@ void ProcessBatch_should_Dispose_rawDocuments( var document = BsonDocument.Parse("{ _id : { resumeAfter : 1 }, operationType : \"insert\", ns : { db : \"db\", coll : \"coll\" }, documentKey : { _id : 1 }, fullDocument : { _id : 1 } }"); var rawDocument = ToRawDocument(document); var rawDocuments = new[] { rawDocument }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockCursor.SetupGet(c => c.Current).Returns(rawDocuments); mockSerializer.Setup(s => s.Deserialize(It.IsAny(), It.IsAny())).Returns(document); @@ -554,7 +558,8 @@ void ProcessBatch_should_save_documentResumeToken( var subject = CreateSubject(cursor: mockCursor.Object, documentSerializer: mockSerializer.Object); var document = BsonDocument.Parse("{ _id : { resumeAfter : 1 }, operationType : \"insert\", ns : { db : \"db\", coll : \"coll\" }, documentKey : { _id : 1 }, fullDocument : { _id : 1 } }"); var rawDocuments = new[] { ToRawDocument(document) }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockCursor.SetupGet(c => c.Current).Returns(rawDocuments); mockSerializer.Setup(s => s.Deserialize(It.IsAny(), It.IsAny())).Returns(document); @@ -586,7 +591,8 @@ void ProcessBatch_should_throw_when_resume_token_is_missing( var subject = CreateSubject(cursor: mockCursor.Object); var document = BsonDocument.Parse("{ operationType : \"insert\", ns : { db : \"db\", coll : \"coll\" }, documentKey : { _id : 1 }, fullDocument : { _id : 1 } }"); var rawDocuments = new[] { ToRawDocument(document) }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockCursor.SetupGet(c => c.Current).Returns(rawDocuments); diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Operations/OperationTestBase.cs b/tests/MongoDB.Driver.Core.Tests/Core/Operations/OperationTestBase.cs index 9976ee8424d..3aeb0f8c6bd 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Operations/OperationTestBase.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Operations/OperationTestBase.cs @@ -481,7 +481,8 @@ protected void VerifySessionIdSending( using (var session = CreateSession(cluster, useImplicitSession)) using (var binding = new WritableServerBinding(cluster, session.Fork())) { - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; Exception exception; if (async) { diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Operations/ReadCommandOperationTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Operations/ReadCommandOperationTests.cs index eaca73e5e4a..9ecb6ad267e 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Operations/ReadCommandOperationTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Operations/ReadCommandOperationTests.cs @@ -91,7 +91,8 @@ public void Execute_should_call_channel_Command_with_unwrapped_command_when_wrap var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockReadBinding(readPreference, channelSource).Object; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; BsonDocument result; if (async) @@ -149,7 +150,8 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_additi var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockReadBinding(readPreference, channelSource).Object; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var additionalOptions = BsonDocument.Parse("{ $comment : \"comment\", additional : 1 }"); BsonDocument result; @@ -207,7 +209,8 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockReadBinding(readPreference, channelSource).Object; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var additionalOptions = BsonDocument.Parse("{ $comment : \"comment\" }"); BsonDocument result; @@ -266,7 +269,8 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_readPr var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockReadBinding(readPreference, channelSource).Object; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var additionalOptions = BsonDocument.Parse("{ $comment : \"comment\", additional : 1 }"); BsonDocument result; @@ -322,7 +326,8 @@ public void Execute_should_call_GetChannel_only_once([Values(false, true)] bool var mockChannel = CreateMockChannel(); var mockChannelSource = CreateMockChannelSource(serverDescription, mockChannel.Object); var binding = CreateMockReadBinding(readPreference, mockChannelSource.Object).Object; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (async) { diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Operations/WriteCommandOperationTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Operations/WriteCommandOperationTests.cs index d9d830b0864..8cbb3a60b09 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Operations/WriteCommandOperationTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Operations/WriteCommandOperationTests.cs @@ -65,7 +65,8 @@ public void Execute_should_call_channel_Command_with_unwrapped_command_when_wrap var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockWriteBinding(channelSource).Object; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; BsonDocument result; if (async) @@ -121,7 +122,8 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_additi var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockWriteBinding(channelSource).Object; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var command = BsonDocument.Parse("{ command : 1 }"); BsonDocument result; @@ -178,7 +180,8 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockWriteBinding(channelSource).Object; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var additionalOptions = BsonDocument.Parse("{ $comment : \"comment\" }"); BsonDocument result; diff --git a/tests/MongoDB.Driver.Examples/ChangeStreamExamples.cs b/tests/MongoDB.Driver.Examples/ChangeStreamExamples.cs index b0942ff2242..d3731364c1f 100644 --- a/tests/MongoDB.Driver.Examples/ChangeStreamExamples.cs +++ b/tests/MongoDB.Driver.Examples/ChangeStreamExamples.cs @@ -13,15 +13,14 @@ * limitations under the License. */ -using FluentAssertions; -using MongoDB.Bson; -using MongoDB.Driver.Core.Misc; -using MongoDB.Driver.Core.TestHelpers.XunitExtensions; -using MongoDB.Driver.Tests; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; +using FluentAssertions; +using MongoDB.Bson; +using MongoDB.Driver.Core.TestHelpers.XunitExtensions; +using MongoDB.Driver.Tests; using Xunit; namespace MongoDB.Driver.Examples @@ -135,7 +134,7 @@ public void ChangestreamExample4() var database = client.GetDatabase("ChangeStreamExamples"); database.DropCollection("inventory"); - var cancelationTokenSource = new CancellationTokenSource(); + using var cancelationTokenSource = new CancellationTokenSource(); try { var document = new BsonDocument("username", "alice"); diff --git a/tests/MongoDB.Driver.GridFS.Tests/DelegatingStreamTests.cs b/tests/MongoDB.Driver.GridFS.Tests/DelegatingStreamTests.cs index a779d4274c4..dcd02487a56 100644 --- a/tests/MongoDB.Driver.GridFS.Tests/DelegatingStreamTests.cs +++ b/tests/MongoDB.Driver.GridFS.Tests/DelegatingStreamTests.cs @@ -146,7 +146,8 @@ public void CopyToAsync_should_call_wrapped_stream() var subject = new DelegatingStream(mockStream.Object); var mockDestination = new Mock(); var bufferSize = 1; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var task1 = Task.FromResult(null); mockStream.Setup(s => s.CopyToAsync(mockDestination.Object, bufferSize, cancellationToken)).Returns(task1); @@ -213,7 +214,8 @@ public void FlushAsync_should_call_wrapped_stream() var mockStream = new Mock(); var subject = new DelegatingStream(mockStream.Object); var task = Task.FromResult(null); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockStream.Setup(s => s.FlushAsync(cancellationToken)).Returns(task); var result = subject.FlushAsync(cancellationToken); @@ -261,7 +263,8 @@ public void ReadAsync_should_call_wrapped_stream() var buffer = new byte[3]; var offset = 1; var count = 2; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var task = Task.FromResult(1); mockStream.Setup(s => s.ReadAsync(buffer, offset, count, cancellationToken)).Returns(task); @@ -349,7 +352,8 @@ public void WriteAsync_should_call_wrapped_stream() var buffer = new byte[3]; var offset = 1; var count = 2; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var task = Task.FromResult(null); mockStream.Setup(s => s.WriteAsync(buffer, offset, count, cancellationToken)).Returns(task); diff --git a/tests/MongoDB.Driver.GridFS.Tests/MongoDB.Driver.GridFS.Tests.csproj b/tests/MongoDB.Driver.GridFS.Tests/MongoDB.Driver.GridFS.Tests.csproj index 0fb841e6462..af69688f67f 100644 --- a/tests/MongoDB.Driver.GridFS.Tests/MongoDB.Driver.GridFS.Tests.csproj +++ b/tests/MongoDB.Driver.GridFS.Tests/MongoDB.Driver.GridFS.Tests.csproj @@ -6,7 +6,7 @@ netcoreapp2.1;netcoreapp3.1;net472 netcoreapp2.1;netcoreapp3.1 - 7.3 + 9 true false diff --git a/tests/MongoDB.Driver.Legacy.Tests/DefaultLegacyOperationExecutorTests.cs b/tests/MongoDB.Driver.Legacy.Tests/DefaultLegacyOperationExecutorTests.cs index 14f5d02cc63..ba7b6c94fe8 100644 --- a/tests/MongoDB.Driver.Legacy.Tests/DefaultLegacyOperationExecutorTests.cs +++ b/tests/MongoDB.Driver.Legacy.Tests/DefaultLegacyOperationExecutorTests.cs @@ -32,7 +32,8 @@ public void ExecuteReadOperation_should_execute_operation() var subject = CreateSubject(); var binding = new Mock().Object; var mockOperation = new Mock>(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var result = subject.ExecuteReadOperation(binding, mockOperation.Object, cancellationToken); @@ -45,7 +46,8 @@ public void ExecuteReadOperationAsync_should_execute_operation() var subject = CreateSubject(); var binding = new Mock().Object; var mockOperation = new Mock>(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var result = subject.ExecuteReadOperationAsync(binding, mockOperation.Object, cancellationToken); @@ -58,7 +60,8 @@ public void ExecuteWriteOperation_should_execute_operation() var subject = CreateSubject(); var binding = new Mock().Object; var mockOperation = new Mock>(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var result = subject.ExecuteWriteOperation(binding, mockOperation.Object, cancellationToken); @@ -71,7 +74,8 @@ public void ExecuteWriteOperationAsync_should_execute_operation() var subject = CreateSubject(); var binding = new Mock().Object; var mockOperation = new Mock>(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var result = subject.ExecuteWriteOperationAsync(binding, mockOperation.Object, cancellationToken); @@ -84,7 +88,8 @@ public void StartImplicitSession_should_return_expected_result( [Values(false, true)] bool async) { var subject = CreateSubject(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; IClientSessionHandle result; if (async) diff --git a/tests/MongoDB.Driver.Legacy.Tests/MongoDB.Driver.Legacy.Tests.csproj b/tests/MongoDB.Driver.Legacy.Tests/MongoDB.Driver.Legacy.Tests.csproj index 325603082b1..92c30a55698 100644 --- a/tests/MongoDB.Driver.Legacy.Tests/MongoDB.Driver.Legacy.Tests.csproj +++ b/tests/MongoDB.Driver.Legacy.Tests/MongoDB.Driver.Legacy.Tests.csproj @@ -6,7 +6,7 @@ netcoreapp2.1;netcoreapp3.1;net472 netcoreapp2.1;netcoreapp3.1 - 7.3 + 9 true false diff --git a/tests/MongoDB.Driver.Tests/AggregateFluentTests.cs b/tests/MongoDB.Driver.Tests/AggregateFluentTests.cs index fd3ff205d04..b6bd0f88e0a 100644 --- a/tests/MongoDB.Driver.Tests/AggregateFluentTests.cs +++ b/tests/MongoDB.Driver.Tests/AggregateFluentTests.cs @@ -954,7 +954,8 @@ public void ToCollection_should_call_collection_AggregateToCollection_with_expec } var expectedPipeline = ((AggregateFluent)subject)._pipeline(); var expectedOptions = subject.Options; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (async) { @@ -1026,7 +1027,8 @@ public void ToCollection_should_call_database_AggregateToCollection_with_expecte } var expectedPipeline = ((AggregateFluent)subject)._pipeline(); var expectedOptions = subject.Options; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (async) { @@ -1091,7 +1093,8 @@ public void ToCursor_should_call_collection_Aggregate_with_expected_arguments( .Match(Builders.Filter.Eq(c => c.X, 1)); var expectedPipeline = ((AggregateFluent)subject)._pipeline(); var expectedOptions = subject.Options; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (async) { @@ -1156,7 +1159,8 @@ public void ToCursor_should_call_database_Aggregate_with_expected_arguments( .AppendStage("{ $currentOp : { } }"); var expectedPipeline = ((AggregateFluent)subject)._pipeline(); var expectedOptions = subject.Options; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (async) { diff --git a/tests/MongoDB.Driver.Tests/FindFluentTests.cs b/tests/MongoDB.Driver.Tests/FindFluentTests.cs index 3d78ee3bfb6..b9ca37b891c 100644 --- a/tests/MongoDB.Driver.Tests/FindFluentTests.cs +++ b/tests/MongoDB.Driver.Tests/FindFluentTests.cs @@ -92,7 +92,8 @@ public void Count_should_call_collection_Count( Skip = 3 }; var subject = CreateSubject(session: session, filter: filter, options: findOptions); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; Predicate matchesExpectedOptions = countOptions => countOptions.Collation.Equals(findOptions.Collation) && @@ -179,7 +180,8 @@ public void CountDocuments_should_call_collection_CountDocuments( Skip = 3 }; var subject = CreateSubject(session: session, filter: filter, options: findOptions); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; Predicate matchesExpectedOptions = countOptions => countOptions.Collation.Equals(findOptions.Collation) && @@ -248,7 +250,8 @@ public void ToCursor_should_call_collection_Find_with_expected_arguments( var filter = Builders.Filter.Eq("_id", 1); var options = new FindOptions(); var subject = CreateSubject(session, filter, options); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (async) { diff --git a/tests/MongoDB.Driver.Tests/IAggregateFluentExtensionsTests.cs b/tests/MongoDB.Driver.Tests/IAggregateFluentExtensionsTests.cs index 80f145d9fc2..a589fa79f55 100644 --- a/tests/MongoDB.Driver.Tests/IAggregateFluentExtensionsTests.cs +++ b/tests/MongoDB.Driver.Tests/IAggregateFluentExtensionsTests.cs @@ -46,7 +46,8 @@ public void First_should_add_limit_and_call_ToCursor( new Person { FirstName = "John" }, new Person { FirstName = "Jane" } }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockSubject1.Setup(s => s.Limit(1)).Returns(mockSubject2.Object); mockCursor.SetupGet(c => c.Current).Returns(firstBatch); @@ -106,7 +107,8 @@ public void FirstOrDefault_should_add_limit_and_call_ToCursor( new Person { FirstName = "John" }, new Person { FirstName = "Jane" } }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockSubject1.Setup(s => s.Limit(1)).Returns(mockSubject2.Object); mockCursor.SetupGet(c => c.Current).Returns(firstBatch); @@ -323,7 +325,8 @@ public void Single_should_add_limit_and_call_ToCursor( { new Person { FirstName = "John" } }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockSubject1.Setup(s => s.Limit(2)).Returns(mockSubject2.Object); mockCursor.SetupGet(c => c.Current).Returns(firstBatch); @@ -382,7 +385,8 @@ public void SingleOrDefault_should_add_limit_and_call_ToCursor( { new Person { FirstName = "John" } }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockSubject1.Setup(s => s.Limit(2)).Returns(mockSubject2.Object); mockCursor.SetupGet(c => c.Current).Returns(firstBatch); diff --git a/tests/MongoDB.Driver.Tests/IFindFluentExtensionsTests.cs b/tests/MongoDB.Driver.Tests/IFindFluentExtensionsTests.cs index 324cd0a24af..8c0b6b2b1bc 100644 --- a/tests/MongoDB.Driver.Tests/IFindFluentExtensionsTests.cs +++ b/tests/MongoDB.Driver.Tests/IFindFluentExtensionsTests.cs @@ -42,7 +42,8 @@ public void Any_should_add_projection_and_limit_and_return_expected_result( var mockSubject3 = new Mock>(); var mockCursor = new Mock>(); var firstBatch = Enumerable.Range(0, count).Select(i => new BsonDocument("_id", i)).ToArray(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockSubject1.Setup(s => s.Project(It.Is>(p => p.Document["_id"].AsInt32 == 1))).Returns(mockSubject2.Object); mockSubject2.Setup(s => s.Limit(1)).Returns(mockSubject3.Object); @@ -100,7 +101,8 @@ public void First_should_add_limit_and_call_ToCursor( new Person { FirstName = "John" }, new Person { FirstName = "Jane" } }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockSubject1.Setup(s => s.Limit(1)).Returns(mockSubject2.Object); mockCursor.SetupGet(c => c.Current).Returns(firstBatch); @@ -158,7 +160,8 @@ public void FirstOrDefault_should_add_limit_and_call_ToCursor( new Person { FirstName = "John" }, new Person { FirstName = "Jane" } }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockSubject1.Setup(s => s.Limit(1)).Returns(mockSubject2.Object); mockCursor.SetupGet(c => c.Current).Returns(firstBatch); @@ -249,7 +252,8 @@ public void Single_should_add_limit_and_call_ToCursor( { new Person { FirstName = "John" } }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockSubject1.SetupGet(s => s.Options).Returns(findOptions); mockSubject1.Setup(s => s.Limit(2)).Returns(mockSubject2.Object); @@ -307,7 +311,8 @@ public void SingleOrDefault_should_add_limit_and_call_ToCursor( { new Person { FirstName = "John" } }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; mockSubject1.SetupGet(s => s.Options).Returns(findOptions); mockSubject1.Setup(s => s.Limit(2)).Returns(mockSubject2.Object); diff --git a/tests/MongoDB.Driver.Tests/IMongoClientExtensionsTests.cs b/tests/MongoDB.Driver.Tests/IMongoClientExtensionsTests.cs index d500f478b53..e3a103c5ec7 100644 --- a/tests/MongoDB.Driver.Tests/IMongoClientExtensionsTests.cs +++ b/tests/MongoDB.Driver.Tests/IMongoClientExtensionsTests.cs @@ -33,7 +33,8 @@ public void Watch_should_call_client_with_expected_arguments( var client = mockClient.Object; var session = new Mock().Object; var options = new ChangeStreamOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { diff --git a/tests/MongoDB.Driver.Tests/IMongoCollectionExtensionsTests.cs b/tests/MongoDB.Driver.Tests/IMongoCollectionExtensionsTests.cs index c3ce8ac4c54..77279086626 100644 --- a/tests/MongoDB.Driver.Tests/IMongoCollectionExtensionsTests.cs +++ b/tests/MongoDB.Driver.Tests/IMongoCollectionExtensionsTests.cs @@ -105,7 +105,8 @@ public void Count_should_call_collection_with_expected_arguments( var session = new Mock().Object; var filterExpression = (Expression>)(x => x.FirstName == "Jack"); var options = new CountOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -154,7 +155,8 @@ public void CountDocuments_should_call_collection_with_expected_arguments( var session = new Mock().Object; var filterExpression = (Expression>)(x => x.FirstName == "Jack"); var options = new CountOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -196,7 +198,8 @@ public void DeleteMany_should_call_collection_with_expected_arguments( var session = new Mock().Object; var filterExpression = (Expression>)(x => x.FirstName == "Jack"); var options = new DeleteOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -254,7 +257,8 @@ public void DeleteOne_should_call_collection_with_expected_arguments( var session = new Mock().Object; var filterExpression = (Expression>)(x => x.FirstName == "Jack"); var options = new DeleteOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -316,7 +320,8 @@ public void Distinct_should_call_collection_with_expected_arguments( var filterDefinition = Builders.Filter.Eq(x => x.FirstName, "Jack"); var filterExpression = (Expression>)(x => x.FirstName == "Jack"); var options = new DistinctOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -544,7 +549,8 @@ public void FindSync_should_call_collection_FindSync_with_expected_arguments( var filterDefinition = Builders.Filter.Eq("FirstName", "Jack"); var filterExpression = (Expression>)(x => x.FirstName == "Jack"); var options = new FindOptions(); // no projection - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -621,7 +627,8 @@ public void FindOneAndDelete_should_call_collection_with_expected_arguments( var filterExpression = (Expression>)(x => x.FirstName == "Jack"); var options = new FindOneAndDeleteOptions(); var optionsWithProjection = new FindOneAndDeleteOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -745,7 +752,8 @@ public void FindOneAndReplace_should_call_collection_with_expected_arguments( var replacement = new Person(); var options = new FindOneAndReplaceOptions(); var optionsWithProjection = new FindOneAndReplaceOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -869,7 +877,8 @@ public void FindOneAndUpdate_should_call_collection_with_expected_arguments( var update = Builders.Update.Set("FirstName", "John"); var options = new FindOneAndUpdateOptions(); var optionsWithProjection = new FindOneAndUpdateOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -988,7 +997,8 @@ public void ReplaceOne_should_call_collection_with_expected_arguments( var session = new Mock().Object; var filterExpression = (Expression>)(x => x.FirstName == "Jack"); var replacement = new Person(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; assertReplaceOne(); @@ -1109,7 +1119,8 @@ public void UpdateMany_should_call_collection_with_expected_arguments( var filterExpression = (Expression>)(x => x.FirstName == "Jack"); var update = Builders.Update.Set("FirstName", "John"); var options = new UpdateOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1151,7 +1162,8 @@ public void UpdateOne_should_call_collection_with_expected_arguments( var filterExpression = (Expression>)(x => x.FirstName == "Jack"); var update = Builders.Update.Set("FirstName", "John"); var options = new UpdateOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1191,7 +1203,8 @@ public void Watch_should_call_collection_with_expected_arguments( var collection = mockCollection.Object; var session = new Mock().Object; var options = new ChangeStreamOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { diff --git a/tests/MongoDB.Driver.Tests/IMongoDatabaseExtensionsTests.cs b/tests/MongoDB.Driver.Tests/IMongoDatabaseExtensionsTests.cs index b5f593ff8df..7158c95f3da 100644 --- a/tests/MongoDB.Driver.Tests/IMongoDatabaseExtensionsTests.cs +++ b/tests/MongoDB.Driver.Tests/IMongoDatabaseExtensionsTests.cs @@ -33,7 +33,8 @@ public void Watch_should_call_client_with_expected_arguments( var database = mockDatabase.Object; var session = new Mock().Object; var options = new ChangeStreamOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { diff --git a/tests/MongoDB.Driver.Tests/MongoClientTests.cs b/tests/MongoDB.Driver.Tests/MongoClientTests.cs index 3688a7a3ced..2a943640a98 100644 --- a/tests/MongoDB.Driver.Tests/MongoClientTests.cs +++ b/tests/MongoDB.Driver.Tests/MongoClientTests.cs @@ -78,7 +78,8 @@ public void DropDatabase_should_invoke_the_correct_operation( var writeConcern = new WriteConcern(1); var subject = new MongoClient(operationExecutor, DriverTestConfiguration.GetClientSettings()).WithWriteConcern(writeConcern); var session = CreateClientSession(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -128,7 +129,8 @@ public void ListDatabaseNames_should_invoke_the_correct_operation( var operationExecutor = new MockOperationExecutor(); var subject = new MongoClient(operationExecutor, DriverTestConfiguration.GetClientSettings()); var session = CreateClientSession(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var listDatabaseNamesResult = @" { ""databases"" : [ @@ -221,7 +223,8 @@ public void ListDatabases_should_invoke_the_correct_operation( var operationExecutor = new MockOperationExecutor(); var subject = new MongoClient(operationExecutor, DriverTestConfiguration.GetClientSettings()); var session = CreateClientSession(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var filterDocument = BsonDocument.Parse("{ name : \"awesome\" }"); var filterDefinition = (FilterDefinition)filterDocument; var nameOnly = true; @@ -291,7 +294,8 @@ public void Watch_should_invoke_the_correct_operation( StartAfter = new BsonDocument(), StartAtOperationTime = new BsonTimestamp(1, 2) }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var renderedPipeline = new[] { BsonDocument.Parse("{ $limit : 1 }") }; if (usingSession) diff --git a/tests/MongoDB.Driver.Tests/MongoCollectionImplTests.cs b/tests/MongoDB.Driver.Tests/MongoCollectionImplTests.cs index 26767d56d9f..c3ceaba7e4b 100644 --- a/tests/MongoDB.Driver.Tests/MongoCollectionImplTests.cs +++ b/tests/MongoDB.Driver.Tests/MongoCollectionImplTests.cs @@ -95,7 +95,8 @@ public void Aggregate_should_execute_an_AggregateOperation_when_out_is_not_speci UseCursor = false #pragma warning restore 618 }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var renderedPipeline = RenderPipeline(subject, pipeline); if (usingSession) @@ -174,8 +175,12 @@ public void Aggregate_should_execute_an_AggregateToCollectionOperation_and_a_Fin UseCursor = false #pragma warning restore 618 }; - var cancellationToken1 = new CancellationTokenSource().Token; - var cancellationToken2 = new CancellationTokenSource().Token; + + using var cancellationTokenSource1 = new CancellationTokenSource(); + using var cancellationTokenSource2 = new CancellationTokenSource(); + + var cancellationToken1 = cancellationTokenSource1.Token; + var cancellationToken2 = cancellationTokenSource2.Token; var expectedPipeline = new List(RenderPipeline(subject, pipeline).Documents); if (!usingDifferentOutputDatabase) { @@ -348,7 +353,8 @@ public void AggregateToCollection_should_execute_an_AggregateToCollectionOperati UseCursor = false #pragma warning restore 618 }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var expectedPipeline = new List(RenderPipeline(subject, pipeline).Documents); if (!usingDifferentOutputDatabase) { @@ -406,7 +412,8 @@ public void AggregateToCollection_should_throw_when_last_stage_is_not_an_output_ var pipeline = new EmptyPipelineDefinition() .Match("{ x : 2 }"); var options = new AggregateOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; Exception exception; if (async) @@ -472,7 +479,8 @@ public void BulkWrite_should_execute_a_BulkMixedWriteOperation( IsOrdered = isOrdered, Let = letDocument }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var operationResult = new BulkWriteOperationResult.Unacknowledged(14, new[] { new InsertRequest(new BsonDocument("b", 1)) }); _operationExecutor.EnqueueResult(operationResult); @@ -735,7 +743,8 @@ public void Count_should_execute_a_CountOperation( MaxTime = TimeSpan.FromSeconds(20), Skip = 30 }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -800,7 +809,8 @@ public void CountDocuments_should_execute_a_CountDocumentsOperation( MaxTime = TimeSpan.FromSeconds(20), Skip = 30 }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -854,7 +864,8 @@ public void DeleteMany_should_execute_a_BulkMixedOperation( var hint = new BsonDocument("_id", 1); var letDocument = let != null ? BsonDocument.Parse(let) : null; var options = new DeleteOptions { Collation = collation, Let = letDocument }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new DeleteRequest(filter) { Collation = collation, CorrelationId = 0, Hint = hint, Limit = 0 }; var operationResult = new BulkWriteOperationResult.Unacknowledged(9, new[] { processedRequest }); @@ -899,7 +910,8 @@ public void DeleteMany_should_throw_a_WriteException_when_an_error_occurs( var session = CreateSession(usingSession); var filter = new BsonDocument("a", 1); var options = new DeleteOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new DeleteRequest(filter) { CorrelationId = 0, Limit = 0 }; var operationException = new MongoBulkWriteOperationException( @@ -961,7 +973,8 @@ public void DeleteOne_should_execute_a_BulkMixedOperation( var hint = new BsonDocument("_id", 1); var letDocument = let != null ? BsonDocument.Parse(let) : null; var options = new DeleteOptions { Collation = collation, Let = letDocument }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new DeleteRequest(filter) { @@ -1012,7 +1025,8 @@ public void DeleteOne_should_throw_a_WriteException_when_an_error_occurs( var session = CreateSession(usingSession); var filter = new BsonDocument("a", 1); var options = new DeleteOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new DeleteRequest(filter) { CorrelationId = 0, Limit = 1 }; var operationException = new MongoBulkWriteOperationException( @@ -1077,7 +1091,8 @@ public void Distinct_should_execute_a_DistinctOperation( Collation = new Collation("en_US"), MaxTime = TimeSpan.FromSeconds(20) }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1142,7 +1157,8 @@ public void Distinct_should_execute_a_DistinctOperation_when_type_parameter_is_a Collation = new Collation("en_US"), MaxTime = TimeSpan.FromSeconds(20) }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1203,7 +1219,8 @@ public void Distinct_should_execute_a_DistinctOperation_when_type_parameter_is_s Collation = new Collation("en_US"), MaxTime = TimeSpan.FromSeconds(20) }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1254,7 +1271,8 @@ public void EstimatedDocumentCount_should_execute_an_EstimatedDocumentCount_oper { MaxTime = TimeSpan.FromSeconds(20) }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (async) { @@ -1314,7 +1332,8 @@ public void Find_should_execute_a_FindOperation( Skip = 40, Sort = sortDefinition }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1408,7 +1427,8 @@ public void Find_with_an_expression_execute_a_FindOperation( Skip = 40, Sort = sortDefinition }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1479,7 +1499,8 @@ public void Find_with_Projection_As_should_execute_correctly( Projection = Builders.Projection.As(), Let = letDocument }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1538,7 +1559,8 @@ public void FindOneAndDelete_should_execute_a_FindOneAndDeleteOperation( Sort = sortDefinition, MaxTime = TimeSpan.FromSeconds(2) }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1595,7 +1617,8 @@ public void FindOneAndDelete_with_Projection_As_should_execute_correctly( Let = letDocument, Projection = Builders.Projection.As() }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1663,7 +1686,8 @@ public void FindOneAndReplace_should_execute_a_FindOneAndReplaceOperation( ReturnDocument = returnDocument, Sort = sortDefinition }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1725,7 +1749,8 @@ public void FindOneAndReplace_with_Projection_As_should_execute_correctly( Let = letDocument, Projection = Builders.Projection.As() }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1796,7 +1821,8 @@ public void FindOneAndUpdate_should_execute_a_FindOneAndUpdateOperation( ReturnDocument = returnDocument, Sort = sortDefinition, }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1858,7 +1884,8 @@ public void FindOneAndUpdate_should_throw_if_parameters_are_invalid( { ArrayFilters = new[] { arrayFilterDefinition }, }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; Exception exception; if (async) @@ -1891,7 +1918,8 @@ public void FindOneAndUpdate_with_Projection_As_should_execute_correctly( Projection = Builders.Projection.As(), Let = letDocument }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1981,7 +2009,8 @@ public void Indexes_CreateOne_should_execute_a_CreateIndexesOperation( options.WildcardProjection = wildcardProjectionDefinition; } - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var model = new CreateIndexModel(keysDefinition, options); if (usingSession) @@ -2118,7 +2147,8 @@ public void Indexes_CreateMany_should_execute_a_CreateIndexesOperation( var model1 = new CreateIndexModel(keysDefinition1, options); var model2 = new CreateIndexModel(keysDefinition2); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -2230,7 +2260,8 @@ public void Indexes_DropAll_should_execute_a_DropIndexOperation( var writeConcern = new WriteConcern(1); var subject = CreateSubject().WithWriteConcern(writeConcern); var session = CreateSession(usingSession); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var maxTime = TimeSpan.FromMilliseconds(42); var options = new DropIndexOptions { MaxTime = maxTime }; @@ -2276,7 +2307,8 @@ public void Indexes_DropOne_should_execute_a_DropIndexOperation( var writeConcern = new WriteConcern(1); var subject = CreateSubject().WithWriteConcern(writeConcern); var session = CreateSession(usingSession); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var maxTime = TimeSpan.FromMilliseconds(42); var options = new DropIndexOptions { MaxTime = maxTime }; @@ -2321,7 +2353,8 @@ public void Indexes_DropOne_should_throw_an_exception_if_an_asterisk_is_used( { var subject = CreateSubject(); var session = CreateSession(usingSession); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; Exception exception; if (async) @@ -2346,7 +2379,8 @@ public void Indexes_List_should_execute_a_ListIndexesOperation( { var subject = CreateSubject(); var session = CreateSession(usingSession); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (batchSize.HasValue) { @@ -2420,7 +2454,8 @@ public void InsertOne_should_execute_a_BulkMixedOperation( var session = CreateSession(usingSession); var document = BsonDocument.Parse("{ _id : 1, a : 1 }"); var options = new InsertOneOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new InsertRequest(document) { CorrelationId = 0 }; var operationResult = new BulkWriteOperationResult.Unacknowledged(1, new[] { processedRequest }); @@ -2465,7 +2500,8 @@ public void InsertOne_should_throw_a_WriteException_when_an_error_occurs( var session = CreateSession(usingSession); var document = BsonDocument.Parse("{ _id : 1, a : 1 }"); var options = new InsertOneOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new InsertRequest(document) { CorrelationId = 0 }; var operationException = new MongoBulkWriteOperationException( @@ -2525,7 +2561,8 @@ public void InsertOne_should_respect_AssignIdOnInsert( var session = CreateSession(usingSession); var document = BsonDocument.Parse("{ a : 1 }"); var options = new InsertOneOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new InsertRequest(document) { CorrelationId = 0 }; var operationResult = new BulkWriteOperationResult.Unacknowledged(1, new[] { processedRequest }); @@ -2584,7 +2621,8 @@ public void InsertMany_should_execute_a_BulkMixedOperation( BypassDocumentValidation = bypassDocumentValidation, IsOrdered = isOrdered }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequests = new[] { @@ -2635,7 +2673,8 @@ public void InsertMany_should_respect_AssignIdOnInsert( var session = CreateSession(usingSession); var document = BsonDocument.Parse("{ a : 1 }"); var options = new InsertManyOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new InsertRequest(document) { CorrelationId = 0 }; var operationResult = new BulkWriteOperationResult.Unacknowledged(1, new[] { processedRequest }); @@ -2707,7 +2746,8 @@ public void MapReduce_with_inline_output_mode_should_execute_a_MapReduceOperatio Sort = sortDefinition, Verbose = true }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -2799,7 +2839,8 @@ public void MapReduce_with_collection_output_mode_should_execute_a_MapReduceOutp Sort = sortDefinition, Verbose = true }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -2883,7 +2924,8 @@ public void ReplaceOne_should_execute_a_BulkMixedOperation( var collation = new Collation("en_US"); var hint = new BsonDocument("x", 1); var letDocument = let != null ? BsonDocument.Parse(let) : null; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new UpdateRequest(UpdateType.Replacement, filterDocument, replacement) { @@ -3038,7 +3080,8 @@ public void ReplaceOne_should_throw_a_WriteException_when_an_error_occurs( var collation = new Collation("en_US"); var hint = new BsonDocument("x", 1); var letDocument = let != null ? BsonDocument.Parse(let) : null; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new UpdateRequest(UpdateType.Replacement, filterDocument, replacement) { @@ -3223,7 +3266,8 @@ public void UpdateMany_should_execute_a_BulkMixedOperation( IsUpsert = isUpsert, Let = letDocument }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new UpdateRequest(UpdateType.Update, filterDocument, updateDocument) { @@ -3295,7 +3339,8 @@ public void UpdateMany_should_throw_a_WriteException_when_an_error_occurs( IsUpsert = isUpsert, Let = letDocument }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new UpdateRequest(UpdateType.Update, filterDocument, updateDocument) { @@ -3380,7 +3425,8 @@ public void UpdateOne_should_execute_a_BulkMixedOperation( IsUpsert = isUpsert, Let = letDocument }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new UpdateRequest(UpdateType.Update, filterDocument, updateDocument) { @@ -3453,7 +3499,8 @@ public void UpdateOne_should_throw_a_WriteException_when_an_error_occurs( IsUpsert = isUpsert, Let = letDocument }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var processedRequest = new UpdateRequest(UpdateType.Update, filterDocument, updateDocument) { @@ -3547,7 +3594,8 @@ public void Watch_should_execute_a_ChangeStreamOperation( StartAfter = startAfter, StartAtOperationTime = startAtOperationTime }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -3605,7 +3653,8 @@ public void Watch_should_execute_a_ChangeStreamOperation_with_default_options_wh var stageDocument = BsonDocument.Parse("{ $match : { operationType : \"insert\" } }"); var pipeline = (PipelineDefinition, ChangeStreamDocument>)(new[] { stageDocument }); ChangeStreamOptions options = null; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { diff --git a/tests/MongoDB.Driver.Tests/MongoDatabaseImplTests.cs b/tests/MongoDB.Driver.Tests/MongoDatabaseImplTests.cs index 2a381db534f..90710661ccf 100644 --- a/tests/MongoDB.Driver.Tests/MongoDatabaseImplTests.cs +++ b/tests/MongoDB.Driver.Tests/MongoDatabaseImplTests.cs @@ -91,7 +91,8 @@ public void Aggregate_should_execute_an_AggregateOperation_when_out_is_not_speci UseCursor = false #pragma warning restore 618 }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var renderedPipeline = RenderPipeline(subject, pipeline); if (usingSession) @@ -291,7 +292,8 @@ public void AggregateToCollection_should_execute_an_AggregateToCollectionOperati UseCursor = false #pragma warning restore 618 }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var expectedPipeline = new List(RenderPipeline(subject, pipeline).Documents); if (!usingDifferentOutputDatabase && lastStageName == "$out") { @@ -349,7 +351,8 @@ public void AggregateToCollection_should_throw_when_last_stage_is_not_an_output_ var pipeline = new EmptyPipelineDefinition() .AppendStage("{ $currentOp : { } }"); var options = new AggregateOptions(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; Exception exception; if (async) @@ -418,7 +421,8 @@ public void CreateCollection_should_execute_a_CreateCollectionOperation_when_opt Validator = validatorDefinition }; #pragma warning restore - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -501,7 +505,8 @@ public void CreateCollection_should_execute_a_CreateCollectionOperation_when_opt ValidationLevel = DocumentValidationLevel.Off }; #pragma warning restore - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -559,7 +564,8 @@ public void CreateCollection_should_execute_a_CreateCollectionOperation_when_opt var subject = _subject.WithWriteConcern(writeConcern); var session = CreateSession(usingSession); var name = "bar"; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -626,7 +632,8 @@ public void CreateView_should_execute_a_CreateViewOperation( DocumentSerializer = BsonDocumentSerializer.Instance, SerializerRegistry = BsonSerializer.SerializerRegistry }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -789,7 +796,8 @@ public void DropCollection_should_execute_a_DropCollectionOperation( var subject = _subject.WithWriteConcern(writeConcern); var session = CreateSession(usingSession); var name = "bar"; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -841,7 +849,8 @@ public void ListCollectionNames_should_execute_a_ListCollectionsOperation( Filter = filterDefinition }; } - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var mockCursor = new Mock>(); _operationExecutor.EnqueueResult>(mockCursor.Object); @@ -969,7 +978,8 @@ public void ListCollections_should_execute_a_ListCollectionsOperation( Filter = usingFilter ? filterDefinition : null }; } - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var mockCursor = new Mock>(); _operationExecutor.EnqueueResult>(mockCursor.Object); @@ -1029,7 +1039,8 @@ public void RenameCollection_should_execute_a_RenameCollectionOperation( { DropTarget = true, }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1073,7 +1084,8 @@ public void RunCommand_should_default_to_ReadPreference_primary( var session = CreateSession(usingSession); var commandDocument = BsonDocument.Parse("{ count : \"foo\" }"); var command = (Command)commandDocument; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1119,7 +1131,8 @@ public void RunCommand_should_use_the_provided_ReadPreference( var commandDocument = new BsonDocument("count", "foo"); var command = (Command)commandDocument; var readPreference = ReadPreference.Secondary; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1164,7 +1177,8 @@ public void RunCommand_should_run_a_non_read_command( var session = CreateSession(usingSession); var commandDocument = new BsonDocument("shutdown", 1); var command = (Command)commandDocument; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1209,7 +1223,8 @@ public void RunCommand_should_run_a_json_command( var session = CreateSession(usingSession); var commandJson = "{ count : \"foo\" }"; var commandDocument = BsonDocument.Parse(commandJson); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1254,7 +1269,8 @@ public void RunCommand_should_run_a_serialized_command( var session = CreateSession(usingSession); var commandObject = new CountCommand { Collection = "foo" }; var command = new ObjectCommand(commandObject); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1300,7 +1316,8 @@ public void RunCommand_should_set_RetryRequested_to_false( var commandDocument = new BsonDocument("count", "foo"); var command = (Command)commandDocument; var readPreference = ReadPreference.Secondary; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; if (usingSession) { @@ -1349,7 +1366,8 @@ public void Watch_should_invoke_the_correct_operation( StartAfter = new BsonDocument(), StartAtOperationTime = new BsonTimestamp(1, 2) }; - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var renderedPipeline = new[] { BsonDocument.Parse("{ $limit : 1 }") }; if (usingSession) diff --git a/tests/MongoDB.Driver.Tests/OfTypeMongoCollectionTests.cs b/tests/MongoDB.Driver.Tests/OfTypeMongoCollectionTests.cs index a5239a2f39c..ae24e361aea 100644 --- a/tests/MongoDB.Driver.Tests/OfTypeMongoCollectionTests.cs +++ b/tests/MongoDB.Driver.Tests/OfTypeMongoCollectionTests.cs @@ -599,7 +599,8 @@ public void EstimatedDocumentCount_should_throw( [Values(false, true)] bool async) { var subject = CreateSubject(); - var cancellationToken = new CancellationTokenSource().Token; + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; var exception = Record.Exception(() => {