Add ability to provide multiple values for headers in response (#59)

* Add ability to provide multiple values for headers

* Updated json model
This commit is contained in:
Oleksandr Liakhevych
2017-10-27 22:49:03 +03:00
committed by Stef Heyenrath
parent a96b7bca1e
commit d134684bcb
27 changed files with 305 additions and 187 deletions

View File

@@ -14,8 +14,9 @@
}, },
"Response": { "Response": {
"BodyAsJson": { "body": "static mapping" }, "BodyAsJson": { "body": "static mapping" },
"Headers": { "Headers": {
"Content-Type": "application/json" "Content-Type": "application/json",
} "Test-X": [ "test 1", "test 2" ]
}
} }
} }

View File

@@ -30,6 +30,13 @@ namespace WireMock.Net.ConsoleApplication
// server.AllowPartialMapping(); // server.AllowPartialMapping();
server
.Given(Request.Create().WithPath("/headers", "/headers_test").UsingPost().WithHeader("Content-Type", "application/json*"))
.RespondWith(Response.Create()
.WithStatusCode(201)
.WithHeader("MyHeader", "application/json", "application/json2")
.WithBody(@"{ ""result"": ""data posted with 201""}"));
server server
.Given(Request.Create().WithPath("/file").UsingGet()) .Given(Request.Create().WithPath("/file").UsingGet())
.RespondWith(Response.Create() .RespondWith(Response.Create()
@@ -92,13 +99,6 @@ namespace WireMock.Net.ConsoleApplication
.WithHeader("Content-Type", "application/json") .WithHeader("Content-Type", "application/json")
.WithBody(@"{ ""result"": ""data posted with FUNC 201""}")); .WithBody(@"{ ""result"": ""data posted with FUNC 201""}"));
server
.Given(Request.Create().WithPath("/data", "/ax").UsingPost().WithHeader("Content-Type", "application/json*"))
.RespondWith(Response.Create()
.WithStatusCode(201)
.WithHeader("Content-Type", "application/json")
.WithBody(@"{ ""result"": ""data posted with 201""}"));
server server
.Given(Request.Create().WithPath("/json").UsingPost().WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]"))) .Given(Request.Create().WithPath("/json").UsingPost().WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]")))
.RespondWith(Response.Create() .RespondWith(Response.Create()

View File

@@ -60,7 +60,7 @@ namespace WireMock.Admin.Mappings
/// <summary> /// <summary>
/// Gets or sets the headers. /// Gets or sets the headers.
/// </summary> /// </summary>
public IDictionary<string, string> Headers { get; set; } public IDictionary<string, object> Headers { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Headers (Raw). /// Gets or sets the Headers (Raw).

View File

@@ -43,7 +43,7 @@ namespace WireMock.Admin.Requests
/// <summary> /// <summary>
/// Gets or sets the Headers. /// Gets or sets the Headers.
/// </summary> /// </summary>
public IDictionary<string, string> Headers { get; set; } public IDictionary<string, WireMockList<string>> Headers { get; set; }
/// <summary> /// <summary>
/// Gets or sets the Cookies. /// Gets or sets the Cookies.

View File

@@ -1,5 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using WireMock.Admin.Mappings; using WireMock.Admin.Mappings;
using WireMock.Util;
namespace WireMock.Admin.Requests namespace WireMock.Admin.Requests
{ {
@@ -16,7 +17,7 @@ namespace WireMock.Admin.Requests
/// <summary> /// <summary>
/// Gets the headers. /// Gets the headers.
/// </summary> /// </summary>
public IDictionary<string, string> Headers { get; set; } public IDictionary<string, WireMockList<string>> Headers { get; set; }
/// <summary> /// <summary>
/// Gets or sets the body destination (SameAsSource, String or Bytes). /// Gets or sets the body destination (SameAsSource, String or Bytes).

View File

@@ -52,7 +52,7 @@ namespace WireMock.Http
{ {
foreach (var headerName in requestMessage.Headers.Keys.Where(k => k.ToUpper() != "HOST")) foreach (var headerName in requestMessage.Headers.Keys.Where(k => k.ToUpper() != "HOST"))
{ {
httpRequestMessage.Headers.TryAddWithoutValidation(headerName, new[] { requestMessage.Headers[headerName] }); httpRequestMessage.Headers.TryAddWithoutValidation(headerName, requestMessage.Headers[headerName]);
} }
} }

View File

@@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Util;
using WireMock.Validation; using WireMock.Validation;
namespace WireMock.Matchers.Request namespace WireMock.Matchers.Request
@@ -14,7 +15,7 @@ namespace WireMock.Matchers.Request
/// <summary> /// <summary>
/// The functions /// The functions
/// </summary> /// </summary>
public Func<IDictionary<string, string>, bool>[] Funcs { get; } public Func<IDictionary<string, string[]>, bool>[] Funcs { get; }
/// <summary> /// <summary>
/// The name /// The name
@@ -59,7 +60,7 @@ namespace WireMock.Matchers.Request
/// Initializes a new instance of the <see cref="RequestMessageHeaderMatcher"/> class. /// Initializes a new instance of the <see cref="RequestMessageHeaderMatcher"/> class.
/// </summary> /// </summary>
/// <param name="funcs">The funcs.</param> /// <param name="funcs">The funcs.</param>
public RequestMessageHeaderMatcher([NotNull] params Func<IDictionary<string, string>, bool>[] funcs) public RequestMessageHeaderMatcher([NotNull] params Func<IDictionary<string, string[]>, bool>[] funcs)
{ {
Check.NotNull(funcs, nameof(funcs)); Check.NotNull(funcs, nameof(funcs));
@@ -86,7 +87,7 @@ namespace WireMock.Matchers.Request
return MatchScores.Mismatch; return MatchScores.Mismatch;
if (Funcs != null) if (Funcs != null)
return MatchScores.ToScore(Funcs.Any(f => f(requestMessage.Headers))); return MatchScores.ToScore(Funcs.Any(f => f(requestMessage.Headers.ToDictionary(entry => entry.Key, entry => entry.Value.ToArray()))));
if (Matchers == null) if (Matchers == null)
return MatchScores.Mismatch; return MatchScores.Mismatch;
@@ -94,8 +95,8 @@ namespace WireMock.Matchers.Request
if (!requestMessage.Headers.ContainsKey(Name)) if (!requestMessage.Headers.ContainsKey(Name))
return MatchScores.Mismatch; return MatchScores.Mismatch;
string value = requestMessage.Headers[Name]; WireMockList<string> list = requestMessage.Headers[Name];
return Matchers.Max(m => m.IsMatch(value)); return Matchers.Max(m => list.Max(value => m.IsMatch(value))); // TODO : is this correct ?
} }
} }
} }

View File

@@ -57,13 +57,13 @@ namespace WireMock.Owin
body = bodyEncoding.GetBytes(bodyAsString); body = bodyEncoding.GetBytes(bodyAsString);
} }
Dictionary<string, string> headers = null; Dictionary<string, string[]> headers = null;
if (request.Headers.Any()) if (request.Headers.Any())
{ {
headers = new Dictionary<string, string>(); headers = new Dictionary<string, string[]>();
foreach (var header in request.Headers) foreach (var header in request.Headers)
{ {
headers.Add(header.Key, header.Value.FirstOrDefault()); headers.Add(header.Key, header.Value);
} }
} }

