diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Authentication/GenericAuthenticationProvider_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Authentication/GenericAuthenticationProvider_Tests.cs index 2ec180a6..89e0a822 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Authentication/GenericAuthenticationProvider_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Authentication/GenericAuthenticationProvider_Tests.cs @@ -206,7 +206,7 @@ public async Task GetTokenAsync_CallsOnFirstRun() { int count = 0; GenericAuthenticationProvider sut = new(_ => { count++; return Task.FromResult(ValidAuthenticationToken); }); - string actual = await sut.GetTokenAsync(); + string actual = await sut.GetTokenAsync(cancellationToken: TestContext.Current.CancellationToken); actual.Should().Be(ValidAuthenticationToken.Token); count.Should().Be(1); } @@ -216,8 +216,8 @@ public async Task GetTokenAsync_CachesResult() { int count = 0; GenericAuthenticationProvider sut = new(_ => { count++; return Task.FromResult(ValidAuthenticationToken); }); - string firstCall = await sut.GetTokenAsync(); - string secondCall = await sut.GetTokenAsync(); + string firstCall = await sut.GetTokenAsync(cancellationToken: TestContext.Current.CancellationToken); + string secondCall = await sut.GetTokenAsync(cancellationToken: TestContext.Current.CancellationToken); firstCall.Should().Be(ValidAuthenticationToken.Token); secondCall.Should().Be(ValidAuthenticationToken.Token); count.Should().Be(1); @@ -228,9 +228,9 @@ public async Task GetTokenAsync_CallsOnForce() { int count = 0; GenericAuthenticationProvider sut = new(_ => { count++; return Task.FromResult(ValidAuthenticationToken); }); - string firstCall = await sut.GetTokenAsync(); + string firstCall = await sut.GetTokenAsync(cancellationToken: TestContext.Current.CancellationToken); firstCall.Should().Be(ValidAuthenticationToken.Token); - string secondCall = await sut.GetTokenAsync(true); + string secondCall = await sut.GetTokenAsync(true, TestContext.Current.CancellationToken); secondCall.Should().Be(ValidAuthenticationToken.Token); count.Should().Be(2); } @@ -239,14 +239,14 @@ public async Task GetTokenAsync_CallsOnForce() public async Task GetTokenAsync_LogsOutWhenExpired() { GenericAuthenticationProvider sut = new(_ => Task.FromResult(ValidAuthenticationToken)); - string firstCall = await sut.GetTokenAsync(); + string firstCall = await sut.GetTokenAsync(cancellationToken: TestContext.Current.CancellationToken); firstCall.Should().Be(ValidAuthenticationToken.Token); sut.DisplayName.Should().Be(ValidAuthenticationToken.DisplayName); sut.UserId.Should().Be(ValidAuthenticationToken.UserId); sut.IsLoggedIn.Should().BeTrue(); sut.TokenRequestorAsync = _ => Task.FromResult(ExpiredAuthenticationToken); - string secondCall = await sut.GetTokenAsync(true); + string secondCall = await sut.GetTokenAsync(true, TestContext.Current.CancellationToken); secondCall.Should().BeNull(); sut.DisplayName.Should().BeNull(); sut.UserId.Should().BeNull(); @@ -258,7 +258,7 @@ public async Task LoginAsync_CallsTokenRequestor() { int count = 0; GenericAuthenticationProvider sut = new(_ => { count++; return Task.FromResult(ValidAuthenticationToken); }); - await sut.LoginAsync(); + await sut.LoginAsync(TestContext.Current.CancellationToken); count.Should().Be(1); } @@ -267,9 +267,9 @@ public async Task LoginAsync_ForcesTokenRequestor() { int count = 0; GenericAuthenticationProvider sut = new(_ => { count++; return Task.FromResult(ValidAuthenticationToken); }); - string firstCall = await sut.GetTokenAsync(); + string firstCall = await sut.GetTokenAsync(cancellationToken: TestContext.Current.CancellationToken); firstCall.Should().Be(ValidAuthenticationToken.Token); - await sut.LoginAsync(); + await sut.LoginAsync(TestContext.Current.CancellationToken); count.Should().Be(2); } @@ -284,7 +284,7 @@ public async Task SendAsync_AddsHeader_BearerAuth() InnerHandler = handler }; - HttpResponseMessage response = await sut.WrappedSendAsync(request); + HttpResponseMessage response = await sut.WrappedSendAsync(request, TestContext.Current.CancellationToken); response.Should().NotBeNull(); @@ -303,7 +303,7 @@ public async Task SendAsync_NoHeader_WhenExpired() InnerHandler = handler }; - HttpResponseMessage response = await sut.WrappedSendAsync(request); + HttpResponseMessage response = await sut.WrappedSendAsync(request, TestContext.Current.CancellationToken); response.Should().NotBeNull(); @@ -323,7 +323,7 @@ public async Task SendAsync_RemoveHeader_WhenExpired() InnerHandler = handler }; - HttpResponseMessage response = await sut.WrappedSendAsync(request); + HttpResponseMessage response = await sut.WrappedSendAsync(request, TestContext.Current.CancellationToken); response.Should().NotBeNull(); @@ -343,7 +343,7 @@ public async Task SendAsync_OverwritesHeader_WhenNotExpired() InnerHandler = handler }; - HttpResponseMessage response = await sut.WrappedSendAsync(request); + HttpResponseMessage response = await sut.WrappedSendAsync(request, TestContext.Current.CancellationToken); response.Should().NotBeNull(); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/ConflictResolver_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/ConflictResolver_Tests.cs index 4a812df9..cf1decd5 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/ConflictResolver_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/ConflictResolver_Tests.cs @@ -33,7 +33,7 @@ public async Task ClientWinsConflictResolver_ShouldReturnClientObject() }; // Act - var resolution = await clientResolver.ResolveConflictAsync(clientObject, serverObject); + var resolution = await clientResolver.ResolveConflictAsync(clientObject, serverObject, TestContext.Current.CancellationToken); // Assert resolution.Result.Should().Be(ConflictResolutionResult.Client); @@ -53,7 +53,7 @@ public async Task ServerWinsConflictResolver_ShouldReturnServerObject() }; // Act - var resolution = await serverResolver.ResolveConflictAsync(clientObject, serverObject); + var resolution = await serverResolver.ResolveConflictAsync(clientObject, serverObject, TestContext.Current.CancellationToken); // Assert resolution.Result.Should().Be(ConflictResolutionResult.Server); @@ -68,7 +68,7 @@ public async Task ClientWinsConflictResolver_ShouldReturnClientObject_WithNullSe var clientObject = new ClientMovie(TestData.Movies.BlackPanther) { Id = "test-id" }; // Act - var resolution = await clientResolver.ResolveConflictAsync(clientObject, null); + var resolution = await clientResolver.ResolveConflictAsync(clientObject, null, TestContext.Current.CancellationToken); // Assert resolution.Result.Should().Be(ConflictResolutionResult.Client); @@ -87,7 +87,7 @@ public async Task ServerWinsConflictResolver_ShouldReturnServerObject_WithNullCl }; // Act - var resolution = await serverResolver.ResolveConflictAsync(null, serverObject); + var resolution = await serverResolver.ResolveConflictAsync(null, serverObject, TestContext.Current.CancellationToken); // Assert resolution.Result.Should().Be(ConflictResolutionResult.Server); @@ -112,7 +112,7 @@ public async Task GenericConflictResolver_ShouldResolveTypedConflict() }; // Act - var resolution = await resolver.ResolveConflictAsync(clientObject, serverObject); + var resolution = await resolver.ResolveConflictAsync(clientObject, serverObject, TestContext.Current.CancellationToken); // Assert resolution.Result.Should().Be(ConflictResolutionResult.Client); @@ -136,7 +136,7 @@ public async Task GenericConflictResolver_ObjectMethod_ShouldCallTypedMethod() }; // Act - var resolution = await resolver.ResolveConflictAsync((object)clientObject, (object)serverObject); + var resolution = await resolver.ResolveConflictAsync((object)clientObject, (object)serverObject, TestContext.Current.CancellationToken); // Assert resolution.Result.Should().Be(ConflictResolutionResult.Client); @@ -154,7 +154,7 @@ public async Task GenericConflictResolver_BothNull_ShouldReturnDefault() var resolver = new TestGenericConflictResolver(); // Act - var resolution = await resolver.ResolveConflictAsync(null, null); + var resolution = await resolver.ResolveConflictAsync(null, null, TestContext.Current.CancellationToken); // Assert resolution.Result.Should().Be(ConflictResolutionResult.Default); @@ -216,7 +216,7 @@ public async Task PushAsync_WithDefaultClientWinsResolver_ShouldResolveConflictA context.Handler.AddResponseContent(finalJson, HttpStatusCode.OK); // Act - var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); // Assert result.IsSuccessful.Should().BeTrue(); @@ -281,7 +281,7 @@ public async Task PushAsync_WithClientWinsResolver_ShouldResolveConflictAndRetry context.Handler.AddResponseContent(finalJson, HttpStatusCode.OK); // Act - var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); // Assert result.IsSuccessful.Should().BeTrue(); @@ -339,7 +339,7 @@ public async Task PushAsync_WithServerWinsResolver_ShouldResolveConflictAndRetry context.Handler.AddResponseContent(finalJson, HttpStatusCode.OK); // Act - var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); // Assert result.IsSuccessful.Should().BeTrue(); @@ -400,7 +400,7 @@ public async Task PushAsync_WithCustomResolver_ShouldResolveConflictAndRetry() context.Handler.AddResponseContent(finalJson, HttpStatusCode.OK); // Act - var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); // Assert result.IsSuccessful.Should().BeTrue(); @@ -459,7 +459,7 @@ public async Task PushAsync_WithPreconditionFailed_ShouldResolveConflict() context.Handler.AddResponseContent(finalJson, HttpStatusCode.OK); // Act - var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); // Assert result.IsSuccessful.Should().BeTrue(); @@ -513,7 +513,7 @@ public async Task PushAsync_WithDeleteOperation_AndConflict_ShouldResolveConflic context.Handler.AddResponse(HttpStatusCode.NoContent); // Act - var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); // Assert result.IsSuccessful.Should().BeTrue(); @@ -556,7 +556,7 @@ public async Task PushAsync_WithDeleteOperation_AndConflict_ServerWinsResolver_S context.Handler.AddResponse(HttpStatusCode.NoContent); // Act - var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); // Assert result.IsSuccessful.Should().BeTrue(); @@ -596,7 +596,7 @@ public async Task PushAsync_WithReplaceOperation_AndConflict_ShouldResolveConfli context.Handler.AddResponseContent(DatasyncSerializer.Serialize(serverMovie), HttpStatusCode.Conflict); // Act - var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); // Assert result.IsSuccessful.Should().BeTrue(); @@ -637,7 +637,7 @@ public async Task PushAsync_WithNull_ConflictResolver_ShouldNotResolveConflict() context.Handler.AddResponseContent(serverJson, HttpStatusCode.Conflict); // Act - var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + var result = await context.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); // Assert result.IsSuccessful.Should().BeFalse(); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/DefaultDeltaTokenStore_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/DefaultDeltaTokenStore_Tests.cs index 9abdf209..7cbdc6b3 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/DefaultDeltaTokenStore_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/DefaultDeltaTokenStore_Tests.cs @@ -18,7 +18,7 @@ public class DefaultDeltaTokenStore_Tests : BaseTest [Fact] public async Task GetDeltaTokenAsync_ReturnsMinValueWhenMissing() { - DateTimeOffset actual = await DeltaTokenStore.GetDeltaTokenAsync("abc"); + DateTimeOffset actual = await DeltaTokenStore.GetDeltaTokenAsync("abc", TestContext.Current.CancellationToken); actual.ToUnixTimeMilliseconds().Should().Be(0); } @@ -28,7 +28,7 @@ public async Task GetDeltaTokenAsync_ReturnsValueWhenPresent() DateTimeOffset expected = DateTimeOffset.UtcNow; this.context.DatasyncDeltaTokens.Add(new DatasyncDeltaToken() { Id = "abc", Value = expected.ToUnixTimeMilliseconds() }); this.context.SaveChanges(); - DateTimeOffset actual = await DeltaTokenStore.GetDeltaTokenAsync("abc"); + DateTimeOffset actual = await DeltaTokenStore.GetDeltaTokenAsync("abc", TestContext.Current.CancellationToken); actual.ToUnixTimeMilliseconds().Should().Be(expected.ToUnixTimeMilliseconds()); } diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/DynamicProxies_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/DynamicProxies_Tests.cs index 239209cc..60ea698c 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/DynamicProxies_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/DynamicProxies_Tests.cs @@ -78,13 +78,13 @@ await context.DynamicProxiesEntities1.AddAsync(new DynamicProxiesEntity1 Name = $"Test {DateTime.Now}", LocalNotes = "These notes should not be serialized into DatasyncOperationsQueue", RelatedEntity = new() { Id = Guid.NewGuid().ToString() } - }); - await context.SaveChangesAsync(); + }, TestContext.Current.CancellationToken); + await context.SaveChangesAsync(TestContext.Current.CancellationToken); } await using (DynamicProxiesTestContext context = new(dbContextOptions)) { - DatasyncOperation operationAfterInsert = await context.DatasyncOperationsQueue.FirstAsync(o => o.ItemId == key); + DatasyncOperation operationAfterInsert = await context.DatasyncOperationsQueue.FirstAsync(o => o.ItemId == key, TestContext.Current.CancellationToken); operationAfterInsert.EntityType.Should().EndWith("DynamicProxiesEntity1"); operationAfterInsert.Version.Should().Be(0); @@ -92,17 +92,17 @@ await context.DynamicProxiesEntities1.AddAsync(new DynamicProxiesEntity1 operationAfterInsert.Item.Should().NotContain("\"localNotes\":"); // Update the entity within the DbContext - DynamicProxiesEntity1 entity = await context.DynamicProxiesEntities1.FirstAsync(e => e.Id == key); + DynamicProxiesEntity1 entity = await context.DynamicProxiesEntities1.FirstAsync(e => e.Id == key, TestContext.Current.CancellationToken); string updatedName = $"Updated name {DateTime.Now}"; entity.Name = updatedName; - await context.SaveChangesAsync(); + await context.SaveChangesAsync(TestContext.Current.CancellationToken); // There should be 1 operation. - int operationsWithItemId = await context.DatasyncOperationsQueue.CountAsync(o => o.ItemId == key); + int operationsWithItemId = await context.DatasyncOperationsQueue.CountAsync(o => o.ItemId == key, TestContext.Current.CancellationToken); operationsWithItemId.Should().Be(1); // Here is the operation after edit. - DatasyncOperation operationAfterEdit = await context.DatasyncOperationsQueue.FirstAsync(o => o.ItemId == key); + DatasyncOperation operationAfterEdit = await context.DatasyncOperationsQueue.FirstAsync(o => o.ItemId == key, TestContext.Current.CancellationToken); operationAfterEdit.EntityType.Should().EndWith("DynamicProxiesEntity1"); operationAfterEdit.Version.Should().Be(1); operationAfterEdit.Item.Should().Contain($"\"name\":\"{updatedName}\""); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Integration_Pull_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Integration_Pull_Tests.cs index da4544c1..65d6ad09 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Integration_Pull_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Integration_Pull_Tests.cs @@ -44,8 +44,8 @@ public void Dispose() [Fact] public async Task PullAsync_ViaDbSet_Works() { - await this.context.Movies.PullAsync(); - List movies = await this.context.Movies.ToListAsync(); + await this.context.Movies.PullAsync(TestContext.Current.CancellationToken); + List movies = await this.context.Movies.ToListAsync(TestContext.Current.CancellationToken); movies.Count.Should().Be(248); foreach (ClientMovie movie in movies) @@ -60,8 +60,8 @@ public async Task PullAsync_ViaDbSet_Works() [Fact] public async Task PullAsync_ViaDbSet_Works_ByteVersion() { - await this.context.ByteMovies.PullAsync(); - List movies = await this.context.ByteMovies.ToListAsync(); + await this.context.ByteMovies.PullAsync(TestContext.Current.CancellationToken); + List movies = await this.context.ByteMovies.ToListAsync(TestContext.Current.CancellationToken); movies.Count.Should().Be(248); foreach (ByteVersionMovie movie in movies) @@ -76,8 +76,8 @@ public async Task PullAsync_ViaDbSet_Works_ByteVersion() [Fact] public async Task PullAsync_ViaContext_Works() { - await this.context.PullAsync(); - List movies = await this.context.Movies.ToListAsync(); + await this.context.PullAsync(TestContext.Current.CancellationToken); + List movies = await this.context.Movies.ToListAsync(TestContext.Current.CancellationToken); movies.Count.Should().Be(248); foreach (ClientMovie movie in movies) @@ -107,8 +107,8 @@ await this.context.PullAsync(builder => opt.QueryId = "pg13-rated"; opt.Query.Where(x => x.Rating == MovieRating.PG13); }); - }); - List movies = await this.context.Movies.ToListAsync(); + }, TestContext.Current.CancellationToken); + List movies = await this.context.Movies.ToListAsync(TestContext.Current.CancellationToken); int expectedCount = TestCommon.TestData.Movies.MovieList.Count(x => x.Rating is MovieRating.PG or MovieRating.PG13); movies.Count.Should().Be(expectedCount); @@ -126,39 +126,39 @@ public async Task PullAsync_WithLocalData_Works() { const string testId = "id-010"; - await this.context.MoviesWithLocalData.PullAsync(); + await this.context.MoviesWithLocalData.PullAsync(TestContext.Current.CancellationToken); - ClientMovieWithLocalData t1 = await this.context.MoviesWithLocalData.FindAsync([testId]); + ClientMovieWithLocalData t1 = await this.context.MoviesWithLocalData.FindAsync([testId], TestContext.Current.CancellationToken); // Update the local data part and push it back to the server. t1.UserRating = 5; this.context.Update(t1); - await this.context.SaveChangesAsync(); - await this.context.MoviesWithLocalData.PushAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); + await this.context.MoviesWithLocalData.PushAsync(TestContext.Current.CancellationToken); // Reload the local data from the server and check that the local data is still there - await this.context.Entry(t1).ReloadAsync(); + await this.context.Entry(t1).ReloadAsync(TestContext.Current.CancellationToken); t1.UserRating.Should().Be(5); // Pull again and check that the local data is still there. - await this.context.MoviesWithLocalData.PullAsync(); - ClientMovieWithLocalData t2 = await this.context.MoviesWithLocalData.FindAsync([testId]); + await this.context.MoviesWithLocalData.PullAsync(TestContext.Current.CancellationToken); + ClientMovieWithLocalData t2 = await this.context.MoviesWithLocalData.FindAsync([testId], TestContext.Current.CancellationToken); t2.UserRating.Should().Be(5); // Do another change (this time, server side) and push again t2.Title = "New Title"; this.context.Update(t2); - await this.context.SaveChangesAsync(); - await this.context.MoviesWithLocalData.PushAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); + await this.context.MoviesWithLocalData.PushAsync(TestContext.Current.CancellationToken); // Reload the local data from the server and check that the local data is still there - await this.context.Entry(t2).ReloadAsync(); + await this.context.Entry(t2).ReloadAsync(TestContext.Current.CancellationToken); t2.UserRating.Should().Be(5); t2.Title.Should().Be("New Title"); // Pull again and check that the local data is still there. - await this.context.MoviesWithLocalData.PullAsync(); - ClientMovieWithLocalData t3 = await this.context.MoviesWithLocalData.FindAsync([testId]); + await this.context.MoviesWithLocalData.PullAsync(TestContext.Current.CancellationToken); + ClientMovieWithLocalData t3 = await this.context.MoviesWithLocalData.FindAsync([testId], TestContext.Current.CancellationToken); t3.UserRating.Should().Be(5); t3.Title.Should().Be("New Title"); } diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Integration_Push_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Integration_Push_Tests.cs index 4c6ec203..79605332 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Integration_Push_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Integration_Push_Tests.cs @@ -45,7 +45,7 @@ public async Task PushAsync_Complex_Situation() { ResetInMemoryMovies(); - PullResult initialPullResults = await this.context.Movies.PullAsync(); + PullResult initialPullResults = await this.context.Movies.PullAsync(TestContext.Current.CancellationToken); initialPullResults.IsSuccessful.Should().BeTrue(); initialPullResults.Additions.Should().Be(248); initialPullResults.Deletions.Should().Be(0); @@ -54,32 +54,32 @@ public async Task PushAsync_Complex_Situation() // Let's add some new movies ClientMovie blackPanther = new(TestCommon.TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N") }; this.context.Movies.Add(blackPanther); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); // And remove any movie that matches some criteria - List moviesToDelete = await this.context.Movies.Where(x => x.Duration > 180).ToListAsync(); + List moviesToDelete = await this.context.Movies.Where(x => x.Duration > 180).ToListAsync(TestContext.Current.CancellationToken); this.context.Movies.RemoveRange(moviesToDelete); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); // Then replace all the Unrated movies with a rating of NC17 - List moviesToReplace = await this.context.Movies.Where(x => x.Rating == MovieRating.Unrated).ToListAsync(); + List moviesToReplace = await this.context.Movies.Where(x => x.Rating == MovieRating.Unrated).ToListAsync(TestContext.Current.CancellationToken); moviesToReplace.ForEach(r => { r.Rating = MovieRating.NC17; r.Title = r.Title.PadLeft('-'); this.context.Movies.Update(r); }); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); // Check the queue. - List operations = await this.context.DatasyncOperationsQueue.ToListAsync(); + List operations = await this.context.DatasyncOperationsQueue.ToListAsync(TestContext.Current.CancellationToken); operations.Count.Should().Be(1 + moviesToDelete.Count + moviesToReplace.Count); operations.Count(x => x.Kind is OperationKind.Add).Should().Be(1); operations.Count(x => x.Kind is OperationKind.Delete).Should().Be(moviesToDelete.Count); operations.Count(x => x.Kind is OperationKind.Replace).Should().Be(moviesToReplace.Count); // Now push the results and check what we did - PushResult pushResults = await this.context.Movies.PushAsync(); + PushResult pushResults = await this.context.Movies.PushAsync(TestContext.Current.CancellationToken); // This little snippet of code is to aid debugging if this test fails if (!pushResults.IsSuccessful) @@ -104,7 +104,7 @@ public async Task PushAsync_Complex_Situation() this.context.DatasyncOperationsQueue.Should().BeEmpty(); // Now use PullAsync() again - these should all be pulled down again - PullResult pullResults = await this.context.Movies.PullAsync(); + PullResult pullResults = await this.context.Movies.PullAsync(TestContext.Current.CancellationToken); pullResults.IsSuccessful.Should().BeTrue(); pullResults.Additions.Should().Be(0); pullResults.Deletions.Should().Be(0); @@ -117,7 +117,7 @@ public async Task PushAsync_ByteVersion() { ResetInMemoryMovies(); - PullResult initialPullResults = await this.context.ByteMovies.PullAsync(); + PullResult initialPullResults = await this.context.ByteMovies.PullAsync(TestContext.Current.CancellationToken); initialPullResults.IsSuccessful.Should().BeTrue(); initialPullResults.Additions.Should().Be(248); initialPullResults.Deletions.Should().Be(0); @@ -127,32 +127,32 @@ public async Task PushAsync_ByteVersion() // Let's add some new movies ByteVersionMovie blackPanther = new(TestCommon.TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N") }; this.context.ByteMovies.Add(blackPanther); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); // And remove any movie that matches some criteria - List moviesToDelete = await this.context.ByteMovies.Where(x => x.Duration > 180).ToListAsync(); + List moviesToDelete = await this.context.ByteMovies.Where(x => x.Duration > 180).ToListAsync(TestContext.Current.CancellationToken); this.context.ByteMovies.RemoveRange(moviesToDelete); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); // Then replace all the Unrated movies with a rating of NC17 - List moviesToReplace = await this.context.ByteMovies.Where(x => x.Rating == MovieRating.Unrated).ToListAsync(); + List moviesToReplace = await this.context.ByteMovies.Where(x => x.Rating == MovieRating.Unrated).ToListAsync(TestContext.Current.CancellationToken); moviesToReplace.ForEach(r => { r.Rating = MovieRating.NC17; r.Title = r.Title.PadLeft('-'); this.context.ByteMovies.Update(r); }); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); // Check the queue. - List operations = await this.context.DatasyncOperationsQueue.ToListAsync(); + List operations = await this.context.DatasyncOperationsQueue.ToListAsync(TestContext.Current.CancellationToken); operations.Count.Should().Be(1 + moviesToDelete.Count + moviesToReplace.Count); operations.Count(x => x.Kind is OperationKind.Add).Should().Be(1); operations.Count(x => x.Kind is OperationKind.Delete).Should().Be(moviesToDelete.Count); operations.Count(x => x.Kind is OperationKind.Replace).Should().Be(moviesToReplace.Count); // Now push the results and check what we did - PushResult pushResults = await this.context.PushAsync(); + PushResult pushResults = await this.context.PushAsync(TestContext.Current.CancellationToken); // This little snippet of code is to aid debugging if this test fails if (!pushResults.IsSuccessful) @@ -177,7 +177,7 @@ public async Task PushAsync_ByteVersion() this.context.DatasyncOperationsQueue.Should().BeEmpty(); // Now use PullAsync() again - these should all be pulled down again - PullResult pullResults = await this.context.ByteMovies.PullAsync(); + PullResult pullResults = await this.context.ByteMovies.PullAsync(TestContext.Current.CancellationToken); pullResults.IsSuccessful.Should().BeTrue(); pullResults.Additions.Should().Be(0); pullResults.Deletions.Should().Be(0); @@ -190,7 +190,7 @@ public async Task PushAsync_Multithreaded() { ResetInMemoryMovies(); - PullResult initialPullResults = await this.context.Movies.PullAsync(); + PullResult initialPullResults = await this.context.Movies.PullAsync(TestContext.Current.CancellationToken); initialPullResults.IsSuccessful.Should().BeTrue(); initialPullResults.Additions.Should().Be(248); initialPullResults.Deletions.Should().Be(0); @@ -199,32 +199,32 @@ public async Task PushAsync_Multithreaded() // Let's add some new movies ClientMovie blackPanther = new(TestCommon.TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N") }; this.context.Movies.Add(blackPanther); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); // And remove any movie that matches some criteria - List moviesToDelete = await this.context.Movies.Where(x => x.Duration > 180).ToListAsync(); + List moviesToDelete = await this.context.Movies.Where(x => x.Duration > 180).ToListAsync(TestContext.Current.CancellationToken); this.context.Movies.RemoveRange(moviesToDelete); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); // Then replace all the Unrated movies with a rating of NC17 - List moviesToReplace = await this.context.Movies.Where(x => x.Rating == MovieRating.Unrated).ToListAsync(); + List moviesToReplace = await this.context.Movies.Where(x => x.Rating == MovieRating.Unrated).ToListAsync(TestContext.Current.CancellationToken); moviesToReplace.ForEach(r => { r.Rating = MovieRating.NC17; r.Title = r.Title.PadLeft('-'); this.context.Movies.Update(r); }); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); // Check the queue. - List operations = await this.context.DatasyncOperationsQueue.ToListAsync(); + List operations = await this.context.DatasyncOperationsQueue.ToListAsync(TestContext.Current.CancellationToken); operations.Count.Should().Be(1 + moviesToDelete.Count + moviesToReplace.Count); operations.Count(x => x.Kind is OperationKind.Add).Should().Be(1); operations.Count(x => x.Kind is OperationKind.Delete).Should().Be(moviesToDelete.Count); operations.Count(x => x.Kind is OperationKind.Replace).Should().Be(moviesToReplace.Count); // Now push the results and check what we did - PushResult pushResults = await this.context.Movies.PushAsync(new PushOptions { ParallelOperations = 8 }); + PushResult pushResults = await this.context.Movies.PushAsync(new PushOptions { ParallelOperations = 8 }, TestContext.Current.CancellationToken); // This little snippet of code is to aid debugging if this test fails if (!pushResults.IsSuccessful) @@ -249,7 +249,7 @@ public async Task PushAsync_Multithreaded() this.context.DatasyncOperationsQueue.Should().BeEmpty(); // Now use PullAsync() again - these should all be pulled down again - PullResult pullResults = await this.context.Movies.PullAsync(); + PullResult pullResults = await this.context.Movies.PullAsync(TestContext.Current.CancellationToken); pullResults.IsSuccessful.Should().BeTrue(); pullResults.Additions.Should().Be(0); pullResults.Deletions.Should().Be(0); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/OfflineDbContext_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/OfflineDbContext_Tests.cs index 33db3a48..efbae2be 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/OfflineDbContext_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/OfflineDbContext_Tests.cs @@ -55,7 +55,7 @@ public async Task PullAsync_List_Works_InitialSync() this.context.Handler.AddResponse(HttpStatusCode.OK, page3); this.context.Handler.AddResponse(HttpStatusCode.OK, page4); - PullResult pullResult = await this.context.PullAsync([typeof(ClientMovie)], new PullOptions()); + PullResult pullResult = await this.context.PullAsync([typeof(ClientMovie)], new PullOptions(), TestContext.Current.CancellationToken); pullResult.IsSuccessful.Should().BeTrue(); pullResult.Additions.Should().Be(20); @@ -63,7 +63,7 @@ public async Task PullAsync_List_Works_InitialSync() pullResult.Replacements.Should().Be(0); List expected = page1.Items.Concat(page2.Items).Concat(page3.Items).Concat(page4.Items).ToList(); - List actual = await this.context.Movies.ToListAsync(); + List actual = await this.context.Movies.ToListAsync(TestContext.Current.CancellationToken); actual.Should().BeEquivalentTo(expected); @@ -91,7 +91,7 @@ public async Task PullAsync_DbSet_Works_InitialSync() this.context.Handler.AddResponse(HttpStatusCode.OK, page3); this.context.Handler.AddResponse(HttpStatusCode.OK, page4); - PullResult pullResult = await this.context.Movies.PullAsync(); + PullResult pullResult = await this.context.Movies.PullAsync(TestContext.Current.CancellationToken); pullResult.IsSuccessful.Should().BeTrue(); pullResult.Additions.Should().Be(20); @@ -99,7 +99,7 @@ public async Task PullAsync_DbSet_Works_InitialSync() pullResult.Replacements.Should().Be(0); List expected = page1.Items.Concat(page2.Items).Concat(page3.Items).Concat(page4.Items).ToList(); - List actual = await this.context.Movies.ToListAsync(); + List actual = await this.context.Movies.ToListAsync(TestContext.Current.CancellationToken); actual.Should().BeEquivalentTo(expected); @@ -135,7 +135,7 @@ public async Task PullAsync_Configurator_Works_InitialSync_Ver1() options.QueryId = "abc"; options.Query.Where(x => x.Title.StartsWith("abc")); }); - }); + }, TestContext.Current.CancellationToken); pullResult.IsSuccessful.Should().BeTrue(); pullResult.Additions.Should().Be(20); @@ -143,7 +143,7 @@ public async Task PullAsync_Configurator_Works_InitialSync_Ver1() pullResult.Replacements.Should().Be(0); List expected = page1.Items.Concat(page2.Items).Concat(page3.Items).Concat(page4.Items).ToList(); - List actual = await this.context.Movies.ToListAsync(); + List actual = await this.context.Movies.ToListAsync(TestContext.Current.CancellationToken); actual.Should().BeEquivalentTo(expected); @@ -179,7 +179,7 @@ public async Task PullAsync_Configurator_Works_InitialSync_Ver2() options.QueryId = string.Empty; options.Query.Where(x => x.Title.StartsWith("abc")); }); - }); + }, TestContext.Current.CancellationToken); pullResult.IsSuccessful.Should().BeTrue(); pullResult.Additions.Should().Be(20); @@ -187,7 +187,7 @@ public async Task PullAsync_Configurator_Works_InitialSync_Ver2() pullResult.Replacements.Should().Be(0); List expected = page1.Items.Concat(page2.Items).Concat(page3.Items).Concat(page4.Items).ToList(); - List actual = await this.context.Movies.ToListAsync(); + List actual = await this.context.Movies.ToListAsync(TestContext.Current.CancellationToken); actual.Should().BeEquivalentTo(expected); @@ -230,7 +230,7 @@ public async Task PullAsync_Configurator_Works_InitialSync_Ver3() options.QueryId = string.Empty; options.Query.Where(x => x.Title.StartsWith("abc")); }); - }); + }, TestContext.Current.CancellationToken); pullResult.IsSuccessful.Should().BeTrue(); pullResult.Additions.Should().Be(20); @@ -238,7 +238,7 @@ public async Task PullAsync_Configurator_Works_InitialSync_Ver3() pullResult.Replacements.Should().Be(0); List expected = page1.Items.Concat(page2.Items).Concat(page3.Items).Concat(page4.Items).ToList(); - List actual = await this.context.Movies.ToListAsync(); + List actual = await this.context.Movies.ToListAsync(TestContext.Current.CancellationToken); actual.Should().BeEquivalentTo(expected); @@ -269,7 +269,7 @@ public async Task PullAsync_Configurator_Works_InitialSync_Ver4() PullResult pullResult = await this.context.PullAsync(cfg => { cfg.AddPullRequest(); - }); + }, TestContext.Current.CancellationToken); pullResult.IsSuccessful.Should().BeTrue(); pullResult.Additions.Should().Be(20); @@ -277,7 +277,7 @@ public async Task PullAsync_Configurator_Works_InitialSync_Ver4() pullResult.Replacements.Should().Be(0); List expected = page1.Items.Concat(page2.Items).Concat(page3.Items).Concat(page4.Items).ToList(); - List actual = await this.context.Movies.ToListAsync(); + List actual = await this.context.Movies.ToListAsync(TestContext.Current.CancellationToken); actual.Should().BeEquivalentTo(expected); @@ -307,9 +307,9 @@ public async Task PullAsync_List_Works_FollowonSync() DatasyncDeltaToken token = new() { Id = typeof(ClientMovie).FullName!, Value = 1724444574291L }; this.context.DatasyncDeltaTokens.Add(token); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); - PullResult pullResult = await this.context.PullAsync([typeof(ClientMovie)], new PullOptions()); + PullResult pullResult = await this.context.PullAsync([typeof(ClientMovie)], new PullOptions(), TestContext.Current.CancellationToken); pullResult.IsSuccessful.Should().BeTrue(); pullResult.Additions.Should().Be(20); @@ -317,7 +317,7 @@ public async Task PullAsync_List_Works_FollowonSync() pullResult.Replacements.Should().Be(0); List expected = page1.Items.Concat(page2.Items).Concat(page3.Items).Concat(page4.Items).ToList(); - List actual = await this.context.Movies.ToListAsync(); + List actual = await this.context.Movies.ToListAsync(TestContext.Current.CancellationToken); actual.Should().BeEquivalentTo(expected); @@ -348,9 +348,9 @@ public async Task PullAsync_List_Works_DoesntAddDeletions() DatasyncDeltaToken token = new() { Id = typeof(ClientMovie).FullName!, Value = 1724444574291L }; this.context.DatasyncDeltaTokens.Add(token); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); - PullResult pullResult = await this.context.PullAsync([typeof(ClientMovie)], new PullOptions()); + PullResult pullResult = await this.context.PullAsync([typeof(ClientMovie)], new PullOptions(), TestContext.Current.CancellationToken); pullResult.IsSuccessful.Should().BeTrue(); pullResult.Additions.Should().Be(19); @@ -358,7 +358,7 @@ public async Task PullAsync_List_Works_DoesntAddDeletions() pullResult.Replacements.Should().Be(0); List expected = page1.Items.Concat(page2.Items).Concat(page3.Items).Concat(page4.Items).Where(x => !x.Deleted).ToList(); - List actual = await this.context.Movies.ToListAsync(); + List actual = await this.context.Movies.ToListAsync(TestContext.Current.CancellationToken); actual.Should().BeEquivalentTo(expected); @@ -398,7 +398,7 @@ public async Task PullAsync_List_Works_DeletionsAndReplacements() this.context.Handler.AddResponse(HttpStatusCode.OK, page3); this.context.Handler.AddResponse(HttpStatusCode.OK, page4); - PullResult pullResult = await this.context.PullAsync([typeof(ClientMovie)], new PullOptions()); + PullResult pullResult = await this.context.PullAsync([typeof(ClientMovie)], new PullOptions(), TestContext.Current.CancellationToken); pullResult.IsSuccessful.Should().BeTrue(); pullResult.Additions.Should().Be(18); @@ -406,7 +406,7 @@ public async Task PullAsync_List_Works_DeletionsAndReplacements() pullResult.Replacements.Should().Be(1); List expected = page1.Items.Concat(page2.Items).Concat(page3.Items).Concat(page4.Items).Where(x => !x.Deleted).ToList(); - List actual = await this.context.Movies.ToListAsync(); + List actual = await this.context.Movies.ToListAsync(TestContext.Current.CancellationToken); actual.Should().BeEquivalentTo(expected); @@ -422,7 +422,7 @@ public async Task PullAsync_List_FailedRequest() { this.context.Handler.AddResponse(HttpStatusCode.BadRequest); - PullResult pullResult = await this.context.PullAsync([typeof(ClientMovie)], new PullOptions()); + PullResult pullResult = await this.context.PullAsync([typeof(ClientMovie)], new PullOptions(), TestContext.Current.CancellationToken); pullResult.IsSuccessful.Should().BeFalse(); pullResult.FailedRequests.Should().HaveCount(1); @@ -433,7 +433,7 @@ public async Task PullAsync_List_FailedRequest() [Fact] public async Task PullAsync_List_NoRequests() { - PullResult pullResult = await this.context.PullAsync([], new PullOptions()); + PullResult pullResult = await this.context.PullAsync((IEnumerable)[], new PullOptions(), TestContext.Current.CancellationToken); pullResult.IsSuccessful!.Should().BeTrue(); pullResult.OperationCount.Should().Be(0); @@ -495,7 +495,7 @@ public async Task PushAsync_NoSynchronizableEntities(int nItems) List allowedTypes = [typeof(Entity1), typeof(Entity2), typeof(Entity4)]; Type[] entityTypes = allowedTypes.Take(nItems).ToArray(); - PushResult result = await this.context.PushAsync(entityTypes, options); + PushResult result = await this.context.PushAsync(entityTypes, options, TestContext.Current.CancellationToken); result.CompletedOperations.Should().Be(0); result.FailedRequests.Count.Should().Be(0); } @@ -506,7 +506,7 @@ public async Task PushAsync_NoOperations() PushOptions options = new(); Type[] entityTypes = [typeof(ClientMovie)]; - PushResult result = await this.context.PushAsync(entityTypes, options); + PushResult result = await this.context.PushAsync(entityTypes, options, TestContext.Current.CancellationToken); result.CompletedOperations.Should().Be(0); result.FailedRequests.Count.Should().Be(0); } @@ -516,7 +516,7 @@ public async Task DbSet_PushAsync_NoOperations() { PushOptions options = new(); - PushResult result = await this.context.Movies.PushAsync(options); + PushResult result = await this.context.Movies.PushAsync(options, TestContext.Current.CancellationToken); result.CompletedOperations.Should().Be(0); result.FailedRequests.Count.Should().Be(0); } @@ -533,7 +533,7 @@ public async Task PushAsync_Addition_Works() string expectedJson = DatasyncSerializer.Serialize(responseMovie); this.context.Handler.AddResponseContent(expectedJson, HttpStatusCode.Created); - PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeTrue(); results.CompletedOperations.Should().Be(1); results.FailedRequests.Should().BeEmpty(); @@ -557,7 +557,7 @@ public async Task DbSet_PushAsync_Addition_Works() string expectedJson = DatasyncSerializer.Serialize(responseMovie); this.context.Handler.AddResponseContent(expectedJson, HttpStatusCode.Created); - PushResult results = await this.context.Movies.PushAsync(); + PushResult results = await this.context.Movies.PushAsync(TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeTrue(); results.CompletedOperations.Should().Be(1); results.FailedRequests.Should().BeEmpty(); @@ -578,7 +578,7 @@ public async Task PushAsync_Addition_HttpError() this.context.Handler.AddResponse(HttpStatusCode.InternalServerError); - PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeFalse(); results.CompletedOperations.Should().Be(0); results.FailedRequests.Should().HaveCount(1); @@ -603,7 +603,7 @@ public async Task PushAsync_Addition_Conflict() string expectedJson = DatasyncSerializer.Serialize(responseMovie); this.context.Handler.AddResponseContent(expectedJson, HttpStatusCode.Conflict); - PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeFalse(); results.CompletedOperations.Should().Be(0); results.FailedRequests.Should().HaveCount(1); @@ -630,7 +630,7 @@ public async Task PushAsync_Removal_Works() this.context.SaveChanges(); this.context.Handler.AddResponse(HttpStatusCode.NoContent); - PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeTrue(); results.CompletedOperations.Should().Be(1); results.FailedRequests.Should().BeEmpty(); @@ -650,7 +650,7 @@ public async Task DbSet_PushAsync_Removal_Works() this.context.SaveChanges(); this.context.Handler.AddResponse(HttpStatusCode.NoContent); - PushResult results = await this.context.Movies.PushAsync(); + PushResult results = await this.context.Movies.PushAsync(TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeTrue(); results.CompletedOperations.Should().Be(1); results.FailedRequests.Should().BeEmpty(); @@ -670,7 +670,7 @@ public async Task PushAsync_Removal_HttpError() this.context.SaveChanges(); this.context.Handler.AddResponse(HttpStatusCode.InternalServerError); - PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeFalse(); results.CompletedOperations.Should().Be(0); results.FailedRequests.Should().HaveCount(1); @@ -698,7 +698,7 @@ public async Task PushAsync_Removal_Conflict() string expectedJson = DatasyncSerializer.Serialize(responseMovie); this.context.Handler.AddResponseContent(expectedJson, HttpStatusCode.Conflict); - PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeFalse(); results.CompletedOperations.Should().Be(0); results.FailedRequests.Should().HaveCount(1); @@ -729,7 +729,7 @@ public async Task PushAsync_Replacement_Works() string expectedJson = DatasyncSerializer.Serialize(responseMovie); this.context.Handler.AddResponseContent(expectedJson, HttpStatusCode.OK); - PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeTrue(); results.CompletedOperations.Should().Be(1); results.FailedRequests.Should().BeEmpty(); @@ -752,7 +752,7 @@ public async Task DbSet_PushAsync_Replacement_Works() string expectedJson = DatasyncSerializer.Serialize(responseMovie); this.context.Handler.AddResponseContent(expectedJson, HttpStatusCode.OK); - PushResult results = await this.context.Movies.PushAsync(); + PushResult results = await this.context.Movies.PushAsync(TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeTrue(); results.CompletedOperations.Should().Be(1); results.FailedRequests.Should().BeEmpty(); @@ -772,7 +772,7 @@ public async Task PushAsync_Replacement_HttpError() this.context.SaveChanges(); this.context.Handler.AddResponse(HttpStatusCode.InternalServerError); - PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeFalse(); results.CompletedOperations.Should().Be(0); results.FailedRequests.Should().HaveCount(1); @@ -801,7 +801,7 @@ public async Task PushAsync_Replacement_Conflict() string expectedJson = DatasyncSerializer.Serialize(responseMovie); this.context.Handler.AddResponseContent(expectedJson, HttpStatusCode.Conflict); - PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await this.context.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeFalse(); results.CompletedOperations.Should().Be(0); results.FailedRequests.Should().HaveCount(1); @@ -1110,7 +1110,7 @@ public async Task SaveChangesAsync_Addition_AddsToQueue() string serializedEntity = DatasyncSerializer.Serialize(clientMovie); this.context.Movies.Add(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); this.context.Movies.Should().HaveCount(1); this.context.DatasyncOperationsQueue.Should().HaveCount(1); @@ -1136,7 +1136,7 @@ public async Task SaveChangesAsync_TwoAdds_AddsToQueue() this.context.Movies.Add(firstMovie); this.context.Movies.Add(secondMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); this.context.Movies.Should().HaveCount(2); this.context.DatasyncOperationsQueue.Should().HaveCount(2); @@ -1182,10 +1182,10 @@ public async Task SaveChangesAsync_AddThenDelete_NoQueue() { ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N") }; this.context.Movies.Add(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); this.context.Movies.Remove(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); this.context.Movies.Should().HaveCount(0); this.context.DatasyncOperationsQueue.Should().HaveCount(0); @@ -1196,12 +1196,12 @@ public async Task SaveChangesAsync_AddThenReplace_AddsToQueue() { ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N") }; this.context.Movies.Add(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); clientMovie.Title = "Foo"; string serializedEntity = DatasyncSerializer.Serialize(clientMovie); this.context.Movies.Update(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); this.context.Movies.Should().HaveCount(1); this.context.DatasyncOperationsQueue.Should().HaveCount(1); @@ -1222,10 +1222,10 @@ public async Task SaveChangesAsync_Deletion_AddsToQueue() ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N") }; string serializedEntity = DatasyncSerializer.Serialize(clientMovie); this.context.Movies.Add(clientMovie); - await this.context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false); + await this.context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false, TestContext.Current.CancellationToken); this.context.Movies.Remove(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); this.context.Movies.Should().HaveCount(0); this.context.DatasyncOperationsQueue.Should().HaveCount(1); @@ -1246,13 +1246,13 @@ public async Task SaveChangesAsync_DeleteThenAdd_AddsToQueue() ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N") }; string serializedEntity = DatasyncSerializer.Serialize(clientMovie); this.context.Movies.Add(clientMovie); - await this.context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false); + await this.context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false, TestContext.Current.CancellationToken); this.context.Movies.Remove(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); this.context.Movies.Add(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); this.context.Movies.Should().HaveCount(1); this.context.DatasyncOperationsQueue.Should().HaveCount(1); @@ -1288,7 +1288,7 @@ public async Task SaveChangesAsync_DeleteThenDelete_Throws() }; this.context.DatasyncOperationsQueue.Add(badOperation); - await this.context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false); + await this.context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false, TestContext.Current.CancellationToken); Func act = async () => { @@ -1306,12 +1306,12 @@ public async Task SaveChangesAsync_Replacement_AddsToQueue() { ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N") }; this.context.Movies.Add(clientMovie); - await this.context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false); + await this.context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false, TestContext.Current.CancellationToken); clientMovie.Title = "Replaced Title"; string serializedEntity = DatasyncSerializer.Serialize(clientMovie); this.context.Movies.Update(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); this.context.Movies.Should().HaveCount(1); this.context.DatasyncOperationsQueue.Should().HaveCount(1); @@ -1331,15 +1331,15 @@ public async Task SaveChangesAsync_ReplaceThenDelete_AddsToQueue() { ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N") }; this.context.Movies.Add(clientMovie); - await this.context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false); + await this.context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false, TestContext.Current.CancellationToken); clientMovie.Title = "Replaced Title"; string serializedEntity = DatasyncSerializer.Serialize(clientMovie); this.context.Movies.Update(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); this.context.Movies.Remove(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); this.context.Movies.Should().HaveCount(0); this.context.DatasyncOperationsQueue.Should().HaveCount(1); @@ -1359,16 +1359,16 @@ public async Task SaveChangesAsync_ReplaceThenReplace_AddsToQueue() { ClientMovie clientMovie = new(TestData.Movies.BlackPanther) { Id = Guid.NewGuid().ToString("N") }; this.context.Movies.Add(clientMovie); - await this.context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false); + await this.context.SaveChangesAsync(acceptAllChangesOnSuccess: true, addToQueue: false, TestContext.Current.CancellationToken); clientMovie.Title = "Replaced Title"; this.context.Movies.Update(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); clientMovie.Title = "Foo"; string serializedEntity = DatasyncSerializer.Serialize(clientMovie); this.context.Movies.Update(clientMovie); - await this.context.SaveChangesAsync(); + await this.context.SaveChangesAsync(TestContext.Current.CancellationToken); this.context.Movies.Should().HaveCount(1); this.context.DatasyncOperationsQueue.Should().HaveCount(1); @@ -1492,7 +1492,7 @@ public async Task SynchronizationProgress_Event_Works() } }; - await this.context.Movies.PullAsync(); + await this.context.Movies.PullAsync(TestContext.Current.CancellationToken); eventFiredForStart.Should().BeTrue(); eventFiredForFetch.Should().BeTrue(); @@ -1537,7 +1537,7 @@ public async Task PullAsync_List_FailedRequest_SynchronizationEventWorks() } }; - PullResult pullResult = await this.context.PullAsync([typeof(ClientMovie)], new PullOptions()); + PullResult pullResult = await this.context.PullAsync([typeof(ClientMovie)], new PullOptions(), TestContext.Current.CancellationToken); eventFiredForStart.Should().BeTrue(); eventFiredForEnd.Should().BeTrue(); @@ -1601,7 +1601,7 @@ public async Task SynchronizationProgress_Event_Works_For_Push() } }; - PushResult results = await this.context.Movies.PushAsync(); + PushResult results = await this.context.Movies.PushAsync(TestContext.Current.CancellationToken); eventFiredForStart.Should().BeTrue(); eventFiredForItem.Should().BeTrue(); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/AddOperation_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/AddOperation_Tests.cs index ba125de6..ce4c02ea 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/AddOperation_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/AddOperation_Tests.cs @@ -47,14 +47,14 @@ public async Task AddOperation_ExecuteAsync() Endpoint = new Uri("/tables/movies", UriKind.Relative), QueryDescription = new() }; - ExecutableOperation operation = await ExecutableOperation.CreateAsync(op); - ServiceResponse response = await operation.ExecuteAsync(options); + ExecutableOperation operation = await ExecutableOperation.CreateAsync(op, TestContext.Current.CancellationToken); + ServiceResponse response = await operation.ExecuteAsync(options, TestContext.Current.CancellationToken); HttpRequestMessage request = handler.Requests.SingleOrDefault(); request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Post); request.RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies"); - (await request.Content.ReadAsStringAsync()).Should().Be(itemJson); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(itemJson); response.Should().NotBeNull(); response.HasContent.Should().BeTrue(); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/DeleteOperation_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/DeleteOperation_Tests.cs index 255b4655..9bcefc52 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/DeleteOperation_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/DeleteOperation_Tests.cs @@ -45,8 +45,8 @@ public async Task DeleteOperation_ExecuteAsync() Endpoint = new Uri("/tables/movies", UriKind.Relative), QueryDescription = new() }; - ExecutableOperation operation = await ExecutableOperation.CreateAsync(op); - ServiceResponse response = await operation.ExecuteAsync(options); + ExecutableOperation operation = await ExecutableOperation.CreateAsync(op, TestContext.Current.CancellationToken); + ServiceResponse response = await operation.ExecuteAsync(options, TestContext.Current.CancellationToken); HttpRequestMessage request = handler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -91,8 +91,8 @@ public async Task DeleteOperation_ExecuteAsync_WithVersion() Endpoint = new Uri("/tables/movies", UriKind.Relative), QueryDescription = new() }; - ExecutableOperation operation = await ExecutableOperation.CreateAsync(op); - ServiceResponse response = await operation.ExecuteAsync(options); + ExecutableOperation operation = await ExecutableOperation.CreateAsync(op, TestContext.Current.CancellationToken); + ServiceResponse response = await operation.ExecuteAsync(options, TestContext.Current.CancellationToken); HttpRequestMessage request = handler.Requests.SingleOrDefault(); request.Should().NotBeNull(); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/PullOperationManager_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/PullOperationManager_Tests.cs index 7fd0b1e3..e8198620 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/PullOperationManager_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/PullOperationManager_Tests.cs @@ -78,7 +78,7 @@ public async Task GetPageAsync_Success_NoNextLink() Page page = CreatePage(5); handler.AddResponse(HttpStatusCode.OK, page); - Page actual = await operationManager.GetPageAsync(client, new Uri("http://localhost/tables/kitchensink"), typeof(Page)); + Page actual = await operationManager.GetPageAsync(client, new Uri("http://localhost/tables/kitchensink"), typeof(Page), TestContext.Current.CancellationToken); HttpRequestMessage request = handler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -97,7 +97,7 @@ public async Task GetPageAsync_Success_WithNextLink() Page page = CreatePage(5, null, "$filter=booleanValue&$skip=5"); handler.AddResponse(HttpStatusCode.OK, page); - Page actual = await operationManager.GetPageAsync(client, new Uri("http://localhost/tables/kitchensink"), typeof(Page)); + Page actual = await operationManager.GetPageAsync(client, new Uri("http://localhost/tables/kitchensink"), typeof(Page), TestContext.Current.CancellationToken); HttpRequestMessage request = handler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -170,7 +170,7 @@ public async Task GetPageAsync_NoItems() handler.AddResponseContent("""{"nextLink":"abc"}""", HttpStatusCode.OK); Uri requestUri = new("http://localhost/tables/movies"); - Page result = await operationManager.GetPageAsync(client, requestUri, typeof(Page)); + Page result = await operationManager.GetPageAsync(client, requestUri, typeof(Page), TestContext.Current.CancellationToken); result.Should().NotBeNull(); result.Items.Should().BeEmpty(); result.NextLink.Should().Be("abc"); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/ReplaceOperation_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/ReplaceOperation_Tests.cs index ad570726..17c6814c 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/ReplaceOperation_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/Operations/ReplaceOperation_Tests.cs @@ -47,15 +47,15 @@ public async Task ReplaceOperation_ExecuteAsync() Endpoint = new Uri("/tables/movies", UriKind.Relative), QueryDescription = new() }; - ExecutableOperation operation = await ExecutableOperation.CreateAsync(op); - ServiceResponse response = await operation.ExecuteAsync(options); + ExecutableOperation operation = await ExecutableOperation.CreateAsync(op, TestContext.Current.CancellationToken); + ServiceResponse response = await operation.ExecuteAsync(options, TestContext.Current.CancellationToken); HttpRequestMessage request = handler.Requests.SingleOrDefault(); request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Put); request.RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies/123"); request.Headers.Should().NotContain(x => x.Key == "If-Match"); - (await request.Content.ReadAsStringAsync()).Should().Be(itemJson); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(itemJson); response.Should().NotBeNull(); response.HasContent.Should().BeTrue(); @@ -97,15 +97,15 @@ public async Task ReplaceOperation_ExecuteAsync_WithVersion() Endpoint = new Uri("/tables/movies", UriKind.Relative), QueryDescription = new() }; - ExecutableOperation operation = await ExecutableOperation.CreateAsync(op); - ServiceResponse response = await operation.ExecuteAsync(options); + ExecutableOperation operation = await ExecutableOperation.CreateAsync(op, TestContext.Current.CancellationToken); + ServiceResponse response = await operation.ExecuteAsync(options, TestContext.Current.CancellationToken); HttpRequestMessage request = handler.Requests.SingleOrDefault(); request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Put); request.RequestUri.ToString().Should().Be("https://test.zumo.net/tables/movies/123"); request.Headers.Should().Contain(x => x.Key == "If-Match" && x.Value.First() == "\"abcdefg\""); - (await request.Content.ReadAsStringAsync()).Should().Be(itemJson); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(itemJson); response.Should().NotBeNull(); response.HasContent.Should().BeTrue(); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Offline/OperationsQueueManager_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Offline/OperationsQueueManager_Tests.cs index c96a053d..e6ba4f1a 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Offline/OperationsQueueManager_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Offline/OperationsQueueManager_Tests.cs @@ -107,7 +107,7 @@ public async Task PushAsync_NoSynchronizableEntities(int nItems) List allowedTypes = [typeof(Entity1), typeof(Entity2), typeof(Entity4)]; Type[] entityTypes = allowedTypes.Take(nItems).ToArray(); - PushResult result = await queueManager.PushAsync(entityTypes, options); + PushResult result = await queueManager.PushAsync(entityTypes, options, TestContext.Current.CancellationToken); result.CompletedOperations.Should().Be(0); result.FailedRequests.Count.Should().Be(0); } @@ -118,7 +118,7 @@ public async Task PushAsync_NoOperations() PushOptions options = new(); Type[] entityTypes = [typeof(ClientMovie)]; - PushResult result = await queueManager.PushAsync(entityTypes, options); + PushResult result = await queueManager.PushAsync(entityTypes, options, TestContext.Current.CancellationToken); result.CompletedOperations.Should().Be(0); result.FailedRequests.Count.Should().Be(0); } @@ -135,7 +135,7 @@ public async Task PushAsync_Addition_Works() string expectedJson = DatasyncSerializer.Serialize(responseMovie); this.context.Handler.AddResponseContent(expectedJson, HttpStatusCode.Created); - PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeTrue(); results.CompletedOperations.Should().Be(1); results.FailedRequests.Should().BeEmpty(); @@ -156,7 +156,7 @@ public async Task PushAsync_Addition_HttpError() this.context.Handler.AddResponse(HttpStatusCode.InternalServerError); - PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeFalse(); results.CompletedOperations.Should().Be(0); results.FailedRequests.Should().HaveCount(1); @@ -181,7 +181,7 @@ public async Task PushAsync_Addition_Conflict() string expectedJson = DatasyncSerializer.Serialize(responseMovie); this.context.Handler.AddResponseContent(expectedJson, HttpStatusCode.Conflict); - PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeFalse(); results.CompletedOperations.Should().Be(0); results.FailedRequests.Should().HaveCount(1); @@ -208,7 +208,7 @@ public async Task PushAsync_Removal_Works() this.context.SaveChanges(); this.context.Handler.AddResponse(HttpStatusCode.NoContent); - PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeTrue(); results.CompletedOperations.Should().Be(1); results.FailedRequests.Should().BeEmpty(); @@ -228,7 +228,7 @@ public async Task PushAsync_Removal_HttpError() this.context.SaveChanges(); this.context.Handler.AddResponse(HttpStatusCode.InternalServerError); - PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeFalse(); results.CompletedOperations.Should().Be(0); results.FailedRequests.Should().HaveCount(1); @@ -256,7 +256,7 @@ public async Task PushAsync_Removal_Conflict() string expectedJson = DatasyncSerializer.Serialize(responseMovie); this.context.Handler.AddResponseContent(expectedJson, HttpStatusCode.Conflict); - PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeFalse(); results.CompletedOperations.Should().Be(0); results.FailedRequests.Should().HaveCount(1); @@ -287,7 +287,7 @@ public async Task PushAsync_Replacement_Works() string expectedJson = DatasyncSerializer.Serialize(responseMovie); this.context.Handler.AddResponseContent(expectedJson, HttpStatusCode.OK); - PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeTrue(); results.CompletedOperations.Should().Be(1); results.FailedRequests.Should().BeEmpty(); @@ -307,7 +307,7 @@ public async Task PushAsync_Replacement_HttpError() this.context.SaveChanges(); this.context.Handler.AddResponse(HttpStatusCode.InternalServerError); - PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeFalse(); results.CompletedOperations.Should().Be(0); results.FailedRequests.Should().HaveCount(1); @@ -336,7 +336,7 @@ public async Task PushAsync_Replacement_Conflict() string expectedJson = DatasyncSerializer.Serialize(responseMovie); this.context.Handler.AddResponseContent(expectedJson, HttpStatusCode.Conflict); - PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await queueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeFalse(); results.CompletedOperations.Should().Be(0); results.FailedRequests.Should().HaveCount(1); @@ -427,7 +427,7 @@ public async Task LLP_PushAsync_Addition_Works() string expectedJson = DatasyncSerializer.Serialize(responseMovie); llpContext.Handler.AddResponseContent(expectedJson, HttpStatusCode.Created); - PushResult results = await llpContext.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await llpContext.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeTrue(); results.CompletedOperations.Should().Be(1); results.FailedRequests.Should().BeEmpty(); @@ -451,7 +451,7 @@ public async Task LLP_PushAsync_Removal_Works() llpContext.SaveChanges(); llpContext.Handler.AddResponse(HttpStatusCode.NoContent); - PushResult results = await llpContext.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await llpContext.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeTrue(); results.CompletedOperations.Should().Be(1); results.FailedRequests.Should().BeEmpty(); @@ -476,7 +476,7 @@ public async Task LLP_PushAsync_Replacement_Works() string expectedJson = DatasyncSerializer.Serialize(responseMovie); llpContext.Handler.AddResponseContent(expectedJson, HttpStatusCode.OK); - PushResult results = await llpContext.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions()); + PushResult results = await llpContext.QueueManager.PushAsync([typeof(ClientMovie)], new PushOptions(), TestContext.Current.CancellationToken); results.IsSuccessful.Should().BeTrue(); results.CompletedOperations.Should().Be(1); results.FailedRequests.Should().BeEmpty(); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Service/DatasyncServiceClient_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Service/DatasyncServiceClient_Tests.cs index 354b2faf..e333df6d 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Service/DatasyncServiceClient_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Service/DatasyncServiceClient_Tests.cs @@ -216,13 +216,13 @@ public async Task AddAsync_Success() ClientKitchenSink entity = new() { Id = "1", StringValue = "abc" }; string expected = JsonSerializer.Serialize(entity, DatasyncSerializer.JsonSerializerOptions); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.AddAsync(entity, new DatasyncServiceOptions()); + ServiceResponse response = await client.AddAsync(entity, new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Post); request.RequestUri.ToString().Should().Be("http://localhost/tables/kitchensink/"); - (await request.Content.ReadAsStringAsync()).Should().Be(expected); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(expected); response.Should().NotBeNull(); response.HasContent.Should().BeTrue(); @@ -241,13 +241,13 @@ public async Task AddAsync_Success_Extn() ClientKitchenSink entity = new() { Id = "1", StringValue = "abc" }; string expected = JsonSerializer.Serialize(entity, DatasyncSerializer.JsonSerializerOptions); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.AddAsync(entity); + ServiceResponse response = await client.AddAsync(entity, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Post); request.RequestUri.ToString().Should().Be("http://localhost/tables/kitchensink/"); - (await request.Content.ReadAsStringAsync()).Should().Be(expected); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(expected); response.Should().NotBeNull(); response.HasContent.Should().BeTrue(); @@ -276,7 +276,7 @@ public async Task AddAsync_Conflict(HttpStatusCode code) request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Post); request.RequestUri.ToString().Should().Be("http://localhost/tables/kitchensink/"); - (await request.Content.ReadAsStringAsync()).Should().Be(expected); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(expected); ex.ClientEntity.Should().BeEquivalentTo(entity, this.entityEquivalentOptions); ex.ServerEntity.Should().BeEquivalentTo(this.successfulKitchenSink, this.entityEquivalentOptions); @@ -354,7 +354,7 @@ public async Task CountAsync_Success_NoQuery() { _ = CreatePage(0, 42L); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.CountAsync(client.AsQueryable(), new DatasyncServiceOptions()); + ServiceResponse response = await client.CountAsync(client.AsQueryable(), new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -377,7 +377,7 @@ public async Task CountAsync_Success_WithQuery() _ = CreatePage(0, 42L); DatasyncServiceClient client = GetMockClient(); IDatasyncQueryable query = client.Where(x => x.StringValue == "abc"); - ServiceResponse response = await client.CountAsync(query, new DatasyncServiceOptions()); + ServiceResponse response = await client.CountAsync(query, new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -399,7 +399,7 @@ public async Task CountAsync_Success_WithQuery_QueryExtn() { _ = CreatePage(0, 42L); DatasyncServiceClient client = GetMockClient(); - int response = await client.Where(x => x.StringValue == "abc").CountAsync(); + int response = await client.Where(x => x.StringValue == "abc").CountAsync(TestContext.Current.CancellationToken); response.Should().Be(42); } @@ -409,7 +409,7 @@ public async Task CountAsync_Success_WithQuery_Extension() _ = CreatePage(0, 42L); DatasyncServiceClient client = GetMockClient(); IDatasyncQueryable query = client.Where(x => x.StringValue == "abc"); - ServiceResponse response = await client.CountAsync(query); + ServiceResponse response = await client.CountAsync(query, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -431,7 +431,7 @@ public async Task CountAsync_Success_NoQuery_Extension() { _ = CreatePage(0, 42L); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.CountAsync(); + ServiceResponse response = await client.CountAsync(TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -454,7 +454,7 @@ public async Task CountAsync_Success_SkipTopSelect() _ = CreatePage(0, 42L); DatasyncServiceClient client = GetMockClient(); IDatasyncQueryable query = client.Where(x => x.StringValue == "abc").Skip(10).Take(5).Select(n => new NamedSelectClass { Id = n.Id, StringValue = n.StringValue }); - ServiceResponse response = await query.ServiceClient.CountAsync(query, new DatasyncServiceOptions()); + ServiceResponse response = await query.ServiceClient.CountAsync(query, new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -541,7 +541,7 @@ public async Task GetAsync_Success() this.mockHandler.Responses.Add(GetSuccessfulResponse(this.successfulKitchenSink, HttpStatusCode.OK)); string id = Guid.NewGuid().ToString("N"); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.GetAsync(id, new DatasyncServiceOptions()); + ServiceResponse response = await client.GetAsync(id, new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -564,7 +564,7 @@ public async Task GetAsync_Success_Extn() this.mockHandler.Responses.Add(GetSuccessfulResponse(this.successfulKitchenSink, HttpStatusCode.OK)); string id = Guid.NewGuid().ToString("N"); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.GetAsync(id); + ServiceResponse response = await client.GetAsync(id, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -588,7 +588,7 @@ public async Task GetAsync_Success_IncludeDeleted() string id = Guid.NewGuid().ToString("N"); DatasyncServiceClient client = GetMockClient(); DatasyncServiceOptions options = new() { IncludeDeleted = true }; - ServiceResponse response = await client.GetAsync(id, options); + ServiceResponse response = await client.GetAsync(id, options, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -639,7 +639,7 @@ public async Task GetAsync_Missing_DontThrow() string id = Guid.NewGuid().ToString("N"); DatasyncServiceOptions options = new() { ThrowIfMissing = false }; DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.GetAsync(id, options); + ServiceResponse response = await client.GetAsync(id, options, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -700,7 +700,7 @@ public async Task GetPageAsync_Success_ItemsOnly(string query) string expectedUri = string.IsNullOrEmpty(query) ? "http://localhost/tables/kitchensink/" : $"http://localhost/tables/kitchensink/?{query}"; Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - ServiceResponse> response = await client.GetPageAsync(query, new DatasyncServiceOptions()); + ServiceResponse> response = await client.GetPageAsync(query, new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -731,7 +731,7 @@ public async Task GetPageAsync_Success_Items_TotalCount(string query) string expectedUri = string.IsNullOrEmpty(query) ? "http://localhost/tables/kitchensink/" : $"http://localhost/tables/kitchensink/?{query}"; Page page = CreatePage(5, 20L); DatasyncServiceClient client = GetMockClient(); - ServiceResponse> response = await client.GetPageAsync(query, new DatasyncServiceOptions()); + ServiceResponse> response = await client.GetPageAsync(query, new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -762,7 +762,7 @@ public async Task GetPageAsync_Success_Items_NextLink(string query) string expectedUri = string.IsNullOrEmpty(query) ? "http://localhost/tables/kitchensink/" : $"http://localhost/tables/kitchensink/?{query}"; Page page = CreatePage(5, null, "$filter=booleanValue&$skip=5"); DatasyncServiceClient client = GetMockClient(); - ServiceResponse> response = await client.GetPageAsync(query, new DatasyncServiceOptions()); + ServiceResponse> response = await client.GetPageAsync(query, new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -894,7 +894,7 @@ public async Task LongCountAsync_Success_NoQuery() { _ = CreatePage(0, 42L); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.LongCountAsync(client.AsQueryable(), new DatasyncServiceOptions()); + ServiceResponse response = await client.LongCountAsync(client.AsQueryable(), new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -917,7 +917,7 @@ public async Task LongCountAsync_Success_WithQuery() _ = CreatePage(0, 42L); DatasyncServiceClient client = GetMockClient(); IDatasyncQueryable query = client.Where(x => x.StringValue == "abc"); - ServiceResponse response = await client.LongCountAsync(query, new DatasyncServiceOptions()); + ServiceResponse response = await client.LongCountAsync(query, new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -939,7 +939,7 @@ public async Task LongCountAsync_Success_WithQuery_QueryExtn() { _ = CreatePage(0, 42L); DatasyncServiceClient client = GetMockClient(); - long response = await client.Where(x => x.StringValue == "abc").LongCountAsync(); + long response = await client.Where(x => x.StringValue == "abc").LongCountAsync(TestContext.Current.CancellationToken); response.Should().Be(42); } @@ -949,7 +949,7 @@ public async Task LongCountAsync_Success_WithQuery_Extn() _ = CreatePage(0, 42L); DatasyncServiceClient client = GetMockClient(); IDatasyncQueryable query = client.Where(x => x.StringValue == "abc"); - ServiceResponse response = await client.LongCountAsync(query); + ServiceResponse response = await client.LongCountAsync(query, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -971,7 +971,7 @@ public async Task LongCountAsync_Success_NoQuery_Extn() { _ = CreatePage(0, 42L); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.LongCountAsync(); + ServiceResponse response = await client.LongCountAsync(TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -994,7 +994,7 @@ public async Task LongCountAsync_Success_SkipTopSelect() _ = CreatePage(0, 42L); DatasyncServiceClient client = GetMockClient(); IDatasyncQueryable query = client.Where(x => x.StringValue == "abc").Skip(10).Take(5).Select(n => new NamedSelectClass { Id = n.Id, StringValue = n.StringValue }); - ServiceResponse response = await query.ServiceClient.LongCountAsync(query, new DatasyncServiceOptions()); + ServiceResponse response = await query.ServiceClient.LongCountAsync(query, new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -1163,7 +1163,7 @@ public async Task Query_ServiceError(HttpStatusCode code) this.mockHandler.AddResponse(code); DatasyncServiceClient client = GetMockClient(); IAsyncPageable sut = client.Query(client.AsQueryable()); - IAsyncEnumerator enumerator = sut.GetAsyncEnumerator(); + IAsyncEnumerator enumerator = sut.GetAsyncEnumerator(TestContext.Current.CancellationToken); Func act = async () => _ = await enumerator.MoveNextAsync(); (await act.Should().ThrowAsync()).Which.ServiceResponse.StatusCode.Should().Be((int)code); } @@ -1174,7 +1174,7 @@ public async Task Query_NoItems() this.mockHandler.AddResponse(HttpStatusCode.OK, new Page()); DatasyncServiceClient client = GetMockClient(); IAsyncPageable sut = client.Query(client.AsQueryable()); - IAsyncEnumerator enumerator = sut.GetAsyncEnumerator(); + IAsyncEnumerator enumerator = sut.GetAsyncEnumerator(TestContext.Current.CancellationToken); bool hasMore = await enumerator.MoveNextAsync(); hasMore.Should().BeFalse(); @@ -1190,7 +1190,7 @@ public async Task Query_OnePageOfItems() Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); IAsyncPageable sut = client.Query(client.AsQueryable()); - List actualItems = await sut.ToListAsync(); + List actualItems = await sut.ToListAsync(TestContext.Current.CancellationToken); actualItems.Should().BeEquivalentTo(page.Items); @@ -1209,7 +1209,7 @@ public async Task Query_TwoPagesOfItems() DatasyncServiceClient client = GetMockClient(); IAsyncPageable sut = client.Query(client.AsQueryable()); - List actualItems = await sut.ToListAsync(); + List actualItems = await sut.ToListAsync(TestContext.Current.CancellationToken); actualItems.Should().HaveCount(10); actualItems.Take(5).Should().BeEquivalentTo(page1.Items); @@ -1237,7 +1237,7 @@ public async Task Query_ThreePagesOfItems() DatasyncServiceClient client = GetMockClient(); IAsyncPageable sut = client.Query(client.AsQueryable()); - List actualItems = await sut.ToListAsync(); + List actualItems = await sut.ToListAsync(TestContext.Current.CancellationToken); actualItems.Should().HaveCount(15); actualItems.Take(5).Should().BeEquivalentTo(page1.Items); @@ -1267,7 +1267,7 @@ public async Task Query_SetsCount() _ = CreatePage(5, 42); DatasyncServiceClient client = GetMockClient(); IAsyncPageable sut = client.Query(client.AsQueryable()); - IAsyncEnumerator enumerator = sut.GetAsyncEnumerator(); + IAsyncEnumerator enumerator = sut.GetAsyncEnumerator(TestContext.Current.CancellationToken); _ = await enumerator.MoveNextAsync(); sut.Count.Should().Be(42); } @@ -1279,7 +1279,7 @@ public async Task Query_RequestsSimpleFilter() DatasyncServiceClient client = GetMockClient(); IDatasyncQueryable query = client.Where(x => x.StringValue == "abc"); IAsyncPageable sut = client.Query(query); - IAsyncEnumerator enumerator = sut.GetAsyncEnumerator(); + IAsyncEnumerator enumerator = sut.GetAsyncEnumerator(TestContext.Current.CancellationToken); _ = await enumerator.MoveNextAsync(); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); @@ -1295,7 +1295,7 @@ public async Task Query_RequestsComplexFilter() DatasyncServiceClient client = GetMockClient(); IDatasyncQueryable query = client.Where(x => x.StringValue == "abc").Skip(5).Take(100).OrderBy(x => x.GuidValue).ThenByDescending(x => x.IntValue); IAsyncPageable sut = client.Query(query); - IAsyncEnumerator enumerator = sut.GetAsyncEnumerator(); + IAsyncEnumerator enumerator = sut.GetAsyncEnumerator(TestContext.Current.CancellationToken); _ = await enumerator.MoveNextAsync(); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); @@ -1386,7 +1386,7 @@ public async Task RemoveAsync_Success() this.mockHandler.AddResponse(HttpStatusCode.NoContent); string id = Guid.NewGuid().ToString("N"); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.RemoveAsync(id, new DatasyncServiceOptions()); + ServiceResponse response = await client.RemoveAsync(id, new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -1407,7 +1407,7 @@ public async Task RemoveAsync_Extn_Success() this.mockHandler.AddResponse(HttpStatusCode.NoContent); ClientKitchenSink entity = new() { Id = Guid.NewGuid().ToString("N") }; DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.RemoveAsync(entity, true); + ServiceResponse response = await client.RemoveAsync(entity, true, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -1429,7 +1429,7 @@ public async Task RemoveAsync_SetsVersion() string id = Guid.NewGuid().ToString("N"); DatasyncServiceOptions options = new() { Version = "abcdefg1234" }; DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.RemoveAsync(id, options); + ServiceResponse response = await client.RemoveAsync(id, options, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -1451,7 +1451,7 @@ public async Task RemoveAsync_Extn_Unforced_SetsVersion() this.mockHandler.AddResponse(HttpStatusCode.NoContent); ClientKitchenSink entity = new() { Id = Guid.NewGuid().ToString("N"), Version = "abcdefg1234" }; DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.RemoveAsync(entity, false); + ServiceResponse response = await client.RemoveAsync(entity, false, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -1473,7 +1473,7 @@ public async Task RemoveAsync_Extn2_SetsVersion() this.mockHandler.AddResponse(HttpStatusCode.NoContent); ClientKitchenSink entity = new() { Id = Guid.NewGuid().ToString("N"), Version = "abcdefg1234" }; DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.RemoveAsync(entity); + ServiceResponse response = await client.RemoveAsync(entity, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -1495,7 +1495,7 @@ public async Task RemoveAsync_Extn_Forced_SetsVersion() this.mockHandler.AddResponse(HttpStatusCode.NoContent); ClientKitchenSink entity = new() { Id = Guid.NewGuid().ToString("N"), Version = "abcdefg1234" }; DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.RemoveAsync(entity, true); + ServiceResponse response = await client.RemoveAsync(entity, true, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -1561,7 +1561,7 @@ public async Task RemoveAsync_Missing_DontThrow() string id = Guid.NewGuid().ToString("N"); DatasyncServiceOptions options = new() { ThrowIfMissing = false }; DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.RemoveAsync(id, options); + ServiceResponse response = await client.RemoveAsync(id, options, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -1662,13 +1662,13 @@ public async Task ReplaceAsync_Success() ClientKitchenSink entity = new() { Id = "1", StringValue = "abc" }; string expected = JsonSerializer.Serialize(entity, DatasyncSerializer.JsonSerializerOptions); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.ReplaceAsync(entity, new DatasyncServiceOptions()); + ServiceResponse response = await client.ReplaceAsync(entity, new DatasyncServiceOptions(), TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Put); request.RequestUri.ToString().Should().Be($"http://localhost/tables/kitchensink/{entity.Id}"); - (await request.Content.ReadAsStringAsync()).Should().Be(expected); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(expected); response.Should().NotBeNull(); response.HasContent.Should().BeTrue(); @@ -1687,13 +1687,13 @@ public async Task ReplaceAsync_Extn_Forced_Success() ClientKitchenSink entity = new() { Id = "1", StringValue = "abc" }; string expected = JsonSerializer.Serialize(entity, DatasyncSerializer.JsonSerializerOptions); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.ReplaceAsync(entity, true); + ServiceResponse response = await client.ReplaceAsync(entity, true, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Put); request.RequestUri.ToString().Should().Be($"http://localhost/tables/kitchensink/{entity.Id}"); - (await request.Content.ReadAsStringAsync()).Should().Be(expected); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(expected); response.Should().NotBeNull(); response.HasContent.Should().BeTrue(); @@ -1712,13 +1712,13 @@ public async Task ReplaceAsync_Extn_Default_Success() ClientKitchenSink entity = new() { Id = "1", StringValue = "abc" }; string expected = JsonSerializer.Serialize(entity, DatasyncSerializer.JsonSerializerOptions); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.ReplaceAsync(entity); + ServiceResponse response = await client.ReplaceAsync(entity, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Put); request.RequestUri.ToString().Should().Be($"http://localhost/tables/kitchensink/{entity.Id}"); - (await request.Content.ReadAsStringAsync()).Should().Be(expected); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(expected); response.Should().NotBeNull(); response.HasContent.Should().BeTrue(); @@ -1738,14 +1738,14 @@ public async Task ReplaceAsync_SetsVersion() string expected = JsonSerializer.Serialize(entity, DatasyncSerializer.JsonSerializerOptions); DatasyncServiceOptions options = new() { Version = "abcdefg1234" }; DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.ReplaceAsync(entity, options); + ServiceResponse response = await client.ReplaceAsync(entity, options, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Put); request.RequestUri.ToString().Should().Be($"http://localhost/tables/kitchensink/{entity.Id}"); request.Headers.Should().Contain(x => x.Key == "If-Match" && x.Value.First() == "\"abcdefg1234\""); - (await request.Content.ReadAsStringAsync()).Should().Be(expected); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(expected); response.Should().NotBeNull(); response.HasContent.Should().BeTrue(); @@ -1764,14 +1764,14 @@ public async Task ReplaceAsync_Extn_Forced_SetsVersion() ClientKitchenSink entity = new() { Id = "1", Version = "abcdefg1234", StringValue = "abc" }; string expected = JsonSerializer.Serialize(entity, DatasyncSerializer.JsonSerializerOptions); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.ReplaceAsync(entity, true); + ServiceResponse response = await client.ReplaceAsync(entity, true, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Put); request.RequestUri.ToString().Should().Be($"http://localhost/tables/kitchensink/{entity.Id}"); request.Headers.Should().NotContain(x => x.Key == "If-Match"); - (await request.Content.ReadAsStringAsync()).Should().Be(expected); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(expected); response.Should().NotBeNull(); response.HasContent.Should().BeTrue(); @@ -1790,14 +1790,14 @@ public async Task ReplaceAsync_Extn_Unforced_SetsVersion() ClientKitchenSink entity = new() { Id = "1", Version = "abcdefg1234", StringValue = "abc" }; string expected = JsonSerializer.Serialize(entity, DatasyncSerializer.JsonSerializerOptions); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.ReplaceAsync(entity, false); + ServiceResponse response = await client.ReplaceAsync(entity, false, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Put); request.RequestUri.ToString().Should().Be($"http://localhost/tables/kitchensink/{entity.Id}"); request.Headers.Should().Contain(x => x.Key == "If-Match" && x.Value.First() == "\"abcdefg1234\""); - (await request.Content.ReadAsStringAsync()).Should().Be(expected); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(expected); response.Should().NotBeNull(); response.HasContent.Should().BeTrue(); @@ -1816,14 +1816,14 @@ public async Task ReplaceAsync_Extn_Default_SetsVersion() ClientKitchenSink entity = new() { Id = "1", Version = "abcdefg1234", StringValue = "abc" }; string expected = JsonSerializer.Serialize(entity, DatasyncSerializer.JsonSerializerOptions); DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.ReplaceAsync(entity); + ServiceResponse response = await client.ReplaceAsync(entity, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Put); request.RequestUri.ToString().Should().Be($"http://localhost/tables/kitchensink/{entity.Id}"); request.Headers.Should().Contain(x => x.Key == "If-Match" && x.Value.First() == "\"abcdefg1234\""); - (await request.Content.ReadAsStringAsync()).Should().Be(expected); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(expected); response.Should().NotBeNull(); response.HasContent.Should().BeTrue(); @@ -1852,7 +1852,7 @@ public async Task ReplaceAsync_Conflict(HttpStatusCode code) request.Should().NotBeNull(); request.Method.Should().Be(HttpMethod.Put); request.RequestUri.ToString().Should().Be($"http://localhost/tables/kitchensink/{entity.Id}"); - (await request.Content.ReadAsStringAsync()).Should().Be(expected); + (await request.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Should().Be(expected); ex.ClientEntity.Should().BeEquivalentTo(entity, this.entityEquivalentOptions); ex.ServerEntity.Should().BeEquivalentTo(this.successfulKitchenSink, this.entityEquivalentOptions); @@ -1898,7 +1898,7 @@ public async Task ReplaceAsync_Missing_DontThrow() ClientKitchenSink entity = new() { Id = "1", StringValue = "abc" }; DatasyncServiceOptions options = new() { ThrowIfMissing = false }; DatasyncServiceClient client = GetMockClient(); - ServiceResponse response = await client.ReplaceAsync(entity, options); + ServiceResponse response = await client.ReplaceAsync(entity, options, TestContext.Current.CancellationToken); HttpRequestMessage request = this.mockHandler.Requests.SingleOrDefault(); request.Should().NotBeNull(); @@ -2011,7 +2011,7 @@ public async Task ToArrayAsync_Table() { Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - ClientKitchenSink[] actualItems = await client.ToArrayAsync(); + ClientKitchenSink[] actualItems = await client.ToArrayAsync(TestContext.Current.CancellationToken); actualItems.Should().BeEquivalentTo(page.Items); @@ -2026,7 +2026,7 @@ public async Task ToArrayAsync_Query() { Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - ClientKitchenSink[] actualItems = await client.Where(x => x.StringValue == "abc").ToArrayAsync(); + ClientKitchenSink[] actualItems = await client.Where(x => x.StringValue == "abc").ToArrayAsync(TestContext.Current.CancellationToken); actualItems.Should().BeEquivalentTo(page.Items); @@ -2044,7 +2044,7 @@ public async Task ToAsyncEnumerable_Table() Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); IAsyncEnumerable result = client.ToAsyncEnumerable(); - List actualItems = await result.ToListAsync(); + List actualItems = await result.ToListAsync(TestContext.Current.CancellationToken); actualItems.Should().BeEquivalentTo(page.Items); @@ -2060,7 +2060,7 @@ public async Task ToAsyncEnumerable_Query() Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); IAsyncEnumerable result = client.Where(x => x.StringValue == "abc").ToAsyncEnumerable(); - List actualItems = await result.ToListAsync(); + List actualItems = await result.ToListAsync(TestContext.Current.CancellationToken); actualItems.Should().BeEquivalentTo(page.Items); @@ -2078,7 +2078,7 @@ public async Task ToAsyncPageable_Table() Page page = CreatePage(5, 42L); DatasyncServiceClient client = GetMockClient(); IAsyncPageable pagedResult = client.ToAsyncPageable(); - Page firstPage = await pagedResult.AsPages().FirstAsync(); + Page firstPage = await pagedResult.AsPages().FirstAsync(TestContext.Current.CancellationToken); List actualItems = firstPage.Items.ToList(); actualItems.Should().BeEquivalentTo(page.Items); @@ -2095,7 +2095,7 @@ public async Task ToAsyncPageable_Query() Page page = CreatePage(5, 42L); DatasyncServiceClient client = GetMockClient(); IAsyncPageable pagedResult = client.Where(x => x.StringValue == "abc").ToAsyncPageable(); - Page firstPage = await pagedResult.AsPages().FirstAsync(); + Page firstPage = await pagedResult.AsPages().FirstAsync(TestContext.Current.CancellationToken); List actualItems = firstPage.Items.ToList(); actualItems.Should().BeEquivalentTo(page.Items); @@ -2113,7 +2113,7 @@ public async Task ToDictionaryAsync_FirstForm_Table() { Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - Dictionary actualItems = await client.ToDictionaryAsync(x => x.Id); + Dictionary actualItems = await client.ToDictionaryAsync(x => x.Id, TestContext.Current.CancellationToken); Dictionary expectedItems = page.Items.ToDictionary(x => x.Id); actualItems.Should().BeEquivalentTo(expectedItems); @@ -2129,7 +2129,7 @@ public async Task ToDictionaryAsync_SecondForm_Table() { Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - Dictionary actualItems = await client.ToDictionaryAsync(x => x.Id, StringComparer.OrdinalIgnoreCase); + Dictionary actualItems = await client.ToDictionaryAsync(x => x.Id, StringComparer.OrdinalIgnoreCase, TestContext.Current.CancellationToken); Dictionary expectedItems = page.Items.ToDictionary(x => x.Id, StringComparer.OrdinalIgnoreCase); actualItems.Should().BeEquivalentTo(expectedItems); @@ -2145,7 +2145,7 @@ public async Task ToDictionaryAsync_FirstForm_Query() { Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - Dictionary actualItems = await client.Where(x => x.StringValue == "abc").ToDictionaryAsync(x => x.Id); + Dictionary actualItems = await client.Where(x => x.StringValue == "abc").ToDictionaryAsync(x => x.Id, TestContext.Current.CancellationToken); Dictionary expectedItems = page.Items.ToDictionary(x => x.Id); actualItems.Should().BeEquivalentTo(expectedItems); @@ -2161,7 +2161,7 @@ public async Task ToDictionaryAsync_SecondForm_Query() { Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - Dictionary actualItems = await client.Where(x => x.StringValue == "abc").ToDictionaryAsync(x => x.Id, StringComparer.OrdinalIgnoreCase); + Dictionary actualItems = await client.Where(x => x.StringValue == "abc").ToDictionaryAsync(x => x.Id, StringComparer.OrdinalIgnoreCase, TestContext.Current.CancellationToken); Dictionary expectedItems = page.Items.ToDictionary(x => x.Id, StringComparer.OrdinalIgnoreCase); actualItems.Should().BeEquivalentTo(expectedItems); @@ -2179,7 +2179,7 @@ public async Task ToHashSetAsync_FirstForm_Table() { Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - HashSet actualItems = await client.ToHashSetAsync(); + HashSet actualItems = await client.ToHashSetAsync(TestContext.Current.CancellationToken); HashSet expectedItems = page.Items.ToHashSet(); actualItems.Should().BeEquivalentTo(expectedItems); @@ -2197,7 +2197,7 @@ public async Task ToHashSetAsync_SecondForm_Table() Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - HashSet actualItems = await client.ToHashSetAsync(comparer); + HashSet actualItems = await client.ToHashSetAsync(comparer, TestContext.Current.CancellationToken); HashSet expectedItems = page.Items.ToHashSet(comparer); actualItems.Should().BeEquivalentTo(expectedItems); @@ -2213,7 +2213,7 @@ public async Task ToHashSetAsync_FirstForm_Query() { Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - HashSet actualItems = await client.Where(x => x.StringValue == "abc").ToHashSetAsync(); + HashSet actualItems = await client.Where(x => x.StringValue == "abc").ToHashSetAsync(TestContext.Current.CancellationToken); HashSet expectedItems = page.Items.ToHashSet(); actualItems.Should().BeEquivalentTo(expectedItems); @@ -2231,7 +2231,7 @@ public async Task ToHashSetAsync_SecondForm_Query() Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - HashSet actualItems = await client.Where(x => x.StringValue == "abc").ToHashSetAsync(comparer); + HashSet actualItems = await client.Where(x => x.StringValue == "abc").ToHashSetAsync(comparer, TestContext.Current.CancellationToken); HashSet expectedItems = page.Items.ToHashSet(comparer); actualItems.Should().BeEquivalentTo(expectedItems); @@ -2258,7 +2258,7 @@ public async Task ToListAsync_Table() { Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - List actualItems = await client.ToListAsync(); + List actualItems = await client.ToListAsync(TestContext.Current.CancellationToken); actualItems.Should().BeEquivalentTo(page.Items); @@ -2273,7 +2273,7 @@ public async Task ToListAsync_Query() { Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - List actualItems = await client.Where(x => x.StringValue == "abc").ToListAsync(); + List actualItems = await client.Where(x => x.StringValue == "abc").ToListAsync(TestContext.Current.CancellationToken); actualItems.Should().BeEquivalentTo(page.Items); @@ -2290,7 +2290,7 @@ public async Task ToObservableCollectionAsync_NewCollection_Table() { Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - ConcurrentObservableCollection actualItems = await client.ToObservableCollectionAsync(); + ConcurrentObservableCollection actualItems = await client.ToObservableCollectionAsync(TestContext.Current.CancellationToken); actualItems.Should().BeEquivalentTo(page.Items); @@ -2306,7 +2306,7 @@ public async Task ToObservableCollectionAsync_ExistingCollection_Table() Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); ConcurrentObservableCollection collection = new(); - ConcurrentObservableCollection actualItems = await client.ToObservableCollectionAsync(collection); + ConcurrentObservableCollection actualItems = await client.ToObservableCollectionAsync(collection, TestContext.Current.CancellationToken); actualItems.Should().BeSameAs(collection).And.BeEquivalentTo(page.Items); @@ -2321,7 +2321,7 @@ public async Task ToObservableCollectionAsync_NewCollection_Query() { Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); - ConcurrentObservableCollection actualItems = await client.Where(x => x.StringValue == "abc").ToObservableCollectionAsync(); + ConcurrentObservableCollection actualItems = await client.Where(x => x.StringValue == "abc").ToObservableCollectionAsync(TestContext.Current.CancellationToken); actualItems.Should().BeEquivalentTo(page.Items); @@ -2337,7 +2337,7 @@ public async Task ToObservableCollectionAsync_ExistingCollection_Query() Page page = CreatePage(5); DatasyncServiceClient client = GetMockClient(); ConcurrentObservableCollection collection = new(); - ConcurrentObservableCollection actualItems = await client.Where(x => x.StringValue == "abc").ToObservableCollectionAsync(collection); + ConcurrentObservableCollection actualItems = await client.Where(x => x.StringValue == "abc").ToObservableCollectionAsync(collection, TestContext.Current.CancellationToken); actualItems.Should().BeSameAs(collection).And.BeEquivalentTo(page.Items); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Service/Integration_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Service/Integration_Tests.cs index 85f56c4d..72a07a2f 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Service/Integration_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Service/Integration_Tests.cs @@ -28,7 +28,7 @@ public async Task Create_WithValidInput_Returns201(string id) ClientMovie source = new(TestData.Movies.BlackPanther) { Id = id }; DatasyncServiceClient client = GetMovieClient(); - ServiceResponse response = await client.AddAsync(source); + ServiceResponse response = await client.AddAsync(source, TestContext.Current.CancellationToken); InMemoryMovie inMemoryMovie = GetServerEntityById(response.Value.Id); response.IsSuccessful.Should().BeTrue(); @@ -92,7 +92,7 @@ public async Task Create_CanRoundtrip_Types() }; DatasyncServiceClient client = GetKitchenSinkClient(); - ServiceResponse response = await client.AddAsync(source); + ServiceResponse response = await client.AddAsync(source, TestContext.Current.CancellationToken); InMemoryKitchenSink serverEntity = GetServerEntityById(id); response.IsSuccessful.Should().BeTrue(); @@ -111,7 +111,7 @@ public async Task Read_Returns200() InMemoryMovie existingMovie = GetRandomMovie(); DatasyncServiceClient client = GetMovieClient(); - ServiceResponse response = await client.GetAsync(existingMovie.Id); + ServiceResponse response = await client.GetAsync(existingMovie.Id, TestContext.Current.CancellationToken); response.IsSuccessful.Should().BeTrue(); response.StatusCode.Should().Be(200); @@ -127,7 +127,7 @@ public async Task Read_MissingId_Returns404() DatasyncServiceClient client = GetMovieClient(); DatasyncServiceOptions options = new() { ThrowIfMissing = false }; - ServiceResponse response = await client.GetAsync("id-is-missing", options); + ServiceResponse response = await client.GetAsync("id-is-missing", options, TestContext.Current.CancellationToken); response.IsSuccessful.Should().BeFalse(); response.StatusCode.Should().Be(404); @@ -149,7 +149,7 @@ public async Task Read_SoftDeleted_NotDeleted_Returns200() InMemoryMovie existingMovie = GetRandomMovie(); DatasyncServiceClient client = GetSoftDeletedMovieClient(); - ServiceResponse response = await client.GetAsync(existingMovie.Id); + ServiceResponse response = await client.GetAsync(existingMovie.Id, TestContext.Current.CancellationToken); response.IsSuccessful.Should().BeTrue(); response.StatusCode.Should().Be(200); @@ -180,7 +180,7 @@ public async Task Read_SoftDeleted_Deleted_WithIncludeDeleted_Returns200() DatasyncServiceClient client = GetSoftDeletedMovieClient(); DatasyncServiceOptions options = new() { IncludeDeleted = true }; - ServiceResponse response = await client.GetAsync(existingMovie.Id, options); + ServiceResponse response = await client.GetAsync(existingMovie.Id, options, TestContext.Current.CancellationToken); response.IsSuccessful.Should().BeTrue(); response.StatusCode.Should().Be(200); @@ -198,7 +198,7 @@ public async Task Delete_ById_Returns204() InMemoryMovie existingMovie = GetRandomMovie(); DatasyncServiceClient client = GetMovieClient(); - ServiceResponse response = await client.RemoveAsync(existingMovie.Id, new DatasyncServiceOptions()); + ServiceResponse response = await client.RemoveAsync(existingMovie.Id, new DatasyncServiceOptions(), TestContext.Current.CancellationToken); response.IsSuccessful.Should().BeTrue(); response.StatusCode.Should().Be(204); @@ -217,7 +217,7 @@ public async Task Delete_WithVersioning_Works() DatasyncServiceClient client = GetMovieClient(); DatasyncServiceOptions options = new() { Version = version }; - ServiceResponse response = await client.RemoveAsync(existingMovie.Id, options); + ServiceResponse response = await client.RemoveAsync(existingMovie.Id, options, TestContext.Current.CancellationToken); response.IsSuccessful.Should().BeTrue(); response.StatusCode.Should().Be(204); @@ -254,7 +254,7 @@ public async Task Delete_MissingId_Returns404() DatasyncServiceClient client = GetMovieClient(); DatasyncServiceOptions options = new() { ThrowIfMissing = false }; - ServiceResponse response = await client.RemoveAsync("id-is-missing", options); + ServiceResponse response = await client.RemoveAsync("id-is-missing", options, TestContext.Current.CancellationToken); response.IsSuccessful.Should().BeFalse(); response.StatusCode.Should().Be(404); @@ -279,7 +279,7 @@ public async Task Delete_NotSoftDeleted_Returns204() DatasyncServiceClient client = GetSoftDeletedMovieClient(); DatasyncServiceOptions options = new(); - ServiceResponse response = await client.RemoveAsync(existingMovie.Id, options); + ServiceResponse response = await client.RemoveAsync(existingMovie.Id, options, TestContext.Current.CancellationToken); response.IsSuccessful.Should().BeTrue(); response.StatusCode.Should().Be(204); @@ -316,7 +316,7 @@ public async Task Replace_Returns200() DatasyncServiceClient client = GetMovieClient(); DatasyncServiceOptions options = new(); - ServiceResponse response = await client.ReplaceAsync(existingMovie, options); + ServiceResponse response = await client.ReplaceAsync(existingMovie, options, TestContext.Current.CancellationToken); InMemoryMovie inMemoryMovie = GetServerEntityById(response.Value.Id); response.IsSuccessful.Should().BeTrue(); @@ -334,7 +334,7 @@ public async Task Replace_WithVersioning_Works() ClientMovie existingMovie = new(GetRandomMovie()) { Title = "New Title" }; DatasyncServiceClient client = GetMovieClient(); - ServiceResponse response = await client.ReplaceAsync(existingMovie); + ServiceResponse response = await client.ReplaceAsync(existingMovie, TestContext.Current.CancellationToken); InMemoryMovie inMemoryMovie = GetServerEntityById(response.Value.Id); response.IsSuccessful.Should().BeTrue(); @@ -373,7 +373,7 @@ public async Task Replace_MissingId_Returns404() DatasyncServiceClient client = GetMovieClient(); DatasyncServiceOptions options = new() { ThrowIfMissing = false }; - ServiceResponse response = await client.ReplaceAsync(source, options); + ServiceResponse response = await client.ReplaceAsync(source, options, TestContext.Current.CancellationToken); response.IsSuccessful.Should().BeFalse(); response.StatusCode.Should().Be(404); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Threading/AsyncLockDictionary_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Threading/AsyncLockDictionary_Tests.cs index 15faa6fe..29b99e42 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Threading/AsyncLockDictionary_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Threading/AsyncLockDictionary_Tests.cs @@ -35,7 +35,7 @@ public async Task AcquireLockAsync_Works() sut.IsLocked("key1").Should().BeFalse(); sut.IsLocked("key2").Should().BeFalse(); - using (await sut.AcquireLockAsync("key1")) + using (await sut.AcquireLockAsync("key1", TestContext.Current.CancellationToken)) { sut.IsLocked("key1").Should().BeTrue(); sut.IsLocked("key2").Should().BeFalse(); diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Threading/DisposableLock_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Threading/DisposableLock_Tests.cs index 220d8444..e0d34834 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Threading/DisposableLock_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Threading/DisposableLock_Tests.cs @@ -29,7 +29,7 @@ public async Task AcquireLockAsync_Works() DisposableLock sut = new(); sut.IsLocked().Should().BeFalse(); - using (await sut.AcquireLockAsync()) + using (await sut.AcquireLockAsync(TestContext.Current.CancellationToken)) { sut.IsLocked().Should().BeTrue(); } diff --git a/tests/CommunityToolkit.Datasync.Client.Test/Threading/QueueHandler_Tests.cs b/tests/CommunityToolkit.Datasync.Client.Test/Threading/QueueHandler_Tests.cs index b408f972..356c4a38 100644 --- a/tests/CommunityToolkit.Datasync.Client.Test/Threading/QueueHandler_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Client.Test/Threading/QueueHandler_Tests.cs @@ -85,7 +85,7 @@ public async Task QueueHandler_WithThreads_EnqueueRange(int nThreads) accId.Should().HaveCount(nElements); accTh.Should().HaveCount(nElements); accTh.AsEnumerable().Distinct().Should().HaveCount(nThreads); - (endTime - startTime).TotalSeconds.Should().BeLessThanOrEqualTo((nElements / nThreads) + 2); + (endTime - startTime).TotalSeconds.Should().BeLessThanOrEqualTo(2 * (nElements / nThreads) + 5); } [Theory, CombinatorialData] diff --git a/tests/CommunityToolkit.Datasync.Server.EntityFrameworkCore.Test/RepositoryControlledEntityTableRepository_Tests.cs b/tests/CommunityToolkit.Datasync.Server.EntityFrameworkCore.Test/RepositoryControlledEntityTableRepository_Tests.cs index f7a4366d..1cfd778c 100644 --- a/tests/CommunityToolkit.Datasync.Server.EntityFrameworkCore.Test/RepositoryControlledEntityTableRepository_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.EntityFrameworkCore.Test/RepositoryControlledEntityTableRepository_Tests.cs @@ -52,7 +52,7 @@ public async Task IdGenerator_Ulid_CanCreate() RepositoryControlledEntityMovie addition = TestData.Movies.OfType(TestData.Movies.BlackPanther); addition.Id = null; RepositoryControlledEntityMovie sut = addition.Clone(); - await repository.CreateAsync(sut); + await repository.CreateAsync(sut, TestContext.Current.CancellationToken); RepositoryControlledEntityMovie actual = await GetEntityAsync(sut.Id); actual.Should().BeEquivalentTo(addition); @@ -78,7 +78,7 @@ public async Task VersionGenerator_Ticks_CanCreate() RepositoryControlledEntityMovie addition = TestData.Movies.OfType(TestData.Movies.BlackPanther); addition.Id = null; RepositoryControlledEntityMovie sut = addition.Clone(); - await repository.CreateAsync(sut); + await repository.CreateAsync(sut, TestContext.Current.CancellationToken); RepositoryControlledEntityMovie actual = await GetEntityAsync(sut.Id); actual.Should().BeEquivalentTo(addition); diff --git a/tests/CommunityToolkit.Datasync.Server.EntityFrameworkCore.Test/SqliteEntityTableRepository_Tests.cs b/tests/CommunityToolkit.Datasync.Server.EntityFrameworkCore.Test/SqliteEntityTableRepository_Tests.cs index 5668217d..7254b985 100644 --- a/tests/CommunityToolkit.Datasync.Server.EntityFrameworkCore.Test/SqliteEntityTableRepository_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.EntityFrameworkCore.Test/SqliteEntityTableRepository_Tests.cs @@ -52,7 +52,7 @@ public async Task IdGenerator_Ulid_CanCreate() SqliteEntityMovie addition = TestData.Movies.OfType(TestData.Movies.BlackPanther); addition.Id = null; SqliteEntityMovie sut = addition.Clone(); - await repository.CreateAsync(sut); + await repository.CreateAsync(sut, TestContext.Current.CancellationToken); SqliteEntityMovie actual = await GetEntityAsync(sut.Id); actual.Should().BeEquivalentTo(addition); diff --git a/tests/CommunityToolkit.Datasync.Server.InMemory.Test/InMemoryRepository_Tests.cs b/tests/CommunityToolkit.Datasync.Server.InMemory.Test/InMemoryRepository_Tests.cs index e4167e05..554d57d8 100644 --- a/tests/CommunityToolkit.Datasync.Server.InMemory.Test/InMemoryRepository_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.InMemory.Test/InMemoryRepository_Tests.cs @@ -138,7 +138,7 @@ public async Task IdGenerator_Ulid_CanCreate() InMemoryMovie addition = TestData.Movies.OfType(TestData.Movies.BlackPanther); addition.Id = null; InMemoryMovie sut = addition.Clone(); - await repository.CreateAsync(sut); + await repository.CreateAsync(sut, TestContext.Current.CancellationToken); InMemoryMovie actual = await GetEntityAsync(sut.Id); actual.Should().BeEquivalentTo(addition); @@ -164,7 +164,7 @@ public async Task VersionGenerator_Ticks_CanCreate() InMemoryMovie addition = TestData.Movies.OfType(TestData.Movies.BlackPanther); addition.Id = null; InMemoryMovie sut = addition.Clone(); - await repository.CreateAsync(sut); + await repository.CreateAsync(sut, TestContext.Current.CancellationToken); InMemoryMovie actual = await GetEntityAsync(sut.Id); actual.Should().BeEquivalentTo(addition); diff --git a/tests/CommunityToolkit.Datasync.Server.LiteDb.Test/LiteDbRepository_Tests.cs b/tests/CommunityToolkit.Datasync.Server.LiteDb.Test/LiteDbRepository_Tests.cs index 78f70f74..f4795d55 100644 --- a/tests/CommunityToolkit.Datasync.Server.LiteDb.Test/LiteDbRepository_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.LiteDb.Test/LiteDbRepository_Tests.cs @@ -82,7 +82,7 @@ public async Task IdGenerator_Ulid_CanCreate() LiteDbMovie addition = TestData.Movies.OfType(TestData.Movies.BlackPanther); addition.Id = null; LiteDbMovie sut = addition.Clone(); - await repository.CreateAsync(sut); + await repository.CreateAsync(sut, TestContext.Current.CancellationToken); LiteDbMovie actual = await GetEntityAsync(sut.Id); actual.Should().BeEquivalentTo(addition); @@ -108,7 +108,7 @@ public async Task VersionGenerator_Ticks_CanCreate() LiteDbMovie addition = TestData.Movies.OfType(TestData.Movies.BlackPanther); addition.Id = null; LiteDbMovie sut = addition.Clone(); - await repository.CreateAsync(sut); + await repository.CreateAsync(sut, TestContext.Current.CancellationToken); LiteDbMovie actual = await GetEntityAsync(sut.Id); actual.Should().BeEquivalentTo(addition); diff --git a/tests/CommunityToolkit.Datasync.Server.NSwag.Test/NSwag_Tests.cs b/tests/CommunityToolkit.Datasync.Server.NSwag.Test/NSwag_Tests.cs index bccfd54d..c670c326 100644 --- a/tests/CommunityToolkit.Datasync.Server.NSwag.Test/NSwag_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.NSwag.Test/NSwag_Tests.cs @@ -31,7 +31,7 @@ public async Task NSwag_GeneratesSwagger() .UseContentRoot(AppContext.BaseDirectory) .UseStartup(); }).Build(); - await host.StartAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); TestServer server = host.GetTestServer(); @@ -40,7 +40,7 @@ public async Task NSwag_GeneratesSwagger() context.InitializeDatabase(); HttpClient client = server.CreateClient(); - string actualContent = (await client.GetStringAsync("swagger/v1/swagger.json")).NormalizeContent(); + string actualContent = (await client.GetStringAsync("swagger/v1/swagger.json", TestContext.Current.CancellationToken)).NormalizeContent(); string expectedContent = Assembly.GetExecutingAssembly().ReadExternalFile("swagger.json"); // There is an x-generator field that is library specific and completely irrelevant diff --git a/tests/CommunityToolkit.Datasync.Server.OpenApi.Test/OpenApi_Tests.cs b/tests/CommunityToolkit.Datasync.Server.OpenApi.Test/OpenApi_Tests.cs index 56b2ab62..f4128215 100644 --- a/tests/CommunityToolkit.Datasync.Server.OpenApi.Test/OpenApi_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.OpenApi.Test/OpenApi_Tests.cs @@ -27,7 +27,7 @@ public async Task GeneratesCorrectOpenApiFile() .UseContentRoot(AppContext.BaseDirectory) .UseStartup(); }).Build(); - await host.StartAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); TestServer server = host.GetTestServer(); @@ -36,7 +36,7 @@ public async Task GeneratesCorrectOpenApiFile() context.InitializeDatabase(); HttpClient client = server.CreateClient(); - string actualContent = (await client.GetStringAsync("openapi/v1.json")).NormalizeContent(); + string actualContent = (await client.GetStringAsync("openapi/v1.json", TestContext.Current.CancellationToken)).NormalizeContent(); string expectedContent = Assembly.GetExecutingAssembly().ReadExternalFile("openapi.json"); // There is an x-generator field that is library specific and completely irrelevant diff --git a/tests/CommunityToolkit.Datasync.Server.Swashbuckle.Test/Swashbuckle_Tests.cs b/tests/CommunityToolkit.Datasync.Server.Swashbuckle.Test/Swashbuckle_Tests.cs index 79974673..527d1c83 100644 --- a/tests/CommunityToolkit.Datasync.Server.Swashbuckle.Test/Swashbuckle_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Swashbuckle.Test/Swashbuckle_Tests.cs @@ -32,7 +32,7 @@ public async Task Swashbuckle_GeneratesSwagger() .UseContentRoot(AppContext.BaseDirectory) .UseStartup(); }).Build(); - await host.StartAsync(); + await host.StartAsync(TestContext.Current.CancellationToken); TestServer server = host.GetTestServer(); @@ -40,7 +40,7 @@ public async Task Swashbuckle_GeneratesSwagger() ServiceDbContext context = scope.ServiceProvider.GetRequiredService(); context.InitializeDatabase(); HttpClient client = server.CreateClient(); - string actualContent = (await client.GetStringAsync("swagger/v1/swagger.json")).NormalizeContent(); + string actualContent = (await client.GetStringAsync("swagger/v1/swagger.json", TestContext.Current.CancellationToken)).NormalizeContent(); string expectedContent = Assembly.GetExecutingAssembly().ReadExternalFile("swagger.json"); // There is an x-generator field that is library specific and completely irrelevant diff --git a/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Base_Tests.cs b/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Base_Tests.cs index a060775e..c98db334 100644 --- a/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Base_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Base_Tests.cs @@ -255,7 +255,7 @@ public async Task PostCommitHookAsync_NoRepositoryUpdated(TableOperation op) Func act = async () => await controller.__PostCommitHookAsync(op, entity, CancellationToken.None); await act.Should().NotThrowAsync(); - await provider.ReceivedWithAnyArgs(1).PostCommitHookAsync(default, default, default); + await provider.ReceivedWithAnyArgs(1).PostCommitHookAsync(default, default, TestContext.Current.CancellationToken); } [Theory] @@ -274,7 +274,7 @@ public async Task PostCommitHookAsync_FiresRepositoryUpdated(TableOperation op) Func act = async () => await controller.__PostCommitHookAsync(op, entity, CancellationToken.None); await act.Should().NotThrowAsync(); - await provider.ReceivedWithAnyArgs(1).PostCommitHookAsync(default, default, default); + await provider.ReceivedWithAnyArgs(1).PostCommitHookAsync(default, default, TestContext.Current.CancellationToken); firedEvents.Should().ContainSingle(); firedEvents[0].Operation.Should().Be(op); firedEvents[0].Entity.Should().BeEquivalentTo(entity); diff --git a/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Create_Tests.cs b/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Create_Tests.cs index 197fd335..53094a22 100644 --- a/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Create_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Create_Tests.cs @@ -24,7 +24,7 @@ public async Task CreateAsync_UnsafeEntityLogging_False_LogsIdOnly() TableData entity = new() { Id = "0da7fb24-3606-442f-9f68-c47c6e7d09d4" }; controller.ControllerContext.HttpContext = CreateHttpContext(HttpMethod.Post, "https://localhost/table", entity); - _ = await controller.CreateAsync(); + _ = await controller.CreateAsync(TestContext.Current.CancellationToken); logger.Entries.Should().Contain(e => e.LogLevel == LogLevel.Information && e.Message.Contains(entity.Id)); logger.Entries.Should().NotContain(e => e.Message.Contains("UpdatedAt", StringComparison.OrdinalIgnoreCase)); @@ -42,7 +42,7 @@ public async Task CreateAsync_UnsafeEntityLogging_True_LogsFullEntityAtDebug() TableData entity = new() { Id = "0da7fb24-3606-442f-9f68-c47c6e7d09d4" }; controller.ControllerContext.HttpContext = CreateHttpContext(HttpMethod.Post, "https://localhost/table", entity); - _ = await controller.CreateAsync(); + _ = await controller.CreateAsync(TestContext.Current.CancellationToken); logger.Entries.Should().Contain(e => e.LogLevel == LogLevel.Information && e.Message.Contains(entity.Id)); logger.Entries.Should().Contain(e => e.LogLevel == LogLevel.Debug && e.Message.Contains("UpdatedAt", StringComparison.OrdinalIgnoreCase)); @@ -132,7 +132,7 @@ public async Task CreateAsync_Works() List firedEvents = []; controller.RepositoryUpdated += (_, e) => firedEvents.Add(e); - CreatedAtRouteResult actual = await controller.CreateAsync() as CreatedAtRouteResult; + CreatedAtRouteResult actual = await controller.CreateAsync(TestContext.Current.CancellationToken) as CreatedAtRouteResult; actual.Should().NotBeNull(); actual.StatusCode.Should().Be(201); diff --git a/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Delete_Tests.cs b/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Delete_Tests.cs index a84a6424..db5ec2f6 100644 --- a/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Delete_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Delete_Tests.cs @@ -141,7 +141,7 @@ public async Task DeleteAsync_SoftDelete_Works(bool includeIfMatch, bool include List firedEvents = []; controller.RepositoryUpdated += (_, e) => firedEvents.Add(e); - NoContentResult actual = await controller.DeleteAsync(entity.Id) as NoContentResult; + NoContentResult actual = await controller.DeleteAsync(entity.Id, TestContext.Current.CancellationToken) as NoContentResult; actual.Should().NotBeNull(); actual.StatusCode.Should().Be(204); @@ -187,7 +187,7 @@ public async Task DeleteAsync_HardDelete_Works(bool includeIfMatch, bool include List firedEvents = []; controller.RepositoryUpdated += (_, e) => firedEvents.Add(e); - NoContentResult actual = await controller.DeleteAsync(entity.Id) as NoContentResult; + NoContentResult actual = await controller.DeleteAsync(entity.Id, TestContext.Current.CancellationToken) as NoContentResult; actual.Should().NotBeNull(); actual.StatusCode.Should().Be(204); diff --git a/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Query_Tests.cs b/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Query_Tests.cs index e4854872..8089dc45 100644 --- a/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Query_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Query_Tests.cs @@ -80,7 +80,7 @@ public async Task QueryAsync_NoExtras_Works() TableController controller = new(repository, accessProvider); controller.ControllerContext.HttpContext = CreateHttpContext(HttpMethod.Get, "https://localhost/table"); - OkObjectResult result = await controller.QueryAsync() as OkObjectResult; + OkObjectResult result = await controller.QueryAsync(TestContext.Current.CancellationToken) as OkObjectResult; result.Should().NotBeNull(); PagedResult pagedResult = result.Value as PagedResult; pagedResult.Should().NotBeNull(); @@ -99,7 +99,7 @@ public async Task QueryAsync_DataView_Works(string filter, int count) TableController controller = new(repository, accessProvider); controller.ControllerContext.HttpContext = CreateHttpContext(HttpMethod.Get, "https://localhost/table"); - OkObjectResult result = await controller.QueryAsync() as OkObjectResult; + OkObjectResult result = await controller.QueryAsync(TestContext.Current.CancellationToken) as OkObjectResult; result.Should().NotBeNull(); PagedResult pagedResult = result.Value as PagedResult; pagedResult.Should().NotBeNull(); @@ -119,7 +119,7 @@ public async Task QueryAsync_DeletedSkipped_Works(bool isDeleted, int count) TableController controller = new(repository, accessProvider) { Options = options }; controller.ControllerContext.HttpContext = CreateHttpContext(HttpMethod.Get, "https://localhost/table"); - OkObjectResult result = await controller.QueryAsync() as OkObjectResult; + OkObjectResult result = await controller.QueryAsync(TestContext.Current.CancellationToken) as OkObjectResult; result.Should().NotBeNull(); PagedResult pagedResult = result.Value as PagedResult; pagedResult.Should().NotBeNull(); @@ -139,7 +139,7 @@ public async Task QueryAsync_DeletedIncluded_Works(bool isDeleted, int count) TableController controller = new(repository, accessProvider) { Options = options }; controller.ControllerContext.HttpContext = CreateHttpContext(HttpMethod.Get, "https://localhost/table?__includedeleted=true"); - OkObjectResult result = await controller.QueryAsync() as OkObjectResult; + OkObjectResult result = await controller.QueryAsync(TestContext.Current.CancellationToken) as OkObjectResult; result.Should().NotBeNull(); PagedResult pagedResult = result.Value as PagedResult; pagedResult.Should().NotBeNull(); diff --git a/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Read_Tests.cs b/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Read_Tests.cs index be9497dc..18949084 100644 --- a/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Read_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Read_Tests.cs @@ -25,7 +25,7 @@ public async Task ReadAsync_UnsafeEntityLogging_False_LogsIdOnly() ExposedTableController controller = new(repository, accessProvider, options) { Logger = logger }; controller.ControllerContext.HttpContext = CreateHttpContext(HttpMethod.Get, $"https://localhost/table/{entity.Id}"); - _ = await controller.ReadAsync(entity.Id); + _ = await controller.ReadAsync(entity.Id, TestContext.Current.CancellationToken); logger.Entries.Should().Contain(e => e.LogLevel == LogLevel.Information && e.Message.Contains(entity.Id)); logger.Entries.Should().NotContain(e => e.Message.Contains("UpdatedAt", StringComparison.OrdinalIgnoreCase)); @@ -44,7 +44,7 @@ public async Task ReadAsync_UnsafeEntityLogging_True_LogsFullEntityAtDebug() ExposedTableController controller = new(repository, accessProvider, options) { Logger = logger }; controller.ControllerContext.HttpContext = CreateHttpContext(HttpMethod.Get, $"https://localhost/table/{entity.Id}"); - _ = await controller.ReadAsync(entity.Id); + _ = await controller.ReadAsync(entity.Id, TestContext.Current.CancellationToken); logger.Entries.Should().Contain(e => e.LogLevel == LogLevel.Information && e.Message.Contains(entity.Id)); logger.Entries.Should().Contain(e => e.LogLevel == LogLevel.Debug && e.Message.Contains("UpdatedAt", StringComparison.OrdinalIgnoreCase)); @@ -179,7 +179,7 @@ public async Task ReadAsync_Works(bool includeIfMatch, bool includeLastModified) List firedEvents = []; controller.RepositoryUpdated += (_, e) => firedEvents.Add(e); - OkObjectResult actual = await controller.ReadAsync(entity.Id) as OkObjectResult; + OkObjectResult actual = await controller.ReadAsync(entity.Id, TestContext.Current.CancellationToken) as OkObjectResult; actual.Should().NotBeNull(); actual.StatusCode.Should().Be(200); diff --git a/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Replace_Tests.cs b/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Replace_Tests.cs index c914a3a0..28056934 100644 --- a/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Replace_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Test/Controllers/TableController_Replace_Tests.cs @@ -25,7 +25,7 @@ public async Task ReplaceAsync_UnsafeEntityLogging_False_LogsIdOnly() ExposedTableController controller = new(repository, accessProvider, options) { Logger = logger }; controller.ControllerContext.HttpContext = CreateHttpContext(HttpMethod.Put, $"https://localhost/table/{entity.Id}", entity); - _ = await controller.ReplaceAsync(entity.Id); + _ = await controller.ReplaceAsync(entity.Id, TestContext.Current.CancellationToken); logger.Entries.Should().Contain(e => e.LogLevel == LogLevel.Information && e.Message.Contains(entity.Id)); logger.Entries.Should().NotContain(e => e.Message.Contains("UpdatedAt", StringComparison.OrdinalIgnoreCase)); @@ -44,7 +44,7 @@ public async Task ReplaceAsync_UnsafeEntityLogging_True_LogsFullEntityAtDebug() ExposedTableController controller = new(repository, accessProvider, options) { Logger = logger }; controller.ControllerContext.HttpContext = CreateHttpContext(HttpMethod.Put, $"https://localhost/table/{entity.Id}", entity); - _ = await controller.ReplaceAsync(entity.Id); + _ = await controller.ReplaceAsync(entity.Id, TestContext.Current.CancellationToken); logger.Entries.Should().Contain(e => e.LogLevel == LogLevel.Information && e.Message.Contains(entity.Id)); logger.Entries.Should().Contain(e => e.LogLevel == LogLevel.Debug && e.Message.Contains("UpdatedAt", StringComparison.OrdinalIgnoreCase)); @@ -209,7 +209,7 @@ public async Task ReplaceAsync_Works(bool includeIfMatch, bool includeLastModifi List firedEvents = []; controller.RepositoryUpdated += (_, e) => firedEvents.Add(e); - OkObjectResult actual = await controller.ReplaceAsync(entity.Id) as OkObjectResult; + OkObjectResult actual = await controller.ReplaceAsync(entity.Id, TestContext.Current.CancellationToken) as OkObjectResult; actual.Should().NotBeNull(); actual.StatusCode.Should().Be(200); diff --git a/tests/CommunityToolkit.Datasync.Server.Test/Helpers/LiveControllerTests.cs b/tests/CommunityToolkit.Datasync.Server.Test/Helpers/LiveControllerTests.cs index 478eeec7..62787462 100644 --- a/tests/CommunityToolkit.Datasync.Server.Test/Helpers/LiveControllerTests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Test/Helpers/LiveControllerTests.cs @@ -147,7 +147,7 @@ public async Task FailedQueryTest(string query, HttpStatusCode expectedStatusCod await CreateControllerAsync(HttpMethod.Get, $"{MovieEndpoint}?{query}"); - IActionResult result = await this.tableController.QueryAsync(); + IActionResult result = await this.tableController.QueryAsync(TestContext.Current.CancellationToken); result.Should().BeAssignableTo(); ((StatusCodeResult)result).StatusCode.Should().Be((int)expectedStatusCode); diff --git a/tests/CommunityToolkit.Datasync.Server.Test/Service/Create_Tests.cs b/tests/CommunityToolkit.Datasync.Server.Test/Service/Create_Tests.cs index 481487fb..285a0365 100644 --- a/tests/CommunityToolkit.Datasync.Server.Test/Service/Create_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Test/Service/Create_Tests.cs @@ -24,10 +24,10 @@ public async Task Create_WithValidInput_Returns201(string id) { ClientMovie source = new(TestData.Movies.BlackPanther) { Id = id }; - HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.MovieEndpoint, source, this.serializerOptions); + HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.MovieEndpoint, source, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.Created); - ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientMovie.Should().NotBeNull().And.HaveChangedMetadata(id, this.StartTime).And.BeEquivalentTo(source); InMemoryMovie inMemoryMovie = this.factory.GetServerEntityById(clientMovie.Id); @@ -43,10 +43,10 @@ public async Task Create_ExistingId_Returns409() InMemoryMovie existingMovie = this.factory.GetRandomMovie(); ClientMovie source = new(TestData.Movies.BlackPanther) { Id = existingMovie.Id }; - HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.MovieEndpoint, source, this.serializerOptions); + HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.MovieEndpoint, source, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.Conflict); - ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientMovie.Should().NotBeNull().And.HaveEquivalentMetadataTo(existingMovie).And.BeEquivalentTo(existingMovie); response.Headers.ETag.Should().BeETag($"\"{clientMovie.Version}\""); @@ -59,10 +59,10 @@ public async Task Create_SoftDeleted_Returns409() this.factory.SoftDelete(existingMovie); ClientMovie source = new(TestData.Movies.BlackPanther) { Id = existingMovie.Id }; - HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.MovieEndpoint, source, this.serializerOptions); + HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.MovieEndpoint, source, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.Conflict); - ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientMovie.Should().NotBeNull().And.HaveEquivalentMetadataTo(existingMovie).And.BeEquivalentTo(existingMovie); response.Headers.ETag.Should().BeETag($"\"{clientMovie.Version}\""); @@ -76,10 +76,10 @@ public async Task Create_ExistingId_WithACP_InView_Returns409() this.factory.SetupAccessControlProvider(true, m => m.Id == existingMovie.Id); ClientMovie source = new(TestData.Movies.BlackPanther) { Id = existingMovie.Id }; - HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.AuthorizedMovieEndpoint, source, this.serializerOptions); + HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.AuthorizedMovieEndpoint, source, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.Conflict); - ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientMovie.Should().NotBeNull().And.HaveEquivalentMetadataTo(existingMovie).And.BeEquivalentTo(existingMovie); } @@ -91,10 +91,10 @@ public async Task Create_ExistingId_WithACP_NotInView_Returns400() this.factory.SetupAccessControlProvider(true, m => m.Id == "id-that-does-not-exist"); ClientMovie source = new(TestData.Movies.BlackPanther) { Id = existingMovie.Id }; - HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.AuthorizedMovieEndpoint, source, this.serializerOptions); + HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.AuthorizedMovieEndpoint, source, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); - string content = await response.Content.ReadAsStringAsync(); + string content = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); content.Should().NotContain(existingMovie.Id); } @@ -112,10 +112,10 @@ public async Task Create_CanRoundtrip_Types() PointValue = GeographyPoint.Create(-122.333056, 47.609722) }; - HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.KitchenSinkEndpoint, source, this.serializerOptions); + HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.KitchenSinkEndpoint, source, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.Created); - ClientKitchenSink clientKitchenSink = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientKitchenSink clientKitchenSink = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientKitchenSink.Should().NotBeNull().And.HaveChangedMetadata(id, this.StartTime).And.BeEquivalentTo(source); InMemoryKitchenSink serverEntity = this.factory.GetServerEntityById(id); @@ -126,7 +126,7 @@ public async Task Create_CanRoundtrip_Types() public async Task Create_NonJsonData_Returns415() { const string content = "

