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 // Copyright © WireMock.Net
using System.Net.Http;
using RestEase; using RestEase;
using WireMock.Client; using WireMock.Client;
using WireMock.Matchers; using WireMock.Matchers;
@@ -50,7 +51,7 @@ message HelloReply {
// Act // Act
var client = server.CreateClient(); 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); await VerifyJson(getMappingsResult, VerifySettings);
} }

View File

@@ -8,80 +8,39 @@ namespace System.Net.Http;
/// </summary> /// </summary>
internal static class HttpClientExtensions internal static class HttpClientExtensions
{ {
/// <summary> public static Task<Stream> GetStreamAsync(this HttpClient client, Uri requestUri, CancellationToken _)
/// 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. return client.GetStreamAsync(requestUri);
/// </summary> }
public static Task<HttpResponseMessage> GetAsync(this HttpClient client, Uri requestUri, CancellationToken _) 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); 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 _) 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); 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 _) 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); 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 _) 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); 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 _) 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); 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 _) 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); 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 #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 public class ProtoBufUtilsTests
{ {
private static readonly IProtoBufUtils ProtoBufUtils = new ProtoBufUtils(); private static readonly ProtoBufUtils _sut = new();
[Fact] [Fact]
public async Task GetProtoBufMessageWithHeader_MultipleProtoFiles() public async Task GetProtoBufMessageWithHeader_MultipleProtoFiles()
@@ -17,7 +17,7 @@ public class ProtoBufUtilsTests
var request = ReadProtoFile("request.proto"); var request = ReadProtoFile("request.proto");
// Act // Act
var responseBytes = await ProtoBufUtils.GetProtoBufMessageWithHeaderAsync( var responseBytes = await _sut.GetProtoBufMessageWithHeaderAsync(
[greet, request], [greet, request],
"greet.HelloRequest", new "greet.HelloRequest", new
{ {
@@ -30,7 +30,7 @@ public class ProtoBufUtilsTests
Convert.ToBase64String(responseBytes).Should().Be("AAAAAAcKBWhlbGxv"); 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)); return File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "Grpc", filename));
} }

View File

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

View File

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

View File