View File

@@ -35,9 +35,16 @@ namespace WireMock.Owin
if (responseMessage.Headers.ContainsKey(HttpKnownHeaderNames.ContentType)) if (responseMessage.Headers.ContainsKey(HttpKnownHeaderNames.ContentType))
{ {
response.ContentType = responseMessage.Headers[HttpKnownHeaderNames.ContentType]; response.ContentType = responseMessage.Headers[HttpKnownHeaderNames.ContentType].FirstOrDefault();
} }
responseMessage.Headers.Where(h => h.Key != HttpKnownHeaderNames.ContentType).ToList().ForEach(pair => response.Headers.Append(pair.Key, pair.Value));
var headers = responseMessage.Headers.Where(h => h.Key != HttpKnownHeaderNames.ContentType).ToList();
#if !NETSTANDARD
headers.ForEach(pair => response.Headers.AppendValues(pair.Key, pair.Value.ToArray()));
#else
headers.ForEach(pair => response.Headers.Append(pair.Key, pair.Value.ToArray()));
#endif
if (responseMessage.Body == null && responseMessage.BodyAsBytes == null && responseMessage.BodyAsFile == null) if (responseMessage.Body == null && responseMessage.BodyAsBytes == null && responseMessage.BodyAsFile == null)
{ {
@@ -49,7 +56,7 @@ namespace WireMock.Owin
await response.Body.WriteAsync(responseMessage.BodyAsBytes, 0, responseMessage.BodyAsBytes.Length); await response.Body.WriteAsync(responseMessage.BodyAsBytes, 0, responseMessage.BodyAsBytes.Length);
return; return;
} }
if (responseMessage.BodyAsFile != null) if (responseMessage.BodyAsFile != null)
{ {
byte[] bytes = File.ReadAllBytes(responseMessage.BodyAsFile); byte[] bytes = File.ReadAllBytes(responseMessage.BodyAsFile);

View File

@@ -4,6 +4,7 @@ using WireMock.Logging;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using System.Linq; using System.Linq;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Util;
#if !NETSTANDARD #if !NETSTANDARD
using Microsoft.Owin; using Microsoft.Owin;
#else #else
@@ -101,8 +102,8 @@ namespace WireMock.Owin
if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null) if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
{ {
bool present = request.Headers.TryGetValue("Authorization", out string authorization); bool present = request.Headers.TryGetValue("Authorization", out WireMockList<string> authorization);
if (!present || _options.AuthorizationMatcher.IsMatch(authorization) < MatchScores.Perfect) if (!present || _options.AuthorizationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfect)
{ {
response = new ResponseMessage { StatusCode = 401 }; response = new ResponseMessage { StatusCode = 401 };
return; return;

View File

@@ -33,7 +33,7 @@ namespace WireMock.RequestBuilders
/// </summary> /// </summary>
/// <param name="funcs">The headers funcs.</param> /// <param name="funcs">The headers funcs.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithHeader([NotNull] params Func<IDictionary<string, string>, bool>[] funcs); IRequestBuilder WithHeader([NotNull] params Func<IDictionary<string, string[]>, bool>[] funcs);
/// <summary> /// <summary>
/// The with cookie. /// The with cookie.

View File

@@ -395,7 +395,7 @@ namespace WireMock.RequestBuilders
/// </summary> /// </summary>
/// <param name="funcs">The funcs.</param> /// <param name="funcs">The funcs.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
public IRequestBuilder WithHeader(params Func<IDictionary<string, string>, bool>[] funcs) public IRequestBuilder WithHeader(params Func<IDictionary<string, string[]>, bool>[] funcs)
{ {
Check.NotEmpty(funcs, nameof(funcs)); Check.NotEmpty(funcs, nameof(funcs));

View File

@@ -41,7 +41,7 @@ namespace WireMock
/// <summary> /// <summary>
/// Gets the headers. /// Gets the headers.
/// </summary> /// </summary>
public IDictionary<string, string> Headers { get; } public IDictionary<string, WireMockList<string>> Headers { get; }
/// <summary> /// <summary>
/// Gets the cookies. /// Gets the cookies.
@@ -79,7 +79,7 @@ namespace WireMock
/// <param name="bodyEncoding">The body encoding</param> /// <param name="bodyEncoding">The body encoding</param>
/// <param name="headers">The headers.</param> /// <param name="headers">The headers.</param>
/// <param name="cookies">The cookies.</param> /// <param name="cookies">The cookies.</param>
public RequestMessage([NotNull] Uri url, [NotNull] string method, [NotNull] string clientIP, [CanBeNull] byte[] bodyAsBytes = null, [CanBeNull] string body = null, [CanBeNull] Encoding bodyEncoding = null, [CanBeNull] IDictionary<string, string> headers = null, [CanBeNull] IDictionary<string, string> cookies = null) public RequestMessage([NotNull] Uri url, [NotNull] string method, [NotNull] string clientIP, [CanBeNull] byte[] bodyAsBytes = null, [CanBeNull] string body = null, [CanBeNull] Encoding bodyEncoding = null, [CanBeNull] IDictionary<string, string[]> headers = null, [CanBeNull] IDictionary<string, string> cookies = null)
{ {
Check.NotNull(url, nameof(url)); Check.NotNull(url, nameof(url));
Check.NotNull(method, nameof(method)); Check.NotNull(method, nameof(method));
@@ -92,7 +92,7 @@ namespace WireMock
BodyAsBytes = bodyAsBytes; BodyAsBytes = bodyAsBytes;
Body = body; Body = body;
BodyEncoding = bodyEncoding; BodyEncoding = bodyEncoding;
Headers = headers; Headers = headers?.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value));
Cookies = cookies; Cookies = cookies;
Query = ParseQuery(url.Query); Query = ParseQuery(url.Query);
} }

View File

@@ -1,5 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Util;
namespace WireMock.ResponseBuilders namespace WireMock.ResponseBuilders
{ {
@@ -12,15 +13,29 @@ namespace WireMock.ResponseBuilders
/// The with header. /// The with header.
/// </summary> /// </summary>
/// <param name="name">The name.</param> /// <param name="name">The name.</param>
/// <param name="value">The value.</param> /// <param name="values">The values.</param>
/// <returns>The <see cref="IResponseBuilder"/>.</returns> /// <returns>The <see cref="IResponseBuilder"/>.</returns>
IResponseBuilder WithHeader([NotNull] string name, string value); IResponseBuilder WithHeader([NotNull] string name, params string[] values);
/// <summary> /// <summary>
/// The with headers. /// The with headers.
/// </summary> /// </summary>
/// <param name="headers">The headers.</param> /// <param name="headers">The headers.</param>
/// <returns>The <see cref="IResponseBuilder"/>.</returns> /// <returns>The <see cref="IResponseBuilder"/>.</returns>
IResponseBuilder WithHeaders([NotNull] IDictionary<string,string> headers); IResponseBuilder WithHeaders([NotNull] IDictionary<string, string> headers);
/// <summary>
/// The with headers.
/// </summary>
/// <param name="headers">The headers.</param>
/// <returns>The <see cref="IResponseBuilder"/>.</returns>
IResponseBuilder WithHeaders([NotNull] IDictionary<string, string[]> headers);
/// <summary>
/// The with headers.
/// </summary>
/// <param name="headers">The headers.</param>
/// <returns>The <see cref="IResponseBuilder"/>.</returns>
IResponseBuilder WithHeaders([NotNull] IDictionary<string, WireMockList<string>> headers);
} }
} }

View File

@@ -1,14 +1,16 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Net; using System.Net;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
using Newtonsoft.Json; using Newtonsoft.Json;
using WireMock.Validation;
using WireMock.Http; using WireMock.Http;
using WireMock.Transformers; using WireMock.Transformers;
using WireMock.Util;
using WireMock.Validation;
namespace WireMock.ResponseBuilders namespace WireMock.ResponseBuilders
{ {
@@ -126,22 +128,35 @@ namespace WireMock.ResponseBuilders
return WithStatusCode((int)HttpStatusCode.NotFound); return WithStatusCode((int)HttpStatusCode.NotFound);
} }
/// <summary> /// <inheritdoc cref="IHeadersResponseBuilder.WithHeader(string, string[])"/>
/// The with header. public IResponseBuilder WithHeader(string name, params string[] values)
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns>The <see cref="IResponseBuilder"/>.</returns>
public IResponseBuilder WithHeader(string name, string value)
{ {
Check.NotNull(name, nameof(name)); Check.NotNull(name, nameof(name));
ResponseMessage.AddHeader(name, value); ResponseMessage.AddHeader(name, values);
return this; return this;
} }
/// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders"/> /// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string})"/>
public IResponseBuilder WithHeaders(IDictionary<string, string> headers) public IResponseBuilder WithHeaders(IDictionary<string, string> headers)
{
Check.NotNull(headers, nameof(headers));
ResponseMessage.Headers = headers.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value));
return this;
}
/// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string[]})"/>
public IResponseBuilder WithHeaders(IDictionary<string, string[]> headers)
{
Check.NotNull(headers, nameof(headers));
ResponseMessage.Headers = headers.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value));
return this;
}
/// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, WireMockList{string}})"/>
public IResponseBuilder WithHeaders(IDictionary<string, WireMockList<string>> headers)
{ {
ResponseMessage.Headers = headers; ResponseMessage.Headers = headers;
return this; return this;

View File

@@ -1,6 +1,9 @@
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
using WireMock.Util;
using WireMock.Validation;
namespace WireMock namespace WireMock
{ {
@@ -12,7 +15,7 @@ namespace WireMock
/// <summary> /// <summary>
/// Gets the headers. /// Gets the headers.
/// </summary> /// </summary>
public IDictionary<string, string> Headers { get; set; } = new ConcurrentDictionary<string, string>(); public IDictionary<string, WireMockList<string>> Headers { get; set; } = new ConcurrentDictionary<string, WireMockList<string>>();
/// <summary> /// <summary>
/// Gets or sets the status code. /// Gets or sets the status code.
@@ -55,17 +58,29 @@ namespace WireMock
public Encoding BodyEncoding { get; set; } = new UTF8Encoding(false); public Encoding BodyEncoding { get; set; } = new UTF8Encoding(false);
/// <summary> /// <summary>
/// The add header. /// Adds the header.
/// </summary> /// </summary>
/// <param name="name"> /// <param name="name">The name.</param>
/// The name. /// <param name="value">The value.</param>
/// </param>
/// <param name="value">
/// The value.
/// </param>
public void AddHeader(string name, string value) public void AddHeader(string name, string value)
{ {
Headers.Add(name, value); Headers.Add(name, new WireMockList<string>(value));
}
/// <summary>
/// Adds the header.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="values">The values.</param>
public void AddHeader(string name, params string[] values)
{
Check.NotEmpty(values, nameof(values));
var newHeaderValues = Headers.TryGetValue(name, out WireMockList<string> existingValues)
? values.Union(existingValues).ToArray()
: values;
Headers[name] = new WireMockList<string>(newHeaderValues);
} }
} }
} }

