This commit is contained in:
Stef Heyenrath
2026-02-14 17:28:37 +01:00
parent 385450a3a8
commit 334675f39c
9 changed files with 139 additions and 132 deletions

View File

@@ -1,5 +1,6 @@
// Copyright © WireMock.Net
using System.Net.Http;
using RestEase;
using WireMock.Client;
using WireMock.Matchers;
@@ -50,7 +51,7 @@ message HelloReply {
// Act
var client = server.CreateClient();
var getMappingsResult = await client.GetStringAsync("/__admin/mappings");
var getMappingsResult = await client.GetStringAsync("/__admin/mappings", TestContext.Current.CancellationToken);
await VerifyJson(getMappingsResult, VerifySettings);
}

View File

@@ -8,80 +8,39 @@ namespace System.Net.Http;
/// </summary>
internal static class HttpClientExtensions
{
/// <summary>
/// Sends a GET request to the specified Uri as an asynchronous operation.
/// This extension is only used in frameworks prior to .NET 5.0 where CancellationToken is not supported.
/// </summary>
public static Task<Stream> GetStreamAsync(this HttpClient client, Uri requestUri, CancellationToken _)
{
return client.GetStreamAsync(requestUri);
}
public static Task<HttpResponseMessage> GetAsync(this HttpClient client, Uri requestUri, CancellationToken _)
{
// In older frameworks, we ignore the cancellation token since it's not supported
return client.GetAsync(requestUri);
}
/// <summary>
/// Sends a GET request to the specified Uri and return the response body as a string.
/// This extension is only used in frameworks prior to .NET 5.0 where CancellationToken is not supported.
/// </summary>
public static Task<string> GetStringAsync(this HttpClient client, string requestUri, CancellationToken _)
{
// In older frameworks, we ignore the cancellation token since it's not supported
return client.GetStringAsync(requestUri);
}
/// <summary>
/// Sends a GET request to the specified Uri and return the response body as a string.
/// This extension is only used in frameworks prior to .NET 5.0 where CancellationToken is not supported.
/// </summary>
public static Task<string> GetStringAsync(this HttpClient client, Uri requestUri, CancellationToken _)
{
// In older frameworks, we ignore the cancellation token since it's not supported
return client.GetStringAsync(requestUri);
}
/// <summary>
/// Sends a POST request to the specified Uri as an asynchronous operation.
/// This extension is only used in frameworks prior to .NET 5.0 where CancellationToken is not supported.
/// </summary>
public static Task<HttpResponseMessage> PostAsync(this HttpClient client, string requestUri, HttpContent content, CancellationToken _)
{
// In older frameworks, we ignore the cancellation token since it's not supported
return client.PostAsync(requestUri, content);
}
/// <summary>
/// Sends a POST request to the specified Uri as an asynchronous operation.
/// This extension is only used in frameworks prior to .NET 5.0 where CancellationToken is not supported.
/// </summary>
public static Task<HttpResponseMessage> PostAsync(this HttpClient client, Uri requestUri, HttpContent content, CancellationToken _)
{
// In older frameworks, we ignore the cancellation token since it's not supported
return client.PostAsync(requestUri, content);
}
/// <summary>
/// Sends an HTTP request as an asynchronous operation.
/// This extension is only used in frameworks prior to .NET 5.0 where CancellationToken is not supported.
/// </summary>
public static Task<HttpResponseMessage> SendAsync(this HttpClient client, HttpRequestMessage request, CancellationToken _)
{
// In older frameworks, we ignore the cancellation token since it's not supported
return client.SendAsync(request);
}
}
/// <summary>
/// Extension methods for HttpContent to provide CancellationToken support in frameworks before .NET 5.0.
/// </summary>
internal static class HttpContentExtensions
{
/// <summary>
/// Serialize the HTTP content to a string as an asynchronous operation.
/// This extension is only used in frameworks prior to .NET 5.0 where CancellationToken is not supported.
/// </summary>
public static Task<string> ReadAsStringAsync(this HttpContent content, CancellationToken _)
{
// In older frameworks, we ignore the cancellation token since it's not supported
return content.ReadAsStringAsync();
}
}
#endif

View File

