ResponseMessageTransformer (#190 ; #188)

ResponseMessageTransformer (#190 ; #188)
This commit is contained in:
Stef Heyenrath
2018-08-23 12:30:36 +00:00
committed by GitHub
parent 5fff3b3a36
commit e6ecf5cc84
3 changed files with 39 additions and 12 deletions

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using HandlebarsDotNet;
using Newtonsoft.Json;
@@ -55,37 +56,41 @@ namespace WireMock.Transformers
private static void TransformBodyAsJson(object template, ResponseMessage original, ResponseMessage responseMessage)
{
JObject jobject;
JToken jToken;
switch (original.BodyAsJson)
{
case JObject bodyAsJObject:
jobject = bodyAsJObject;
jToken = bodyAsJObject;
break;
case Array bodyAsArray:
jToken = JArray.FromObject(bodyAsArray);
break;
default:
jobject = JObject.FromObject(original.BodyAsJson);
jToken = JObject.FromObject(original.BodyAsJson);
break;
}
WalkNode(jobject, template);
WalkNode(jToken, template);
responseMessage.BodyAsJson = jobject;
responseMessage.BodyAsJson = jToken;
}
private static void WalkNode(JToken node, object template)
{
if (node.Type == JTokenType.Object)
{
// In case of Object, loop all children.
foreach (JProperty child in node.Children<JProperty>())
// 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);
}
}
else if (node.Type == JTokenType.Array)
{
// In case of Array, loop all items.
foreach (JToken child in node.Children())
// 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);
}

View File

@@ -1,5 +1,4 @@
using System;
using Moq;
using Moq;
using NFluent;
using WireMock.Matchers;
using WireMock.Matchers.Request;

View File

@@ -493,5 +493,28 @@ namespace WireMock.Net.Tests.ResponseBuilderTests
// Act
Check.ThatAsyncCode(() => response.ProvideResponseAsync(request)).Throws<ArgumentNullException>();
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsArray()
{
// Assign
string jsonString = "{ \"a\": \"test 1\", \"b\": \"test 2\" }";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_array"), "POST", ClientIp, bodyData);
var response = Response.Create()
.WithBodyAsJson(new[] { "first", "{{request.path}}", "{{request.bodyAsJson.a}}", "{{request.bodyAsJson.b}}", "last" })
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
Check.That(JsonConvert.SerializeObject(responseMessage.BodyAsJson)).Equals("[\"first\",\"/foo_array\",\"test 1\",\"test 2\",\"last\"]");
}
}
}