View File

@@ -8,6 +8,7 @@ using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Util;
namespace WireMock.Serialization namespace WireMock.Serialization
{ {
@@ -108,7 +109,7 @@ namespace WireMock.Serialization
{ {
mappingModel.Response.BodyDestination = response.ResponseMessage.BodyDestination; mappingModel.Response.BodyDestination = response.ResponseMessage.BodyDestination;
mappingModel.Response.StatusCode = response.ResponseMessage.StatusCode; mappingModel.Response.StatusCode = response.ResponseMessage.StatusCode;
mappingModel.Response.Headers = response.ResponseMessage.Headers; mappingModel.Response.Headers = Map(response.ResponseMessage.Headers);
mappingModel.Response.Body = response.ResponseMessage.Body; mappingModel.Response.Body = response.ResponseMessage.Body;
mappingModel.Response.BodyAsBytes = response.ResponseMessage.BodyAsBytes; mappingModel.Response.BodyAsBytes = response.ResponseMessage.BodyAsBytes;
mappingModel.Response.BodyAsFile = response.ResponseMessage.BodyAsFile; mappingModel.Response.BodyAsFile = response.ResponseMessage.BodyAsFile;
@@ -127,7 +128,24 @@ namespace WireMock.Serialization
return mappingModel; return mappingModel;
} }
public static MatcherModel[] Map([CanBeNull] IEnumerable<IMatcher> matchers) private static IDictionary<string, object> Map(IDictionary<string, WireMockList<string>> dictionary)
{
if (dictionary == null)
{
return null;
}
var newDictionary = new Dictionary<string, object>();
foreach (var entry in dictionary)
{
object value = entry.Value.Count == 1 ? (object)entry.Value.ToString() : entry.Value;
newDictionary.Add(entry.Key, value);
}
return newDictionary;
}
private static MatcherModel[] Map([CanBeNull] IEnumerable<IMatcher> matchers)
{ {
if (matchers == null || !matchers.Any()) if (matchers == null || !matchers.Any())
return null; return null;
@@ -135,7 +153,7 @@ namespace WireMock.Serialization
return matchers.Select(Map).Where(x => x != null).ToArray(); return matchers.Select(Map).Where(x => x != null).ToArray();
} }
public static MatcherModel Map([CanBeNull] IMatcher matcher) private static MatcherModel Map([CanBeNull] IMatcher matcher)
{ {
if (matcher == null) if (matcher == null)
return null; return null;
@@ -150,7 +168,7 @@ namespace WireMock.Serialization
}; };
} }
public static string[] Map<T>([CanBeNull] IEnumerable<Func<T, bool>> funcs) private static string[] Map<T>([CanBeNull] IEnumerable<Func<T, bool>> funcs)
{ {
if (funcs == null || !funcs.Any()) if (funcs == null || !funcs.Any())
return null; return null;
@@ -158,7 +176,7 @@ namespace WireMock.Serialization
return funcs.Select(Map).Where(x => x != null).ToArray(); return funcs.Select(Map).Where(x => x != null).ToArray();
} }
public static string Map<T>([CanBeNull] Func<T, bool> func) private static string Map<T>([CanBeNull] Func<T, bool> func)
{ {
return func?.ToString(); return func?.ToString();
} }