@@ -14,18 +14,19 @@ namespace WireMock.Net.Tests;
public class WireMockServerAdminFilesTests public class WireMockServerAdminFilesTests
{ {
private readonly HttpClient _client = new HttpClient(); private readonly HttpClient _client = new();
[Fact] [Fact]
public async Task WireMockServer_Admin_Files_Post_Ascii() public async Task WireMockServer_Admin_Files_Post_Ascii()
{ {
// Arrange // Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("__admin/mappings"); filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("__admin/mappings");
filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(true); filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>())); 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, UseSSL = false,
StartAdminInterface = true, StartAdminInterface = true,
@@ -37,7 +38,7 @@ public class WireMockServerAdminFilesTests
multipartFormDataContent.Add(new StreamContent(new MemoryStream(Encoding.ASCII.GetBytes("Here's a string.")))); multipartFormDataContent.Add(new StreamContent(new MemoryStream(Encoding.ASCII.GetBytes("Here's a string."))));
// Act // 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 // Assert
httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.OK); httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -53,13 +54,14 @@ public class WireMockServerAdminFilesTests
public async Task WireMockServer_Admin_Files_Post_MappingFolderDoesNotExistsButWillBeCreated() public async Task WireMockServer_Admin_Files_Post_MappingFolderDoesNotExistsButWillBeCreated()
{ {
// Arrange // Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("x"); filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("x");
filesystemHandlerMock.Setup(fs => fs.CreateFolder(It.IsAny<string>())); filesystemHandlerMock.Setup(fs => fs.CreateFolder(It.IsAny<string>()));
filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(false); filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(false);
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>())); 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, UseSSL = false,
StartAdminInterface = true, StartAdminInterface = true,
@@ -71,7 +73,7 @@ public class WireMockServerAdminFilesTests
multipartFormDataContent.Add(new StreamContent(new MemoryStream(Encoding.ASCII.GetBytes("Here's a string.")))); multipartFormDataContent.Add(new StreamContent(new MemoryStream(Encoding.ASCII.GetBytes("Here's a string."))));
// Act // 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 // Assert
httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.OK); httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -88,11 +90,12 @@ public class WireMockServerAdminFilesTests
public async Task WireMockServer_Admin_Files_GetAscii() public async Task WireMockServer_Admin_Files_GetAscii()
{ {
// Arrange // Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true); 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.")); 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, UseSSL = false,
StartAdminInterface = true, StartAdminInterface = true,
@@ -104,12 +107,12 @@ public class WireMockServerAdminFilesTests
multipartFormDataContent.Add(new StreamContent(new MemoryStream())); multipartFormDataContent.Add(new StreamContent(new MemoryStream()));
// Act // 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 // Assert
httpResponseMessageGet.StatusCode.Should().Be(HttpStatusCode.OK); 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."); result.Should().Be("Here's a string.");
// Verify // Verify
@@ -122,12 +125,13 @@ public class WireMockServerAdminFilesTests
public async Task WireMockServer_Admin_Files_GetUTF16() public async Task WireMockServer_Admin_Files_GetUTF16()
{ {
// Arrange // 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); var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true); filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(symbol); 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, UseSSL = false,
StartAdminInterface = true, StartAdminInterface = true,
@@ -139,12 +143,12 @@ public class WireMockServerAdminFilesTests
multipartFormDataContent.Add(new StreamContent(new MemoryStream())); multipartFormDataContent.Add(new StreamContent(new MemoryStream()));
// Act // 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 // Assert
httpResponseMessageGet.StatusCode.Should().Be(HttpStatusCode.OK); httpResponseMessageGet.StatusCode.Should().Be(HttpStatusCode.OK);
var result = await httpResponseMessageGet.Content.ReadAsByteArrayAsync(); var result = await httpResponseMessageGet.Content.ReadAsByteArrayAsync(cancellationToken);
result.Should().BeEquivalentTo(symbol); result.Should().BeEquivalentTo(symbol);
// Verify // Verify
@@ -157,10 +161,11 @@ public class WireMockServerAdminFilesTests
public async Task WireMockServer_Admin_Files_Head() public async Task WireMockServer_Admin_Files_Head()
{ {
// Arrange // Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true); 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, UseSSL = false,
StartAdminInterface = true, StartAdminInterface = true,
@@ -170,7 +175,7 @@ public class WireMockServerAdminFilesTests
// Act // Act
var requestUri = "http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt"; var requestUri = "http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, requestUri); var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, requestUri);
var httpResponseMessage = await _client.SendAsync(httpRequestMessage); var httpResponseMessage = await _client.SendAsync(httpRequestMessage, cancellationToken);
// Assert // Assert
httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.NoContent); httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.NoContent);
@@ -184,10 +189,11 @@ public class WireMockServerAdminFilesTests
public async Task WireMockServer_Admin_Files_Head_FileDoesNotExistsReturns404() public async Task WireMockServer_Admin_Files_Head_FileDoesNotExistsReturns404()
{ {
// Arrange // Arrange
var cancellationToken = TestContext.Current.CancellationToken;
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false); 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, UseSSL = false,
StartAdminInterface = true, StartAdminInterface = true,
@@ -197,7 +203,7 @@ public class WireMockServerAdminFilesTests
// Act // Act
var requestUri = "http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt"; var requestUri = "http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, requestUri); var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, requestUri);
var httpResponseMessage = await _client.SendAsync(httpRequestMessage); var httpResponseMessage = await _client.SendAsync(httpRequestMessage, cancellationToken);
// Assert // Assert
httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.NotFound); 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() public async Task WireMockServer_WithBodyAsJson_Using_PostAsJsonAsync_And_MultipleJmesPathMatchers_ShouldMatch()
{ {
// Arrange // Arrange
var server = WireMockServer.Start(); var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server.Given( server.Given(
Request.Create() Request.Create()
.WithPath("/a") .WithPath("/a")
@@ -56,7 +57,7 @@ public partial class WireMockServerTests
var requestUri = new Uri($"http://localhost:{server.Port}/a"); var requestUri = new Uri($"http://localhost:{server.Port}/a");
var json = new { requestId = "1", value = "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 // Assert
response.StatusCode.Should().Be(HttpStatusCode.OK); 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() public async Task WireMockServer_WithBodyAsJson_Using_PostAsJsonAsync_And_MultipleJmesPathMatchers_ShouldMatch_BestMatching()
{ {
// Arrange // Arrange
var server = WireMockServer.Start(); var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server.Given( server.Given(
Request.Create() Request.Create()
.WithPath("/a") .WithPath("/a")
@@ -104,7 +106,7 @@ public partial class WireMockServerTests
var requestUri = new Uri($"http://localhost:{server.Port}/a"); var requestUri = new Uri($"http://localhost:{server.Port}/a");
var json = new { extra = "X", requestId = "1", value = "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 // Assert
response.StatusCode.Should().Be(HttpStatusCode.OK); response.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -116,7 +118,8 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithBodyAsJson_Using_PostAsJsonAsync_And_WildcardMatcher_ShouldMatch() public async Task WireMockServer_WithBodyAsJson_Using_PostAsJsonAsync_And_WildcardMatcher_ShouldMatch()
{ {
// Arrange // Arrange
var server = WireMockServer.Start(); var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server.Given( server.Given(
Request.Create().UsingPost().WithPath("/foo").WithBody(new WildcardMatcher("*Hello*")) Request.Create().UsingPost().WithPath("/foo").WithBody(new WildcardMatcher("*Hello*"))
) )
@@ -130,7 +133,7 @@ public partial class WireMockServerTests
}; };
// Act // 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 // Assert
response.StatusCode.Should().Be(HttpStatusCode.OK); response.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -142,7 +145,8 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithBodyAsJson_Using_PostAsync_And_WildcardMatcher_ShouldMatch() public async Task WireMockServer_WithBodyAsJson_Using_PostAsync_And_WildcardMatcher_ShouldMatch()
{ {
// Arrange // Arrange
var server = WireMockServer.Start(); var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server.Given( server.Given(
Request.Create().UsingPost().WithPath("/foo").WithBody(new WildcardMatcher("*Hello*")) Request.Create().UsingPost().WithPath("/foo").WithBody(new WildcardMatcher("*Hello*"))
) )
@@ -151,7 +155,7 @@ public partial class WireMockServerTests
); );
// Act // 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 // Assert
response.StatusCode.Should().Be(HttpStatusCode.OK); response.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -163,6 +167,7 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithBodyAsJson_Using_PostAsync_And_JsonPartialWildcardMatcher_ShouldMatch() public async Task WireMockServer_WithBodyAsJson_Using_PostAsync_And_JsonPartialWildcardMatcher_ShouldMatch()
{ {
// Arrange // Arrange
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start(); using var server = WireMockServer.Start();
var matcher = new JsonPartialWildcardMatcher(new { method = "initialize", id = "^[a-f0-9]{32}-[0-9]$" }, ignoreCase: true, regex: true); 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 // 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 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() 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 // Assert
response.StatusCode.Should().Be(HttpStatusCode.OK); 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"); 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() public async Task WireMockServer_WithBodyAsJson_Using_PostAsync_And_JsonPartialWildcardMatcher_And_SystemTextJson_ShouldMatch()
{ {
// Arrange // Arrange
var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start(x => x.DefaultJsonSerializer = new JsonConverter.System.Text.Json.SystemTextJsonConverter() ); 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); 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 // Act
var content = """{"id":"ec475f56d4694b48bc737500ba575b35-1"}"""; var content = """{"id":"ec475f56d4694b48bc737500ba575b35-1"}""";
using var httpClient = new HttpClient(); 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 // Assert
response.StatusCode.Should().Be(HttpStatusCode.OK); response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseText = await response.Content.ReadAsStringAsync(); var responseText = await response.Content.ReadAsStringAsync(cancellationToken);
responseText.Should().Contain("OK"); responseText.Should().Contain("OK");
} }
#endif #endif
@@ -245,8 +250,7 @@ public partial class WireMockServerTests
// Act // Act
var content = new FormUrlEncodedContent([new KeyValuePair<string, string>("key1", "value1")]); var content = new FormUrlEncodedContent([new KeyValuePair<string, string>("key1", "value1")]);
var response = await new HttpClient() var response = await new HttpClient()
.PostAsync($"{server.Url}/foo", content, cancelationToken) .PostAsync($"{server.Url}/foo", content, cancelationToken);
;
// Assert // Assert
response.StatusCode.Should().Be(HttpStatusCode.OK); response.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -258,7 +262,8 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithBodyAsFormUrlEncoded_Using_PostAsync_And_WithExactMatcher() public async Task WireMockServer_WithBodyAsFormUrlEncoded_Using_PostAsync_And_WithExactMatcher()
{ {
// Arrange // Arrange
var server = WireMockServer.Start(); var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server.Given( server.Given(
Request.Create() Request.Create()
.UsingPost() .UsingPost()
@@ -272,15 +277,14 @@ public partial class WireMockServerTests
); );
// Act // Act
var content = new FormUrlEncodedContent(new[] var content = new FormUrlEncodedContent(
{ [
new KeyValuePair<string, string>("name", "John Doe"), new KeyValuePair<string, string>("name", "John Doe"),
new KeyValuePair<string, string>("email", "johndoe@example.com") new KeyValuePair<string, string>("email", "johndoe@example.com")
}); ]);
var response = await new HttpClient() using var httpClient = new HttpClient();
.PostAsync($"{server.Url}/foo", content) var response = await httpClient.PostAsync($"{server.Url}/foo", content, cancellationToken)
; ;
// Assert // Assert
response.StatusCode.Should().Be(HttpStatusCode.OK); response.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -293,7 +297,7 @@ public partial class WireMockServerTests
// Arrange // Arrange
var cancelationToken = TestContext.Current.CancellationToken; var cancelationToken = TestContext.Current.CancellationToken;
var matcher = new FormUrlEncodedMatcher(["email=johndoe@example.com", "name=John Doe"]); var matcher = new FormUrlEncodedMatcher(["email=johndoe@example.com", "name=John Doe"]);
var server = WireMockServer.Start(); using var server = WireMockServer.Start();
server.Given( server.Given(
Request.Create() Request.Create()
.UsingPost() .UsingPost()
@@ -317,11 +321,11 @@ public partial class WireMockServerTests
); );
// Act 1 // Act 1
var contentOrdered = new FormUrlEncodedContent(new[] var contentOrdered = new FormUrlEncodedContent(
{ [
new KeyValuePair<string, string>("name", "John Doe"), new KeyValuePair<string, string>("name", "John Doe"),
new KeyValuePair<string, string>("email", "johndoe@example.com") new KeyValuePair<string, string>("email", "johndoe@example.com")
}); ]);
var responseOrdered = await new HttpClient() var responseOrdered = await new HttpClient()
.PostAsync($"{server.Url}/foo", contentOrdered, cancelationToken) .PostAsync($"{server.Url}/foo", contentOrdered, cancelationToken)
; ;
@@ -331,11 +335,11 @@ public partial class WireMockServerTests
// Act 2 // Act 2
var contentUnordered = new FormUrlEncodedContent(new[] var contentUnordered = new FormUrlEncodedContent(
{ [
new KeyValuePair<string, string>("email", "johndoe@example.com"), new KeyValuePair<string, string>("email", "johndoe@example.com"),
new KeyValuePair<string, string>("name", "John Doe"), new KeyValuePair<string, string>("name", "John Doe"),
}); ]);
var responseUnordered = await new HttpClient() var responseUnordered = await new HttpClient()
.PostAsync($"{server.Url}/bar", contentUnordered, cancelationToken) .PostAsync($"{server.Url}/bar", contentUnordered, cancelationToken)
; ;
@@ -350,7 +354,8 @@ public partial class WireMockServerTests
public async Task WireMockServer_WithSseBody() public async Task WireMockServer_WithSseBody()
{ {
// Arrange // Arrange
var server = WireMockServer.Start(); var cancellationToken = TestContext.Current.CancellationToken;
using var server = WireMockServer.Start();
server server
.WhenRequest(r => r .WhenRequest(r => r
.UsingGet() .UsingGet()
@@ -383,10 +388,9 @@ public partial class WireMockServerTests
using var client = new HttpClient(); using var client = new HttpClient();
// Act 1 // Act 1
var normal = await new HttpClient() var normal = await client.GetAsync(server.Url, cancellationToken)
.GetAsync(server.Url)
; ;
(await normal.Content.ReadAsStringAsync()).Should().Be("normal"); (await normal.Content.ReadAsStringAsync(cancellationToken)).Should().Be("normal");
// Act 2 // Act 2
using var response = await client.GetStreamAsync($"{server.Url}/sse"); using var response = await client.GetStreamAsync($"{server.Url}/sse");
@@ -395,7 +399,7 @@ public partial class WireMockServerTests
var data = string.Empty; var data = string.Empty;
while (!reader.EndOfStream) while (!reader.EndOfStream)
{ {
var line = await reader.ReadLineAsync(); var line = reader.ReadLine();
data += line; data += line;
} }

View File

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