JsonPartialMatcher - support Regex (#771)

* JsonPartialMatcher - support Regex

* .

* .

* more tests

* .

* .
This commit is contained in:
Stef Heyenrath
2022-07-24 15:54:53 +02:00
committed by GitHub
parent 150b448d07
commit bdd421e128
20 changed files with 1773 additions and 1625 deletions

View File

@@ -1,48 +1,52 @@
namespace WireMock.Admin.Mappings namespace WireMock.Admin.Mappings;
/// <summary>
/// MatcherModel
/// </summary>
[FluentBuilder.AutoGenerateBuilder]
public class MatcherModel
{ {
/// <summary> /// <summary>
/// MatcherModel /// Gets or sets the name.
/// </summary> /// </summary>
[FluentBuilder.AutoGenerateBuilder] public string Name { get; set; } = null!;
public class MatcherModel
{
/// <summary>
/// Gets or sets the name.
/// </summary>
public string Name { get; set; }
/// <summary> /// <summary>
/// Gets or sets the pattern. Can be a string (default) or an object. /// Gets or sets the pattern. Can be a string (default) or an object.
/// </summary> /// </summary>
public object? Pattern { get; set; } public object? Pattern { get; set; }
/// <summary> /// <summary>
/// Gets or sets the patterns. Can be array of strings (default) or an array of objects. /// Gets or sets the patterns. Can be array of strings (default) or an array of objects.
/// </summary> /// </summary>
public object[]? Patterns { get; set; } public object[]? Patterns { get; set; }
/// <summary> /// <summary>
/// Gets or sets the pattern as a file. /// Gets or sets the pattern as a file.
/// </summary> /// </summary>
public string? PatternAsFile { get; set; } public string? PatternAsFile { get; set; }
/// <summary> /// <summary>
/// Gets or sets the ignore case. /// Gets or sets the ignore case.
/// </summary> /// </summary>
public bool? IgnoreCase { get; set; } public bool? IgnoreCase { get; set; }
/// <summary> /// <summary>
/// Reject on match. /// Reject on match.
/// </summary> /// </summary>
public bool? RejectOnMatch { get; set; } public bool? RejectOnMatch { get; set; }
/// <summary> /// <summary>
/// The Operator to use when multiple patterns are defined. Optional. /// The Operator to use when multiple patterns are defined. Optional.
/// - null = Same as "or". /// - null = Same as "or".
/// - "or" = Only one pattern should match. /// - "or" = Only one pattern should match.
/// - "and" = All patterns should match. /// - "and" = All patterns should match.
/// - "average" = The average value from all patterns. /// - "average" = The average value from all patterns.
/// </summary> /// </summary>
public string? MatchOperator { get; set; } public string? MatchOperator { get; set; }
}
/// <summary>
/// Support Regex, only used for JsonPartialMatcher.
/// </summary>
public bool? Regex { get; set; }
} }

View File

@@ -1,20 +1,17 @@
using JetBrains.Annotations; namespace WireMock.Matchers.Request;
namespace WireMock.Matchers.Request /// <summary>
/// The RequestMatcher interface.
/// </summary>
public interface IRequestMatcher
{ {
/// <summary> /// <summary>
/// The RequestMatcher interface. /// Determines whether the specified RequestMessage is match.
/// </summary> /// </summary>
public interface IRequestMatcher /// <param name="requestMessage">The RequestMessage.</param>
{ /// <param name="requestMatchResult">The RequestMatchResult.</param>
/// <summary> /// <returns>
/// Determines whether the specified RequestMessage is match. /// A value between 0.0 - 1.0 of the similarity.
/// </summary> /// </returns>
/// <param name="requestMessage">The RequestMessage.</param> double GetMatchingScore(IRequestMessage requestMessage, IRequestMatchResult requestMatchResult);
/// <param name="requestMatchResult">The RequestMatchResult.</param>
/// <returns>
/// A value between 0.0 - 1.0 of the similarity.
/// </returns>
double GetMatchingScore(IRequestMessage requestMessage, IRequestMatchResult requestMatchResult);
}
} }

View File

@@ -1,6 +1,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using WireMock.Util;
namespace WireMock.Matchers; namespace WireMock.Matchers;
@@ -9,15 +10,22 @@ namespace WireMock.Matchers;
/// </summary> /// </summary>
public abstract class AbstractJsonPartialMatcher : JsonMatcher public abstract class AbstractJsonPartialMatcher : JsonMatcher
{ {
/// <summary>
/// Support Regex
/// </summary>
public bool Regex { get; }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="AbstractJsonPartialMatcher"/> class. /// Initializes a new instance of the <see cref="AbstractJsonPartialMatcher"/> class.
/// </summary> /// </summary>
/// <param name="value">The string value to check for equality.</param> /// <param name="value">The string value to check for equality.</param>
/// <param name="ignoreCase">Ignore the case from the PropertyName and PropertyValue (string only).</param> /// <param name="ignoreCase">Ignore the case from the PropertyName and PropertyValue (string only).</param>
/// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param> /// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param>
protected AbstractJsonPartialMatcher(string value, bool ignoreCase = false, bool throwException = false) /// <param name="regex">Support Regex.</param>
protected AbstractJsonPartialMatcher(string value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(value, ignoreCase, throwException) : base(value, ignoreCase, throwException)
{ {
Regex = regex;
} }
/// <summary> /// <summary>
@@ -26,9 +34,11 @@ public abstract class AbstractJsonPartialMatcher : JsonMatcher
/// <param name="value">The object value to check for equality.</param> /// <param name="value">The object value to check for equality.</param>
/// <param name="ignoreCase">Ignore the case from the PropertyName and PropertyValue (string only).</param> /// <param name="ignoreCase">Ignore the case from the PropertyName and PropertyValue (string only).</param>
/// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param> /// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param>
protected AbstractJsonPartialMatcher(object value, bool ignoreCase = false, bool throwException = false) /// <param name="regex">Support Regex.</param>
protected AbstractJsonPartialMatcher(object value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(value, ignoreCase, throwException) : base(value, ignoreCase, throwException)
{ {
Regex = regex;
} }
/// <summary> /// <summary>
@@ -38,9 +48,11 @@ public abstract class AbstractJsonPartialMatcher : JsonMatcher
/// <param name="value">The value to check for equality.</param> /// <param name="value">The value to check for equality.</param>
/// <param name="ignoreCase">Ignore the case from the PropertyName and PropertyValue (string only).</param> /// <param name="ignoreCase">Ignore the case from the PropertyName and PropertyValue (string only).</param>
/// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param> /// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param>
protected AbstractJsonPartialMatcher(MatchBehaviour matchBehaviour, object value, bool ignoreCase = false, bool throwException = false) /// <param name="regex">Support Regex.</param>
protected AbstractJsonPartialMatcher(MatchBehaviour matchBehaviour, object value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(matchBehaviour, value, ignoreCase, throwException) : base(matchBehaviour, value, ignoreCase, throwException)
{ {
Regex = regex;
} }
/// <inheritdoc /> /// <inheritdoc />
@@ -51,6 +63,17 @@ public abstract class AbstractJsonPartialMatcher : JsonMatcher
return true; return true;
} }
if (Regex && value.Type == JTokenType.String && input != null)
{
var valueAsString = value.ToString();
var (valid, result) = RegexUtils.MatchRegex(valueAsString, input.ToString());
if (valid)
{
return result;
}
}
if (input == null || value.Type != input.Type) if (input == null || value.Type != input.Type)
{ {
return false; return false;

View File

@@ -13,12 +13,12 @@ namespace WireMock.Matchers;
/// </summary> /// </summary>
public class JsonMatcher : IValueMatcher, IIgnoreCaseMatcher public class JsonMatcher : IValueMatcher, IIgnoreCaseMatcher
{ {
/// <inheritdoc cref="IValueMatcher.Value"/>
public object Value { get; }
/// <inheritdoc cref="IMatcher.Name"/> /// <inheritdoc cref="IMatcher.Name"/>
public virtual string Name => "JsonMatcher"; public virtual string Name => "JsonMatcher";
/// <inheritdoc cref="IValueMatcher.Value"/>
public object Value { get; }
/// <inheritdoc cref="IMatcher.MatchBehaviour"/> /// <inheritdoc cref="IMatcher.MatchBehaviour"/>
public MatchBehaviour MatchBehaviour { get; } public MatchBehaviour MatchBehaviour { get; }

View File

@@ -9,20 +9,20 @@ public class JsonPartialMatcher : AbstractJsonPartialMatcher
public override string Name => nameof(JsonPartialMatcher); public override string Name => nameof(JsonPartialMatcher);
/// <inheritdoc /> /// <inheritdoc />
public JsonPartialMatcher(string value, bool ignoreCase = false, bool throwException = false) public JsonPartialMatcher(string value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(value, ignoreCase, throwException) : base(value, ignoreCase, throwException, regex)
{ {
} }
/// <inheritdoc /> /// <inheritdoc />
public JsonPartialMatcher(object value, bool ignoreCase = false, bool throwException = false) public JsonPartialMatcher(object value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(value, ignoreCase, throwException) : base(value, ignoreCase, throwException, regex)
{ {
} }
/// <inheritdoc /> /// <inheritdoc />
public JsonPartialMatcher(MatchBehaviour matchBehaviour, object value, bool ignoreCase = false, bool throwException = false) public JsonPartialMatcher(MatchBehaviour matchBehaviour, object value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(matchBehaviour, value, ignoreCase, throwException) : base(matchBehaviour, value, ignoreCase, throwException, regex)
{ {
} }

View File

@@ -1,5 +1,3 @@
using JetBrains.Annotations;
namespace WireMock.Matchers; namespace WireMock.Matchers;
/// <summary> /// <summary>
@@ -11,20 +9,20 @@ public class JsonPartialWildcardMatcher : AbstractJsonPartialMatcher
public override string Name => nameof(JsonPartialWildcardMatcher); public override string Name => nameof(JsonPartialWildcardMatcher);
/// <inheritdoc /> /// <inheritdoc />
public JsonPartialWildcardMatcher(string value, bool ignoreCase = false, bool throwException = false) public JsonPartialWildcardMatcher(string value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(value, ignoreCase, throwException) : base(value, ignoreCase, throwException, regex)
{ {
} }
/// <inheritdoc /> /// <inheritdoc />
public JsonPartialWildcardMatcher(object value, bool ignoreCase = false, bool throwException = false) public JsonPartialWildcardMatcher(object value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(value, ignoreCase, throwException) : base(value, ignoreCase, throwException, regex)
{ {
} }
/// <inheritdoc /> /// <inheritdoc />
public JsonPartialWildcardMatcher(MatchBehaviour matchBehaviour, object value, bool ignoreCase = false, bool throwException = false) public JsonPartialWildcardMatcher(MatchBehaviour matchBehaviour, object value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(matchBehaviour, value, ignoreCase, throwException) : base(matchBehaviour, value, ignoreCase, throwException, regex)
{ {
} }

View File

@@ -23,7 +23,7 @@ public class RequestMessageHeaderMatcher : IRequestMatcher
/// <summary> /// <summary>
/// The name /// The name
/// </summary> /// </summary>
public string? Name { get; } public string Name { get; }
/// <value> /// <value>
/// The matchers. /// The matchers.
@@ -94,6 +94,7 @@ public class RequestMessageHeaderMatcher : IRequestMatcher
public RequestMessageHeaderMatcher(params Func<IDictionary<string, string[]>, bool>[] funcs) public RequestMessageHeaderMatcher(params Func<IDictionary<string, string[]>, bool>[] funcs)
{ {
Funcs = Guard.NotNull(funcs); Funcs = Guard.NotNull(funcs);
Name = string.Empty; // Not used when Func, but set to a non-null valid value.
} }
/// <inheritdoc /> /// <inheritdoc />
@@ -121,7 +122,7 @@ public class RequestMessageHeaderMatcher : IRequestMatcher
if (Matchers != null) if (Matchers != null)
{ {
if (!headers.ContainsKey(Name!)) if (!headers.ContainsKey(Name))
{ {
return MatchBehaviourHelper.Convert(_matchBehaviour, MatchScores.Mismatch); return MatchBehaviourHelper.Convert(_matchBehaviour, MatchScores.Mismatch);
} }
@@ -129,7 +130,7 @@ public class RequestMessageHeaderMatcher : IRequestMatcher
var results = new List<double>(); var results = new List<double>();
foreach (var matcher in Matchers) foreach (var matcher in Matchers)
{ {
var resultsPerMatcher = headers[Name!].Select(v => matcher.IsMatch(v)).ToArray(); var resultsPerMatcher = headers[Name].Select(v => matcher.IsMatch(v)).ToArray();
results.Add(MatchScores.ToScore(resultsPerMatcher, MatchOperator.And)); results.Add(MatchScores.ToScore(resultsPerMatcher, MatchOperator.And));
} }

View File

@@ -92,7 +92,7 @@ public class RequestMessageParamMatcher : IRequestMatcher
return MatchScores.ToScore(requestMessage.Query != null && Funcs.Any(f => f(requestMessage.Query))); return MatchScores.ToScore(requestMessage.Query != null && Funcs.Any(f => f(requestMessage.Query)));
} }
WireMockList<string> valuesPresentInRequestMessage = ((RequestMessage)requestMessage).GetParameter(Key, IgnoreCase ?? false); var valuesPresentInRequestMessage = ((RequestMessage)requestMessage).GetParameter(Key!, IgnoreCase ?? false);
if (valuesPresentInRequestMessage == null) if (valuesPresentInRequestMessage == null)
{ {
// Key is not present at all, just return Mismatch // Key is not present at all, just return Mismatch
@@ -102,7 +102,7 @@ public class RequestMessageParamMatcher : IRequestMatcher
if (Matchers != null && Matchers.Any()) if (Matchers != null && Matchers.Any())
{ {
// Return the score based on Matchers and valuesPresentInRequestMessage // Return the score based on Matchers and valuesPresentInRequestMessage
return CalculateScore(valuesPresentInRequestMessage); return CalculateScore(Matchers, valuesPresentInRequestMessage);
} }
if (Matchers == null || !Matchers.Any()) if (Matchers == null || !Matchers.Any())
@@ -114,14 +114,14 @@ public class RequestMessageParamMatcher : IRequestMatcher
return MatchScores.Mismatch; return MatchScores.Mismatch;
} }
private double CalculateScore(WireMockList<string> valuesPresentInRequestMessage) private double CalculateScore(IReadOnlyList<IStringMatcher> matchers, WireMockList<string> valuesPresentInRequestMessage)
{ {
var total = new List<double>(); var total = new List<double>();
// If the total patterns in all matchers > values in message, use the matcher as base // If the total patterns in all matchers > values in message, use the matcher as base
if (Matchers.Sum(m => m.GetPatterns().Length) > valuesPresentInRequestMessage.Count) if (matchers.Sum(m => m.GetPatterns().Length) > valuesPresentInRequestMessage.Count)
{ {
foreach (var matcher in Matchers) foreach (var matcher in matchers)
{ {
double score = 0d; double score = 0d;
foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage) foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage)
@@ -136,7 +136,7 @@ public class RequestMessageParamMatcher : IRequestMatcher
{ {
foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage) foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage)
{ {
double score = Matchers.Max(m => m.IsMatch(valuePresentInRequestMessage)); double score = matchers.Max(m => m.IsMatch(valuePresentInRequestMessage));
total.Add(score); total.Add(score);
} }
} }

View File

@@ -3,88 +3,87 @@ using System.Collections.Generic;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Stef.Validation; using Stef.Validation;
namespace WireMock.RegularExpressions namespace WireMock.RegularExpressions;
/// <summary>
/// Extension to the <see cref="Regex"/> object, adding support for GUID tokens for matching on.
/// </summary>
#if !NETSTANDARD1_3
[Serializable]
#endif
internal class RegexExtended : Regex
{ {
/// <summary> /// <inheritdoc cref="Regex"/>
/// Extension to the <see cref="Regex"/> object, adding support for GUID tokens for matching on. public RegexExtended(string pattern) : this(pattern, RegexOptions.None)
/// </summary>
#if !NETSTANDARD1_3
[Serializable]
#endif
internal class RegexExtended : Regex
{ {
/// <inheritdoc cref="Regex"/> }
public RegexExtended(string pattern) : this(pattern, RegexOptions.None)
{
}
/// <inheritdoc cref="Regex"/> /// <inheritdoc cref="Regex"/>
public RegexExtended(string pattern, RegexOptions options) : public RegexExtended(string pattern, RegexOptions options) :
this(pattern, options, Regex.InfiniteMatchTimeout) this(pattern, options, Regex.InfiniteMatchTimeout)
{ {
} }
/// <inheritdoc cref="Regex"/> /// <inheritdoc cref="Regex"/>
public RegexExtended(string pattern, RegexOptions options, TimeSpan matchTimeout) : public RegexExtended(string pattern, RegexOptions options, TimeSpan matchTimeout) :
base(ReplaceGuidPattern(pattern), options, matchTimeout) base(ReplaceGuidPattern(pattern), options, matchTimeout)
{ {
} }
#if !NETSTANDARD1_3 #if !NETSTANDARD1_3
/// <inheritdoc cref="Regex"/> /// <inheritdoc cref="Regex"/>
protected RegexExtended(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : protected RegexExtended(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) :
base(info, context) base(info, context)
{ {
} }
#endif #endif
// Dictionary of various Guid tokens with a corresponding regular expression pattern to use instead. // Dictionary of various Guid tokens with a corresponding regular expression pattern to use instead.
private static readonly Dictionary<string, string> GuidTokenPatterns = new Dictionary<string, string> private static readonly Dictionary<string, string> GuidTokenPatterns = new()
{
// Lower case format `B` Guid pattern
{ @"\guidb", @"(\{[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\})" },
// Upper case format `B` Guid pattern
{ @"\GUIDB", @"(\{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}\})" },
// Lower case format `D` Guid pattern
{ @"\guidd", "([a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12})" },
// Upper case format `D` Guid pattern
{ @"\GUIDD", "([A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12})" },
// Lower case format `N` Guid pattern
{ @"\guidn", "([a-z0-9]{32})" },
// Upper case format `N` Guid pattern
{ @"\GUIDN", "([A-Z0-9]{32})" },
// Lower case format `P` Guid pattern
{ @"\guidp", @"(\([a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\))" },
// Upper case format `P` Guid pattern
{ @"\GUIDP", @"(\([A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}\))" },
// Lower case format `X` Guid pattern
{ @"\guidx", @"(\{0x[a-f0-9]{8},0x[a-f0-9]{4},0x[a-f0-9]{4},\{(0x[a-f0-9]{2},){7}(0x[a-f0-9]{2})\}\})" },
// Upper case format `X` Guid pattern
{ @"\GUIDX", @"(\{0x[A-F0-9]{8},0x[A-F0-9]{4},0x[A-F0-9]{4},\{(0x[A-F0-9]{2},){7}(0x[A-F0-9]{2})\}\})" },
};
/// <summary>
/// Replaces all instances of valid GUID tokens with the correct regular expression to match.
/// </summary>
/// <param name="pattern">Pattern to replace token for.</param>
private static string ReplaceGuidPattern(string pattern)
{
Guard.NotNull(pattern, nameof(pattern));
foreach (var tokenPattern in GuidTokenPatterns)
{ {
// Lower case format `B` Guid pattern pattern = pattern.Replace(tokenPattern.Key, tokenPattern.Value);
{ @"\guidb", @"(\{[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\})" },
// Upper case format `B` Guid pattern
{ @"\GUIDB", @"(\{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}\})" },
// Lower case format `D` Guid pattern
{ @"\guidd", "([a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12})" },
// Upper case format `D` Guid pattern
{ @"\GUIDD", "([A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12})" },
// Lower case format `N` Guid pattern
{ @"\guidn", "([a-z0-9]{32})" },
// Upper case format `N` Guid pattern
{ @"\GUIDN", "([A-Z0-9]{32})" },
// Lower case format `P` Guid pattern
{ @"\guidp", @"(\([a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\))" },
// Upper case format `P` Guid pattern
{ @"\GUIDP", @"(\([A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}\))" },
// Lower case format `X` Guid pattern
{ @"\guidx", @"(\{0x[a-f0-9]{8},0x[a-f0-9]{4},0x[a-f0-9]{4},\{(0x[a-f0-9]{2},){7}(0x[a-f0-9]{2})\}\})" },
// Upper case format `X` Guid pattern
{ @"\GUIDX", @"(\{0x[A-F0-9]{8},0x[A-F0-9]{4},0x[A-F0-9]{4},\{(0x[A-F0-9]{2},){7}(0x[A-F0-9]{2})\}\})" },
};
/// <summary>
/// Replaces all instances of valid GUID tokens with the correct regular expression to match.
/// </summary>
/// <param name="pattern">Pattern to replace token for.</param>
private static string ReplaceGuidPattern(string pattern)
{
Guard.NotNull(pattern, nameof(pattern));
foreach (var tokenPattern in GuidTokenPatterns)
{
pattern = pattern.Replace(tokenPattern.Key, tokenPattern.Value);
}
return pattern;
} }
return pattern;
} }
} }

View File

@@ -1,159 +1,157 @@
// This source file is based on mock4net by Alexandre Victoor which is licensed under the Apache 2.0 License. // This source file is based on mock4net by Alexandre Victoor which is licensed under the Apache 2.0 License.
// For more details see 'mock4net/LICENSE.txt' and 'mock4net/readme.md' in this project root. // For more details see 'mock4net/LICENSE.txt' and 'mock4net/readme.md' in this project root.
using JetBrains.Annotations;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using Stef.Validation;
using WireMock.Models; using WireMock.Models;
using WireMock.Types; using WireMock.Types;
using WireMock.Util; using WireMock.Util;
using Stef.Validation;
namespace WireMock namespace WireMock;
/// <summary>
/// The RequestMessage.
/// </summary>
public class RequestMessage : IRequestMessage
{ {
/// <inheritdoc cref="IRequestMessage.ClientIP" />
public string ClientIP { get; }
/// <inheritdoc cref="IRequestMessage.Url" />
public string Url { get; }
/// <inheritdoc cref="IRequestMessage.AbsoluteUrl" />
public string AbsoluteUrl { get; }
/// <inheritdoc cref="IRequestMessage.ProxyUrl" />
public string ProxyUrl { get; set; }
/// <inheritdoc cref="IRequestMessage.DateTime" />
public DateTime DateTime { get; set; }
/// <inheritdoc cref="IRequestMessage.Path" />
public string Path { get; }
/// <inheritdoc cref="IRequestMessage.AbsolutePath" />
public string AbsolutePath { get; }
/// <inheritdoc cref="IRequestMessage.PathSegments" />
public string[] PathSegments { get; }
/// <inheritdoc cref="IRequestMessage.AbsolutePathSegments" />
public string[] AbsolutePathSegments { get; }
/// <inheritdoc cref="IRequestMessage.Method" />
public string Method { get; }
/// <inheritdoc cref="IRequestMessage.Headers" />
public IDictionary<string, WireMockList<string>>? Headers { get; }
/// <inheritdoc cref="IRequestMessage.Cookies" />
public IDictionary<string, string>? Cookies { get; }
/// <inheritdoc cref="IRequestMessage.Query" />
public IDictionary<string, WireMockList<string>>? Query { get; }
/// <inheritdoc cref="IRequestMessage.RawQuery" />
public string RawQuery { get; }
/// <inheritdoc cref="IRequestMessage.BodyData" />
public IBodyData? BodyData { get; }
/// <inheritdoc cref="IRequestMessage.Body" />
public string Body { get; }
/// <inheritdoc cref="IRequestMessage.BodyAsJson" />
public object BodyAsJson { get; }
/// <inheritdoc cref="IRequestMessage.BodyAsBytes" />
public byte[] BodyAsBytes { get; }
/// <inheritdoc cref="IRequestMessage.DetectedBodyType" />
public string DetectedBodyType { get; }
/// <inheritdoc cref="IRequestMessage.DetectedBodyTypeFromContentType" />
public string DetectedBodyTypeFromContentType { get; }
/// <inheritdoc cref="IRequestMessage.DetectedCompression" />
public string DetectedCompression { get; }
/// <inheritdoc cref="IRequestMessage.Host" />
public string Host { get; }
/// <inheritdoc cref="IRequestMessage.Protocol" />
public string Protocol { get; }
/// <inheritdoc cref="IRequestMessage.Port" />
public int Port { get; }
/// <inheritdoc cref="IRequestMessage.Origin" />
public string Origin { get; }
/// <summary> /// <summary>
/// The RequestMessage. /// Initializes a new instance of the <see cref="RequestMessage"/> class.
/// </summary> /// </summary>
public class RequestMessage : IRequestMessage /// <param name="urlDetails">The original url details.</param>
/// <param name="method">The HTTP method.</param>
/// <param name="clientIP">The client IP Address.</param>
/// <param name="bodyData">The BodyData.</param>
/// <param name="headers">The headers.</param>
/// <param name="cookies">The cookies.</param>
public RequestMessage(UrlDetails urlDetails, string method, string clientIP, IBodyData? bodyData = null, IDictionary<string, string[]>? headers = null, IDictionary<string, string>? cookies = null)
{ {
/// <inheritdoc cref="IRequestMessage.ClientIP" /> Guard.NotNull(urlDetails, nameof(urlDetails));
public string ClientIP { get; } Guard.NotNull(method, nameof(method));
Guard.NotNull(clientIP, nameof(clientIP));
/// <inheritdoc cref="IRequestMessage.Url" /> AbsoluteUrl = urlDetails.AbsoluteUrl.ToString();
public string Url { get; } Url = urlDetails.Url.ToString();
Protocol = urlDetails.Url.Scheme;
Host = urlDetails.Url.Host;
Port = urlDetails.Url.Port;
Origin = $"{Protocol}://{Host}:{Port}";
/// <inheritdoc cref="IRequestMessage.AbsoluteUrl" /> AbsolutePath = WebUtility.UrlDecode(urlDetails.AbsoluteUrl.AbsolutePath);
public string AbsoluteUrl { get; } Path = WebUtility.UrlDecode(urlDetails.Url.AbsolutePath);
PathSegments = Path.Split('/').Skip(1).ToArray();
AbsolutePathSegments = AbsolutePath.Split('/').Skip(1).ToArray();
/// <inheritdoc cref="IRequestMessage.ProxyUrl" /> Method = method;
public string ProxyUrl { get; set; } ClientIP = clientIP;
/// <inheritdoc cref="IRequestMessage.DateTime" /> BodyData = bodyData;
public DateTime DateTime { get; set; }
/// <inheritdoc cref="IRequestMessage.Path" /> // Convenience getters for e.g. Handlebars
public string Path { get; } Body = BodyData?.BodyAsString;
BodyAsJson = BodyData?.BodyAsJson;
BodyAsBytes = BodyData?.BodyAsBytes;
DetectedBodyType = BodyData?.DetectedBodyType.ToString();
DetectedBodyTypeFromContentType = BodyData?.DetectedBodyTypeFromContentType.ToString();
DetectedCompression = BodyData?.DetectedCompression;
/// <inheritdoc cref="IRequestMessage.AbsolutePath" /> Headers = headers?.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value));
public string AbsolutePath { get; } Cookies = cookies;
RawQuery = urlDetails.Url.Query;
Query = QueryStringParser.Parse(RawQuery);
}
/// <inheritdoc cref="IRequestMessage.PathSegments" /> /// <summary>
public string[] PathSegments { get; } /// Get a query parameter.
/// </summary>
/// <inheritdoc cref="IRequestMessage.AbsolutePathSegments" /> /// <param name="key">The key.</param>
public string[] AbsolutePathSegments { get; } /// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <returns>The query parameter.</returns>
/// <inheritdoc cref="IRequestMessage.Method" /> public WireMockList<string>? GetParameter(string key, bool ignoreCase = false)
public string Method { get; } {
if (Query == null)
/// <inheritdoc cref="IRequestMessage.Headers" />
public IDictionary<string, WireMockList<string>>? Headers { get; }
/// <inheritdoc cref="IRequestMessage.Cookies" />
public IDictionary<string, string>? Cookies { get; }
/// <inheritdoc cref="IRequestMessage.Query" />
public IDictionary<string, WireMockList<string>>? Query { get; }
/// <inheritdoc cref="IRequestMessage.RawQuery" />
public string RawQuery { get; }
/// <inheritdoc cref="IRequestMessage.BodyData" />
public IBodyData? BodyData { get; }
/// <inheritdoc cref="IRequestMessage.Body" />
public string Body { get; }
/// <inheritdoc cref="IRequestMessage.BodyAsJson" />
public object BodyAsJson { get; }
/// <inheritdoc cref="IRequestMessage.BodyAsBytes" />
public byte[] BodyAsBytes { get; }
/// <inheritdoc cref="IRequestMessage.DetectedBodyType" />
public string DetectedBodyType { get; }
/// <inheritdoc cref="IRequestMessage.DetectedBodyTypeFromContentType" />
public string DetectedBodyTypeFromContentType { get; }
/// <inheritdoc cref="IRequestMessage.DetectedCompression" />
public string DetectedCompression { get; }
/// <inheritdoc cref="IRequestMessage.Host" />
public string Host { get; }
/// <inheritdoc cref="IRequestMessage.Protocol" />
public string Protocol { get; }
/// <inheritdoc cref="IRequestMessage.Port" />
public int Port { get; }
/// <inheritdoc cref="IRequestMessage.Origin" />
public string Origin { get; }
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessage"/> class.
/// </summary>
/// <param name="urlDetails">The original url details.</param>
/// <param name="method">The HTTP method.</param>
/// <param name="clientIP">The client IP Address.</param>
/// <param name="bodyData">The BodyData.</param>
/// <param name="headers">The headers.</param>
/// <param name="cookies">The cookies.</param>
public RequestMessage(UrlDetails urlDetails, string method, string clientIP, IBodyData? bodyData = null, IDictionary<string, string[]>? headers = null, IDictionary<string, string>? cookies = null)
{ {
Guard.NotNull(urlDetails, nameof(urlDetails)); return null;
Guard.NotNull(method, nameof(method));
Guard.NotNull(clientIP, nameof(clientIP));
AbsoluteUrl = urlDetails.AbsoluteUrl.ToString();
Url = urlDetails.Url.ToString();
Protocol = urlDetails.Url.Scheme;
Host = urlDetails.Url.Host;
Port = urlDetails.Url.Port;
Origin = $"{Protocol}://{Host}:{Port}";
AbsolutePath = WebUtility.UrlDecode(urlDetails.AbsoluteUrl.AbsolutePath);
Path = WebUtility.UrlDecode(urlDetails.Url.AbsolutePath);
PathSegments = Path.Split('/').Skip(1).ToArray();
AbsolutePathSegments = AbsolutePath.Split('/').Skip(1).ToArray();
Method = method;
ClientIP = clientIP;
BodyData = bodyData;
// Convenience getters for e.g. Handlebars
Body = BodyData?.BodyAsString;
BodyAsJson = BodyData?.BodyAsJson;
BodyAsBytes = BodyData?.BodyAsBytes;
DetectedBodyType = BodyData?.DetectedBodyType.ToString();
DetectedBodyTypeFromContentType = BodyData?.DetectedBodyTypeFromContentType.ToString();
DetectedCompression = BodyData?.DetectedCompression;
Headers = headers?.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value));
Cookies = cookies;
RawQuery = urlDetails.Url.Query;
Query = QueryStringParser.Parse(RawQuery);
} }
/// <summary> var query = !ignoreCase ? Query : new Dictionary<string, WireMockList<string>>(Query, StringComparer.OrdinalIgnoreCase);
/// Get a query parameter.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <returns>The query parameter.</returns>
public WireMockList<string>? GetParameter(string? key, bool ignoreCase = false)
{
if (Query == null)
{
return null;
}
var query = !ignoreCase ? Query : new Dictionary<string, WireMockList<string>>(Query, StringComparer.OrdinalIgnoreCase); return query.ContainsKey(key) ? query[key] : null;
return query.ContainsKey(key) ? query[key] : null;
}
} }
} }

View File

@@ -47,6 +47,7 @@ internal class MatcherMapper
bool ignoreCase = matcher.IgnoreCase == true; bool ignoreCase = matcher.IgnoreCase == true;
bool throwExceptionWhenMatcherFails = _settings.ThrowExceptionWhenMatcherFails == true; bool throwExceptionWhenMatcherFails = _settings.ThrowExceptionWhenMatcherFails == true;
bool useRegexExtended = _settings.UseRegexExtended == true; bool useRegexExtended = _settings.UseRegexExtended == true;
bool useRegex = matcher.Regex == true;
switch (matcherName) switch (matcherName)
{ {
@@ -79,11 +80,11 @@ internal class MatcherMapper
case nameof(JsonPartialMatcher): case nameof(JsonPartialMatcher):
var valueForJsonPartialMatcher = matcher.Pattern ?? matcher.Patterns; var valueForJsonPartialMatcher = matcher.Pattern ?? matcher.Patterns;
return new JsonPartialMatcher(matchBehaviour, valueForJsonPartialMatcher!, ignoreCase, throwExceptionWhenMatcherFails); return new JsonPartialMatcher(matchBehaviour, valueForJsonPartialMatcher!, ignoreCase, throwExceptionWhenMatcherFails, useRegex);
case nameof(JsonPartialWildcardMatcher): case nameof(JsonPartialWildcardMatcher):
var valueForJsonPartialWildcardMatcher = matcher.Pattern ?? matcher.Patterns; var valueForJsonPartialWildcardMatcher = matcher.Pattern ?? matcher.Patterns;
return new JsonPartialWildcardMatcher(matchBehaviour, valueForJsonPartialWildcardMatcher!, ignoreCase, throwExceptionWhenMatcherFails); return new JsonPartialWildcardMatcher(matchBehaviour, valueForJsonPartialWildcardMatcher!, ignoreCase, throwExceptionWhenMatcherFails, useRegex);
case nameof(JsonPathMatcher): case nameof(JsonPathMatcher):
return new JsonPathMatcher(matchBehaviour, throwExceptionWhenMatcherFails, matchOperator, stringPatterns); return new JsonPathMatcher(matchBehaviour, throwExceptionWhenMatcherFails, matchOperator, stringPatterns);
@@ -146,6 +147,17 @@ internal class MatcherMapper
Name = matcher.Name Name = matcher.Name
}; };
switch (matcher)
{
case JsonPartialMatcher jsonPartialMatcher:
model.Regex = jsonPartialMatcher.Regex;
break;
case JsonPartialWildcardMatcher jsonPartialWildcardMatcher:
model.Regex = jsonPartialWildcardMatcher.Regex;
break;
}
switch (matcher) switch (matcher)
{ {
// If the matcher is a IStringMatcher, get the operator & patterns. // If the matcher is a IStringMatcher, get the operator & patterns.

View File

@@ -293,7 +293,7 @@ public partial class WireMockServer
private IResponseMessage SettingsUpdate(IRequestMessage requestMessage) private IResponseMessage SettingsUpdate(IRequestMessage requestMessage)
{ {
var settings = DeserializeObject<SettingsModel>(requestMessage); var settings = DeserializeObject<SettingsModel>(requestMessage)!;
// _settings // _settings
_settings.AllowBodyForAllHttpMethods = settings.AllowBodyForAllHttpMethods; _settings.AllowBodyForAllHttpMethods = settings.AllowBodyForAllHttpMethods;

View File

@@ -9,9 +9,9 @@ using WireMock.Handlers;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.RegularExpressions; using WireMock.RegularExpressions;
using WireMock.Types;
#if USE_ASPNETCORE #if USE_ASPNETCORE
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using WireMock.Types;
#endif #endif
namespace WireMock.Settings namespace WireMock.Settings

View File

@@ -1,24 +1,53 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using WireMock.RegularExpressions;
namespace WireMock.Util namespace WireMock.Util;
internal static class RegexUtils
{ {
internal static class RegexUtils private static readonly TimeSpan RegexTimeOut = new(0, 0, 10);
public static Dictionary<string, string> GetNamedGroups(Regex regex, string input)
{ {
public static Dictionary<string, string> GetNamedGroups(Regex regex, string input) var namedGroupsDictionary = new Dictionary<string, string>();
GroupCollection groups = regex.Match(input).Groups;
foreach (string groupName in regex.GetGroupNames())
{ {
var namedGroupsDictionary = new Dictionary<string, string>(); if (groups[groupName].Captures.Count > 0)
GroupCollection groups = regex.Match(input).Groups;
foreach (string groupName in regex.GetGroupNames())
{ {
if (groups[groupName].Captures.Count > 0) namedGroupsDictionary.Add(groupName, groups[groupName].Value);
{
namedGroupsDictionary.Add(groupName, groups[groupName].Value);
}
} }
}
return namedGroupsDictionary; return namedGroupsDictionary;
}
public static (bool IsValid, bool Result) MatchRegex(string pattern, string input, bool useRegexExtended = true)
{
if (string.IsNullOrEmpty(pattern))
{
return (false, false);
}
try
{
if (useRegexExtended)
{
var r = new RegexExtended(pattern, RegexOptions.None, RegexTimeOut);
return (true, r.IsMatch(input));
}
else
{
var r = new Regex(pattern, RegexOptions.None, RegexTimeOut);
return (true, r.IsMatch(input));
}
}
catch
{
return (false, false);
} }
} }
} }

View File

@@ -1,5 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using FluentAssertions; using FluentAssertions;
using Newtonsoft.Json; using Newtonsoft.Json;
@@ -42,6 +41,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialMatcher_WithInvalidStringValue_Should_ThrowException() public void JsonPartialMatcher_WithInvalidStringValue_Should_ThrowException()
{ {
// Act // Act
// ReSharper disable once ObjectCreationAsStatement
Action action = () => new JsonPartialMatcher(MatchBehaviour.AcceptOnMatch, "{ \"Id\""); Action action = () => new JsonPartialMatcher(MatchBehaviour.AcceptOnMatch, "{ \"Id\"");
// Assert // Assert
@@ -52,6 +52,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialMatcher_WithInvalidObjectValue_Should_ThrowException() public void JsonPartialMatcher_WithInvalidObjectValue_Should_ThrowException()
{ {
// Act // Act
// ReSharper disable once ObjectCreationAsStatement
Action action = () => new JsonPartialMatcher(MatchBehaviour.AcceptOnMatch, new MemoryStream()); Action action = () => new JsonPartialMatcher(MatchBehaviour.AcceptOnMatch, new MemoryStream());
// Assert // Assert
@@ -102,7 +103,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialMatcher_IsMatch_NullString() public void JsonPartialMatcher_IsMatch_NullString()
{ {
// Assign // Assign
string s = null; string? s = null;
var matcher = new JsonPartialMatcher(""); var matcher = new JsonPartialMatcher("");
// Act // Act
@@ -116,7 +117,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialMatcher_IsMatch_NullObject() public void JsonPartialMatcher_IsMatch_NullObject()
{ {
// Assign // Assign
object o = null; object? o = null;
var matcher = new JsonPartialMatcher(""); var matcher = new JsonPartialMatcher("");
// Act // Act
@@ -151,17 +152,53 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher(new { Id = 1, Name = "Test" }); var matcher = new JsonPartialMatcher(new { Id = 1, Name = "Test" });
// Act // Act
var jobject = new JObject var jObject = new JObject
{ {
{ "Id", new JValue(1) }, { "Id", new JValue(1) },
{ "Name", new JValue("Test") } { "Name", new JValue("Test") }
}; };
double match = matcher.IsMatch(jobject); double match = matcher.IsMatch(jObject);
// Assert // Assert
Assert.Equal(1.0, match); Assert.Equal(1.0, match);
} }
[Fact]
public void JsonPartialMatcher_IsMatch_WithRegexTrue()
{
// Assign
var matcher = new JsonPartialMatcher(new { Id = "^\\d+$", Name = "Test" }, false, false, true);
// Act
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialMatcher_IsMatch_WithRegexFalse()
{
// Assign
var matcher = new JsonPartialMatcher(new { Id = "^\\d+$", Name = "Test" });
// Act
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(0.0, match);
}
[Fact] [Fact]
public void JsonPartialMatcher_IsMatch_WithIgnoreCaseTrue_JObject() public void JsonPartialMatcher_IsMatch_WithIgnoreCaseTrue_JObject()
{ {
@@ -169,12 +206,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher(new { id = 1, Name = "test" }, true); var matcher = new JsonPartialMatcher(new { id = 1, Name = "test" }, true);
// Act // Act
var jobject = new JObject var jObject = new JObject
{ {
{ "Id", new JValue(1) }, { "Id", new JValue(1) },
{ "NaMe", new JValue("Test") } { "NaMe", new JValue("Test") }
}; };
double match = matcher.IsMatch(jobject); double match = matcher.IsMatch(jObject);
// Assert // Assert
Assert.Equal(1.0, match); Assert.Equal(1.0, match);
@@ -187,8 +224,8 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher(new { Id = 1, Name = "Test" }); var matcher = new JsonPartialMatcher(new { Id = 1, Name = "Test" });
// Act // Act
var jobject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }"); var jObject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jobject); double match = matcher.IsMatch(jObject);
// Assert // Assert
Assert.Equal(1.0, match); Assert.Equal(1.0, match);
@@ -201,8 +238,8 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher(new { Id = 1, Name = "TESt" }, true); var matcher = new JsonPartialMatcher(new { Id = 1, Name = "TESt" }, true);
// Act // Act
var jobject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }"); var jObject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jobject); double match = matcher.IsMatch(jObject);
// Assert // Assert
Assert.Equal(1.0, match); Assert.Equal(1.0, match);
@@ -233,12 +270,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher("{ \"Id\" : 1, \"Name\" : \"Test\" }"); var matcher = new JsonPartialMatcher("{ \"Id\" : 1, \"Name\" : \"Test\" }");
// Act // Act
var jobject = new JObject var jObject = new JObject
{ {
{ "Id", new JValue(1) }, { "Id", new JValue(1) },
{ "Name", new JValue("Test") } { "Name", new JValue("Test") }
}; };
double match = matcher.IsMatch(jobject); double match = matcher.IsMatch(jObject);
// Assert // Assert
Assert.Equal(1.0, match); Assert.Equal(1.0, match);
@@ -251,12 +288,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher("{ \"Id\" : 1, \"Name\" : \"test\" }", true); var matcher = new JsonPartialMatcher("{ \"Id\" : 1, \"Name\" : \"test\" }", true);
// Act // Act
var jobject = new JObject var jObject = new JObject
{ {
{ "Id", new JValue(1) }, { "Id", new JValue(1) },
{ "Name", new JValue("Test") } { "Name", new JValue("Test") }
}; };
double match = matcher.IsMatch(jobject); double match = matcher.IsMatch(jObject);
// Assert // Assert
Assert.Equal(1.0, match); Assert.Equal(1.0, match);
@@ -269,12 +306,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher(MatchBehaviour.RejectOnMatch, "{ \"Id\" : 1, \"Name\" : \"Test\" }"); var matcher = new JsonPartialMatcher(MatchBehaviour.RejectOnMatch, "{ \"Id\" : 1, \"Name\" : \"Test\" }");
// Act // Act
var jobject = new JObject var jObject = new JObject
{ {
{ "Id", new JValue(1) }, { "Id", new JValue(1) },
{ "Name", new JValue("Test") } { "Name", new JValue("Test") }
}; };
double match = matcher.IsMatch(jobject); double match = matcher.IsMatch(jObject);
// Assert // Assert
Assert.Equal(0.0, match); Assert.Equal(0.0, match);
@@ -287,11 +324,11 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher("{ \"preferredAt\" : \"2019-11-21T10:32:53.2210009+00:00\" }"); var matcher = new JsonPartialMatcher("{ \"preferredAt\" : \"2019-11-21T10:32:53.2210009+00:00\" }");
// Act // Act
var jobject = new JObject var jObject = new JObject
{ {
{ "preferredAt", new JValue("2019-11-21T10:32:53.2210009+00:00") } { "preferredAt", new JValue("2019-11-21T10:32:53.2210009+00:00") }
}; };
double match = matcher.IsMatch(jobject); double match = matcher.IsMatch(jObject);
// Assert // Assert
Assert.Equal(1.0, match); Assert.Equal(1.0, match);

View File

@@ -1,5 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using FluentAssertions; using FluentAssertions;
using Newtonsoft.Json; using Newtonsoft.Json;
@@ -8,393 +7,394 @@ using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
public class JsonPartialWildcardMatcherTests
{ {
public class JsonPartialWildcardMatcherTests [Fact]
public void JsonPartialWildcardMatcher_GetName()
{ {
[Fact] // Assign
public void JsonPartialWildcardMatcher_GetName() var matcher = new JsonPartialWildcardMatcher("{}");
{
// Assign
var matcher = new JsonPartialWildcardMatcher("{}");
// Act // Act
string name = matcher.Name; string name = matcher.Name;
// Assert // Assert
Check.That(name).Equals("JsonPartialWildcardMatcher"); Check.That(name).Equals("JsonPartialWildcardMatcher");
}
[Fact]
public void JsonPartialWildcardMatcher_GetValue()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("{}");
// Act
object value = matcher.Value;
// Assert
Check.That(value).Equals("{}");
}
[Fact]
public void JsonPartialWildcardMatcher_WithInvalidStringValue_Should_ThrowException()
{
// Act
Action action = () => new JsonPartialWildcardMatcher(MatchBehaviour.AcceptOnMatch, "{ \"Id\"");
// Assert
action.Should().Throw<JsonException>();
}
[Fact]
public void JsonPartialWildcardMatcher_WithInvalidObjectValue_Should_ThrowException()
{
// Act
Action action = () => new JsonPartialWildcardMatcher(MatchBehaviour.AcceptOnMatch, new MemoryStream());
// Assert
action.Should().Throw<JsonException>();
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_WithInvalidValue_And_ThrowExceptionIsFalse_Should_ReturnMismatch()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("");
// Act
double match = matcher.IsMatch(new MemoryStream());
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_WithInvalidValue_And_ThrowExceptionIsTrue_Should_ReturnMismatch()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("", false, true);
// Act
Action action = () => matcher.IsMatch(new MemoryStream());
// Assert
action.Should().Throw<JsonException>();
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_ByteArray()
{
// Assign
var bytes = new byte[0];
var matcher = new JsonPartialWildcardMatcher("");
// Act
double match = matcher.IsMatch(bytes);
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_NullString()
{
// Assign
string s = null;
var matcher = new JsonPartialWildcardMatcher("");
// Act
double match = matcher.IsMatch(s);
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_NullObject()
{
// Assign
object o = null;
var matcher = new JsonPartialWildcardMatcher("");
// Act
double match = matcher.IsMatch(o);
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JArray()
{
// Assign
var matcher = new JsonPartialWildcardMatcher(new[] { "x", "y" });
// Act
var jArray = new JArray
{
"x",
"y"
};
double match = matcher.IsMatch(jArray);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JObject()
{
// Assign
var matcher = new JsonPartialWildcardMatcher(new { Id = 1, Name = "Test" });
// Act
var jobject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_WithIgnoreCaseTrue_JObject()
{
// Assign
var matcher = new JsonPartialWildcardMatcher(new { id = 1, Name = "test" }, true);
// Act
var jobject = new JObject
{
{ "Id", new JValue(1) },
{ "NaMe", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JObjectParsed()
{
// Assign
var matcher = new JsonPartialWildcardMatcher(new { Id = 1, Name = "Test" });
// Act
var jobject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jobject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_WithIgnoreCaseTrue_JObjectParsed()
{
// Assign
var matcher = new JsonPartialWildcardMatcher(new { Id = 1, Name = "TESt" }, true);
// Act
var jobject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jobject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JArrayAsString()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("[ \"x\", \"y\" ]");
// Act
var jArray = new JArray
{
"x",
"y"
};
double match = matcher.IsMatch(jArray);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JObjectAsString()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("{ \"Id\" : 1, \"Name\" : \"Test\" }");
// Act
var jobject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_WithIgnoreCaseTrue_JObjectAsString()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("{ \"Id\" : 1, \"Name\" : \"test\" }", true);
// Act
var jobject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JObjectAsString_RejectOnMatch()
{
// Assign
var matcher = new JsonPartialWildcardMatcher(MatchBehaviour.RejectOnMatch, "{ \"Id\" : 1, \"Name\" : \"Test\" }");
// Act
var jobject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
// Assert
Assert.Equal(0.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JObjectWithDateTimeOffsetAsString()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("{ \"preferredAt\" : \"2019-11-21T10:32:53.2210009+00:00\" }");
// Act
var jobject = new JObject
{
{ "preferredAt", new JValue("2019-11-21T10:32:53.2210009+00:00") }
};
double match = matcher.IsMatch(jobject);
// Assert
Assert.Equal(1.0, match);
}
[Theory]
[InlineData("{\"test\":\"abc\"}", "{\"test\":\"abc\",\"other\":\"xyz\"}")]
[InlineData("\"test\"", "\"test\"")]
[InlineData("123", "123")]
[InlineData("[\"test\"]", "[\"test\"]")]
[InlineData("[\"test\"]", "[\"test\", \"other\"]")]
[InlineData("[123]", "[123]")]
[InlineData("[123]", "[123, 456]")]
[InlineData("{ \"test\":\"value\" }", "{\"test\":\"value\",\"other\":123}")]
[InlineData("{ \"test\":\"value\" }", "{\"test\":\"value\"}")]
[InlineData("{\"test\":{\"nested\":\"value\"}}", "{\"test\":{\"nested\":\"value\"}}")]
public void JsonPartialWildcardMatcher_IsMatch_StringInput_IsValidMatch(string value, string input)
{
// Assign
var matcher = new JsonPartialWildcardMatcher(value);
// Act
double match = matcher.IsMatch(input);
// Assert
Assert.Equal(1.0, match);
}
[Theory]
[InlineData("{\"test\":\"*\"}", "{\"test\":\"xxx\",\"other\":\"xyz\"}")]
[InlineData("\"t*t\"", "\"test\"")]
public void JsonPartialWildcardMatcher_IsMatch_StringInputWithWildcard_IsValidMatch(string value, string input)
{
// Assign
var matcher = new JsonPartialWildcardMatcher(value);
// Act
double match = matcher.IsMatch(input);
// Assert
match.Should().Be(1.0);
}
[Theory]
[InlineData("\"test\"", null)]
[InlineData("\"test1\"", "\"test2\"")]
[InlineData("123", "1234")]
[InlineData("[\"test\"]", "[\"test1\"]")]
[InlineData("[\"test\"]", "[\"test1\", \"test2\"]")]
[InlineData("[123]", "[1234]")]
[InlineData("{}", "\"test\"")]
[InlineData("{ \"test\":\"value\" }", "{\"test\":\"value2\"}")]
[InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value1\"}}")]
[InlineData("{\"test\":{\"test1\":\"value\"}}", "{\"test\":{\"test1\":\"value1\"}}")]
[InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value1\"}}]")]
public void JsonPartialWildcardMatcher_IsMatch_StringInputWithInvalidMatch(string value, string input)
{
// Assign
var matcher = new JsonPartialWildcardMatcher(value);
// Act
double match = matcher.IsMatch(input);
// Assert
Assert.Equal(0.0, match);
}
[Theory]
[InlineData("{ \"test.nested\":123 }", "{\"test\":{\"nested\":123}}")]
[InlineData("{ \"test.nested\":[123, 456] }", "{\"test\":{\"nested\":[123, 456]}}")]
[InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value\"}}")]
[InlineData("{ \"['name.with.dot']\":\"value\" }", "{\"name.with.dot\":\"value\"}")]
[InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value\"}}]")]
[InlineData("[{ \"['name.with.dot']\":\"value\" }]", "[{\"name.with.dot\":\"value\"}]")]
public void JsonPartialWildcardMatcher_IsMatch_ValueAsJPathValidMatch(string value, string input)
{
// Assign
var matcher = new JsonPartialWildcardMatcher(value);
// Act
double match = matcher.IsMatch(input);
// Assert
Assert.Equal(1.0, match);
}
[Theory]
[InlineData("{ \"test.nested\":123 }", "{\"test\":{\"nested\":456}}")]
[InlineData("{ \"test.nested\":[123, 456] }", "{\"test\":{\"nested\":[1, 2]}}")]
[InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value1\"}}")]
[InlineData("{ \"['name.with.dot']\":\"value\" }", "{\"name.with.dot\":\"value1\"}")]
[InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value1\"}}]")]
[InlineData("[{ \"['name.with.dot']\":\"value\" }]", "[{\"name.with.dot\":\"value1\"}]")]
public void JsonPartialWildcardMatcher_IsMatch_ValueAsJPathInvalidMatch(string value, string input)
{
// Assign
var matcher = new JsonPartialWildcardMatcher(value);
// Act
double match = matcher.IsMatch(input);
// Assert
Assert.Equal(0.0, match);
}
} }
}
[Fact]
public void JsonPartialWildcardMatcher_GetValue()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("{}");
// Act
object value = matcher.Value;
// Assert
Check.That(value).Equals("{}");
}
[Fact]
public void JsonPartialWildcardMatcher_WithInvalidStringValue_Should_ThrowException()
{
// Act
// ReSharper disable once ObjectCreationAsStatement
Action action = () => new JsonPartialWildcardMatcher(MatchBehaviour.AcceptOnMatch, "{ \"Id\"");
// Assert
action.Should().Throw<JsonException>();
}
[Fact]
public void JsonPartialWildcardMatcher_WithInvalidObjectValue_Should_ThrowException()
{
// Act
// ReSharper disable once ObjectCreationAsStatement
Action action = () => new JsonPartialWildcardMatcher(MatchBehaviour.AcceptOnMatch, new MemoryStream());
// Assert
action.Should().Throw<JsonException>();
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_WithInvalidValue_And_ThrowExceptionIsFalse_Should_ReturnMismatch()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("");
// Act
double match = matcher.IsMatch(new MemoryStream());
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_WithInvalidValue_And_ThrowExceptionIsTrue_Should_ReturnMismatch()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("", false, true);
// Act
Action action = () => matcher.IsMatch(new MemoryStream());
// Assert
action.Should().Throw<JsonException>();
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_ByteArray()
{
// Assign
var bytes = new byte[0];
var matcher = new JsonPartialWildcardMatcher("");
// Act
double match = matcher.IsMatch(bytes);
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_NullString()
{
// Assign
string? s = null;
var matcher = new JsonPartialWildcardMatcher("");
// Act
double match = matcher.IsMatch(s);
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_NullObject()
{
// Assign
object? o = null;
var matcher = new JsonPartialWildcardMatcher("");
// Act
double match = matcher.IsMatch(o);
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JArray()
{
// Assign
var matcher = new JsonPartialWildcardMatcher(new[] { "x", "y" });
// Act
var jArray = new JArray
{
"x",
"y"
};
double match = matcher.IsMatch(jArray);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JObject()
{
// Assign
var matcher = new JsonPartialWildcardMatcher(new { Id = 1, Name = "Test" });
// Act
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_WithIgnoreCaseTrue_JObject()
{
// Assign
var matcher = new JsonPartialWildcardMatcher(new { id = 1, Name = "test" }, true);
// Act
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "NaMe", new JValue("Test") }
};
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JObjectParsed()
{
// Assign
var matcher = new JsonPartialWildcardMatcher(new { Id = 1, Name = "Test" });
// Act
var jObject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_WithIgnoreCaseTrue_JObjectParsed()
{
// Assign
var matcher = new JsonPartialWildcardMatcher(new { Id = 1, Name = "TESt" }, true);
// Act
var jObject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JArrayAsString()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("[ \"x\", \"y\" ]");
// Act
var jArray = new JArray
{
"x",
"y"
};
double match = matcher.IsMatch(jArray);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JObjectAsString()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("{ \"Id\" : 1, \"Name\" : \"Test\" }");
// Act
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_WithIgnoreCaseTrue_JObjectAsString()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("{ \"Id\" : 1, \"Name\" : \"test\" }", true);
// Act
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JObjectAsString_RejectOnMatch()
{
// Assign
var matcher = new JsonPartialWildcardMatcher(MatchBehaviour.RejectOnMatch, "{ \"Id\" : 1, \"Name\" : \"Test\" }");
// Act
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(0.0, match);
}
[Fact]
public void JsonPartialWildcardMatcher_IsMatch_JObjectWithDateTimeOffsetAsString()
{
// Assign
var matcher = new JsonPartialWildcardMatcher("{ \"preferredAt\" : \"2019-11-21T10:32:53.2210009+00:00\" }");
// Act
var jObject = new JObject
{
{ "preferredAt", new JValue("2019-11-21T10:32:53.2210009+00:00") }
};
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
}
[Theory]
[InlineData("{\"test\":\"abc\"}", "{\"test\":\"abc\",\"other\":\"xyz\"}")]
[InlineData("\"test\"", "\"test\"")]
[InlineData("123", "123")]
[InlineData("[\"test\"]", "[\"test\"]")]
[InlineData("[\"test\"]", "[\"test\", \"other\"]")]
[InlineData("[123]", "[123]")]
[InlineData("[123]", "[123, 456]")]
[InlineData("{ \"test\":\"value\" }", "{\"test\":\"value\",\"other\":123}")]
[InlineData("{ \"test\":\"value\" }", "{\"test\":\"value\"}")]
[InlineData("{\"test\":{\"nested\":\"value\"}}", "{\"test\":{\"nested\":\"value\"}}")]
public void JsonPartialWildcardMatcher_IsMatch_StringInput_IsValidMatch(string value, string input)
{
// Assign
var matcher = new JsonPartialWildcardMatcher(value);
// Act
double match = matcher.IsMatch(input);
// Assert
Assert.Equal(1.0, match);
}
[Theory]
[InlineData("{\"test\":\"*\"}", "{\"test\":\"xxx\",\"other\":\"xyz\"}")]
[InlineData("\"t*t\"", "\"test\"")]
public void JsonPartialWildcardMatcher_IsMatch_StringInputWithWildcard_IsValidMatch(string value, string input)
{
// Assign
var matcher = new JsonPartialWildcardMatcher(value);
// Act
double match = matcher.IsMatch(input);
// Assert
match.Should().Be(1.0);
}
[Theory]
[InlineData("\"test\"", null)]
[InlineData("\"test1\"", "\"test2\"")]
[InlineData("123", "1234")]
[InlineData("[\"test\"]", "[\"test1\"]")]
[InlineData("[\"test\"]", "[\"test1\", \"test2\"]")]
[InlineData("[123]", "[1234]")]
[InlineData("{}", "\"test\"")]
[InlineData("{ \"test\":\"value\" }", "{\"test\":\"value2\"}")]
[InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value1\"}}")]
[InlineData("{\"test\":{\"test1\":\"value\"}}", "{\"test\":{\"test1\":\"value1\"}}")]
[InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value1\"}}]")]
public void JsonPartialWildcardMatcher_IsMatch_StringInputWithInvalidMatch(string value, string input)
{
// Assign
var matcher = new JsonPartialWildcardMatcher(value);
// Act
double match = matcher.IsMatch(input);
// Assert
Assert.Equal(0.0, match);
}
[Theory]
[InlineData("{ \"test.nested\":123 }", "{\"test\":{\"nested\":123}}")]
[InlineData("{ \"test.nested\":[123, 456] }", "{\"test\":{\"nested\":[123, 456]}}")]
[InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value\"}}")]
[InlineData("{ \"['name.with.dot']\":\"value\" }", "{\"name.with.dot\":\"value\"}")]
[InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value\"}}]")]
[InlineData("[{ \"['name.with.dot']\":\"value\" }]", "[{\"name.with.dot\":\"value\"}]")]
public void JsonPartialWildcardMatcher_IsMatch_ValueAsJPathValidMatch(string value, string input)
{
// Assign
var matcher = new JsonPartialWildcardMatcher(value);
// Act
double match = matcher.IsMatch(input);
// Assert
Assert.Equal(1.0, match);
}
[Theory]
[InlineData("{ \"test.nested\":123 }", "{\"test\":{\"nested\":456}}")]
[InlineData("{ \"test.nested\":[123, 456] }", "{\"test\":{\"nested\":[1, 2]}}")]
[InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value1\"}}")]
[InlineData("{ \"['name.with.dot']\":\"value\" }", "{\"name.with.dot\":\"value1\"}")]
[InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value1\"}}]")]
[InlineData("[{ \"['name.with.dot']\":\"value\" }]", "[{\"name.with.dot\":\"value1\"}]")]
public void JsonPartialWildcardMatcher_IsMatch_ValueAsJPathInvalidMatch(string value, string input)
{
// Assign
var matcher = new JsonPartialWildcardMatcher(value);
// Act
double match = matcher.IsMatch(input);
// Assert
Assert.Equal(0.0, match);
}
}

View File

@@ -5,165 +5,164 @@ using WireMock.Matchers.Request;
using WireMock.Models; using WireMock.Models;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.RequestMatchers namespace WireMock.Net.Tests.RequestMatchers;
public class RequestMessageHeaderMatcherTests
{ {
public class RequestMessageHeaderMatcherTests [Fact]
public void RequestMessageHeaderMatcher_GetMatchingScore_AcceptOnMatch_HeaderDoesNotExists()
{ {
[Fact] // Assign
public void RequestMessageHeaderMatcher_GetMatchingScore_AcceptOnMatch_HeaderDoesNotExists() var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1");
{ var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, "h", "x", true);
// Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1");
var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, "h", "x", true);
// Act // Act
var result = new RequestMatchResult(); var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result); double score = matcher.GetMatchingScore(requestMessage, result);
// Assert // Assert
Check.That(score).IsEqualTo(0.0d); Check.That(score).IsEqualTo(0.0d);
} }
[Fact] [Fact]
public void RequestMessageHeaderMatcher_GetMatchingScore_RejectOnMatch_HeaderDoesNotExists() public void RequestMessageHeaderMatcher_GetMatchingScore_RejectOnMatch_HeaderDoesNotExists()
{ {
// Assign // Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1"); var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1");
var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.RejectOnMatch, "h", "x", true); var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.RejectOnMatch, "h", "x", true);
// Act // Act
var result = new RequestMatchResult(); var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result); double score = matcher.GetMatchingScore(requestMessage, result);
// Assert // Assert
Check.That(score).IsEqualTo(1.0d); Check.That(score).IsEqualTo(1.0d);
} }
[Fact] [Fact]
public void RequestMessageHeaderMatcher_GetMatchingScore_AcceptOnMatch_HeaderDoesNotMatchPattern() public void RequestMessageHeaderMatcher_GetMatchingScore_AcceptOnMatch_HeaderDoesNotMatchPattern()
{ {
// Assign // Assign
var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } }; var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers); var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers);
var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, "no-match", "123", true); var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, "no-match", "123", true);
// Act // Act
var result = new RequestMatchResult(); var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result); double score = matcher.GetMatchingScore(requestMessage, result);
// Assert // Assert
Check.That(score).IsEqualTo(0.0d); Check.That(score).IsEqualTo(0.0d);
} }
[Fact] [Fact]
public void RequestMessageHeaderMatcher_GetMatchingScore_RejectOnMatch_HeaderDoesNotMatchPattern() public void RequestMessageHeaderMatcher_GetMatchingScore_RejectOnMatch_HeaderDoesNotMatchPattern()
{ {
// Assign // Assign
var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } }; var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers); var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers);
var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.RejectOnMatch, "no-match", "123", true); var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.RejectOnMatch, "no-match", "123", true);
// Act // Act
var result = new RequestMatchResult(); var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result); double score = matcher.GetMatchingScore(requestMessage, result);
// Assert // Assert
Check.That(score).IsEqualTo(1.0d); Check.That(score).IsEqualTo(1.0d);
} }
[Fact] [Fact]
public void RequestMessageHeaderMatcher_GetMatchingScore_AcceptOnMatch() public void RequestMessageHeaderMatcher_GetMatchingScore_AcceptOnMatch()
{ {
// Assign // Assign
var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } }; var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers); var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers);
var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, "h", "x", true); var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, "h", "x", true);
// Act // Act
var result = new RequestMatchResult(); var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result); double score = matcher.GetMatchingScore(requestMessage, result);
// Assert // Assert
Check.That(score).IsEqualTo(1.0d); Check.That(score).IsEqualTo(1.0d);
} }
[Fact(Skip = "does not work anymore since 'and'/'or'/'average'")] [Fact(Skip = "does not work anymore since 'and'/'or'/'average'")]
public void RequestMessageHeaderMatcher_GetMatchingScore_RejectOnMatch() public void RequestMessageHeaderMatcher_GetMatchingScore_RejectOnMatch()
{ {
// Assign // Assign
var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } }; var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers); var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers);
var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.RejectOnMatch, "h", "x", true); var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.RejectOnMatch, "h", "x", true);
// Act // Act
var result = new RequestMatchResult(); var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result); double score = matcher.GetMatchingScore(requestMessage, result);
// Assert // Assert
Check.That(score).IsEqualTo(0.0d); Check.That(score).IsEqualTo(0.0d);
} }
[Fact] [Fact]
public void RequestMessageHeaderMatcher_GetMatchingScore_IStringMatcher_Match() public void RequestMessageHeaderMatcher_GetMatchingScore_IStringMatcher_Match()
{ {
// Assign // Assign
var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } }; var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers); var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers);
var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, MatchOperator.Or, "h", false, new ExactMatcher("x")); var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, MatchOperator.Or, "h", false, new ExactMatcher("x"));
// Act // Act
var result = new RequestMatchResult(); var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result); double score = matcher.GetMatchingScore(requestMessage, result);
// Assert // Assert
Check.That(score).IsEqualTo(1.0d); Check.That(score).IsEqualTo(1.0d);
} }
[Fact] [Fact]
public void RequestMessageHeaderMatcher_GetMatchingScore_Func_Match() public void RequestMessageHeaderMatcher_GetMatchingScore_Func_Match()
{ {
// Assign // Assign
var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } }; var headers = new Dictionary<string, string[]> { { "h", new[] { "x" } } };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers); var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers);
var matcher = new RequestMessageHeaderMatcher(x => x.ContainsKey("h")); var matcher = new RequestMessageHeaderMatcher(x => x.ContainsKey("h"));
// Act // Act
var result = new RequestMatchResult(); var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result); double score = matcher.GetMatchingScore(requestMessage, result);
// Assert // Assert
Check.That(score).IsEqualTo(1.0d); Check.That(score).IsEqualTo(1.0d);
} }
[Fact] [Fact]
public void RequestMessageHeaderMatcher_GetMatchingScore_CaseIgnoreForHeaderValue() public void RequestMessageHeaderMatcher_GetMatchingScore_CaseIgnoreForHeaderValue()
{ {
// Assign // Assign
var headers = new Dictionary<string, string[]> { { "h", new[] { "teST" } } }; var headers = new Dictionary<string, string[]> { { "h", new[] { "teST" } } };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers); var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers);
var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, "h", "test", true); var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, "h", "test", true);
// Act // Act
var result = new RequestMatchResult(); var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result); double score = matcher.GetMatchingScore(requestMessage, result);
// Assert // Assert
Check.That(score).IsEqualTo(1.0d); Check.That(score).IsEqualTo(1.0d);
} }
[Fact] [Fact]
public void RequestMessageHeaderMatcher_GetMatchingScore_CaseIgnoreForHeaderName() public void RequestMessageHeaderMatcher_GetMatchingScore_CaseIgnoreForHeaderName()
{ {
// Assign // Assign
var headers = new Dictionary<string, string[]> { { "teST", new[] { "x" } } }; var headers = new Dictionary<string, string[]> { { "teST", new[] { "x" } } };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers); var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, headers);
var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, "TEST", "x", true); var matcher = new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, "TEST", "x", true);
// Act // Act
var result = new RequestMatchResult(); var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result); double score = matcher.GetMatchingScore(requestMessage, result);
// Assert // Assert
Check.That(score).IsEqualTo(1.0d); Check.That(score).IsEqualTo(1.0d);
}
} }
} }