View File

@@ -3,22 +3,22 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
using Newtonsoft.Json; using Newtonsoft.Json;
using WireMock.Admin.Mappings; using WireMock.Admin.Mappings;
using WireMock.Admin.Requests; using WireMock.Admin.Requests;
using WireMock.Admin.Settings; using WireMock.Admin.Settings;
using WireMock.Http;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Serialization;
using WireMock.Settings;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation; using WireMock.Validation;
using WireMock.Http;
using System.Threading.Tasks;
using WireMock.Settings;
using WireMock.Serialization;
namespace WireMock.Server namespace WireMock.Server
{ {
@@ -519,12 +519,15 @@ namespace WireMock.Server
{ {
string path = requestModel.Path as string; string path = requestModel.Path as string;
if (path != null) if (path != null)
{
requestBuilder = requestBuilder.WithPath(path); requestBuilder = requestBuilder.WithPath(path);
}
else else
{ {
var pathModel = JsonUtils.ParseJTokenToObject<PathModel>(requestModel.Path); var pathModel = JsonUtils.ParseJTokenToObject<PathModel>(requestModel.Path);
if (pathModel?.Matchers != null) if (pathModel?.Matchers != null)
requestBuilder = requestBuilder.WithPath(pathModel.Matchers.Select(MappingConverter.Map).ToArray()); requestBuilder =
requestBuilder.WithPath(pathModel.Matchers.Select(MappingConverter.Map).ToArray());
} }
} }
@@ -532,17 +535,22 @@ namespace WireMock.Server
{ {
string url = requestModel.Url as string; string url = requestModel.Url as string;
if (url != null) if (url != null)
{
requestBuilder = requestBuilder.WithUrl(url); requestBuilder = requestBuilder.WithUrl(url);
}
else else
{ {
var urlModel = JsonUtils.ParseJTokenToObject<UrlModel>(requestModel.Url); var urlModel = JsonUtils.ParseJTokenToObject<UrlModel>(requestModel.Url);
if (urlModel?.Matchers != null) if (urlModel?.Matchers != null)
requestBuilder = requestBuilder.WithUrl(urlModel.Matchers.Select(MappingConverter.Map).ToArray()); requestBuilder =
requestBuilder.WithUrl(urlModel.Matchers.Select(MappingConverter.Map).ToArray());
} }
} }
if (requestModel.Methods != null) if (requestModel.Methods != null)
{
requestBuilder = requestBuilder.UsingVerb(requestModel.Methods); requestBuilder = requestBuilder.UsingVerb(requestModel.Methods);
}
if (requestModel.Headers != null) if (requestModel.Headers != null)
{ {
@@ -603,7 +611,12 @@ namespace WireMock.Server
if (responseModel.Headers != null) if (responseModel.Headers != null)
{ {
responseBuilder = responseBuilder.WithHeaders(responseModel.Headers); foreach (var entry in responseModel.Headers)
{
responseBuilder = entry.Value is string value ?
responseBuilder.WithHeader(entry.Key, value) :
responseBuilder.WithHeader(entry.Key, JsonUtils.ParseJTokenToObject<string[]>(entry.Value));
}
} }
else if (responseModel.HeadersRaw != null) else if (responseModel.HeadersRaw != null)
{ {
@@ -647,7 +660,7 @@ namespace WireMock.Server
{ {
Body = JsonConvert.SerializeObject(result, _settings), Body = JsonConvert.SerializeObject(result, _settings),
StatusCode = 200, StatusCode = 200,
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } Headers = new Dictionary<string, WireMockList<string>> { { "Content-Type", new WireMockList<string>("application/json") } }
}; };
} }

View File

@@ -1,5 +1,7 @@
using HandlebarsDotNet; using System.Collections.Generic;
using System.Collections.Generic; using System.Linq;
using HandlebarsDotNet;
using WireMock.Util;
namespace WireMock.Transformers namespace WireMock.Transformers
{ {
@@ -16,13 +18,16 @@ namespace WireMock.Transformers
responseMessage.Body = templateBody(template); responseMessage.Body = templateBody(template);
// Headers // Headers
var newHeaders = new Dictionary<string, 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 = Handlebars.Compile(header.Key);
var templateHeaderValue = Handlebars.Compile(header.Value); var templateHeaderValues = header.Value
.Select(Handlebars.Compile)
.Select(func => func(template))
.ToArray();
newHeaders.Add(templateHeaderKey(template), templateHeaderValue(template)); newHeaders.Add(templateHeaderKey(template), new WireMockList<string>(templateHeaderValues));
} }
responseMessage.Headers = newHeaders; responseMessage.Headers = newHeaders;

View File

@@ -7,13 +7,12 @@ namespace WireMock.Util
public static T ParseJTokenToObject<T>(object value) public static T ParseJTokenToObject<T>(object value)
{ {
if (value == null) if (value == null)
{
return default(T); return default(T);
}
JToken token = value as JToken; var token = value as JToken;
if (token == null) return token == null ? default(T) : token.ToObject<T>();
return default(T);
return token.ToObject<T>();
} }
} }
} }

