From ea4ea95866cd8654150531c1413a38e2cc933672 Mon Sep 17 00:00:00 2001 From: Stef Heyenrath Date: Sat, 25 May 2024 09:09:03 +0200 Subject: [PATCH 1/2] Fix Request.Create().WithBodyAsJson(...) (#1111) * Fix Request.Create().WithBodyAsJson(...) * [CodeFactor] Apply fixes --------- Co-authored-by: codefactor-io --- .../MainApp.cs | 63 +++++++------------ .../RequestBuilders/IBodyRequestBuilder.cs | 12 +--- .../RequestBuilders/Request.WithBody.cs | 16 +---- .../RequestBuilderWithBodyTests.cs | 42 +++---------- 4 files changed, 30 insertions(+), 103 deletions(-) diff --git a/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs b/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs index cc211d5d..e9a89eac 100644 --- a/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs +++ b/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs @@ -97,34 +97,30 @@ message HelloReply { private static void RunOnLocal() { - var localIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork); - - //try - //{ - // var server = WireMockServer.Start(new WireMockServerSettings - // { - // Urls = new[] { $"http://{localIP}:9091" }, - // StartAdminInterface = true - // }); - // System.Console.WriteLine($"1: {string.Join(", ", server.Urls)}"); - - // System.Console.WriteLine("Press any key to stop..."); - // System.Console.ReadKey(); - // server.Stop(); - //} - //catch (Exception e) - //{ - // System.Console.WriteLine(e); - //} - try { var server = WireMockServer.Start(new WireMockServerSettings { Port = 9091, - StartAdminInterface = true + StartAdminInterface = true, + Logger = new WireMockConsoleLogger() }); - System.Console.WriteLine($"2: {string.Join(", ", server.Urls)}"); + System.Console.WriteLine(string.Join(", ", server.Urls)); + + var requestJson = new { PricingContext = new { Market = "USA" } }; + var responseJson = new { Market = "{{JsonPath.SelectToken request.body \"$.PricingContext.Market\"}}" }; + server + .Given(Request.Create() + //.WithBody(new JsonMatcher(requestJson)) + .WithBodyAsJson(requestJson) + .WithPath("/pricing") + .UsingPost() + ) + .RespondWith(Response.Create() + .WithHeader("Content-Type", "application/json") + .WithBodyAsJson(responseJson) + .WithTransformer(true) + ); System.Console.WriteLine("Press any key to stop..."); System.Console.ReadKey(); @@ -134,24 +130,6 @@ message HelloReply { { System.Console.WriteLine(e); } - - //try - //{ - // var server = WireMockServer.Start(new WireMockServerSettings - // { - // Urls = new[] { "http://*:9091" }, - // StartAdminInterface = true - // }); - // System.Console.WriteLine($"3: {string.Join(", ", server.Urls)}"); - - // System.Console.WriteLine("Press any key to stop..."); - // System.Console.ReadKey(); - // server.Stop(); - //} - //catch (Exception e) - //{ - // System.Console.WriteLine(e); - //} } public static void Run() @@ -251,7 +229,9 @@ message HelloReply { server.SetBasicAuthentication("a", "b"); //server.SetAzureADAuthentication("6c2a4722-f3b9-4970-b8fc-fac41e29stef", "8587fde1-7824-42c7-8592-faf92b04stef"); - // server.AllowPartialMapping(); + //var http = new HttpClient(); + //var response = await http.GetAsync($"{_wireMockServer.Url}/pricing"); + //var value = await response.Content.ReadAsStringAsync(); #if PROTOBUF var protoBufJsonMatcher = new JsonPartialWildcardMatcher(new { name = "*" }); @@ -395,7 +375,6 @@ message HelloReply { .WithHeader("Content-Type", "text/plain") ); - server .Given(Request.Create() .UsingMethod("GET") diff --git a/src/WireMock.Net/RequestBuilders/IBodyRequestBuilder.cs b/src/WireMock.Net/RequestBuilders/IBodyRequestBuilder.cs index 49751bd4..c0702247 100644 --- a/src/WireMock.Net/RequestBuilders/IBodyRequestBuilder.cs +++ b/src/WireMock.Net/RequestBuilders/IBodyRequestBuilder.cs @@ -51,23 +51,13 @@ public interface IBodyRequestBuilder : IProtoBufRequestBuilder IRequestBuilder WithBody(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); /// - /// WithBody : Body as a string response based on a object (which will be converted to a JSON string using NewtonSoft.Json). + /// WithBodyAsJson: A will be used to match this object. /// /// The body. /// The match behaviour [default is AcceptOnMatch]. /// A . IRequestBuilder WithBodyAsJson(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); - /// - /// WithBody : Body as a string response based on a object (which will be converted to a JSON string using the ). - /// - /// The body. - /// The JsonConverter. - /// The [optional]. - /// The match behaviour [default is AcceptOnMatch]. - /// A . - IRequestBuilder WithBodyAsJson(object body, IJsonConverter converter, JsonConverterOptions? options = null, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); - /// /// WithBody: func (string) /// diff --git a/src/WireMock.Net/RequestBuilders/Request.WithBody.cs b/src/WireMock.Net/RequestBuilders/Request.WithBody.cs index 884e4a1d..a64efb02 100644 --- a/src/WireMock.Net/RequestBuilders/Request.WithBody.cs +++ b/src/WireMock.Net/RequestBuilders/Request.WithBody.cs @@ -2,8 +2,6 @@ // For more details see 'mock4net/LICENSE.txt' and 'mock4net/readme.md' in this project root. using System; using System.Collections.Generic; -using JsonConverter.Abstractions; -using Newtonsoft.Json; using Stef.Validation; using WireMock.Matchers; using WireMock.Matchers.Request; @@ -37,19 +35,7 @@ public partial class Request /// public IRequestBuilder WithBodyAsJson(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch) { - var bodyAsJsonString = JsonConvert.SerializeObject(body); - _requestMatchers.Add(new RequestMessageBodyMatcher(matchBehaviour, bodyAsJsonString)); - return this; - } - - /// - public IRequestBuilder WithBodyAsJson(object body, IJsonConverter converter, JsonConverterOptions? options = null, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch) - { - Guard.NotNull(converter); - - var bodyAsJsonString = converter.Serialize(body, options); - _requestMatchers.Add(new RequestMessageBodyMatcher(matchBehaviour, bodyAsJsonString)); - return this; + return WithBody(new IMatcher[] { new JsonMatcher(matchBehaviour, body) }); } /// diff --git a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithBodyTests.cs b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithBodyTests.cs index e12014af..cfac7b6b 100644 --- a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithBodyTests.cs +++ b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithBodyTests.cs @@ -3,8 +3,6 @@ using FluentAssertions; using System.Collections.Generic; using System.Linq; using System.Text; -using JsonConverter.Abstractions; -using Moq; using Newtonsoft.Json; using NFluent; using WireMock.Matchers; @@ -293,7 +291,7 @@ public class RequestBuilderWithBodyTests } [Fact] - public void Request_WithBodyAsJson_Object_JsonPathMatcher_true() + public void Request_WithBody_Object_JsonPathMatcher_true() { // Arrange var spec = Request.Create().UsingAnyMethod().WithBody(new JsonPathMatcher("$..things[?(@.name == 'RequiredThing')]")); @@ -316,7 +314,7 @@ public class RequestBuilderWithBodyTests } [Fact] - public void Request_WithBodyAsJson_Array_JsonPathMatcher_1() + public void Request_WithBody_Array_JsonPathMatcher_1() { // Arrange var spec = Request.Create().UsingAnyMethod().WithBody(new JsonPathMatcher("$..books[?(@.price < 10)]")); @@ -339,7 +337,7 @@ public class RequestBuilderWithBodyTests } [Fact] - public void Request_WithBodyAsJson_Array_JsonPathMatcher_2() + public void Request_WithBody_Array_JsonPathMatcher_2() { // Arrange var spec = Request.Create().UsingAnyMethod().WithBody(new JsonPathMatcher("$..[?(@.Id == 1)]")); @@ -363,7 +361,7 @@ public class RequestBuilderWithBodyTests } [Fact] - public void Request_WithBodyAsObject_ExactObjectMatcher_true() + public void Request_WithBody_ExactObjectMatcher_true() { // Assign object body = DateTime.MinValue; @@ -384,7 +382,7 @@ public class RequestBuilderWithBodyTests } [Fact] - public void Request_WithBodyAsJson_UsingObject() + public void Request_WithBodyAsJson_UsingObject_UsesJsonMatcher() { // Assign object body = new @@ -395,34 +393,8 @@ public class RequestBuilderWithBodyTests var bodyData = new BodyData { - BodyAsString = JsonConvert.SerializeObject(body), - DetectedBodyType = BodyType.String - }; - - // Act - var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, bodyData); - - // Assert - var requestMatchResult = new RequestMatchResult(); - Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Fact] - public void Request_WithBodyAsJson_WithIJsonConverter_UsingObject() - { - // Assign - var jsonConverterMock = new Mock(); - jsonConverterMock.Setup(j => j.Serialize(It.IsAny(), It.IsAny())).Returns("test"); - object body = new - { - Any = "key" - }; - var requestBuilder = Request.Create().UsingAnyMethod().WithBodyAsJson(body, jsonConverterMock.Object); - - var bodyData = new BodyData - { - BodyAsString = "test", - DetectedBodyType = BodyType.String + BodyAsJson = body, + DetectedBodyType = BodyType.Json }; // Act From f76ea1d8ec9b05885a55803f798277d200f81746 Mon Sep 17 00:00:00 2001 From: Stef Heyenrath Date: Sat, 25 May 2024 09:31:39 +0200 Subject: [PATCH 2/2] Update Unit Test Response_ProvideResponse_Transformer_WithBodyAsFile_JsonPath --- .../ResponseWithHandlebarsJsonPathTests.cs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsJsonPathTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsJsonPathTests.cs index 04ee3d3d..4fb70594 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsJsonPathTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsJsonPathTests.cs @@ -1,6 +1,7 @@ using System; using System.Text; using System.Threading.Tasks; +using FluentAssertions; using Moq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -354,7 +355,7 @@ public class ResponseWithHandlebarsJsonPathTests public async Task Response_ProvideResponse_Transformer_WithBodyAsFile_JsonPath() { // Assign - string jsonString = "{ \"MyUniqueNumber\": \"1\" }"; + const string jsonString = "{ \"MyUniqueNumber\": \"1\" }"; var bodyData = new BodyData { BodyAsString = jsonString, @@ -365,15 +366,17 @@ public class ResponseWithHandlebarsJsonPathTests }; var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, bodyData); - string jsonPath = "\"$.MyUniqueNumber\""; var responseBuilder = Response.Create() .WithTransformer() - .WithBodyFromFile(@"c:\\{{JsonPath.SelectToken request.body " + jsonPath + "}}\\test.json"); // why use a \\ here ? + + // We need to use `c:\\\\` here because when just using `c:\\\`, the `\\` it will be interpreted as an escape character to skip / exclude / escape the whole {{}} expression. + // See https://handlebarsjs.com/guide/expressions.html#escaping-handlebars-expressions + .WithBodyFromFile("c:\\\\{{JsonPath.SelectToken request.body \"$.MyUniqueNumber\" }}\\test.json"); // Act var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false); // Assert - Check.That(response.Message.BodyData.BodyAsFile).Equals(@"c:\1\test.json"); + response.Message.BodyData?.BodyAsFile.Should().Be(@"c:\1\test.json"); } } \ No newline at end of file