View File

@@ -1,107 +1,106 @@
using NFluent; using NFluent;
using WireMock.Models; using WireMock.Models;
using WireMock.Util; using WireMock.Util;
using Xunit; using Xunit;
namespace WireMock.Net.Tests namespace WireMock.Net.Tests;
public class RequestMessageTests
{ {
public class RequestMessageTests private const string ClientIp = "::1";
[Fact]
public void RequestMessage_Method_Should_BeSame()
{ {
private const string ClientIp = "::1"; // given
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "posT", ClientIp);
[Fact] // then
public void RequestMessage_Method_Should_BeSame() Check.That(request.Method).IsEqualTo("posT");
{ }
// given
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "posT", ClientIp);
// then [Fact]
Check.That(request.Method).IsEqualTo("posT"); public void RequestMessage_ParseQuery_NoKeys()
} {
// given
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp);
[Fact] // then
public void RequestMessage_ParseQuery_NoKeys() Check.That(request.GetParameter("not_there")).IsNull();
{ }
// given
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp);
// then [Fact]
Check.That(request.GetParameter("not_there")).IsNull(); public void RequestMessage_ParseQuery_SingleKey_SingleValue()
} {
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost?foo=bar"), "POST", ClientIp);
[Fact] // Assert
public void RequestMessage_ParseQuery_SingleKey_SingleValue() Check.That(request.GetParameter("foo")).ContainsExactly("bar");
{ }
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost?foo=bar"), "POST", ClientIp);
// Assert [Fact]
Check.That(request.GetParameter("foo")).ContainsExactly("bar"); public void RequestMessage_ParseQuery_SingleKey_SingleValue_WithIgnoreCase()
} {
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost?foo=bar"), "POST", ClientIp);
[Fact] // Assert
public void RequestMessage_ParseQuery_SingleKey_SingleValue_WithIgnoreCase() Check.That(request.GetParameter("FoO", true)).ContainsExactly("bar");
{ }
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost?foo=bar"), "POST", ClientIp);
// Assert [Fact]
Check.That(request.GetParameter("FoO", true)).ContainsExactly("bar"); public void RequestMessage_ParseQuery_MultipleKeys_MultipleValues()
} {
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost?key=1&key=2"), "POST", ClientIp);
[Fact] // Assert
public void RequestMessage_ParseQuery_MultipleKeys_MultipleValues() Check.That(request.GetParameter("key")).Contains("1");
{ Check.That(request.GetParameter("key")).Contains("2");
// Assign }
var request = new RequestMessage(new UrlDetails("http://localhost?key=1&key=2"), "POST", ClientIp);
// Assert [Fact]
Check.That(request.GetParameter("key")).Contains("1"); public void RequestMessage_ParseQuery_SingleKey_MultipleValuesCommaSeparated()
Check.That(request.GetParameter("key")).Contains("2"); {
} // Assign
var request = new RequestMessage(new UrlDetails("http://localhost?key=1,2,3"), "POST", ClientIp);
[Fact] // Assert
public void RequestMessage_ParseQuery_SingleKey_MultipleValuesCommaSeparated() Check.That(request.GetParameter("key")).Contains("1");
{ Check.That(request.GetParameter("key")).Contains("2");
// Assign Check.That(request.GetParameter("key")).Contains("3");
var request = new RequestMessage(new UrlDetails("http://localhost?key=1,2,3"), "POST", ClientIp); }
// Assert [Fact]
Check.That(request.GetParameter("key")).Contains("1"); public void RequestMessage_ParseQuery_SingleKey_MultipleValues()
Check.That(request.GetParameter("key")).Contains("2"); {
Check.That(request.GetParameter("key")).Contains("3"); // Assign
} var request = new RequestMessage(new UrlDetails("http://localhost?key=1,2&foo=bar&key=3"), "POST", ClientIp);
[Fact] // Assert
public void RequestMessage_ParseQuery_SingleKey_MultipleValues() Check.That(request.GetParameter("key")).Contains("1");
{ Check.That(request.GetParameter("key")).Contains("2");
// Assign Check.That(request.GetParameter("key")).Contains("3");
var request = new RequestMessage(new UrlDetails("http://localhost?key=1,2&foo=bar&key=3"), "POST", ClientIp); }
// Assert [Fact]
Check.That(request.GetParameter("key")).Contains("1"); public void RequestMessage_Constructor1_PathSegments()
Check.That(request.GetParameter("key")).Contains("2"); {
Check.That(request.GetParameter("key")).Contains("3"); // Assign
} var request = new RequestMessage(new UrlDetails("http://localhost/a/b/c"), "POST", ClientIp);
[Fact] // Assert
public void RequestMessage_Constructor1_PathSegments() Check.That(request.PathSegments).ContainsExactly("a", "b", "c");
{ }
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost/a/b/c"), "POST", ClientIp);
// Assert [Fact]
Check.That(request.PathSegments).ContainsExactly("a", "b", "c"); public void RequestMessage_Constructor2_PathSegments()
} {
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost/a/b/c"), "POST", ClientIp, new BodyData());
[Fact] // Assert
public void RequestMessage_Constructor2_PathSegments() Check.That(request.PathSegments).ContainsExactly("a", "b", "c");
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost/a/b/c"), "POST", ClientIp, new BodyData());
// Assert
Check.That(request.PathSegments).ContainsExactly("a", "b", "c");
}
} }
} }

