Use RandomDataGenerator.Net 1.0.3.0 (#231)

* Include="RandomDataGenerator.Net" Version="1.0.3"

* UndefinedBindingResult
This commit is contained in:
Stef Heyenrath
2018-11-13 09:49:46 +00:00
committed by GitHub
parent ac2ecd112f
commit 18af7a41d4
9 changed files with 220 additions and 50 deletions

View File

@@ -1,4 +1,5 @@
using System; using System;
using System.Globalization;
using System.Net; using System.Net;
using Newtonsoft.Json; using Newtonsoft.Json;
using WireMock.Logging; using WireMock.Logging;
@@ -398,7 +399,23 @@ namespace WireMock.Net.ConsoleApplication
server server
.Given(Request.Create().WithPath("/random")) .Given(Request.Create().WithPath("/random"))
.RespondWith(Response.Create() .RespondWith(Response.Create()
.WithBody("Text:{{Random Type=\"Text\" Min=8 Max=20}}\r\nDateTime:{{Random Type=\"DateTime\"}}\r\nGuid:{{Random Type=\"Guid\" Uppercase=true}}") .WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new
{
Text = "{{Random Type=\"Text\" Min=8 Max=20}}",
TextLipsum = "{{Random Type=\"TextLipsum\"}}",
TimeSpan1 = "{{Random Type=\"TimeSpan\" Format=\"c\" IncludeMilliseconds=false}}",
TimeSpan2 = "{{Random Type=\"TimeSpan\"}}",
DateTime1 = "{{Random Type=\"DateTime\"}}",
DateTime2 = DateTime.Now,
DateTime3 = DateTime.Now.ToString("s", CultureInfo.InvariantCulture),
Guid1 = "{{Random Type=\"Guid\" Uppercase=false}}",
Guid2 = "{{Random Type=\"Guid\"}}",
Integer1 = "{{Random Type=\"Integer\" Min=1000 Max=9999}}",
Integer2 = "{{#Random Type=\"Integer\" Min=10000000 Max=99999999}}{{this}}{{/Random}}",
Double1 = "{{Random Type=\"Double\" Min=10 Max=99}}",
Double2 = "{{Random Type=\"Double\" Min=100 Max=999}}"
})
.WithTransformer() .WithTransformer()
); );

View File

@@ -1,16 +1,18 @@
namespace WireMock.Transformers using HandlebarsDotNet;
namespace WireMock.Transformers
{ {
internal static class HandlebarsHelpers internal static class HandlebarsHelpers
{ {
public static void Register() public static void Register(IHandlebars handlebarsContext)
{ {
HandleBarsRegex.Register(); HandleBarsRegex.Register(handlebarsContext);
HandleBarsJsonPath.Register(); HandleBarsJsonPath.Register(handlebarsContext);
HandleBarsLinq.Register(); HandleBarsLinq.Register(handlebarsContext);
HandleBarsRandom.Register(); HandleBarsRandom.Register(handlebarsContext);
} }
} }
} }

View File

