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

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>

View File

@@ -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; }
} }
} }

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;

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;
} }

View File

@@ -0,0 +1,13 @@
namespace WireMock.Matchers
{
/// <summary>
/// IIgnoreCaseMatcher
/// </summary>
public interface IIgnoreCaseMatcher : IMatcher
{
/// <summary>
/// Ignore the case.
/// </summary>
bool IgnoreCase { get; }
}
}

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; }
} }
} }

View File

@@ -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)
{ {

View File

@@ -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())

View File

@@ -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);

View File

@@ -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";
} }
} }

View File

@@ -1,366 +1,374 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; 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 WireMock.Http; using Newtonsoft.Json;
using WireMock.Settings; using WireMock.Http;
using WireMock.Transformers; using WireMock.Settings;
using WireMock.Util; using WireMock.Transformers;
using WireMock.Validation; using WireMock.Util;
using WireMock.Validation;
namespace WireMock.ResponseBuilders
{ namespace WireMock.ResponseBuilders
/// <summary> {
/// The Response. /// <summary>
/// </summary> /// The Response.
public class Response : IResponseBuilder /// </summary>
{ public class Response : IResponseBuilder
private HttpClient _httpClientForProxy; {
private HttpClient _httpClientForProxy;
/// <summary>
/// The delay /// <summary>
/// </summary> /// The delay
public TimeSpan? Delay { get; private set; } /// </summary>
public TimeSpan? Delay { get; private set; }
/// <summary>
/// Gets a value indicating whether [use transformer]. /// <summary>
/// </summary> /// Gets a value indicating whether [use transformer].
/// <value> /// </summary>
/// <c>true</c> if [use transformer]; otherwise, <c>false</c>. /// <value>
/// </value> /// <c>true</c> if [use transformer]; otherwise, <c>false</c>.
public bool UseTransformer { get; private set; } /// </value>
public bool UseTransformer { get; private set; }
/// <summary>
/// The Proxy URL to use. /// <summary>
/// </summary> /// The Proxy URL to use.
public string ProxyUrl { get; private set; } /// </summary>
public string ProxyUrl { get; private set; }
/// <summary>
/// The client X509Certificate2 Thumbprint or SubjectName to use. /// <summary>
/// </summary> /// The client X509Certificate2 Thumbprint or SubjectName to use.
public string ClientX509Certificate2ThumbprintOrSubjectName { get; private set; } /// </summary>
public string ClientX509Certificate2ThumbprintOrSubjectName { get; private set; }
/// <summary>
/// Gets the response message. /// <summary>
/// </summary> /// Gets the response message.
public ResponseMessage ResponseMessage { get; } /// </summary>
public ResponseMessage ResponseMessage { get; }
/// <summary>
/// A delegate to execute to generate the response /// <summary>
/// </summary> /// A delegate to execute to generate the response
public Func<RequestMessage, ResponseMessage> Callback { get; private set; } /// </summary>
public Func<RequestMessage, ResponseMessage> Callback { get; private set; }
/// <summary>
/// Creates this instance. /// <summary>
/// </summary> /// Creates this instance.
/// <param name="responseMessage">ResponseMessage</param> /// </summary>
/// <returns>A <see cref="IResponseBuilder"/>.</returns> /// <param name="responseMessage">ResponseMessage</param>
[PublicAPI] /// <returns>A <see cref="IResponseBuilder"/>.</returns>
public static IResponseBuilder Create([CanBeNull] ResponseMessage responseMessage = null) [PublicAPI]
{ public static IResponseBuilder Create([CanBeNull] ResponseMessage responseMessage = null)
var message = responseMessage ?? new ResponseMessage { StatusCode = (int)HttpStatusCode.OK }; {
return new Response(message); var message = responseMessage ?? new ResponseMessage { StatusCode = (int)HttpStatusCode.OK };
} return new Response(message);
}
/// <summary>
/// Creates this instance. /// <summary>
/// </summary> /// Creates this instance with the specified function.
/// <returns>A <see cref="IResponseBuilder"/>.</returns> /// </summary>
[PublicAPI] /// <param name="func">The callback function.</param>
public static IResponseBuilder Create([NotNull] Func<ResponseMessage> func) /// <returns>A <see cref="IResponseBuilder"/>.</returns>
{ [PublicAPI]
Check.NotNull(func, nameof(func)); public static IResponseBuilder Create([NotNull] Func<ResponseMessage> func)
{
return new Response(func()); Check.NotNull(func, nameof(func));
}
return new Response(func());
/// <summary> }
/// Initializes a new instance of the <see cref="Response"/> class.
/// </summary> /// <summary>
/// <param name="responseMessage"> /// Initializes a new instance of the <see cref="Response"/> class.
/// The response. /// </summary>
/// </param> /// <param name="responseMessage">
private Response(ResponseMessage responseMessage) /// The response.
{ /// </param>
ResponseMessage = responseMessage; private Response(ResponseMessage responseMessage)
} {
ResponseMessage = responseMessage;
/// <summary> }
/// The with status code.
/// </summary> /// <summary>
/// <param name="code">The code.</param> /// The with status code.
/// <returns>A <see cref="IResponseBuilder"/>.</returns>\ /// </summary>
[PublicAPI] /// <param name="code">The code.</param>
public IResponseBuilder WithStatusCode(int code) /// <returns>A <see cref="IResponseBuilder"/>.</returns>\
{ [PublicAPI]
ResponseMessage.StatusCode = code; public IResponseBuilder WithStatusCode(int code)
return this; {
} ResponseMessage.StatusCode = code;
return this;
/// <summary> }
/// The with status code.
/// </summary> /// <summary>
/// <param name="code">The code.</param> /// The with status code.
/// <returns>A <see cref="IResponseBuilder"/>.</returns> /// </summary>
[PublicAPI] /// <param name="code">The code.</param>
public IResponseBuilder WithStatusCode(HttpStatusCode code) /// <returns>A <see cref="IResponseBuilder"/>.</returns>
{ [PublicAPI]
return WithStatusCode((int)code); public IResponseBuilder WithStatusCode(HttpStatusCode code)
} {
return WithStatusCode((int)code);
/// <summary> }
/// The with Success status code (200).
/// </summary> /// <summary>
/// <returns>A <see cref="IResponseBuilder"/>.</returns> /// The with Success status code (200).
[PublicAPI] /// </summary>
public IResponseBuilder WithSuccess() /// <returns>A <see cref="IResponseBuilder"/>.</returns>
{ [PublicAPI]
return WithStatusCode((int)HttpStatusCode.OK); public IResponseBuilder WithSuccess()
} {
return WithStatusCode((int)HttpStatusCode.OK);
/// <summary> }
/// The with NotFound status code (404).
/// </summary> /// <summary>
/// <returns>The <see cref="IResponseBuilder"/>.</returns> /// The with NotFound status code (404).
[PublicAPI] /// </summary>
public IResponseBuilder WithNotFound() /// <returns>The <see cref="IResponseBuilder"/>.</returns>
{ [PublicAPI]
return WithStatusCode((int)HttpStatusCode.NotFound); public IResponseBuilder WithNotFound()
} {
return WithStatusCode((int)HttpStatusCode.NotFound);
/// <inheritdoc cref="IHeadersResponseBuilder.WithHeader(string, string[])"/> }
public IResponseBuilder WithHeader(string name, params string[] values)
{ /// <inheritdoc cref="IHeadersResponseBuilder.WithHeader(string, string[])"/>
Check.NotNull(name, nameof(name)); public IResponseBuilder WithHeader(string name, params string[] values)
{
ResponseMessage.AddHeader(name, values); Check.NotNull(name, nameof(name));
return this;
} ResponseMessage.AddHeader(name, values);
return this;
/// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string})"/> }
public IResponseBuilder WithHeaders(IDictionary<string, string> headers)
{ /// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string})"/>
Check.NotNull(headers, nameof(headers)); public IResponseBuilder WithHeaders(IDictionary<string, string> headers)
{
ResponseMessage.Headers = headers.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value)); Check.NotNull(headers, nameof(headers));
return this;
} 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)
{ /// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string[]})"/>
Check.NotNull(headers, nameof(headers)); public IResponseBuilder WithHeaders(IDictionary<string, string[]> headers)
{
ResponseMessage.Headers = headers.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value)); Check.NotNull(headers, nameof(headers));
return this;
} 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)
{ /// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, WireMockList{string}})"/>
ResponseMessage.Headers = headers; public IResponseBuilder WithHeaders(IDictionary<string, WireMockList<string>> headers)
return this; {
} ResponseMessage.Headers = headers;
return this;
}
/// <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)"/> public IResponseBuilder WithBody(byte[] body, string destination, Encoding encoding = null)
public IResponseBuilder WithBody(byte[] body, string destination, Encoding encoding = null) {
{ Check.NotNull(body, nameof(body));
Check.NotNull(body, nameof(body));
ResponseMessage.BodyDestination = destination;
ResponseMessage.BodyDestination = destination;
switch (destination)
switch (destination) {
{ case BodyDestinationFormat.String:
case BodyDestinationFormat.String: var enc = encoding ?? Encoding.UTF8;
var enc = encoding ?? Encoding.UTF8; ResponseMessage.BodyAsBytes = null;
ResponseMessage.BodyAsBytes = null; ResponseMessage.Body = enc.GetString(body);
ResponseMessage.Body = enc.GetString(body); ResponseMessage.BodyEncoding = enc;
ResponseMessage.BodyEncoding = enc; break;
break;
default:
default: ResponseMessage.BodyAsBytes = body;
ResponseMessage.BodyAsBytes = body; ResponseMessage.BodyEncoding = null;
ResponseMessage.BodyEncoding = null; break;
break; }
}
return this;
return this; }
}
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromFile"/>
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromFile"/> public IResponseBuilder WithBodyFromFile(string filename, bool cache = true)
public IResponseBuilder WithBodyFromFile(string filename, bool cache = true) {
{ Check.NotNull(filename, nameof(filename));
Check.NotNull(filename, nameof(filename));
ResponseMessage.BodyEncoding = null;
ResponseMessage.BodyEncoding = null; ResponseMessage.BodyAsFileIsCached = cache;
ResponseMessage.BodyAsFileIsCached = cache;
if (cache)
if (cache) {
{ ResponseMessage.Body = null;
ResponseMessage.Body = null; ResponseMessage.BodyAsBytes = File.ReadAllBytes(filename);
ResponseMessage.BodyAsBytes = File.ReadAllBytes(filename); ResponseMessage.BodyAsFile = null;
ResponseMessage.BodyAsFile = null; }
} else
else {
{ ResponseMessage.Body = null;
ResponseMessage.Body = null; ResponseMessage.BodyAsBytes = null;
ResponseMessage.BodyAsBytes = null; ResponseMessage.BodyAsFile = filename;
ResponseMessage.BodyAsFile = filename; }
}
return this;
return this; }
}
/// <inheritdoc cref="IBodyResponseBuilder.WithBody(string, string, Encoding)"/>
/// <inheritdoc cref="IBodyResponseBuilder.WithBody(string, string, Encoding)"/> public IResponseBuilder WithBody(string body, string destination = BodyDestinationFormat.SameAsSource, Encoding encoding = null)
public IResponseBuilder WithBody(string body, string destination = BodyDestinationFormat.SameAsSource, Encoding encoding = null) {
{ Check.NotNull(body, nameof(body));
Check.NotNull(body, nameof(body));
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.BodyAsBytes = encoding.GetBytes(body); ResponseMessage.BodyAsJson = null;
ResponseMessage.BodyEncoding = encoding; ResponseMessage.BodyAsBytes = encoding.GetBytes(body);
break; break;
default: case BodyDestinationFormat.Json:
ResponseMessage.Body = body; ResponseMessage.Body = null;
ResponseMessage.BodyAsBytes = null; ResponseMessage.BodyAsJson = JsonConvert.DeserializeObject(body);
ResponseMessage.BodyEncoding = encoding; ResponseMessage.BodyAsBytes = null;
break; break;
}
default:
return this; ResponseMessage.Body = body;
} ResponseMessage.BodyAsJson = null;
ResponseMessage.BodyAsBytes = null;
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson"/> break;
public IResponseBuilder WithBodyAsJson(object body, Encoding encoding = null) }
{
Check.NotNull(body, nameof(body)); return this;
}
ResponseMessage.BodyDestination = null;
ResponseMessage.BodyAsJson = body; /// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson"/>
ResponseMessage.BodyEncoding = encoding; public IResponseBuilder WithBodyAsJson(object body, Encoding encoding = null)
{
return this; Check.NotNull(body, nameof(body));
}
ResponseMessage.BodyDestination = null;
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromBase64"/> ResponseMessage.BodyAsJson = body;
public IResponseBuilder WithBodyFromBase64(string bodyAsbase64, Encoding encoding = null) ResponseMessage.BodyEncoding = encoding;
{
Check.NotNull(bodyAsbase64, nameof(bodyAsbase64)); return this;
}
encoding = encoding ?? Encoding.UTF8;
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromBase64"/>
ResponseMessage.BodyDestination = null; public IResponseBuilder WithBodyFromBase64(string bodyAsbase64, Encoding encoding = null)
ResponseMessage.Body = encoding.GetString(Convert.FromBase64String(bodyAsbase64)); {
ResponseMessage.BodyEncoding = encoding; Check.NotNull(bodyAsbase64, nameof(bodyAsbase64));
return this; encoding = encoding ?? Encoding.UTF8;
}
ResponseMessage.BodyDestination = null;
/// <inheritdoc cref="ITransformResponseBuilder.WithTransformer"/> ResponseMessage.Body = encoding.GetString(Convert.FromBase64String(bodyAsbase64));
public IResponseBuilder WithTransformer() ResponseMessage.BodyEncoding = encoding;
{
UseTransformer = true; return this;
return this; }
}
/// <inheritdoc cref="ITransformResponseBuilder.WithTransformer"/>
/// <inheritdoc cref="IDelayResponseBuilder.WithDelay(TimeSpan)"/> public IResponseBuilder WithTransformer()
public IResponseBuilder WithDelay(TimeSpan delay) {
{ UseTransformer = true;
Check.Condition(delay, d => d > TimeSpan.Zero, nameof(delay)); return this;
}
Delay = delay;
return this; /// <inheritdoc cref="IDelayResponseBuilder.WithDelay(TimeSpan)"/>
} public IResponseBuilder WithDelay(TimeSpan delay)
{
/// <inheritdoc cref="IDelayResponseBuilder.WithDelay(int)"/> Check.Condition(delay, d => d > TimeSpan.Zero, nameof(delay));
public IResponseBuilder WithDelay(int milliseconds)
{ Delay = delay;
return WithDelay(TimeSpan.FromMilliseconds(milliseconds)); return this;
} }
/// <inheritdoc cref="IProxyResponseBuilder.WithProxy(string, string)"/> /// <inheritdoc cref="IDelayResponseBuilder.WithDelay(int)"/>
public IResponseBuilder WithProxy(string proxyUrl, string clientX509Certificate2ThumbprintOrSubjectName = null) public IResponseBuilder WithDelay(int milliseconds)
{ {
Check.NotNullOrEmpty(proxyUrl, nameof(proxyUrl)); return WithDelay(TimeSpan.FromMilliseconds(milliseconds));
}
ProxyUrl = proxyUrl;
ClientX509Certificate2ThumbprintOrSubjectName = clientX509Certificate2ThumbprintOrSubjectName; /// <inheritdoc cref="IProxyResponseBuilder.WithProxy(string, string)"/>
_httpClientForProxy = HttpClientHelper.CreateHttpClient(clientX509Certificate2ThumbprintOrSubjectName); public IResponseBuilder WithProxy(string proxyUrl, string clientX509Certificate2ThumbprintOrSubjectName = null)
return this; {
} Check.NotNullOrEmpty(proxyUrl, nameof(proxyUrl));
/// <inheritdoc cref="IProxyResponseBuilder.WithProxy(IProxyAndRecordSettings)"/> ProxyUrl = proxyUrl;
public IResponseBuilder WithProxy(IProxyAndRecordSettings settings) ClientX509Certificate2ThumbprintOrSubjectName = clientX509Certificate2ThumbprintOrSubjectName;
{ _httpClientForProxy = HttpClientHelper.CreateHttpClient(clientX509Certificate2ThumbprintOrSubjectName);
Check.NotNull(settings, nameof(settings)); return this;
}
return WithProxy(settings.Url, settings.ClientX509Certificate2ThumbprintOrSubjectName);
} /// <inheritdoc cref="IProxyResponseBuilder.WithProxy(IProxyAndRecordSettings)"/>
public IResponseBuilder WithProxy(IProxyAndRecordSettings settings)
/// <inheritdoc cref="ICallbackResponseBuilder.WithCallback"/> {
public IResponseBuilder WithCallback(Func<RequestMessage, ResponseMessage> callbackHandler) Check.NotNull(settings, nameof(settings));
{
Check.NotNull(callbackHandler, nameof(callbackHandler)); return WithProxy(settings.Url, settings.ClientX509Certificate2ThumbprintOrSubjectName);
}
Callback = callbackHandler;
/// <inheritdoc cref="ICallbackResponseBuilder.WithCallback"/>
return this; public IResponseBuilder WithCallback(Func<RequestMessage, ResponseMessage> callbackHandler)
} {
Check.NotNull(callbackHandler, nameof(callbackHandler));
/// <summary>
/// The provide response. Callback = callbackHandler;
/// </summary>
/// <param name="requestMessage">The request.</param> return this;
/// <returns>The <see cref="ResponseMessage"/>.</returns> }
public async Task<ResponseMessage> ProvideResponseAsync(RequestMessage requestMessage)
{ /// <summary>
Check.NotNull(requestMessage, nameof(requestMessage)); /// The provide response.
/// </summary>
if (Delay != null) /// <param name="requestMessage">The request.</param>
{ /// <returns>The <see cref="ResponseMessage"/>.</returns>
await Task.Delay(Delay.Value); public async Task<ResponseMessage> ProvideResponseAsync(RequestMessage requestMessage)
} {
Check.NotNull(requestMessage, nameof(requestMessage));
if (ProxyUrl != null && _httpClientForProxy != null)
{ if (Delay != null)
var requestUri = new Uri(requestMessage.Url); {
var proxyUri = new Uri(ProxyUrl); await Task.Delay(Delay.Value);
var proxyUriWithRequestPathAndQuery = new Uri(proxyUri, requestUri.PathAndQuery); }
return await HttpClientHelper.SendAsync(_httpClientForProxy, requestMessage, proxyUriWithRequestPathAndQuery.AbsoluteUri); if (ProxyUrl != null && _httpClientForProxy != null)
} {
var requestUri = new Uri(requestMessage.Url);
if (UseTransformer) var proxyUri = new Uri(ProxyUrl);
{ var proxyUriWithRequestPathAndQuery = new Uri(proxyUri, requestUri.PathAndQuery);
return ResponseMessageTransformer.Transform(requestMessage, ResponseMessage);
} return await HttpClientHelper.SendAsync(_httpClientForProxy, requestMessage, proxyUriWithRequestPathAndQuery.AbsoluteUri);
}
if (Callback != null)
{ if (UseTransformer)
return Callback(requestMessage); {
} return ResponseMessageTransformer.Transform(requestMessage, ResponseMessage);
}
return ResponseMessage;
} if (Callback != null)
} {
return Callback(requestMessage);
}
return ResponseMessage;
}
}
} }

View File

@@ -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.");
}
}
} }
} }

View File

@@ -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
};
}
}
}

View File

@@ -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.");
}
}
}
}

View File

@@ -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);
} }

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>

View File

@@ -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);
}
}
}

View File

@@ -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");
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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");
}
}
}

View File

@@ -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");
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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()
{ {

View File

@@ -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);
}
}
}

View File

@@ -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
{ {

View File

@@ -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);
}
} }
} }

View File

@@ -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");
}
}
}

View File

@@ -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();
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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>();
}
}
}

View File

@@ -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>");
}
}
}

View File

@@ -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);
}
}
}
}