Compare commits

...

6 Commits

Author SHA1 Message Date
Stef Heyenrath
15ece7ec09 . 2024-05-27 07:19:07 +02:00
Stef Heyenrath
f76ea1d8ec Update Unit Test Response_ProvideResponse_Transformer_WithBodyAsFile_JsonPath 2024-05-25 09:31:39 +02:00
Stef Heyenrath
ea4ea95866 Fix Request.Create().WithBodyAsJson(...) (#1111)
* Fix Request.Create().WithBodyAsJson(...)

* [CodeFactor] Apply fixes

---------

Co-authored-by: codefactor-io <support@codefactor.io>
2024-05-25 09:09:03 +02:00
Stef Heyenrath
336cb7ccae Fix Request.Create().WithBodyAsJson(...) 2024-05-24 23:09:55 +02:00
Stef Heyenrath
13f87a1364 1.5.55 2024-05-22 16:38:30 +02:00
Stef Heyenrath
dd35cea44e When only Port is provided, bind to * (Fixes #1100) (#1107)
* Fix for #1100

* tst
2024-05-22 16:33:35 +02:00
11 changed files with 60 additions and 98 deletions

View File

@@ -1,3 +1,6 @@
# 1.5.55 (22 May 2024)
- [#1107](https://github.com/WireMock-Net/WireMock.Net/pull/1107) - When only Port is provided, bind to * (Fixes #1100) [bug] contributed by [StefH](https://github.com/StefH)
# 1.5.54 (18 May 2024) # 1.5.54 (18 May 2024)
- [#1100](https://github.com/WireMock-Net/WireMock.Net/pull/1100) - Add support to bind to ip-address instead of only localhost [feature] contributed by [StefH](https://github.com/StefH) - [#1100](https://github.com/WireMock-Net/WireMock.Net/pull/1100) - Add support to bind to ip-address instead of only localhost [feature] contributed by [StefH](https://github.com/StefH)
- [#1104](https://github.com/WireMock-Net/WireMock.Net/pull/1104) - Use try..catch to set encoding in WireMockConsoleLogger [feature] contributed by [asherber](https://github.com/asherber) - [#1104](https://github.com/WireMock-Net/WireMock.Net/pull/1104) - Use try..catch to set encoding in WireMockConsoleLogger [feature] contributed by [asherber](https://github.com/asherber)

View File

@@ -4,7 +4,7 @@
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<VersionPrefix>1.5.54</VersionPrefix> <VersionPrefix>1.5.55</VersionPrefix>
<PackageIcon>WireMock.Net-Logo.png</PackageIcon> <PackageIcon>WireMock.Net-Logo.png</PackageIcon>
<PackageProjectUrl>https://github.com/WireMock-Net/WireMock.Net</PackageProjectUrl> <PackageProjectUrl>https://github.com/WireMock-Net/WireMock.Net</PackageProjectUrl>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression> <PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>

View File

@@ -1,6 +1,6 @@
rem https://github.com/StefH/GitHubReleaseNotes rem https://github.com/StefH/GitHubReleaseNotes
SET version=1.5.54 SET version=1.5.55
GitHubReleaseNotes --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc duplicate example --version %version% --token %GH_TOKEN% GitHubReleaseNotes --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc duplicate example --version %version% --token %GH_TOKEN%

View File

@@ -1,5 +1,4 @@
# 1.5.54 (18 May 2024) # 1.5.55 (22 May 2024)
- #1100 Add support to bind to ip-address instead of only localhost [feature] - #1107 When only Port is provided, bind to * (Fixes #1100) [bug]
- #1104 Use try..catch to set encoding in WireMockConsoleLogger [feature]
The full release notes can be found here: https://github.com/WireMock-Net/WireMock.Net/blob/master/CHANGELOG.md The full release notes can be found here: https://github.com/WireMock-Net/WireMock.Net/blob/master/CHANGELOG.md

View File

@@ -4,6 +4,7 @@ using System.Globalization;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using WireMock.Logging; using WireMock.Logging;
@@ -98,30 +99,36 @@ message HelloReply {
{ {
try try
{ {
var serverOnPrivateIPAddress192_168_1 = WireMockServer.Start(new WireMockServerSettings var server = WireMockServer.Start(new WireMockServerSettings
{ {
Urls = new[] { "http://192.168.1.166:8102" } Port = 9091,
StartAdminInterface = true,
Logger = new WireMockConsoleLogger()
}); });
System.Console.WriteLine($"{string.Join(", ", serverOnPrivateIPAddress192_168_1.Urls)}"); System.Console.WriteLine(string.Join(", ", server.Urls));
serverOnPrivateIPAddress192_168_1.Stop();
}
catch (Exception e)
{
System.Console.WriteLine("serverOnPrivateIPAddress192: " + e);
}
try var requestJson = new { PricingContext = new { Market = "USA" } };
{ var responseJson = new { Market = "{{JsonPath.SelectToken request.body \"$.PricingContext.Market\"}}" };
var serverOnPrivateIPAddress172_19 = WireMockServer.Start(new WireMockServerSettings server
{ .Given(Request.Create()
Urls = new[] { "https://172.19.80.1:8103" } //.WithBody(new JsonMatcher(requestJson))
}); .WithBodyAsJson(requestJson)
System.Console.WriteLine($"{string.Join(", ", serverOnPrivateIPAddress172_19.Urls)}"); .WithPath("/pricing")
serverOnPrivateIPAddress172_19.Stop(); .UsingPost()
)
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(responseJson)
.WithTransformer(true)
);
System.Console.WriteLine("Press any key to stop...");
System.Console.ReadKey();
server.Stop();
} }
catch (Exception e) catch (Exception e)
{ {
System.Console.WriteLine("serverOnPrivateIPAddress172_19: " + e); System.Console.WriteLine(e);
} }
} }
@@ -222,7 +229,10 @@ message HelloReply {
server.SetBasicAuthentication("a", "b"); server.SetBasicAuthentication("a", "b");
//server.SetAzureADAuthentication("6c2a4722-f3b9-4970-b8fc-fac41e29stef", "8587fde1-7824-42c7-8592-faf92b04stef"); //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 #if PROTOBUF
var protoBufJsonMatcher = new JsonPartialWildcardMatcher(new { name = "*" }); var protoBufJsonMatcher = new JsonPartialWildcardMatcher(new { name = "*" });
@@ -366,7 +376,6 @@ message HelloReply {
.WithHeader("Content-Type", "text/plain") .WithHeader("Content-Type", "text/plain")
); );
server server
.Given(Request.Create() .Given(Request.Create()
.UsingMethod("GET") .UsingMethod("GET")

View File

@@ -6,7 +6,7 @@ namespace WireMock.Owin;
internal class HostUrlOptions internal class HostUrlOptions
{ {
private const string Localhost = "localhost"; private const string Star = "*";
public ICollection<string>? Urls { get; set; } public ICollection<string>? Urls { get; set; }
@@ -25,16 +25,16 @@ internal class HostUrlOptions
{ {
var port = Port > 0 ? Port.Value : FindFreeTcpPort(); var port = Port > 0 ? Port.Value : FindFreeTcpPort();
var scheme = HostingScheme == HostingScheme.Https ? "https" : "http"; var scheme = HostingScheme == HostingScheme.Https ? "https" : "http";
list.Add(new HostUrlDetails { IsHttps = HostingScheme == HostingScheme.Https, IsHttp2 = UseHttp2 == true, Url = $"{scheme}://{Localhost}:{port}", Scheme = scheme, Host = Localhost, Port = port }); list.Add(new HostUrlDetails { IsHttps = HostingScheme == HostingScheme.Https, IsHttp2 = UseHttp2 == true, Url = $"{scheme}://{Star}:{port}", Scheme = scheme, Host = Star, Port = port });
} }
if (HostingScheme == HostingScheme.HttpAndHttps) if (HostingScheme == HostingScheme.HttpAndHttps)
{ {
var httpPort = Port > 0 ? Port.Value : FindFreeTcpPort(); var httpPort = Port > 0 ? Port.Value : FindFreeTcpPort();
list.Add(new HostUrlDetails { IsHttps = false, IsHttp2 = UseHttp2 == true, Url = $"http://{Localhost}:{httpPort}", Scheme = "http", Host = Localhost, Port = httpPort }); list.Add(new HostUrlDetails { IsHttps = false, IsHttp2 = UseHttp2 == true, Url = $"http://{Star}:{httpPort}", Scheme = "http", Host = Star, Port = httpPort });
var httpsPort = FindFreeTcpPort(); // In this scenario, always get a free port for https. var httpsPort = FindFreeTcpPort(); // In this scenario, always get a free port for https.
list.Add(new HostUrlDetails { IsHttps = true, IsHttp2 = UseHttp2 == true, Url = $"https://{Localhost}:{httpsPort}", Scheme = "https", Host = Localhost, Port = httpsPort }); list.Add(new HostUrlDetails { IsHttps = true, IsHttp2 = UseHttp2 == true, Url = $"https://{Star}:{httpsPort}", Scheme = "https", Host = Star, Port = httpsPort });
} }
} }
else else

View File

@@ -51,23 +51,13 @@ public interface IBodyRequestBuilder : IProtoBufRequestBuilder
IRequestBuilder WithBody(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); IRequestBuilder WithBody(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary> /// <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> /// </summary>
/// <param name="body">The body.</param> /// <param name="body">The body.</param>
/// <param name="matchBehaviour">The match behaviour [default is AcceptOnMatch].</param> /// <param name="matchBehaviour">The match behaviour [default is AcceptOnMatch].</param>
/// <returns>A <see cref="IRequestBuilder"/>.</returns> /// <returns>A <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithBodyAsJson(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); 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> /// <summary>
/// WithBody: func (string) /// WithBody: func (string)
/// </summary> /// </summary>

View File

@@ -2,8 +2,6 @@
// For more details see 'mock4net/LICENSE.txt' and 'mock4net/readme.md' in this project root. // For more details see 'mock4net/LICENSE.txt' and 'mock4net/readme.md' in this project root.
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using JsonConverter.Abstractions;
using Newtonsoft.Json;
using Stef.Validation; using Stef.Validation;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
@@ -37,19 +35,7 @@ public partial class Request
/// <inheritdoc /> /// <inheritdoc />
public IRequestBuilder WithBodyAsJson(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch) public IRequestBuilder WithBodyAsJson(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{ {
var bodyAsJsonString = JsonConvert.SerializeObject(body); return WithBody(new IMatcher[] { new JsonMatcher(matchBehaviour, 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;
} }
/// <inheritdoc /> /// <inheritdoc />

View File

@@ -11,7 +11,7 @@ namespace WireMock.Net.Tests.Owin;
public class HostUrlOptionsTests public class HostUrlOptionsTests
{ {
[Fact] [Fact]
public void GetDetails_WithNoUrlsAndHttpScheme_ShouldReturnCorrectDetails() public void GetDetails_WithHostingSchemeHttpAndPort_ShouldReturnCorrectDetails()
{ {
// Arrange // Arrange
var options = new HostUrlOptions var options = new HostUrlOptions
@@ -28,14 +28,14 @@ public class HostUrlOptionsTests
var detail = details.Single(); var detail = details.Single();
detail.Should().Match<HostUrlDetails>(d => detail.Should().Match<HostUrlDetails>(d =>
d.Scheme == "http" && d.Scheme == "http" &&
d.Host == "localhost" && d.Host == "*" &&
d.Port == 8080 && d.Port == 8080 &&
d.IsHttps == false d.IsHttps == false
); );
} }
[Fact] [Fact]
public void GetDetails_WithNoUrlsAndHttpsScheme_ShouldReturnCorrectDetails() public void GetDetails_WithHostingSchemeHttpsAndPort_ShouldReturnCorrectDetails()
{ {
// Arrange // Arrange
var options = new HostUrlOptions var options = new HostUrlOptions
@@ -52,7 +52,7 @@ public class HostUrlOptionsTests
var detail = details.Single(); var detail = details.Single();
detail.Should().Match<HostUrlDetails>(d => detail.Should().Match<HostUrlDetails>(d =>
d.Scheme == "https" && d.Scheme == "https" &&
d.Host == "localhost" && d.Host == "*" &&
d.Port == 8081 && d.Port == 8081 &&
d.IsHttps == true d.IsHttps == true
); );

View File

@@ -3,8 +3,6 @@ using FluentAssertions;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using JsonConverter.Abstractions;
using Moq;
using Newtonsoft.Json; using Newtonsoft.Json;
using NFluent; using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
@@ -293,7 +291,7 @@ public class RequestBuilderWithBodyTests
} }
[Fact] [Fact]
public void Request_WithBodyAsJson_Object_JsonPathMatcher_true() public void Request_WithBody_Object_JsonPathMatcher_true()
{ {
// Arrange // Arrange
var spec = Request.Create().UsingAnyMethod().WithBody(new JsonPathMatcher("$..things[?(@.name == 'RequiredThing')]")); var spec = Request.Create().UsingAnyMethod().WithBody(new JsonPathMatcher("$..things[?(@.name == 'RequiredThing')]"));
@@ -316,7 +314,7 @@ public class RequestBuilderWithBodyTests
} }
[Fact] [Fact]
public void Request_WithBodyAsJson_Array_JsonPathMatcher_1() public void Request_WithBody_Array_JsonPathMatcher_1()
{ {
// Arrange // Arrange
var spec = Request.Create().UsingAnyMethod().WithBody(new JsonPathMatcher("$..books[?(@.price < 10)]")); var spec = Request.Create().UsingAnyMethod().WithBody(new JsonPathMatcher("$..books[?(@.price < 10)]"));
@@ -339,7 +337,7 @@ public class RequestBuilderWithBodyTests
} }
[Fact] [Fact]
public void Request_WithBodyAsJson_Array_JsonPathMatcher_2() public void Request_WithBody_Array_JsonPathMatcher_2()
{ {
// Arrange // Arrange
var spec = Request.Create().UsingAnyMethod().WithBody(new JsonPathMatcher("$..[?(@.Id == 1)]")); var spec = Request.Create().UsingAnyMethod().WithBody(new JsonPathMatcher("$..[?(@.Id == 1)]"));
@@ -363,7 +361,7 @@ public class RequestBuilderWithBodyTests
} }
[Fact] [Fact]
public void Request_WithBodyAsObject_ExactObjectMatcher_true() public void Request_WithBody_ExactObjectMatcher_true()
{ {
// Assign // Assign
object body = DateTime.MinValue; object body = DateTime.MinValue;
@@ -384,7 +382,7 @@ public class RequestBuilderWithBodyTests
} }
[Fact] [Fact]
public void Request_WithBodyAsJson_UsingObject() public void Request_WithBodyAsJson_UsingObject_UsesJsonMatcher()
{ {
// Assign // Assign
object body = new object body = new
@@ -395,34 +393,8 @@ public class RequestBuilderWithBodyTests
var bodyData = new BodyData var bodyData = new BodyData
{ {
BodyAsString = JsonConvert.SerializeObject(body), BodyAsJson = body,
DetectedBodyType = BodyType.String DetectedBodyType = BodyType.Json
};
// 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
}; };
// Act // Act

View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using FluentAssertions;
using Moq; using Moq;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@@ -354,7 +355,7 @@ public class ResponseWithHandlebarsJsonPathTests
public async Task Response_ProvideResponse_Transformer_WithBodyAsFile_JsonPath() public async Task Response_ProvideResponse_Transformer_WithBodyAsFile_JsonPath()
{ {
// Assign // Assign
string jsonString = "{ \"MyUniqueNumber\": \"1\" }"; const string jsonString = "{ \"MyUniqueNumber\": \"1\" }";
var bodyData = new BodyData var bodyData = new BodyData
{ {
BodyAsString = jsonString, BodyAsString = jsonString,
@@ -365,15 +366,17 @@ public class ResponseWithHandlebarsJsonPathTests
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, bodyData); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, bodyData);
string jsonPath = "\"$.MyUniqueNumber\"";
var responseBuilder = Response.Create() var responseBuilder = Response.Create()
.WithTransformer() .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 // Act
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false); var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert // Assert
Check.That(response.Message.BodyData.BodyAsFile).Equals(@"c:\1\test.json"); response.Message.BodyData?.BodyAsFile.Should().Be(@"c:\1\test.json");
} }
} }