@@ -0,0 +1,21 @@
// Copyright © WireMock.Net
#if !NET5_0_OR_GREATER
namespace System.Net.Http;
/// <summary>
/// Extension methods for HttpContent to provide CancellationToken support in frameworks before .NET 5.0.
/// </summary>
internal static class HttpContentExtensions
{
public static Task<string> ReadAsStringAsync(this HttpContent content, CancellationToken _)
{
return content.ReadAsStringAsync();
}
public static Task<byte[]> ReadAsByteArrayAsync(this HttpContent content, CancellationToken _)
{
return content.ReadAsByteArrayAsync();
}
}
#endif

View File

@@ -7,7 +7,7 @@ namespace WireMock.Net.Tests.Grpc;
public class ProtoBufUtilsTests
{
private static readonly IProtoBufUtils ProtoBufUtils = new ProtoBufUtils();
private static readonly ProtoBufUtils _sut = new();
[Fact]
public async Task GetProtoBufMessageWithHeader_MultipleProtoFiles()
@@ -17,7 +17,7 @@ public class ProtoBufUtilsTests
var request = ReadProtoFile("request.proto");
// Act
var responseBytes = await ProtoBufUtils.GetProtoBufMessageWithHeaderAsync(
var responseBytes = await _sut.GetProtoBufMessageWithHeaderAsync(
[greet, request],
"greet.HelloRequest", new
{
@@ -30,7 +30,7 @@ public class ProtoBufUtilsTests
Convert.ToBase64String(responseBytes).Should().Be("AAAAAAcKBWhlbGxv");
}
private string ReadProtoFile(string filename)
private static string ReadProtoFile(string filename)
{
return File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "Grpc", filename));
}

View File

@@ -35,7 +35,7 @@ public class ProtoDefinitionHelperTests
resolver.Exists("x").Should().BeFalse();
// Act + Assert
var text = await resolver.OpenText(expectedFilename).ReadToEndAsync();
var text = resolver.OpenText(expectedFilename).ReadToEnd();
text.Should().StartWith(expectedComment);
System.Action action = () => resolver.OpenText("x");
action.Should().Throw<FileNotFoundException>();

View File

@@ -4,8 +4,8 @@ using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using ExampleIntegrationTest.Lookup;
using AwesomeAssertions;
using ExampleIntegrationTest.Lookup;
using Google.Protobuf.WellKnownTypes;
using Greet;
using Grpc.Net.Client;
@@ -147,6 +147,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf(string data)
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var bytes = Convert.FromBase64String(data);
var jsonMatcher = new JsonMatcher(new { name = "stef" });
@@ -173,11 +174,11 @@ message Other {
protoBuf.Headers.ContentType = new MediaTypeHeaderValue("application/grpc-web");
var client = server.CreateClient();
var response = await client.PostAsync("/grpc/greet.Greeter/SayHello", protoBuf, TestContext.Current.CancellationToken);
var response = await client.PostAsync("/grpc/greet.Greeter/SayHello", protoBuf, cancellationToken);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseBytes = await response.Content.ReadAsByteArrayAsync();
var responseBytes = await response.Content.ReadAsByteArrayAsync(cancellationToken);
Convert.ToBase64String(responseBytes).Should().Be("AAAAAAcKBWhlbGxv");
}
@@ -186,6 +187,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf_WithWellKnownTypes_Empty()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server
@@ -207,11 +209,11 @@ message Other {
protoBuf.Headers.ContentType = new MediaTypeHeaderValue("application/grpc-web");
var client = server.CreateClient();
var response = await client.PostAsync("/grpc/Greeter/SayNothing", protoBuf);
var response = await client.PostAsync("/grpc/Greeter/SayNothing", protoBuf, cancellationToken);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseBytes = await response.Content.ReadAsByteArrayAsync();
var responseBytes = await response.Content.ReadAsByteArrayAsync(cancellationToken);
Convert.ToBase64String(responseBytes).Should().Be("AAAAAAA=");
}
@@ -220,6 +222,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf_WithWellKnownTypes_Timestamp()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server
@@ -249,11 +252,11 @@ message Other {
protoBuf.Headers.ContentType = new MediaTypeHeaderValue("application/grpc-web");
var client = server.CreateClient();
var response = await client.PostAsync("/grpc/Greeter/SayTimestamp", protoBuf);
var response = await client.PostAsync("/grpc/Greeter/SayTimestamp", protoBuf, cancellationToken);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseBytes = await response.Content.ReadAsByteArrayAsync();
var responseBytes = await response.Content.ReadAsByteArrayAsync(cancellationToken);
Convert.ToBase64String(responseBytes).Should().Be("AAAAAAsKCQiL96C1BhCMYA==");
}
@@ -262,6 +265,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf_WithWellKnownTypes_Duration()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server
@@ -291,11 +295,11 @@ message Other {
protoBuf.Headers.ContentType = new MediaTypeHeaderValue("application/grpc-web");
var client = server.CreateClient();
var response = await client.PostAsync("/grpc/Greeter/SayDuration", protoBuf);
var response = await client.PostAsync("/grpc/Greeter/SayDuration", protoBuf, cancellationToken);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseBytes = await response.Content.ReadAsByteArrayAsync();
var responseBytes = await response.Content.ReadAsByteArrayAsync(cancellationToken);
Convert.ToBase64String(responseBytes).Should().Be("AAAAAAsKCQiL96C1BhCMYA==");
}
@@ -304,6 +308,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf_ServerProtoDefinition_WithWellKnownTypes()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var bytes = Convert.FromBase64String("CgRzdGVm");
using var server = WireMockServer.Start();
@@ -330,11 +335,11 @@ message Other {
protoBuf.Headers.ContentType = new MediaTypeHeaderValue("application/grpc-web");
var client = server.CreateClient();
var response = await client.PostAsync("/grpc/Greeter/SayNothing", protoBuf);
var response = await client.PostAsync("/grpc/Greeter/SayNothing", protoBuf, cancellationToken);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseBytes = await response.Content.ReadAsByteArrayAsync();
var responseBytes = await response.Content.ReadAsByteArrayAsync(cancellationToken);
Convert.ToBase64String(responseBytes).Should().Be("AAAAAAA=");
}
@@ -343,6 +348,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf_MultipleFiles()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var bytes = Convert.FromBase64String("CgRzdGVm");
var jsonMatcher = new JsonMatcher(new { name = "stef" });
@@ -371,11 +377,11 @@ message Other {
protoBuf.Headers.ContentType = new MediaTypeHeaderValue("application/grpc-web");
var client = server.CreateClient();
var response = await client.PostAsync("/grpc/greet.Greeter/SayOther", protoBuf);
var response = await client.PostAsync("/grpc/greet.Greeter/SayOther", protoBuf, cancellationToken);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseBytes = await response.Content.ReadAsByteArrayAsync();
var responseBytes = await response.Content.ReadAsByteArrayAsync(cancellationToken);
Convert.ToBase64String(responseBytes).Should().Be("AAAAAAcKBWhlbGxv");
}
@@ -384,6 +390,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf_InlineProtoDefinition_UsingGrpcGeneratedClient()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start(useHttp2: true);
var jsonMatcher = new JsonMatcher(new { name = "stef" });
@@ -410,7 +417,7 @@ message Other {
var channel = GrpcChannel.ForAddress(server.Url!);
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(new HelloRequest { Name = "stef" });
var reply = await client.SayHelloAsync(new HelloRequest { Name = "stef" }, cancellationToken: cancellationToken);
// Assert
reply.Message.Should().Be("hello stef POST");
@@ -420,6 +427,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf_MappingProtoDefinition_UsingGrpcGeneratedClient()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start(useHttp2: true);
var jsonMatcher = new JsonMatcher(new { name = "stef" });
@@ -448,7 +456,7 @@ message Other {
var channel = GrpcChannel.ForAddress(server.Url!);
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(new HelloRequest { Name = "stef" });
var reply = await client.SayHelloAsync(new HelloRequest { Name = "stef" }, cancellationToken: cancellationToken);
// Assert
reply.Message.Should().Be("hello stef POST");
@@ -460,6 +468,7 @@ message Other {
// Arrange
var id = $"test-{Guid.NewGuid()}";
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start(useHttp2: true);
var jsonMatcher = new JsonMatcher(new { name = "stef" });
@@ -486,7 +495,7 @@ message Other {
);
// Act
var reply = await When_GrpcClient_Calls_SayHelloAsync(server.Url!);
var reply = await When_GrpcClient_Calls_SayHelloAsync(server.Url!, cancellationToken);
// Assert
Then_ReplyMessage_Should_BeCorrect(reply);
@@ -496,6 +505,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf_WithWellKnownTypes_Empty_UsingGrpcGeneratedClient()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var definition = File.ReadAllText("./Grpc/greet.proto");
using var server = WireMockServer.Start(useHttp2: true);
@@ -517,7 +527,7 @@ message Other {
var channel = GrpcChannel.ForAddress(server.Url!);
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayNothingAsync(new Empty());
var reply = await client.SayNothingAsync(new Empty(), cancellationToken: cancellationToken);
// Assert
reply.Should().Be(new Empty());
@@ -529,6 +539,7 @@ message Other {
// Arrange
const int seconds = 1722301323;
const int nanos = 12300;
var cancellationToken = TestContext.Current.CancellationToken;
var definition = File.ReadAllText("./Grpc/greet.proto");
using var server = WireMockServer.Start(useHttp2: true);
@@ -558,7 +569,7 @@ message Other {
var channel = GrpcChannel.ForAddress(server.Url!);
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayTimestampAsync(new MyMessageTimestamp { Ts = Timestamp.FromDateTime(DateTime.UtcNow) });
var reply = await client.SayTimestampAsync(new MyMessageTimestamp { Ts = Timestamp.FromDateTime(DateTime.UtcNow) }, cancellationToken: cancellationToken);
// Assert
reply.Ts.Should().Be(new Timestamp { Seconds = seconds, Nanos = nanos });
@@ -570,6 +581,7 @@ message Other {
// Arrange
const int seconds = 1722301323;
const int nanos = 12300;
var cancellationToken = TestContext.Current.CancellationToken;
var definition = File.ReadAllText("./Grpc/greet.proto");
using var server = WireMockServer.Start(useHttp2: true);
@@ -599,7 +611,7 @@ message Other {
var channel = GrpcChannel.ForAddress(server.Url!);
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayDurationAsync(new MyMessageDuration { Du = Duration.FromTimeSpan(TimeSpan.MinValue) });
var reply = await client.SayDurationAsync(new MyMessageDuration { Du = Duration.FromTimeSpan(TimeSpan.MinValue) }, cancellationToken: cancellationToken);
// Assert
reply.Du.Should().Be(new Duration { Seconds = seconds, Nanos = nanos });
@@ -609,6 +621,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf_Enum_UsingGrpcGeneratedClient()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var definition = File.ReadAllText("./Grpc/greet.proto");
using var server = WireMockServer.Start(useHttp2: true);
@@ -635,7 +648,7 @@ message Other {
var channel = GrpcChannel.ForAddress(server.Url!);
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(new HelloRequest());
var reply = await client.SayHelloAsync(new HelloRequest(), cancellationToken: cancellationToken);
// Assert
reply.Message.Should().Be("hello");
@@ -646,6 +659,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf_Enum_UsingPolicyGrpcGeneratedClient()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
const int seconds = 1722301323;
const int nanos = 12300;
const string version = "test";
@@ -685,7 +699,7 @@ message Other {
var channel = GrpcChannel.ForAddress(server.Url!);
var client = new PolicyService.PolicyServiceClient(channel);
var reply = await client.GetVersionAsync(new GetVersionRequest());
var reply = await client.GetVersionAsync(new GetVersionRequest(), cancellationToken: cancellationToken);
// Assert
reply.Version.Should().Be(version);
@@ -697,10 +711,11 @@ message Other {
[Fact]
public async Task WireMockServer_WithBodyAsProtoBuf_FromJson_UsingGrpcGeneratedClient()
{
var cancellationToken = TestContext.Current.CancellationToken;
var server = Given_When_ServerStarted_And_RunningOnHttpAndGrpc();
await Given_When_ProtoBufMappingIsAddedViaAdminInterfaceAsync(server, "protobuf-mapping-1.json");
await Given_When_ProtoBufMappingIsAddedViaAdminInterfaceAsync(server, "protobuf-mapping-1.json", cancellationToken);
var reply = await When_GrpcClient_Calls_SayHelloAsync(server.Urls[1]);
var reply = await When_GrpcClient_Calls_SayHelloAsync(server.Urls[1], cancellationToken);
Then_ReplyMessage_Should_BeCorrect(reply);
}
@@ -708,11 +723,12 @@ message Other {
[Fact]
public async Task WireMockServer_WithBodyAsProtoBuf_ServerProtoDefinitionFromJson_UsingGrpcGeneratedClient()
{
var cancellationToken = TestContext.Current.CancellationToken;
var server = Given_When_ServerStarted_And_RunningOnHttpAndGrpc();
Given_ProtoDefinition_IsAddedOnServerLevel(server);
await Given_When_ProtoBufMappingIsAddedViaAdminInterfaceAsync(server, "protobuf-mapping-3.json");
await Given_When_ProtoBufMappingIsAddedViaAdminInterfaceAsync(server, "protobuf-mapping-3.json", cancellationToken);
var reply = await When_GrpcClient_Calls_SayHelloAsync(server.Urls[1]);
var reply = await When_GrpcClient_Calls_SayHelloAsync(server.Urls[1], cancellationToken);
Then_ReplyMessage_Should_BeCorrect(reply);
}
@@ -734,23 +750,23 @@ message Other {
server.AddProtoDefinition("my-greeter", ReadProtoFile("greet.proto"));
}
private static async Task Given_When_ProtoBufMappingIsAddedViaAdminInterfaceAsync(WireMockServer server, string filename)
private static async Task Given_When_ProtoBufMappingIsAddedViaAdminInterfaceAsync(WireMockServer server, string filename, CancellationToken cancellationToken)
{
var mappingsJson = ReadMappingFile(filename);
using var httpClient = server.CreateClient();
var result = await httpClient.PostAsync("/__admin/mappings", new StringContent(mappingsJson, Encoding.UTF8, WireMockConstants.ContentTypeJson));
var result = await httpClient.PostAsync("/__admin/mappings", new StringContent(mappingsJson, Encoding.UTF8, WireMockConstants.ContentTypeJson), cancellationToken);
result.EnsureSuccessStatusCode();
}
private static async Task<HelloReply> When_GrpcClient_Calls_SayHelloAsync(string address)
private static async Task<HelloReply> When_GrpcClient_Calls_SayHelloAsync(string address, CancellationToken cancellationToken)
{
var channel = GrpcChannel.ForAddress(address);
var client = new Greeter.GreeterClient(channel);
return await client.SayHelloAsync(new HelloRequest { Name = "stef" });
return await client.SayHelloAsync(new HelloRequest { Name = "stef" }, cancellationToken: cancellationToken);
}
private static void Then_ReplyMessage_Should_BeCorrect(HelloReply reply)

View File

@@ -14,18 +14,19 @@ namespace WireMock.Net.Tests;
public class WireMockServerAdminFilesTests
{
private readonly HttpClient _client = new HttpClient();
private readonly HttpClient _client = new();
[Fact]
public async Task WireMockServer_Admin_Files_Post_Ascii()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("__admin/mappings");
filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>()));
var server = WireMockServer.Start(new WireMockServerSettings
using var server = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
@@ -37,7 +38,7 @@ public class WireMockServerAdminFilesTests
multipartFormDataContent.Add(new StreamContent(new MemoryStream(Encoding.ASCII.GetBytes("Here's a string."))));
// Act
var httpResponseMessage = await _client.PostAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt", multipartFormDataContent);
var httpResponseMessage = await _client.PostAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt", multipartFormDataContent, cancellationToken);
// Assert
httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -53,13 +54,14 @@ public class WireMockServerAdminFilesTests
public async Task WireMockServer_Admin_Files_Post_MappingFolderDoesNotExistsButWillBeCreated()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("x");
filesystemHandlerMock.Setup(fs => fs.CreateFolder(It.IsAny<string>()));
filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(false);
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>()));
var server = WireMockServer.Start(new WireMockServerSettings
using var server = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
@@ -71,7 +73,7 @@ public class WireMockServerAdminFilesTests
multipartFormDataContent.Add(new StreamContent(new MemoryStream(Encoding.ASCII.GetBytes("Here's a string."))));
// Act
var httpResponseMessage = await _client.PostAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt", multipartFormDataContent);
var httpResponseMessage = await _client.PostAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt", multipartFormDataContent, cancellationToken);
// Assert
httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -88,11 +90,12 @@ public class WireMockServerAdminFilesTests
public async Task WireMockServer_Admin_Files_GetAscii()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(Encoding.ASCII.GetBytes("Here's a string."));
var server = WireMockServer.Start(new WireMockServerSettings
using var server = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
@@ -104,12 +107,12 @@ public class WireMockServerAdminFilesTests
multipartFormDataContent.Add(new StreamContent(new MemoryStream()));
// Act
var httpResponseMessageGet = await _client.GetAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt");
var httpResponseMessageGet = await _client.GetAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt", cancellationToken);
// Assert
httpResponseMessageGet.StatusCode.Should().Be(HttpStatusCode.OK);
var result = await httpResponseMessageGet.Content.ReadAsStringAsync();
var result = await httpResponseMessageGet.Content.ReadAsStringAsync(cancellationToken);
result.Should().Be("Here's a string.");
// Verify
@@ -122,12 +125,13 @@ public class WireMockServerAdminFilesTests
public async Task WireMockServer_Admin_Files_GetUTF16()
{
// Arrange
byte[] symbol = Encoding.UTF32.GetBytes(char.ConvertFromUtf32(0x1D161));
var cancellationToken = TestContext.Current.CancellationToken;
var symbol = Encoding.UTF32.GetBytes(char.ConvertFromUtf32(0x1D161));
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(symbol);
var server = WireMockServer.Start(new WireMockServerSettings
using var server = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
@@ -139,12 +143,12 @@ public class WireMockServerAdminFilesTests
multipartFormDataContent.Add(new StreamContent(new MemoryStream()));
// Act
var httpResponseMessageGet = await _client.GetAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.bin");
var httpResponseMessageGet = await _client.GetAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.bin", cancellationToken);
// Assert
httpResponseMessageGet.StatusCode.Should().Be(HttpStatusCode.OK);
var result = await httpResponseMessageGet.Content.ReadAsByteArrayAsync();
var result = await httpResponseMessageGet.Content.ReadAsByteArrayAsync(cancellationToken);
result.Should().BeEquivalentTo(symbol);
// Verify
@@ -157,10 +161,11 @@ public class WireMockServerAdminFilesTests
public async Task WireMockServer_Admin_Files_Head()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
var server = WireMockServer.Start(new WireMockServerSettings
using var server = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
@@ -170,7 +175,7 @@ public class WireMockServerAdminFilesTests
// Act
var requestUri = "http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, requestUri);
var httpResponseMessage = await _client.SendAsync(httpRequestMessage);
var httpResponseMessage = await _client.SendAsync(httpRequestMessage, cancellationToken);
// Assert
httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.NoContent);
@@ -184,10 +189,11 @@ public class WireMockServerAdminFilesTests
public async Task WireMockServer_Admin_Files_Head_FileDoesNotExistsReturns404()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false);
var server = WireMockServer.Start(new WireMockServerSettings
using var server = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
@@ -197,7 +203,7 @@ public class WireMockServerAdminFilesTests
// Act
var requestUri = "http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, requestUri);
var httpResponseMessage = await _client.SendAsync(httpRequestMessage);
var httpResponseMessage = await _client.SendAsync(httpRequestMessage, cancellationToken);
// Assert
httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.NotFound);

View File

@@ -23,7 +23,8 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithBodyAsJson_Using_PostAsJsonAsync_And_MultipleJmesPathMatchers_ShouldMatch()
{
// Arrange
var server = WireMockServer.Start();
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server.Given(
Request.Create()
.WithPath("/a")
@@ -56,7 +57,7 @@ public partial class WireMockServerTests
var requestUri = new Uri($"http://localhost:{server.Port}/a");
var json = new { requestId = "1", value = "A" };
var response = await server.CreateClient().PostAsJsonAsync(requestUri, json);
var response = await server.CreateClient().PostAsJsonAsync(requestUri, json, cancellationToken);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -68,7 +69,8 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithBodyAsJson_Using_PostAsJsonAsync_And_MultipleJmesPathMatchers_ShouldMatch_BestMatching()
{
// Arrange
var server = WireMockServer.Start();
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server.Given(
Request.Create()
.WithPath("/a")
@@ -104,7 +106,7 @@ public partial class WireMockServerTests
var requestUri = new Uri($"http://localhost:{server.Port}/a");
var json = new { extra = "X", requestId = "1", value = "A" };
var response = await server.CreateClient().PostAsJsonAsync(requestUri, json);
var response = await server.CreateClient().PostAsJsonAsync(requestUri, json, cancellationToken);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -116,7 +118,8 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithBodyAsJson_Using_PostAsJsonAsync_And_WildcardMatcher_ShouldMatch()
{
// Arrange
var server = WireMockServer.Start();
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server.Given(
Request.Create().UsingPost().WithPath("/foo").WithBody(new WildcardMatcher("*Hello*"))
)
@@ -130,7 +133,7 @@ public partial class WireMockServerTests
};
// Act
var response = await new HttpClient().PostAsJsonAsync("http://localhost:" + server.Ports[0] + "/foo", jsonObject);
var response = await new HttpClient().PostAsJsonAsync("http://localhost:" + server.Ports[0] + "/foo", jsonObject, cancellationToken);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -142,7 +145,8 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithBodyAsJson_Using_PostAsync_And_WildcardMatcher_ShouldMatch()
{
// Arrange
var server = WireMockServer.Start();
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server.Given(
Request.Create().UsingPost().WithPath("/foo").WithBody(new WildcardMatcher("*Hello*"))
)
@@ -151,7 +155,7 @@ public partial class WireMockServerTests
);
// Act
var response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/foo", new StringContent("{ Hi = \"Hello World\" }"));
var response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/foo", new StringContent("{ Hi = \"Hello World\" }"), cancellationToken);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -163,6 +167,7 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithBodyAsJson_Using_PostAsync_And_JsonPartialWildcardMatcher_ShouldMatch()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
var matcher = new JsonPartialWildcardMatcher(new { method = "initialize", id = "^[a-f0-9]{32}-[0-9]$" }, ignoreCase: true, regex: true);
@@ -182,16 +187,15 @@ public partial class WireMockServerTests
);
// Act
var cancelationToken = TestContext.Current.CancellationToken;
var content = "{\"jsonrpc\":\"2.0\",\"id\":\"ec475f56d4694b48bc737500ba575b35-1\",\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"GitHub Test\",\"version\":\"1.0.0\"}}}";
var response = await new HttpClient()
.PostAsync($"{server.Url}/foo", new StringContent(content, Encoding.UTF8, "application/json"), cancelationToken)
.PostAsync($"{server.Url}/foo", new StringContent(content, Encoding.UTF8, "application/json"), cancellationToken)
;
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseText = await response.Content.ReadAsStringAsync(cancelationToken);
var responseText = await response.Content.ReadAsStringAsync(cancellationToken);
responseText.Should().Contain("ec475f56d4694b48bc737500ba575b35-1");
}
@@ -200,6 +204,7 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithBodyAsJson_Using_PostAsync_And_JsonPartialWildcardMatcher_And_SystemTextJson_ShouldMatch()
{
// Arrange
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start(x => x.DefaultJsonSerializer = new JsonConverter.System.Text.Json.SystemTextJsonConverter() );
var matcher = new JsonPartialWildcardMatcher(new { id = "^[a-f0-9]{32}-[0-9]$" }, ignoreCase: true, regex: true);
@@ -216,12 +221,12 @@ public partial class WireMockServerTests
// Act
var content = """{"id":"ec475f56d4694b48bc737500ba575b35-1"}""";
using var httpClient = new HttpClient();
var response = await httpClient.PostAsync($"{server.Url}/system-text-json", new StringContent(content, Encoding.UTF8, "application/json"));
var response = await httpClient.PostAsync($"{server.Url}/system-text-json", new StringContent(content, Encoding.UTF8, "application/json"), cancellationToken);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseText = await response.Content.ReadAsStringAsync();
var responseText = await response.Content.ReadAsStringAsync(cancellationToken);
responseText.Should().Contain("OK");
}
#endif
@@ -245,8 +250,7 @@ public partial class WireMockServerTests
// Act
var content = new FormUrlEncodedContent([new KeyValuePair<string, string>("key1", "value1")]);
var response = await new HttpClient()
.PostAsync($"{server.Url}/foo", content, cancelationToken)
;
.PostAsync($"{server.Url}/foo", content, cancelationToken);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -258,7 +262,8 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithBodyAsFormUrlEncoded_Using_PostAsync_And_WithExactMatcher()
{
// Arrange
var server = WireMockServer.Start();
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server.Given(
Request.Create()
.UsingPost()
@@ -272,15 +277,14 @@ public partial class WireMockServerTests
);
// Act
var content = new FormUrlEncodedContent(new[]
{
var content = new FormUrlEncodedContent(
[
new KeyValuePair<string, string>("name", "John Doe"),
new KeyValuePair<string, string>("email", "johndoe@example.com")
});
var response = await new HttpClient()
.PostAsync($"{server.Url}/foo", content)
]);
using var httpClient = new HttpClient();
var response = await httpClient.PostAsync($"{server.Url}/foo", content, cancellationToken)
;
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -293,7 +297,7 @@ public partial class WireMockServerTests
// Arrange
var cancelationToken = TestContext.Current.CancellationToken;
var matcher = new FormUrlEncodedMatcher(["email=johndoe@example.com", "name=John Doe"]);
var server = WireMockServer.Start();
using var server = WireMockServer.Start();
server.Given(
Request.Create()
.UsingPost()
@@ -317,11 +321,11 @@ public partial class WireMockServerTests
);
// Act 1
var contentOrdered = new FormUrlEncodedContent(new[]
{
var contentOrdered = new FormUrlEncodedContent(
[
new KeyValuePair<string, string>("name", "John Doe"),
new KeyValuePair<string, string>("email", "johndoe@example.com")
});
]);
var responseOrdered = await new HttpClient()
.PostAsync($"{server.Url}/foo", contentOrdered, cancelationToken)
;
@@ -331,11 +335,11 @@ public partial class WireMockServerTests
// Act 2
var contentUnordered = new FormUrlEncodedContent(new[]
{
var contentUnordered = new FormUrlEncodedContent(
[
new KeyValuePair<string, string>("email", "johndoe@example.com"),
new KeyValuePair<string, string>("name", "John Doe"),
});
]);
var responseUnordered = await new HttpClient()
.PostAsync($"{server.Url}/bar", contentUnordered, cancelationToken)
;
@@ -350,7 +354,8 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithSseBody()
{
// Arrange
var server = WireMockServer.Start();
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server
.WhenRequest(r => r
.UsingGet()
@@ -383,10 +388,9 @@ public partial class WireMockServerTests
using var client = new HttpClient();
// Act 1
var normal = await new HttpClient()
.GetAsync(server.Url)
var normal = await client.GetAsync(server.Url, cancellationToken)
;
(await normal.Content.ReadAsStringAsync()).Should().Be("normal");
(await normal.Content.ReadAsStringAsync(cancellationToken)).Should().Be("normal");
// Act 2
using var response = await client.GetStreamAsync($"{server.Url}/sse");
@@ -395,7 +399,7 @@ public partial class WireMockServerTests
var data = string.Empty;
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync();
var line = reader.ReadLine();
data += line;
}

View File

@@ -67,7 +67,7 @@ public partial class WireMockServerTests
var server = WireMockServer.Start();
// Act
await server.CreateClient().GetAsync("/foo");
await server.CreateClient().GetAsync("/foo", TestContext.Current.CancellationToken);
server.ResetLogEntries();
// Assert
@@ -245,7 +245,7 @@ public partial class WireMockServerTests
foreach (var address in IPv6)
{
// 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", TestContext.Current.CancellationToken);
// Assert
response.Should().Be("x");