View File

@@ -36,9 +36,6 @@ namespace WireMock.Util
/// <summary> /// <summary>
/// Returns a <see cref="string" /> that represents this instance. /// Returns a <see cref="string" /> that represents this instance.
/// </summary> /// </summary>
/// <returns>
/// A <see cref="string" /> that represents this instance.
/// </returns>
public override string ToString() public override string ToString()
{ {
if (this != null && this.Any()) if (this != null && this.Any())

View File

@@ -8,13 +8,13 @@ namespace WireMock.Net.Tests
//[TestFixture] //[TestFixture]
public class RequestMessageTests public class RequestMessageTests
{ {
private const string clientIP = "::1"; private const string ClientIp = "::1";
[Fact] [Fact]
public void Should_handle_empty_query() public void Should_handle_empty_query()
{ {
// given // given
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp);
// then // then
Check.That(request.GetParameter("not_there")).IsNull(); Check.That(request.GetParameter("not_there")).IsNull();
@@ -26,7 +26,7 @@ namespace WireMock.Net.Tests
// given // given
string bodyAsString = "whatever"; string bodyAsString = "whatever";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost?foo=bar&multi=1&multi=2"), "POST", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost?foo=bar&multi=1&multi=2"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
// then // then
Check.That(request.GetParameter("foo")).Contains("bar"); Check.That(request.GetParameter("foo")).Contains("bar");

View File

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

View File

@@ -12,7 +12,7 @@ namespace WireMock.Net.Tests
//[TestFixture] //[TestFixture]
public partial class RequestTests public partial class RequestTests
{ {
private const string clientIP = "::1"; private const string ClientIp = "::1";
[Fact] [Fact]
public void Should_specify_requests_matching_given_path() public void Should_specify_requests_matching_given_path()
@@ -21,7 +21,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithPath("/foo"); var spec = Request.Create().WithPath("/foo");
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo"), "blabla", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo"), "blabla", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -33,8 +33,8 @@ namespace WireMock.Net.Tests
{ {
var requestBuilder = Request.Create().WithPath("/x1", "/x2"); var requestBuilder = Request.Create().WithPath("/x1", "/x2");
var request1 = new RequestMessage(new Uri("http://localhost/x1"), "blabla", clientIP); var request1 = new RequestMessage(new Uri("http://localhost/x1"), "blabla", ClientIp);
var request2 = new RequestMessage(new Uri("http://localhost/x2"), "blabla", clientIP); var request2 = new RequestMessage(new Uri("http://localhost/x2"), "blabla", ClientIp);
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request1, requestMatchResult)).IsEqualTo(1.0); Check.That(requestBuilder.GetMatchingScore(request1, requestMatchResult)).IsEqualTo(1.0);
@@ -48,7 +48,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithPath(url => url.EndsWith("/foo")); var spec = Request.Create().WithPath(url => url.EndsWith("/foo"));
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo"), "blabla", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo"), "blabla", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -62,7 +62,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithPath(new RegexMatcher("^/foo")); var spec = Request.Create().WithPath(new RegexMatcher("^/foo"));
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo/bar"), "blabla", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo/bar"), "blabla", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -76,7 +76,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithPath("/foo"); var spec = Request.Create().WithPath("/foo");
// when // when
var request = new RequestMessage(new Uri("http://localhost/bar"), "blabla", clientIP); var request = new RequestMessage(new Uri("http://localhost/bar"), "blabla", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -90,7 +90,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithUrl("*/foo"); var spec = Request.Create().WithUrl("*/foo");
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo"), "blabla", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo"), "blabla", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -104,7 +104,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithPath("/foo").UsingPut(); var spec = Request.Create().WithPath("/foo").UsingPut();
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -118,7 +118,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithPath("/foo").UsingPost(); var spec = Request.Create().WithPath("/foo").UsingPost();
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -132,7 +132,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithPath("/foo").UsingGet(); var spec = Request.Create().WithPath("/foo").UsingGet();
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo"), "GET", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo"), "GET", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -148,7 +148,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "whatever"; string bodyAsString = "whatever";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "Delete", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "Delete", ClientIp, body, bodyAsString, Encoding.UTF8);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -162,7 +162,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithPath("/foo").UsingHead(); var spec = Request.Create().WithPath("/foo").UsingHead();
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo"), "HEAD", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo"), "HEAD", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -176,7 +176,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithPath("/foo").UsingPut(); var spec = Request.Create().WithPath("/foo").UsingPut();
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo"), "HEAD", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo"), "HEAD", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -190,7 +190,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithPath("/bar").UsingPut(); var spec = Request.Create().WithPath("/bar").UsingPut();
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -206,7 +206,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "whatever"; string bodyAsString = "whatever";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string> { { "X-toto", "tata" } }); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string[]> { { "X-toto", new [] { "tata" } } });
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -222,7 +222,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "whatever"; string bodyAsString = "whatever";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string> { { "X-toto", "tata" } }); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string[]> { { "X-toto", new[] { "tata" } } });
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -238,7 +238,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "whatever"; string bodyAsString = "whatever";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string> { { "X-toto", "ABC" } }); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string[]> { { "X-toto", new[] { "ABC" } } });
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -254,7 +254,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "whatever"; string bodyAsString = "whatever";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string> { { "X-toto", "TaTa" } }); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string[]> { { "X-toto", new[] { "TaTa" } } });
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -268,7 +268,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().UsingAnyVerb().WithCookie("session", "a*"); var spec = Request.Create().UsingAnyVerb().WithCookie("session", "a*");
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, null, null, null, null, new Dictionary<string, string> { { "session", "abc" } }); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, null, null, null, null, new Dictionary<string, string> { { "session", "abc" } });
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -284,7 +284,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "Hello world!"; string bodyAsString = "Hello world!";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, bodyAsString, Encoding.UTF8);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -300,7 +300,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "cat"; string bodyAsString = "cat";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -316,7 +316,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "cat"; string bodyAsString = "cat";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -332,7 +332,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "caR"; string bodyAsString = "caR";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -348,7 +348,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "The car drives in the street."; string bodyAsString = "The car drives in the street.";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -364,7 +364,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "Hello"; string bodyAsString = "Hello";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -380,7 +380,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "Hello world!"; string bodyAsString = "Hello world!";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string> { { "X-toto", "tatata" } }); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string[]> { { "X-toto", new[] { "tatata" } } });
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -396,7 +396,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "Hello world!"; string bodyAsString = "Hello world!";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, bodyAsString, Encoding.UTF8);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -417,7 +417,7 @@ namespace WireMock.Net.Tests
<todo-item id='a3'>xyz</todo-item> <todo-item id='a3'>xyz</todo-item>
</todo-list>"; </todo-list>";
byte[] body = Encoding.UTF8.GetBytes(xmlBodyAsString); byte[] body = Encoding.UTF8.GetBytes(xmlBodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, body, xmlBodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, xmlBodyAsString, Encoding.UTF8);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -438,7 +438,7 @@ namespace WireMock.Net.Tests
<todo-item id='a3'>xyz</todo-item> <todo-item id='a3'>xyz</todo-item>
</todo-list>"; </todo-list>";
byte[] body = Encoding.UTF8.GetBytes(xmlBodyAsString); byte[] body = Encoding.UTF8.GetBytes(xmlBodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, body, xmlBodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, xmlBodyAsString, Encoding.UTF8);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -454,7 +454,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }"; string bodyAsString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, bodyAsString, Encoding.UTF8);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -470,7 +470,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "{ \"things\": { \"name\": \"Wiremock\" } }"; string bodyAsString = "{ \"things\": { \"name\": \"Wiremock\" } }";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, bodyAsString, Encoding.UTF8);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -486,7 +486,7 @@ namespace WireMock.Net.Tests
// when // when
string bodyAsString = "xxx"; string bodyAsString = "xxx";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", clientIP, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string> { { "X-toto", "tatata" } }); var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string[]> { { "X-toto", new[] { "tata" } } });
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -500,7 +500,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithParam("bar", "1", "2"); var spec = Request.Create().WithParam("bar", "1", "2");
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo?bar=1&bar=2"), "PUT", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo?bar=1&bar=2"), "PUT", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -514,7 +514,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithParam("bar"); var spec = Request.Create().WithParam("bar");
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo?bar"), "PUT", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo?bar"), "PUT", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -528,7 +528,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().UsingAnyVerb().WithParam(p => p.ContainsKey("bar")); var spec = Request.Create().UsingAnyVerb().WithParam(p => p.ContainsKey("bar"));
// when // when
var request = new RequestMessage(new Uri("http://localhost/foo?bar=1&bar=2"), "PUT", clientIP); var request = new RequestMessage(new Uri("http://localhost/foo?bar=1&bar=2"), "PUT", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();
@@ -542,7 +542,7 @@ namespace WireMock.Net.Tests
var spec = Request.Create().WithParam("bar", "1"); var spec = Request.Create().WithParam("bar", "1");
// when // when
var request = new RequestMessage(new Uri("http://localhost/test=7"), "PUT", clientIP); var request = new RequestMessage(new Uri("http://localhost/test=7"), "PUT", ClientIp);
// then // then
var requestMatchResult = new RequestMatchResult(); var requestMatchResult = new RequestMatchResult();

View File

@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using NFluent;
using WireMock.ResponseBuilders;
using Xunit;
namespace WireMock.Net.Tests
{
public partial class ResponseTests
{
[Fact]
public async Task Response_ProvideResponse_Handlebars_UrlPathVerb()
{
// given
string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
var response = Response.Create()
.WithBody("test {{request.url}} {{request.path}} {{request.method}}")
.WithTransformer();
// act
var responseMessage = await response.ProvideResponseAsync(request);
// then
Check.That(responseMessage.Body).Equals("test http://localhost/foo /foo post");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_Query()
{
// given
string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo?a=1&a=2&b=5"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
var response = Response.Create()
.WithBody("test keya={{request.query.a}} idx={{request.query.a.[0]}} idx={{request.query.a.[1]}} keyb={{request.query.b}}")
.WithTransformer();
// act
var responseMessage = await response.ProvideResponseAsync(request);
// then
Check.That(responseMessage.Body).Equals("test keya=1 idx=1 idx=2 keyb=5");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_Header()
{
// given
string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } });
var response = Response.Create().WithHeader("x", "{{request.headers.Content-Type}}").WithBody("test").WithTransformer();
// act
var responseMessage = await response.ProvideResponseAsync(request);
// then
Check.That(responseMessage.Body).Equals("test");
Check.That(responseMessage.Headers).ContainsKey("x");
Check.That(responseMessage.Headers["x"]).ContainsExactly("text/plain");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_Headers()
{
// given
string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } });
var response = Response.Create().WithHeader("x", "{{request.headers.Content-Type}}", "{{request.url}}").WithBody("test").WithTransformer();
// act
var responseMessage = await response.ProvideResponseAsync(request);
// then
Check.That(responseMessage.Body).Equals("test");
Check.That(responseMessage.Headers).ContainsKey("x");
Check.That(responseMessage.Headers["x"]).Contains("text/plain");
Check.That(responseMessage.Headers["x"]).Contains("http://localhost/foo");
}
}
}

