Merge branch 'master' into SystemTextJsonMatcher

This commit is contained in:
Stef Heyenrath
2026-05-03 09:28:26 +02:00
35 changed files with 453 additions and 10 deletions

View File

@@ -8,8 +8,11 @@ using ExampleIntegrationTest.Lookup;
using Google.Protobuf.WellKnownTypes;
using Greet;
using Grpc.Net.Client;
using Moq;
using WireMock.Constants;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.Net.Xunit;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
@@ -78,7 +81,7 @@ import ""google/protobuf/empty.proto"";
service Greeter {
rpc Nothing (google.protobuf.Empty) returns (google.protobuf.Empty);
rpc SayHello (HelloRequest) returns (HelloReply);
rpc SayOther (Other) returns (HelloReply);
@@ -731,6 +734,93 @@ message Other {
Then_ReplyMessage_Should_BeCorrect(reply);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task WireMockServer_WithBodyAsProtoBuf_WithEarlyMismatch_ErrorLogs_Issue1442(
bool withEarlyMismatch)
{
// Arrange
var greeterId = $"test-greeter-{Guid.NewGuid()}";
var policyId = $"test-policy-{Guid.NewGuid()}";
var ct = TestContext.Current.CancellationToken;
var greeterProtoDefinition = ProtoDefinition;
var policyProtoDefinition = File.ReadAllText("./Grpc/policy.proto");
var mockTestOutputHelper = new Mock<ITestOutputHelper>();
using var server = WireMockServer.Start(new WireMockServerSettings
{
UseHttp2 = true,
Logger = new TestOutputHelperWireMockLogger(mockTestOutputHelper.Object)
});
server
.AddProtoDefinition(greeterId, greeterProtoDefinition)
.Given(Request.Create()
.UsingPost()
.WithHttpVersion("2")
.WithPath("/greet.Greeter/SayHello")
.WithEarlyMismatch(withEarlyMismatch
? RequestMatcherType.Path
: null)
.WithBodyAsProtoBuf("greet.HelloRequest", new JsonMatcher(new { name = "stef" })))
.WithProtoDefinition(greeterId)
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/grpc")
.WithTrailingHeader("grpc-status", "0")
.WithBodyAsProtoBuf("greet.HelloReply",
new
{
message = "hello {{request.BodyAsJson.name}} {{request.method}}"
})
.WithTransformer());
server
.AddProtoDefinition(policyId, policyProtoDefinition)
.Given(Request.Create()
.UsingPost()
.WithHttpVersion("2")
.WithPath("/Policy.PolicyService/GetVersion")
.WithEarlyMismatch(withEarlyMismatch
? RequestMatcherType.Path
: null)
.WithBodyAsProtoBuf("ExampleIntegrationTest.Lookup.GetVersionRequest", new NotNullOrEmptyMatcher()))
.WithProtoDefinition(policyId)
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/grpc")
.WithTrailingHeader("grpc-status", "0")
.WithBodyAsProtoBuf("ExampleIntegrationTest.Lookup.GetVersionResponse",
new GetVersionResponse
{
Version = "test",
DateHired = new Timestamp
{
Seconds = 1722301323,
Nanos = 12300
},
Client = new ExampleIntegrationTest.Lookup.Client
{
ClientName = ExampleIntegrationTest.Lookup.Client.Types.Clients.Test,
CorrelationId = "correlation"
}
})
.WithTransformer());
// Act
var channel = GrpcChannel.ForAddress(server.Url!);
var policyServiceClient = new PolicyService.PolicyServiceClient(channel);
var greeterClient = new Greeter.GreeterClient(channel);
_ = await policyServiceClient.GetVersionAsync(new GetVersionRequest(), cancellationToken: ct);
_ = await greeterClient.SayHelloAsync(new HelloRequest { Name = "stef" }, cancellationToken: ct);
mockTestOutputHelper.Verify(
x => x.WriteLine(
It.Is<string>(log => log.Contains("[Error]") && log.Contains("Exception"))),
withEarlyMismatch ? Times.Never : Times.AtLeastOnce);
}
private static WireMockServer Given_When_ServerStarted_And_RunningOnHttpAndGrpc()
{
var settings = new WireMockServerSettings

View File

@@ -1,8 +1,11 @@
// Copyright © WireMock.Net
using Moq;
using WireMock.Constants;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.RequestBuilders;
namespace WireMock.Net.Tests.RequestMatchers;
@@ -10,8 +13,12 @@ public class RequestMessageCompositeMatcherTests
{
private class Helper : RequestMessageCompositeMatcher
{
public Helper(IEnumerable<IRequestMatcher> requestMatchers, CompositeMatcherType type = CompositeMatcherType.And) : base(requestMatchers, type)
public Helper(
IEnumerable<IRequestMatcher> requestMatchers,
CompositeMatcherType type = CompositeMatcherType.And,
RequestMatcherType? earlyMatcherType = null) : base(requestMatchers, type)
{
EarlyMatcherType = earlyMatcherType;
}
}
@@ -77,4 +84,74 @@ public class RequestMessageCompositeMatcherTests
requestMatcher1Mock.Verify(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>()), Times.Once);
requestMatcher2Mock.Verify(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>()), Times.Once);
}
[Fact]
public void RequestMessageCompositeMatcher_GetMatchingScore_EarlyMismatch()
{
// Assign
var requestMatcher1Mock = new Mock<IRequestMatcher>();
requestMatcher1Mock.Setup(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>())).Returns(1.0d);
var requestMatcher2Mock = new Mock<IRequestMatcher>();
requestMatcher2Mock.Setup(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>())).Returns(0.8d);
var postMatcher = new RequestMessageMethodMatcher(HttpRequestMethod.POST);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), HttpRequestMethod.GET, "127.0.0.1");
var matcher = new Helper(
[requestMatcher1Mock.Object, requestMatcher2Mock.Object, postMatcher],
earlyMatcherType: RequestMatcherType.Method);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
score.Should().Be(0.0d);
// Verify
requestMatcher1Mock.Verify(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>()), Times.Never);
requestMatcher2Mock.Verify(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>()), Times.Never);
}
[Fact]
public void RequestMessageCompositeMatcher_GetMatchingScore_SeveralHeadersEarlyMismatch()
{
// Assign
var headers = new Dictionary<string, string[]>
{
{ "teST", new[] { "x" } },
{ "teST2", new[] { "z" } }
};
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers);
var request = Request.Create()
.WithEarlyMismatch(RequestMatcherType.Header)
.UsingAnyMethod()
.WithHeader("teST", "x")
.WithHeader("teST1", ["xx", "yy"])
.WithHeader("teST2", ["y", "z"], matchOperator: MatchOperator.And);
// Act
var score = request.GetMatchingScore(requestMessage, new RequestMatchResult());
// Assert
score.Should().Be(0.0d);
}
[Fact]
public void RequestMessageCompositeMatcher_GetMatchingScore_SeveralParamEarlyMismatchSuccess()
{
// Assign
var uriWithParams = new Uri("http://localhost?test1=1&test2=2");
var requestMessage = new RequestMessage(new UrlDetails(uriWithParams), "GET", "127.0.0.1");
var request = Request.Create()
.WithEarlyMismatch(RequestMatcherType.Param)
.UsingAnyMethod()
.WithParam("test1", "1")
.WithParam("test2", "2");
// Act
var score = request.GetMatchingScore(requestMessage, new RequestMatchResult());
// Assert
score.Should().Be(1.0d);
}
}