View File

@@ -10,399 +10,402 @@ using WireMock.Serialization;
using WireMock.Settings; using WireMock.Settings;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Serialization namespace WireMock.Net.Tests.Serialization;
public class MatcherMapperTests
{ {
public class MatcherMapperTests private readonly WireMockServerSettings _settings = new();
private readonly MatcherMapper _sut;
public MatcherMapperTests()
{ {
private readonly WireMockServerSettings _settings = new WireMockServerSettings(); _sut = new MatcherMapper(_settings);
private readonly MatcherMapper _sut;
public MatcherMapperTests()
{
_sut = new MatcherMapper(_settings);
}
[Fact]
public void MatcherMapper_Map_IMatcher_Null()
{
// Act
var model = _sut.Map((IMatcher)null);
// Assert
model.Should().BeNull();
}
[Fact]
public void MatcherMapper_Map_IMatchers_Null()
{
// Act
var model = _sut.Map((IMatcher[])null);
// Assert
model.Should().BeNull();
}
[Fact]
public void MatcherMapper_Map_IMatchers()
{
// Assign
var matcherMock1 = new Mock<IStringMatcher>();
var matcherMock2 = new Mock<IStringMatcher>();
// Act
var models = _sut.Map(new[] { matcherMock1.Object, matcherMock2.Object });
// Assert
models.Should().HaveCount(2);
}
[Fact]
public void MatcherMapper_Map_IStringMatcher()
{
// Assign
var matcherMock = new Mock<IStringMatcher>();
matcherMock.Setup(m => m.Name).Returns("test");
matcherMock.Setup(m => m.GetPatterns()).Returns(new AnyOf<string, StringPattern>[] { "p1", "p2" });
// Act
var model = _sut.Map(matcherMock.Object);
// Assert
model.IgnoreCase.Should().BeNull();
model.Name.Should().Be("test");
model.Pattern.Should().BeNull();
model.Patterns.Should().HaveCount(2)
.And.Contain("p1")
.And.Contain("p2");
}
[Fact]
public void MatcherMapper_Map_IStringMatcher_With_PatternAsFile()
{
// Arrange
var pattern = new StringPattern { Pattern = "p", PatternAsFile = "pf" };
var matcherMock = new Mock<IStringMatcher>();
matcherMock.Setup(m => m.Name).Returns("test");
matcherMock.Setup(m => m.GetPatterns()).Returns(new AnyOf<string, StringPattern>[] { pattern });
// Act
var model = _sut.Map(matcherMock.Object);
// Assert
model.IgnoreCase.Should().BeNull();
model.Name.Should().Be("test");
model.Pattern.Should().Be("p");
model.Patterns.Should().BeNull();
model.PatternAsFile.Should().Be("pf");
}
[Fact]
public void MatcherMapper_Map_IIgnoreCaseMatcher()
{
// Assign
var matcherMock = new Mock<IIgnoreCaseMatcher>();
matcherMock.Setup(m => m.IgnoreCase).Returns(true);
// Act
var model = _sut.Map(matcherMock.Object);
// Assert
model.IgnoreCase.Should().BeTrue();
}
[Fact]
public void MatcherMapper_Map_MatcherModel_Null()
{
// Act
var result = _sut.Map((MatcherModel)null);
// Assert
result.Should().BeNull();
}
[Fact]
public void MatcherMapper_Map_MatcherModel_Exception()
{
// Assign
var model = new MatcherModel { Name = "test" };
// Act and Assert
Check.ThatCode(() => _sut.Map(model)).Throws<NotSupportedException>();
}
[Fact]
public void MatcherMapper_Map_MatcherModel_LinqMatcher_Pattern()
{
// Assign
var model = new MatcherModel
{
Name = "LinqMatcher",
Pattern = "p"
};
// Act
var matcher = (LinqMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.GetPatterns().Should().Contain("p");
}
[Fact]
public void MatcherMapper_Map_MatcherModel_LinqMatcher_Patterns()
{
// Assign
var model = new MatcherModel
{
Name = "LinqMatcher",
Patterns = new[] { "p1", "p2" }
};
// Act
var matcher = (LinqMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.GetPatterns().Should().Contain("p1", "p2");
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonMatcher_Pattern_As_String()
{
// Assign
var pattern = "{ \"AccountIds\": [ 1, 2, 3 ] }";
var model = new MatcherModel
{
Name = "JsonMatcher",
Pattern = pattern
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonMatcher_Patterns_1_Value_As_String()
{
// Assign
var pattern = "{ \"post1\": \"value1\", \"post2\": \"value2\" }";
var patterns = new[] { pattern };
var model = new MatcherModel
{
Name = "JsonMatcher",
Patterns = patterns
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(patterns);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonMatcher_Patterns_2_Values_As_String()
{
// Assign
var pattern1 = "{ \"AccountIds\": [ 1, 2, 3 ] }";
var pattern2 = "{ \"post1\": \"value1\", \"post2\": \"value2\" }";
var patterns = new[] { pattern1, pattern2 };
var model = new MatcherModel
{
Name = "JsonMatcher",
Patterns = patterns
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(patterns);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonMatcher_Pattern_As_Object()
{
// Assign
var pattern = new { AccountIds = new[] { 1, 2, 3 } };
var model = new MatcherModel
{
Name = "JsonMatcher",
Pattern = pattern
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonMatcher_Patterns_1_Value_As_Object()
{
// Assign
object pattern = new { post1 = "value1", post2 = "value2" };
var patterns = new[] { pattern };
var model = new MatcherModel
{
Name = "JsonMatcher",
Patterns = patterns
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(patterns);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonMatcher_Patterns_2_Values_As_Object()
{
// Assign
object pattern1 = new { AccountIds = new[] { 1, 2, 3 } };
object pattern2 = new { post1 = "value1", post2 = "value2" };
var patterns = new[] { pattern1, pattern2 };
var model = new MatcherModel
{
Name = "JsonMatcher",
Patterns = patterns
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(patterns);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialMatcher_Pattern_As_String()
{
// Assign
var pattern = "{ \"AccountIds\": [ 1, 2, 3 ] }";
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Pattern = pattern
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialMatcher_Patterns_As_String()
{
// Assign
var pattern1 = "{ \"AccountIds\": [ 1, 2, 3 ] }";
var pattern2 = "{ \"X\": \"x\" }";
var patterns = new[] { pattern1, pattern2 };
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Pattern = patterns
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(patterns);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialMatcher_Pattern_As_Object()
{
// Assign
var pattern = new { AccountIds = new[] { 1, 2, 3 } };
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Pattern = pattern
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialMatcher_Patterns_As_Object()
{
// Assign
object pattern1 = new { AccountIds = new[] { 1, 2, 3 } };
object pattern2 = new { X = "x" };
var patterns = new[] { pattern1, pattern2 };
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Patterns = patterns
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(patterns);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialMatcher_StringPattern_With_PatternAsFile()
{
// Assign
var pattern = new StringPattern { Pattern = "{ \"AccountIds\": [ 1, 2, 3 ] }", PatternAsFile = "pf" };
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Pattern = pattern
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialWilcardMatcher_Patterns_As_Object()
{
// Assign
object pattern = new { X = "*" };
var model = new MatcherModel
{
Name = "JsonPartialWildcardMatcher",
Pattern = pattern
};
// Act
var matcher = (JsonPartialWildcardMatcher)_sut.Map(model);
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
}
} }
}
[Fact]
public void MatcherMapper_Map_IMatcher_Null()
{
// Act
var model = _sut.Map((IMatcher?)null);
// Assert
model.Should().BeNull();
}
[Fact]
public void MatcherMapper_Map_IMatchers_Null()
{
// Act
var model = _sut.Map((IMatcher[]?)null);
// Assert
model.Should().BeNull();
}
[Fact]
public void MatcherMapper_Map_IMatchers()
{
// Assign
var matcherMock1 = new Mock<IStringMatcher>();
var matcherMock2 = new Mock<IStringMatcher>();
// Act
var models = _sut.Map(new[] { matcherMock1.Object, matcherMock2.Object });
// Assert
models.Should().HaveCount(2);
}
[Fact]
public void MatcherMapper_Map_IStringMatcher()
{
// Assign
var matcherMock = new Mock<IStringMatcher>();
matcherMock.Setup(m => m.Name).Returns("test");
matcherMock.Setup(m => m.GetPatterns()).Returns(new AnyOf<string, StringPattern>[] { "p1", "p2" });
// Act
var model = _sut.Map(matcherMock.Object)!;
// Assert
model.IgnoreCase.Should().BeNull();
model.Name.Should().Be("test");
model.Pattern.Should().BeNull();
model.Patterns.Should().HaveCount(2)
.And.Contain("p1")
.And.Contain("p2");
}
[Fact]
public void MatcherMapper_Map_IStringMatcher_With_PatternAsFile()
{
// Arrange
var pattern = new StringPattern { Pattern = "p", PatternAsFile = "pf" };
var matcherMock = new Mock<IStringMatcher>();
matcherMock.Setup(m => m.Name).Returns("test");
matcherMock.Setup(m => m.GetPatterns()).Returns(new AnyOf<string, StringPattern>[] { pattern });
// Act
var model = _sut.Map(matcherMock.Object)!;
// Assert
model.IgnoreCase.Should().BeNull();
model.Name.Should().Be("test");
model.Pattern.Should().Be("p");
model.Patterns.Should().BeNull();
model.PatternAsFile.Should().Be("pf");
}
[Fact]
public void MatcherMapper_Map_IIgnoreCaseMatcher()
{
// Assign
var matcherMock = new Mock<IIgnoreCaseMatcher>();
matcherMock.Setup(m => m.IgnoreCase).Returns(true);
// Act
var model = _sut.Map(matcherMock.Object)!;
// Assert
model.IgnoreCase.Should().BeTrue();
}
[Fact]
public void MatcherMapper_Map_MatcherModel_Null()
{
// Act
var result = _sut.Map((MatcherModel?)null);
// Assert
result.Should().BeNull();
}
[Fact]
public void MatcherMapper_Map_MatcherModel_Exception()
{
// Assign
var model = new MatcherModel { Name = "test" };
// Act and Assert
Check.ThatCode(() => _sut.Map(model)).Throws<NotSupportedException>();
}
[Fact]
public void MatcherMapper_Map_MatcherModel_LinqMatcher_Pattern()
{
// Assign
var model = new MatcherModel
{
Name = "LinqMatcher",
Pattern = "p"
};
// Act
var matcher = (LinqMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.GetPatterns().Should().Contain("p");
}
[Fact]
public void MatcherMapper_Map_MatcherModel_LinqMatcher_Patterns()
{
// Assign
var model = new MatcherModel
{
Name = "LinqMatcher",
Patterns = new[] { "p1", "p2" }
};
// Act
var matcher = (LinqMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.GetPatterns().Should().Contain("p1", "p2");
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonMatcher_Pattern_As_String()
{
// Assign
var pattern = "{ \"AccountIds\": [ 1, 2, 3 ] }";
var model = new MatcherModel
{
Name = "JsonMatcher",
Pattern = pattern
};
// Act
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonMatcher_Patterns_1_Value_As_String()
{
// Assign
var pattern = "{ \"post1\": \"value1\", \"post2\": \"value2\" }";
var patterns = new[] { pattern };
var model = new MatcherModel
{
Name = "JsonMatcher",
Patterns = patterns
};
// Act
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(patterns);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonMatcher_Patterns_2_Values_As_String()
{
// Assign
var pattern1 = "{ \"AccountIds\": [ 1, 2, 3 ] }";
var pattern2 = "{ \"post1\": \"value1\", \"post2\": \"value2\" }";
var patterns = new[] { pattern1, pattern2 };
var model = new MatcherModel
{
Name = "JsonMatcher",
Patterns = patterns
};
// Act
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(patterns);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonMatcher_Pattern_As_Object()
{
// Assign
var pattern = new { AccountIds = new[] { 1, 2, 3 } };
var model = new MatcherModel
{
Name = "JsonMatcher",
Pattern = pattern
};
// Act
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonMatcher_Patterns_1_Value_As_Object()
{
// Assign
object pattern = new { post1 = "value1", post2 = "value2" };
var patterns = new[] { pattern };
var model = new MatcherModel
{
Name = "JsonMatcher",
Patterns = patterns
};
// Act
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(patterns);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonMatcher_Patterns_2_Values_As_Object()
{
// Assign
object pattern1 = new { AccountIds = new[] { 1, 2, 3 } };
object pattern2 = new { post1 = "value1", post2 = "value2" };
var patterns = new[] { pattern1, pattern2 };
var model = new MatcherModel
{
Name = "JsonMatcher",
Patterns = patterns
};
// Act
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(patterns);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialMatcher_Pattern_As_String()
{
// Assign
var pattern = "{ \"AccountIds\": [ 1, 2, 3 ] }";
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Pattern = pattern
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialMatcher_Patterns_As_String()
{
// Assign
var pattern1 = "{ \"AccountIds\": [ 1, 2, 3 ] }";
var pattern2 = "{ \"X\": \"x\" }";
var patterns = new[] { pattern1, pattern2 };
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Pattern = patterns
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(patterns);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialMatcher_Pattern_As_Object()
{
// Assign
var pattern = new { AccountIds = new[] { 1, 2, 3 } };
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Pattern = pattern
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialMatcher_Patterns_As_Object()
{
// Assign
object pattern1 = new { AccountIds = new[] { 1, 2, 3 } };
object pattern2 = new { X = "x" };
var patterns = new[] { pattern1, pattern2 };
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Patterns = patterns
};
// Act
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(patterns);
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialMatcher_StringPattern_With_PatternAsFile()
{
// Assign
var pattern = new StringPattern { Pattern = "{ \"AccountIds\": [ 1, 2, 3 ] }", PatternAsFile = "pf" };
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Pattern = pattern,
Regex = true
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
matcher.Regex.Should().BeTrue();
}
[Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialWildcardMatcher_Patterns_As_Object()
{
// Assign
object pattern = new { X = "*" };
var model = new MatcherModel
{
Name = "JsonPartialWildcardMatcher",
Pattern = pattern,
Regex = false
};
// Act
var matcher = (JsonPartialWildcardMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
matcher.Regex.Should().BeFalse();
}
}

View File

@@ -14,378 +14,427 @@ using WireMock.Serialization;
using WireMock.Settings; using WireMock.Settings;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Serialization namespace WireMock.Net.Tests.Serialization;
public class MatcherModelMapperTests
{ {
public class MatcherModelMapperTests private readonly WireMockServerSettings _settings = new();
private readonly MatcherMapper _sut;
public MatcherModelMapperTests()
{ {
private readonly WireMockServerSettings _settings = new WireMockServerSettings(); _sut = new MatcherMapper(_settings);
}
private readonly MatcherMapper _sut; [Fact]
public void MatcherModelMapper_Map_CSharpCodeMatcher()
public MatcherModelMapperTests() {
// Assign
var model = new MatcherModel
{ {
_sut = new MatcherMapper(_settings); Name = "CSharpCodeMatcher",
} Patterns = new[] { "return it == \"x\";" }
};
var sut = new MatcherMapper(new WireMockServerSettings { AllowCSharpCodeMatcher = true });
[Fact] // Act 1
public void MatcherModelMapper_Map_CSharpCodeMatcher() var matcher1 = (ICSharpCodeMatcher)sut.Map(model)!;
// Assert 1
matcher1.Should().NotBeNull();
matcher1.IsMatch("x").Should().Be(1.0d);
// Act 2
var matcher2 = (ICSharpCodeMatcher)sut.Map(model)!;
// Assert 2
matcher2.Should().NotBeNull();
matcher2.IsMatch("x").Should().Be(1.0d);
}
[Fact]
public void MatcherModelMapper_Map_CSharpCodeMatcher_NotAllowed_ThrowsException()
{
// Assign
var model = new MatcherModel
{ {
// Assign Name = "CSharpCodeMatcher",
var model = new MatcherModel Patterns = new[] { "x" }
{ };
Name = "CSharpCodeMatcher", var sut = new MatcherMapper(new WireMockServerSettings { AllowCSharpCodeMatcher = false });
Patterns = new[] { "return it == \"x\";" }
};
var sut = new MatcherMapper(new WireMockServerSettings { AllowCSharpCodeMatcher = true });
// Act 1 // Act
var matcher1 = (ICSharpCodeMatcher)sut.Map(model); Action action = () => sut.Map(model);
// Assert 1 // Assert
matcher1.Should().NotBeNull(); action.Should().Throw<NotSupportedException>();
matcher1.IsMatch("x").Should().Be(1.0d); }
// Act 2 [Fact]
var matcher2 = (ICSharpCodeMatcher)sut.Map(model); public void MatcherModelMapper_Map_Null()
{
// Act
IMatcher matcher = _sut.Map((MatcherModel?)null)!;
// Assert 2 // Assert
matcher2.Should().NotBeNull(); Check.That(matcher).IsNull();
matcher2.IsMatch("x").Should().Be(1.0d); }
}
[Fact] [Fact]
public void MatcherModelMapper_Map_CSharpCodeMatcher_NotAllowed_ThrowsException() public void MatcherModelMapper_Map_ExactMatcher_Pattern()
{
// Assign
var model = new MatcherModel
{ {
// Assign Name = "ExactMatcher",
var model = new MatcherModel Patterns = new[] { "x" }
{ };
Name = "CSharpCodeMatcher",
Patterns = new[] { "x" }
};
var sut = new MatcherMapper(new WireMockServerSettings { AllowCSharpCodeMatcher = false });
// Act // Act
Action action = () => sut.Map(model); var matcher = (ExactMatcher)_sut.Map(model)!;
// Assert // Assert
action.Should().Throw<NotSupportedException>(); matcher.GetPatterns().Should().ContainSingle("x");
} matcher.ThrowException.Should().BeFalse();
}
[Fact] [Fact]
public void MatcherModelMapper_Map_Null() public void MatcherModelMapper_Map_ExactMatcher_Patterns()
{
// Assign
var model = new MatcherModel
{ {
// Act Name = "ExactMatcher",
IMatcher matcher = _sut.Map((MatcherModel)null); Patterns = new[] { "x", "y" }
};
// Assert // Act
Check.That(matcher).IsNull(); var matcher = (ExactMatcher)_sut.Map(model)!;
}
[Fact] // Assert
public void MatcherModelMapper_Map_ExactMatcher_Pattern() Check.That(matcher.GetPatterns()).ContainsExactly("x", "y");
}
[Fact]
public void MatcherModelMapper_Map_JsonPartialMatcher_RegexFalse()
{
// Assign
var pattern = "{ \"x\": 1 }";
var model = new MatcherModel
{ {
// Assign Name = "JsonPartialMatcher",
var model = new MatcherModel Regex = false,
{ Pattern = pattern
Name = "ExactMatcher", };
Patterns = new[] { "x" }
};
// Act // Act
var matcher = (ExactMatcher)_sut.Map(model); var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.GetPatterns().Should().ContainSingle("x"); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.ThrowException.Should().BeFalse(); matcher.IgnoreCase.Should().BeFalse();
} matcher.Value.Should().Be(pattern);
matcher.Regex.Should().BeFalse();
matcher.ThrowException.Should().BeFalse();
}
[Fact] [Fact]
public void MatcherModelMapper_Map_ExactMatcher_Patterns() public void MatcherModelMapper_Map_JsonPartialMatcher_RegexTrue()
{
// Assign
var pattern = "{ \"x\": 1 }";
var model = new MatcherModel
{ {
// Assign Name = "JsonPartialMatcher",
var model = new MatcherModel Regex = true,
{ Pattern = pattern
Name = "ExactMatcher", };
Patterns = new[] { "x", "y" }
};
// Act // Act
var matcher = (ExactMatcher)_sut.Map(model); var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert // Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x", "y"); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
} matcher.IgnoreCase.Should().BeFalse();
matcher.Value.Should().Be(pattern);
matcher.Regex.Should().BeTrue();
matcher.ThrowException.Should().BeFalse();
}
[Theory] [Theory]
[InlineData(nameof(LinqMatcher))] [InlineData(nameof(LinqMatcher))]
[InlineData(nameof(ExactMatcher))] [InlineData(nameof(ExactMatcher))]
[InlineData(nameof(ExactObjectMatcher))] [InlineData(nameof(ExactObjectMatcher))]
[InlineData(nameof(RegexMatcher))] [InlineData(nameof(RegexMatcher))]
[InlineData(nameof(JsonMatcher))] [InlineData(nameof(JsonMatcher))]
[InlineData(nameof(JsonPathMatcher))] [InlineData(nameof(JsonPartialMatcher))]
[InlineData(nameof(JmesPathMatcher))] [InlineData(nameof(JsonPartialWildcardMatcher))]
[InlineData(nameof(XPathMatcher))] [InlineData(nameof(JsonPathMatcher))]
[InlineData(nameof(WildcardMatcher))] [InlineData(nameof(JmesPathMatcher))]
[InlineData(nameof(ContentTypeMatcher))] [InlineData(nameof(XPathMatcher))]
[InlineData(nameof(SimMetricsMatcher))] [InlineData(nameof(WildcardMatcher))]
public void MatcherModelMapper_Map_ThrowExceptionWhenMatcherFails_True(string name) [InlineData(nameof(ContentTypeMatcher))]
[InlineData(nameof(SimMetricsMatcher))]
public void MatcherModelMapper_Map_ThrowExceptionWhenMatcherFails_True(string name)
{
// Assign
var settings = new WireMockServerSettings
{ {
// Assign ThrowExceptionWhenMatcherFails = true
var settings = new WireMockServerSettings };
{ var sut = new MatcherMapper(settings);
ThrowExceptionWhenMatcherFails = true var model = new MatcherModel
};
var sut = new MatcherMapper(settings);
var model = new MatcherModel
{
Name = name,
Patterns = new[] { "" }
};
// Act
var matcher = sut.Map(model);
// Assert
matcher.ThrowException.Should().BeTrue();
}
[Fact]
public void MatcherModelMapper_Map_ExactObjectMatcher_ValidBase64StringPattern()
{ {
// Assign Name = name,
var model = new MatcherModel Patterns = new[] { "" }
{ };
Name = "ExactObjectMatcher",
Patterns = new object[] { "c3RlZg==" }
};
// Act // Act
var matcher = (ExactObjectMatcher)_sut.Map(model); var matcher = sut.Map(model)!;
// Assert // Assert
Check.That(matcher.ValueAsBytes).ContainsExactly(new byte[] { 115, 116, 101, 102 }); matcher.Should().NotBeNull();
} matcher.ThrowException.Should().BeTrue();
}
[Fact] [Fact]
public void MatcherModelMapper_Map_ExactObjectMatcher_InvalidBase64StringPattern() public void MatcherModelMapper_Map_ExactObjectMatcher_ValidBase64StringPattern()
{
// Assign
var model = new MatcherModel
{ {
// Assign Name = "ExactObjectMatcher",
var model = new MatcherModel Patterns = new object[] { "c3RlZg==" }
{ };
Name = "ExactObjectMatcher",
Patterns = new object[] { "_" }
};
// Act & Assert // Act
Check.ThatCode(() => _sut.Map(model)).Throws<ArgumentException>(); var matcher = (ExactObjectMatcher)_sut.Map(model)!;
}
[Theory] // Assert
[InlineData(MatchOperator.Or, 1.0d)] Check.That(matcher.ValueAsBytes).ContainsExactly(new byte[] { 115, 116, 101, 102 });
[InlineData(MatchOperator.And, 0.0d)] }
[InlineData(MatchOperator.Average, 0.5d)]
public void MatcherModelMapper_Map_RegexMatcher(MatchOperator matchOperator, double expected) [Fact]
public void MatcherModelMapper_Map_ExactObjectMatcher_InvalidBase64StringPattern()
{
// Assign
var model = new MatcherModel
{ {
// Assign Name = "ExactObjectMatcher",
var model = new MatcherModel Patterns = new object[] { "_" }
{ };
Name = "RegexMatcher",
Patterns = new[] { "x", "y" },
IgnoreCase = true,
MatchOperator = matchOperator.ToString()
};
// Act // Act & Assert
var matcher = (RegexMatcher)_sut.Map(model)!; Check.ThatCode(() => _sut.Map(model)).Throws<ArgumentException>();
}
// Assert [Theory]
Check.That(matcher.GetPatterns()).ContainsExactly("x", "y"); [InlineData(MatchOperator.Or, 1.0d)]
Check.That(matcher.IsMatch("X")).IsEqualTo(expected); [InlineData(MatchOperator.And, 0.0d)]
} [InlineData(MatchOperator.Average, 0.5d)]
public void MatcherModelMapper_Map_RegexMatcher(MatchOperator matchOperator, double expected)
[Theory] {
[InlineData(MatchOperator.Or, 1.0d)] // Assign
[InlineData(MatchOperator.And, 0.0d)] var model = new MatcherModel
[InlineData(MatchOperator.Average, 0.5d)]
public void MatcherModelMapper_Map_WildcardMatcher_IgnoreCase(MatchOperator matchOperator, double expected)
{ {
// Assign Name = "RegexMatcher",
var model = new MatcherModel Patterns = new[] { "x", "y" },
{ IgnoreCase = true,
Name = "WildcardMatcher", MatchOperator = matchOperator.ToString()
Patterns = new[] { "x", "y" }, };
IgnoreCase = true,
MatchOperator = matchOperator.ToString()
};
// Act // Act
var matcher = (WildcardMatcher)_sut.Map(model)!; var matcher = (RegexMatcher)_sut.Map(model)!;
// Assert // Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x", "y"); Check.That(matcher.GetPatterns()).ContainsExactly("x", "y");
Check.That(matcher.IsMatch("X")).IsEqualTo(expected); Check.That(matcher.IsMatch("X")).IsEqualTo(expected);
} }
[Fact] [Theory]
public void MatcherModelMapper_Map_WildcardMatcher_With_PatternAsFile() [InlineData(MatchOperator.Or, 1.0d)]
[InlineData(MatchOperator.And, 0.0d)]
[InlineData(MatchOperator.Average, 0.5d)]
public void MatcherModelMapper_Map_WildcardMatcher_IgnoreCase(MatchOperator matchOperator, double expected)
{
// Assign
var model = new MatcherModel
{ {
// Arrange Name = "WildcardMatcher",
var file = "c:\\test.txt"; Patterns = new[] { "x", "y" },
var fileContent = "c"; IgnoreCase = true,
var stringPattern = new StringPattern MatchOperator = matchOperator.ToString()
{ };
Pattern = fileContent,
PatternAsFile = file
};
var fileSystemHandleMock = new Mock<IFileSystemHandler>();
fileSystemHandleMock.Setup(f => f.ReadFileAsString(file)).Returns(fileContent);
var model = new MatcherModel // Act
{ var matcher = (WildcardMatcher)_sut.Map(model)!;
Name = "WildcardMatcher",
PatternAsFile = file
};
var settings = new WireMockServerSettings // Assert
{ Check.That(matcher.GetPatterns()).ContainsExactly("x", "y");
FileSystemHandler = fileSystemHandleMock.Object Check.That(matcher.IsMatch("X")).IsEqualTo(expected);
}; }
var sut = new MatcherMapper(settings);
// Act [Fact]
var matcher = (WildcardMatcher)sut.Map(model); public void MatcherModelMapper_Map_WildcardMatcher_With_PatternAsFile()
{
// Assert // Arrange
matcher.GetPatterns().Should().HaveCount(1).And.Contain(new AnyOf<string, StringPattern>(stringPattern)); var file = "c:\\test.txt";
matcher.IsMatch("c").Should().Be(1.0d); var fileContent = "c";
} var stringPattern = new StringPattern
[Fact]
public void MatcherModelMapper_Map_SimMetricsMatcher()
{ {
// Assign Pattern = fileContent,
var model = new MatcherModel PatternAsFile = file
{ };
Name = "SimMetricsMatcher", var fileSystemHandleMock = new Mock<IFileSystemHandler>();
Pattern = "x" fileSystemHandleMock.Setup(f => f.ReadFileAsString(file)).Returns(fileContent);
};
// Act var model = new MatcherModel
var matcher = (SimMetricsMatcher)_sut.Map(model);
// Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x");
}
[Fact]
public void MatcherModelMapper_Map_SimMetricsMatcher_BlockDistance()
{ {
// Assign Name = "WildcardMatcher",
var model = new MatcherModel PatternAsFile = file
{ };
Name = "SimMetricsMatcher.BlockDistance",
Pattern = "x"
};
// Act var settings = new WireMockServerSettings
var matcher = (SimMetricsMatcher)_sut.Map(model);
// Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x");
}
[Fact]
public void MatcherModelMapper_Map_SimMetricsMatcher_Throws1()
{ {
// Assign FileSystemHandler = fileSystemHandleMock.Object
var model = new MatcherModel };
{ var sut = new MatcherMapper(settings);
Name = "error",
Pattern = "x"
};
// Act // Act
Check.ThatCode(() => _sut.Map(model)).Throws<NotSupportedException>(); var matcher = (WildcardMatcher)sut.Map(model)!;
}
[Fact] // Assert
public void MatcherModelMapper_Map_SimMetricsMatcher_Throws2() matcher.GetPatterns().Should().HaveCount(1).And.Contain(new AnyOf<string, StringPattern>(stringPattern));
matcher.IsMatch("c").Should().Be(1.0d);
}
[Fact]
public void MatcherModelMapper_Map_SimMetricsMatcher()
{
// Assign
var model = new MatcherModel
{ {
// Assign Name = "SimMetricsMatcher",
var model = new MatcherModel Pattern = "x"
{ };
Name = "SimMetricsMatcher.error",
Pattern = "x"
};
// Act // Act
Check.ThatCode(() => _sut.Map(model)).Throws<NotSupportedException>(); var matcher = (SimMetricsMatcher)_sut.Map(model)!;
}
[Fact] // Assert
public void MatcherModelMapper_Map_MatcherModelToCustomMatcher() Check.That(matcher.GetPatterns()).ContainsExactly("x");
}
[Fact]
public void MatcherModelMapper_Map_SimMetricsMatcher_BlockDistance()
{
// Assign
var model = new MatcherModel
{ {
// Arrange Name = "SimMetricsMatcher.BlockDistance",
var patternModel = new CustomPathParamMatcherModel("/customer/{customerId}/document/{documentId}", Pattern = "x"
new Dictionary<string, string>(2) };
{
{ "customerId", @"^[0-9]+$" },
{ "documentId", @"^[0-9a-zA-Z\-\_]+\.[a-zA-Z]+$" }
});
var model = new MatcherModel
{
Name = nameof(CustomPathParamMatcher),
Pattern = JsonConvert.SerializeObject(patternModel)
};
var settings = new WireMockServerSettings(); // Act
settings.CustomMatcherMappings = settings.CustomMatcherMappings ?? new Dictionary<string, Func<MatcherModel, IMatcher>>(); var matcher = (SimMetricsMatcher)_sut.Map(model)!;
settings.CustomMatcherMappings[nameof(CustomPathParamMatcher)] = matcherModel =>
{
var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)matcherModel.Pattern);
return new CustomPathParamMatcher(
matcherModel.RejectOnMatch == true ? MatchBehaviour.RejectOnMatch : MatchBehaviour.AcceptOnMatch,
matcherParams.Path, matcherParams.PathParams,
settings.ThrowExceptionWhenMatcherFails == true
);
};
var sut = new MatcherMapper(settings);
// Act // Assert
var matcher = sut.Map(model) as CustomPathParamMatcher; Check.That(matcher.GetPatterns()).ContainsExactly("x");
}
// Assert [Fact]
matcher.Should().NotBeNull(); public void MatcherModelMapper_Map_SimMetricsMatcher_Throws1()
} {
// Assign
[Fact] var model = new MatcherModel
public void MatcherModelMapper_Map_CustomMatcherToMatcherModel()
{ {
// Arrange Name = "error",
var matcher = new CustomPathParamMatcher("/customer/{customerId}/document/{documentId}", Pattern = "x"
new Dictionary<string, string>(2) };
{
{ "customerId", @"^[0-9]+$" },
{ "documentId", @"^[0-9a-zA-Z\-\_]+\.[a-zA-Z]+$" }
});
// Act // Act
var model = _sut.Map(matcher); Check.ThatCode(() => _sut.Map(model)).Throws<NotSupportedException>();
}
// Assert [Fact]
using (new AssertionScope()) public void MatcherModelMapper_Map_SimMetricsMatcher_Throws2()
{
// Assign
var model = new MatcherModel
{
Name = "SimMetricsMatcher.error",
Pattern = "x"
};
// Act
Check.ThatCode(() => _sut.Map(model)).Throws<NotSupportedException>();
}
[Fact]
public void MatcherModelMapper_Map_MatcherModelToCustomMatcher()
{
// Arrange
var patternModel = new CustomPathParamMatcherModel("/customer/{customerId}/document/{documentId}",
new Dictionary<string, string>(2)
{ {
model.Should().NotBeNull(); { "customerId", @"^[0-9]+$" },
model.Name.Should().Be(nameof(CustomPathParamMatcher)); { "documentId", @"^[0-9a-zA-Z\-\_]+\.[a-zA-Z]+$" }
});
var model = new MatcherModel
{
Name = nameof(CustomPathParamMatcher),
Pattern = JsonConvert.SerializeObject(patternModel)
};
var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)model.Pattern); var settings = new WireMockServerSettings();
matcherParams.Path.Should().Be("/customer/{customerId}/document/{documentId}"); settings.CustomMatcherMappings = settings.CustomMatcherMappings ?? new Dictionary<string, Func<MatcherModel, IMatcher>>();
matcherParams.PathParams.Should().BeEquivalentTo(new Dictionary<string, string>(2) settings.CustomMatcherMappings[nameof(CustomPathParamMatcher)] = matcherModel =>
{ {
{ "customerId", @"^[0-9]+$" }, var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)matcherModel.Pattern!)!;
{ "documentId", @"^[0-9a-zA-Z\-\_]+\.[a-zA-Z]+$" } return new CustomPathParamMatcher(
}); matcherModel.RejectOnMatch == true ? MatchBehaviour.RejectOnMatch : MatchBehaviour.AcceptOnMatch,
} matcherParams.Path,
matcherParams.PathParams,
settings.ThrowExceptionWhenMatcherFails == true
);
};
var sut = new MatcherMapper(settings);
// Act
var matcher = sut.Map(model) as CustomPathParamMatcher;
// Assert
matcher.Should().NotBeNull();
}
[Fact]
public void MatcherModelMapper_Map_CustomMatcherToMatcherModel()
{
// Arrange
var matcher = new CustomPathParamMatcher("/customer/{customerId}/document/{documentId}",
new Dictionary<string, string>(2)
{
{ "customerId", @"^[0-9]+$" },
{ "documentId", @"^[0-9a-zA-Z\-\_]+\.[a-zA-Z]+$" }
});
// Act
var model = _sut.Map(matcher)!;
// Assert
using (new AssertionScope())
{
model.Should().NotBeNull();
model.Name.Should().Be(nameof(CustomPathParamMatcher));
var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)model.Pattern!)!;
matcherParams.Path.Should().Be("/customer/{customerId}/document/{documentId}");
matcherParams.PathParams.Should().BeEquivalentTo(new Dictionary<string, string>(2)
{
{ "customerId", @"^[0-9]+$" },
{ "documentId", @"^[0-9a-zA-Z\-\_]+\.[a-zA-Z]+$" }
});
} }
} }
} }