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
@@ -1,15 +1,15 @@
namespace WireMock.Admin.Mappings namespace WireMock.Admin.Mappings;
/// <summary>
/// MatcherModel
/// </summary>
[FluentBuilder.AutoGenerateBuilder]
public class MatcherModel
{ {
/// <summary>
/// MatcherModel
/// </summary>
[FluentBuilder.AutoGenerateBuilder]
public class MatcherModel
{
/// <summary> /// <summary>
/// Gets or sets the name. /// Gets or sets the name.
/// </summary> /// </summary>
public string Name { get; set; } public string Name { get; set; } = null!;
/// <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.
@@ -44,5 +44,9 @@ namespace WireMock.Admin.Mappings
/// - "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; }
} }
@@ -1,12 +1,10 @@
using JetBrains.Annotations; namespace WireMock.Matchers.Request;
namespace WireMock.Matchers.Request /// <summary>
/// The RequestMatcher interface.
/// </summary>
public interface IRequestMatcher
{ {
/// <summary>
/// The RequestMatcher interface.
/// </summary>
public interface IRequestMatcher
{
/// <summary> /// <summary>
/// Determines whether the specified RequestMessage is match. /// Determines whether the specified RequestMessage is match.
/// </summary> /// </summary>
@@ -16,5 +14,4 @@ namespace WireMock.Matchers.Request
/// A value between 0.0 - 1.0 of the similarity. /// A value between 0.0 - 1.0 of the similarity.
/// </returns> /// </returns>
double GetMatchingScore(IRequestMessage requestMessage, IRequestMatchResult requestMatchResult); double GetMatchingScore(IRequestMessage requestMessage, IRequestMatchResult requestMatchResult);
}
} }
@@ -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;
+3 -3
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; }
@@ -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)
{ {
} }
@@ -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)
{ {
} }
@@ -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));
} }
@@ -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);
} }
} }
@@ -3,16 +3,16 @@ 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> /// <summary>
/// Extension to the <see cref="Regex"/> object, adding support for GUID tokens for matching on. /// Extension to the <see cref="Regex"/> object, adding support for GUID tokens for matching on.
/// </summary> /// </summary>
#if !NETSTANDARD1_3 #if !NETSTANDARD1_3
[Serializable] [Serializable]
#endif #endif
internal class RegexExtended : Regex internal class RegexExtended : Regex
{ {
/// <inheritdoc cref="Regex"/> /// <inheritdoc cref="Regex"/>
public RegexExtended(string pattern) : this(pattern, RegexOptions.None) public RegexExtended(string pattern) : this(pattern, RegexOptions.None)
{ {
@@ -38,7 +38,7 @@ namespace WireMock.RegularExpressions
} }
#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 // Lower case format `B` Guid pattern
{ @"\guidb", @"(\{[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\})" }, { @"\guidb", @"(\{[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\})" },
@@ -86,5 +86,4 @@ namespace WireMock.RegularExpressions
return pattern; return pattern;
} }
}
} }
+8 -10
View File
@@ -1,22 +1,21 @@
// 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
{ {
/// <summary>
/// The RequestMessage.
/// </summary>
public class RequestMessage : IRequestMessage
{
/// <inheritdoc cref="IRequestMessage.ClientIP" /> /// <inheritdoc cref="IRequestMessage.ClientIP" />
public string ClientIP { get; } public string ClientIP { get; }
@@ -144,7 +143,7 @@ namespace WireMock
/// <param name="key">The key.</param> /// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param> /// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <returns>The query parameter.</returns> /// <returns>The query parameter.</returns>
public WireMockList<string>? GetParameter(string? key, bool ignoreCase = false) public WireMockList<string>? GetParameter(string key, bool ignoreCase = false)
{ {
if (Query == null) if (Query == null)
{ {
@@ -155,5 +154,4 @@ namespace WireMock
return query.ContainsKey(key) ? query[key] : null; return query.ContainsKey(key) ? query[key] : null;
} }
}
} }
@@ -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.
@@ -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;
@@ -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
+33 -4
View File
@@ -1,10 +1,14 @@
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>(); var namedGroupsDictionary = new Dictionary<string, string>();
@@ -20,5 +24,30 @@ namespace WireMock.Util
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);
}
} }
} }
@@ -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);
@@ -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,10 +7,10 @@ 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] [Fact]
public void JsonPartialWildcardMatcher_GetName() public void JsonPartialWildcardMatcher_GetName()
{ {
@@ -42,6 +41,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialWildcardMatcher_WithInvalidStringValue_Should_ThrowException() public void JsonPartialWildcardMatcher_WithInvalidStringValue_Should_ThrowException()
{ {
// Act // Act
// ReSharper disable once ObjectCreationAsStatement
Action action = () => new JsonPartialWildcardMatcher(MatchBehaviour.AcceptOnMatch, "{ \"Id\""); Action action = () => new JsonPartialWildcardMatcher(MatchBehaviour.AcceptOnMatch, "{ \"Id\"");
// Assert // Assert
@@ -52,6 +52,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialWildcardMatcher_WithInvalidObjectValue_Should_ThrowException() public void JsonPartialWildcardMatcher_WithInvalidObjectValue_Should_ThrowException()
{ {
// Act // Act
// ReSharper disable once ObjectCreationAsStatement
Action action = () => new JsonPartialWildcardMatcher(MatchBehaviour.AcceptOnMatch, new MemoryStream()); Action action = () => new JsonPartialWildcardMatcher(MatchBehaviour.AcceptOnMatch, new MemoryStream());
// Assert // Assert
@@ -102,7 +103,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialWildcardMatcher_IsMatch_NullString() public void JsonPartialWildcardMatcher_IsMatch_NullString()
{ {
// Assign // Assign
string s = null; string? s = null;
var matcher = new JsonPartialWildcardMatcher(""); var matcher = new JsonPartialWildcardMatcher("");
// Act // Act
@@ -116,7 +117,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialWildcardMatcher_IsMatch_NullObject() public void JsonPartialWildcardMatcher_IsMatch_NullObject()
{ {
// Assign // Assign
object o = null; object? o = null;
var matcher = new JsonPartialWildcardMatcher(""); var matcher = new JsonPartialWildcardMatcher("");
// Act // Act
@@ -151,12 +152,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher(new { Id = 1, Name = "Test" }); var matcher = new JsonPartialWildcardMatcher(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);
@@ -169,12 +170,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher(new { id = 1, Name = "test" }, true); var matcher = new JsonPartialWildcardMatcher(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 +188,8 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher(new { Id = 1, Name = "Test" }); var matcher = new JsonPartialWildcardMatcher(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 +202,8 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher(new { Id = 1, Name = "TESt" }, true); var matcher = new JsonPartialWildcardMatcher(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 +234,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher("{ \"Id\" : 1, \"Name\" : \"Test\" }"); var matcher = new JsonPartialWildcardMatcher("{ \"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 +252,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher("{ \"Id\" : 1, \"Name\" : \"test\" }", true); var matcher = new JsonPartialWildcardMatcher("{ \"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 +270,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher(MatchBehaviour.RejectOnMatch, "{ \"Id\" : 1, \"Name\" : \"Test\" }"); var matcher = new JsonPartialWildcardMatcher(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 +288,11 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher("{ \"preferredAt\" : \"2019-11-21T10:32:53.2210009+00:00\" }"); var matcher = new JsonPartialWildcardMatcher("{ \"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);
@@ -396,5 +397,4 @@ namespace WireMock.Net.Tests.Matchers
// Assert // Assert
Assert.Equal(0.0, match); Assert.Equal(0.0, match);
} }
}
} }
@@ -5,10 +5,10 @@ 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] [Fact]
public void RequestMessageHeaderMatcher_GetMatchingScore_AcceptOnMatch_HeaderDoesNotExists() public void RequestMessageHeaderMatcher_GetMatchingScore_AcceptOnMatch_HeaderDoesNotExists()
{ {
@@ -165,5 +165,4 @@ namespace WireMock.Net.Tests.RequestMatchers
// Assert // Assert
Check.That(score).IsEqualTo(1.0d); Check.That(score).IsEqualTo(1.0d);
} }
}
} }
@@ -1,12 +1,12 @@
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"; private const string ClientIp = "::1";
[Fact] [Fact]
@@ -103,5 +103,4 @@ namespace WireMock.Net.Tests
// Assert // Assert
Check.That(request.PathSegments).ContainsExactly("a", "b", "c"); Check.That(request.PathSegments).ContainsExactly("a", "b", "c");
} }
}
} }
@@ -10,11 +10,11 @@ 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 WireMockServerSettings _settings = new WireMockServerSettings();
private readonly MatcherMapper _sut; private readonly MatcherMapper _sut;
public MatcherMapperTests() public MatcherMapperTests()
@@ -26,7 +26,7 @@ namespace WireMock.Net.Tests.Serialization
public void MatcherMapper_Map_IMatcher_Null() public void MatcherMapper_Map_IMatcher_Null()
{ {
// Act // Act
var model = _sut.Map((IMatcher)null); var model = _sut.Map((IMatcher?)null);
// Assert // Assert
model.Should().BeNull(); model.Should().BeNull();
@@ -36,7 +36,7 @@ namespace WireMock.Net.Tests.Serialization
public void MatcherMapper_Map_IMatchers_Null() public void MatcherMapper_Map_IMatchers_Null()
{ {
// Act // Act
var model = _sut.Map((IMatcher[])null); var model = _sut.Map((IMatcher[]?)null);
// Assert // Assert
model.Should().BeNull(); model.Should().BeNull();
@@ -65,7 +65,7 @@ namespace WireMock.Net.Tests.Serialization
matcherMock.Setup(m => m.GetPatterns()).Returns(new AnyOf<string, StringPattern>[] { "p1", "p2" }); matcherMock.Setup(m => m.GetPatterns()).Returns(new AnyOf<string, StringPattern>[] { "p1", "p2" });
// Act // Act
var model = _sut.Map(matcherMock.Object); var model = _sut.Map(matcherMock.Object)!;
// Assert // Assert
model.IgnoreCase.Should().BeNull(); model.IgnoreCase.Should().BeNull();
@@ -87,7 +87,7 @@ namespace WireMock.Net.Tests.Serialization
matcherMock.Setup(m => m.GetPatterns()).Returns(new AnyOf<string, StringPattern>[] { pattern }); matcherMock.Setup(m => m.GetPatterns()).Returns(new AnyOf<string, StringPattern>[] { pattern });
// Act // Act
var model = _sut.Map(matcherMock.Object); var model = _sut.Map(matcherMock.Object)!;
// Assert // Assert
model.IgnoreCase.Should().BeNull(); model.IgnoreCase.Should().BeNull();
@@ -105,7 +105,7 @@ namespace WireMock.Net.Tests.Serialization
matcherMock.Setup(m => m.IgnoreCase).Returns(true); matcherMock.Setup(m => m.IgnoreCase).Returns(true);
// Act // Act
var model = _sut.Map(matcherMock.Object); var model = _sut.Map(matcherMock.Object)!;
// Assert // Assert
model.IgnoreCase.Should().BeTrue(); model.IgnoreCase.Should().BeTrue();
@@ -115,7 +115,7 @@ namespace WireMock.Net.Tests.Serialization
public void MatcherMapper_Map_MatcherModel_Null() public void MatcherMapper_Map_MatcherModel_Null()
{ {
// Act // Act
var result = _sut.Map((MatcherModel)null); var result = _sut.Map((MatcherModel?)null);
// Assert // Assert
result.Should().BeNull(); result.Should().BeNull();
@@ -142,7 +142,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (LinqMatcher)_sut.Map(model); var matcher = (LinqMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -160,7 +160,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (LinqMatcher)_sut.Map(model); var matcher = (LinqMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -179,7 +179,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (JsonMatcher)_sut.Map(model); var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -199,7 +199,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (JsonMatcher)_sut.Map(model); var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -220,7 +220,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (JsonMatcher)_sut.Map(model); var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -239,7 +239,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (JsonMatcher)_sut.Map(model); var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -259,7 +259,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (JsonMatcher)_sut.Map(model); var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -280,7 +280,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (JsonMatcher)_sut.Map(model); var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -299,7 +299,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (JsonPartialMatcher)_sut.Map(model); var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -320,7 +320,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (JsonPartialMatcher)_sut.Map(model); var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -339,7 +339,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (JsonPartialMatcher)_sut.Map(model); var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -360,7 +360,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (JsonMatcher)_sut.Map(model); var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -375,34 +375,37 @@ namespace WireMock.Net.Tests.Serialization
var model = new MatcherModel var model = new MatcherModel
{ {
Name = "JsonPartialMatcher", Name = "JsonPartialMatcher",
Pattern = pattern Pattern = pattern,
Regex = true
}; };
// Act // Act
var matcher = (JsonPartialMatcher)_sut.Map(model); var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern); matcher.Value.Should().BeEquivalentTo(pattern);
matcher.Regex.Should().BeTrue();
} }
[Fact] [Fact]
public void MatcherMapper_Map_MatcherModel_JsonPartialWilcardMatcher_Patterns_As_Object() public void MatcherMapper_Map_MatcherModel_JsonPartialWildcardMatcher_Patterns_As_Object()
{ {
// Assign // Assign
object pattern = new { X = "*" }; object pattern = new { X = "*" };
var model = new MatcherModel var model = new MatcherModel
{ {
Name = "JsonPartialWildcardMatcher", Name = "JsonPartialWildcardMatcher",
Pattern = pattern Pattern = pattern,
Regex = false
}; };
// Act // Act
var matcher = (JsonPartialWildcardMatcher)_sut.Map(model); var matcher = (JsonPartialWildcardMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern); matcher.Value.Should().BeEquivalentTo(pattern);
} matcher.Regex.Should().BeFalse();
} }
} }
@@ -14,11 +14,11 @@ 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 WireMockServerSettings _settings = new WireMockServerSettings();
private readonly MatcherMapper _sut; private readonly MatcherMapper _sut;
@@ -39,14 +39,14 @@ namespace WireMock.Net.Tests.Serialization
var sut = new MatcherMapper(new WireMockServerSettings { AllowCSharpCodeMatcher = true }); var sut = new MatcherMapper(new WireMockServerSettings { AllowCSharpCodeMatcher = true });
// Act 1 // Act 1
var matcher1 = (ICSharpCodeMatcher)sut.Map(model); var matcher1 = (ICSharpCodeMatcher)sut.Map(model)!;
// Assert 1 // Assert 1
matcher1.Should().NotBeNull(); matcher1.Should().NotBeNull();
matcher1.IsMatch("x").Should().Be(1.0d); matcher1.IsMatch("x").Should().Be(1.0d);
// Act 2 // Act 2
var matcher2 = (ICSharpCodeMatcher)sut.Map(model); var matcher2 = (ICSharpCodeMatcher)sut.Map(model)!;
// Assert 2 // Assert 2
matcher2.Should().NotBeNull(); matcher2.Should().NotBeNull();
@@ -75,7 +75,7 @@ namespace WireMock.Net.Tests.Serialization
public void MatcherModelMapper_Map_Null() public void MatcherModelMapper_Map_Null()
{ {
// Act // Act
IMatcher matcher = _sut.Map((MatcherModel)null); IMatcher matcher = _sut.Map((MatcherModel?)null)!;
// Assert // Assert
Check.That(matcher).IsNull(); Check.That(matcher).IsNull();
@@ -92,7 +92,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (ExactMatcher)_sut.Map(model); var matcher = (ExactMatcher)_sut.Map(model)!;
// Assert // Assert
matcher.GetPatterns().Should().ContainSingle("x"); matcher.GetPatterns().Should().ContainSingle("x");
@@ -110,18 +110,66 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (ExactMatcher)_sut.Map(model); var matcher = (ExactMatcher)_sut.Map(model)!;
// Assert // Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x", "y"); Check.That(matcher.GetPatterns()).ContainsExactly("x", "y");
} }
[Fact]
public void MatcherModelMapper_Map_JsonPartialMatcher_RegexFalse()
{
// Assign
var pattern = "{ \"x\": 1 }";
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Regex = false,
Pattern = pattern
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.IgnoreCase.Should().BeFalse();
matcher.Value.Should().Be(pattern);
matcher.Regex.Should().BeFalse();
matcher.ThrowException.Should().BeFalse();
}
[Fact]
public void MatcherModelMapper_Map_JsonPartialMatcher_RegexTrue()
{
// Assign
var pattern = "{ \"x\": 1 }";
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Regex = true,
Pattern = pattern
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert
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(JsonPartialMatcher))]
[InlineData(nameof(JsonPartialWildcardMatcher))]
[InlineData(nameof(JsonPathMatcher))] [InlineData(nameof(JsonPathMatcher))]
[InlineData(nameof(JmesPathMatcher))] [InlineData(nameof(JmesPathMatcher))]
[InlineData(nameof(XPathMatcher))] [InlineData(nameof(XPathMatcher))]
@@ -143,9 +191,10 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = sut.Map(model); var matcher = sut.Map(model)!;
// Assert // Assert
matcher.Should().NotBeNull();
matcher.ThrowException.Should().BeTrue(); matcher.ThrowException.Should().BeTrue();
} }
@@ -160,7 +209,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (ExactObjectMatcher)_sut.Map(model); var matcher = (ExactObjectMatcher)_sut.Map(model)!;
// Assert // Assert
Check.That(matcher.ValueAsBytes).ContainsExactly(new byte[] { 115, 116, 101, 102 }); Check.That(matcher.ValueAsBytes).ContainsExactly(new byte[] { 115, 116, 101, 102 });
@@ -253,7 +302,7 @@ namespace WireMock.Net.Tests.Serialization
var sut = new MatcherMapper(settings); var sut = new MatcherMapper(settings);
// Act // Act
var matcher = (WildcardMatcher)sut.Map(model); var matcher = (WildcardMatcher)sut.Map(model)!;
// Assert // Assert
matcher.GetPatterns().Should().HaveCount(1).And.Contain(new AnyOf<string, StringPattern>(stringPattern)); matcher.GetPatterns().Should().HaveCount(1).And.Contain(new AnyOf<string, StringPattern>(stringPattern));
@@ -271,7 +320,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (SimMetricsMatcher)_sut.Map(model); var matcher = (SimMetricsMatcher)_sut.Map(model)!;
// Assert // Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x"); Check.That(matcher.GetPatterns()).ContainsExactly("x");
@@ -288,7 +337,7 @@ namespace WireMock.Net.Tests.Serialization
}; };
// Act // Act
var matcher = (SimMetricsMatcher)_sut.Map(model); var matcher = (SimMetricsMatcher)_sut.Map(model)!;
// Assert // Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x"); Check.That(matcher.GetPatterns()).ContainsExactly("x");
@@ -342,10 +391,11 @@ namespace WireMock.Net.Tests.Serialization
settings.CustomMatcherMappings = settings.CustomMatcherMappings ?? new Dictionary<string, Func<MatcherModel, IMatcher>>(); settings.CustomMatcherMappings = settings.CustomMatcherMappings ?? new Dictionary<string, Func<MatcherModel, IMatcher>>();
settings.CustomMatcherMappings[nameof(CustomPathParamMatcher)] = matcherModel => settings.CustomMatcherMappings[nameof(CustomPathParamMatcher)] = matcherModel =>
{ {
var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)matcherModel.Pattern); var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)matcherModel.Pattern!)!;
return new CustomPathParamMatcher( return new CustomPathParamMatcher(
matcherModel.RejectOnMatch == true ? MatchBehaviour.RejectOnMatch : MatchBehaviour.AcceptOnMatch, matcherModel.RejectOnMatch == true ? MatchBehaviour.RejectOnMatch : MatchBehaviour.AcceptOnMatch,
matcherParams.Path, matcherParams.PathParams, matcherParams.Path,
matcherParams.PathParams,
settings.ThrowExceptionWhenMatcherFails == true settings.ThrowExceptionWhenMatcherFails == true
); );
}; };
@@ -370,7 +420,7 @@ namespace WireMock.Net.Tests.Serialization
}); });
// Act // Act
var model = _sut.Map(matcher); var model = _sut.Map(matcher)!;
// Assert // Assert
using (new AssertionScope()) using (new AssertionScope())
@@ -378,7 +428,7 @@ namespace WireMock.Net.Tests.Serialization
model.Should().NotBeNull(); model.Should().NotBeNull();
model.Name.Should().Be(nameof(CustomPathParamMatcher)); model.Name.Should().Be(nameof(CustomPathParamMatcher));
var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)model.Pattern); var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)model.Pattern!)!;
matcherParams.Path.Should().Be("/customer/{customerId}/document/{documentId}"); matcherParams.Path.Should().Be("/customer/{customerId}/document/{documentId}");
matcherParams.PathParams.Should().BeEquivalentTo(new Dictionary<string, string>(2) matcherParams.PathParams.Should().BeEquivalentTo(new Dictionary<string, string>(2)
{ {
@@ -387,5 +437,4 @@ namespace WireMock.Net.Tests.Serialization
}); });
} }
} }
}
} }