Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
StefH committed Mar 18, 2021
1 parent 3617e95 commit 99d9004
Show file tree
Hide file tree
Showing 5 changed files with 133 additions and 66 deletions.
137 changes: 73 additions & 64 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);
}
}

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");
}
}
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));

_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
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;
}
}
}
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

0 comments on commit 99d9004

Please sign in to comment.