Skip to content

Commit

Permalink
Add support to use 'mapping' object in in reponse templating (#798)
Browse files Browse the repository at this point in the history
* mapping

* .

* .
  • Loading branch information
StefH authored Sep 3, 2022
1 parent 862c04e commit 74480c8
Show file tree
Hide file tree
Showing 37 changed files with 2,194 additions and 2,135 deletions.
1 change: 1 addition & 0 deletions WireMock.Net Solution.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,6 @@
<s:Boolean x:Key="/Default/UserDictionary/Words/=Webhooks/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=wiremock/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=wiremockserver/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Xeger/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=xunit/@EntryIndexedValue">True</s:Boolean>
</wpf:ResourceDictionary>
21 changes: 10 additions & 11 deletions examples/WireMock.Net.Console.NETCoreApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
using System.IO;
using System.IO;
using System.Reflection;
using log4net;
using log4net.Config;
using log4net.Repository;
using WireMock.Net.ConsoleApplication;

namespace WireMock.Net.Console.NETCoreApp
namespace WireMock.Net.Console.NETCoreApp;

static class Program
{
static class Program
{
private static readonly ILoggerRepository LogRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
private static readonly ILoggerRepository LogRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));

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

MainApp.Run();
}
MainApp.Run();
}
}
15 changes: 7 additions & 8 deletions examples/WireMock.Net.Console.Net452.Classic/Program.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
using System.IO;
using System.IO;
using log4net.Config;

namespace WireMock.Net.ConsoleApplication
namespace WireMock.Net.ConsoleApplication;

static class Program
{
static class Program
static void Main(params string[] args)
{
static void Main(params string[] args)
{
XmlConfigurator.Configure(new FileInfo("log4net.config"));
XmlConfigurator.Configure(new FileInfo("log4net.config"));

MainApp.Run();
}
MainApp.Run();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@
<None Include="App.config">
<SubType>Designer</SubType>
</None>
<None Include="libman.json" />
<None Include="log4net.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
Expand Down
47 changes: 23 additions & 24 deletions examples/WireMock.Net.StandAlone.Net452/Program.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
using System;
using System.IO;
using System.Linq;
using log4net.Config;
using WireMock.Server;
using WireMock.Settings;

namespace WireMock.Net.StandAlone.Net452
{
public class Program
{
static void Main(params string[] args)
{
XmlConfigurator.Configure(new FileInfo("log4net.config"));

if (WireMockServerSettingsParser.TryParseArguments(args, out var settings))
{
settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));
using System;
using System.IO;
using System.Linq;
using log4net.Config;
using WireMock.Server;
using WireMock.Settings;

WireMockServer.Start(settings);
namespace WireMock.Net.StandAlone.Net452;

Console.WriteLine("Press any key to stop the server");
Console.ReadKey();
}
}
}
public class Program
{
static void Main(params string[] args)
{
XmlConfigurator.Configure(new FileInfo("log4net.config"));

if (WireMockServerSettingsParser.TryParseArguments(args, out var settings))
{
Console.WriteLine("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));

WireMockServer.Start(settings);

Console.WriteLine("Press any key to stop the server");
Console.ReadKey();
}
}
}
39 changes: 19 additions & 20 deletions examples/WireMock.Net.StandAlone.Net461/Program.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
using System;
using System.Linq;
using WireMock.Server;
using WireMock.Settings;

namespace WireMock.Net.StandAlone.Net461
{
static class Program
{
static void Main(string[] args)
{
if (WireMockServerSettingsParser.TryParseArguments(args, out var settings))
{
settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));
using System;
using System.Linq;
using WireMock.Server;
using WireMock.Settings;

WireMockServer.Start(settings);
namespace WireMock.Net.StandAlone.Net461;

Console.WriteLine("Press any key to stop the server");
Console.ReadKey();
}
}
}
static class Program
{
static void Main(string[] args)
{
if (WireMockServerSettingsParser.TryParseArguments(args, out var settings))
{
Console.WriteLine("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));

WireMockServer.Start(settings);

Console.WriteLine("Press any key to stop the server");
Console.ReadKey();
}
}
}
5 changes: 3 additions & 2 deletions src/WireMock.Net/Http/WebhookSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@ public WebhookSender(WireMockServerSettings settings)
_settings = Guard.NotNull(settings);
}

public Task<HttpResponseMessage> SendAsync(HttpClient client, IWebhookRequest request, IRequestMessage originalRequestMessage, IResponseMessage originalResponseMessage)
public Task<HttpResponseMessage> SendAsync(HttpClient client, IMapping mapping, IWebhookRequest request, IRequestMessage originalRequestMessage, IResponseMessage originalResponseMessage)
{
Guard.NotNull(client);
Guard.NotNull(mapping);
Guard.NotNull(request);
Guard.NotNull(originalRequestMessage);
Guard.NotNull(originalResponseMessage);
Expand All @@ -54,7 +55,7 @@ public Task<HttpResponseMessage> SendAsync(HttpClient client, IWebhookRequest re
throw new NotImplementedException($"TransformerType '{request.TransformerType}' is not supported.");
}

(bodyData, headers) = responseMessageTransformer.Transform(originalRequestMessage, originalResponseMessage, request.BodyData, request.Headers, request.TransformerReplaceNodeOptions);
(bodyData, headers) = responseMessageTransformer.Transform(mapping, originalRequestMessage, originalResponseMessage, request.BodyData, request.Headers, request.TransformerReplaceNodeOptions);
}
else
{
Expand Down
30 changes: 15 additions & 15 deletions src/WireMock.Net/Mapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ public class Mapping : IMapping
/// <inheritdoc />
public Guid Guid { get; }

/// <inheritdoc />
public string? Title { get; }
/// <inheritdoc />
public string? Title { get; }

/// <inheritdoc />
public string? Description { get; }
/// <inheritdoc />
public string? Description { get; }

/// <inheritdoc />
public string? Path { get; set; }
/// <inheritdoc />
public string? Path { get; set; }

/// <inheritdoc />
public int Priority { get; }
Expand Down Expand Up @@ -115,16 +115,16 @@ public Mapping(
TimeSettings = timeSettings;
}

/// <inheritdoc cref="IMapping.ProvideResponseAsync" />
public Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IRequestMessage requestMessage)
{
return Provider.ProvideResponseAsync(requestMessage, Settings);
}
/// <inheritdoc cref="IMapping.ProvideResponseAsync" />
public Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IRequestMessage requestMessage)
{
return Provider.ProvideResponseAsync(this, requestMessage, Settings);
}

