mirror of
https://github.com/wiremock/WireMock.Net.git
synced 2026-01-15 14:53:37 +01:00
Add support for HandleBars File (to read a file) (#278)
* HandleBarsFileFragment
* 1.0.17
* {{File}}
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<VersionPrefix>1.0.16</VersionPrefix>
|
||||
<VersionPrefix>1.0.17</VersionPrefix>
|
||||
</PropertyGroup>
|
||||
|
||||
<Choose>
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
https://github.com/StefH/GitHubReleaseNotes
|
||||
|
||||
GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --version 1.0.16.0
|
||||
GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --version 1.0.17.0
|
||||
@@ -50,6 +50,12 @@ namespace WireMock.Net.ConsoleApplication
|
||||
return File.ReadAllBytes(Path.GetFileName(path) == path ? Path.Combine(GetMappingFolder(), path) : path);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.ReadResponseBodyAsFile"/>
|
||||
public string ReadResponseBodyAsString(string path)
|
||||
{
|
||||
return File.ReadAllText(Path.GetFileName(path) == path ? Path.Combine(GetMappingFolder(), path) : path);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.FileExists"/>
|
||||
public bool FileExists(string path)
|
||||
{
|
||||
|
||||
@@ -49,12 +49,19 @@ namespace WireMock.Handlers
|
||||
void WriteMappingFile([NotNull] string path, [NotNull] string text);
|
||||
|
||||
/// <summary>
|
||||
/// Read a response body file as text.
|
||||
/// Read a response body file as byte[].
|
||||
/// </summary>
|
||||
/// <param name="path">The path or filename from the file to read.</param>
|
||||
/// <returns>The file content as bytes.</returns>
|
||||
byte[] ReadResponseBodyAsFile([NotNull] string path);
|
||||
|
||||
/// <summary>
|
||||
/// Read a response body file as text.
|
||||
/// </summary>
|
||||
/// <param name="path">The path or filename from the file to read.</param>
|
||||
/// <returns>The file content as text.</returns>
|
||||
string ReadResponseBodyAsString([NotNull] string path);
|
||||
|
||||
/// <summary>
|
||||
/// Delete a file.
|
||||
/// </summary>
|
||||
|
||||
@@ -68,6 +68,16 @@ namespace WireMock.Handlers
|
||||
return File.ReadAllBytes(Path.GetFileName(path) == path ? Path.Combine(GetMappingFolder(), path) : path);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.ReadResponseBodyAsString"/>
|
||||
public string ReadResponseBodyAsString(string path)
|
||||
{
|
||||
Check.NotNullOrEmpty(path, nameof(path));
|
||||
|
||||
// In case the path is a filename, the path will be adjusted to the MappingFolder.
|
||||
// Else the path will just be as-is.
|
||||
return File.ReadAllText(Path.GetFileName(path) == path ? Path.Combine(GetMappingFolder(), path) : path);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.FileExists"/>
|
||||
public bool FileExists(string filename)
|
||||
{
|
||||
|
||||
@@ -21,7 +21,8 @@ namespace WireMock.ResponseBuilders
|
||||
/// </summary>
|
||||
public class Response : IResponseBuilder
|
||||
{
|
||||
private readonly IFileSystemHandler _fileSystemHandler = new LocalFileSystemHandler();
|
||||
private readonly IFileSystemHandler _fileSystemHandler;
|
||||
private readonly ResponseMessageTransformer _responseMessageTransformer;
|
||||
private HttpClient _httpClientForProxy;
|
||||
|
||||
/// <summary>
|
||||
@@ -93,6 +94,9 @@ namespace WireMock.ResponseBuilders
|
||||
private Response(ResponseMessage responseMessage)
|
||||
{
|
||||
ResponseMessage = responseMessage;
|
||||
|
||||
_fileSystemHandler = new LocalFileSystemHandler();
|
||||
_responseMessageTransformer = new ResponseMessageTransformer(_fileSystemHandler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -417,7 +421,7 @@ namespace WireMock.ResponseBuilders
|
||||
|
||||
if (UseTransformer)
|
||||
{
|
||||
return ResponseMessageTransformer.Transform(requestMessage, ResponseMessage);
|
||||
return _responseMessageTransformer.Transform(requestMessage, ResponseMessage);
|
||||
}
|
||||
|
||||
// Just return normal defined ResponseMessage
|
||||
|
||||
41
src/WireMock.Net/Transformers/HandleBarsFile.cs
Normal file
41
src/WireMock.Net/Transformers/HandleBarsFile.cs
Normal file
@@ -0,0 +1,41 @@
|
||||
using HandlebarsDotNet;
|
||||
using System;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Validation;
|
||||
|
||||
namespace WireMock.Transformers
|
||||
{
|
||||
internal static class HandleBarsFile
|
||||
{
|
||||
public static void Register(IHandlebars handlebarsContext, IFileSystemHandler fileSystemHandler)
|
||||
{
|
||||
handlebarsContext.RegisterHelper("File", (writer, context, arguments) =>
|
||||
{
|
||||
string value = ParseArgumentAndReadFileFragment(handlebarsContext, context, fileSystemHandler, arguments);
|
||||
writer.Write(value);
|
||||
});
|
||||
|
||||
handlebarsContext.RegisterHelper("File", (writer, options, context, arguments) =>
|
||||
{
|
||||
string value = ParseArgumentAndReadFileFragment(handlebarsContext, context, fileSystemHandler, arguments);
|
||||
options.Template(writer, value);
|
||||
});
|
||||
}
|
||||
|
||||
private static string ParseArgumentAndReadFileFragment(IHandlebars handlebarsContext, dynamic context, IFileSystemHandler fileSystemHandler, object[] arguments)
|
||||
{
|
||||
Check.Condition(arguments, args => args.Length == 1, nameof(arguments));
|
||||
Check.NotNull(arguments[0], "arguments[0]");
|
||||
|
||||
switch (arguments[0])
|
||||
{
|
||||
case string path:
|
||||
var templateFunc = handlebarsContext.Compile(path);
|
||||
string transformed = templateFunc(context);
|
||||
return fileSystemHandler.ReadResponseBodyAsString(transformed);
|
||||
}
|
||||
|
||||
throw new NotSupportedException($"The value '{arguments[0]}' with type '{arguments[0]?.GetType()}' cannot be used in Handlebars File.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
using HandlebarsDotNet;
|
||||
using WireMock.Handlers;
|
||||
|
||||
namespace WireMock.Transformers
|
||||
{
|
||||
internal static class HandlebarsHelpers
|
||||
{
|
||||
public static void Register(IHandlebars handlebarsContext)
|
||||
public static void Register(IHandlebars handlebarsContext, IFileSystemHandler fileSystemHandler)
|
||||
{
|
||||
HandleBarsRegex.Register(handlebarsContext);
|
||||
|
||||
@@ -15,6 +16,8 @@ namespace WireMock.Transformers
|
||||
HandleBarsRandom.Register(handlebarsContext);
|
||||
|
||||
HandleBarsXeger.Register(handlebarsContext);
|
||||
|
||||
HandleBarsFile.Register(handlebarsContext, fileSystemHandler);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,17 @@
|
||||
using HandlebarsDotNet;
|
||||
using JetBrains.Annotations;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Util;
|
||||
using WireMock.Validation;
|
||||
|
||||
namespace WireMock.Transformers
|
||||
{
|
||||
internal static class ResponseMessageTransformer
|
||||
internal class ResponseMessageTransformer
|
||||
{
|
||||
private static readonly HandlebarsConfiguration HandlebarsConfiguration = new HandlebarsConfiguration
|
||||
{
|
||||
@@ -17,12 +20,14 @@ namespace WireMock.Transformers
|
||||
|
||||
private static readonly IHandlebars HandlebarsContext = Handlebars.Create(HandlebarsConfiguration);
|
||||
|
||||
static ResponseMessageTransformer()
|
||||
public ResponseMessageTransformer([NotNull] IFileSystemHandler fileSystemHandler)
|
||||
{
|
||||
HandlebarsHelpers.Register(HandlebarsContext);
|
||||
Check.NotNull(fileSystemHandler, nameof(fileSystemHandler));
|
||||
|
||||
HandlebarsHelpers.Register(HandlebarsContext, fileSystemHandler);
|
||||
}
|
||||
|
||||
public static ResponseMessage Transform(RequestMessage requestMessage, ResponseMessage original)
|
||||
public ResponseMessage Transform(RequestMessage requestMessage, ResponseMessage original)
|
||||
{
|
||||
var responseMessage = new ResponseMessage { StatusCode = original.StatusCode };
|
||||
|
||||
@@ -90,14 +95,14 @@ namespace WireMock.Transformers
|
||||
};
|
||||
}
|
||||
|
||||
private static void WalkNode(JToken node, object template)
|
||||
private static void WalkNode(JToken node, object context)
|
||||
{
|
||||
if (node.Type == JTokenType.Object)
|
||||
{
|
||||
// In case of Object, loop all children. Do a ToArray() to avoid `Collection was modified` exceptions.
|
||||
foreach (JProperty child in node.Children<JProperty>().ToArray())
|
||||
{
|
||||
WalkNode(child.Value, template);
|
||||
WalkNode(child.Value, context);
|
||||
}
|
||||
}
|
||||
else if (node.Type == JTokenType.Array)
|
||||
@@ -105,7 +110,7 @@ namespace WireMock.Transformers
|
||||
// In case of Array, loop all items. Do a ToArray() to avoid `Collection was modified` exceptions.
|
||||
foreach (JToken child in node.Children().ToArray())
|
||||
{
|
||||
WalkNode(child, template);
|
||||
WalkNode(child, context);
|
||||
}
|
||||
}
|
||||
else if (node.Type == JTokenType.String)
|
||||
@@ -118,7 +123,7 @@ namespace WireMock.Transformers
|
||||
}
|
||||
|
||||
var templateForStringValue = HandlebarsContext.Compile(stringValue);
|
||||
string transformedString = templateForStringValue(template);
|
||||
string transformedString = templateForStringValue(context);
|
||||
if (!string.Equals(stringValue, transformedString))
|
||||
{
|
||||
ReplaceNodeValue(node, transformedString);
|
||||
|
||||
@@ -62,7 +62,7 @@
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.12" />
|
||||
<PackageReference Include="RandomDataGenerator.Net" Version="1.0.7" />
|
||||
<PackageReference Include="RandomDataGenerator.Net" Version="1.0.8" />
|
||||
<PackageReference Include="JmesPath.Net" Version="1.0.125" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
using Moq;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using NFluent;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Models;
|
||||
using WireMock.ResponseBuilders;
|
||||
using WireMock.Transformers;
|
||||
using Xunit;
|
||||
|
||||
namespace WireMock.Net.Tests.ResponseBuilders
|
||||
{
|
||||
public class ResponseWithHandlebarsFileTests
|
||||
{
|
||||
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
|
||||
private const string ClientIp = "::1";
|
||||
|
||||
public ResponseWithHandlebarsFileTests()
|
||||
{
|
||||
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponseAsync_Handlebars_File()
|
||||
{
|
||||
// Assign
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||
|
||||
var response = Response.Create()
|
||||
.WithBodyAsJson(new
|
||||
{
|
||||
Data = "{{File \"x.json\"}}"
|
||||
})
|
||||
.WithTransformer();
|
||||
|
||||
response.SetPrivateFieldValue("_fileSystemHandler", _filesystemHandlerMock.Object);
|
||||
response.SetPrivateFieldValue("_responseMessageTransformer", new ResponseMessageTransformer(_filesystemHandlerMock.Object));
|
||||
|
||||
// Act
|
||||
var responseMessage = await response.ProvideResponseAsync(request);
|
||||
|
||||
// Assert
|
||||
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
|
||||
Check.That(j["Data"].Value<string>()).Equals("abc");
|
||||
|
||||
// Verify
|
||||
_filesystemHandlerMock.Verify(fs => fs.ReadResponseBodyAsString("x.json"), Times.Once);
|
||||
_filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponseAsync_Handlebars_File_Replace()
|
||||
{
|
||||
// Assign
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234?id=x"), "GET", ClientIp);
|
||||
|
||||
var response = Response.Create()
|
||||
.WithBodyAsJson(new
|
||||
{
|
||||
Data = "{{File \"{{request.query.id}}.json\"}}"
|
||||
})
|
||||
.WithTransformer();
|
||||
|
||||
response.SetPrivateFieldValue("_fileSystemHandler", _filesystemHandlerMock.Object);
|
||||
response.SetPrivateFieldValue("_responseMessageTransformer", new ResponseMessageTransformer(_filesystemHandlerMock.Object));
|
||||
|
||||
// Act
|
||||
var responseMessage = await response.ProvideResponseAsync(request);
|
||||
|
||||
// Assert
|
||||
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
|
||||
Check.That(j["Data"].Value<string>()).Equals("abc");
|
||||
|
||||
// Verify
|
||||
_filesystemHandlerMock.Verify(fs => fs.ReadResponseBodyAsString("x.json"), Times.Once);
|
||||
_filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Response_ProvideResponseAsync_Handlebars_File_WithMissingArgument_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
// Assign
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||
|
||||
var response = Response.Create()
|
||||
.WithBodyAsJson(new
|
||||
{
|
||||
Data = "{{File}}"
|
||||
})
|
||||
.WithTransformer();
|
||||
|
||||
// Act
|
||||
Check.ThatAsyncCode(() => response.ProvideResponseAsync(request)).Throws<ArgumentOutOfRangeException>();
|
||||
|
||||
// Verify
|
||||
_filesystemHandlerMock.Verify(fs => fs.ReadResponseBodyAsString(It.IsAny<string>()), Times.Never);
|
||||
_filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Reflection;
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
namespace WireMock.Net.Tests
|
||||
{
|
||||
@@ -10,5 +11,53 @@ namespace WireMock.Net.Tests
|
||||
|
||||
return (T)field.GetValue(obj);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set a _private_ Field Value on a given Object
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type of the Property</typeparam>
|
||||
/// <param name="obj">Object from where the Property Value is returned</param>
|
||||
/// <param name="propertyName">Property name as string.</param>
|
||||
/// <param name="value">the value to set</param>
|
||||
public static void SetPrivateFieldValue<T>(this object obj, string propertyName, T value)
|
||||
{
|
||||
if (obj == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(obj));
|
||||
}
|
||||
|
||||
Type t = obj.GetType();
|
||||
FieldInfo fi = null;
|
||||
while (fi == null && t != null)
|
||||
{
|
||||
fi = t.GetField(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
t = t.BaseType;
|
||||
}
|
||||
|
||||
if (fi == null)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(propertyName), $"Field {propertyName} was not found in Type {obj.GetType().FullName}");
|
||||
}
|
||||
|
||||
fi.SetValue(obj, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a _private_ Property Value from a given Object.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type of the Property</typeparam>
|
||||
/// <param name="obj">Object from where the Property Value is set</param>
|
||||
/// <param name="propertyName">Property name as string.</param>
|
||||
/// <param name="value">Value to set.</param>
|
||||
public static void SetPrivatePropertyValue<T>(this object obj, string propertyName, T value)
|
||||
{
|
||||
Type t = obj.GetType();
|
||||
if (t.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) == null)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(propertyName), $"Property {propertyName} was not found in Type {obj.GetType().FullName}");
|
||||
}
|
||||
|
||||
t.InvokeMember(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance, null, obj, new object[] { value });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,8 @@
|
||||
</PackageReference>
|
||||
<PackageReference Include="System.Threading" Version="4.3.0" />
|
||||
|
||||
<PackageReference Include="RestEase" Version="1.4.7" />
|
||||
<PackageReference Include="RandomDataGenerator.Net" Version="1.0.8" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
|
||||
<PackageReference Include="MimeKitLite" Version="2.0.7" />
|
||||
<PackageReference Include="Moq" Version="4.10.1" />
|
||||
@@ -50,6 +52,7 @@
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
|
||||
</PackageReference>
|
||||
<!--<PackageReference Include="StrongNamer" Version="0.0.8" />-->
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'net452'">
|
||||
|
||||
Reference in New Issue
Block a user