Merge branch 'stef_increase_code_coverage'

This commit is contained in:
Stef Heyenrath
2018-03-15 22:14:52 +01:00
35 changed files with 1476 additions and 640 deletions
+3
View File
@@ -0,0 +1,3 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=IP/@EntryIndexedValue">IP</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SSL/@EntryIndexedValue">SSL</s:String></wpf:ResourceDictionary>
@@ -8,33 +8,21 @@
/// <summary> /// <summary>
/// Gets or sets the name. /// Gets or sets the name.
/// </summary> /// </summary>
/// <value>
/// The name.
/// </value>
public string Name { get; set; } public string Name { get; set; }
/// <summary> /// <summary>
/// Gets or sets the pattern. /// Gets or sets the pattern.
/// </summary> /// </summary>
/// <value>
/// The pattern.
/// </value>
public string Pattern { get; set; } public string Pattern { get; set; }
/// <summary> /// <summary>
/// Gets or sets the patterns. /// Gets or sets the patterns.
/// </summary> /// </summary>
/// <value>
/// The patterns.
/// </value>
public string[] Patterns { get; set; } public string[] Patterns { get; set; }
/// <summary> /// <summary>
/// Gets or sets the ignore case. /// Gets or sets the ignore case.
/// </summary> /// </summary>
/// <value>
/// The ignore case.
/// </value>
public bool? IgnoreCase { get; set; } public bool? IgnoreCase { get; set; }
} }
} }
+6 -7
View File
@@ -71,13 +71,6 @@ namespace WireMock.Http
var httpRequestMessage = new HttpRequestMessage(new HttpMethod(requestMessage.Method), url); var httpRequestMessage = new HttpRequestMessage(new HttpMethod(requestMessage.Method), url);
WireMockList<string> contentTypeHeader = null;
bool contentTypeHeaderPresent = requestMessage.Headers.Any(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase));
if (contentTypeHeaderPresent)
{
contentTypeHeader = requestMessage.Headers[HttpKnownHeaderNames.ContentType];
}
// Set Body if present // Set Body if present
if (requestMessage.BodyAsBytes != null) if (requestMessage.BodyAsBytes != null)
{ {
@@ -119,6 +112,12 @@ namespace WireMock.Http
if (httpResponseMessage.Content != null) if (httpResponseMessage.Content != null)
{ {
var stream = await httpResponseMessage.Content.ReadAsStreamAsync(); var stream = await httpResponseMessage.Content.ReadAsStreamAsync();
IEnumerable<string> contentTypeHeader = null;
if (headers.Any(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase)))
{
contentTypeHeader = headers.First(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase)).Value;
}
var body = await BodyParser.Parse(stream, contentTypeHeader?.FirstOrDefault()); var body = await BodyParser.Parse(stream, contentTypeHeader?.FirstOrDefault());
responseMessage.Body = body.BodyAsString; responseMessage.Body = body.BodyAsString;
responseMessage.BodyAsJson = body.BodyAsJson; responseMessage.BodyAsJson = body.BodyAsJson;
+1 -1
View File
@@ -18,7 +18,7 @@ namespace WireMock.Matchers
/// <param name="values">The values.</param> /// <param name="values">The values.</param>
public ExactMatcher([NotNull] params string[] values) public ExactMatcher([NotNull] params string[] values)
{ {
Check.NotNull(values, nameof(values)); Check.HasNoNulls(values, nameof(values));
_values = values; _values = values;
} }
@@ -0,0 +1,13 @@
namespace WireMock.Matchers
{
/// <summary>
/// IIgnoreCaseMatcher
/// </summary>
public interface IIgnoreCaseMatcher : IMatcher
{
/// <summary>
/// Ignore the case.
/// </summary>
bool IgnoreCase { get; }
}
}
+5 -1
View File
@@ -10,7 +10,7 @@ namespace WireMock.Matchers
/// Regular Expression Matcher /// Regular Expression Matcher
/// </summary> /// </summary>
/// <seealso cref="IStringMatcher" /> /// <seealso cref="IStringMatcher" />
public class RegexMatcher : IStringMatcher public class RegexMatcher : IStringMatcher, IIgnoreCaseMatcher
{ {
private readonly string[] _patterns; private readonly string[] _patterns;
private readonly Regex[] _expressions; private readonly Regex[] _expressions;
@@ -34,6 +34,7 @@ namespace WireMock.Matchers
Check.NotNull(patterns, nameof(patterns)); Check.NotNull(patterns, nameof(patterns));
_patterns = patterns; _patterns = patterns;
IgnoreCase = ignoreCase;
RegexOptions options = RegexOptions.Compiled; RegexOptions options = RegexOptions.Compiled;
if (ignoreCase) if (ignoreCase)
@@ -73,5 +74,8 @@ namespace WireMock.Matchers
{ {
return "RegexMatcher"; return "RegexMatcher";
} }
/// <inheritdoc cref="IIgnoreCaseMatcher.IgnoreCase"/>
public bool IgnoreCase { get; }
} }
} }
@@ -104,15 +104,13 @@ namespace WireMock.Matchers.Request
{ {
if (requestMessage.Body != null) if (requestMessage.Body != null)
{ {
var stringMatcher = Matcher as IStringMatcher; if (Matcher is IStringMatcher stringMatcher)
if (stringMatcher != null)
{ {
return stringMatcher.IsMatch(requestMessage.Body); return stringMatcher.IsMatch(requestMessage.Body);
} }
} }
var objectMatcher = Matcher as IObjectMatcher; if (Matcher is IObjectMatcher objectMatcher)
if (objectMatcher != null)
{ {
if (requestMessage.BodyAsJson != null) if (requestMessage.BodyAsJson != null)
{ {
@@ -33,14 +33,7 @@ namespace WireMock.Matchers.Request
RequestMatchers = requestMatchers; RequestMatchers = requestMatchers;
} }
/// <summary> /// <inheritdoc cref="IRequestMatcher.GetMatchingScore"/>
/// Determines whether the specified RequestMessage is match.
/// </summary>
/// <param name="requestMessage">The RequestMessage.</param>
/// <param name="requestMatchResult">The RequestMatchResult.</param>
/// <returns>
/// A value between 0.0 - 1.0 of the similarity.
/// </returns>
public double GetMatchingScore(RequestMessage requestMessage, RequestMatchResult requestMatchResult) public double GetMatchingScore(RequestMessage requestMessage, RequestMatchResult requestMatchResult)
{ {
if (!RequestMatchers.Any()) if (!RequestMatchers.Any())
@@ -66,14 +66,7 @@ namespace WireMock.Matchers.Request
Funcs = funcs; Funcs = funcs;
} }
/// <summary> /// <inheritdoc cref="IRequestMatcher.GetMatchingScore"/>
/// Determines whether the specified RequestMessage is match.
/// </summary>
/// <param name="requestMessage">The RequestMessage.</param>
/// <param name="requestMatchResult">The RequestMatchResult.</param>
/// <returns>
/// A value between 0.0 - 1.0 of the similarity.
/// </returns>
public double GetMatchingScore(RequestMessage requestMessage, RequestMatchResult requestMatchResult) public double GetMatchingScore(RequestMessage requestMessage, RequestMatchResult requestMatchResult)
{ {
double score = IsMatch(requestMessage); double score = IsMatch(requestMessage);
@@ -19,5 +19,10 @@
/// Convert to bytes /// Convert to bytes
/// </summary> /// </summary>
public const string Bytes = "Bytes"; public const string Bytes = "Bytes";
/// <summary>
/// Convert to Json object
/// </summary>
public const string Json = "Json";
} }
} }
+14 -6
View File
@@ -7,6 +7,7 @@ using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
using Newtonsoft.Json;
using WireMock.Http; using WireMock.Http;
using WireMock.Settings; using WireMock.Settings;
using WireMock.Transformers; using WireMock.Transformers;
@@ -68,8 +69,9 @@ namespace WireMock.ResponseBuilders
} }
/// <summary> /// <summary>
/// Creates this instance. /// Creates this instance with the specified function.
/// </summary> /// </summary>
/// <param name="func">The callback function.</param>
/// <returns>A <see cref="IResponseBuilder"/>.</returns> /// <returns>A <see cref="IResponseBuilder"/>.</returns>
[PublicAPI] [PublicAPI]
public static IResponseBuilder Create([NotNull] Func<ResponseMessage> func) public static IResponseBuilder Create([NotNull] Func<ResponseMessage> func)
@@ -168,10 +170,9 @@ namespace WireMock.ResponseBuilders
} }
/// <inheritdoc cref="IBodyResponseBuilder.WithBody(Func{RequestMessage, string}, string, Encoding)"/> /// <inheritdoc cref="IBodyResponseBuilder.WithBody(Func{RequestMessage, string}, string, Encoding)"/>
public IResponseBuilder WithBody(Func<RequestMessage, string> bodyFactory, string destination = BodyDestinationFormat.SameAsSource, public IResponseBuilder WithBody(Func<RequestMessage, string> bodyFactory, string destination = BodyDestinationFormat.SameAsSource, Encoding encoding = null)
Encoding encoding = null)
{ {
return WithCallback(req => new ResponseMessage {Body = bodyFactory(req)}); return WithCallback(req => new ResponseMessage { Body = bodyFactory(req) });
} }
/// <inheritdoc cref="IBodyResponseBuilder.WithBody(byte[], string, Encoding)"/> /// <inheritdoc cref="IBodyResponseBuilder.WithBody(byte[], string, Encoding)"/>
@@ -231,19 +232,26 @@ namespace WireMock.ResponseBuilders
encoding = encoding ?? Encoding.UTF8; encoding = encoding ?? Encoding.UTF8;
ResponseMessage.BodyDestination = destination; ResponseMessage.BodyDestination = destination;
ResponseMessage.BodyEncoding = encoding;
switch (destination) switch (destination)
{ {
case BodyDestinationFormat.Bytes: case BodyDestinationFormat.Bytes:
ResponseMessage.Body = null; ResponseMessage.Body = null;
ResponseMessage.BodyAsJson = null;
ResponseMessage.BodyAsBytes = encoding.GetBytes(body); ResponseMessage.BodyAsBytes = encoding.GetBytes(body);
ResponseMessage.BodyEncoding = encoding; break;
case BodyDestinationFormat.Json:
ResponseMessage.Body = null;
ResponseMessage.BodyAsJson = JsonConvert.DeserializeObject(body);
ResponseMessage.BodyAsBytes = null;
break; break;
default: default:
ResponseMessage.Body = body; ResponseMessage.Body = body;
ResponseMessage.BodyAsJson = null;
ResponseMessage.BodyAsBytes = null; ResponseMessage.BodyAsBytes = null;
ResponseMessage.BodyEncoding = encoding;
break; break;
} }
@@ -2,9 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using JetBrains.Annotations; using JetBrains.Annotations;
using SimMetrics.Net;
using WireMock.Admin.Mappings; using WireMock.Admin.Mappings;
using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
@@ -40,19 +38,19 @@ namespace WireMock.Serialization
{ {
ClientIP = clientIPMatchers != null && clientIPMatchers.Any() ? new ClientIPModel ClientIP = clientIPMatchers != null && clientIPMatchers.Any() ? new ClientIPModel
{ {
Matchers = Map(clientIPMatchers.Where(m => m.Matchers != null).SelectMany(m => m.Matchers)), Matchers = MatcherMapper.Map(clientIPMatchers.Where(m => m.Matchers != null).SelectMany(m => m.Matchers)),
Funcs = Map(clientIPMatchers.Where(m => m.Funcs != null).SelectMany(m => m.Funcs)) Funcs = Map(clientIPMatchers.Where(m => m.Funcs != null).SelectMany(m => m.Funcs))
} : null, } : null,
Path = pathMatchers != null && pathMatchers.Any() ? new PathModel Path = pathMatchers != null && pathMatchers.Any() ? new PathModel
{ {
Matchers = Map(pathMatchers.Where(m => m.Matchers != null).SelectMany(m => m.Matchers)), Matchers = MatcherMapper.Map(pathMatchers.Where(m => m.Matchers != null).SelectMany(m => m.Matchers)),
Funcs = Map(pathMatchers.Where(m => m.Funcs != null).SelectMany(m => m.Funcs)) Funcs = Map(pathMatchers.Where(m => m.Funcs != null).SelectMany(m => m.Funcs))
} : null, } : null,
Url = urlMatchers != null && urlMatchers.Any() ? new UrlModel Url = urlMatchers != null && urlMatchers.Any() ? new UrlModel
{ {
Matchers = Map(urlMatchers.Where(m => m.Matchers != null).SelectMany(m => m.Matchers)), Matchers = MatcherMapper.Map(urlMatchers.Where(m => m.Matchers != null).SelectMany(m => m.Matchers)),
Funcs = Map(urlMatchers.Where(m => m.Funcs != null).SelectMany(m => m.Funcs)) Funcs = Map(urlMatchers.Where(m => m.Funcs != null).SelectMany(m => m.Funcs))
} : null, } : null,
@@ -61,14 +59,14 @@ namespace WireMock.Serialization
Headers = headerMatchers != null && headerMatchers.Any() ? headerMatchers.Select(hm => new HeaderModel Headers = headerMatchers != null && headerMatchers.Any() ? headerMatchers.Select(hm => new HeaderModel
{ {
Name = hm.Name, Name = hm.Name,
Matchers = Map(hm.Matchers), Matchers = MatcherMapper.Map(hm.Matchers),
Funcs = Map(hm.Funcs) Funcs = Map(hm.Funcs)
}).ToList() : null, }).ToList() : null,
Cookies = cookieMatchers != null && cookieMatchers.Any() ? cookieMatchers.Select(cm => new CookieModel Cookies = cookieMatchers != null && cookieMatchers.Any() ? cookieMatchers.Select(cm => new CookieModel
{ {
Name = cm.Name, Name = cm.Name,
Matchers = Map(cm.Matchers), Matchers = MatcherMapper.Map(cm.Matchers),
Funcs = Map(cm.Funcs) Funcs = Map(cm.Funcs)
}).ToList() : null, }).ToList() : null,
@@ -81,7 +79,7 @@ namespace WireMock.Serialization
Body = methodMatcher?.Methods != null && methodMatcher.Methods.Any(m => m == "get") ? null : new BodyModel Body = methodMatcher?.Methods != null && methodMatcher.Methods.Any(m => m == "get") ? null : new BodyModel
{ {
Matcher = bodyMatcher != null ? Map(bodyMatcher.Matcher) : null, Matcher = bodyMatcher != null ? MatcherMapper.Map(bodyMatcher.Matcher) : null,
Func = bodyMatcher != null ? Map(bodyMatcher.Func) : null, Func = bodyMatcher != null ? Map(bodyMatcher.Func) : null,
DataFunc = bodyMatcher != null ? Map(bodyMatcher.DataFunc) : null DataFunc = bodyMatcher != null ? Map(bodyMatcher.DataFunc) : null
} }
@@ -149,87 +147,16 @@ namespace WireMock.Serialization
return newDictionary; return newDictionary;
} }
private static MatcherModel[] Map([CanBeNull] IEnumerable<IMatcher> matchers)
{
if (matchers == null || !matchers.Any())
{
return null;
}
return matchers.Select(Map).Where(x => x != null).ToArray();
}
private static MatcherModel Map([CanBeNull] IMatcher matcher)
{
if (matcher == null)
{
return null;
}
IStringMatcher stringMatcher = matcher as IStringMatcher;
string[] patterns = stringMatcher != null ? stringMatcher.GetPatterns() : new string[0];
return new MatcherModel
{
Name = matcher.GetName(),
Pattern = patterns.Length == 1 ? patterns.First() : null,
Patterns = patterns.Length > 1 ? patterns : null
};
}
private 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()) return funcs?.Select(Map).Where(x => x != null).ToArray();
return null;
return funcs.Select(Map).Where(x => x != null).ToArray();
} }
private 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();
} }
public static IMatcher Map([CanBeNull] MatcherModel matcher)
{
if (matcher == null)
{
return null;
}
var parts = matcher.Name.Split('.');
string matcherName = parts[0];
string matcherType = parts.Length > 1 ? parts[1] : null;
string[] patterns = matcher.Patterns ?? new[] { matcher.Pattern };
switch (matcherName)
{
case "ExactMatcher":
return new ExactMatcher(patterns);
case "RegexMatcher":
return new RegexMatcher(patterns);
case "JsonPathMatcher":
return new JsonPathMatcher(patterns);
case "XPathMatcher":
return new XPathMatcher(matcher.Pattern);
case "WildcardMatcher":
return new WildcardMatcher(patterns, matcher.IgnoreCase == true);
case "SimMetricsMatcher":
SimMetricType type = SimMetricType.Levenstein;
if (!string.IsNullOrEmpty(matcherType) && !Enum.TryParse(matcherType, out type))
throw new NotSupportedException($"Matcher '{matcherName}' with Type '{matcherType}' is not supported.");
return new SimMetricsMatcher(matcher.Pattern, type);
default:
throw new NotSupportedException($"Matcher '{matcherName}' is not supported.");
}
}
} }
} }
@@ -0,0 +1,35 @@
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using WireMock.Admin.Mappings;
using WireMock.Matchers;
namespace WireMock.Serialization
{
internal static class MatcherMapper
{
public static MatcherModel[] Map([CanBeNull] IEnumerable<IMatcher> matchers)
{
return matchers?.Select(Map).Where(x => x != null).ToArray();
}
public static MatcherModel Map([CanBeNull] IMatcher matcher)
{
if (matcher == null)
{
return null;
}
string[] patterns = matcher is IStringMatcher stringMatcher ? stringMatcher.GetPatterns() : new string[0];
bool? ignorecase = matcher is IIgnoreCaseMatcher ignoreCaseMatcher ? ignoreCaseMatcher.IgnoreCase : (bool?)null;
return new MatcherModel
{
IgnoreCase = ignorecase,
Name = matcher.GetName(),
Pattern = patterns.Length == 1 ? patterns.First() : null,
Patterns = patterns.Length > 1 ? patterns : null
};
}
}
}
@@ -0,0 +1,55 @@
using System;
using JetBrains.Annotations;
using SimMetrics.Net;
using WireMock.Admin.Mappings;
using WireMock.Matchers;
namespace WireMock.Serialization
{
internal static class MatcherModelMapper
{
public static IMatcher Map([CanBeNull] MatcherModel matcher)
{
if (matcher == null)
{
return null;
}
string[] parts = matcher.Name.Split('.');
string matcherName = parts[0];
string matcherType = parts.Length > 1 ? parts[1] : null;
string[] patterns = matcher.Patterns ?? new[] { matcher.Pattern };
switch (matcherName)
{
case "ExactMatcher":
return new ExactMatcher(patterns);
case "RegexMatcher":
return new RegexMatcher(patterns, matcher.IgnoreCase == true);
case "JsonPathMatcher":
return new JsonPathMatcher(patterns);
case "XPathMatcher":
return new XPathMatcher(matcher.Pattern);
case "WildcardMatcher":
return new WildcardMatcher(patterns, matcher.IgnoreCase == true);
case "SimMetricsMatcher":
SimMetricType type = SimMetricType.Levenstein;
if (!string.IsNullOrEmpty(matcherType) && !Enum.TryParse(matcherType, out type))
{
throw new NotSupportedException($"Matcher '{matcherName}' with Type '{matcherType}' is not supported.");
}
return new SimMetricsMatcher(matcher.Pattern, type);
default:
throw new NotSupportedException($"Matcher '{matcherName}' is not supported.");
}
}
}
}
@@ -230,9 +230,10 @@ namespace WireMock.Server
requestMessage.Query.Loop((key, value) => request.WithParam(key, value.ToArray())); requestMessage.Query.Loop((key, value) => request.WithParam(key, value.ToArray()));
requestMessage.Cookies.Loop((key, value) => request.WithCookie(key, value)); requestMessage.Cookies.Loop((key, value) => request.WithCookie(key, value));
var allBlackListedHeaders = new List<string>(blacklistedHeaders) { "Cookie" };
requestMessage.Headers.Loop((key, value) => requestMessage.Headers.Loop((key, value) =>
{ {
if (!blacklistedHeaders.Any(b => string.Equals(key, b, StringComparison.OrdinalIgnoreCase))) if (!allBlackListedHeaders.Any(b => string.Equals(key, b, StringComparison.OrdinalIgnoreCase)))
{ {
request.WithHeader(key, value.ToArray()); request.WithHeader(key, value.ToArray());
} }
@@ -607,7 +608,7 @@ namespace WireMock.Server
var clientIPModel = JsonUtils.ParseJTokenToObject<ClientIPModel>(requestModel.ClientIP); var clientIPModel = JsonUtils.ParseJTokenToObject<ClientIPModel>(requestModel.ClientIP);
if (clientIPModel?.Matchers != null) if (clientIPModel?.Matchers != null)
{ {
requestBuilder = requestBuilder.WithPath(clientIPModel.Matchers.Select(MappingConverter.Map).Cast<IStringMatcher>().ToArray()); requestBuilder = requestBuilder.WithPath(clientIPModel.Matchers.Select(MatcherModelMapper.Map).Cast<IStringMatcher>().ToArray());
} }
} }
} }
@@ -624,7 +625,7 @@ namespace WireMock.Server
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).Cast<IStringMatcher>().ToArray()); requestBuilder = requestBuilder.WithPath(pathModel.Matchers.Select(MatcherModelMapper.Map).Cast<IStringMatcher>().ToArray());
} }
} }
} }
@@ -641,7 +642,7 @@ namespace WireMock.Server
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).Cast<IStringMatcher>().ToArray()); requestBuilder = requestBuilder.WithUrl(urlModel.Matchers.Select(MatcherModelMapper.Map).Cast<IStringMatcher>().ToArray());
} }
} }
} }
@@ -655,7 +656,7 @@ namespace WireMock.Server
{ {
foreach (var headerModel in requestModel.Headers.Where(h => h.Matchers != null)) foreach (var headerModel in requestModel.Headers.Where(h => h.Matchers != null))
{ {
requestBuilder = requestBuilder.WithHeader(headerModel.Name, headerModel.Matchers.Select(MappingConverter.Map).Cast<IStringMatcher>().ToArray()); requestBuilder = requestBuilder.WithHeader(headerModel.Name, headerModel.Matchers.Select(MatcherModelMapper.Map).Cast<IStringMatcher>().ToArray());
} }
} }
@@ -663,21 +664,21 @@ namespace WireMock.Server
{ {
foreach (var cookieModel in requestModel.Cookies.Where(c => c.Matchers != null)) foreach (var cookieModel in requestModel.Cookies.Where(c => c.Matchers != null))
{ {
requestBuilder = requestBuilder.WithCookie(cookieModel.Name, cookieModel.Matchers.Select(MappingConverter.Map).Cast<IStringMatcher>().ToArray()); requestBuilder = requestBuilder.WithCookie(cookieModel.Name, cookieModel.Matchers.Select(MatcherModelMapper.Map).Cast<IStringMatcher>().ToArray());
} }
} }
if (requestModel.Params != null) if (requestModel.Params != null)
{ {
foreach (var paramModel in requestModel.Params.Where(p => p.Values != null)) foreach (var paramModel in requestModel.Params)
{ {
requestBuilder = requestBuilder.WithParam(paramModel.Name, paramModel.Values.ToArray()); requestBuilder = paramModel.Values == null ? requestBuilder.WithParam(paramModel.Name) : requestBuilder.WithParam(paramModel.Name, paramModel.Values.ToArray());
} }
} }
if (requestModel.Body?.Matcher != null) if (requestModel.Body?.Matcher != null)
{ {
var bodyMatcher = MappingConverter.Map(requestModel.Body.Matcher); var bodyMatcher = MatcherModelMapper.Map(requestModel.Body.Matcher);
requestBuilder = requestBuilder.WithBody(bodyMatcher); requestBuilder = requestBuilder.WithBody(bodyMatcher);
} }
+4
View File
@@ -32,6 +32,10 @@
<DefineConstants>NETSTANDARD</DefineConstants> <DefineConstants>NETSTANDARD</DefineConstants>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Remove="Util\NamedReaderWriterLocker.cs" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<None Remove="Server\FluentMockServer.cs~RF44936b9f.TMP" /> <None Remove="Server\FluentMockServer.cs~RF44936b9f.TMP" />
</ItemGroup> </ItemGroup>
@@ -0,0 +1,61 @@
using NFluent;
using WireMock.Matchers;
using Xunit;
namespace WireMock.Net.Tests.Matchers
{
public class ExactMatcherTests
{
[Fact]
public void ExactMatcher_GetName()
{
// Assign
var matcher = new ExactMatcher("X");
// Act
string name = matcher.GetName();
// Assert
Check.That(name).Equals("ExactMatcher");
}
[Fact]
public void ExactMatcher_GetPatterns()
{
// Assign
var matcher = new ExactMatcher("X");
// Act
string[] patterns = matcher.GetPatterns();
// Assert
Check.That(patterns).ContainsExactly("X");
}
[Fact]
public void ExactMatcher_IsMatch_MultiplePatterns()
{
// Assign
var matcher = new ExactMatcher("x", "y");
// Act
double result = matcher.IsMatch("x");
// Assert
Check.That(result).IsEqualTo(0.5d);
}
[Fact]
public void Request_WithBodyExactMatcher_false()
{
// Assign
var matcher = new ExactMatcher("cat");
// Act
double result = matcher.IsMatch("caR");
// Assert
Check.That(result).IsStrictlyLessThan(1.0);
}
}
}
@@ -0,0 +1,35 @@
using NFluent;
using WireMock.Matchers;
using Xunit;
namespace WireMock.Net.Tests.Matchers
{
public class JsonPathMatcherTests
{
[Fact]
public void JsonPathMatcher_GetName()
{
// Assign
var matcher = new JsonPathMatcher("X");
// Act
string name = matcher.GetName();
// Assert
Check.That(name).Equals("JsonPathMatcher");
}
[Fact]
public void JsonPathMatcher_GetPatterns()
{
// Assign
var matcher = new JsonPathMatcher("X");
// Act
string[] patterns = matcher.GetPatterns();
// Assert
Check.That(patterns).ContainsExactly("X");
}
}
}
@@ -0,0 +1,74 @@
using NFluent;
using WireMock.Matchers;
using Xunit;
namespace WireMock.Net.Tests.Matchers
{
public class RegexMatcherTests
{
[Fact]
public void RegexMatcher_GetName()
{
// Assign
var matcher = new RegexMatcher("");
// Act
string name = matcher.GetName();
// Assert
Check.That(name).Equals("RegexMatcher");
}
[Fact]
public void RegexMatcher_GetPatterns()
{
// Assign
var matcher = new RegexMatcher("X");
// Act
string[] patterns = matcher.GetPatterns();
// Assert
Check.That(patterns).ContainsExactly("X");
}
[Fact]
public void RegexMatcher_IsMatch()
{
// Assign
var matcher = new RegexMatcher("H.*o");
// Act
double result = matcher.IsMatch("Hello world!");
// Assert
Check.That(result).IsEqualTo(1.0d);
}
[Fact]
public void RegexMatcher_IsMatch_NullInput()
{
// Assign
var matcher = new RegexMatcher("H.*o");
// Act
double result = matcher.IsMatch(null);
// Assert
Check.That(result).IsEqualTo(0.0d);
}
[Fact]
public void RegexMatcher_IsMatch_IgnoreCase()
{
// Assign
var matcher = new RegexMatcher("H.*o", true);
// Act
double result = matcher.IsMatch("hello world!");
// Assert
Check.That(result).IsEqualTo(1.0d);
}
}
}
@@ -0,0 +1,61 @@
using NFluent;
using WireMock.Matchers;
using Xunit;
namespace WireMock.Net.Tests.Matchers
{
public class SimMetricsMatcherTests
{
[Fact]
public void SimMetricsMatcher_GetName()
{
// Assign
var matcher = new SimMetricsMatcher("X");
// Act
string name = matcher.GetName();
// Assert
Check.That(name).Equals("SimMetricsMatcher.Levenstein");
}
[Fact]
public void SimMetricsMatcher_GetPatterns()
{
// Assign
var matcher = new SimMetricsMatcher("X");
// Act
string[] patterns = matcher.GetPatterns();
// Assert
Check.That(patterns).ContainsExactly("X");
}
[Fact]
public void SimMetricsMatcher_IsMatch_1()
{
// Assign
var matcher = new SimMetricsMatcher("The cat walks in the street.");
// Act
double result = matcher.IsMatch("The car drives in the street.");
// Assert
Check.That(result).IsStrictlyLessThan(1.0).And.IsStrictlyGreaterThan(0.5);
}
[Fact]
public void SimMetricsMatcher_IsMatch_2()
{
// Assign
var matcher = new SimMetricsMatcher("The cat walks in the street.");
// Act
double result = matcher.IsMatch("Hello");
// Assert
Check.That(result).IsStrictlyLessThan(0.1).And.IsStrictlyGreaterThan(0.05);
}
}
}
@@ -0,0 +1,87 @@
using NFluent;
using WireMock.Matchers;
using Xunit;
namespace WireMock.Net.Tests.Matchers
{
public class WildcardMatcherTest
{
[Fact]
public void WildcardMatcher_IsMatch_Positive()
{
var tests = new[]
{
new {p = "*", i = ""},
new {p = "?", i = " "},
new {p = "*", i = "a"},
new {p = "*", i = "ab"},
new {p = "?", i = "a"},
new {p = "*?", i = "abc"},
new {p = "?*", i = "abc"},
new {p = "abc", i = "abc"},
new {p = "abc*", i = "abc"},
new {p = "abc*", i = "abcd"},
new {p = "*abc*", i = "abc"},
new {p = "*a*bc*", i = "abc"},
new {p = "*a*b?", i = "aXXXbc"}
};
foreach (var test in tests)
{
var matcher = new WildcardMatcher(test.p);
Check.That(matcher.IsMatch(test.i)).IsEqualTo(1.0d);
}
}
[Fact]
public void WildcardMatcher_IsMatch_Negative()
{
var tests = new[]
{
new {p = "*a", i = ""},
new {p = "a*", i = ""},
new {p = "?", i = ""},
new {p = "*b*", i = "a"},
new {p = "b*a", i = "ab"},
new {p = "??", i = "a"},
new {p = "*?", i = ""},
new {p = "??*", i = "a"},
new {p = "*abc", i = "abX"},
new {p = "*abc*", i = "Xbc"},
new {p = "*a*bc*", i = "ac"}
};
foreach (var test in tests)
{
var matcher = new WildcardMatcher(test.p);
Check.That(matcher.IsMatch(test.i)).IsEqualTo(0.0);
}
}
[Fact]
public void WildcardMatcher_GetName()
{
// Assign
var matcher = new WildcardMatcher("x");
// Act
string name = matcher.GetName();
// Assert
Check.That(name).Equals("WildcardMatcher");
}
[Fact]
public void WildcardMatcher_GetPatterns()
{
// Assign
var matcher = new WildcardMatcher("x");
// Act
string[] patterns = matcher.GetPatterns();
// Assert
Check.That(patterns).ContainsExactly("x");
}
}
}
@@ -0,0 +1,35 @@
using NFluent;
using WireMock.Matchers;
using Xunit;
namespace WireMock.Net.Tests.Matchers
{
public class XPathMatcherTests
{
[Fact]
public void XPathMatcher_GetName()
{
// Assign
var matcher = new XPathMatcher("X");
// Act
string name = matcher.GetName();
// Assert
Check.That(name).Equals("XPathMatcher");
}
[Fact]
public void XPathMatcher_GetPatterns()
{
// Assign
var matcher = new XPathMatcher("X");
// Act
string[] patterns = matcher.GetPatterns();
// Assert
Check.That(patterns).ContainsExactly("X");
}
}
}
@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using NFluent;
using WireMock.Matchers.Request;
using Xunit;
namespace WireMock.Net.Tests.RequestMatchers
{
public class RequestMessageCompositeMatcherTests
{
private class Helper : RequestMessageCompositeMatcher
{
public Helper(IEnumerable<IRequestMatcher> requestMatchers, CompositeMatcherType type = CompositeMatcherType.And) : base(requestMatchers, type)
{
}
}
[Fact]
public void RequestMessageCompositeMatcher_GetMatchingScore_EmptyArray()
{
// Assign
var requestMessage = new RequestMessage(new Uri("http://localhost"), "GET", "127.0.0.1");
var matcher = new Helper(Enumerable.Empty<IRequestMatcher>());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.0d);
}
[Fact]
public void RequestMessageCompositeMatcher_GetMatchingScore_CompositeMatcherType_And()
{
// Assign
var requestMatcher1Mock = new Mock<IRequestMatcher>();
requestMatcher1Mock.Setup(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>())).Returns(1.0d);
var requestMatcher2Mock = new Mock<IRequestMatcher>();
requestMatcher2Mock.Setup(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>())).Returns(0.8d);
var requestMessage = new RequestMessage(new Uri("http://localhost"), "GET", "127.0.0.1");
var matcher = new Helper(new[] { requestMatcher1Mock.Object, requestMatcher2Mock.Object });
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.9d);
// Verify
requestMatcher1Mock.Verify(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>()), Times.Once);
requestMatcher2Mock.Verify(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>()), Times.Once);
}
[Fact]
public void RequestMessageCompositeMatcher_GetMatchingScore_CompositeMatcherType_Or()
{
// Assign
var requestMatcher1Mock = new Mock<IRequestMatcher>();
requestMatcher1Mock.Setup(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>())).Returns(1.0d);
var requestMatcher2Mock = new Mock<IRequestMatcher>();
requestMatcher2Mock.Setup(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>())).Returns(0.8d);
var requestMessage = new RequestMessage(new Uri("http://localhost"), "GET", "127.0.0.1");
var matcher = new Helper(new[] { requestMatcher1Mock.Object, requestMatcher2Mock.Object }, CompositeMatcherType.Or);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
// Verify
requestMatcher1Mock.Verify(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>()), Times.Once);
requestMatcher2Mock.Verify(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>()), Times.Once);
}
}
}
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using NFluent;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using Xunit;
namespace WireMock.Net.Tests.RequestMatchers
{
public class RequestMessageCookieMatcherTests
{
[Fact]
public void RequestMessageCookieMatcher_GetMatchingScore_IStringMatcher_Match()
{
// Assign
var cookies = new Dictionary<string, string> { { "cook", "x" } };
var requestMessage = new RequestMessage(new Uri("http://localhost"), "GET", "127.0.0.1", null, null, cookies);
var matcher = new RequestMessageCookieMatcher("cook", new ExactMatcher("x"));
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
}
[Fact]
public void RequestMessageCookieMatcher_GetMatchingScore_Func_Match()
{
// Assign
var cookies = new Dictionary<string, string> { { "cook", "x" } };
var requestMessage = new RequestMessage(new Uri("http://localhost"), "GET", "127.0.0.1", null, null, cookies);
var matcher = new RequestMessageCookieMatcher(x => x.ContainsKey("cook"));
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
}
}
}
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using NFluent;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using Xunit;
namespace WireMock.Net.Tests.RequestMatchers
{
public class RequestMessageHeaderMatcherTests
{
[Fact]
public void RequestMessageHeaderMatcher_GetMatchingScore_IStringMatcher_Match()
{
// Assign
var headers = new Dictionary<string, string[]> { { "h", new [] { "x" } } };
var requestMessage = new RequestMessage(new Uri("http://localhost"), "GET", "127.0.0.1", null, headers);
var matcher = new RequestMessageHeaderMatcher("h", new ExactMatcher("x"));
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
}
[Fact]
public void RequestMessageHeaderMatcher_GetMatchingScore_Func_Match()
{
// Assign
var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } };
var requestMessage = new RequestMessage(new Uri("http://localhost"), "GET", "127.0.0.1", null, headers);
var matcher = new RequestMessageHeaderMatcher(x => x.ContainsKey("h"));
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
}
}
}
@@ -85,70 +85,6 @@ namespace WireMock.Net.Tests
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
} }
[Fact]
public void Request_WithBodyExactMatcher_multiplePatterns()
{
// given
var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new ExactMatcher("cat", "dog"));
// when
string bodyAsString = "cat";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsEqualTo(0.5);
}
[Fact]
public void Request_WithBodyExactMatcher_false()
{
// given
var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new ExactMatcher("cat"));
// when
string bodyAsString = "caR";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsStrictlyLessThan(1.0);
}
[Fact]
public void Request_WithBodySimMetricsMatcher1()
{
// given
var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new SimMetricsMatcher("The cat walks in the street."));
// when
string bodyAsString = "The car drives in the street.";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsStrictlyLessThan(1.0).And.IsStrictlyGreaterThan(0.5);
}
[Fact]
public void Request_WithBodySimMetricsMatcher2()
{
// given
var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new SimMetricsMatcher("The cat walks in the street."));
// when
string bodyAsString = "Hello";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", ClientIp, body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsStrictlyLessThan(0.1).And.IsStrictlyGreaterThan(0.05);
}
[Fact] [Fact]
public void Request_WithBodyWildcardMatcher() public void Request_WithBodyWildcardMatcher()
{ {
@@ -165,22 +101,6 @@ namespace WireMock.Net.Tests
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
} }
[Fact]
public void Request_WithBodyRegexMatcher()
{
// given
var spec = Request.Create().UsingAnyVerb().WithBody(new RegexMatcher("H.*o"));
// when
string bodyAsString = "Hello world!";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp, body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact] [Fact]
public void Request_WithBodyXPathMatcher_true() public void Request_WithBodyXPathMatcher_true()
{ {
@@ -0,0 +1,29 @@
using System;
using System.Threading.Tasks;
using NFluent;
using WireMock.ResponseBuilders;
using Xunit;
namespace WireMock.Net.Tests.ResponseBuilderTests
{
public class ResponseCreateTests
{
private const string ClientIp = "::1";
[Fact]
public async Task Response_Create()
{
// Assign
var responseMessage = new ResponseMessage { StatusCode = 500 };
var request = new RequestMessage(new Uri("http://localhost"), "GET", ClientIp);
var response = Response.Create(() => responseMessage);
// Act
var providedResponse = await response.ProvideResponseAsync(request);
// Assert
Check.That(providedResponse).Equals(responseMessage);
}
}
}
@@ -8,7 +8,7 @@ using WireMock.ResponseBuilders;
using WireMock.Util; using WireMock.Util;
using Xunit; using Xunit;
namespace WireMock.Net.Tests namespace WireMock.Net.Tests.ResponseBuilderTests
{ {
public class ResponseWithBodyHandlebarsTests public class ResponseWithBodyHandlebarsTests
{ {
@@ -5,7 +5,7 @@ using NFluent;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using Xunit; using Xunit;
namespace WireMock.Net.Tests namespace WireMock.Net.Tests.ResponseBuilderTests
{ {
public class ResponseWithBodyTests public class ResponseWithBodyTests
{ {
@@ -86,5 +86,59 @@ namespace WireMock.Net.Tests
Check.That(responseMessage.BodyAsJson).Equals(x); Check.That(responseMessage.BodyAsJson).Equals(x);
Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII); Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII);
} }
[Fact]
public async Task Response_ProvideResponse_WithBody_String_SameAsSource_Encoding()
{
// Assign
var request = new RequestMessage(new Uri("http://localhost"), "GET", ClientIp);
var response = Response.Create().WithBody("r", BodyDestinationFormat.SameAsSource, Encoding.ASCII);
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
Check.That(responseMessage.BodyAsBytes).IsNull();
Check.That(responseMessage.BodyAsJson).IsNull();
Check.That(responseMessage.Body).Equals("r");
Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII);
}
[Fact]
public async Task Response_ProvideResponse_WithBody_String_Bytes_Encoding()
{
// Assign
var request = new RequestMessage(new Uri("http://localhost"), "GET", ClientIp);
var response = Response.Create().WithBody("r", BodyDestinationFormat.Bytes, Encoding.ASCII);
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
Check.That(responseMessage.Body).IsNull();
Check.That(responseMessage.BodyAsJson).IsNull();
Check.That(responseMessage.BodyAsBytes).IsNotNull();
Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII);
}
[Fact]
public async Task Response_ProvideResponse_WithBody_String_Json_Encoding()
{
// Assign
var request = new RequestMessage(new Uri("http://localhost"), "GET", ClientIp);
var response = Response.Create().WithBody("{ \"value\": 42 }", BodyDestinationFormat.Json, Encoding.ASCII);
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
Check.That(responseMessage.Body).IsNull();
Check.That(responseMessage.BodyAsBytes).IsNull();
Check.That(((dynamic) responseMessage.BodyAsJson).value).Equals(42);
Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII);
}
} }
} }
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NFluent;
using WireMock.ResponseBuilders;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.ResponseBuilderTests
{
public class ResponseWithHeadersTests
{
private const string ClientIp = "::1";
[Fact]
public async Task Response_ProvideResponse_WithHeaders_SingleValue()
{
// Assign
var request = new RequestMessage(new Uri("http://localhost"), "GET", ClientIp);
var headers = new Dictionary<string, string> { { "h", "x" } };
var response = Response.Create().WithHeaders(headers);
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
Check.That(responseMessage.Headers["h"]).ContainsExactly("x");
}
[Fact]
public async Task Response_ProvideResponse_WithHeaders_MultipleValues()
{
// Assign
var request = new RequestMessage(new Uri("http://localhost"), "GET", ClientIp);
var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } };
var response = Response.Create().WithHeaders(headers);
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
Check.That(responseMessage.Headers["h"]).ContainsExactly("x");
}
[Fact]
public async Task Response_ProvideResponse_WithHeaders_WiremockList()
{
// Assign
var request = new RequestMessage(new Uri("http://localhost"), "GET", ClientIp);
var headers = new Dictionary<string, WireMockList<string>> { { "h", new WireMockList<string>("x") } };
var response = Response.Create().WithHeaders(headers);
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
Check.That(responseMessage.Headers["h"]).ContainsExactly("x");
}
}
}
@@ -0,0 +1,27 @@
using System;
using NFluent;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Serialization;
using Xunit;
namespace WireMock.Net.Tests.Serialization
{
public class MappingConverterTests
{
[Fact]
public void MappingConverter_ToMappingModel()
{
// Assign
var request = Request.Create();
var response = Response.Create();
var mapping = new Mapping(Guid.NewGuid(), "", null, request, response, 0, null, null, null);
// Act
var model = MappingConverter.ToMappingModel(mapping);
// Assert
Check.That(model).IsNotNull();
}
}
}
@@ -0,0 +1,77 @@
using Moq;
using NFluent;
using WireMock.Matchers;
using WireMock.Serialization;
using Xunit;
namespace WireMock.Net.Tests.Serialization
{
public class MatcherMapperTests
{
[Fact]
public void MatcherMapper_Map_IMatcher_Null()
{
// Act
var model = MatcherMapper.Map((IMatcher)null);
// Assert
Check.That(model).IsNull();
}
[Fact]
public void MatcherMapper_Map_IMatchers_Null()
{
// Act
var model = MatcherMapper.Map((IMatcher[])null);
// Assert
Check.That(model).IsNull();
}
[Fact]
public void MatcherMapper_Map_IMatchers()
{
// Assign
var matcherMock1 = new Mock<IStringMatcher>();
var matcherMock2 = new Mock<IStringMatcher>();
// Act
var models = MatcherMapper.Map(new [] { matcherMock1.Object, matcherMock2.Object });
// Assert
Check.That(models).HasSize(2);
}
[Fact]
public void MatcherMapper_Map_IStringMatcher()
{
// Assign
var matcherMock = new Mock<IStringMatcher>();
matcherMock.Setup(m => m.GetName()).Returns("test");
matcherMock.Setup(m => m.GetPatterns()).Returns(new[] { "p1", "p2" });
// Act
var model = MatcherMapper.Map(matcherMock.Object);
// Assert
Check.That(model.IgnoreCase).IsNull();
Check.That(model.Name).Equals("test");
Check.That(model.Pattern).IsNull();
Check.That(model.Patterns).ContainsExactly("p1", "p2");
}
[Fact]
public void MatcherMapper_Map_IIgnoreCaseMatcher()
{
// Assign
var matcherMock = new Mock<IIgnoreCaseMatcher>();
matcherMock.Setup(m => m.IgnoreCase).Returns(true);
// Act
var model = MatcherMapper.Map(matcherMock.Object);
// Assert
Check.That(model.IgnoreCase).Equals(true);
}
}
}
@@ -0,0 +1,156 @@
using System;
using NFluent;
using WireMock.Admin.Mappings;
using WireMock.Matchers;
using WireMock.Serialization;
using Xunit;
namespace WireMock.Net.Tests.Serialization
{
public class MatcherModelMapperTests
{
[Fact]
public void MatcherModelMapper_Map_Null()
{
// Act
IMatcher matcher = MatcherModelMapper.Map(null);
// Assert
Check.That(matcher).IsNull();
}
[Fact]
public void MatcherModelMapper_Map_ExactMatcher_Pattern()
{
// Assign
var model = new MatcherModel
{
Name = "ExactMatcher",
Patterns = new[] { "x" }
};
// Act
var matcher = (ExactMatcher)MatcherModelMapper.Map(model);
// Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x");
}
[Fact]
public void MatcherModelMapper_Map_ExactMatcher_Patterns()
{
// Assign
var model = new MatcherModel
{
Name = "ExactMatcher",
Patterns = new[] { "x", "y" }
};
// Act
var matcher = (ExactMatcher)MatcherModelMapper.Map(model);
// Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x", "y");
}
[Fact]
public void MatcherModelMapper_Map_RegexMatcher()
{
// Assign
var model = new MatcherModel
{
Name = "RegexMatcher",
Patterns = new[] { "x", "y" },
IgnoreCase = true
};
// Act
var matcher = (RegexMatcher)MatcherModelMapper.Map(model);
// Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x", "y");
Check.That(matcher.IsMatch("X")).IsEqualTo(0.5d);
}
[Fact]
public void MatcherModelMapper_Map_WildcardMatcher()
{
// Assign
var model = new MatcherModel
{
Name = "WildcardMatcher",
Patterns = new[] { "x", "y" },
IgnoreCase = true
};
// Act
var matcher = (WildcardMatcher)MatcherModelMapper.Map(model);
// Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x", "y");
Check.That(matcher.IsMatch("X")).IsEqualTo(0.5d);
}
[Fact]
public void MatcherModelMapper_Map_SimMetricsMatcher()
{
// Assign
var model = new MatcherModel
{
Name = "SimMetricsMatcher",
Pattern = "x"
};
// Act
var matcher = (SimMetricsMatcher)MatcherModelMapper.Map(model);
// Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x");
}
[Fact]
public void MatcherModelMapper_Map_SimMetricsMatcher_BlockDistance()
{
// Assign
var model = new MatcherModel
{
Name = "SimMetricsMatcher.BlockDistance",
Pattern = "x"
};
// Act
var matcher = (SimMetricsMatcher)MatcherModelMapper.Map(model);
// Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x");
}
[Fact]
public void MatcherModelMapper_Map_SimMetricsMatcher_Throws1()
{
// Assign
var model = new MatcherModel
{
Name = "error",
Pattern = "x"
};
// Act
Check.ThatCode(() => MatcherModelMapper.Map(model)).Throws<NotSupportedException>();
}
[Fact]
public void MatcherModelMapper_Map_SimMetricsMatcher_Throws2()
{
// Assign
var model = new MatcherModel
{
Name = "SimMetricsMatcher.error",
Pattern = "x"
};
// Act
Check.ThatCode(() => MatcherModelMapper.Map(model)).Throws<NotSupportedException>();
}
}
}
@@ -0,0 +1,27 @@
using System.IO;
using System.Text;
using System.Threading.Tasks;
using NFluent;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.Util
{
public class BodyParserTests
{
[Fact]
public async Task BodyParser_Parse_ApplicationXml()
{
// Assign
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes("<xml>hello</xml>"));
// Act
var body = await BodyParser.Parse(memoryStream, "application/xml; charset=UTF-8");
// Assert
Check.That(body.BodyAsBytes).IsNull();
Check.That(body.BodyAsJson).IsNull();
Check.That(body.BodyAsString).Equals("<xml>hello</xml>");
}
}
}
@@ -1,64 +0,0 @@
using NFluent;
using Xunit;
using WireMock.Matchers;
namespace WireMock.Net.Tests
{
//[TestFixture]
public class WildcardMatcherTest
{
[Fact]
public void WildcardMatcher_patterns_positive()
{
var tests = new[]
{
new { p = "*", i = "" },
new { p = "?", i = " " },
new { p = "*", i = "a" },
new { p = "*", i = "ab" },
new { p = "?", i = "a" },
new { p = "*?", i = "abc" },
new { p = "?*", i = "abc" },
new { p = "abc", i = "abc" },
new { p = "abc*", i = "abc" },
new { p = "abc*", i = "abcd" },
new { p = "*abc*", i = "abc" },
new { p = "*a*bc*", i = "abc" },
new { p = "*a*b?", i = "aXXXbc" }
};
foreach (var test in tests)
{
var matcher = new WildcardMatcher(test.p);
Check.That(matcher.IsMatch(test.i)).Equals(1.0);
//Assert.AreEqual(1.0, matcher.IsMatch(test.i), "p = " + test.p + ", i = " + test.i);
}
}
[Fact]
public void WildcardMatcher_patterns_negative()
{
var tests = new[]
{
new { p = "*a", i = ""},
new { p = "a*", i = ""},
new { p = "?", i = ""},
new { p = "*b*", i = "a"},
new { p = "b*a", i = "ab"},
new { p = "??", i = "a"},
new { p = "*?", i = ""},
new { p = "??*", i = "a"},
new { p = "*abc", i = "abX"},
new { p = "*abc*", i = "Xbc"},
new { p = "*a*bc*", i = "ac"}
};
foreach (var test in tests)
{
var matcher = new WildcardMatcher(test.p);
//Assert.AreEqual(0.0, matcher.IsMatch(test.i), "p = " + test.p + ", i = " + test.i);
Check.That(matcher.IsMatch(test.i)).Equals(0.0);
}
}
}
}