/// <inheritdoc cref="IMapping.GetRequestMatchResult" />
public IRequestMatchResult GetRequestMatchResult(IRequestMessage requestMessage, string? nextState)
{
var result = new RequestMatchResult();
/// <inheritdoc cref="IMapping.GetRequestMatchResult" />
public IRequestMatchResult GetRequestMatchResult(IRequestMessage requestMessage, string? nextState)
{
var result = new RequestMatchResult();

RequestMatcher.GetMatchingScore(requestMessage, result);

Expand Down
2 changes: 1 addition & 1 deletion src/WireMock.Net/Owin/IWireMockMiddlewareOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.Util;
using WireMock.Types;
#if !USE_ASPNETCORE
using Owin;
#else
using IAppBuilder = Microsoft.AspNetCore.Builder.IApplicationBuilder;
using Microsoft.Extensions.DependencyInjection;
using WireMock.Types;
#endif

namespace WireMock.Owin;
Expand Down
8 changes: 4 additions & 4 deletions src/WireMock.Net/Owin/WireMockMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ namespace WireMock.Owin
{
internal class WireMockMiddleware : OwinMiddleware
{
private readonly object _lock = new object();
private readonly object _lock = new();
private static readonly Task CompletedTask = Task.FromResult(false);
private readonly IWireMockMiddlewareOptions _options;
private readonly IOwinRequestMapper _requestMapper;
Expand Down Expand Up @@ -108,10 +108,10 @@ private async Task InvokeInternalAsync(IContext ctx)

logRequest = targetMapping.LogMapping;

if (targetMapping.IsAdminInterface && _options.AuthenticationMatcher != null)
if (targetMapping.IsAdminInterface && _options.AuthenticationMatcher != null && request.Headers != null)
{
bool present = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out WireMockList<string> authorization);
if (!present || _options.AuthenticationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfect)
if (!present || _options.AuthenticationMatcher.IsMatch(authorization!.ToString()) < MatchScores.Perfect)
{
_options.Logger.Error("HttpStatusCode set to 401");
response = ResponseMessageBuilder.Create(null, HttpStatusCode.Unauthorized);
Expand Down Expand Up @@ -208,7 +208,7 @@ private async Task SendToWebhooksAsync(IMapping mapping, IRequestMessage request

try
{
await webhookSender.SendAsync(httpClientForWebhook, mapping.Webhooks[index].Request, request, response).ConfigureAwait(false);
await webhookSender.SendAsync(httpClientForWebhook, mapping, mapping.Webhooks[index].Request, request, response).ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down
4 changes: 2 additions & 2 deletions src/WireMock.Net/ResponseBuilders/Response.cs
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ public IResponseBuilder WithRandomDelay(int minimumMilliseconds = 0, int maximum
}

/// <inheritdoc />
public async Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IRequestMessage requestMessage, WireMockServerSettings settings)
public async Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IMapping mapping, IRequestMessage requestMessage, WireMockServerSettings settings)
{
Guard.NotNull(requestMessage);
Guard.NotNull(settings);
Expand Down Expand Up @@ -327,7 +327,7 @@ string RemoveFirstOccurrence(string source, string find)
throw new NotImplementedException($"TransformerType '{TransformerType}' is not supported.");
}

return (responseMessageTransformer.Transform(requestMessage, responseMessage, UseTransformerForBodyAsFile, TransformerReplaceNodeOptions), null);
return (responseMessageTransformer.Transform(mapping, requestMessage, responseMessage, UseTransformerForBodyAsFile, TransformerReplaceNodeOptions), null);
}

if (!UseTransformer && ResponseMessage.BodyData?.BodyAsFileIsCached == true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public DynamicAsyncResponseProvider(Func<IRequestMessage, Task<IResponseMessage>
_responseMessageFunc = responseMessageFunc;
}

public async Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IRequestMessage requestMessage, WireMockServerSettings settings)
public async Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IMapping mapping, IRequestMessage requestMessage, WireMockServerSettings settings)
{
return (await _responseMessageFunc(requestMessage).ConfigureAwait(false), null);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public DynamicResponseProvider(Func<IRequestMessage, IResponseMessage> responseM
_responseMessageFunc = responseMessageFunc;
}

public Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IRequestMessage requestMessage, WireMockServerSettings settings)
public Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IMapping mapping, IRequestMessage requestMessage, WireMockServerSettings settings)
{
(IResponseMessage responseMessage, IMapping? mapping) result = (_responseMessageFunc(requestMessage), null);
return Task.FromResult(result);
Expand Down
3 changes: 2 additions & 1 deletion src/WireMock.Net/ResponseProviders/IResponseProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ public interface IResponseProvider
/// <summary>
/// The provide response.
/// </summary>
/// <param name="mapping">The used mapping.</param>
/// <param name="requestMessage">The request.</param>
/// <param name="settings">The WireMockServerSettings.</param>
/// <returns>The <see cref="ResponseMessage"/> including a new (optional) <see cref="IMapping"/>.</returns>
Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IRequestMessage requestMessage, WireMockServerSettings settings);
Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IMapping mapping, IRequestMessage requestMessage, WireMockServerSettings settings);
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public ProxyAsyncResponseProvider(Func<IRequestMessage, WireMockServerSettings,
_settings = settings;
}

public async Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IRequestMessage requestMessage, WireMockServerSettings settings)
public async Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IMapping mapping, IRequestMessage requestMessage, WireMockServerSettings settings)
{
return (await _responseMessageFunc(requestMessage, _settings).ConfigureAwait(false), null);
}
Expand Down
49 changes: 24 additions & 25 deletions src/WireMock.Net/ScenarioState.cs
Original file line number Diff line number Diff line change
@@ -1,33 +1,32 @@
namespace WireMock
namespace WireMock;

