Skip to content

Commit

Permalink
merge from master + fix conflict
Browse files Browse the repository at this point in the history
  • Loading branch information
StefH committed Mar 24, 2021
2 parents 8196291 + cee7302 commit bf6f946
Show file tree
Hide file tree
Showing 9 changed files with 187 additions and 74 deletions.
135 changes: 72 additions & 63 deletions examples/WireMock.Net.StandAlone.NETCoreApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,70 +1,79 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using log4net;
using log4net.Config;
using log4net.Repository;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;

namespace WireMock.Net.StandAlone.NETCoreApp
{
static class Program
{
private static readonly ILoggerRepository LogRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
// private static readonly ILog Log = LogManager.GetLogger(typeof(Program));

private static int sleepTime = 30000;
private static WireMockServer _server;

static void Main(string[] args)
{
XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));

using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using log4net;
using log4net.Config;
using log4net.Repository;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;
using WireMock.Util;

namespace WireMock.Net.StandAlone.NETCoreApp
{
static class Program
{
private static readonly ILoggerRepository LogRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
// private static readonly ILog Log = LogManager.GetLogger(typeof(Program));

private static int sleepTime = 30000;
private static WireMockServer _server;

static void Main(string[] args)
{
XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));

if (!WireMockServerSettingsParser.TryParseArguments(args, out var settings, new WireMockLog4NetLogger()))
{
return;
}

settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));

_server = WireMockServer.Start(settings);

_server
.Given(Request.Create()
.UsingAnyMethod())
.RespondWith(Response.Create()
.WithTransformer()
.WithBody("{{Random Type=\"Integer\" Min=100 Max=999999}} {{DateTime.Now}} {{DateTime.Now \"yyyy-MMM\"}} {{String.Format (DateTime.Now) \"MMM-dd\"}}"));

Console.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down");

Console.CancelKeyPress += (s, e) =>
{
Stop("CancelKeyPress");
};

System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
{
Stop("AssemblyLoadContext.Default.Unloading");
};

while (true)
{
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server running : {_server.IsStarted}");
Thread.Sleep(sleepTime);
}
}
settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));

_server = WireMockServer.Start(settings);

_server.Given(Request.Create().WithPath("/api/sap")
.UsingPost()
.WithBody((IBodyData xmlData) => {
//xmlData is always null
return true;
}))
.RespondWith(Response.Create().WithStatusCode(System.Net.HttpStatusCode.OK));

private static void Stop(string why)
{
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server stopping because '{why}'");
_server.Stop();
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server stopped");
}
}
_server
.Given(Request.Create()
.UsingAnyMethod())
.RespondWith(Response.Create()
.WithTransformer()
.WithBody("{{Random Type=\"Integer\" Min=100 Max=999999}} {{DateTime.Now}} {{DateTime.Now \"yyyy-MMM\"}} {{String.Format (DateTime.Now) \"MMM-dd\"}}"));

Console.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down");

Console.CancelKeyPress += (s, e) =>
{
Stop("CancelKeyPress");
};

System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
{
Stop("AssemblyLoadContext.Default.Unloading");
};

while (true)
{
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server running : {_server.IsStarted}");
Thread.Sleep(sleepTime);
}
}

private static void Stop(string why)
{
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server stopping because '{why}'");
_server.Stop();
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server stopped");
}
}
}
21 changes: 21 additions & 0 deletions src/WireMock.Net/Matchers/Request/RequestMessageBodyMatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System;
using System.Linq;
using WireMock.Types;
using WireMock.Util;
using WireMock.Validation;

namespace WireMock.Matchers.Request
Expand All @@ -26,6 +27,11 @@ public class RequestMessageBodyMatcher : IRequestMatcher
/// </summary>
public Func<object, bool> JsonFunc { get; }

/// <summary>
/// The body data function for BodyData
/// </summary>
public Func<IBodyData, bool> BodyDataFunc { get; }

/// <summary>
/// The matchers.
/// </summary>
Expand Down Expand Up @@ -88,6 +94,16 @@ public RequestMessageBodyMatcher([NotNull] Func<object, bool> func)
JsonFunc = func;
}

/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
/// <param name="func">The function.</param>
public RequestMessageBodyMatcher([NotNull] Func<IBodyData, bool> func)
{
Check.NotNull(func, nameof(func));
BodyDataFunc = func;
}

/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
Expand Down Expand Up @@ -158,6 +174,11 @@ private double CalculateMatchScore(IRequestMessage requestMessage)
return MatchScores.ToScore(DataFunc(requestMessage?.BodyData?.BodyAsBytes));
}

if (BodyDataFunc != null)
{
return MatchScores.ToScore(BodyDataFunc(requestMessage?.BodyData));
}

