diff --git a/src/WireMock.Net.AwesomeAssertions/Assertions/WireMockAssertions.cs b/src/WireMock.Net.AwesomeAssertions/Assertions/WireMockAssertions.cs index 0ce9f3a1..ab63e823 100644 --- a/src/WireMock.Net.AwesomeAssertions/Assertions/WireMockAssertions.cs +++ b/src/WireMock.Net.AwesomeAssertions/Assertions/WireMockAssertions.cs @@ -18,7 +18,7 @@ public partial class WireMockAssertions public WireMockAssertions(IWireMockServer subject, int? callsCount, AssertionChain chain) { CallsCount = callsCount; - RequestMessages = subject.LogEntries.Select(logEntry => logEntry.RequestMessage).ToList(); + RequestMessages = subject.LogEntries.Select(logEntry => logEntry.RequestMessage).OfType().ToList(); _chain = chain; } diff --git a/src/WireMock.Net.Minimal/Server/WireMockServer.LogEntries.cs b/src/WireMock.Net.Minimal/Server/WireMockServer.LogEntries.cs index 7bc1a6df..98d03574 100644 --- a/src/WireMock.Net.Minimal/Server/WireMockServer.LogEntries.cs +++ b/src/WireMock.Net.Minimal/Server/WireMockServer.LogEntries.cs @@ -1,9 +1,6 @@ // Copyright © WireMock.Net -using System; -using System.Collections.Generic; using System.Collections.Specialized; -using System.Linq; using JetBrains.Annotations; using Stef.Validation; using WireMock.Logging; diff --git a/test/WireMock.Net.Tests/Extensions/HttpClientExtensions.cs b/test/WireMock.Net.Tests/Extensions/HttpClientExtensions.cs index 4976e5ff..7a5341d4 100644 --- a/test/WireMock.Net.Tests/Extensions/HttpClientExtensions.cs +++ b/test/WireMock.Net.Tests/Extensions/HttpClientExtensions.cs @@ -8,12 +8,12 @@ namespace System.Net.Http; /// internal static class HttpClientExtensions { - public static Task GetStreamAsync(this HttpClient client, Uri requestUri, CancellationToken _) + public static Task GetStreamAsync(this HttpClient client, string requestUri, CancellationToken _) { return client.GetStreamAsync(requestUri); } - public static Task GetAsync(this HttpClient client, Uri requestUri, CancellationToken _) + public static Task GetAsync(this HttpClient client, string requestUri, CancellationToken _) { return client.GetAsync(requestUri); } diff --git a/test/WireMock.Net.Tests/Extensions/HttpContentExtensions.cs b/test/WireMock.Net.Tests/Extensions/HttpContentExtensions.cs index 0c48d0c8..07488a42 100644 --- a/test/WireMock.Net.Tests/Extensions/HttpContentExtensions.cs +++ b/test/WireMock.Net.Tests/Extensions/HttpContentExtensions.cs @@ -13,9 +13,19 @@ internal static class HttpContentExtensions return content.ReadAsStringAsync(); } + public static Task ReadAsStringAsync(this StringContent content, CancellationToken _) + { + return content.ReadAsStringAsync(); + } + public static Task ReadAsByteArrayAsync(this HttpContent content, CancellationToken _) { return content.ReadAsByteArrayAsync(); } + + public static Task ReadAsByteArrayAsync(this ByteArrayContent content, CancellationToken _) + { + return content.ReadAsByteArrayAsync(); + } } #endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/FluentAssertions/WireMockAssertionsTests.cs b/test/WireMock.Net.Tests/FluentAssertions/WireMockAssertionsTests.cs index 2d95e050..e1d02c53 100644 --- a/test/WireMock.Net.Tests/FluentAssertions/WireMockAssertionsTests.cs +++ b/test/WireMock.Net.Tests/FluentAssertions/WireMockAssertionsTests.cs @@ -16,6 +16,8 @@ namespace WireMock.Net.Tests.FluentAssertions; public class WireMockAssertionsTests : IDisposable { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + private readonly WireMockServer _server; private readonly HttpClient _httpClient; private readonly int _portUsed; @@ -26,14 +28,13 @@ public class WireMockAssertionsTests : IDisposable _server.Given(Request.Create().UsingAnyMethod()).RespondWith(Response.Create().WithSuccess()); _portUsed = _server.Ports.First(); - - _httpClient = new HttpClient { BaseAddress = new Uri(_server.Url!) }; + _httpClient = _server.CreateClient(); } [Fact] public async Task HaveReceivedNoCalls_AtAbsoluteUrl_WhenACallWasNotMadeToAbsoluteUrl_Should_BeOK() { - await _httpClient.GetAsync("xxx", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("xxx", _ct); _server.Should() .HaveReceivedNoCalls() @@ -43,7 +44,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceived0Calls_AtAbsoluteUrl_WhenACallWasNotMadeToAbsoluteUrl_Should_BeOK() { - await _httpClient.GetAsync("xxx", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("xxx", _ct); _server.Should() .HaveReceived(0).Calls() @@ -53,7 +54,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceived1Calls_AtAbsoluteUrl_WhenACallWasMadeToAbsoluteUrl_Should_BeOK() { - await _httpClient.GetAsync("anyurl", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("anyurl", _ct); _server.Should() .HaveReceived(1).Calls() @@ -63,7 +64,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceived1Calls_AtAbsoluteUrl2_WhenACallWasMadeToAbsoluteUrl_Should_BeOK() { - await _httpClient.GetAsync("anyurl", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("anyurl", _ct); _server.Should() .HaveReceived(1).Calls() @@ -73,7 +74,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceived1Calls_AtAbsoluteUrlUsingPost_WhenAPostCallWasMadeToAbsoluteUrl_Should_BeOK() { - await _httpClient.PostAsync("anyurl", new StringContent(""), TestContext.Current.CancellationToken); + await _httpClient.PostAsync("anyurl", new StringContent(""), _ct); _server.Should() .HaveReceived(1).Calls() @@ -85,9 +86,9 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceived2Calls_AtAbsoluteUrl_WhenACallWasMadeToAbsoluteUrl_Should_BeOK() { - await _httpClient.GetAsync("anyurl", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("anyurl", _ct); - await _httpClient.GetAsync("anyurl", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("anyurl", _ct); _server.Should() .HaveReceived(2).Calls() @@ -97,7 +98,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_AtAbsoluteUrl_WhenACallWasMadeToAbsoluteUrl_Should_BeOK() { - await _httpClient.GetAsync("anyurl", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("anyurl", _ct); _server.Should() .HaveReceivedACall() @@ -107,7 +108,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_AtAbsoluteUrlWildcardMatcher_WhenACallWasMadeToAbsoluteUrl_Should_BeOK() { - await _httpClient.GetAsync("anyurl", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("anyurl", _ct); _server.Should() .HaveReceivedACall() @@ -129,7 +130,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_AtAbsoluteUrl_Should_ThrowWhenNoCallsMatchingTheAbsoluteUrlWereMade() { - await _httpClient.GetAsync("", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("", _ct); Action act = () => _server.Should() .HaveReceivedACall() @@ -143,7 +144,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedNoCalls_AtAbsolutePath_WhenACallWasNotMadeToAbsolutePath_Should_BeOK() { - await _httpClient.GetAsync("xxx", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("xxx", _ct); _server.Should() .HaveReceivedNoCalls() @@ -153,7 +154,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceived0Calls_AtAbsolutePath_WhenACallWasNotMadeToAbsolutePath_Should_BeOK() { - await _httpClient.GetAsync("xxx", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("xxx", _ct); _server.Should() .HaveReceived(0).Calls() @@ -163,7 +164,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceived1Calls_AtAbsolutePath_WhenACallWasMadeToAbsolutePath_Should_BeOK() { - await _httpClient.GetAsync("anypath", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("anypath", _ct); _server.Should() .HaveReceived(1).Calls() @@ -173,7 +174,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceived1Calls_AtAbsolutePathUsingPost_WhenAPostCallWasMadeToAbsolutePath_Should_BeOK() { - await _httpClient.PostAsync("anypath", new StringContent(""), TestContext.Current.CancellationToken); + await _httpClient.PostAsync("anypath", new StringContent(""), _ct); _server.Should() .HaveReceived(1).Calls() @@ -185,9 +186,9 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceived2Calls_AtAbsolutePath_WhenACallWasMadeToAbsolutePath_Should_BeOK() { - await _httpClient.GetAsync("anypath", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("anypath", _ct); - await _httpClient.GetAsync("anypath", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("anypath", _ct); _server.Should() .HaveReceived(2).Calls() @@ -197,7 +198,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_AtAbsolutePath_WhenACallWasMadeToAbsolutePath_Should_BeOK() { - await _httpClient.GetAsync("anypath", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("anypath", _ct); _server.Should() .HaveReceivedACall() @@ -207,7 +208,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_AtAbsolutePathWildcardMatcher_WhenACallWasMadeToAbsolutePath_Should_BeOK() { - await _httpClient.GetAsync("anypath", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("anypath", _ct); _server.Should() .HaveReceivedACall() @@ -229,7 +230,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_AtAbsolutePath_Should_ThrowWhenNoCallsMatchingTheAbsolutePathWereMade() { - await _httpClient.GetAsync("", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("", _ct); Action act = () => _server.Should() .HaveReceivedACall() @@ -244,7 +245,7 @@ public class WireMockAssertionsTests : IDisposable public async Task HaveReceivedACall_WithHeader_WhenACallWasMadeWithExpectedHeader_Should_BeOK() { _httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer a"); - await _httpClient.GetAsync("", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("", _ct); _server.Should() .HaveReceivedACall() @@ -255,7 +256,7 @@ public class WireMockAssertionsTests : IDisposable public async Task HaveReceivedACall_WithHeader_WhenACallWasMadeWithExpectedHeaderWithValue_Should_BeOK() { _httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer a"); - await _httpClient.GetAsync("", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("", _ct); _server.Should() .HaveReceivedACall() @@ -267,10 +268,10 @@ public class WireMockAssertionsTests : IDisposable { _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - await _httpClient.GetAsync("1", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("1", _ct); _httpClient.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("EN")); - await _httpClient.GetAsync("2", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("2", _ct); _server.Should() .HaveReceivedACall() @@ -282,7 +283,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_WithHeader_Should_ThrowWhenNoCallsMatchingTheHeaderNameWereMade() { - await _httpClient.GetAsync("", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("", _ct); Action act = () => _server.Should() .HaveReceivedACall() @@ -298,7 +299,7 @@ public class WireMockAssertionsTests : IDisposable { _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - await _httpClient.GetAsync("", TestContext.Current.CancellationToken); + await _httpClient.GetAsync("", _ct); Action act = () => _server.Should() .HaveReceivedACall() @@ -316,7 +317,7 @@ public class WireMockAssertionsTests : IDisposable httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - await httpClient.GetAsync("", TestContext.Current.CancellationToken); + await httpClient.GetAsync("", _ct); Action act = () => _server.Should() .HaveReceivedACall() @@ -331,7 +332,7 @@ public class WireMockAssertionsTests : IDisposable public async Task HaveReceivedACall_WithHeader_ShouldCheckAllRequests() { // Arrange - var cancellationToken = TestContext.Current.CancellationToken; + var cancellationToken = _ct; using var server = WireMockServer.Start(); using var client1 = server.CreateClient(); @@ -371,7 +372,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_AtUrl_WhenACallWasMadeToUrl_Should_BeOK() { - await _httpClient.GetAsync("anyurl"); + await _httpClient.GetAsync("anyurl", _ct); _server.Should() .HaveReceivedACall() @@ -381,7 +382,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_AtUrlWildcardMatcher_WhenACallWasMadeToUrl_Should_BeOK() { - await _httpClient.GetAsync("anyurl"); + await _httpClient.GetAsync("anyurl", _ct); _server.Should() .HaveReceivedACall() @@ -403,7 +404,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_AtUrl_Should_ThrowWhenNoCallsMatchingTheUrlWereMade() { - await _httpClient.GetAsync(""); + await _httpClient.GetAsync("", _ct); Action act = () => _server.Should() .HaveReceivedACall() @@ -421,7 +422,7 @@ public class WireMockAssertionsTests : IDisposable _server.Given(Request.Create().UsingAnyMethod()) .RespondWith(Response.Create().WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999" })); - await _httpClient.GetAsync(""); + await _httpClient.GetAsync("", _ct); _server.Should() .HaveReceivedACall() @@ -451,7 +452,7 @@ public class WireMockAssertionsTests : IDisposable _server.Given(Request.Create().UsingAnyMethod()) .RespondWith(Response.Create().WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999" })); - await _httpClient.GetAsync(""); + await _httpClient.GetAsync("", _ct); Action act = () => _server.Should() .HaveReceivedACall() @@ -465,7 +466,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_FromClientIP_whenACallWasMadeFromClientIP_Should_BeOK() { - await _httpClient.GetAsync(""); + await _httpClient.GetAsync("", _ct); var clientIP = _server.LogEntries.Last().RequestMessage.ClientIP; _server.Should() @@ -488,7 +489,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_FromClientIP_Should_ThrowWhenNoCallsFromClientIPWereMade() { - await _httpClient.GetAsync(""); + await _httpClient.GetAsync("", _ct); var clientIP = _server.LogEntries.Last().RequestMessage.ClientIP; Action act = () => _server.Should() @@ -503,7 +504,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedNoCalls_UsingPost_WhenACallWasNotMadeUsingPost_Should_BeOK() { - await _httpClient.GetAsync("anyurl"); + await _httpClient.GetAsync("anyurl", _ct); _server.Should() .HaveReceivedNoCalls() @@ -515,9 +516,9 @@ public class WireMockAssertionsTests : IDisposable { var tasks = new[] { - _httpClient.DeleteAsync("anyurl"), - _httpClient.DeleteAsync("anyurl"), - _httpClient.GetAsync("anyurl") + _httpClient.DeleteAsync("anyurl", _ct), + _httpClient.DeleteAsync("anyurl", _ct), + _httpClient.GetAsync("anyurl", _ct) }; await Task.WhenAll(tasks); @@ -542,7 +543,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_UsingOptions_Should_ThrowWhenCallsWereNotMadeUsingOptions() { - await _httpClient.PostAsync("anyurl", new StringContent("anycontent")); + await _httpClient.PostAsync("anyurl", new StringContent("anycontent"), _ct); Action act = () => _server.Should() .HaveReceivedACall() @@ -563,7 +564,7 @@ public class WireMockAssertionsTests : IDisposable _httpClient.DefaultRequestHeaders.Add("Host", new Uri(_server.Urls[0]).Authority); - await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("CONNECT"), "anyurl")); + await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("CONNECT"), "anyurl"), _ct); _server.Should() .HaveReceivedACall() @@ -574,7 +575,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_UsingDelete_WhenACallWasMadeUsingDelete_Should_BeOK() { - await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("DELETE"), "anyurl")); + await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("DELETE"), "anyurl"), _ct); _server.Should() .HaveReceivedACall() @@ -584,7 +585,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_UsingGet_WhenACallWasMadeUsingGet_Should_BeOK() { - await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("GET"), "anyurl")); + await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("GET"), "anyurl"), _ct); _server.Should() .HaveReceivedACall() @@ -594,7 +595,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_UsingHead_WhenACallWasMadeUsingHead_Should_BeOK() { - await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("HEAD"), "anyurl")); + await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("HEAD"), "anyurl"), _ct); _server.Should() .HaveReceivedACall() @@ -604,7 +605,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_UsingOptions_WhenACallWasMadeUsingOptions_Should_BeOK() { - await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("OPTIONS"), "anyurl")); + await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("OPTIONS"), "anyurl"), _ct); _server.Should() .HaveReceivedACall() @@ -616,7 +617,7 @@ public class WireMockAssertionsTests : IDisposable [InlineData("Post")] public async Task HaveReceivedACall_UsingPost_WhenACallWasMadeUsingPost_Should_BeOK(string method) { - await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod(method), "anyurl")); + await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod(method), "anyurl"), _ct); _server.Should() .HaveReceivedACall() @@ -646,9 +647,9 @@ public class WireMockAssertionsTests : IDisposable var tasks = new[] { - httpClient.GetAsync($"{server.Url}/a"), - httpClient.PostAsync($"{server.Url}/b", new StringContent("B")), - httpClient.PostAsync($"{server.Url}/c", new StringContent("C")) + httpClient.GetAsync($"{server.Url}/a", _ct), + httpClient.PostAsync($"{server.Url}/b", new StringContent("B"), _ct), + httpClient.PostAsync($"{server.Url}/c", new StringContent("C"), _ct) }; await Task.WhenAll(tasks); @@ -701,7 +702,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_UsingPatch_WhenACallWasMadeUsingPatch_Should_BeOK() { - await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("PATCH"), "anyurl")); + await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("PATCH"), "anyurl"), _ct); _server.Should() .HaveReceivedACall() @@ -711,7 +712,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_UsingPut_WhenACallWasMadeUsingPut_Should_BeOK() { - await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("PUT"), "anyurl")); + await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("PUT"), "anyurl"), _ct); _server.Should() .HaveReceivedACall() @@ -721,7 +722,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_UsingTrace_WhenACallWasMadeUsingTrace_Should_BeOK() { - await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("TRACE"), "anyurl")); + await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("TRACE"), "anyurl"), _ct); _server.Should() .HaveReceivedACall() @@ -731,7 +732,7 @@ public class WireMockAssertionsTests : IDisposable [Fact] public async Task HaveReceivedACall_UsingAnyMethod_WhenACallWasMadeUsingGet_Should_BeOK() { - await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("GET"), "anyurl")); + await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("GET"), "anyurl"), _ct); _server.Should() .HaveReceivedACall() @@ -779,7 +780,7 @@ public class WireMockAssertionsTests : IDisposable // Act var httpClient = new HttpClient(); - await httpClient.PostAsync($"{server.Url}/a", new StringContent("x")); + await httpClient.PostAsync($"{server.Url}/a", new StringContent("x"), _ct); // Assert server @@ -834,7 +835,7 @@ public class WireMockAssertionsTests : IDisposable { x = "y" }; - await httpClient.PostAsJsonAsync($"{server.Url}/a", requestBody); + await httpClient.PostAsJsonAsync($"{server.Url}/a", requestBody, _ct); // Assert server @@ -889,7 +890,7 @@ public class WireMockAssertionsTests : IDisposable { x = "123" }; - await httpClient.PostAsJsonAsync($"{server.Url}/a", requestBody); + await httpClient.PostAsJsonAsync($"{server.Url}/a", requestBody, _ct); // Assert Action act = () => server @@ -920,7 +921,7 @@ public class WireMockAssertionsTests : IDisposable // Act var httpClient = new HttpClient(); - await httpClient.PostAsync($"{server.Url}/a", new StringContent("123")); + await httpClient.PostAsync($"{server.Url}/a", new StringContent("123"), _ct); // Assert Action act = () => server @@ -951,7 +952,7 @@ public class WireMockAssertionsTests : IDisposable // Act var httpClient = new HttpClient(); - await httpClient.PostAsync($"{server.Url}/a", new ByteArrayContent([5])); + await httpClient.PostAsync($"{server.Url}/a", new ByteArrayContent([5]), _ct); // Assert Action act = () => server @@ -982,7 +983,7 @@ public class WireMockAssertionsTests : IDisposable // Act var httpClient = new HttpClient(); - await httpClient.PutAsync($"{server.Url}/a", new ByteArrayContent([100])); + await httpClient.PutAsync($"{server.Url}/a", new ByteArrayContent([100]), _ct); // Assert server @@ -1025,7 +1026,7 @@ public class WireMockAssertionsTests : IDisposable // Act var httpClient = new HttpClient(); - await httpClient.PostAsync($"{server.Url}/a", new StringContent("x")); + await httpClient.PostAsync($"{server.Url}/a", new StringContent("x"), _ct); // Assert server @@ -1063,13 +1064,13 @@ public class WireMockAssertionsTests : IDisposable // Act : HTTP GET using var httpClient = new HttpClient(); - await httpClient.GetAsync(server.Url!); + await httpClient.GetAsync(server.Url, _ct); // Act : HTTP POST - var request = new HttpRequestMessage(HttpMethod.Post, server.Url!); + var request = new HttpRequestMessage(HttpMethod.Post, server.Url); request.Headers.Add("TestHeader", ["Value", "Value2"]); - await httpClient.SendAsync(request); + await httpClient.SendAsync(request, _ct); // Assert server.Should().HaveReceivedACall().UsingPost().And.WithHeader("TestHeader", ["Value", "Value2"]); @@ -1088,13 +1089,13 @@ public class WireMockAssertionsTests : IDisposable // Act : HTTP GET using var httpClient = new HttpClient(); - await httpClient.GetAsync(server.Url!); + await httpClient.GetAsync(server.Url, _ct); // Act : HTTP POST - var request = new HttpRequestMessage(HttpMethod.Post, server.Url!); + var request = new HttpRequestMessage(HttpMethod.Post, server.Url); request.Headers.Add("TestHeader", ["Value", "Value2"]); - await httpClient.SendAsync(request); + await httpClient.SendAsync(request, _ct); // Assert server.Should().HaveReceivedACall().UsingPost().And.WitHeaderKey("TestHeader"); diff --git a/test/WireMock.Net.Tests/Http/ByteArrayContentHelperTests.cs b/test/WireMock.Net.Tests/Http/ByteArrayContentHelperTests.cs index 6cbe0a02..0a9c2e6c 100644 --- a/test/WireMock.Net.Tests/Http/ByteArrayContentHelperTests.cs +++ b/test/WireMock.Net.Tests/Http/ByteArrayContentHelperTests.cs @@ -1,5 +1,6 @@ // Copyright © WireMock.Net +using System.Net.Http; using System.Net.Http.Headers; using System.Text; using AwesomeAssertions; @@ -9,6 +10,8 @@ namespace WireMock.Net.Tests.Http; public class ByteArrayContentHelperTests { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + [Fact] public async Task ByteArrayContentHelperTests_Create_WithNullContentType() { @@ -20,7 +23,7 @@ public class ByteArrayContentHelperTests // Assert result.Headers.ContentType.Should().BeNull(); - (await result.ReadAsByteArrayAsync()).Should().BeEquivalentTo(content); + (await result.ReadAsByteArrayAsync(_ct)).Should().BeEquivalentTo(content); } [Theory] @@ -37,7 +40,7 @@ public class ByteArrayContentHelperTests var result = ByteArrayContentHelper.Create(content, contentType); // Assert - result.Headers.ContentType.ToString().Should().Be(expected); - (await result.ReadAsByteArrayAsync()).Should().BeEquivalentTo(content); + result.Headers.ContentType?.ToString().Should().Be(expected); + (await result.ReadAsByteArrayAsync(_ct)).Should().BeEquivalentTo(content); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Http/HttpRequestMessageHelperTests.cs b/test/WireMock.Net.Tests/Http/HttpRequestMessageHelperTests.cs index a5436393..e2eab7c7 100644 --- a/test/WireMock.Net.Tests/Http/HttpRequestMessageHelperTests.cs +++ b/test/WireMock.Net.Tests/Http/HttpRequestMessageHelperTests.cs @@ -1,5 +1,6 @@ // Copyright © WireMock.Net +using System.Net.Http; using System.Text; using AwesomeAssertions; using NFluent; @@ -14,6 +15,8 @@ public class HttpRequestMessageHelperTests { private const string ClientIp = "::1"; + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + [Fact] public void HttpRequestMessageHelper_Create() { @@ -43,7 +46,7 @@ public class HttpRequestMessageHelperTests var message = HttpRequestMessageHelper.Create(request, "http://url"); // Assert - Check.That(await message.Content!.ReadAsByteArrayAsync()).ContainsExactly(Encoding.UTF8.GetBytes("hi")); + Check.That(await message.Content!.ReadAsByteArrayAsync(_ct)).ContainsExactly(Encoding.UTF8.GetBytes("hi")); } [Fact] @@ -61,7 +64,7 @@ public class HttpRequestMessageHelperTests var message = HttpRequestMessageHelper.Create(request, "http://url"); // Assert - Check.That(await message.Content!.ReadAsStringAsync()).Equals("0123"); + Check.That(await message.Content!.ReadAsStringAsync(_ct)).Equals("0123"); } [Fact] @@ -79,7 +82,7 @@ public class HttpRequestMessageHelperTests var message = HttpRequestMessageHelper.Create(request, "http://url"); // Assert - Check.That(await message.Content!.ReadAsStringAsync()).Equals("{\"x\":42}"); + Check.That(await message.Content!.ReadAsStringAsync(_ct)).Equals("{\"x\":42}"); } [Fact] @@ -98,7 +101,7 @@ public class HttpRequestMessageHelperTests var message = HttpRequestMessageHelper.Create(request, "http://url"); // Assert - Check.That(await message.Content!.ReadAsStringAsync()).Equals("{\"x\":42}"); + Check.That(await message.Content!.ReadAsStringAsync(_ct)).Equals("{\"x\":42}"); Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/json"); } @@ -118,7 +121,7 @@ public class HttpRequestMessageHelperTests var message = HttpRequestMessageHelper.Create(request, "http://url"); // Assert - Check.That(await message.Content!.ReadAsStringAsync()).Equals("{\"x\":42}"); + Check.That(await message.Content!.ReadAsStringAsync(_ct)).Equals("{\"x\":42}"); Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/json; charset=utf-8"); } @@ -139,7 +142,7 @@ public class HttpRequestMessageHelperTests var message = HttpRequestMessageHelper.Create(request, "http://url"); // Assert - Check.That(await message.Content!.ReadAsStringAsync()).Equals("{\"x\":42}"); + Check.That(await message.Content!.ReadAsStringAsync(_ct)).Equals("{\"x\":42}"); Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("multipart/form-data"); } @@ -239,7 +242,7 @@ public class HttpRequestMessageHelperTests var message = HttpRequestMessageHelper.Create(request, "http://url"); // Assert - Check.That(await message.Content!.ReadAsStringAsync()).Equals(body); + (await message.Content!.ReadAsStringAsync(_ct)).Should().Be(body); Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("multipart/form-data"); } diff --git a/test/WireMock.Net.Tests/Http/StringContentHelperTests.cs b/test/WireMock.Net.Tests/Http/StringContentHelperTests.cs index a4317ed8..83089352 100644 --- a/test/WireMock.Net.Tests/Http/StringContentHelperTests.cs +++ b/test/WireMock.Net.Tests/Http/StringContentHelperTests.cs @@ -1,5 +1,6 @@ // Copyright © WireMock.Net +using System.Net.Http; using System.Net.Http.Headers; using AwesomeAssertions; using WireMock.Http; @@ -8,15 +9,17 @@ namespace WireMock.Net.Tests.Http; public class StringContentHelperTests { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + [Fact] - public void StringContentHelper_Create_WithNullContentType() + public async Task StringContentHelper_Create_WithNullContentType() { // Act var result = StringContentHelper.Create("test", null); // Assert result.Headers.ContentType.Should().BeNull(); - result.ReadAsStringAsync().Result.Should().Be("test"); + (await result.ReadAsStringAsync(_ct)).Should().Be("test"); } [Theory] @@ -24,7 +27,7 @@ public class StringContentHelperTests [InlineData("application/soap+xml", "application/soap+xml")] [InlineData("application/soap+xml;charset=UTF-8", "application/soap+xml; charset=UTF-8")] [InlineData("application/soap+xml;charset=UTF-8;action=\"http://myCompany.Customer.Contract/ICustomerService/GetSomeConfiguration\"", "application/soap+xml; charset=UTF-8; action=\"http://myCompany.Customer.Contract/ICustomerService/GetSomeConfiguration\"")] - public void StringContentHelper_Create(string test, string expected) + public async Task StringContentHelper_Create(string test, string expected) { // Arrange var contentType = MediaTypeHeaderValue.Parse(test); @@ -33,7 +36,7 @@ public class StringContentHelperTests var result = StringContentHelper.Create("test", contentType); // Assert - result.Headers.ContentType.ToString().Should().Be(expected); - result.ReadAsStringAsync().Result.Should().Be("test"); + result.Headers.ContentType?.ToString().Should().Be(expected); + (await result.ReadAsStringAsync(_ct)).Should().Be("test"); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/FormUrlEncodedMatcherTests.cs b/test/WireMock.Net.Tests/Matchers/FormUrlEncodedMatcherTests.cs index f4e55e1d..6e7c8ccb 100644 --- a/test/WireMock.Net.Tests/Matchers/FormUrlEncodedMatcherTests.cs +++ b/test/WireMock.Net.Tests/Matchers/FormUrlEncodedMatcherTests.cs @@ -10,6 +10,8 @@ namespace WireMock.Net.Tests.Matchers; public class FormUrlEncodedMatcherTest { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + [Theory] [InlineData("*=*")] [InlineData("name=John Doe")] @@ -25,12 +27,12 @@ public class FormUrlEncodedMatcherTest public async Task FormUrlEncodedMatcher_IsMatch(params string[] patterns) { // Arrange - var content = new FormUrlEncodedContent(new[] - { + var content = new FormUrlEncodedContent( + [ new KeyValuePair("name", "John Doe"), new KeyValuePair("email", "johndoe@example.com") - }); - var contentAsString = await content.ReadAsStringAsync(); + ]); + var contentAsString = await content.ReadAsStringAsync(_ct); var matcher = new FormUrlEncodedMatcher(patterns.Select(p => new AnyOf(p)).ToArray()); @@ -56,12 +58,12 @@ public class FormUrlEncodedMatcherTest public async Task FormUrlEncodedMatcher_IsMatch_And(bool expected, params string[] patterns) { // Arrange - var content = new FormUrlEncodedContent(new[] - { + var content = new FormUrlEncodedContent( + [ new KeyValuePair("name", "John Doe"), new KeyValuePair("email", "johndoe@example.com") - }); - var contentAsString = await content.ReadAsStringAsync(); + ]); + var contentAsString = await content.ReadAsStringAsync(_ct); var matcher = new FormUrlEncodedMatcher(patterns.Select(p => new AnyOf(p)).ToArray(), true, MatchOperator.And); @@ -76,12 +78,12 @@ public class FormUrlEncodedMatcherTest public async Task FormUrlEncodedMatcher_IsMatch_And_MatchAllProperties() { // Arrange - var content = new FormUrlEncodedContent(new[] - { + var content = new FormUrlEncodedContent( + [ new KeyValuePair("name", "John Doe"), new KeyValuePair("email", "johndoe@example.com") - }); - var contentAsString = await content.ReadAsStringAsync(); + ]); + var contentAsString = await content.ReadAsStringAsync(_ct); // The expectation is that the matcher requires all properties to be present in the content. var matcher = new FormUrlEncodedMatcher(["name=*", "email=*", "required=*"], matchOperator: MatchOperator.And); diff --git a/test/WireMock.Net.Tests/Matchers/JsonPartialMatcherTests.cs b/test/WireMock.Net.Tests/Matchers/JsonPartialMatcherTests.cs index b216ef35..27685d4d 100644 --- a/test/WireMock.Net.Tests/Matchers/JsonPartialMatcherTests.cs +++ b/test/WireMock.Net.Tests/Matchers/JsonPartialMatcherTests.cs @@ -414,7 +414,7 @@ public class JsonPartialMatcherTests [InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value1\"}}")] [InlineData("{\"test\":{\"test1\":\"value\"}}", "{\"test\":{\"test1\":\"value1\"}}")] [InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value1\"}}]")] - public void JsonPartialMatcher_IsMatch_StringInputWithInvalidMatch(string value, string input) + public void JsonPartialMatcher_IsMatch_StringInputWithInvalidMatch(string value, string? input) { // Assign var matcher = new JsonPartialMatcher(value); diff --git a/test/WireMock.Net.Tests/Matchers/ProtoBufMatcherTests.cs b/test/WireMock.Net.Tests/Matchers/ProtoBufMatcherTests.cs index cc609e0c..63d8d436 100644 --- a/test/WireMock.Net.Tests/Matchers/ProtoBufMatcherTests.cs +++ b/test/WireMock.Net.Tests/Matchers/ProtoBufMatcherTests.cs @@ -9,6 +9,8 @@ namespace WireMock.Net.Tests.Matchers; public class ProtoBufMatcherTests { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + private const string MessageType = "greet.HelloRequest"; private static IdOrTexts ProtoDefinition => new(null, @" @@ -37,7 +39,7 @@ message HelloReply { // Act var matcher = new ProtoBufMatcher(() => ProtoDefinition, MessageType); - var result = await matcher.DecodeAsync(bytes); + var result = await matcher.DecodeAsync(bytes, _ct); // Assert result.Should().BeEquivalentTo(new { name = "stef" }); @@ -51,7 +53,7 @@ message HelloReply { // Act var matcher = new ProtoBufMatcher(() => ProtoDefinition, MessageType); - var result = await matcher.IsMatchAsync(bytes); + var result = await matcher.IsMatchAsync(bytes, _ct); // Assert result.Score.Should().Be(MatchScores.Perfect); @@ -67,7 +69,7 @@ message HelloReply { // Act var matcher = new ProtoBufMatcher(() => ProtoDefinition, MessageType, matcher: jsonMatcher); - var result = await matcher.IsMatchAsync(bytes); + var result = await matcher.IsMatchAsync(bytes, _ct); // Assert result.Score.Should().Be(MatchScores.Perfect); @@ -82,7 +84,7 @@ message HelloReply { // Act var matcher = new ProtoBufMatcher(() => ProtoDefinition, MessageType); - var result = await matcher.IsMatchAsync(bytes); + var result = await matcher.IsMatchAsync(bytes, _ct); // Assert result.Score.Should().Be(MatchScores.Mismatch); @@ -97,7 +99,7 @@ message HelloReply { // Act var matcher = new ProtoBufMatcher(() => ProtoDefinition, "greet.Greeter.X"); - var result = await matcher.IsMatchAsync(bytes); + var result = await matcher.IsMatchAsync(bytes, _ct); // Assert result.Score.Should().Be(MatchScores.Mismatch); diff --git a/test/WireMock.Net.Tests/ObservableLogEntriesTest.cs b/test/WireMock.Net.Tests/ObservableLogEntriesTest.cs index 358cb245..788a00eb 100644 --- a/test/WireMock.Net.Tests/ObservableLogEntriesTest.cs +++ b/test/WireMock.Net.Tests/ObservableLogEntriesTest.cs @@ -16,6 +16,8 @@ namespace WireMock.Net.Tests; public class ObservableLogEntriesTest { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + [Fact] public async Task WireMockServer_LogEntriesChanged_WithException_Should_LogError() { @@ -39,7 +41,7 @@ public class ObservableLogEntriesTest server.LogEntriesChanged += (sender, args) => throw new Exception(); // Act - await new HttpClient().GetAsync($"http://localhost:{server.Ports[0]}{path}"); + await new HttpClient().GetAsync($"http://localhost:{server.Ports[0]}{path}", _ct); // Assert loggerMock.Verify(l => l.Error(It.IsAny(), It.IsAny()), Times.Once); @@ -63,10 +65,10 @@ public class ObservableLogEntriesTest server.LogEntriesChanged += (sender, args) => count++; // Act 1a - await server.CreateClient().GetAsync(path); + await server.CreateClient().GetAsync(path, _ct); // Act 1b - await server.CreateClient().GetAsync(path); + await server.CreateClient().GetAsync(path, _ct); // Assert count.Should().Be(2); @@ -90,13 +92,13 @@ public class ObservableLogEntriesTest int count = 0; - void OnServerOnLogEntriesChanged(object sender, NotifyCollectionChangedEventArgs args) => count++; + void OnServerOnLogEntriesChanged(object? sender, NotifyCollectionChangedEventArgs args) => count++; // Add Handler server.LogEntriesChanged += OnServerOnLogEntriesChanged; // Act 1 - await server.CreateClient().GetAsync(path); + await server.CreateClient().GetAsync(path, _ct); // Assert 1 count.Should().Be(1); @@ -105,7 +107,7 @@ public class ObservableLogEntriesTest server.LogEntriesChanged -= OnServerOnLogEntriesChanged; // Act 2 - await server.CreateClient().GetAsync(path); + await server.CreateClient().GetAsync(path, _ct); // Assert 2 count.Should().Be(1); @@ -138,8 +140,8 @@ public class ObservableLogEntriesTest var listOfTasks = new List>(); for (var i = 0; i < expectedCount; i++) { - Thread.Sleep(50); - listOfTasks.Add(http.GetAsync($"{server.Urls[0]}{path}")); + await Task.Delay(50, _ct); + listOfTasks.Add(http.GetAsync($"{server.Urls[0]}{path}", _ct)); } var responses = await Task.WhenAll(listOfTasks); var countResponsesWithStatusNotOk = responses.Count(r => r.StatusCode != HttpStatusCode.OK); diff --git a/test/WireMock.Net.Tests/Owin/Mappers/OwinResponseMapperTests.cs b/test/WireMock.Net.Tests/Owin/Mappers/OwinResponseMapperTests.cs index 74cecac8..14b90f2c 100644 --- a/test/WireMock.Net.Tests/Owin/Mappers/OwinResponseMapperTests.cs +++ b/test/WireMock.Net.Tests/Owin/Mappers/OwinResponseMapperTests.cs @@ -274,7 +274,7 @@ public class OwinResponseMapperTests [InlineData("abcd", BodyType.String)] [InlineData("", BodyType.String)] [InlineData(null, BodyType.None)] - public async Task OwinResponseMapper_MapAsync_WithFault_MALFORMED_RESPONSE_CHUNK(string body, BodyType detected) + public async Task OwinResponseMapper_MapAsync_WithFault_MALFORMED_RESPONSE_CHUNK(string? body, BodyType detected) { // Arrange var responseMessage = new ResponseMessage diff --git a/test/WireMock.Net.Tests/RequestMatchers/RequestMessageBodyMatcherTests.cs b/test/WireMock.Net.Tests/RequestMatchers/RequestMessageBodyMatcherTests.cs index fd1f42b0..bb36b2ad 100644 --- a/test/WireMock.Net.Tests/RequestMatchers/RequestMessageBodyMatcherTests.cs +++ b/test/WireMock.Net.Tests/RequestMatchers/RequestMessageBodyMatcherTests.cs @@ -326,7 +326,7 @@ public class RequestMessageBodyMatcherTests [InlineData(null, 0.0)] [InlineData(new byte[0], 0.0)] [InlineData(new byte[] { 48 }, 1.0)] - public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_NotNullOrEmptyObjectMatcher(byte[] bytes, double expected) + public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_NotNullOrEmptyObjectMatcher(byte[]? bytes, double expected) { // Assign var body = new BodyData @@ -350,7 +350,7 @@ public class RequestMessageBodyMatcherTests [InlineData(null, 0.0)] [InlineData("", 0.0)] [InlineData("x", 1.0)] - public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_NotNullOrEmptyObjectMatcher(string data, double expected) + public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_NotNullOrEmptyObjectMatcher(string? data, double expected) { // Assign var body = new BodyData diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithBodyFromFileTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithBodyFromFileTests.cs index 8ef67a57..3f7cebf6 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithBodyFromFileTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithBodyFromFileTests.cs @@ -7,102 +7,103 @@ using WireMock.RequestBuilders; using WireMock.ResponseBuilders; using WireMock.Server; -namespace WireMock.Net.Tests.ResponseBuilders +namespace WireMock.Net.Tests.ResponseBuilders; + +public class ResponseWithBodyFromFileTests { - public class ResponseWithBodyFromFileTests + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + + [Fact] + public async Task Response_ProvideResponse_WithBodyFromFile_AbsolutePath() { - [Fact] - public async Task Response_ProvideResponse_WithBodyFromFile_AbsolutePath() - { - // Arrange - var server = WireMockServer.Start(); - string path = Path.Combine(Directory.GetCurrentDirectory(), "__admin", "mappings", "MyXmlResponse.xml"); + // Arrange + var server = WireMockServer.Start(); + string path = Path.Combine(Directory.GetCurrentDirectory(), "__admin", "mappings", "MyXmlResponse.xml"); - server - .Given( - Request - .Create() - .UsingGet() - .WithPath("/v1/content") - ) - .RespondWith( - Response - .Create() - .WithStatusCode(HttpStatusCode.OK) - .WithHeader("Content-Type", "application/xml") - .WithBodyFromFile(path) - ); + server + .Given( + Request + .Create() + .UsingGet() + .WithPath("/v1/content") + ) + .RespondWith( + Response + .Create() + .WithStatusCode(HttpStatusCode.OK) + .WithHeader("Content-Type", "application/xml") + .WithBodyFromFile(path) + ); - // Act - var response = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/v1/content"); + // Act + var response = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/v1/content"); - // Assert - response.Should().Contain("world"); + // Assert + response.Should().Contain("world"); - server.Stop(); - } + server.Stop(); + } - [Fact] - public async Task Response_ProvideResponse_WithBodyFromFile_InSubDirectory() - { - // Arrange - var server = WireMockServer.Start(); - string path = @"subdirectory/MyXmlResponse.xml"; + [Fact] + public async Task Response_ProvideResponse_WithBodyFromFile_InSubDirectory() + { + // Arrange + var server = WireMockServer.Start(); + string path = @"subdirectory/MyXmlResponse.xml"; - server - .Given( - Request - .Create() - .UsingGet() - .WithPath("/v1/content") - ) - .RespondWith( - Response - .Create() - .WithStatusCode(HttpStatusCode.OK) - .WithHeader("Content-Type", "application/xml") - .WithBodyFromFile(path) - ); + server + .Given( + Request + .Create() + .UsingGet() + .WithPath("/v1/content") + ) + .RespondWith( + Response + .Create() + .WithStatusCode(HttpStatusCode.OK) + .WithHeader("Content-Type", "application/xml") + .WithBodyFromFile(path) + ); - // Act - using var httpClient = new HttpClient(); - var response = await httpClient.GetStringAsync("http://localhost:" + server.Ports[0] + "/v1/content"); + // Act + using var httpClient = new HttpClient(); + var response = await httpClient.GetStringAsync("http://localhost:" + server.Ports[0] + "/v1/content", _ct); - // Assert - response.Should().Contain("world"); + // Assert + response.Should().Contain("world"); - server.Stop(); - } + server.Stop(); + } - [Fact] - public async Task Response_ProvideResponse_WithBodyFromFile_InAdminMappingFolder() - { - // Arrange - var server = WireMockServer.Start(); - string path = @"MyXmlResponse.xml"; + [Fact] + public async Task Response_ProvideResponse_WithBodyFromFile_InAdminMappingFolder() + { + // Arrange + var server = WireMockServer.Start(); + string path = @"MyXmlResponse.xml"; - server - .Given( - Request - .Create() - .UsingGet() - .WithPath("/v1/content") - ) - .RespondWith( - Response - .Create() - .WithStatusCode(HttpStatusCode.OK) - .WithHeader("Content-Type", "application/xml") - .WithBodyFromFile(path) - ); + server + .Given( + Request + .Create() + .UsingGet() + .WithPath("/v1/content") + ) + .RespondWith( + Response + .Create() + .WithStatusCode(HttpStatusCode.OK) + .WithHeader("Content-Type", "application/xml") + .WithBodyFromFile(path) + ); - // Act - var response = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/v1/content"); + // Act + var response = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/v1/content", _ct); - // Assert - response.Should().Contain("world"); + // Assert + response.Should().Contain("world"); - server.Stop(); - } + server.Stop(); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsLinqTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsLinqTests.cs index 8391e4d3..c31458b7 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsLinqTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsLinqTests.cs @@ -108,9 +108,8 @@ public class ResponseWithHandlebarsLinqTests var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, Mock.Of(), request, _settings); // Assert - JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson); - Check.That(j["x"]).IsNotNull(); - Check.That(j["x"].ToString()).Equals("{ N = Test_123, I = 9 }"); + var j = JObject.FromObject(response.Message.BodyData!.BodyAsJson!); + j["x"]?.ToString().Should().Be("{ N = Test_123, I = 9 }"); } [Fact(Skip = "DynamicLinq")] @@ -138,9 +137,8 @@ public class ResponseWithHandlebarsLinqTests var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, Mock.Of(), request, _settings); // Assert - JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson); - Check.That(j["x"]).IsNotNull(); - Check.That(j["x"].ToString()).Equals("{ N = Test_123, I = 9 }"); + var j = JObject.FromObject(response.Message.BodyData!.BodyAsJson!); + j["x"]?.ToString().Should().Be("{ N = Test_123 }"); } [Fact(Skip = "DynamicLinq")] diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithProxyIntegrationTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithProxyIntegrationTests.cs index 6acac640..32d1a498 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithProxyIntegrationTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithProxyIntegrationTests.cs @@ -22,6 +22,8 @@ namespace WireMock.Net.Tests.ResponseBuilders; public sealed class ResponseWithProxyIntegrationTests(ITestOutputHelper output) { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + [Fact] public async Task Response_UsingTextPlain() { @@ -44,12 +46,12 @@ public sealed class ResponseWithProxyIntegrationTests(ITestOutputHelper output) content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); // When - var response = await client.PatchAsync("/zipcode", content); + var response = await client.PatchAsync("/zipcode", content, _ct); // Then response.StatusCode.Should().Be(HttpStatusCode.OK); response.Content.Headers.GetValues("Content-Type").Should().BeEquivalentTo("text/plain; charset=utf-8"); - var result = await response.Content.ReadAsStringAsync(); + var result = await response.Content.ReadAsStringAsync(_ct); result.Should().Be("0123"); } diff --git a/test/WireMock.Net.Tests/Testcontainers/TestcontainersTestsGrpc.cs b/test/WireMock.Net.Tests/Testcontainers/TestcontainersTestsGrpc.cs index 75944f98..e01655c4 100644 --- a/test/WireMock.Net.Tests/Testcontainers/TestcontainersTestsGrpc.cs +++ b/test/WireMock.Net.Tests/Testcontainers/TestcontainersTestsGrpc.cs @@ -17,6 +17,8 @@ namespace WireMock.Net.Tests.Testcontainers; [Collection("Grpc")] public class TestcontainersTestsGrpc(ITestOutputHelper testOutputHelper) { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + private readonly ILogger _logger = new XUnitLogger(testOutputHelper, new LoggerExternalScopeProvider(), nameof(TestcontainersTestsGrpc), new XUnitLoggerOptions { IncludeCategory = true, @@ -42,12 +44,12 @@ public class TestcontainersTestsGrpc(ITestOutputHelper testOutputHelper) try { - await wireMockContainer.StartAsync(); + await wireMockContainer.StartAsync(_ct); // Assert using (new AssertionScope()) { - var logs = await wireMockContainer.GetLogsAsync(DateTime.MinValue); + var logs = await wireMockContainer.GetLogsAsync(DateTime.MinValue, ct: _ct); logs.Should().NotBeNull(); var url = wireMockContainer.GetPublicUrl(); @@ -70,7 +72,7 @@ public class TestcontainersTestsGrpc(ITestOutputHelper testOutputHelper) var adminClient = wireMockContainer.CreateWireMockAdminClient(); - var settings = await adminClient.GetSettingsAsync(); + var settings = await adminClient.GetSettingsAsync(_ct); settings.Should().NotBeNull(); } } @@ -99,12 +101,12 @@ public class TestcontainersTestsGrpc(ITestOutputHelper testOutputHelper) try { - await wireMockContainer.StartAsync(); + await wireMockContainer.StartAsync(_ct); // Assert using (new AssertionScope()) { - var logs = await wireMockContainer.GetLogsAsync(DateTime.MinValue); + var logs = await wireMockContainer.GetLogsAsync(DateTime.MinValue, ct: _ct); logs.Should().NotBeNull(); var url = wireMockContainer.GetPublicUrl(); @@ -124,7 +126,7 @@ public class TestcontainersTestsGrpc(ITestOutputHelper testOutputHelper) var adminClient = wireMockContainer.CreateWireMockAdminClient(); - var settings = await adminClient.GetSettingsAsync(); + var settings = await adminClient.GetSettingsAsync(_ct); settings.Should().NotBeNull(); } } diff --git a/test/WireMock.Net.Tests/Util/HttpStatusRangeParserTests.cs b/test/WireMock.Net.Tests/Util/HttpStatusRangeParserTests.cs index ad23c255..88185c94 100644 --- a/test/WireMock.Net.Tests/Util/HttpStatusRangeParserTests.cs +++ b/test/WireMock.Net.Tests/Util/HttpStatusRangeParserTests.cs @@ -52,7 +52,7 @@ public class HttpStatusRangeParserTests [InlineData(",,,", 9999, false)] [InlineData(null, 399, true)] - public void HttpStatusRangeParser_ValidPattern_IsMatch(string pattern, int value, bool expectedResult) + public void HttpStatusRangeParser_ValidPattern_IsMatch(string? pattern, int value, bool expectedResult) { HttpStatusRangeParser.IsMatch(pattern, value).Should().Be(expectedResult); } diff --git a/test/WireMock.Net.Tests/Util/StringUtilsTests.cs b/test/WireMock.Net.Tests/Util/StringUtilsTests.cs index 93d483dd..67c8274c 100644 --- a/test/WireMock.Net.Tests/Util/StringUtilsTests.cs +++ b/test/WireMock.Net.Tests/Util/StringUtilsTests.cs @@ -227,7 +227,7 @@ public class StringUtilsTests [InlineData("")] [InlineData(null)] [InlineData("x")] - public void StringUtils_TryParseQuotedString_With_InvalidStringLength_Returns_False(string input) + public void StringUtils_TryParseQuotedString_With_InvalidStringLength_Returns_False(string? input) { // Act var valid = StringUtils.TryParseQuotedString(input, out _, out _); @@ -252,7 +252,7 @@ public class StringUtilsTests public void StringUtils_TryParseQuotedString_With_UnexpectedUnrecognizedEscapeSequence_Returns_False() { // Arrange - var input = new string(new[] { '"', '\\', 'u', '?', '"' }); + var input = new string(['"', '\\', 'u', '?', '"']); // Act var valid = StringUtils.TryParseQuotedString(input, out _, out _); diff --git a/test/WireMock.Net.Tests/WireMockServer.Proxy.cs b/test/WireMock.Net.Tests/WireMockServer.Proxy.cs index e7c399cc..685a29d9 100644 --- a/test/WireMock.Net.Tests/WireMockServer.Proxy.cs +++ b/test/WireMock.Net.Tests/WireMockServer.Proxy.cs @@ -21,6 +21,8 @@ namespace WireMock.Net.Tests; public class WireMockServerProxyTests { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + [Fact(Skip = "Fails in Linux CI")] public async Task WireMockServer_ProxySSL_Should_log_proxied_requests() { @@ -65,7 +67,7 @@ public class WireMockServerProxyTests Url = "http://www.google.com", SaveMapping = true, SaveMappingToFile = false, - ExcludedHeaders = new[] { "Connection" } // Needed for .NET 4.5.x and 4.6.x + ExcludedHeaders = ["Connection"] // Needed for .NET 4.5.x and 4.6.x } }; var server = WireMockServer.Start(settings); @@ -268,7 +270,7 @@ public class WireMockServerProxyTests SaveMappingToFile = true, SaveMappingSettings = new ProxySaveMappingSettings { - HttpMethods = new ProxySaveMappingSetting(new string[] { "GET" }, MatchBehaviour.RejectOnMatch) // To make sure that we don't want this mapping + HttpMethods = new ProxySaveMappingSetting(["GET"], MatchBehaviour.RejectOnMatch) // To make sure that we don't want this mapping } }, FileSystemHandler = fileSystemHandlerMock.Object @@ -443,7 +445,7 @@ public class WireMockServerProxyTests server.Mappings.Should().HaveCount(2); var authorizationRequestMessageHeaderMatcher = ((Request)server.Mappings.Single(m => !m.IsAdminInterface).RequestMatcher) - .GetRequestMessageMatcher(x => x.Matchers.Any(m => m.GetPatterns().Contains("BASIC test-A"))); + .GetRequestMessageMatcher(x => x.Matchers!.Any(m => m.GetPatterns().Contains("BASIC test-A"))); authorizationRequestMessageHeaderMatcher.Should().NotBeNull(); } @@ -464,7 +466,7 @@ public class WireMockServerProxyTests Url = serverForProxyForwarding.Urls[0], SaveMapping = true, SaveMappingToFile = false, - ExcludedHeaders = new[] { "excluded-header-X" } + ExcludedHeaders = ["excluded-header-X"] } }; var server = WireMockServer.Start(settings); @@ -507,7 +509,7 @@ public class WireMockServerProxyTests Url = serverForProxyForwarding.Urls[0], SaveMapping = true, SaveMappingToFile = false, - ExcludedCookies = new[] { "ASP.NET_SessionId" } + ExcludedCookies = ["ASP.NET_SessionId"] } }; var server = WireMockServer.Start(settings); @@ -557,7 +559,7 @@ public class WireMockServerProxyTests Url = serverForProxyForwarding.Urls[0], SaveMapping = true, SaveMappingToFile = false, - ExcludedParams = new[] { "timestamp" } + ExcludedParams = ["timestamp"] } }; var server = WireMockServer.Start(settings); @@ -625,8 +627,7 @@ public class WireMockServerProxyTests // Assert var mapping = serverForProxyForwarding.Mappings.FirstOrDefault(m => m.Guid != defaultMapping.Guid); - var score = mapping.RequestMatcher.GetMatchingScore(serverForProxyForwarding.LogEntries.First().RequestMessage, - new RequestMatchResult()); + var score = mapping!.RequestMatcher.GetMatchingScore(serverForProxyForwarding.LogEntries.First().RequestMessage!, new RequestMatchResult()); Check.That(score).IsEqualTo(1.0); } @@ -774,8 +775,7 @@ public class WireMockServerProxyTests { // arrange var jpegHeader = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00 }; - var brokenJpegHeader = new byte[] - {0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00}; + var brokenJpegHeader = new byte[] { 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00 }; bool HasCorrectHeader(byte[]? bytes) => bytes?.SequenceEqual(jpegHeader) == true; bool HasBrokenHeader(byte[]? bytes) => bytes?.SequenceEqual(brokenJpegHeader) == true; @@ -859,10 +859,10 @@ public class WireMockServerProxyTests { new StringContent("data"), "test", "test.txt" } }; using var httpClient = new HttpClient(); - var response = await httpClient.PostAsync(uri, form); + var response = await httpClient.PostAsync(uri, form, _ct); // Assert - string content = await response.Content.ReadAsStringAsync(); + string content = await response.Content.ReadAsStringAsync(_ct); Check.That(content).IsEqualTo("{\"i\":42}"); } @@ -894,10 +894,10 @@ public class WireMockServerProxyTests Method = HttpMethod.Get, RequestUri = new Uri($"{server.Urls[0]}{path}") }; - var response1 = await new HttpClient().SendAsync(requestMessage1); + var response1 = await new HttpClient().SendAsync(requestMessage1, _ct); // Assert 1 - string content1 = await response1.Content.ReadAsStringAsync(); + string content1 = await response1.Content.ReadAsStringAsync(_ct); Check.That(content1).IsEqualTo("ok"); // Act 2 @@ -906,10 +906,10 @@ public class WireMockServerProxyTests Method = HttpMethod.Get, RequestUri = new Uri($"{server.Urls[0]}/__admin/mappings") }; - var response2 = await new HttpClient().SendAsync(requestMessage2); + var response2 = await new HttpClient().SendAsync(requestMessage2, _ct); // Assert 2 - string content2 = await response2.Content.ReadAsStringAsync(); + string content2 = await response2.Content.ReadAsStringAsync(_ct); Check.That(content2).IsEqualTo("[]"); } @@ -936,12 +936,12 @@ public class WireMockServerProxyTests }; var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false }; using var httpClient = new HttpClient(httpClientHandler); - var result = await httpClient.SendAsync(requestMessage); + var result = await httpClient.SendAsync(requestMessage, _ct); // Assert result.StatusCode.Should().Be(HttpStatusCode.InternalServerError); - var content = await result.Content.ReadAsStringAsync(); + var content = await result.Content.ReadAsStringAsync(_ct); content.Should().NotBeEmpty(); server.LogEntries.Should().HaveCount(1); diff --git a/test/WireMock.Net.Tests/WireMockServer.Proxy2.cs b/test/WireMock.Net.Tests/WireMockServer.Proxy2.cs index 5d128ede..e44d2457 100644 --- a/test/WireMock.Net.Tests/WireMockServer.Proxy2.cs +++ b/test/WireMock.Net.Tests/WireMockServer.Proxy2.cs @@ -11,6 +11,8 @@ namespace WireMock.Net.Tests; public class WireMockServerProxy2Tests { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + [Fact] public async Task WireMockServer_ProxyAndRecordSettings_ShouldProxy() { @@ -34,8 +36,8 @@ public class WireMockServerProxy2Tests // Assert using var httpClient = new HttpClient(); - var response = await httpClient.SendAsync(request); - string content = await response.Content.ReadAsStringAsync(); + var response = await httpClient.SendAsync(request, _ct); + string content = await response.Content.ReadAsStringAsync(_ct); Check.That(content).IsEqualTo("{\"p\":42}"); Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.Created); diff --git a/test/WireMock.Net.Tests/WireMockServer.WebhookTests.cs b/test/WireMock.Net.Tests/WireMockServer.WebhookTests.cs index 43d0c23f..625650bb 100644 --- a/test/WireMock.Net.Tests/WireMockServer.WebhookTests.cs +++ b/test/WireMock.Net.Tests/WireMockServer.WebhookTests.cs @@ -17,6 +17,8 @@ namespace WireMock.Net.Tests; public class WireMockServerWebhookTests { + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + [Fact] public async Task WireMockServer_WithWebhooks_Should_Send_Message_To_Webhooks() { @@ -71,8 +73,8 @@ public class WireMockServerWebhookTests }; // Assert - var response = await new HttpClient().SendAsync(request); - var content = await response.Content.ReadAsStringAsync(); + var response = await new HttpClient().SendAsync(request, _ct); + var content = await response.Content.ReadAsStringAsync(_ct); response.StatusCode.Should().Be(HttpStatusCode.OK); content.Should().Be("a-response"); @@ -120,8 +122,8 @@ public class WireMockServerWebhookTests }; // Assert - var response = await new HttpClient().SendAsync(request); - var content = await response.Content.ReadAsStringAsync(); + var response = await new HttpClient().SendAsync(request, _ct); + var content = await response.Content.ReadAsStringAsync(_ct); response.StatusCode.Should().Be(HttpStatusCode.OK); content.Should().Be("a-response"); @@ -176,8 +178,8 @@ public class WireMockServerWebhookTests }; // Assert - var response = await new HttpClient().SendAsync(request); - var content = await response.Content.ReadAsStringAsync(); + var response = await new HttpClient().SendAsync(request, _ct); + var content = await response.Content.ReadAsStringAsync(_ct); response.StatusCode.Should().Be(HttpStatusCode.OK); content.Should().Be("a-response"); @@ -231,8 +233,8 @@ public class WireMockServerWebhookTests }; // Assert - var response = await new HttpClient().SendAsync(request); - var content = await response.Content.ReadAsStringAsync(); + var response = await new HttpClient().SendAsync(request, _ct); + var content = await response.Content.ReadAsStringAsync(_ct); response.StatusCode.Should().Be(HttpStatusCode.OK); content.Should().Be("a-response"); @@ -263,14 +265,14 @@ public class WireMockServerWebhookTests }; // Assert - var response = await new HttpClient().SendAsync(request); - var content = await response.Content.ReadAsStringAsync(); + var response = await new HttpClient().SendAsync(request, _ct); + var content = await response.Content.ReadAsStringAsync(_ct); response.StatusCode.Should().Be(HttpStatusCode.OK); content.Should().Be("a-response"); serverReceivingTheWebhook.LogEntries.Should().HaveCount(1); - serverReceivingTheWebhook.LogEntries.First().RequestMessage.Body.Should().Be("OK !"); + serverReceivingTheWebhook.LogEntries.First().RequestMessage!.Body.Should().Be("OK !"); server.Dispose(); serverReceivingTheWebhook.Dispose(); @@ -297,14 +299,14 @@ public class WireMockServerWebhookTests }; // Assert - var response = await new HttpClient().SendAsync(request); - var content = await response.Content.ReadAsStringAsync(); + var response = await new HttpClient().SendAsync(request, _ct); + var content = await response.Content.ReadAsStringAsync(_ct); response.StatusCode.Should().Be(HttpStatusCode.OK); content.Should().Be("a-response"); serverReceivingTheWebhook.LogEntries.Should().HaveCount(1); - serverReceivingTheWebhook.LogEntries.First().RequestMessage.Body.Should().Be("{\"Status\":\"OK\"}"); + serverReceivingTheWebhook.LogEntries.First().RequestMessage!.Body.Should().Be("{\"Status\":\"OK\"}"); server.Dispose(); serverReceivingTheWebhook.Dispose(); diff --git a/test/WireMock.Net.Tests/WireMockServerTests.WithBody.cs b/test/WireMock.Net.Tests/WireMockServerTests.WithBody.cs index 009a4065..867557e3 100644 --- a/test/WireMock.Net.Tests/WireMockServerTests.WithBody.cs +++ b/test/WireMock.Net.Tests/WireMockServerTests.WithBody.cs @@ -393,7 +393,7 @@ public partial class WireMockServerTests (await normal.Content.ReadAsStringAsync(cancellationToken)).Should().Be("normal"); // Act 2 - using var response = await client.GetStreamAsync($"{server.Url}/sse"); + using var response = await client.GetStreamAsync($"{server.Url}/sse", _ct); using var reader = new StreamReader(response); var data = string.Empty; diff --git a/test/WireMock.Net.Tests/WireMockServerTests.WithCallback.cs b/test/WireMock.Net.Tests/WireMockServerTests.WithCallback.cs index 5a69c50f..a10fc4ea 100644 --- a/test/WireMock.Net.Tests/WireMockServerTests.WithCallback.cs +++ b/test/WireMock.Net.Tests/WireMockServerTests.WithCallback.cs @@ -28,7 +28,7 @@ namespace WireMock.Net.Tests // Act var httpClient = new HttpClient(); - var response = await httpClient.PostAsync("http://localhost:" + server.Ports[0] + "/foo", new StringContent("dummy")); + var response = await httpClient.PostAsync("http://localhost:" + server.Ports[0] + "/foo", new StringContent("dummy"), _ct); // Assert response.StatusCode.Should().Be(HttpStatusCode.Conflict); diff --git a/test/WireMock.Net.Tests/WireMockServerTests.WithMultiPart.cs b/test/WireMock.Net.Tests/WireMockServerTests.WithMultiPart.cs index ec9b98a3..cefee324 100644 --- a/test/WireMock.Net.Tests/WireMockServerTests.WithMultiPart.cs +++ b/test/WireMock.Net.Tests/WireMockServerTests.WithMultiPart.cs @@ -62,7 +62,7 @@ public partial class WireMockServerTests var client = server.CreateClient(); - var response = await client.PostAsync("/multipart", formDataContent); + var response = await client.PostAsync("/multipart", formDataContent, _ct); // Assert response.StatusCode.Should().Be(HttpStatusCode.OK); diff --git a/test/WireMock.Net.Tests/WireMockServerTests.cs b/test/WireMock.Net.Tests/WireMockServerTests.cs index 64cbfaf3..8be40b16 100644 --- a/test/WireMock.Net.Tests/WireMockServerTests.cs +++ b/test/WireMock.Net.Tests/WireMockServerTests.cs @@ -25,14 +25,9 @@ using WireMock.Util; namespace WireMock.Net.Tests; -public partial class WireMockServerTests +public partial class WireMockServerTests(ITestOutputHelper testOutputHelper) { - private readonly ITestOutputHelper _testOutputHelper; - - public WireMockServerTests(ITestOutputHelper testOutputHelper) - { - _testOutputHelper = testOutputHelper; - } + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; [Fact] public void WireMockServer_Start() @@ -129,7 +124,7 @@ public partial class WireMockServerTests using var client = new HttpClient(handler); // Act - var result = await client.GetStringAsync($"{server.Url}{path}"); + var result = await client.GetStringAsync($"{server.Url}{path}", _ct); // Assert result.Should().Be(body); @@ -177,7 +172,7 @@ public partial class WireMockServerTests { HttpClient.DefaultProxy = new WebProxy(httpUrl, false); - result = await new HttpClient().GetStringAsync(httpUrl); + result = await new HttpClient().GetStringAsync(httpUrl, _ct); } finally { @@ -220,7 +215,7 @@ public partial class WireMockServerTests foreach (var address in IPv4) { // Act - var response = await new HttpClient().GetStringAsync("http://" + address + ":" + server.Ports[0] + "/foo"); + var response = await new HttpClient().GetStringAsync("http://" + address + ":" + server.Ports[0] + "/foo", _ct); // Assert response.Should().Be("x"); @@ -263,7 +258,7 @@ public partial class WireMockServerTests var server = WireMockServer.Start(new WireMockServerSettings { - Logger = new TestOutputHelperWireMockLogger(_testOutputHelper) + Logger = new TestOutputHelperWireMockLogger(testOutputHelper) }); server @@ -282,7 +277,7 @@ public partial class WireMockServerTests .WithBody("REDIRECT SUCCESSFUL")); // Act - var response = await new HttpClient().GetStringAsync($"http://localhost:{server.Ports[0]}{path}"); + var response = await new HttpClient().GetStringAsync($"http://localhost:{server.Ports[0]}{path}", _ct); // Assert Check.That(response).IsEqualTo("REDIRECT SUCCESSFUL"); @@ -304,7 +299,7 @@ public partial class WireMockServerTests server.Given(Request.Create().WithPath("/*")).RespondWith(Response.Create().WithBody("x")); // Act - var response = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo"); + var response = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo", _ct); // Assert response.Should().Be("x"); @@ -329,7 +324,7 @@ public partial class WireMockServerTests // Act var watch = new Stopwatch(); watch.Start(); - await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo"); + await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo", _ct); watch.Stop(); // Assert @@ -358,7 +353,7 @@ public partial class WireMockServerTests async Task ExecuteTimedRequestAsync() { watch.Reset(); - await httClient.GetStringAsync("http://localhost:" + server.Ports[0] + "/foo"); + await httClient.GetStringAsync("http://localhost:" + server.Ports[0] + "/foo", _ct); return watch.ElapsedMilliseconds; } @@ -383,7 +378,7 @@ public partial class WireMockServerTests // Act var watch = new Stopwatch(); watch.Start(); - await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo"); + await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo", _ct); watch.Stop(); // Assert @@ -421,7 +416,7 @@ public partial class WireMockServerTests .RespondWith(Response.Create().WithHeader("Transfer-Encoding", "chunked").WithHeader("test", "t")); // Act - var response = await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + path); + var response = await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + path, _ct); // Assert Check.That(response.Headers.Contains("test")).IsTrue(); @@ -444,7 +439,7 @@ public partial class WireMockServerTests // Act var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, path); - var response = await server.CreateClient().SendAsync(httpRequestMessage); + var response = await server.CreateClient().SendAsync(httpRequestMessage, _ct); // Assert response.Content.Headers.GetValues(HttpKnownHeaderNames.ContentLength).Should().Contain(length); @@ -461,7 +456,7 @@ public partial class WireMockServerTests var server = WireMockServer.Start(); server - .Given(Request.Create().WithBody((byte[] bodyBytes) => bodyBytes != null)) + .Given(Request.Create().WithBody((byte[]? bodyBytes) => bodyBytes != null)) .AtPriority(0) .RespondWith(Response.Create().WithStatusCode(400)); server @@ -472,7 +467,7 @@ public partial class WireMockServerTests // Act var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost:" + server.Ports[0] + "/"); request.Content = new StringContent(content); - var response = await new HttpClient().SendAsync(request); + var response = await new HttpClient().SendAsync(request, _ct); // Assert Check.That(response.StatusCode).Equals(HttpStatusCode.OK); @@ -506,7 +501,7 @@ public partial class WireMockServerTests // Act var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost:" + server.Ports[0] + "/"); request.Content = new StringContent(content); - var response = await new HttpClient().SendAsync(request); + var response = await new HttpClient().SendAsync(request, _ct); // Assert Check.That(response.StatusCode).Equals(HttpStatusCode.OK); @@ -540,11 +535,11 @@ public partial class WireMockServerTests var server = WireMockServer.StartWithAdminInterface(); // Act - var response = await new HttpClient().PostAsync($"{server.Url}/__admin/mappings", stringContent); + var response = await new HttpClient().PostAsync($"{server.Url}/__admin/mappings", stringContent, _ct); // Assert Check.That(response.StatusCode).Equals(HttpStatusCode.Created); - Check.That(await response.Content.ReadAsStringAsync()).Contains("Mapping added"); + Check.That(await response.Content.ReadAsStringAsync(_ct)).Contains("Mapping added"); server.Stop(); } @@ -573,10 +568,10 @@ public partial class WireMockServerTests content.Headers.ContentEncoding.Add(contentEncoding); // Act - var response = await new HttpClient().PostAsync($"{server.Urls[0]}/foo", content); + var response = await new HttpClient().PostAsync($"{server.Urls[0]}/foo", content, _ct); // Assert - Check.That(await response.Content.ReadAsStringAsync()).Contains("OK"); + Check.That(await response.Content.ReadAsStringAsync(_ct)).Contains("OK"); server.Stop(); } @@ -596,7 +591,7 @@ public partial class WireMockServerTests .WithBody("from ipv4 loopback")); // Act - var response = await new HttpClient().GetStringAsync($"http://127.0.0.1:{server.Ports[0]}/foo"); + var response = await new HttpClient().GetStringAsync($"http://127.0.0.1:{server.Ports[0]}/foo", _ct); // Assert Check.That(response).IsEqualTo("from ipv4 loopback"); @@ -618,7 +613,7 @@ public partial class WireMockServerTests .WithBody("from ipv6 loopback")); // Act - var response = await new HttpClient().GetStringAsync($"http://[::1]:{server.Ports[0]}/foo"); + var response = await new HttpClient().GetStringAsync($"http://[::1]:{server.Ports[0]}/foo", _ct); // Assert Check.That(response).IsEqualTo("from ipv6 loopback"); @@ -665,7 +660,7 @@ public partial class WireMockServerTests }"); // Act - var response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/customer/132/document/pic.jpg", new StringContent("{ Hi = \"Hello World\" }")); + var response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/customer/132/document/pic.jpg", new StringContent("{ Hi = \"Hello World\" }"), _ct); // Assert response.StatusCode.Should().Be(HttpStatusCode.OK); @@ -712,7 +707,7 @@ public partial class WireMockServerTests }"); // Act - var response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/customer/132/document/pic", new StringContent("{ Hi = \"Hello World\" }")); + var response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/customer/132/document/pic", new StringContent("{ Hi = \"Hello World\" }"), _ct); // Assert response.StatusCode.Should().Be(HttpStatusCode.NotFound);