/// <summary>
/// The ScenarioState
/// </summary>
public class ScenarioState
{
/// <summary>
/// The ScenarioState
/// Gets or sets the Name (from the Scenario).
/// </summary>
public class ScenarioState
{
/// <summary>
/// Gets or sets the Name (from the Scenario).
/// </summary>
public string Name { get; set; }
public string? Name { get; set; }

/// <summary>
/// Gets or sets the NextState.
/// </summary>
public string NextState { get; set; }
/// <summary>
/// Gets or sets the NextState.
/// </summary>
public string? NextState { get; set; }

/// <summary>
/// Gets or sets a value indicating whether this <see cref="ScenarioState"/> is started.
/// </summary>
public bool Started { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ScenarioState"/> is started.
/// </summary>
public bool Started { get; set; }

/// <summary>
/// Gets or sets a value indicating whether this <see cref="ScenarioState"/> is finished.
/// </summary>
public bool Finished { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ScenarioState"/> is finished.
/// </summary>
public bool Finished { get; set; }

/// <summary>
/// Gets or sets the state counter.
/// </summary>
public int Counter { get; set; }
}
/// <summary>
/// Gets or sets the state counter.
/// </summary>
public int Counter { get; set; }
}
Loading

0 comments on commit 74480c8

Please sign in to comment.