From 336cb7ccaeed3745dc138e7c49e6426c63d89616 Mon Sep 17 00:00:00 2001 From: Stef Heyenrath Date: Fri, 24 May 2024 23:09:55 +0200 Subject: [PATCH 1/2] Fix Request.Create().WithBodyAsJson(...) --- .../MainApp.cs | 63 +++++++------------ .../RequestBuilders/IBodyRequestBuilder.cs | 12 +--- .../RequestBuilders/Request.WithBody.cs | 16 +---- .../RequestBuilderWithBodyTests.cs | 42 +++---------- 4 files changed, 31 insertions(+), 102 deletions(-) diff --git a/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs b/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs index cc211d5dd..bcb002569 100644 --- a/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs +++ b/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs @@ -97,34 +97,30 @@ type Student { 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 @@ private static void RunOnLocal() { 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,10 @@ public static void Run() 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 = "*" }); diff --git a/src/WireMock.Net/RequestBuilders/IBodyRequestBuilder.cs b/src/WireMock.Net/RequestBuilders/IBodyRequestBuilder.cs index 49751bd45..c07022474 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 884e4a1d6..a64efb02d 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 IRequestBuilder WithBody(object body, MatchBehaviour matchBehaviour = Mat /// 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 e12014af0..cfac7b6b2 100644 --- a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithBodyTests.cs +++ b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithBodyTests.cs @@ -3,8 +3,6 @@ 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 void Request_WithBodyJson_PathMatcher_false() } [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 void Request_WithBodyAsJson_Object_JsonPathMatcher_true() } [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 void Request_WithBodyAsJson_Array_JsonPathMatcher_1() } [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 void Request_WithBodyAsJson_Array_JsonPathMatcher_2() } [Fact] - public void Request_WithBodyAsObject_ExactObjectMatcher_true() + public void Request_WithBody_ExactObjectMatcher_true() { // Assign object body = DateTime.MinValue; @@ -384,7 +382,7 @@ public void Request_WithBodyAsObject_ExactObjectMatcher_true() } [Fact] - public void Request_WithBodyAsJson_UsingObject() + public void Request_WithBodyAsJson_UsingObject_UsesJsonMatcher() { // Assign object body = new @@ -395,34 +393,8 @@ public void Request_WithBodyAsJson_UsingObject() 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 395867021086f1420e32c03567ec84811a8e3076 Mon Sep 17 00:00:00 2001 From: codefactor-io Date: Fri, 24 May 2024 21:12:57 +0000 Subject: [PATCH 2/2] [CodeFactor] Apply fixes --- examples/WireMock.Net.Console.Net452.Classic/MainApp.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs b/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs index bcb002569..e9a89eac4 100644 --- a/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs +++ b/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs @@ -229,7 +229,6 @@ public static void Run() server.SetBasicAuthentication("a", "b"); //server.SetAzureADAuthentication("6c2a4722-f3b9-4970-b8fc-fac41e29stef", "8587fde1-7824-42c7-8592-faf92b04stef"); - //var http = new HttpClient(); //var response = await http.GetAsync($"{_wireMockServer.Url}/pricing"); //var value = await response.Content.ReadAsStringAsync(); @@ -376,7 +375,6 @@ public static void Run() .WithHeader("Content-Type", "text/plain") ); - server .Given(Request.Create() .UsingMethod("GET")