Not JSON

"; - HttpResponseMessage response = await this.client.PostAsync(this.factory.MovieEndpoint, new StringContent(content, Encoding.UTF8, "text/html")); + HttpResponseMessage response = await this.client.PostAsync(this.factory.MovieEndpoint, new StringContent(content, Encoding.UTF8, "text/html"), TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); } @@ -163,7 +163,7 @@ public async Task Create_ValidationError_Returns400(string propName, object prop source[propName] = propValue; } - HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.MovieEndpoint, source, this.serializerOptions); + HttpResponseMessage response = await this.client.PostAsJsonAsync(this.factory.MovieEndpoint, source, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); } } diff --git a/tests/CommunityToolkit.Datasync.Server.Test/Service/Delete_Tests.cs b/tests/CommunityToolkit.Datasync.Server.Test/Service/Delete_Tests.cs index 04b14ff4..862b033f 100644 --- a/tests/CommunityToolkit.Datasync.Server.Test/Service/Delete_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Test/Service/Delete_Tests.cs @@ -18,7 +18,7 @@ public async Task Delete_ById_Returns204() { InMemoryMovie existingMovie = this.factory.GetRandomMovie(); - HttpResponseMessage response = await this.client.DeleteAsync($"{this.factory.MovieEndpoint}/{existingMovie.Id}"); + HttpResponseMessage response = await this.client.DeleteAsync($"{this.factory.MovieEndpoint}/{existingMovie.Id}", TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.NoContent); InMemoryMovie serverEntity = this.factory.GetServerEntityById(existingMovie.Id); @@ -38,13 +38,13 @@ public async Task Delete_WithVersioning_Works(string headerName, string value, H HttpRequestMessage request = new(HttpMethod.Delete, $"{this.factory.MovieEndpoint}/{existingMovie.Id}"); request.Headers.Add(headerName, etag); - HttpResponseMessage response = await this.client.SendAsync(request); + HttpResponseMessage response = await this.client.SendAsync(request, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(expectedStatusCode); if (expectedStatusCode == HttpStatusCode.PreconditionFailed) { InMemoryMovie serverEntity = this.factory.GetServerEntityById(existingMovie.Id); - ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientMovie.Should().HaveEquivalentMetadataTo(serverEntity).And.BeEquivalentTo(serverEntity); } } @@ -52,7 +52,7 @@ public async Task Delete_WithVersioning_Works(string headerName, string value, H [Fact] public async Task Delete_MissingId_Returns404() { - HttpResponseMessage response = await this.client.DeleteAsync($"{this.factory.MovieEndpoint}/missing"); + HttpResponseMessage response = await this.client.DeleteAsync($"{this.factory.MovieEndpoint}/missing", TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.NotFound); } @@ -63,7 +63,7 @@ public async Task Delete_NotSoftDeleted_Returns204() byte[] existingVersion = [.. existingMovie.Version]; DateTimeOffset existingUpdatedAt = (DateTimeOffset)existingMovie.UpdatedAt; - HttpResponseMessage response = await this.client.DeleteAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}"); + HttpResponseMessage response = await this.client.DeleteAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}", TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.NoContent); InMemoryMovie serverEntity = this.factory.GetServerEntityById(existingMovie.Id); @@ -79,7 +79,7 @@ public async Task Delete_SoftDeletedId_Returns410() InMemoryMovie existingMovie = this.factory.GetRandomMovie(); this.factory.SoftDelete(existingMovie); - HttpResponseMessage response = await this.client.DeleteAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}"); + HttpResponseMessage response = await this.client.DeleteAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}", TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.Gone); InMemoryMovie serverEntity = this.factory.GetServerEntityById(existingMovie.Id); diff --git a/tests/CommunityToolkit.Datasync.Server.Test/Service/Query_Tests.cs b/tests/CommunityToolkit.Datasync.Server.Test/Service/Query_Tests.cs index f0bbb67f..4f99e8e4 100644 --- a/tests/CommunityToolkit.Datasync.Server.Test/Service/Query_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Test/Service/Query_Tests.cs @@ -29,7 +29,7 @@ public class Query_Tests(ServiceApplicationFactory factory) : ServiceTest(factor [InlineData("$top=NaN", HttpStatusCode.BadRequest)] public async Task FailedQueryTest(string query, HttpStatusCode expectedStatusCode) { - HttpResponseMessage response = await this.client.GetAsync($"{this.factory.MovieEndpoint}?{query}"); + HttpResponseMessage response = await this.client.GetAsync($"{this.factory.MovieEndpoint}?{query}", TestContext.Current.CancellationToken); response.StatusCode.Should().Be(expectedStatusCode); } @@ -3903,9 +3903,9 @@ public async Task SelectQueryTest(bool sId, bool sUpdatedAt, bool sVersion, bool string query = $"{this.factory.MovieEndpoint}?$top=5&$skip=5&$select={string.Join(',', selection)}"; - HttpResponseMessage response = await this.client.GetAsync(query); + HttpResponseMessage response = await this.client.GetAsync(query, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); + string content = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); PageOfItems result = JsonSerializer.Deserialize>(content, this.serializerOptions); result.Should().NotBeNull(); result.Items.Should().NotBeNullOrEmpty(); diff --git a/tests/CommunityToolkit.Datasync.Server.Test/Service/Read_Tests.cs b/tests/CommunityToolkit.Datasync.Server.Test/Service/Read_Tests.cs index a83f6734..721e9567 100644 --- a/tests/CommunityToolkit.Datasync.Server.Test/Service/Read_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Test/Service/Read_Tests.cs @@ -18,10 +18,10 @@ public class Read_Tests(ServiceApplicationFactory factory) : ServiceTest(factory public async Task Read_Returns200() { InMemoryMovie existingMovie = this.factory.GetRandomMovie(); - HttpResponseMessage response = await this.client.GetAsync($"{this.factory.MovieEndpoint}/{existingMovie.Id}"); + HttpResponseMessage response = await this.client.GetAsync($"{this.factory.MovieEndpoint}/{existingMovie.Id}", TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.OK); - ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientMovie.Should().NotBeNull().And.HaveEquivalentMetadataTo(existingMovie).And.BeEquivalentTo(existingMovie); response.Headers.ETag.Should().BeETag($"\"{clientMovie.Version}\""); } @@ -36,12 +36,12 @@ public async Task Read_WithVersioning_Works(string headerName, string headerValu InMemoryMovie existingMovie = this.factory.GetRandomMovie(); HttpRequestMessage request = new(HttpMethod.Get, $"{this.factory.MovieEndpoint}/{existingMovie.Id}"); request.Headers.Add(headerName, headerValue ?? $"\"{Convert.ToBase64String(existingMovie.Version)}\""); - HttpResponseMessage response = await this.client.SendAsync(request); + HttpResponseMessage response = await this.client.SendAsync(request, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(expectedStatusCode); if (expectedStatusCode == HttpStatusCode.OK) { - ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientMovie.Should().NotBeNull().And.HaveEquivalentMetadataTo(existingMovie).And.BeEquivalentTo(existingMovie); response.Headers.ETag.Should().BeETag($"\"{clientMovie.Version}\""); } @@ -63,10 +63,10 @@ public async Task Read_CanRoundtripTypes() }; this.factory.Store(storedEntity); - HttpResponseMessage response = await this.client.GetAsync($"{this.factory.KitchenSinkEndpoint}/{storedEntity.Id}"); + HttpResponseMessage response = await this.client.GetAsync($"{this.factory.KitchenSinkEndpoint}/{storedEntity.Id}", TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.OK); - ClientKitchenSink clientEntity = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientKitchenSink clientEntity = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientEntity.Should().NotBeNull().And.HaveEquivalentMetadataTo(storedEntity).And.BeEquivalentTo(storedEntity); response.Headers.ETag.Should().BeETag($"\"{clientEntity.Version}\""); } @@ -116,10 +116,10 @@ public async Task Read_SerializationTests() this.factory.Store(entity1); this.factory.Store(entity2); - HttpResponseMessage response = await this.client.GetAsync($"{this.factory.KitchenSinkEndpoint}/{entity1.Id}"); + HttpResponseMessage response = await this.client.GetAsync($"{this.factory.KitchenSinkEndpoint}/{entity1.Id}", TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.OK); - ClientObject actual = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientObject actual = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); actual.Data["id"].Should().BeJsonElement(entity1.Id); actual.Data["booleanValue"].Should().BeJsonElement(true); @@ -142,10 +142,10 @@ public async Task Read_SerializationTests() actual.Data["stringValue"].Should().BeJsonElement("state=none"); actual.Data["timeOnlyValue"].Should().BeJsonElement("09:52:35.321"); - HttpResponseMessage response2 = await this.client.GetAsync($"{this.factory.KitchenSinkEndpoint}/{entity2.Id}"); + HttpResponseMessage response2 = await this.client.GetAsync($"{this.factory.KitchenSinkEndpoint}/{entity2.Id}", TestContext.Current.CancellationToken); response2.StatusCode.Should().Be(HttpStatusCode.OK); - ClientObject actual2 = await response2.Content.ReadFromJsonAsync(); + ClientObject actual2 = await response2.Content.ReadFromJsonAsync(TestContext.Current.CancellationToken); actual2.Data["nullableDouble"].Should().BeJsonElement(42.42); actual2.Data["nullableEnumValue"].Should().BeJsonElement("Failed"); @@ -154,7 +154,7 @@ public async Task Read_SerializationTests() [Fact] public async Task Read_MissingId_Returns404() { - HttpResponseMessage response = await this.client.GetAsync($"{this.factory.MovieEndpoint}/missing"); + HttpResponseMessage response = await this.client.GetAsync($"{this.factory.MovieEndpoint}/missing", TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.NotFound); } @@ -162,10 +162,10 @@ public async Task Read_MissingId_Returns404() public async Task Read_SoftDeleted_NotDeleted_Returns200() { InMemoryMovie existingMovie = this.factory.GetRandomMovie(); - HttpResponseMessage response = await this.client.GetAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}"); + HttpResponseMessage response = await this.client.GetAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}", TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.OK); - ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientMovie.Should().NotBeNull().And.HaveEquivalentMetadataTo(existingMovie).And.BeEquivalentTo(existingMovie); response.Headers.ETag.Should().BeETag($"\"{clientMovie.Version}\""); } @@ -175,7 +175,7 @@ public async Task Read_SoftDeleted_Deleted_Returns410() { InMemoryMovie existingMovie = this.factory.GetRandomMovie(); this.factory.SoftDelete(existingMovie); - HttpResponseMessage response = await this.client.GetAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}"); + HttpResponseMessage response = await this.client.GetAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}", TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.Gone); } @@ -184,10 +184,10 @@ public async Task Read_SoftDeleted_Deleted_WithIncludeDeleted_Returns200() { InMemoryMovie existingMovie = this.factory.GetRandomMovie(); this.factory.SoftDelete(existingMovie); - HttpResponseMessage response = await this.client.GetAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}?__includedeleted=true"); + HttpResponseMessage response = await this.client.GetAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}?__includedeleted=true", TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.OK); - ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientMovie.Should().NotBeNull().And.HaveEquivalentMetadataTo(existingMovie).And.BeEquivalentTo(existingMovie); response.Headers.ETag.Should().BeETag($"\"{clientMovie.Version}\""); } diff --git a/tests/CommunityToolkit.Datasync.Server.Test/Service/Replace_Tests.cs b/tests/CommunityToolkit.Datasync.Server.Test/Service/Replace_Tests.cs index 8c5a297d..5340d04b 100644 --- a/tests/CommunityToolkit.Datasync.Server.Test/Service/Replace_Tests.cs +++ b/tests/CommunityToolkit.Datasync.Server.Test/Service/Replace_Tests.cs @@ -21,11 +21,11 @@ public class Replace_Tests(ServiceApplicationFactory factory) : ServiceTest(fact public async Task Replace_Returns200() { ClientMovie existingMovie = new(this.factory.GetRandomMovie()) { Title = "New Title" }; - HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.MovieEndpoint}/{existingMovie.Id}", existingMovie, this.serializerOptions); + HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.MovieEndpoint}/{existingMovie.Id}", existingMovie, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.OK); #if CAPTURE_STRING_JSON - string jsonContent = await response.Content.ReadAsStringAsync(); + string jsonContent = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); ClientMovie clientMovie = JsonSerializer.Deserialize(jsonContent, this.serializerOptions); #else ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); @@ -51,12 +51,12 @@ public async Task Replace_WithVersioning_Works(string headerName, string headerV HttpRequestMessage request = new(HttpMethod.Put, $"{this.factory.MovieEndpoint}/{existingMovie.Id}") { Content = new StringContent(content, Encoding.UTF8, "application/json") }; request.Headers.Add(headerName, etag); - HttpResponseMessage response = await this.client.SendAsync(request); + HttpResponseMessage response = await this.client.SendAsync(request, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(expectedStatusCode); if (expectedStatusCode == HttpStatusCode.OK) { - ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientMovie.Should().NotBeNull().And.HaveChangedMetadata(existingMovie, this.StartTime).And.BeEquivalentTo(existingMovie); InMemoryMovie inMemoryMovie = this.factory.GetServerEntityById(clientMovie.Id); @@ -70,7 +70,7 @@ public async Task Replace_MissingId_Returns404() { InMemoryMovie existingMovie = this.factory.GetRandomMovie(); ClientMovie source = new(existingMovie) { Id = "missing" }; - HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.MovieEndpoint}/missing", source, this.serializerOptions); + HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.MovieEndpoint}/missing", source, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.NotFound, "Movie = {0}", existingMovie.Id); } @@ -78,7 +78,7 @@ public async Task Replace_MissingId_Returns404() public async Task Replace_IdMismatch_Returns400() { ClientMovie existingMovie = new(this.factory.GetRandomMovie()) { Title = "New Title" }; - HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.MovieEndpoint}/different-id", existingMovie, this.serializerOptions); + HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.MovieEndpoint}/different-id", existingMovie, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); } @@ -86,10 +86,10 @@ public async Task Replace_IdMismatch_Returns400() public async Task Replace_NotSoftDeleted_Works() { InMemoryMovie existingMovie = this.factory.GetRandomMovie(); - HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}", existingMovie, this.serializerOptions); + HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}", existingMovie, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.OK); - ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientMovie.Should().NotBeNull().And.HaveChangedMetadata(existingMovie, this.StartTime).And.BeEquivalentTo(existingMovie); InMemoryMovie inMemoryMovie = this.factory.GetServerEntityById(clientMovie.Id); @@ -102,7 +102,7 @@ public async Task Replace_SoftDeleted_NotUndeleting_Returns410() { InMemoryMovie existingMovie = this.factory.GetRandomMovie(); this.factory.SoftDelete(existingMovie); - HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}", existingMovie, this.serializerOptions); + HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}", existingMovie, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.Gone); } @@ -111,7 +111,7 @@ public async Task Replace_SoftDeleted_Undeleting_Returns410() { InMemoryMovie existingMovie = this.factory.GetRandomMovie(); this.factory.SoftDelete(existingMovie); - HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}", existingMovie, this.serializerOptions); + HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}", existingMovie, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.Gone); } @@ -121,10 +121,10 @@ public async Task Replace_SoftDeleted_Undeleting_WithShowDeleted_Returns200() InMemoryMovie existingMovie = this.factory.GetRandomMovie(); this.factory.SoftDelete(existingMovie); existingMovie.Deleted = false; - HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}?__includedeleted=true", existingMovie, this.serializerOptions); + HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.SoftDeletedMovieEndpoint}/{existingMovie.Id}?__includedeleted=true", existingMovie, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.OK); - ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions); + ClientMovie clientMovie = await response.Content.ReadFromJsonAsync(this.serializerOptions, TestContext.Current.CancellationToken); clientMovie.Should().NotBeNull().And.HaveChangedMetadata(existingMovie, this.StartTime).And.BeEquivalentTo(existingMovie); clientMovie.Deleted.Should().BeFalse(); @@ -137,7 +137,7 @@ public async Task Replace_SoftDeleted_Undeleting_WithShowDeleted_Returns200() public async Task Replace_NonJsonData_Returns415() { const string content = "

Not JSON

"; - HttpResponseMessage response = await this.client.PutAsync($"{this.factory.MovieEndpoint}/1", new StringContent(content, Encoding.UTF8, "text/html")); + HttpResponseMessage response = await this.client.PutAsync($"{this.factory.MovieEndpoint}/1", new StringContent(content, Encoding.UTF8, "text/html"), TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); } @@ -153,7 +153,7 @@ public async Task Replace_Unauthorized_Returns401() InMemoryMovie inMemoryMovie = this.factory.GetRandomMovie(); ClientMovie existingMovie = new(inMemoryMovie) { Title = "New Title" }; - HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.AuthorizedMovieEndpoint}/{existingMovie.Id}", existingMovie, this.serializerOptions); + HttpResponseMessage response = await this.client.PutAsJsonAsync($"{this.factory.AuthorizedMovieEndpoint}/{existingMovie.Id}", existingMovie, this.serializerOptions, TestContext.Current.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); // Ensure that the access provider was called with the existing movie, not the new movie