mirror of
https://github.com/wiremock/WireMock.Net.git
synced 2026-04-21 00:11:44 +02:00
Add support to use 'mapping' object in in reponse templating (#798)
* mapping * . * .
This commit is contained in:
@@ -30,5 +30,6 @@
|
|||||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Webhooks/@EntryIndexedValue">True</s:Boolean>
|
<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/=wiremock/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=wiremockserver/@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>
|
<s:Boolean x:Key="/Default/UserDictionary/Words/=xunit/@EntryIndexedValue">True</s:Boolean>
|
||||||
</wpf:ResourceDictionary>
|
</wpf:ResourceDictionary>
|
||||||
@@ -1,22 +1,21 @@
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using log4net;
|
using log4net;
|
||||||
using log4net.Config;
|
using log4net.Config;
|
||||||
using log4net.Repository;
|
using log4net.Repository;
|
||||||
using WireMock.Net.ConsoleApplication;
|
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));
|
||||||
|
|
||||||
|
static void Main(params string[] args)
|
||||||
{
|
{
|
||||||
private static readonly ILoggerRepository LogRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
|
XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));
|
||||||
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
|
|
||||||
|
|
||||||
static void Main(params string[] args)
|
MainApp.Run();
|
||||||
{
|
|
||||||
XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));
|
|
||||||
|
|
||||||
MainApp.Run();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,14 @@
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using log4net.Config;
|
using log4net.Config;
|
||||||
|
|
||||||
namespace WireMock.Net.ConsoleApplication
|
namespace WireMock.Net.ConsoleApplication;
|
||||||
{
|
|
||||||
static class Program
|
|
||||||
{
|
|
||||||
static void Main(params string[] args)
|
|
||||||
{
|
|
||||||
XmlConfigurator.Configure(new FileInfo("log4net.config"));
|
|
||||||
|
|
||||||
MainApp.Run();
|
static class Program
|
||||||
}
|
{
|
||||||
|
static void Main(params string[] args)
|
||||||
|
{
|
||||||
|
XmlConfigurator.Configure(new FileInfo("log4net.config"));
|
||||||
|
|
||||||
|
MainApp.Run();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -80,7 +80,6 @@
|
|||||||
<None Include="App.config">
|
<None Include="App.config">
|
||||||
<SubType>Designer</SubType>
|
<SubType>Designer</SubType>
|
||||||
</None>
|
</None>
|
||||||
<None Include="libman.json" />
|
|
||||||
<None Include="log4net.config">
|
<None Include="log4net.config">
|
||||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
</None>
|
</None>
|
||||||
|
|||||||
@@ -1,27 +1,26 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using log4net.Config;
|
using log4net.Config;
|
||||||
using WireMock.Server;
|
using WireMock.Server;
|
||||||
using WireMock.Settings;
|
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}'")));
|
|
||||||
|
|
||||||
WireMockServer.Start(settings);
|
namespace WireMock.Net.StandAlone.Net452;
|
||||||
|
|
||||||
Console.WriteLine("Press any key to stop the server");
|
public class Program
|
||||||
Console.ReadKey();
|
{
|
||||||
}
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,23 +1,22 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using WireMock.Server;
|
using WireMock.Server;
|
||||||
using WireMock.Settings;
|
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}'")));
|
|
||||||
|
|
||||||
WireMockServer.Start(settings);
|
namespace WireMock.Net.StandAlone.Net461;
|
||||||
|
|
||||||
Console.WriteLine("Press any key to stop the server");
|
static class Program
|
||||||
Console.ReadKey();
|
{
|
||||||
}
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -25,9 +25,10 @@ internal class WebhookSender
|
|||||||
_settings = Guard.NotNull(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(client);
|
||||||
|
Guard.NotNull(mapping);
|
||||||
Guard.NotNull(request);
|
Guard.NotNull(request);
|
||||||
Guard.NotNull(originalRequestMessage);
|
Guard.NotNull(originalRequestMessage);
|
||||||
Guard.NotNull(originalResponseMessage);
|
Guard.NotNull(originalResponseMessage);
|
||||||
@@ -54,7 +55,7 @@ internal class WebhookSender
|
|||||||
throw new NotImplementedException($"TransformerType '{request.TransformerType}' is not supported.");
|
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
|
else
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -15,14 +15,14 @@ public class Mapping : IMapping
|
|||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public Guid Guid { get; }
|
public Guid Guid { get; }
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public string? Title { get; }
|
public string? Title { get; }
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public string? Description { get; }
|
public string? Description { get; }
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public string? Path { get; set; }
|
public string? Path { get; set; }
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public int Priority { get; }
|
public int Priority { get; }
|
||||||
@@ -115,16 +115,16 @@ public class Mapping : IMapping
|
|||||||
TimeSettings = timeSettings;
|
TimeSettings = timeSettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc cref="IMapping.ProvideResponseAsync" />
|
/// <inheritdoc cref="IMapping.ProvideResponseAsync" />
|
||||||
public Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IRequestMessage requestMessage)
|
public Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IRequestMessage requestMessage)
|
||||||
{
|
{
|
||||||
return Provider.ProvideResponseAsync(requestMessage, Settings);
|
return Provider.ProvideResponseAsync(this, requestMessage, Settings);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc cref="IMapping.GetRequestMatchResult" />
|
/// <inheritdoc cref="IMapping.GetRequestMatchResult" />
|
||||||
public IRequestMatchResult GetRequestMatchResult(IRequestMessage requestMessage, string? nextState)
|
public IRequestMatchResult GetRequestMatchResult(IRequestMessage requestMessage, string? nextState)
|
||||||
{
|
{
|
||||||
var result = new RequestMatchResult();
|
var result = new RequestMatchResult();
|
||||||
|
|
||||||
RequestMatcher.GetMatchingScore(requestMessage, result);
|
RequestMatcher.GetMatchingScore(requestMessage, result);
|
||||||
|
|
||||||
|
|||||||
@@ -4,12 +4,12 @@ using WireMock.Handlers;
|
|||||||
using WireMock.Logging;
|
using WireMock.Logging;
|
||||||
using WireMock.Matchers;
|
using WireMock.Matchers;
|
||||||
using WireMock.Util;
|
using WireMock.Util;
|
||||||
using WireMock.Types;
|
|
||||||
#if !USE_ASPNETCORE
|
#if !USE_ASPNETCORE
|
||||||
using Owin;
|
using Owin;
|
||||||
#else
|
#else
|
||||||
using IAppBuilder = Microsoft.AspNetCore.Builder.IApplicationBuilder;
|
using IAppBuilder = Microsoft.AspNetCore.Builder.IApplicationBuilder;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using WireMock.Types;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace WireMock.Owin;
|
namespace WireMock.Owin;
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ namespace WireMock.Owin
|
|||||||
{
|
{
|
||||||
internal class WireMockMiddleware : OwinMiddleware
|
internal class WireMockMiddleware : OwinMiddleware
|
||||||
{
|
{
|
||||||
private readonly object _lock = new object();
|
private readonly object _lock = new();
|
||||||
private static readonly Task CompletedTask = Task.FromResult(false);
|
private static readonly Task CompletedTask = Task.FromResult(false);
|
||||||
private readonly IWireMockMiddlewareOptions _options;
|
private readonly IWireMockMiddlewareOptions _options;
|
||||||
private readonly IOwinRequestMapper _requestMapper;
|
private readonly IOwinRequestMapper _requestMapper;
|
||||||
@@ -108,10 +108,10 @@ namespace WireMock.Owin
|
|||||||
|
|
||||||
logRequest = targetMapping.LogMapping;
|
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);
|
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");
|
_options.Logger.Error("HttpStatusCode set to 401");
|
||||||
response = ResponseMessageBuilder.Create(null, HttpStatusCode.Unauthorized);
|
response = ResponseMessageBuilder.Create(null, HttpStatusCode.Unauthorized);
|
||||||
@@ -208,7 +208,7 @@ namespace WireMock.Owin
|
|||||||
|
|
||||||
try
|
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)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -244,7 +244,7 @@ public partial class Response : IResponseBuilder
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <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(requestMessage);
|
||||||
Guard.NotNull(settings);
|
Guard.NotNull(settings);
|
||||||
@@ -327,7 +327,7 @@ public partial class Response : IResponseBuilder
|
|||||||
throw new NotImplementedException($"TransformerType '{TransformerType}' is not supported.");
|
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)
|
if (!UseTransformer && ResponseMessage.BodyData?.BodyAsFileIsCached == true)
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ internal class DynamicAsyncResponseProvider : IResponseProvider
|
|||||||
_responseMessageFunc = responseMessageFunc;
|
_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);
|
return (await _responseMessageFunc(requestMessage).ConfigureAwait(false), null);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ internal class DynamicResponseProvider : IResponseProvider
|
|||||||
_responseMessageFunc = responseMessageFunc;
|
_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);
|
(IResponseMessage responseMessage, IMapping? mapping) result = (_responseMessageFunc(requestMessage), null);
|
||||||
return Task.FromResult(result);
|
return Task.FromResult(result);
|
||||||
|
|||||||
@@ -13,8 +13,9 @@ public interface IResponseProvider
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// The provide response.
|
/// The provide response.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <param name="mapping">The used mapping.</param>
|
||||||
/// <param name="requestMessage">The request.</param>
|
/// <param name="requestMessage">The request.</param>
|
||||||
/// <param name="settings">The WireMockServerSettings.</param>
|
/// <param name="settings">The WireMockServerSettings.</param>
|
||||||
/// <returns>The <see cref="ResponseMessage"/> including a new (optional) <see cref="IMapping"/>.</returns>
|
/// <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);
|
||||||
}
|
}
|
||||||
@@ -15,7 +15,7 @@ internal class ProxyAsyncResponseProvider : IResponseProvider
|
|||||||
_settings = settings;
|
_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);
|
return (await _responseMessageFunc(requestMessage, _settings).ConfigureAwait(false), null);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +1,32 @@
|
|||||||
namespace WireMock
|
namespace WireMock;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The ScenarioState
|
||||||
|
/// </summary>
|
||||||
|
public class ScenarioState
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The ScenarioState
|
/// Gets or sets the Name (from the Scenario).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class ScenarioState
|
public string? Name { get; set; }
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the Name (from the Scenario).
|
|
||||||
/// </summary>
|
|
||||||
public string Name { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the NextState.
|
/// Gets or sets the NextState.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string NextState { get; set; }
|
public string? NextState { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets a value indicating whether this <see cref="ScenarioState"/> is started.
|
/// Gets or sets a value indicating whether this <see cref="ScenarioState"/> is started.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool Started { get; set; }
|
public bool Started { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets a value indicating whether this <see cref="ScenarioState"/> is finished.
|
/// Gets or sets a value indicating whether this <see cref="ScenarioState"/> is finished.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool Finished { get; set; }
|
public bool Finished { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the state counter.
|
/// Gets or sets the state counter.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int Counter { get; set; }
|
public int Counter { get; set; }
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -21,7 +21,7 @@ public static class WireMockServerSettingsParser
|
|||||||
[PublicAPI]
|
[PublicAPI]
|
||||||
public static bool TryParseArguments(string[] args, [NotNullWhen(true)] out WireMockServerSettings? settings, IWireMockLogger? logger = null)
|
public static bool TryParseArguments(string[] args, [NotNullWhen(true)] out WireMockServerSettings? settings, IWireMockLogger? logger = null)
|
||||||
{
|
{
|
||||||
Guard.HasNoNulls(args, nameof(args));
|
Guard.HasNoNulls(args);
|
||||||
|
|
||||||
var parser = new SimpleCommandLineParser();
|
var parser = new SimpleCommandLineParser();
|
||||||
parser.Parse(args);
|
parser.Parse(args);
|
||||||
@@ -68,8 +68,7 @@ public static class WireMockServerSettingsParser
|
|||||||
{
|
{
|
||||||
settings.Logger = logger;
|
settings.Logger = logger;
|
||||||
}
|
}
|
||||||
|
else if (parser.GetStringValue("WireMockLogger") == "WireMockConsoleLogger")
|
||||||
if (parser.GetStringValue("WireMockLogger") == "WireMockConsoleLogger")
|
|
||||||
{
|
{
|
||||||
settings.Logger = new WireMockConsoleLogger();
|
settings.Logger = new WireMockConsoleLogger();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ namespace WireMock.Transformers;
|
|||||||
|
|
||||||
interface ITransformer
|
interface ITransformer
|
||||||
{
|
{
|
||||||
ResponseMessage Transform(IRequestMessage requestMessage, IResponseMessage original, bool useTransformerForBodyAsFile, ReplaceNodeOptions options);
|
ResponseMessage Transform(IMapping mapping, IRequestMessage requestMessage, IResponseMessage original, bool useTransformerForBodyAsFile, ReplaceNodeOptions options);
|
||||||
|
|
||||||
(IBodyData? BodyData, IDictionary<string, WireMockList<string>>? Headers) Transform(IRequestMessage originalRequestMessage, IResponseMessage originalResponseMessage, IBodyData? bodyData, IDictionary<string, WireMockList<string>>? headers, ReplaceNodeOptions options);
|
(IBodyData? BodyData, IDictionary<string, WireMockList<string>>? Headers) Transform(IMapping mapping, IRequestMessage originalRequestMessage, IResponseMessage originalResponseMessage, IBodyData? bodyData, IDictionary<string, WireMockList<string>>? headers, ReplaceNodeOptions options);
|
||||||
}
|
}
|
||||||
@@ -19,6 +19,7 @@ internal class Transformer : ITransformer
|
|||||||
}
|
}
|
||||||
|
|
||||||
public (IBodyData? BodyData, IDictionary<string, WireMockList<string>>? Headers) Transform(
|
public (IBodyData? BodyData, IDictionary<string, WireMockList<string>>? Headers) Transform(
|
||||||
|
IMapping mapping,
|
||||||
IRequestMessage originalRequestMessage,
|
IRequestMessage originalRequestMessage,
|
||||||
IResponseMessage originalResponseMessage,
|
IResponseMessage originalResponseMessage,
|
||||||
IBodyData? bodyData,
|
IBodyData? bodyData,
|
||||||
@@ -29,6 +30,7 @@ internal class Transformer : ITransformer
|
|||||||
|
|
||||||
var model = new
|
var model = new
|
||||||
{
|
{
|
||||||
|
mapping,
|
||||||
request = originalRequestMessage,
|
request = originalRequestMessage,
|
||||||
response = originalResponseMessage
|
response = originalResponseMessage
|
||||||
};
|
};
|
||||||
@@ -42,7 +44,7 @@ internal class Transformer : ITransformer
|
|||||||
return (newBodyData, TransformHeaders(transformerContext, model, headers));
|
return (newBodyData, TransformHeaders(transformerContext, model, headers));
|
||||||
}
|
}
|
||||||
|
|
||||||
public ResponseMessage Transform(IRequestMessage requestMessage, IResponseMessage original, bool useTransformerForBodyAsFile, ReplaceNodeOptions options)
|
public ResponseMessage Transform(IMapping mapping, IRequestMessage requestMessage, IResponseMessage original, bool useTransformerForBodyAsFile, ReplaceNodeOptions options)
|
||||||
{
|
{
|
||||||
var transformerContext = _factory.Create();
|
var transformerContext = _factory.Create();
|
||||||
|
|
||||||
@@ -50,6 +52,7 @@ internal class Transformer : ITransformer
|
|||||||
|
|
||||||
var model = new
|
var model = new
|
||||||
{
|
{
|
||||||
|
mapping,
|
||||||
request = requestMessage
|
request = requestMessage
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -82,22 +85,15 @@ internal class Transformer : ITransformer
|
|||||||
return responseMessage;
|
return responseMessage;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static IBodyData TransformBodyData(ITransformerContext transformerContext, ReplaceNodeOptions options, object model, IBodyData original, bool useTransformerForBodyAsFile)
|
private static IBodyData? TransformBodyData(ITransformerContext transformerContext, ReplaceNodeOptions options, object model, IBodyData original, bool useTransformerForBodyAsFile)
|
||||||
{
|
{
|
||||||
switch (original?.DetectedBodyType)
|
return original.DetectedBodyType switch
|
||||||
{
|
{
|
||||||
case BodyType.Json:
|
BodyType.Json => TransformBodyAsJson(transformerContext, options, model, original),
|
||||||
return TransformBodyAsJson(transformerContext, options, model, original);
|
BodyType.File => TransformBodyAsFile(transformerContext, model, original, useTransformerForBodyAsFile),
|
||||||
|
BodyType.String => TransformBodyAsString(transformerContext, model, original),
|
||||||
case BodyType.File:
|
_ => null
|
||||||
return TransformBodyAsFile(transformerContext, model, original, useTransformerForBodyAsFile);
|
};
|
||||||
|
|
||||||
case BodyType.String:
|
|
||||||
return TransformBodyAsString(transformerContext, model, original);
|
|
||||||
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static IDictionary<string, WireMockList<string>> TransformHeaders(ITransformerContext transformerContext, object model, IDictionary<string, WireMockList<string>>? original)
|
private static IDictionary<string, WireMockList<string>> TransformHeaders(ITransformerContext transformerContext, object model, IDictionary<string, WireMockList<string>>? original)
|
||||||
@@ -166,11 +162,17 @@ internal class Transformer : ITransformer
|
|||||||
{
|
{
|
||||||
const string property = "_";
|
const string property = "_";
|
||||||
JObject dummy = JObject.Parse($"{{ \"{property}\": null }}");
|
JObject dummy = JObject.Parse($"{{ \"{property}\": null }}");
|
||||||
JToken node = dummy[property];
|
if (dummy[property] == null)
|
||||||
|
{
|
||||||
|
// TODO: check if just returning null is fine
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
JToken node = dummy[property]!;
|
||||||
|
|
||||||
ReplaceNodeValue(options, node, transformedString);
|
ReplaceNodeValue(options, node, transformedString);
|
||||||
|
|
||||||
return dummy[property];
|
return dummy[property]!;
|
||||||
}
|
}
|
||||||
|
|
||||||
return stringValue;
|
return stringValue;
|
||||||
|
|||||||
@@ -1,30 +1,31 @@
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using Moq;
|
||||||
using NFluent;
|
using NFluent;
|
||||||
using WireMock.Models;
|
using WireMock.Models;
|
||||||
using WireMock.ResponseBuilders;
|
using WireMock.ResponseBuilders;
|
||||||
using WireMock.Settings;
|
using WireMock.Settings;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseCreateTests
|
||||||
{
|
{
|
||||||
public class ResponseCreateTests
|
private readonly WireMockServerSettings _settings = new ();
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Response_Create_Func()
|
||||||
{
|
{
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
// Assign
|
||||||
|
var responseMessage = new ResponseMessage { StatusCode = 500 };
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost"), "GET", "::1");
|
||||||
|
var mapping = new Mock<IMapping>().Object;
|
||||||
|
|
||||||
[Fact]
|
var responseBuilder = Response.Create(() => responseMessage);
|
||||||
public async Task Response_Create_Func()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var responseMessage = new ResponseMessage { StatusCode = 500 };
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost"), "GET", "::1");
|
|
||||||
|
|
||||||
var responseBuilder = Response.Create(() => responseMessage);
|
// Act
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(mapping, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Act
|
// Assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
Check.That(response.Message).Equals(responseMessage);
|
||||||
|
|
||||||
// Assert
|
|
||||||
Check.That(response.Message).Equals(responseMessage);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,11 +19,14 @@ public class ResponseWithBodyTests
|
|||||||
{
|
{
|
||||||
private const string ClientIp = "::1";
|
private const string ClientIp = "::1";
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
private readonly WireMockServerSettings _settings = new ();
|
||||||
|
|
||||||
public ResponseWithBodyTests()
|
public ResponseWithBodyTests()
|
||||||
{
|
{
|
||||||
|
_mappingMock = new Mock<IMapping>();
|
||||||
|
|
||||||
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||||
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||||
|
|
||||||
@@ -44,7 +47,7 @@ public class ResponseWithBodyTests
|
|||||||
var responseBuilder = Response.Create().WithBody(new byte[] { 48, 49 }, BodyDestinationFormat.String, Encoding.ASCII);
|
var responseBuilder = Response.Create().WithBody(new byte[] { 48, 49 }, BodyDestinationFormat.String, Encoding.ASCII);
|
||||||
|
|
||||||
// act
|
// act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// then
|
// then
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Equals("01");
|
Check.That(response.Message.BodyData.BodyAsString).Equals("01");
|
||||||
@@ -66,7 +69,7 @@ public class ResponseWithBodyTests
|
|||||||
var responseBuilder = Response.Create().WithBody(new byte[] { 48, 49 }, BodyDestinationFormat.SameAsSource, Encoding.ASCII);
|
var responseBuilder = Response.Create().WithBody(new byte[] { 48, 49 }, BodyDestinationFormat.SameAsSource, Encoding.ASCII);
|
||||||
|
|
||||||
// act
|
// act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// then
|
// then
|
||||||
Check.That(response.Message.BodyData.BodyAsBytes).ContainsExactly(new byte[] { 48, 49 });
|
Check.That(response.Message.BodyData.BodyAsBytes).ContainsExactly(new byte[] { 48, 49 });
|
||||||
@@ -88,7 +91,7 @@ public class ResponseWithBodyTests
|
|||||||
var responseBuilder = Response.Create().WithBody("test", null, Encoding.ASCII);
|
var responseBuilder = Response.Create().WithBody("test", null, Encoding.ASCII);
|
||||||
|
|
||||||
// act
|
// act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// then
|
// then
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
|
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
|
||||||
@@ -110,7 +113,7 @@ public class ResponseWithBodyTests
|
|||||||
var responseBuilder = Response.Create().WithBodyAsJson(x, Encoding.ASCII);
|
var responseBuilder = Response.Create().WithBodyAsJson(x, Encoding.ASCII);
|
||||||
|
|
||||||
// act
|
// act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// then
|
// then
|
||||||
Check.That(response.Message.BodyData.BodyAsJson).Equals(x);
|
Check.That(response.Message.BodyData.BodyAsJson).Equals(x);
|
||||||
@@ -132,7 +135,7 @@ public class ResponseWithBodyTests
|
|||||||
var responseBuilder = Response.Create().WithBodyAsJson(x, true);
|
var responseBuilder = Response.Create().WithBodyAsJson(x, true);
|
||||||
|
|
||||||
// act
|
// act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// then
|
// then
|
||||||
Check.That(response.Message.BodyData.BodyAsJson).Equals(x);
|
Check.That(response.Message.BodyData.BodyAsJson).Equals(x);
|
||||||
@@ -148,7 +151,7 @@ public class ResponseWithBodyTests
|
|||||||
var responseBuilder = Response.Create().WithBody("r", BodyDestinationFormat.SameAsSource, Encoding.ASCII);
|
var responseBuilder = Response.Create().WithBody("r", BodyDestinationFormat.SameAsSource, Encoding.ASCII);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.BodyData.BodyAsBytes).IsNull();
|
Check.That(response.Message.BodyData.BodyAsBytes).IsNull();
|
||||||
@@ -166,7 +169,7 @@ public class ResponseWithBodyTests
|
|||||||
var responseBuilder = Response.Create().WithBody("r", BodyDestinationFormat.Bytes, Encoding.ASCII);
|
var responseBuilder = Response.Create().WithBody("r", BodyDestinationFormat.Bytes, Encoding.ASCII);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.BodyData.BodyAsString).IsNull();
|
Check.That(response.Message.BodyData.BodyAsString).IsNull();
|
||||||
@@ -184,7 +187,7 @@ public class ResponseWithBodyTests
|
|||||||
var responseBuilder = Response.Create().WithBody("{ \"value\": 42 }", BodyDestinationFormat.Json, Encoding.ASCII);
|
var responseBuilder = Response.Create().WithBody("{ \"value\": 42 }", BodyDestinationFormat.Json, Encoding.ASCII);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.BodyData.BodyAsString).IsNull();
|
Check.That(response.Message.BodyData.BodyAsString).IsNull();
|
||||||
@@ -206,7 +209,7 @@ public class ResponseWithBodyTests
|
|||||||
.WithBody(req => $"path: {req.Path}");
|
.WithBody(req => $"path: {req.Path}");
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.BodyData.BodyAsString).IsEqualTo("path: /test");
|
Check.That(response.Message.BodyData.BodyAsString).IsEqualTo("path: /test");
|
||||||
@@ -235,7 +238,7 @@ public class ResponseWithBodyTests
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.BodyData.BodyAsString).IsEqualTo("path: /test");
|
Check.That(response.Message.BodyData.BodyAsString).IsEqualTo("path: /test");
|
||||||
@@ -263,8 +266,8 @@ public class ResponseWithBodyTests
|
|||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response1 = await responseBuilder.ProvideResponseAsync(request1, _settings).ConfigureAwait(false);
|
var response1 = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request1, _settings).ConfigureAwait(false);
|
||||||
var response2 = await responseBuilder.ProvideResponseAsync(request2, _settings).ConfigureAwait(false);
|
var response2 = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request2, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(((JToken)response1.Message.BodyData.BodyAsJson).SelectToken("id")?.Value<int>()).IsEqualTo(request1Id);
|
Check.That(((JToken)response1.Message.BodyData.BodyAsJson).SelectToken("id")?.Value<int>()).IsEqualTo(request1Id);
|
||||||
@@ -288,7 +291,7 @@ public class ResponseWithBodyTests
|
|||||||
|
|
||||||
var responseBuilder = Response.Create().WithStatusCode(200).WithBody(fileContents);
|
var responseBuilder = Response.Create().WithStatusCode(200).WithBody(fileContents);
|
||||||
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request1, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request1, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
Check.That(response.Message.StatusCode).IsEqualTo(200);
|
Check.That(response.Message.StatusCode).IsEqualTo(200);
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Contains(fileContents);
|
Check.That(response.Message.BodyData.BodyAsString).Contains(fileContents);
|
||||||
@@ -304,7 +307,7 @@ public class ResponseWithBodyTests
|
|||||||
|
|
||||||
var responseBuilder = Response.Create().WithStatusCode(200).WithBody(fileContents);
|
var responseBuilder = Response.Create().WithStatusCode(200).WithBody(fileContents);
|
||||||
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request1, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request1, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
Check.That(response.Message.StatusCode).IsEqualTo(200);
|
Check.That(response.Message.StatusCode).IsEqualTo(200);
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Contains(fileContents);
|
Check.That(response.Message.BodyData.BodyAsString).Contains(fileContents);
|
||||||
@@ -320,7 +323,7 @@ public class ResponseWithBodyTests
|
|||||||
|
|
||||||
var responseBuilder = Response.Create().WithStatusCode(200).WithBody("File deleted.");
|
var responseBuilder = Response.Create().WithStatusCode(200).WithBody("File deleted.");
|
||||||
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request1, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request1, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
Check.That(response.Message.StatusCode).IsEqualTo(200);
|
Check.That(response.Message.StatusCode).IsEqualTo(200);
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Contains("File deleted.");
|
Check.That(response.Message.BodyData.BodyAsString).Contains("File deleted.");
|
||||||
@@ -341,7 +344,7 @@ public class ResponseWithBodyTests
|
|||||||
var responseBuilder = Response.Create().WithBody(new { foo = "bar", n = 42 }, new JsonConverter.System.Text.Json.SystemTextJsonConverter());
|
var responseBuilder = Response.Create().WithBody(new { foo = "bar", n = 42 }, new JsonConverter.System.Text.Json.SystemTextJsonConverter());
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
response.Message.BodyData!.BodyAsString.Should().Be(@"{""foo"":""bar"",""n"":42}");
|
response.Message.BodyData!.BodyAsString.Should().Be(@"{""foo"":""bar"",""n"":42}");
|
||||||
|
|||||||
@@ -11,59 +11,37 @@ using WireMock.Types;
|
|||||||
using WireMock.Util;
|
using WireMock.Util;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithCallbackTests
|
||||||
{
|
{
|
||||||
public class ResponseWithCallbackTests
|
private const string ClientIp = "::1";
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
|
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
||||||
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
|
||||||
|
public ResponseWithCallbackTests()
|
||||||
{
|
{
|
||||||
private const string ClientIp = "::1";
|
_mappingMock = new Mock<IMapping>();
|
||||||
|
|
||||||
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||||
|
|
||||||
public ResponseWithCallbackTests()
|
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
|
||||||
{
|
}
|
||||||
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
|
||||||
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
|
||||||
|
|
||||||
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
|
[Fact]
|
||||||
}
|
public async Task Response_WithCallbackAsync()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
|
||||||
|
var responseBuilder = Response.Create()
|
||||||
|
.WithCallback(async request =>
|
||||||
|
{
|
||||||
|
await Task.Delay(1);
|
||||||
|
|
||||||
[Fact]
|
return new ResponseMessage
|
||||||
public async Task Response_WithCallbackAsync()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
|
|
||||||
var responseBuilder = Response.Create()
|
|
||||||
.WithCallback(async request =>
|
|
||||||
{
|
|
||||||
await Task.Delay(1);
|
|
||||||
|
|
||||||
return new ResponseMessage
|
|
||||||
{
|
|
||||||
BodyData = new BodyData
|
|
||||||
{
|
|
||||||
DetectedBodyType = BodyType.String,
|
|
||||||
BodyAsString = request.Path + "Bar"
|
|
||||||
},
|
|
||||||
StatusCode = 302
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(requestMessage, _settings).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
|
|
||||||
response.Message.StatusCode.Should().Be(302);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Response_WithCallback()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
|
|
||||||
var responseBuilder = Response.Create()
|
|
||||||
.WithCallback(request => new ResponseMessage
|
|
||||||
{
|
{
|
||||||
BodyData = new BodyData
|
BodyData = new BodyData
|
||||||
{
|
{
|
||||||
@@ -71,101 +49,125 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
|||||||
BodyAsString = request.Path + "Bar"
|
BodyAsString = request.Path + "Bar"
|
||||||
},
|
},
|
||||||
StatusCode = 302
|
StatusCode = 302
|
||||||
});
|
};
|
||||||
|
});
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(requestMessage, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, requestMessage, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
|
response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
|
||||||
response.Message.StatusCode.Should().Be(302);
|
response.Message.StatusCode.Should().Be(302);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_WithCallback_ShouldUseStatusCodeAndHeaderInTheCallback()
|
public async Task Response_WithCallback()
|
||||||
{
|
{
|
||||||
// Assign
|
// Assign
|
||||||
var header = "X-UserId";
|
var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
|
||||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
|
var responseBuilder = Response.Create()
|
||||||
var responseBuilder = Response.Create()
|
.WithCallback(request => new ResponseMessage
|
||||||
.WithCallback(request => new ResponseMessage
|
{
|
||||||
|
BodyData = new BodyData
|
||||||
{
|
{
|
||||||
BodyData = new BodyData
|
DetectedBodyType = BodyType.String,
|
||||||
{
|
BodyAsString = request.Path + "Bar"
|
||||||
DetectedBodyType = BodyType.String,
|
},
|
||||||
BodyAsString = request.Path + "Bar"
|
StatusCode = 302
|
||||||
},
|
});
|
||||||
StatusCode = HttpStatusCode.Accepted,
|
|
||||||
Headers = new Dictionary<string, WireMockList<string>>
|
|
||||||
{
|
|
||||||
{ header, new WireMockList<string>("Stef") }
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(requestMessage, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, requestMessage, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
|
response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
|
||||||
response.Message.StatusCode.Should().Be(HttpStatusCode.Accepted);
|
response.Message.StatusCode.Should().Be(302);
|
||||||
response.Message.Headers[header].Should().ContainSingle("Stef");
|
}
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_WithCallback_And_Additional_WithStatusCode_And_WithHeader_ShouldUseAdditional()
|
public async Task Response_WithCallback_ShouldUseStatusCodeAndHeaderInTheCallback()
|
||||||
{
|
{
|
||||||
// Assign
|
// Assign
|
||||||
var header = "X-UserId";
|
var header = "X-UserId";
|
||||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
|
var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithCallback(request => new ResponseMessage
|
.WithCallback(request => new ResponseMessage
|
||||||
|
{
|
||||||
|
BodyData = new BodyData
|
||||||
{
|
{
|
||||||
BodyData = new BodyData
|
DetectedBodyType = BodyType.String,
|
||||||
{
|
BodyAsString = request.Path + "Bar"
|
||||||
DetectedBodyType = BodyType.String,
|
},
|
||||||
BodyAsString = request.Path + "Bar"
|
StatusCode = HttpStatusCode.Accepted,
|
||||||
},
|
Headers = new Dictionary<string, WireMockList<string>>
|
||||||
StatusCode = HttpStatusCode.NotFound,
|
|
||||||
Headers = new Dictionary<string, WireMockList<string>>
|
|
||||||
{
|
|
||||||
{ header, new WireMockList<string>("NA") }
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.WithStatusCode(HttpStatusCode.Accepted)
|
|
||||||
.WithHeader(header, "Stef");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(requestMessage, _settings).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
|
|
||||||
response.Message.StatusCode.Should().Be((int) HttpStatusCode.Accepted);
|
|
||||||
response.Message.Headers[header].Should().ContainSingle("Stef");
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Response_WithCallback_And_UseTransformer_Is_True()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
|
|
||||||
var responseBuilder = Response.Create()
|
|
||||||
.WithCallback(request => new ResponseMessage
|
|
||||||
{
|
{
|
||||||
BodyData = new BodyData
|
{ header, new WireMockList<string>("Stef") }
|
||||||
{
|
}
|
||||||
DetectedBodyType = BodyType.String,
|
});
|
||||||
BodyAsString = "{{request.Path}}Bar"
|
|
||||||
},
|
|
||||||
StatusCode = 302
|
|
||||||
})
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(requestMessage, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, requestMessage, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
|
response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
|
||||||
response.Message.StatusCode.Should().Be(302);
|
response.Message.StatusCode.Should().Be(HttpStatusCode.Accepted);
|
||||||
}
|
response.Message.Headers[header].Should().ContainSingle("Stef");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Response_WithCallback_And_Additional_WithStatusCode_And_WithHeader_ShouldUseAdditional()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var header = "X-UserId";
|
||||||
|
var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
|
||||||
|
var responseBuilder = Response.Create()
|
||||||
|
.WithCallback(request => new ResponseMessage
|
||||||
|
{
|
||||||
|
BodyData = new BodyData
|
||||||
|
{
|
||||||
|
DetectedBodyType = BodyType.String,
|
||||||
|
BodyAsString = request.Path + "Bar"
|
||||||
|
},
|
||||||
|
StatusCode = HttpStatusCode.NotFound,
|
||||||
|
Headers = new Dictionary<string, WireMockList<string>>
|
||||||
|
{
|
||||||
|
{ header, new WireMockList<string>("NA") }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.WithStatusCode(HttpStatusCode.Accepted)
|
||||||
|
.WithHeader(header, "Stef");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, requestMessage, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
|
||||||
|
response.Message.StatusCode.Should().Be((int)HttpStatusCode.Accepted);
|
||||||
|
response.Message.Headers[header].Should().ContainSingle("Stef");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Response_WithCallback_And_UseTransformer_Is_True()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
|
||||||
|
var responseBuilder = Response.Create()
|
||||||
|
.WithCallback(request => new ResponseMessage
|
||||||
|
{
|
||||||
|
BodyData = new BodyData
|
||||||
|
{
|
||||||
|
DetectedBodyType = BodyType.String,
|
||||||
|
BodyAsString = "{{request.Path}}Bar"
|
||||||
|
},
|
||||||
|
StatusCode = 302
|
||||||
|
})
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, requestMessage, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
|
||||||
|
response.Message.StatusCode.Should().Be(302);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,48 +1,55 @@
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
|
using Moq;
|
||||||
using WireMock.Models;
|
using WireMock.Models;
|
||||||
using WireMock.ResponseBuilders;
|
using WireMock.ResponseBuilders;
|
||||||
using WireMock.Settings;
|
using WireMock.Settings;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithFaultTests
|
||||||
{
|
{
|
||||||
public class ResponseWithFaultTests
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
private const string ClientIp = "::1";
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
|
|
||||||
|
public ResponseWithFaultTests()
|
||||||
{
|
{
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
_mappingMock = new Mock<IMapping>();
|
||||||
private const string ClientIp = "::1";
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData(FaultType.EMPTY_RESPONSE)]
|
|
||||||
[InlineData(FaultType.MALFORMED_RESPONSE_CHUNK)]
|
|
||||||
public async Task Response_ProvideResponse_WithFault(FaultType faultType)
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost/fault"), "GET", ClientIp);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var responseBuilder = Response.Create().WithFault(faultType);
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
response.Message.FaultType.Should().Be(faultType);
|
|
||||||
response.Message.FaultPercentage.Should().BeNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData(FaultType.EMPTY_RESPONSE, 0.5)]
|
|
||||||
public async Task Response_ProvideResponse_WithFault_IncludingPercentage(FaultType faultType, double percentage)
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost/fault"), "GET", ClientIp);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var responseBuilder = Response.Create().WithFault(faultType, percentage);
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
response.Message.FaultType.Should().Be(faultType);
|
|
||||||
response.Message.FaultPercentage.Should().Be(percentage);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(FaultType.EMPTY_RESPONSE)]
|
||||||
|
[InlineData(FaultType.MALFORMED_RESPONSE_CHUNK)]
|
||||||
|
public async Task Response_ProvideResponse_WithFault(FaultType faultType)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost/fault"), "GET", ClientIp);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var responseBuilder = Response.Create().WithFault(faultType);
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.Message.FaultType.Should().Be(faultType);
|
||||||
|
response.Message.FaultPercentage.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(FaultType.EMPTY_RESPONSE, 0.5)]
|
||||||
|
public async Task Response_ProvideResponse_WithFault_IncludingPercentage(FaultType faultType, double percentage)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost/fault"), "GET", ClientIp);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var responseBuilder = Response.Create().WithFault(faultType, percentage);
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.Message.FaultType.Should().Be(faultType);
|
||||||
|
response.Message.FaultPercentage.Should().Be(percentage);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,91 +9,94 @@ using WireMock.ResponseBuilders;
|
|||||||
using WireMock.Settings;
|
using WireMock.Settings;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithHandlebarsFileTests
|
||||||
{
|
{
|
||||||
public class ResponseWithHandlebarsFileTests
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
private const string ClientIp = "::1";
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
|
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
||||||
|
|
||||||
|
public ResponseWithHandlebarsFileTests()
|
||||||
{
|
{
|
||||||
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
_mappingMock = new Mock<IMapping>();
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
|
||||||
private const string ClientIp = "::1";
|
|
||||||
|
|
||||||
public ResponseWithHandlebarsFileTests()
|
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||||
{
|
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||||
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
|
||||||
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
|
||||||
|
|
||||||
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
|
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_File()
|
public async Task Response_ProvideResponseAsync_Handlebars_File()
|
||||||
{
|
{
|
||||||
// Assign
|
// Assign
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithBodyAsJson(new
|
.WithBodyAsJson(new
|
||||||
{
|
{
|
||||||
Data = "{{File \"x.json\"}}"
|
Data = "{{File \"x.json\"}}"
|
||||||
})
|
})
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
Check.That(j["Data"].Value<string>()).Equals("abc");
|
Check.That(j["Data"].Value<string>()).Equals("abc");
|
||||||
|
|
||||||
// Verify
|
// Verify
|
||||||
_filesystemHandlerMock.Verify(fs => fs.ReadResponseBodyAsString("x.json"), Times.Once);
|
_filesystemHandlerMock.Verify(fs => fs.ReadResponseBodyAsString("x.json"), Times.Once);
|
||||||
_filesystemHandlerMock.VerifyNoOtherCalls();
|
_filesystemHandlerMock.VerifyNoOtherCalls();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_File_Replace()
|
public async Task Response_ProvideResponseAsync_Handlebars_File_Replace()
|
||||||
{
|
{
|
||||||
// Assign
|
// Assign
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234?id=x"), "GET", ClientIp);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234?id=x"), "GET", ClientIp);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithBodyAsJson(new
|
.WithBodyAsJson(new
|
||||||
{
|
{
|
||||||
Data = "{{File \"{{request.query.id}}.json\"}}"
|
Data = "{{File \"{{request.query.id}}.json\"}}"
|
||||||
})
|
})
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
Check.That(j["Data"].Value<string>()).Equals("abc");
|
Check.That(j["Data"].Value<string>()).Equals("abc");
|
||||||
|
|
||||||
// Verify
|
// Verify
|
||||||
_filesystemHandlerMock.Verify(fs => fs.ReadResponseBodyAsString("x.json"), Times.Once);
|
_filesystemHandlerMock.Verify(fs => fs.ReadResponseBodyAsString("x.json"), Times.Once);
|
||||||
_filesystemHandlerMock.VerifyNoOtherCalls();
|
_filesystemHandlerMock.VerifyNoOtherCalls();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Response_ProvideResponseAsync_Handlebars_File_WithMissingArgument_Throws_HandlebarsException()
|
public void Response_ProvideResponseAsync_Handlebars_File_WithMissingArgument_Throws_HandlebarsException()
|
||||||
{
|
{
|
||||||
// Assign
|
// Assign
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithBodyAsJson(new
|
.WithBodyAsJson(new
|
||||||
{
|
{
|
||||||
Data = "{{File}}"
|
Data = "{{File}}"
|
||||||
})
|
})
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(request, _settings)).Throws<HandlebarsException>();
|
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<HandlebarsException>();
|
||||||
|
|
||||||
// Verify
|
// Verify
|
||||||
_filesystemHandlerMock.Verify(fs => fs.ReadResponseBodyAsString(It.IsAny<string>()), Times.Never);
|
_filesystemHandlerMock.Verify(fs => fs.ReadResponseBodyAsString(It.IsAny<string>()), Times.Never);
|
||||||
_filesystemHandlerMock.VerifyNoOtherCalls();
|
_filesystemHandlerMock.VerifyNoOtherCalls();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,40 +9,38 @@ using WireMock.Types;
|
|||||||
using WireMock.Util;
|
using WireMock.Util;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithHandlebarsHelpersTests
|
||||||
{
|
{
|
||||||
public class ResponseWithHandlebarsHelpersTests
|
private const string ClientIp = "::1";
|
||||||
|
|
||||||
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
|
||||||
|
public ResponseWithHandlebarsHelpersTests()
|
||||||
{
|
{
|
||||||
private const string ClientIp = "::1";
|
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||||
|
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||||
|
|
||||||
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
_settings.FileSystemHandler = filesystemHandlerMock.Object;
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
}
|
||||||
|
|
||||||
public ResponseWithHandlebarsHelpersTests()
|
[Fact]
|
||||||
{
|
public async Task Response_ProvideResponseAsync_HandlebarsHelpers_String_Uppercase()
|
||||||
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
{
|
||||||
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
// Assign
|
||||||
|
var body = new BodyData { BodyAsString = "abc", DetectedBodyType = BodyType.String };
|
||||||
|
|
||||||
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
var responseBuilder = Response.Create()
|
||||||
public async Task Response_ProvideResponseAsync_HandlebarsHelpers_String_Uppercase()
|
.WithBody("{{String.Uppercase request.body}}")
|
||||||
{
|
.WithTransformer();
|
||||||
// Assign
|
|
||||||
var body = new BodyData { BodyAsString = "abc", DetectedBodyType = BodyType.String };
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
// Act
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(new Mock<IMapping>().Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// assert
|
||||||
.WithBody("{{String.Uppercase request.body}}")
|
Check.That(response.Message.BodyData.BodyAsString).Equals("ABC");
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// assert
|
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Equals("ABC");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,42 +9,43 @@ using WireMock.ResponseBuilders;
|
|||||||
using WireMock.Settings;
|
using WireMock.Settings;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithHandlebarsHumanizerTests
|
||||||
{
|
{
|
||||||
public class ResponseWithHandlebarsHumanizerTests
|
private const string ClientIp = "::1";
|
||||||
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
|
|
||||||
|
public ResponseWithHandlebarsHumanizerTests()
|
||||||
{
|
{
|
||||||
private const string ClientIp = "::1";
|
_mappingMock = new Mock<IMapping>();
|
||||||
|
|
||||||
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||||
|
|
||||||
public ResponseWithHandlebarsHumanizerTests()
|
_settings.FileSystemHandler = filesystemHandlerMock.Object;
|
||||||
{
|
}
|
||||||
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
|
||||||
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
|
||||||
|
|
||||||
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
|
[Fact]
|
||||||
}
|
public async Task Response_ProvideResponseAsync_Handlebars_Humanizer()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||||
|
|
||||||
[Fact]
|
var responseBuilder = Response.Create()
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_Humanizer()
|
.WithBodyAsJson(new
|
||||||
{
|
{
|
||||||
// Assign
|
Text = string.Format("{{{{[Humanizer.Humanize] \"{0}\" }}}}", "PascalCaseInputStringIsTurnedIntoSentence")
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
})
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBodyAsJson(new
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
{
|
|
||||||
Text = string.Format("{{{{[Humanizer.Humanize] \"{0}\" }}}}", "PascalCaseInputStringIsTurnedIntoSentence")
|
|
||||||
})
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// Assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
|
Check.That(j["Text"].Value<string>()).IsEqualTo("Pascal case input string is turned into sentence");
|
||||||
// Assert
|
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
|
||||||
Check.That(j["Text"].Value<string>()).IsEqualTo("Pascal case input string is turned into sentence");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -13,30 +13,32 @@ using WireMock.Types;
|
|||||||
using WireMock.Util;
|
using WireMock.Util;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithHandlebarsJsonPathTests
|
||||||
{
|
{
|
||||||
public class ResponseWithHandlebarsJsonPathTests
|
private const string ClientIp = "::1";
|
||||||
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
|
|
||||||
|
public ResponseWithHandlebarsJsonPathTests()
|
||||||
{
|
{
|
||||||
private const string ClientIp = "::1";
|
_mappingMock = new Mock<IMapping>();
|
||||||
|
|
||||||
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||||
|
|
||||||
public ResponseWithHandlebarsJsonPathTests()
|
_settings.FileSystemHandler = filesystemHandlerMock.Object;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Object_ResponseBodyAsJson()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
BodyAsString = @"{
|
||||||
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
|
||||||
|
|
||||||
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Object_ResponseBodyAsJson()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData
|
|
||||||
{
|
|
||||||
BodyAsString = @"{
|
|
||||||
""Stores"": [
|
""Stores"": [
|
||||||
""Lambton Quay"",
|
""Lambton Quay"",
|
||||||
""Willis Street""
|
""Willis Street""
|
||||||
@@ -66,57 +68,57 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
}",
|
}",
|
||||||
DetectedBodyType = BodyType.String
|
DetectedBodyType = BodyType.String
|
||||||
};
|
};
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/json")
|
.WithHeader("Content-Type", "application/json")
|
||||||
.WithBodyAsJson(new { x = "{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}" })
|
.WithBodyAsJson(new { x = "{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}" })
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
Check.That(j["x"]).IsNotNull();
|
Check.That(j["x"]).IsNotNull();
|
||||||
Check.That(j["x"]["Name"].ToString()).Equals("Acme Co");
|
Check.That(j["x"]["Name"].ToString()).Equals("Acme Co");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Number_ResponseBodyAsJson()
|
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Number_ResponseBodyAsJson()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsString = "{ \"Price\": 99 }",
|
||||||
var body = new BodyData
|
DetectedBodyType = BodyType.String
|
||||||
{
|
};
|
||||||
BodyAsString = "{ \"Price\": 99 }",
|
|
||||||
DetectedBodyType = BodyType.String
|
|
||||||
};
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/json")
|
.WithHeader("Content-Type", "application/json")
|
||||||
.WithBodyAsJson(new { x = "{{JsonPath.SelectToken request.body \"..Price\"}}" })
|
.WithBodyAsJson(new { x = "{{JsonPath.SelectToken request.body \"..Price\"}}" })
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
Check.That(j["x"].Value<long>()).Equals(99);
|
Check.That(j["x"].Value<long>()).Equals(99);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Request_BodyAsString()
|
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Request_BodyAsString()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsString = @"{
|
||||||
var body = new BodyData
|
|
||||||
{
|
|
||||||
BodyAsString = @"{
|
|
||||||
""Stores"": [
|
""Stores"": [
|
||||||
""Lambton Quay"",
|
""Lambton Quay"",
|
||||||
""Willis Street""
|
""Willis Street""
|
||||||
@@ -146,30 +148,30 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
}",
|
}",
|
||||||
DetectedBodyType = BodyType.String
|
DetectedBodyType = BodyType.String
|
||||||
};
|
};
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/json")
|
.WithHeader("Content-Type", "application/json")
|
||||||
.WithBody("{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}")
|
.WithBody("{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}")
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Equals($"{{{Environment.NewLine} \"Name\": \"Acme Co\",{Environment.NewLine} \"Products\": [{Environment.NewLine} {{{Environment.NewLine} \"Name\": \"Anvil\",{Environment.NewLine} \"Price\": 50{Environment.NewLine} }}{Environment.NewLine} ]{Environment.NewLine}}}");
|
Check.That(response.Message.BodyData.BodyAsString).Equals($"{{{Environment.NewLine} \"Name\": \"Acme Co\",{Environment.NewLine} \"Products\": [{Environment.NewLine} {{{Environment.NewLine} \"Name\": \"Anvil\",{Environment.NewLine} \"Price\": 50{Environment.NewLine} }}{Environment.NewLine} ]{Environment.NewLine}}}");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Request_BodyAsJObject()
|
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Request_BodyAsJObject()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsJson = JObject.Parse(@"{
|
||||||
var body = new BodyData
|
|
||||||
{
|
|
||||||
BodyAsJson = JObject.Parse(@"{
|
|
||||||
'Stores': [
|
'Stores': [
|
||||||
'Lambton Quay',
|
'Lambton Quay',
|
||||||
'Willis Street'
|
'Willis Street'
|
||||||
@@ -199,30 +201,30 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
}"),
|
}"),
|
||||||
DetectedBodyType = BodyType.Json
|
DetectedBodyType = BodyType.Json
|
||||||
};
|
};
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/json")
|
.WithHeader("Content-Type", "application/json")
|
||||||
.WithBody("{{JsonPath.SelectToken request.bodyAsJson \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}")
|
.WithBody("{{JsonPath.SelectToken request.bodyAsJson \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}")
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Equals($"{{{Environment.NewLine} \"Name\": \"Acme Co\",{Environment.NewLine} \"Products\": [{Environment.NewLine} {{{Environment.NewLine} \"Name\": \"Anvil\",{Environment.NewLine} \"Price\": 50{Environment.NewLine} }}{Environment.NewLine} ]{Environment.NewLine}}}");
|
Check.That(response.Message.BodyData.BodyAsString).Equals($"{{{Environment.NewLine} \"Name\": \"Acme Co\",{Environment.NewLine} \"Products\": [{Environment.NewLine} {{{Environment.NewLine} \"Name\": \"Anvil\",{Environment.NewLine} \"Price\": 50{Environment.NewLine} }}{Environment.NewLine} ]{Environment.NewLine}}}");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectTokens_Request_BodyAsString()
|
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectTokens_Request_BodyAsString()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsString = @"{
|
||||||
var body = new BodyData
|
|
||||||
{
|
|
||||||
BodyAsString = @"{
|
|
||||||
""Stores"": [
|
""Stores"": [
|
||||||
""Lambton Quay"",
|
""Lambton Quay"",
|
||||||
""Willis Street""
|
""Willis Street""
|
||||||
@@ -252,30 +254,30 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
}",
|
}",
|
||||||
DetectedBodyType = BodyType.String
|
DetectedBodyType = BodyType.String
|
||||||
};
|
};
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/json")
|
.WithHeader("Content-Type", "application/json")
|
||||||
.WithBody("{{#JsonPath.SelectTokens request.body \"$..Products[?(@.Price >= 50)].Name\"}}{{#each this}}%{{@index}}:{{this}}%{{/each}}{{/JsonPath.SelectTokens}}")
|
.WithBody("{{#JsonPath.SelectTokens request.body \"$..Products[?(@.Price >= 50)].Name\"}}{{#each this}}%{{@index}}:{{this}}%{{/each}}{{/JsonPath.SelectTokens}}")
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Equals("%0:Anvil%%1:Elbow Grease%");
|
Check.That(response.Message.BodyData.BodyAsString).Equals("%0:Anvil%%1:Elbow Grease%");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectTokens_Request_BodyAsJObject()
|
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectTokens_Request_BodyAsJObject()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsJson = JObject.Parse(@"{
|
||||||
var body = new BodyData
|
|
||||||
{
|
|
||||||
BodyAsJson = JObject.Parse(@"{
|
|
||||||
'Stores': [
|
'Stores': [
|
||||||
'Lambton Quay',
|
'Lambton Quay',
|
||||||
'Willis Street'
|
'Willis Street'
|
||||||
@@ -305,74 +307,73 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
}"),
|
}"),
|
||||||
DetectedBodyType = BodyType.Json
|
DetectedBodyType = BodyType.Json
|
||||||
};
|
};
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/json")
|
.WithHeader("Content-Type", "application/json")
|
||||||
.WithBody("{{#JsonPath.SelectTokens request.bodyAsJson \"$..Products[?(@.Price >= 50)].Name\"}}{{#each this}}%{{@index}}:{{this}}%{{/each}}{{/JsonPath.SelectTokens}}")
|
.WithBody("{{#JsonPath.SelectTokens request.bodyAsJson \"$..Products[?(@.Price >= 50)].Name\"}}{{#each this}}%{{@index}}:{{this}}%{{/each}}{{/JsonPath.SelectTokens}}")
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Equals("%0:Anvil%%1:Elbow Grease%");
|
Check.That(response.Message.BodyData.BodyAsString).Equals("%0:Anvil%%1:Elbow Grease%");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Response_ProvideResponse_Handlebars_JsonPath_SelectTokens_Throws()
|
public void Response_ProvideResponse_Handlebars_JsonPath_SelectTokens_Throws()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsJson = JObject.Parse(@"{
|
||||||
var body = new BodyData
|
|
||||||
{
|
|
||||||
BodyAsJson = JObject.Parse(@"{
|
|
||||||
'Stores': [
|
'Stores': [
|
||||||
'Lambton Quay',
|
'Lambton Quay',
|
||||||
'Willis Street'
|
'Willis Street'
|
||||||
]
|
]
|
||||||
}"),
|
}"),
|
||||||
DetectedBodyType = BodyType.Json
|
DetectedBodyType = BodyType.Json
|
||||||
};
|
};
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/json")
|
.WithHeader("Content-Type", "application/json")
|
||||||
.WithBody("{{#JsonPath.SelectTokens request.body \"$..Products[?(@.Price >= 50)].Name\"}}{{id}} {{value}},{{/JsonPath.SelectTokens}}")
|
.WithBody("{{#JsonPath.SelectTokens request.body \"$..Products[?(@.Price >= 50)].Name\"}}{{id}} {{value}},{{/JsonPath.SelectTokens}}")
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(request, _settings)).Throws<ArgumentNullException>();
|
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<ArgumentNullException>();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_Transformer_WithBodyAsFile_JsonPath()
|
public async Task Response_ProvideResponse_Transformer_WithBodyAsFile_JsonPath()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
string jsonString = "{ \"MyUniqueNumber\": \"1\" }";
|
||||||
|
var bodyData = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsString = jsonString,
|
||||||
string jsonString = "{ \"MyUniqueNumber\": \"1\" }";
|
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
|
||||||
var bodyData = new BodyData
|
DetectedBodyType = BodyType.Json,
|
||||||
{
|
DetectedBodyTypeFromContentType = BodyType.Json,
|
||||||
BodyAsString = jsonString,
|
Encoding = Encoding.UTF8
|
||||||
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
|
};
|
||||||
DetectedBodyType = BodyType.Json,
|
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, bodyData);
|
||||||
DetectedBodyTypeFromContentType = BodyType.Json,
|
|
||||||
Encoding = Encoding.UTF8
|
|
||||||
};
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, bodyData);
|
|
||||||
|
|
||||||
string jsonPath = "\"$.MyUniqueNumber\"";
|
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 ?
|
.WithBodyFromFile(@"c:\\{{JsonPath.SelectToken request.body " + jsonPath + "}}\\test.json"); // why use a \\ here ?
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(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");
|
Check.That(response.Message.BodyData.BodyAsFile).Equals(@"c:\1\test.json");
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -13,237 +13,239 @@ using WireMock.Types;
|
|||||||
using WireMock.Util;
|
using WireMock.Util;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithHandlebarsLinqTests
|
||||||
{
|
{
|
||||||
public class ResponseWithHandlebarsLinqTests
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
|
||||||
|
private Mock<IMapping> mappingMock;
|
||||||
|
|
||||||
|
public ResponseWithHandlebarsLinqTests()
|
||||||
{
|
{
|
||||||
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
mappingMock = new Mock<IMapping>();
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
|
||||||
|
|
||||||
public ResponseWithHandlebarsLinqTests()
|
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||||
|
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||||
|
|
||||||
|
_settings.FileSystemHandler = filesystemHandlerMock.Object;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Response_ProvideResponse_Handlebars_Linq1_String0()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData();
|
||||||
|
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234/pathtest"), "POST", "::1", body);
|
||||||
|
|
||||||
|
var responseBuilder = Response.Create()
|
||||||
|
.WithHeader("Content-Type", "application/json")
|
||||||
|
.WithBodyAsJson(new { x = "{{Linq request.Path 'it'}}" })
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
|
Check.That(j["x"]).IsNotNull();
|
||||||
|
Check.That(j["x"].ToString()).Equals("/pathtest");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Response_ProvideResponse_Handlebars_Linq1_String1()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
BodyAsJson = new JObject
|
||||||
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
|
||||||
|
|
||||||
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Response_ProvideResponse_Handlebars_Linq1_String0()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData();
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234/pathtest"), "POST", "::1", body);
|
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
|
||||||
.WithHeader("Content-Type", "application/json")
|
|
||||||
.WithBodyAsJson(new { x = "{{Linq request.Path 'it'}}" })
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
|
||||||
Check.That(j["x"]).IsNotNull();
|
|
||||||
Check.That(j["x"].ToString()).Equals("/pathtest");
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Response_ProvideResponse_Handlebars_Linq1_String1()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData
|
|
||||||
{
|
{
|
||||||
BodyAsJson = new JObject
|
{ "Id", new JValue(9) },
|
||||||
{
|
{ "Name", new JValue("Test") }
|
||||||
{ "Id", new JValue(9) },
|
},
|
||||||
{ "Name", new JValue("Test") }
|
DetectedBodyType = BodyType.Json
|
||||||
},
|
};
|
||||||
DetectedBodyType = BodyType.Json
|
|
||||||
};
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/json")
|
.WithHeader("Content-Type", "application/json")
|
||||||
.WithBodyAsJson(new { x = "{{Linq request.bodyAsJson 'it.Name + \"_123\"' }}" })
|
.WithBodyAsJson(new { x = "{{Linq request.bodyAsJson 'it.Name + \"_123\"' }}" })
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
Check.That(j["x"]).IsNotNull();
|
Check.That(j["x"]).IsNotNull();
|
||||||
Check.That(j["x"].ToString()).Equals("Test_123");
|
Check.That(j["x"].ToString()).Equals("Test_123");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_Handlebars_Linq1_String2()
|
public async Task Response_ProvideResponse_Handlebars_Linq1_String2()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsJson = new JObject
|
||||||
var body = new BodyData
|
|
||||||
{
|
{
|
||||||
BodyAsJson = new JObject
|
{ "Id", new JValue(9) },
|
||||||
{
|
{ "Name", new JValue("Test") }
|
||||||
{ "Id", new JValue(9) },
|
},
|
||||||
{ "Name", new JValue("Test") }
|
DetectedBodyType = BodyType.Json
|
||||||
},
|
};
|
||||||
DetectedBodyType = BodyType.Json
|
|
||||||
};
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/json")
|
.WithHeader("Content-Type", "application/json")
|
||||||
.WithBodyAsJson(new { x = "{{Linq request.bodyAsJson 'new(it.Name + \"_123\" as N, it.Id as I)' }}" })
|
.WithBodyAsJson(new { x = "{{Linq request.bodyAsJson 'new(it.Name + \"_123\" as N, it.Id as I)' }}" })
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
Check.That(j["x"]).IsNotNull();
|
Check.That(j["x"]).IsNotNull();
|
||||||
Check.That(j["x"].ToString()).Equals("{ N = Test_123, I = 9 }");
|
Check.That(j["x"].ToString()).Equals("{ N = Test_123, I = 9 }");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_Handlebars_Linq2_Object()
|
public async Task Response_ProvideResponse_Handlebars_Linq2_Object()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsJson = new JObject
|
||||||
var body = new BodyData
|
|
||||||
{
|
{
|
||||||
BodyAsJson = new JObject
|
{ "Id", new JValue(9) },
|
||||||
{
|
{ "Name", new JValue("Test") }
|
||||||
{ "Id", new JValue(9) },
|
},
|
||||||
{ "Name", new JValue("Test") }
|
DetectedBodyType = BodyType.Json
|
||||||
},
|
};
|
||||||
DetectedBodyType = BodyType.Json
|
|
||||||
};
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/json")
|
.WithHeader("Content-Type", "application/json")
|
||||||
.WithBodyAsJson(new { x = "{{#Linq request.bodyAsJson 'new(it.Name + \"_123\" as N, it.Id as I)' }}{{this}}{{/Linq}}" })
|
.WithBodyAsJson(new { x = "{{#Linq request.bodyAsJson 'new(it.Name + \"_123\" as N, it.Id as I)' }}{{this}}{{/Linq}}" })
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
Check.That(j["x"]).IsNotNull();
|
Check.That(j["x"]).IsNotNull();
|
||||||
Check.That(j["x"].ToString()).Equals("{ N = Test_123, I = 9 }");
|
Check.That(j["x"].ToString()).Equals("{ N = Test_123, I = 9 }");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Response_ProvideResponse_Handlebars_Linq_Throws_ArgumentException()
|
public void Response_ProvideResponse_Handlebars_Linq_Throws_ArgumentException()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsJson = new { x = "x" },
|
||||||
var body = new BodyData
|
DetectedBodyType = BodyType.Json
|
||||||
|
};
|
||||||
|
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
||||||
|
|
||||||
|
var responseBuilder = Response.Create()
|
||||||
|
.WithBodyAsJson(new { x = "{{Linq request.bodyAsJson 1}}" })
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(mappingMock.Object, request, _settings)).Throws<ArgumentException>();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Response_ProvideResponse_Handlebars_Linq1_Throws_ArgumentNullException()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData();
|
||||||
|
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
||||||
|
|
||||||
|
var responseBuilder = Response.Create()
|
||||||
|
.WithBodyAsJson(new { x = "{{Linq request.body 'Name'}}" })
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(mappingMock.Object, request, _settings)).Throws<ArgumentNullException>();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Response_ProvideResponse_Handlebars_Linq1_Throws_HandlebarsException()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData();
|
||||||
|
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
||||||
|
|
||||||
|
var responseBuilder = Response.Create()
|
||||||
|
.WithBodyAsJson(new { x = "{{Linq request.bodyAsJson}} ''" })
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(mappingMock.Object, request, _settings)).Throws<HandlebarsException>();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Response_ProvideResponse_Handlebars_Linq1_ParseError_Throws_ExceptionMessage()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
|
{
|
||||||
|
BodyAsJson = new JObject
|
||||||
{
|
{
|
||||||
BodyAsJson = new { x = "x" },
|
{ "Id", new JValue(9) },
|
||||||
DetectedBodyType = BodyType.Json
|
{ "Name", new JValue("Test") }
|
||||||
};
|
},
|
||||||
|
DetectedBodyType = BodyType.Json
|
||||||
|
};
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithBodyAsJson(new { x = "{{Linq request.bodyAsJson 1}}" })
|
.WithBodyAsJson(new { x = "{{Linq request.bodyAsJson '---' }}" })
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(request, _settings)).Throws<ArgumentException>();
|
Func<Task> a = async () => await responseBuilder.ProvideResponseAsync(mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
// Assert
|
||||||
public void Response_ProvideResponse_Handlebars_Linq1_Throws_ArgumentNullException()
|
a.Should().ThrowAsync<HandlebarsException>();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Response_ProvideResponse_Handlebars_Linq2_ParseError_Throws_ExceptionMessage()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsJson = new JObject
|
||||||
var body = new BodyData();
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
|
||||||
.WithBodyAsJson(new { x = "{{Linq request.body 'Name'}}" })
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(request, _settings)).Throws<ArgumentNullException>();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Response_ProvideResponse_Handlebars_Linq1_Throws_HandlebarsException()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData();
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
|
||||||
.WithBodyAsJson(new { x = "{{Linq request.bodyAsJson}} ''" })
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(request, _settings)).Throws<HandlebarsException>();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Response_ProvideResponse_Handlebars_Linq1_ParseError_Throws_ExceptionMessage()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData
|
|
||||||
{
|
{
|
||||||
BodyAsJson = new JObject
|
{ "Id", new JValue(9) },
|
||||||
{
|
{ "Name", new JValue("Test") }
|
||||||
{ "Id", new JValue(9) },
|
},
|
||||||
{ "Name", new JValue("Test") }
|
DetectedBodyType = BodyType.Json
|
||||||
},
|
};
|
||||||
DetectedBodyType = BodyType.Json
|
|
||||||
};
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithBodyAsJson(new { x = "{{Linq request.bodyAsJson '---' }}" })
|
.WithBodyAsJson(new { x = "{{#Linq request.bodyAsJson '---' }}{{this}}{{/Linq}}" })
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Func<Task> a = async () => await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
Func<Task> a = async () => await responseBuilder.ProvideResponseAsync(mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
a.Should().ThrowAsync<HandlebarsException>();
|
a.Should().ThrowAsync<HandlebarsException>();
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Response_ProvideResponse_Handlebars_Linq2_ParseError_Throws_ExceptionMessage()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData
|
|
||||||
{
|
|
||||||
BodyAsJson = new JObject
|
|
||||||
{
|
|
||||||
{ "Id", new JValue(9) },
|
|
||||||
{ "Name", new JValue("Test") }
|
|
||||||
},
|
|
||||||
DetectedBodyType = BodyType.Json
|
|
||||||
};
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
|
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
|
||||||
.WithBodyAsJson(new { x = "{{#Linq request.bodyAsJson '---' }}{{this}}{{/Linq}}" })
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
Func<Task> a = async () => await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
a.Should().ThrowAsync<HandlebarsException>();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,160 +10,162 @@ using WireMock.Settings;
|
|||||||
using WireMock.Types;
|
using WireMock.Types;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithHandlebarsRandomTests
|
||||||
{
|
{
|
||||||
public class ResponseWithHandlebarsRandomTests
|
private const string ClientIp = "::1";
|
||||||
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
|
|
||||||
|
public ResponseWithHandlebarsRandomTests()
|
||||||
{
|
{
|
||||||
private const string ClientIp = "::1";
|
_mappingMock = new Mock<IMapping>();
|
||||||
|
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||||
|
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||||
|
|
||||||
public ResponseWithHandlebarsRandomTests()
|
_settings.FileSystemHandler = filesystemHandlerMock.Object;
|
||||||
{
|
}
|
||||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
|
||||||
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
|
||||||
|
|
||||||
_settings.FileSystemHandler = filesystemHandlerMock.Object;
|
[Fact]
|
||||||
}
|
public async Task Response_ProvideResponseAsync_Handlebars_Random1()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||||
|
|
||||||
[Fact]
|
var responseBuilder = Response.Create()
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_Random1()
|
.WithBodyAsJson(new
|
||||||
{
|
{
|
||||||
// Assign
|
Text = "{{Random Type=\"Text\" Min=8 Max=20}}",
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
DateTime = "{{Random Type=\"DateTime\"}}",
|
||||||
|
Integer = "{{Random Type=\"Integer\" Min=1000 Max=1000}}",
|
||||||
|
Long = "{{Random Type=\"Long\" Min=77777777 Max=99999999}}"
|
||||||
|
})
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBodyAsJson(new
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
{
|
|
||||||
Text = "{{Random Type=\"Text\" Min=8 Max=20}}",
|
|
||||||
DateTime = "{{Random Type=\"DateTime\"}}",
|
|
||||||
Integer = "{{Random Type=\"Integer\" Min=1000 Max=1000}}",
|
|
||||||
Long = "{{Random Type=\"Long\" Min=77777777 Max=99999999}}"
|
|
||||||
})
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// Assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
|
Check.That(j["Text"].Value<string>()).IsNotEmpty();
|
||||||
|
Check.That(j["Integer"].Value<int>()).IsEqualTo(1000);
|
||||||
|
Check.That(j["Long"].Value<long>()).IsStrictlyGreaterThan(77777777).And.IsStrictlyLessThan(99999999);
|
||||||
|
}
|
||||||
|
|
||||||
// Assert
|
[Fact]
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
public async Task Response_ProvideResponseAsync_Handlebars_Random1_Boolean()
|
||||||
Check.That(j["Text"].Value<string>()).IsNotEmpty();
|
{
|
||||||
Check.That(j["Integer"].Value<int>()).IsEqualTo(1000);
|
// Assign
|
||||||
Check.That(j["Long"].Value<long>()).IsStrictlyGreaterThan(77777777).And.IsStrictlyLessThan(99999999);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
var responseBuilder = Response.Create()
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_Random1_Boolean()
|
.WithBodyAsJson(new
|
||||||
{
|
{
|
||||||
// Assign
|
Value = "{{Random Type=\"Boolean\"}}"
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
})
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBodyAsJson(new
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
{
|
|
||||||
Value = "{{Random Type=\"Boolean\"}}"
|
|
||||||
})
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// Assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
|
Check.That(j["Value"].Type).IsEqualTo(JTokenType.Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
// Assert
|
[Theory]
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
[InlineData(ReplaceNodeOptions.None, JTokenType.Integer)]
|
||||||
Check.That(j["Value"].Type).IsEqualTo(JTokenType.Boolean);
|
//[InlineData(ReplaceNodeOptions.Bool, JTokenType.String)]
|
||||||
}
|
//[InlineData(ReplaceNodeOptions.Integer, JTokenType.Integer)]
|
||||||
|
//[InlineData(ReplaceNodeOptions.Bool | ReplaceNodeOptions.Integer, JTokenType.Integer)]
|
||||||
|
public async Task Response_ProvideResponseAsync_Handlebars_Random1_Integer(ReplaceNodeOptions options, JTokenType expected)
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||||
|
|
||||||
[Theory]
|
var responseBuilder = Response.Create()
|
||||||
[InlineData(ReplaceNodeOptions.None, JTokenType.Integer)]
|
.WithBodyAsJson(new
|
||||||
//[InlineData(ReplaceNodeOptions.Bool, JTokenType.String)]
|
{
|
||||||
//[InlineData(ReplaceNodeOptions.Integer, JTokenType.Integer)]
|
Value = "{{Random Type=\"Integer\"}}"
|
||||||
//[InlineData(ReplaceNodeOptions.Bool | ReplaceNodeOptions.Integer, JTokenType.Integer)]
|
})
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_Random1_Integer(ReplaceNodeOptions options, JTokenType expected)
|
.WithTransformer(options);
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBodyAsJson(new
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
{
|
|
||||||
Value = "{{Random Type=\"Integer\"}}"
|
|
||||||
})
|
|
||||||
.WithTransformer(options);
|
|
||||||
|
|
||||||
// Act
|
// Assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
|
Check.That(j["Value"].Type).IsEqualTo(expected);
|
||||||
|
}
|
||||||
|
|
||||||
// Assert
|
[Fact]
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
public async Task Response_ProvideResponseAsync_Handlebars_Random1_Guid()
|
||||||
Check.That(j["Value"].Type).IsEqualTo(expected);
|
{
|
||||||
}
|
// Assign
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||||
|
|
||||||
[Fact]
|
var responseBuilder = Response.Create()
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_Random1_Guid()
|
.WithBodyAsJson(new
|
||||||
{
|
{
|
||||||
// Assign
|
Guid1 = "{{Random Type=\"Guid\" Uppercase=false}}",
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
Guid2 = "{{Random Type=\"Guid\"}}"
|
||||||
|
})
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBodyAsJson(new
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
{
|
|
||||||
Guid1 = "{{Random Type=\"Guid\" Uppercase=false}}",
|
|
||||||
Guid2 = "{{Random Type=\"Guid\"}}"
|
|
||||||
})
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// Assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
|
string guid1 = j["Guid1"].Value<string>();
|
||||||
|
Check.That(guid1.ToUpper()).IsNotEqualTo(guid1);
|
||||||
|
string guid2 = j["Guid2"].Value<string>();
|
||||||
|
Check.That(guid2.ToUpper()).IsEqualTo(guid2);
|
||||||
|
}
|
||||||
|
|
||||||
// Assert
|
[Fact]
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
public async Task Response_ProvideResponseAsync_Handlebars_Random1_StringList()
|
||||||
string guid1 = j["Guid1"].Value<string>();
|
{
|
||||||
Check.That(guid1.ToUpper()).IsNotEqualTo(guid1);
|
// Assign
|
||||||
string guid2 = j["Guid2"].Value<string>();
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||||
Check.That(guid2.ToUpper()).IsEqualTo(guid2);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
var responseBuilder = Response.Create()
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_Random1_StringList()
|
.WithBodyAsJson(new
|
||||||
{
|
{
|
||||||
// Assign
|
StringValue = "{{Random Type=\"StringList\" Values=[\"a\", \"b\", \"c\"]}}"
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
})
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBodyAsJson(new
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
{
|
|
||||||
StringValue = "{{Random Type=\"StringList\" Values=[\"a\", \"b\", \"c\"]}}"
|
|
||||||
})
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// Assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
|
string value = j["StringValue"].Value<string>();
|
||||||
|
Check.That(new[] { "a", "b", "c" }.Contains(value)).IsTrue();
|
||||||
|
}
|
||||||
|
|
||||||
// Assert
|
[Fact]
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
public async Task Response_ProvideResponseAsync_Handlebars_Random2()
|
||||||
string value = j["StringValue"].Value<string>();
|
{
|
||||||
Check.That(new[] { "a", "b", "c" }.Contains(value)).IsTrue();
|
// Assign
|
||||||
}
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||||
|
|
||||||
[Fact]
|
var responseBuilder = Response.Create()
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_Random2()
|
.WithBodyAsJson(new
|
||||||
{
|
{
|
||||||
// Assign
|
Integer = "{{#Random Type=\"Integer\" Min=10000000 Max=99999999}}{{this}}{{/Random}}",
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
})
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBodyAsJson(new
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
{
|
|
||||||
Integer = "{{#Random Type=\"Integer\" Min=10000000 Max=99999999}}{{this}}{{/Random}}",
|
|
||||||
})
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// Assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
|
Check.That(j["Integer"].Value<int>()).IsStrictlyGreaterThan(10000000).And.IsStrictlyLessThan(99999999);
|
||||||
// Assert
|
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
|
||||||
Check.That(j["Integer"].Value<int>()).IsStrictlyGreaterThan(10000000).And.IsStrictlyLessThan(99999999);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,113 +10,114 @@ using WireMock.Types;
|
|||||||
using WireMock.Util;
|
using WireMock.Util;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithHandlebarsRegexTests
|
||||||
{
|
{
|
||||||
public class ResponseWithHandlebarsRegexTests
|
private const string ClientIp = "::1";
|
||||||
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
|
|
||||||
|
public ResponseWithHandlebarsRegexTests()
|
||||||
{
|
{
|
||||||
private const string ClientIp = "::1";
|
_mappingMock = new Mock<IMapping>();
|
||||||
|
|
||||||
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||||
|
|
||||||
public ResponseWithHandlebarsRegexTests()
|
_settings.FileSystemHandler = filesystemHandlerMock.Object;
|
||||||
{
|
}
|
||||||
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
|
||||||
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
|
||||||
|
|
||||||
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
|
[Fact]
|
||||||
}
|
public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData { BodyAsString = "abc", DetectedBodyType = BodyType.String };
|
||||||
|
|
||||||
[Fact]
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData { BodyAsString = "abc", DetectedBodyType = BodyType.String };
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var responseBuilder = Response.Create()
|
||||||
|
.WithBody("{{Regex.Match request.body \"^(\\w+)$\"}}")
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBody("{{Regex.Match request.body \"^(\\w+)$\"}}")
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
Check.That(response.Message.BodyData.BodyAsString).Equals("abc");
|
||||||
|
}
|
||||||
|
|
||||||
// assert
|
[Fact]
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Equals("abc");
|
public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch_NoMatch()
|
||||||
}
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData { BodyAsString = "abc", DetectedBodyType = BodyType.String };
|
||||||
|
|
||||||
[Fact]
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch_NoMatch()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData { BodyAsString = "abc", DetectedBodyType = BodyType.String };
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var responseBuilder = Response.Create()
|
||||||
|
.WithBody("{{Regex.Match request.body \"^?0$\"}}")
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBody("{{Regex.Match request.body \"^?0$\"}}")
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
Check.That(response.Message.BodyData.BodyAsString).Equals("");
|
||||||
|
}
|
||||||
|
|
||||||
// assert
|
[Fact]
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Equals("");
|
public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch2()
|
||||||
}
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData { BodyAsString = "https://localhost:5000/", DetectedBodyType = BodyType.String };
|
||||||
|
|
||||||
[Fact]
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch2()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData { BodyAsString = "https://localhost:5000/", DetectedBodyType = BodyType.String };
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var responseBuilder = Response.Create()
|
||||||
|
.WithBody("{{#Regex.Match request.body \"^(?<proto>\\w+)://[^/]+?(?<port>\\d+)/?\"}}{{this.port}}-{{this.proto}}{{/Regex.Match}}")
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBody("{{#Regex.Match request.body \"^(?<proto>\\w+)://[^/]+?(?<port>\\d+)/?\"}}{{this.port}}-{{this.proto}}{{/Regex.Match}}")
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
Check.That(response.Message.BodyData.BodyAsString).Equals("5000-https");
|
||||||
|
}
|
||||||
|
|
||||||
// assert
|
[Fact]
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Equals("5000-https");
|
public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch2_NoMatch()
|
||||||
}
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData { BodyAsString = "{{\\test", DetectedBodyType = BodyType.String };
|
||||||
|
|
||||||
[Fact]
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch2_NoMatch()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData { BodyAsString = "{{\\test", DetectedBodyType = BodyType.String };
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var responseBuilder = Response.Create()
|
||||||
|
.WithBody("{{#Regex.Match request.body \"^(?<proto>\\w+)://[^/]+?(?<port>\\d+)/?\"}}{{this}}{{/Regex.Match}}")
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBody("{{#Regex.Match request.body \"^(?<proto>\\w+)://[^/]+?(?<port>\\d+)/?\"}}{{this}}{{/Regex.Match}}")
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
Check.That(response.Message.BodyData.BodyAsString).Equals("");
|
||||||
|
}
|
||||||
|
|
||||||
// assert
|
[Fact]
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Equals("");
|
public void Response_ProvideResponseAsync_Handlebars_RegexMatch2_Throws()
|
||||||
}
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData { BodyAsString = "{{\\test", DetectedBodyType = BodyType.String };
|
||||||
|
|
||||||
[Fact]
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
public void Response_ProvideResponseAsync_Handlebars_RegexMatch2_Throws()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData { BodyAsString = "{{\\test", DetectedBodyType = BodyType.String };
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var responseBuilder = Response.Create()
|
||||||
|
.WithBody("{{#Regex.Match request.bodyAsJson \"^(?<proto>\\w+)://[^/]+?(?<port>\\d+)/?\"}}{{/Regex.Match}}")
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act and Assert
|
||||||
.WithBody("{{#Regex.Match request.bodyAsJson \"^(?<proto>\\w+)://[^/]+?(?<port>\\d+)/?\"}}{{/Regex.Match}}")
|
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<ArgumentNullException>();
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act and Assert
|
|
||||||
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(request, _settings)).Throws<ArgumentNullException>();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,117 +14,119 @@ using FluentAssertions;
|
|||||||
using Wmhelp.XPath2;
|
using Wmhelp.XPath2;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithHandlebarsXPathTests
|
||||||
{
|
{
|
||||||
public class ResponseWithHandlebarsXPathTests
|
private const string ClientIp = "::1";
|
||||||
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
|
|
||||||
|
public ResponseWithHandlebarsXPathTests()
|
||||||
{
|
{
|
||||||
private const string ClientIp = "::1";
|
_mappingMock = new Mock<IMapping>();
|
||||||
|
|
||||||
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||||
|
|
||||||
public ResponseWithHandlebarsXPathTests()
|
_settings.FileSystemHandler = filesystemHandlerMock.Object;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Response_ProvideResponse_Handlebars_XPath_SelectSingleNode_Request_BodyAsString()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
BodyAsString = @"<todo-list>
|
||||||
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
|
||||||
|
|
||||||
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Response_ProvideResponse_Handlebars_XPath_SelectSingleNode_Request_BodyAsString()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData
|
|
||||||
{
|
|
||||||
BodyAsString = @"<todo-list>
|
|
||||||
<todo-item id='a1'>abc</todo-item>
|
<todo-item id='a1'>abc</todo-item>
|
||||||
<todo-item id='a2'>def</todo-item>
|
<todo-item id='a2'>def</todo-item>
|
||||||
<todo-item id='a3'>xyz</todo-item>
|
<todo-item id='a3'>xyz</todo-item>
|
||||||
</todo-list>",
|
</todo-list>",
|
||||||
DetectedBodyType = BodyType.String
|
DetectedBodyType = BodyType.String
|
||||||
};
|
};
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/xml")
|
.WithHeader("Content-Type", "application/xml")
|
||||||
.WithBody("<response>{{XPath.SelectSingleNode request.body \"/todo-list/todo-item[1]\"}}</response>")
|
.WithBody("<response>{{XPath.SelectSingleNode request.body \"/todo-list/todo-item[1]\"}}</response>")
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
var nav = new XmlDocument { InnerXml = response.Message.BodyData.BodyAsString }.CreateNavigator();
|
var nav = new XmlDocument { InnerXml = response.Message.BodyData.BodyAsString }.CreateNavigator();
|
||||||
var node = nav.XPath2SelectSingleNode("/response/todo-item");
|
var node = nav.XPath2SelectSingleNode("/response/todo-item");
|
||||||
Check.That(node.Value).Equals("abc");
|
Check.That(node.Value).Equals("abc");
|
||||||
Check.That(node.GetAttribute("id", "")).Equals("a1");
|
Check.That(node.GetAttribute("id", "")).Equals("a1");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_Handlebars_XPath_SelectSingleNode_Text_Request_BodyAsString()
|
public async Task Response_ProvideResponse_Handlebars_XPath_SelectSingleNode_Text_Request_BodyAsString()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsString = @"<todo-list>
|
||||||
var body = new BodyData
|
|
||||||
{
|
|
||||||
BodyAsString = @"<todo-list>
|
|
||||||
<todo-item id='a1'>abc</todo-item>
|
<todo-item id='a1'>abc</todo-item>
|
||||||
<todo-item id='a2'>def</todo-item>
|
<todo-item id='a2'>def</todo-item>
|
||||||
<todo-item id='a3'>xyz</todo-item>
|
<todo-item id='a3'>xyz</todo-item>
|
||||||
</todo-list>",
|
</todo-list>",
|
||||||
DetectedBodyType = BodyType.String
|
DetectedBodyType = BodyType.String
|
||||||
};
|
};
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/xml")
|
.WithHeader("Content-Type", "application/xml")
|
||||||
.WithBody("{{XPath.SelectSingleNode request.body \"/todo-list/todo-item[1]/text()\"}}")
|
.WithBody("{{XPath.SelectSingleNode request.body \"/todo-list/todo-item[1]/text()\"}}")
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.BodyData.BodyAsString).IsEqualTo("abc");
|
Check.That(response.Message.BodyData.BodyAsString).IsEqualTo("abc");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_Handlebars_XPath_SelectNodes_Request_BodyAsString()
|
public async Task Response_ProvideResponse_Handlebars_XPath_SelectNodes_Request_BodyAsString()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsString = @"<todo-list>
|
||||||
var body = new BodyData
|
|
||||||
{
|
|
||||||
BodyAsString = @"<todo-list>
|
|
||||||
<todo-item id='a1'>abc</todo-item>
|
<todo-item id='a1'>abc</todo-item>
|
||||||
<todo-item id='a2'>def</todo-item>
|
<todo-item id='a2'>def</todo-item>
|
||||||
<todo-item id='a3'>xyz</todo-item>
|
<todo-item id='a3'>xyz</todo-item>
|
||||||
</todo-list>",
|
</todo-list>",
|
||||||
DetectedBodyType = BodyType.String
|
DetectedBodyType = BodyType.String
|
||||||
};
|
};
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/xml")
|
.WithHeader("Content-Type", "application/xml")
|
||||||
.WithBody("<response>{{XPath.SelectNodes request.body \"/todo-list/todo-item\"}}</response>")
|
.WithBody("<response>{{XPath.SelectNodes request.body \"/todo-list/todo-item\"}}</response>")
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
var nav = new XmlDocument { InnerXml = response.Message.BodyData.BodyAsString }.CreateNavigator();
|
var nav = new XmlDocument { InnerXml = response.Message.BodyData.BodyAsString }.CreateNavigator();
|
||||||
var nodes = nav.XPath2SelectNodes("/response/todo-item");
|
var nodes = nav.XPath2SelectNodes("/response/todo-item");
|
||||||
Check.That(nodes.Count + 1).IsEqualTo(3);
|
Check.That(nodes.Count + 1).IsEqualTo(3);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_Handlebars_XPath_SelectSingleNode_Request_SoapXML_BodyAsString()
|
public async Task Response_ProvideResponse_Handlebars_XPath_SelectSingleNode_Request_SoapXML_BodyAsString()
|
||||||
{
|
{
|
||||||
// Assign
|
// Assign
|
||||||
string soap = @"
|
string soap = @"
|
||||||
<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:ns=""http://www.Test.nl/XMLHeader/10"" xmlns:req=""http://www.Test.nl/Betalen/COU/Services/RdplDbTknLystByOvkLyst/8/Req"">
|
<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:ns=""http://www.Test.nl/XMLHeader/10"" xmlns:req=""http://www.Test.nl/Betalen/COU/Services/RdplDbTknLystByOvkLyst/8/Req"">
|
||||||
<soapenv:Header>
|
<soapenv:Header>
|
||||||
<ns:TestHeader>
|
<ns:TestHeader>
|
||||||
@@ -156,80 +158,79 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
|||||||
</req:RdplDbTknLystByOvkLyst_REQ>
|
</req:RdplDbTknLystByOvkLyst_REQ>
|
||||||
</soapenv:Body>
|
</soapenv:Body>
|
||||||
</soapenv:Envelope>";
|
</soapenv:Envelope>";
|
||||||
var body = new BodyData
|
var body = new BodyData
|
||||||
{
|
|
||||||
BodyAsString = soap,
|
|
||||||
DetectedBodyType = BodyType.String
|
|
||||||
};
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
|
||||||
.WithHeader("Content-Type", "application/xml")
|
|
||||||
.WithBody("<response>{{XPath.SelectSingleNode request.body \"//*[local-name()='TokenIdLijst']\"}}</response>")
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
response.Message.BodyData.BodyAsString.Should().Contain("TokenIdLijst").And.Contain("0000083256").And.Contain("0000083259");
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Response_ProvideResponse_Handlebars_XPath_Evaluate_Request_BodyAsString()
|
|
||||||
{
|
{
|
||||||
// Assign
|
BodyAsString = soap,
|
||||||
var body = new BodyData
|
DetectedBodyType = BodyType.String
|
||||||
{
|
};
|
||||||
BodyAsString = @"<todo-list>
|
|
||||||
<todo-item id='a1'>abc</todo-item>
|
|
||||||
<todo-item id='a2'>def</todo-item>
|
|
||||||
<todo-item id='a3'>xyz</todo-item>
|
|
||||||
</todo-list>",
|
|
||||||
DetectedBodyType = BodyType.String
|
|
||||||
};
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
var responseBuilder = Response.Create()
|
||||||
.WithHeader("Content-Type", "application/xml")
|
.WithHeader("Content-Type", "application/xml")
|
||||||
.WithBody("{{XPath.Evaluate request.body \"boolean(/todo-list[count(todo-item) = 3])\"}}")
|
.WithBody("<response>{{XPath.SelectSingleNode request.body \"//*[local-name()='TokenIdLijst']\"}}</response>")
|
||||||
.WithTransformer();
|
.WithTransformer();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.BodyData.BodyAsString).IsEqualIgnoringCase("True");
|
response.Message.BodyData.BodyAsString.Should().Contain("TokenIdLijst").And.Contain("0000083256").And.Contain("0000083259");
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Response_ProvideResponse_Handlebars_XPath_Evaluate_Attribute_Request_BodyAsString()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData
|
|
||||||
{
|
|
||||||
BodyAsString = @"<todo-list>
|
|
||||||
<todo-item id='a1'>abc</todo-item>
|
|
||||||
<todo-item id='a2'>def</todo-item>
|
|
||||||
<todo-item id='a3'>xyz</todo-item>
|
|
||||||
</todo-list>",
|
|
||||||
DetectedBodyType = BodyType.String
|
|
||||||
};
|
|
||||||
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
|
||||||
.WithHeader("Content-Type", "application/xml")
|
|
||||||
.WithBody("{{XPath.Evaluate request.body \"string(/todo-list/todo-item[1]/@id)\"}}")
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Check.That(response.Message.BodyData.BodyAsString).IsEqualTo("a1");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Response_ProvideResponse_Handlebars_XPath_Evaluate_Request_BodyAsString()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
|
{
|
||||||
|
BodyAsString = @"<todo-list>
|
||||||
|
<todo-item id='a1'>abc</todo-item>
|
||||||
|
<todo-item id='a2'>def</todo-item>
|
||||||
|
<todo-item id='a3'>xyz</todo-item>
|
||||||
|
</todo-list>",
|
||||||
|
DetectedBodyType = BodyType.String
|
||||||
|
};
|
||||||
|
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
|
var responseBuilder = Response.Create()
|
||||||
|
.WithHeader("Content-Type", "application/xml")
|
||||||
|
.WithBody("{{XPath.Evaluate request.body \"boolean(/todo-list[count(todo-item) = 3])\"}}")
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Check.That(response.Message.BodyData.BodyAsString).IsEqualIgnoringCase("True");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Response_ProvideResponse_Handlebars_XPath_Evaluate_Attribute_Request_BodyAsString()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
|
{
|
||||||
|
BodyAsString = @"<todo-list>
|
||||||
|
<todo-item id='a1'>abc</todo-item>
|
||||||
|
<todo-item id='a2'>def</todo-item>
|
||||||
|
<todo-item id='a3'>xyz</todo-item>
|
||||||
|
</todo-list>",
|
||||||
|
DetectedBodyType = BodyType.String
|
||||||
|
};
|
||||||
|
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
|
||||||
|
|
||||||
|
var responseBuilder = Response.Create()
|
||||||
|
.WithHeader("Content-Type", "application/xml")
|
||||||
|
.WithBody("{{XPath.Evaluate request.body \"string(/todo-list/todo-item[1]/@id)\"}}")
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Check.That(response.Message.BodyData.BodyAsString).IsEqualTo("a1");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
using Moq;
|
using Moq;
|
||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
using NFluent;
|
using NFluent;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -8,67 +8,68 @@ using WireMock.ResponseBuilders;
|
|||||||
using WireMock.Settings;
|
using WireMock.Settings;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithHandlebarsXegerTests
|
||||||
{
|
{
|
||||||
public class ResponseWithHandlebarsXegerTests
|
private const string ClientIp = "::1";
|
||||||
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
|
|
||||||
|
public ResponseWithHandlebarsXegerTests()
|
||||||
{
|
{
|
||||||
private const string ClientIp = "::1";
|
_mappingMock = new Mock<IMapping>();
|
||||||
|
|
||||||
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||||
|
|
||||||
public ResponseWithHandlebarsXegerTests()
|
_settings.FileSystemHandler = filesystemHandlerMock.Object;
|
||||||
{
|
}
|
||||||
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
|
||||||
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
|
||||||
|
|
||||||
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
|
[Fact]
|
||||||
}
|
public async Task Response_ProvideResponseAsync_Handlebars_Xeger1()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||||
|
|
||||||
[Fact]
|
var responseBuilder = Response.Create()
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_Xeger1()
|
.WithBodyAsJson(new
|
||||||
{
|
{
|
||||||
// Assign
|
Number = "{{Xeger.Generate \"[1-9]{1}\\d{3}\"}}",
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
Postcode = "{{Xeger.Generate \"[1-9][0-9]{3}[A-Z]{2}\"}}"
|
||||||
|
})
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBodyAsJson(new
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings);
|
||||||
{
|
|
||||||
Number = "{{Xeger.Generate \"[1-9]{1}\\d{3}\"}}",
|
|
||||||
Postcode = "{{Xeger.Generate \"[1-9][0-9]{3}[A-Z]{2}\"}}"
|
|
||||||
})
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// Assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
|
Check.That(j["Number"].Value<int>()).IsStrictlyGreaterThan(1000).And.IsStrictlyLessThan(9999);
|
||||||
|
Check.That(j["Postcode"].Value<string>()).IsNotEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
// Assert
|
[Fact]
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
public async Task Response_ProvideResponseAsync_Handlebars_Xeger2()
|
||||||
Check.That(j["Number"].Value<int>()).IsStrictlyGreaterThan(1000).And.IsStrictlyLessThan(9999);
|
{
|
||||||
Check.That(j["Postcode"].Value<string>()).IsNotEmpty();
|
// Assign
|
||||||
}
|
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||||
|
|
||||||
[Fact]
|
var responseBuilder = Response.Create()
|
||||||
public async Task Response_ProvideResponseAsync_Handlebars_Xeger2()
|
.WithBodyAsJson(new
|
||||||
{
|
{
|
||||||
// Assign
|
Number = "{{#Xeger.Generate \"[1-9]{1}\\d{3}\"}}{{this}}{{/Xeger.Generate}}",
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
Postcode = "{{#Xeger.Generate \"[1-9][0-9]{3}[A-Z]{2}\"}}{{this}}{{/Xeger.Generate}}"
|
||||||
|
})
|
||||||
|
.WithTransformer();
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
// Act
|
||||||
.WithBodyAsJson(new
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings);
|
||||||
{
|
|
||||||
Number = "{{#Xeger.Generate \"[1-9]{1}\\d{3}\"}}{{this}}{{/Xeger.Generate}}",
|
|
||||||
Postcode = "{{#Xeger.Generate \"[1-9][0-9]{3}[A-Z]{2}\"}}{{this}}{{/Xeger.Generate}}"
|
|
||||||
})
|
|
||||||
.WithTransformer();
|
|
||||||
|
|
||||||
// Act
|
// Assert
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings);
|
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
||||||
|
Check.That(j["Number"].Value<int>()).IsStrictlyGreaterThan(1000).And.IsStrictlyLessThan(9999);
|
||||||
// Assert
|
Check.That(j["Postcode"].Value<string>()).IsNotEmpty();
|
||||||
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
|
|
||||||
Check.That(j["Number"].Value<int>()).IsStrictlyGreaterThan(1000).And.IsStrictlyLessThan(9999);
|
|
||||||
Check.That(j["Postcode"].Value<string>()).IsNotEmpty();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using Moq;
|
||||||
using NFluent;
|
using NFluent;
|
||||||
using WireMock.Models;
|
using WireMock.Models;
|
||||||
using WireMock.ResponseBuilders;
|
using WireMock.ResponseBuilders;
|
||||||
@@ -7,89 +8,95 @@ using WireMock.Settings;
|
|||||||
using WireMock.Types;
|
using WireMock.Types;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithHeadersTests
|
||||||
{
|
{
|
||||||
public class ResponseWithHeadersTests
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
private const string ClientIp = "::1";
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
|
|
||||||
|
public ResponseWithHeadersTests()
|
||||||
{
|
{
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
_mappingMock = new Mock<IMapping>();
|
||||||
private const string ClientIp = "::1";
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("Content-Length", "1024")]
|
[InlineData("Content-Length", "1024")]
|
||||||
[InlineData("Transfer-Encoding", "identity")]
|
[InlineData("Transfer-Encoding", "identity")]
|
||||||
[InlineData("Location", "http://test")]
|
[InlineData("Location", "http://test")]
|
||||||
public async Task Response_ProvideResponse_WithHeader_SingleValue(string headerName, string headerValue)
|
public async Task Response_ProvideResponse_WithHeader_SingleValue(string headerName, string headerValue)
|
||||||
{
|
{
|
||||||
// Assign
|
// Assign
|
||||||
var requestMock = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp);
|
var requestMock = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp);
|
||||||
IResponseBuilder builder = Response.Create().WithHeader(headerName, headerValue);
|
IResponseBuilder builder = Response.Create().WithHeader(headerName, headerValue);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await builder.ProvideResponseAsync(requestMock, _settings).ConfigureAwait(false);
|
var response = await builder.ProvideResponseAsync(_mappingMock.Object, requestMock, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.Headers[headerName].ToString()).Equals(headerValue);
|
Check.That(response.Message.Headers[headerName].ToString()).Equals(headerValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("Test", new[] { "one" })]
|
[InlineData("Test", new[] { "one" })]
|
||||||
[InlineData("Test", new[] { "a", "b" })]
|
[InlineData("Test", new[] { "a", "b" })]
|
||||||
public async Task Response_ProvideResponse_WithHeader_MultipleValues(string headerName, string[] headerValues)
|
public async Task Response_ProvideResponse_WithHeader_MultipleValues(string headerName, string[] headerValues)
|
||||||
{
|
{
|
||||||
// Assign
|
// Assign
|
||||||
var requestMock = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp);
|
var requestMock = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp);
|
||||||
IResponseBuilder builder = Response.Create().WithHeader(headerName, headerValues);
|
IResponseBuilder builder = Response.Create().WithHeader(headerName, headerValues);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await builder.ProvideResponseAsync(requestMock, _settings).ConfigureAwait(false);
|
var response = await builder.ProvideResponseAsync(_mappingMock.Object, requestMock, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.Headers[headerName].ToArray()).Equals(headerValues);
|
Check.That(response.Message.Headers[headerName].ToArray()).Equals(headerValues);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_WithHeaders_SingleValue()
|
public async Task Response_ProvideResponse_WithHeaders_SingleValue()
|
||||||
{
|
{
|
||||||
// Assign
|
// Assign
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost"), "GET", ClientIp);
|
var request = new RequestMessage(new UrlDetails("http://localhost"), "GET", ClientIp);
|
||||||
var headers = new Dictionary<string, string> { { "h", "x" } };
|
var headers = new Dictionary<string, string> { { "h", "x" } };
|
||||||
var response = Response.Create().WithHeaders(headers);
|
var response = Response.Create().WithHeaders(headers);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var responseMessage = await response.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var responseMessage = await response.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(responseMessage.Message.Headers["h"]).ContainsExactly("x");
|
Check.That(responseMessage.Message.Headers["h"]).ContainsExactly("x");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_WithHeaders_MultipleValues()
|
public async Task Response_ProvideResponse_WithHeaders_MultipleValues()
|
||||||
{
|
{
|
||||||
// Assign
|
// Assign
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost"), "GET", ClientIp);
|
var request = new RequestMessage(new UrlDetails("http://localhost"), "GET", ClientIp);
|
||||||
var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } };
|
var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } };
|
||||||
var responseBuilder = Response.Create().WithHeaders(headers);
|
var responseBuilder = Response.Create().WithHeaders(headers);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.Headers["h"]).ContainsExactly("x");
|
Check.That(response.Message.Headers["h"]).ContainsExactly("x");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Response_ProvideResponse_WithHeaders_WiremockList()
|
public async Task Response_ProvideResponse_WithHeaders_WiremockList()
|
||||||
{
|
{
|
||||||
// Assign
|
// Assign
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost"), "GET", ClientIp);
|
var request = new RequestMessage(new UrlDetails("http://localhost"), "GET", ClientIp);
|
||||||
var headers = new Dictionary<string, WireMockList<string>> { { "h", new WireMockList<string>("x") } };
|
var headers = new Dictionary<string, WireMockList<string>> { { "h", new WireMockList<string>("x") } };
|
||||||
var builder = Response.Create().WithHeaders(headers);
|
var builder = Response.Create().WithHeaders(headers);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var response = await builder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
var response = await builder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Check.That(response.Message.Headers["h"]).ContainsExactly("x");
|
Check.That(response.Message.Headers["h"]).ContainsExactly("x");
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using Moq;
|
||||||
using NFluent;
|
using NFluent;
|
||||||
using WireMock.Models;
|
using WireMock.Models;
|
||||||
using WireMock.RequestBuilders;
|
using WireMock.RequestBuilders;
|
||||||
@@ -12,78 +13,81 @@ using WireMock.Types;
|
|||||||
using WireMock.Util;
|
using WireMock.Util;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithProxyTests : IDisposable
|
||||||
{
|
{
|
||||||
public class ResponseWithProxyTests : IDisposable
|
private const string ClientIp = "::1";
|
||||||
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
private readonly WireMockServer _server;
|
||||||
|
private readonly Guid _guid;
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
|
|
||||||
|
public ResponseWithProxyTests()
|
||||||
{
|
{
|
||||||
private const string ClientIp = "::1";
|
_mappingMock = new Mock<IMapping>();
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
|
||||||
private readonly WireMockServer _server;
|
|
||||||
private readonly Guid _guid;
|
|
||||||
|
|
||||||
public ResponseWithProxyTests()
|
_guid = Guid.NewGuid();
|
||||||
|
|
||||||
|
_server = WireMockServer.Start();
|
||||||
|
_server.Given(Request.Create().UsingPost().WithPath($"/{_guid}"))
|
||||||
|
.RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 42 }).WithHeader("Content-Type", "application/json"));
|
||||||
|
_server.Given(Request.Create().UsingPost().WithPath($"/{_guid}/append"))
|
||||||
|
.RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 10 }).WithHeader("Content-Type", "application/json"));
|
||||||
|
_server.Given(Request.Create().UsingPost().WithPath($"/prepend/{_guid}"))
|
||||||
|
.RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 11 }).WithHeader("Content-Type", "application/json"));
|
||||||
|
_server.Given(Request.Create().UsingPost().WithPath($"/prepend/{_guid}/append"))
|
||||||
|
.RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 12 }).WithHeader("Content-Type", "application/json"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("", "", "{\"p\":42}")]
|
||||||
|
[InlineData("", "/append", "{\"p\":10}")]
|
||||||
|
[InlineData("/prepend", "", "{\"p\":11}")]
|
||||||
|
[InlineData("/prepend", "/append", "{\"p\":12}")]
|
||||||
|
public async Task Response_WithProxy(string prepend, string append, string expectedBody)
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/xml" } } };
|
||||||
|
var request = new RequestMessage(new UrlDetails($"{_server.Urls[0]}{prepend}/{_guid}{append}"), "POST", ClientIp, new BodyData { DetectedBodyType = BodyType.Json, BodyAsJson = new { a = 1 } }, headers);
|
||||||
|
var responseBuilder = Response.Create().WithProxy(_server.Urls[0]);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Check.That(request.ProxyUrl).IsNotNull();
|
||||||
|
Check.That(response.Message.BodyData.BodyAsString).IsEqualTo(expectedBody);
|
||||||
|
Check.That(response.Message.StatusCode).IsEqualTo(201);
|
||||||
|
Check.That(response.Message.Headers["Content-Type"].ToString()).IsEqualTo("application/json");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Response_WithProxy_WebProxySettings()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var settings = new ProxyAndRecordSettings
|
||||||
{
|
{
|
||||||
_guid = Guid.NewGuid();
|
Url = "http://test.nl",
|
||||||
|
WebProxySettings = new WebProxySettings
|
||||||
_server = WireMockServer.Start();
|
|
||||||
_server.Given(Request.Create().UsingPost().WithPath($"/{_guid}"))
|
|
||||||
.RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 42 }).WithHeader("Content-Type", "application/json"));
|
|
||||||
_server.Given(Request.Create().UsingPost().WithPath($"/{_guid}/append"))
|
|
||||||
.RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 10 }).WithHeader("Content-Type", "application/json"));
|
|
||||||
_server.Given(Request.Create().UsingPost().WithPath($"/prepend/{_guid}"))
|
|
||||||
.RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 11 }).WithHeader("Content-Type", "application/json"));
|
|
||||||
_server.Given(Request.Create().UsingPost().WithPath($"/prepend/{_guid}/append"))
|
|
||||||
.RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 12 }).WithHeader("Content-Type", "application/json"));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("", "", "{\"p\":42}")]
|
|
||||||
[InlineData("", "/append", "{\"p\":10}")]
|
|
||||||
[InlineData("/prepend", "", "{\"p\":11}")]
|
|
||||||
[InlineData("/prepend", "/append", "{\"p\":12}")]
|
|
||||||
public async Task Response_WithProxy(string prepend, string append, string expectedBody)
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/xml" } } };
|
|
||||||
var request = new RequestMessage(new UrlDetails($"{_server.Urls[0]}{prepend}/{_guid}{append}"), "POST", ClientIp, new BodyData { DetectedBodyType = BodyType.Json, BodyAsJson = new { a = 1 } }, headers);
|
|
||||||
var responseBuilder = Response.Create().WithProxy(_server.Urls[0]);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Check.That(request.ProxyUrl).IsNotNull();
|
|
||||||
Check.That(response.Message.BodyData.BodyAsString).IsEqualTo(expectedBody);
|
|
||||||
Check.That(response.Message.StatusCode).IsEqualTo(201);
|
|
||||||
Check.That(response.Message.Headers["Content-Type"].ToString()).IsEqualTo("application/json");
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Response_WithProxy_WebProxySettings()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var settings = new ProxyAndRecordSettings
|
|
||||||
{
|
{
|
||||||
Url = "http://test.nl",
|
Address = "http://company",
|
||||||
WebProxySettings = new WebProxySettings
|
UserName = "x",
|
||||||
{
|
Password = "y"
|
||||||
Address = "http://company",
|
}
|
||||||
UserName = "x",
|
};
|
||||||
Password = "y"
|
var responseBuilder = Response.Create().WithProxy(settings);
|
||||||
}
|
|
||||||
};
|
|
||||||
var responseBuilder = Response.Create().WithProxy(settings);
|
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var request = new RequestMessage(new UrlDetails($"{_server.Urls[0]}/{_guid}"), "GET", ClientIp);
|
var request = new RequestMessage(new UrlDetails($"{_server.Urls[0]}/{_guid}"), "GET", ClientIp);
|
||||||
|
|
||||||
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(request, _settings)).Throws<HttpRequestException>();
|
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<HttpRequestException>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
_server?.Stop();
|
_server?.Stop();
|
||||||
_server?.Dispose();
|
_server?.Dispose();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -16,59 +16,60 @@ using Microsoft.Owin;
|
|||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithScribanTests
|
||||||
{
|
{
|
||||||
public class ResponseWithScribanTests
|
private const string ClientIp = "::1";
|
||||||
|
private readonly WireMockServerSettings _settings = new();
|
||||||
|
|
||||||
|
private readonly Mock<IMapping> _mappingMock;
|
||||||
|
|
||||||
|
public ResponseWithScribanTests()
|
||||||
{
|
{
|
||||||
private const string ClientIp = "::1";
|
_mappingMock = new Mock<IMapping>();
|
||||||
|
|
||||||
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||||
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
|
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||||
|
|
||||||
public ResponseWithScribanTests()
|
_settings.FileSystemHandler = filesystemHandlerMock.Object;
|
||||||
{
|
|
||||||
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
|
||||||
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
|
||||||
|
|
||||||
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Response_ProvideResponse_DotLiquid_WithNullBody_ShouldNotThrowException()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
|
|
||||||
var request = new RequestMessage(urlDetails, "GET", ClientIp);
|
|
||||||
|
|
||||||
var responseBuilder = Response.Create().WithTransformer(TransformerType.ScribanDotLiquid);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
response.Message.BodyData.Should().BeNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Response_ProvideResponse_DotLiquid_UrlPathVerb()
|
|
||||||
{
|
|
||||||
// Assign
|
|
||||||
var body = new BodyData
|
|
||||||
{
|
|
||||||
BodyAsString = "whatever",
|
|
||||||
DetectedBodyType = BodyType.String
|
|
||||||
};
|
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POSt", ClientIp, body);
|
|
||||||
|
|
||||||
var responseBuilder = Response.Create()
|
|
||||||
.WithBody("test {{request.Url}} {{request.Path}} {{request.Method}}")
|
|
||||||
.WithTransformer(TransformerType.Scriban);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Check.That(response.Message.BodyData.BodyAsString).Equals("test http://localhost/foo /foo POSt");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Response_ProvideResponse_DotLiquid_WithNullBody_ShouldNotThrowException()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
|
||||||
|
var request = new RequestMessage(urlDetails, "GET", ClientIp);
|
||||||
|
|
||||||
|
var responseBuilder = Response.Create().WithTransformer(TransformerType.ScribanDotLiquid);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.Message.BodyData.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Response_ProvideResponse_DotLiquid_UrlPathVerb()
|
||||||
|
{
|
||||||
|
// Assign
|
||||||
|
var body = new BodyData
|
||||||
|
{
|
||||||
|
BodyAsString = "whatever",
|
||||||
|
DetectedBodyType = BodyType.String
|
||||||
|
};
|
||||||
|
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POSt", ClientIp, body);
|
||||||
|
|
||||||
|
var responseBuilder = Response.Create()
|
||||||
|
.WithBody("test {{request.Url}} {{request.Path}} {{request.Method}}")
|
||||||
|
.WithTransformer(TransformerType.Scriban);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Check.That(response.Message.BodyData.BodyAsString).Equals("test http://localhost/foo /foo POSt");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,43 +7,42 @@ using WireMock.ResponseBuilders;
|
|||||||
using WireMock.Settings;
|
using WireMock.Settings;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace WireMock.Net.Tests.ResponseBuilders
|
namespace WireMock.Net.Tests.ResponseBuilders;
|
||||||
|
|
||||||
|
public class ResponseWithStatusCodeTests
|
||||||
{
|
{
|
||||||
public class ResponseWithStatusCodeTests
|
private readonly Mock<WireMockServerSettings> _settingsMock = new();
|
||||||
|
private const string ClientIp = "::1";
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("201", "201")]
|
||||||
|
[InlineData(201, 201)]
|
||||||
|
[InlineData(HttpStatusCode.Created, 201)]
|
||||||
|
public async Task Response_ProvideResponse_WithStatusCode(object statusCode, object expectedStatusCode)
|
||||||
{
|
{
|
||||||
private readonly Mock<WireMockServerSettings> _settingsMock = new Mock<WireMockServerSettings>();
|
// Arrange
|
||||||
private const string ClientIp = "::1";
|
var request = new RequestMessage(new UrlDetails("http://localhost/fault"), "GET", ClientIp);
|
||||||
|
|
||||||
[Theory]
|
// Act
|
||||||
[InlineData("201", "201")]
|
var responseBuilder = Response.Create();
|
||||||
[InlineData(201, 201)]
|
switch (statusCode)
|
||||||
[InlineData(HttpStatusCode.Created, 201)]
|
|
||||||
public async Task Response_ProvideResponse_WithStatusCode(object statusCode, object expectedStatusCode)
|
|
||||||
{
|
{
|
||||||
// Arrange
|
case string statusCodeAsString:
|
||||||
var request = new RequestMessage(new UrlDetails("http://localhost/fault"), "GET", ClientIp);
|
responseBuilder = responseBuilder.WithStatusCode(statusCodeAsString);
|
||||||
|
break;
|
||||||
|
|
||||||
// Act
|
case int statusCodeAInteger:
|
||||||
var responseBuilder = Response.Create();
|
responseBuilder = responseBuilder.WithStatusCode(statusCodeAInteger);
|
||||||
switch (statusCode)
|
break;
|
||||||
{
|
|
||||||
case string statusCodeAsString:
|
|
||||||
responseBuilder = responseBuilder.WithStatusCode(statusCodeAsString);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case int statusCodeAInteger:
|
case HttpStatusCode statusCodeAsEnum:
|
||||||
responseBuilder = responseBuilder.WithStatusCode(statusCodeAInteger);
|
responseBuilder = responseBuilder.WithStatusCode(statusCodeAsEnum);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case HttpStatusCode statusCodeAsEnum:
|
|
||||||
responseBuilder = responseBuilder.WithStatusCode(statusCodeAsEnum);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
var response = await responseBuilder.ProvideResponseAsync(request, _settingsMock.Object).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
response.Message.StatusCode.Should().Be(expectedStatusCode);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var response = await responseBuilder.ProvideResponseAsync(new Mock<IMapping>().Object, request, _settingsMock.Object).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.Message.StatusCode.Should().Be(expectedStatusCode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user