View File

@@ -1,73 +1,15 @@
using System; using System;
using System.Collections.Generic;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using NFluent; using NFluent;
using Xunit;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using Xunit;
namespace WireMock.Net.Tests namespace WireMock.Net.Tests
{ {
//[TestFixture] public partial class ResponseTests
public class ResponseTests
{ {
private const string clientIP = "::1"; private const string ClientIp = "::1";
[Fact]
public async Task Response_ProvideResponse_Handlebars_UrlPathVerb()
{
// given
string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP, body, bodyAsString, Encoding.UTF8);
var response = Response.Create()
.WithBody("test {{request.url}} {{request.path}} {{request.method}}")
.WithTransformer();
// act
var responseMessage = await response.ProvideResponseAsync(request);
// then
Check.That(responseMessage.Body).Equals("test http://localhost/foo /foo post");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_Query()
{
// given
string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo?a=1&a=2&b=5"), "POST", clientIP, body, bodyAsString, Encoding.UTF8);
var response = Response.Create()
.WithBody("test keya={{request.query.a}} idx={{request.query.a.[0]}} idx={{request.query.a.[1]}} keyb={{request.query.b}}")
.WithTransformer();
// act
var responseMessage = await response.ProvideResponseAsync(request);
// then
Check.That(responseMessage.Body).Equals("test keya=1 idx=1 idx=2 keyb=5");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_Headers()
{
// given
string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP, body, bodyAsString, Encoding.UTF8, new Dictionary<string, string> { { "Content-Type", "text/plain" } });
var response = Response.Create().WithHeader("x", "{{request.headers.Content-Type}}").WithBody("test").WithTransformer();
// act
var responseMessage = await response.ProvideResponseAsync(request);
// then
Check.That(responseMessage.Body).Equals("test");
Check.That(responseMessage.Headers).Contains(new KeyValuePair<string, string>("x", "text/plain"));
}
[Fact] [Fact]
public async Task Response_ProvideResponse_WithBody_Bytes_Encoding_Destination_String() public async Task Response_ProvideResponse_WithBody_Bytes_Encoding_Destination_String()
@@ -75,7 +17,7 @@ namespace WireMock.Net.Tests
// given // given
string bodyAsString = "abc"; string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
var response = Response.Create().WithBody(new byte[] { 48, 49 }, BodyDestinationFormat.String, Encoding.ASCII); var response = Response.Create().WithBody(new byte[] { 48, 49 }, BodyDestinationFormat.String, Encoding.ASCII);
@@ -94,7 +36,7 @@ namespace WireMock.Net.Tests
// given // given
string bodyAsString = "abc"; string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
var response = Response.Create().WithBody(new byte[] { 48, 49 }, BodyDestinationFormat.SameAsSource, Encoding.ASCII); var response = Response.Create().WithBody(new byte[] { 48, 49 }, BodyDestinationFormat.SameAsSource, Encoding.ASCII);
@@ -113,7 +55,7 @@ namespace WireMock.Net.Tests
// given // given
string bodyAsString = "abc"; string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
var response = Response.Create().WithBody("test", null, Encoding.ASCII); var response = Response.Create().WithBody("test", null, Encoding.ASCII);
@@ -131,7 +73,7 @@ namespace WireMock.Net.Tests
// given // given
string bodyAsString = "abc"; string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString); byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", clientIP, body, bodyAsString, Encoding.UTF8); var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
var response = Response.Create().WithBodyAsJson(new { value = "test" }, Encoding.ASCII); var response = Response.Create().WithBodyAsJson(new { value = "test" }, Encoding.ASCII);

View File

@@ -7,7 +7,6 @@ using WireMock.RequestBuilders;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Server; using WireMock.Server;
using Xunit; using Xunit;
using Xunit.Abstractions;
namespace WireMock.Net.Tests namespace WireMock.Net.Tests
{ {