View File

@@ -1,5 +1,6 @@
// Copyright © WireMock.Net
using WireMock.Matchers.Request;
using WireMock.Net.Tests.VerifyExtensions;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
@@ -101,6 +102,7 @@ public partial class MappingConverterTests
var guid = new Guid("8e7b9ab7-e18e-4502-8bc9-11e6679811cc");
var request = Request.Create()
.UsingGet()
.WithEarlyMismatch(RequestMatcherType.Method)
.WithPath("/test_path")
.WithParam("q", "42")
.WithClientIP("112.123.100.99")

View File

@@ -1,5 +1,6 @@
builder
.Given(Request.Create()
.WithEarlyMismatch(WireMock.Matchers.Request.RequestMatcherType.Method)
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/test_path", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("q", new ExactMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, false, WireMock.Matchers.MatchOperator.And, "42"))

View File

@@ -1,6 +1,7 @@
var builder = new MappingBuilder();
builder
.Given(Request.Create()
.WithEarlyMismatch(WireMock.Matchers.Request.RequestMatcherType.Method)
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/test_path", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("q", new ExactMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, false, WireMock.Matchers.MatchOperator.And, "42"))

View File

@@ -1,5 +1,6 @@
server
.Given(Request.Create()
.WithEarlyMismatch(WireMock.Matchers.Request.RequestMatcherType.Method)
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/test_path", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("q", new ExactMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, false, WireMock.Matchers.MatchOperator.And, "42"))

View File

@@ -1,6 +1,7 @@
var server = WireMockServer.Start();
server
.Given(Request.Create()
.WithEarlyMismatch(WireMock.Matchers.Request.RequestMatcherType.Method)
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/test_path", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("q", new ExactMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, false, WireMock.Matchers.MatchOperator.And, "42"))

View File

@@ -19,7 +19,7 @@
id:ID!
firstName:String
lastName:String
fullName:String
fullName:String
}
}
}

View File

@@ -0,0 +1,34 @@
{
Guid: Guid_1,
UpdatedAt: DateTime_1,
Title: ,
Description: ,
Priority: 42,
Request: {
Path: {
Matchers: [
{
Name: WildcardMatcher,
Pattern: 1.2.3.4,
IgnoreCase: false
}
]
},
Headers: [
{
Name: x1,
Matchers: [
{
Name: WildcardMatcher,
Pattern: y,
IgnoreCase: true
}
],
IgnoreCase: true
}
],
EarlyMatcherType: ClientIP
},
Response: {},
UseWebhooksFireAndForget: false
}

View File

@@ -1,6 +1,7 @@
// Copyright © WireMock.Net
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
@@ -538,7 +539,7 @@ message HelloReply {
id:ID!
firstName:String
lastName:String
fullName:String
fullName:String
}";
var request = Request.Create().WithGraphQLSchema(schema);
var response = Response.Create();
@@ -640,4 +641,25 @@ message HelloReply {
// Verify
return Verify(model);
}
[Fact]
public Task ToMappingModel_Request_WithEarlyMismatch_ReturnsCorrectModel()
{
// Arrange
var request = Request.Create().WithEarlyMismatch(RequestMatcherType.ClientIP)
.WithHeader("x1", "y")
.WithClientIP("1.2.3.4");
var response = Response.Create();
var mapping = new Mapping(_guid, _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Request.EarlyMatcherType.Should().Be(RequestMatcherType.ClientIP);
// Verify
return Verify(model);
}
}