@@ -9,15 +9,15 @@ namespace WireMock.Transformers
{ {
internal static class HandleBarsJsonPath internal static class HandleBarsJsonPath
{ {
public static void Register() public static void Register(IHandlebars handlebarsContext)
{ {
Handlebars.RegisterHelper("JsonPath.SelectToken", (writer, context, arguments) => handlebarsContext.RegisterHelper("JsonPath.SelectToken", (writer, context, arguments) =>
{ {
(JObject valueToProcess, string jsonpath) = ParseArguments(arguments); (JObject valueToProcess, string jsonPath) = ParseArguments(arguments);
try try
{ {
var result = valueToProcess.SelectToken(jsonpath); var result = valueToProcess.SelectToken(jsonPath);
writer.WriteSafeString(result); writer.WriteSafeString(result);
} }
catch (JsonException) catch (JsonException)
@@ -26,13 +26,13 @@ namespace WireMock.Transformers
} }
}); });
Handlebars.RegisterHelper("JsonPath.SelectTokens", (writer, options, context, arguments) => handlebarsContext.RegisterHelper("JsonPath.SelectTokens", (writer, options, context, arguments) =>
{ {
(JObject valueToProcess, string jsonpath) = ParseArguments(arguments); (JObject valueToProcess, string jsonPath) = ParseArguments(arguments);
try try
{ {
var values = valueToProcess.SelectTokens(jsonpath); var values = valueToProcess.SelectTokens(jsonPath);
if (values != null) if (values != null)
{ {
options.Template(writer, values.ToDictionary(value => value.Path, value => value)); options.Template(writer, values.ToDictionary(value => value.Path, value => value));

View File

@@ -11,9 +11,9 @@ namespace WireMock.Transformers
{ {
internal static class HandleBarsLinq internal static class HandleBarsLinq
{ {
public static void Register() public static void Register(IHandlebars handlebarsContext)
{ {
Handlebars.RegisterHelper("Linq", (writer, context, arguments) => handlebarsContext.RegisterHelper("Linq", (writer, context, arguments) =>
{ {
(JToken valueToProcess, string linqStatement) = ParseArguments(arguments); (JToken valueToProcess, string linqStatement) = ParseArguments(arguments);
@@ -28,7 +28,7 @@ namespace WireMock.Transformers
} }
}); });
Handlebars.RegisterHelper("Linq", (writer, options, context, arguments) => handlebarsContext.RegisterHelper("Linq", (writer, options, context, arguments) =>
{ {
(JToken valueToProcess, string linqStatement) = ParseArguments(arguments); (JToken valueToProcess, string linqStatement) = ParseArguments(arguments);

View File

@@ -1,5 +1,10 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using HandlebarsDotNet; using HandlebarsDotNet;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RandomDataGenerator.FieldOptions; using RandomDataGenerator.FieldOptions;
using RandomDataGenerator.Randomizers; using RandomDataGenerator.Randomizers;
using WireMock.Validation; using WireMock.Validation;
@@ -8,24 +13,40 @@ namespace WireMock.Transformers
{ {
internal static class HandleBarsRandom internal static class HandleBarsRandom
{ {
public static void Register() public static void Register(IHandlebars handlebarsContext)
{ {
Handlebars.RegisterHelper("Random", (writer, context, arguments) => handlebarsContext.RegisterHelper("Random", (writer, context, arguments) =>
{ {
var fieldOptions = GetFieldOptionsFromArguments(arguments); object value = GetRandomValue(arguments);
writer.Write(value);
dynamic randomizer = RandomizerFactory.GetRandomizerAsDynamic(fieldOptions);
if (randomizer.GetType().GetMethod("GenerateAsString") != null)
{
string valueAsString = randomizer.GenerateAsString();
writer.WriteSafeString(valueAsString);
}
else
{
object valueAsObject = randomizer.Generate();
writer.WriteSafeString(valueAsObject);
}
}); });
handlebarsContext.RegisterHelper("Random", (writer, options, context, arguments) =>
{
object value = GetRandomValue(arguments);
options.Template(writer, value);
});
}
private static object GetRandomValue(object[] arguments)
{
var fieldOptions = GetFieldOptionsFromArguments(arguments);
dynamic randomizer = RandomizerFactory.GetRandomizerAsDynamic(fieldOptions);
// Format DateTime as ISO 8601
if (fieldOptions is IFieldOptionsDateTime)
{
DateTime? date = randomizer.Generate();
return date?.ToString("s", CultureInfo.InvariantCulture);
}
// If the IFieldOptionsGuid defines Uppercase, use the 'GenerateAsString' method.
if (fieldOptions is IFieldOptionsGuid fieldOptionsGuid)
{
return fieldOptionsGuid.Uppercase ? randomizer.GenerateAsString() : randomizer.Generate();
}
return randomizer.Generate();
} }
private static FieldOptionsAbstract GetFieldOptionsFromArguments(object[] arguments) private static FieldOptionsAbstract GetFieldOptionsFromArguments(object[] arguments)
@@ -34,11 +55,59 @@ namespace WireMock.Transformers
Check.NotNull(arguments[0], "arguments[0]"); Check.NotNull(arguments[0], "arguments[0]");
var properties = (Dictionary<string, object>)arguments[0]; var properties = (Dictionary<string, object>)arguments[0];
string type = (string)properties["Type"]; var newProperties = new Dictionary<string, object>();
properties.Remove("Type"); foreach (KeyValuePair<string, object> property in properties.Where(p => p.Key != "Type"))
{
if (property.Value.GetType().Name == "UndefinedBindingResult")
{
if (TryParseSpecialValue(property.Value, out object parsedValue))
{
newProperties.Add(property.Key, parsedValue);
}
}
else
{
newProperties.Add(property.Key, property.Value);
}
}
return FieldOptionsFactory.GetFieldOptions(type, properties); return FieldOptionsFactory.GetFieldOptions((string)properties["Type"], newProperties);
}
/// <summary>
/// In case it's an UndefinedBindingResult, just try to convert the value using Json
/// This logic adds functionality like parsing an array
/// </summary>
/// <param name="value">The property value</param>
/// <param name="parsedValue">The parsed value</param>
/// <returns>true in case parsing is ok, else false</returns>
private static bool TryParseSpecialValue(object value, out object parsedValue)
{
parsedValue = null;
string propertyValueAsString = value.ToString();
try
{
JToken jToken = JToken.Parse(propertyValueAsString);
switch (jToken)
{
case JArray jTokenArray:
parsedValue = jTokenArray.ToObject<string[]>().ToList(); // Just convert to a String List to enable Random StringList
break;
default:
return jToken.ToObject<dynamic>();
}
return true;
}
catch (JsonException)
{
// Ignore and don't add this value
}
return false;
} }
} }
} }

View File

@@ -9,9 +9,9 @@ namespace WireMock.Transformers
{ {
internal static class HandleBarsRegex internal static class HandleBarsRegex
{ {
public static void Register() public static void Register(IHandlebars handlebarsContext)
{ {
Handlebars.RegisterHelper("Regex.Match", (writer, context, arguments) => handlebarsContext.RegisterHelper("Regex.Match", (writer, context, arguments) =>
{ {
(string stringToProcess, string regexPattern, object defaultValue) = ParseArguments(arguments); (string stringToProcess, string regexPattern, object defaultValue) = ParseArguments(arguments);
@@ -27,7 +27,7 @@ namespace WireMock.Transformers
} }
}); });
Handlebars.RegisterHelper("Regex.Match", (writer, options, context, arguments) => handlebarsContext.RegisterHelper("Regex.Match", (writer, options, context, arguments) =>
{ {
(string stringToProcess, string regexPattern, object defaultValue) = ParseArguments(arguments); (string stringToProcess, string regexPattern, object defaultValue) = ParseArguments(arguments);

View File

@@ -10,9 +10,16 @@ namespace WireMock.Transformers
{ {
internal static class ResponseMessageTransformer internal static class ResponseMessageTransformer
{ {
private static readonly HandlebarsConfiguration HandlebarsConfiguration = new HandlebarsConfiguration
{
UnresolvedBindingFormatter = "{0}"
};
private static readonly IHandlebars HandlebarsContext = Handlebars.Create(HandlebarsConfiguration);
static ResponseMessageTransformer() static ResponseMessageTransformer()
{ {
HandlebarsHelpers.Register(); HandlebarsHelpers.Register(HandlebarsContext);
} }
public static ResponseMessage Transform(RequestMessage requestMessage, ResponseMessage original) public static ResponseMessage Transform(RequestMessage requestMessage, ResponseMessage original)
@@ -40,9 +47,9 @@ namespace WireMock.Transformers
var newHeaders = new Dictionary<string, WireMockList<string>>(); var newHeaders = new Dictionary<string, WireMockList<string>>();
foreach (var header in original.Headers) foreach (var header in original.Headers)
{ {
var templateHeaderKey = Handlebars.Compile(header.Key); var templateHeaderKey = HandlebarsContext.Compile(header.Key);
var templateHeaderValues = header.Value var templateHeaderValues = header.Value
.Select(Handlebars.Compile) .Select(HandlebarsContext.Compile)
.Select(func => func(template)) .Select(func => func(template))
.ToArray(); .ToArray();
@@ -109,7 +116,7 @@ namespace WireMock.Transformers
return; return;
} }
var templateForStringValue = Handlebars.Compile(stringValue); var templateForStringValue = HandlebarsContext.Compile(stringValue);
string transformedString = templateForStringValue(template); string transformedString = templateForStringValue(template);
if (!string.Equals(stringValue, transformedString)) if (!string.Equals(stringValue, transformedString))
{ {
@@ -132,7 +139,7 @@ namespace WireMock.Transformers
private static void TransformBodyAsString(object template, ResponseMessage original, ResponseMessage responseMessage) private static void TransformBodyAsString(object template, ResponseMessage original, ResponseMessage responseMessage)
{ {
var templateBody = Handlebars.Compile(original.BodyData.BodyAsString); var templateBody = HandlebarsContext.Compile(original.BodyData.BodyAsString);
responseMessage.BodyData = new BodyData responseMessage.BodyData = new BodyData
{ {

View File

@@ -53,7 +53,7 @@
<PackageReference Include="RestEase" Version="1.4.7" /> <PackageReference Include="RestEase" Version="1.4.7" />
<PackageReference Include="MimeKitLite" Version="2.0.7" /> <PackageReference Include="MimeKitLite" Version="2.0.7" />
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.9" /> <PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.9" />
<PackageReference Include="RandomDataGenerator.Net" Version="1.0.1" /> <PackageReference Include="RandomDataGenerator.Net" Version="1.0.3" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net451' "> <ItemGroup Condition=" '$(TargetFramework)' == 'net451' ">

View File

@@ -1,4 +1,7 @@
using System.Threading.Tasks; using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NFluent; using NFluent;
using WireMock.Models; using WireMock.Models;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
@@ -11,7 +14,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
private const string ClientIp = "::1"; private const string ClientIp = "::1";
[Fact] [Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Random() public async Task Response_ProvideResponseAsync_Handlebars_Random1()
{ {
// Assign // Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
@@ -21,15 +24,87 @@ namespace WireMock.Net.Tests.ResponseBuilders
{ {
Text = "{{Random Type=\"Text\" Min=8 Max=20}}", Text = "{{Random Type=\"Text\" Min=8 Max=20}}",
DateTime = "{{Random Type=\"DateTime\"}}", DateTime = "{{Random Type=\"DateTime\"}}",
Guid = "{{Random Type=\"Guid\" Uppercase=true}}" Integer = "{{Random Type=\"Integer\" Min=1000 Max=1000}}",
Long = "{{Random Type=\"Long\" Min=77777777 Max=99999999}}"
}) })
.WithTransformer(); .WithTransformer();
// Act // Act
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// assert // Assert
Check.That(responseMessage.BodyData).IsNotNull(); JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["Text"]).IsNotNull();
Check.That(j["Integer"].Value<int>()).IsEqualTo(1000);
Check.That(j["Long"].Value<int>()).IsStrictlyGreaterThan(77777777).And.IsStrictlyLessThan(99999999);
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Random1_Guid()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
var response = Response.Create()
.WithBodyAsJson(new
{
Guid1 = "{{Random Type=\"Guid\" Uppercase=false}}",
Guid2 = "{{Random Type=\"Guid\"}}"
})
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
JObject j = JObject.FromObject(responseMessage.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);
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Random1_StringList()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
var response = Response.Create()
.WithBodyAsJson(new
{
StringValue = "{{Random Type=\"StringList\" Values=[\"a\", \"b\", \"c\"]}}"
})
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
string value = j["StringValue"].Value<string>();
Check.That(new[] { "a", "b", "c" }.Contains(value)).IsTrue();
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Random2()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
var response = Response.Create()
.WithBodyAsJson(new
{
Integer = "{{#Random Type=\"Integer\" Min=10000000 Max=99999999}}{{this}}{{/Random}}",
})
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["Integer"].Value<int>()).IsStrictlyGreaterThan(10000000).And.IsStrictlyLessThan(99999999);
} }
} }
} }