Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Request.Create().WithBodyAsJson(...) #1111

Merged
merged 2 commits into from
May 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 21 additions & 42 deletions examples/WireMock.Net.Console.Net452.Classic/MainApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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()
Expand Down Expand Up @@ -251,7 +229,9 @@ 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 = "*" });
Expand Down Expand Up @@ -395,7 +375,6 @@ public static void Run()
.WithHeader("Content-Type", "text/plain")
);


server
.Given(Request.Create()
.UsingMethod("GET")
Expand Down
12 changes: 1 addition & 11 deletions src/WireMock.Net/RequestBuilders/IBodyRequestBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,23 +51,13 @@ public interface IBodyRequestBuilder : IProtoBufRequestBuilder
IRequestBuilder WithBody(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);

/// <summary>
/// WithBody : Body as a string response based on a object (which will be converted to a JSON string using NewtonSoft.Json).
/// WithBodyAsJson: A <see cref="JsonMatcher"/> will be used to match this object.
/// </summary>
/// <param name="body">The body.</param>
/// <param name="matchBehaviour">The match behaviour [default is AcceptOnMatch].</param>
/// <returns>A <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithBodyAsJson(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);

/// <summary>
/// WithBody : Body as a string response based on a object (which will be converted to a JSON string using the <see cref="IJsonConverter"/>).
/// </summary>
/// <param name="body">The body.</param>
/// <param name="converter">The JsonConverter.</param>
/// <param name="options">The <see cref="JsonConverterOptions"/> [optional].</param>
/// <param name="matchBehaviour">The match behaviour [default is AcceptOnMatch].</param>
/// <returns>A <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithBodyAsJson(object body, IJsonConverter converter, JsonConverterOptions? options = null, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);

/// <summary>
/// WithBody: func (string)
/// </summary>
Expand Down
16 changes: 1 addition & 15 deletions src/WireMock.Net/RequestBuilders/Request.WithBody.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -37,19 +35,7 @@ public IRequestBuilder WithBody(object body, MatchBehaviour matchBehaviour = Mat
/// <inheritdoc />
public IRequestBuilder WithBodyAsJson(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
var bodyAsJsonString = JsonConvert.SerializeObject(body);
_requestMatchers.Add(new RequestMessageBodyMatcher(matchBehaviour, bodyAsJsonString));
return this;
}

/// <inheritdoc />
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) });
}

/// <inheritdoc />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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')]"));
Expand All @@ -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)]"));
Expand All @@ -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)]"));
Expand All @@ -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;
Expand All @@ -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
Expand All @@ -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<IJsonConverter>();
jsonConverterMock.Setup(j => j.Serialize(It.IsAny<object>(), It.IsAny<JsonConverterOptions>())).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
Expand Down
Loading