return MatchScores.Mismatch;
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/WireMock.Net/Owin/AspNetCoreSelfHost.NETStandard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ private static void SetHttpsAndUrls(KestrelServerOptions kestrelOptions, IWireMo
{
if (urlDetail.IsHttps)
{
kestrelOptions.Listen(System.Net.IPAddress.Any, urlDetail.Port, listenOptions =>
kestrelOptions.ListenAnyIP(urlDetail.Port, listenOptions =>
{
if (wireMockMiddlewareOptions.CustomCertificateDefined)
{
Expand All @@ -45,7 +45,7 @@ private static void SetHttpsAndUrls(KestrelServerOptions kestrelOptions, IWireMo
}
else
{
kestrelOptions.Listen(System.Net.IPAddress.Any, urlDetail.Port);
kestrelOptions.ListenAnyIP(urlDetail.Port);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/WireMock.Net/Owin/AspNetCoreSelfHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ private Task RunHost(CancellationToken token)
foreach (string address in addresses)
{
Urls.Add(address.Replace("0.0.0.0", "localhost"));
Urls.Add(address.Replace("0.0.0.0", "localhost").Replace("[::]", "localhost"));
PortUtils.TryExtract(address, out bool isHttps, out string protocol, out string host, out int port);
Ports.Add(port);
Expand Down
12 changes: 10 additions & 2 deletions src/WireMock.Net/RequestBuilders/IBodyRequestBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
using System;
using WireMock.Matchers;
using WireMock.Matchers.Request;

using WireMock.Util;

namespace WireMock.RequestBuilders
{
/// <summary>
Expand Down Expand Up @@ -63,10 +64,17 @@ public interface IBodyRequestBuilder : IRequestMatcher
IRequestBuilder WithBody([NotNull] Func<byte[], bool> func);

/// <summary>
/// WithBody: func (object)
/// WithBody: func (json object)
/// </summary>
/// <param name="func">The function.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithBody([NotNull] Func<object, bool> func);

/// <summary>
/// WithBody: func (BodyData object)
/// </summary>
/// <param name="func">The function.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithBody([NotNull] Func<IBodyData, bool> func);
}
}
10 changes: 10 additions & 0 deletions src/WireMock.Net/RequestBuilders/Request.WithBody.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.Util;
using WireMock.Validation;

namespace WireMock.RequestBuilders
Expand Down Expand Up @@ -71,5 +72,14 @@ public IRequestBuilder WithBody(Func<object, bool> func)
_requestMatchers.Add(new RequestMessageBodyMatcher(func));
return this;
}

/// <inheritdoc cref="IBodyRequestBuilder.WithBody(Func{IBodyData, bool})"/>
public IRequestBuilder WithBody(Func<IBodyData, bool> func)
{
Check.NotNull(func, nameof(func));

_requestMatchers.Add(new RequestMessageBodyMatcher(func));
return this;
}
}
}
12 changes: 6 additions & 6 deletions src/WireMock.Net/WireMock.Net.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,12 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Handlebars.Net.Helpers" Version="2.1.1" />
<PackageReference Include="Handlebars.Net.Helpers.DynamicLinq" Version="2.1.1" />
<PackageReference Include="Handlebars.Net.Helpers.Json" Version="2.1.1" />
<PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.1.1" />
<PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.1.1" />
<PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.1.1" />
<PackageReference Include="Handlebars.Net.Helpers" Version="2.1.2" />
<PackageReference Include="Handlebars.Net.Helpers.DynamicLinq" Version="2.1.2" />
<PackageReference Include="Handlebars.Net.Helpers.Json" Version="2.1.2" />
<PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.1.2" />
<PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.1.2" />
<PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.1.2" />

<ProjectReference Include="..\WireMock.Net.Abstractions\WireMock.Net.Abstractions.csproj" />
</ItemGroup>
Expand Down
19 changes: 19 additions & 0 deletions test/WireMock.Net.Tests/RequestWithBodyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,25 @@ public void Request_WithBody_FuncJson()
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}

[Fact]
public void Request_WithBody_FuncBodyData()
{
// Assign
var requestBuilder = Request.Create().UsingAnyMethod().WithBody((IBodyData b) => b != null);

// Act
var body = new BodyData
{
BodyAsJson = 123,
DetectedBodyType = BodyType.Json
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);

// Assert
var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}

[Fact]
public void Request_WithBody_FuncByteArray()
{
Expand Down
46 changes: 46 additions & 0 deletions test/WireMock.Net.Tests/WireMockServerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -305,5 +305,51 @@ public async Task WireMockServer_Should_SupportRequestGZipAndDeflate(string cont

server.Stop();
}

#if !NET452
[Fact]
public async Task WireMockServer_Should_respond_to_ipv4_loopback()
{
// Assign
var server = WireMockServer.Start();

server
.Given(Request.Create()
.WithPath("/*"))
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBody("from ipv4 loopback"));

// Act
var response = await new HttpClient().GetStringAsync($"http://127.0.0.1:{server.Ports[0]}/foo");

// Assert
Check.That(response).IsEqualTo("from ipv4 loopback");

server.Stop();
}

[Fact]
public async Task WireMockServer_Should_respond_to_ipv6_loopback()
{
// Assign
var server = WireMockServer.Start();

server
.Given(Request.Create()
.WithPath("/*"))
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBody("from ipv6 loopback"));

// Act
var response = await new HttpClient().GetStringAsync($"http://[::1]:{server.Ports[0]}/foo");

// Assert
Check.That(response).IsEqualTo("from ipv6 loopback");

server.Stop();
}
#endif
}
}

0 comments on commit bf6f946

Please sign in to comment.