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>
/// Gets or sets the name.
/// </summary>
public string Name { get; set; }
public string Name { get; set; } = null!;
/// <summary>
/// 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.
/// </summary>
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>
/// Determines whether the specified RequestMessage is match.
/// </summary>
@@ -16,5 +14,4 @@ namespace WireMock.Matchers.Request
/// A value between 0.0 - 1.0 of the similarity.
/// </returns>
double GetMatchingScore(IRequestMessage requestMessage, IRequestMatchResult requestMatchResult);
}
}
@@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using WireMock.Util;
namespace WireMock.Matchers;
@@ -9,15 +10,22 @@ namespace WireMock.Matchers;
/// </summary>
public abstract class AbstractJsonPartialMatcher : JsonMatcher
{
/// <summary>
/// Support Regex
/// </summary>
public bool Regex { get; }
/// <summary>
/// Initializes a new instance of the <see cref="AbstractJsonPartialMatcher"/> class.
/// </summary>
/// <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="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)
{
Regex = regex;
}
/// <summary>
@@ -26,9 +34,11 @@ public abstract class AbstractJsonPartialMatcher : JsonMatcher
/// <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="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)
{
Regex = regex;
}
/// <summary>
@@ -38,9 +48,11 @@ public abstract class AbstractJsonPartialMatcher : JsonMatcher
/// <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="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)
{
Regex = regex;
}
/// <inheritdoc />
@@ -51,6 +63,17 @@ public abstract class AbstractJsonPartialMatcher : JsonMatcher
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)
{
return false;
+3 -3
View File
@@ -13,12 +13,12 @@ namespace WireMock.Matchers;
/// </summary>
public class JsonMatcher : IValueMatcher, IIgnoreCaseMatcher
{
/// <inheritdoc cref="IValueMatcher.Value"/>
public object Value { get; }
/// <inheritdoc cref="IMatcher.Name"/>
public virtual string Name => "JsonMatcher";
/// <inheritdoc cref="IValueMatcher.Value"/>
public object Value { get; }
/// <inheritdoc cref="IMatcher.MatchBehaviour"/>
public MatchBehaviour MatchBehaviour { get; }
@@ -9,20 +9,20 @@ public class JsonPartialMatcher : AbstractJsonPartialMatcher
public override string Name => nameof(JsonPartialMatcher);
/// <inheritdoc />
public JsonPartialMatcher(string value, bool ignoreCase = false, bool throwException = false)
: base(value, ignoreCase, throwException)
public JsonPartialMatcher(string value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(value, ignoreCase, throwException, regex)
{
}
/// <inheritdoc />
public JsonPartialMatcher(object value, bool ignoreCase = false, bool throwException = false)
: base(value, ignoreCase, throwException)
public JsonPartialMatcher(object value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(value, ignoreCase, throwException, regex)
{
}
/// <inheritdoc />
public JsonPartialMatcher(MatchBehaviour matchBehaviour, object value, bool ignoreCase = false, bool throwException = false)
: base(matchBehaviour, value, ignoreCase, throwException)
public JsonPartialMatcher(MatchBehaviour matchBehaviour, object value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(matchBehaviour, value, ignoreCase, throwException, regex)
{
}
@@ -1,5 +1,3 @@
using JetBrains.Annotations;
namespace WireMock.Matchers;
/// <summary>
@@ -11,20 +9,20 @@ public class JsonPartialWildcardMatcher : AbstractJsonPartialMatcher
public override string Name => nameof(JsonPartialWildcardMatcher);
/// <inheritdoc />
public JsonPartialWildcardMatcher(string value, bool ignoreCase = false, bool throwException = false)
: base(value, ignoreCase, throwException)
public JsonPartialWildcardMatcher(string value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(value, ignoreCase, throwException, regex)
{
}
/// <inheritdoc />
public JsonPartialWildcardMatcher(object value, bool ignoreCase = false, bool throwException = false)
: base(value, ignoreCase, throwException)
public JsonPartialWildcardMatcher(object value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(value, ignoreCase, throwException, regex)
{
}
/// <inheritdoc />
public JsonPartialWildcardMatcher(MatchBehaviour matchBehaviour, object value, bool ignoreCase = false, bool throwException = false)
: base(matchBehaviour, value, ignoreCase, throwException)
public JsonPartialWildcardMatcher(MatchBehaviour matchBehaviour, object value, bool ignoreCase = false, bool throwException = false, bool regex = false)
: base(matchBehaviour, value, ignoreCase, throwException, regex)
{
}
@@ -23,7 +23,7 @@ public class RequestMessageHeaderMatcher : IRequestMatcher
/// <summary>
/// The name
/// </summary>
public string? Name { get; }
public string Name { get; }
/// <value>
/// The matchers.
@@ -94,6 +94,7 @@ public class RequestMessageHeaderMatcher : IRequestMatcher
public RequestMessageHeaderMatcher(params Func<IDictionary<string, string[]>, bool>[] funcs)
{
Funcs = Guard.NotNull(funcs);
Name = string.Empty; // Not used when Func, but set to a non-null valid value.
}
/// <inheritdoc />
@@ -121,7 +122,7 @@ public class RequestMessageHeaderMatcher : IRequestMatcher
if (Matchers != null)
{
if (!headers.ContainsKey(Name!))
if (!headers.ContainsKey(Name))
{
return MatchBehaviourHelper.Convert(_matchBehaviour, MatchScores.Mismatch);
}
@@ -129,7 +130,7 @@ public class RequestMessageHeaderMatcher : IRequestMatcher
var results = new List<double>();
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));
}
@@ -92,7 +92,7 @@ public class RequestMessageParamMatcher : IRequestMatcher
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)
{
// Key is not present at all, just return Mismatch
@@ -102,7 +102,7 @@ public class RequestMessageParamMatcher : IRequestMatcher
if (Matchers != null && Matchers.Any())
{
// Return the score based on Matchers and valuesPresentInRequestMessage
return CalculateScore(valuesPresentInRequestMessage);
return CalculateScore(Matchers, valuesPresentInRequestMessage);
}
if (Matchers == null || !Matchers.Any())
@@ -114,14 +114,14 @@ public class RequestMessageParamMatcher : IRequestMatcher
return MatchScores.Mismatch;
}
private double CalculateScore(WireMockList<string> valuesPresentInRequestMessage)
private double CalculateScore(IReadOnlyList<IStringMatcher> matchers, WireMockList<string> valuesPresentInRequestMessage)
{
var total = new List<double>();
// 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;
foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage)
@@ -136,7 +136,7 @@ public class RequestMessageParamMatcher : IRequestMatcher
{
foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage)
{
double score = Matchers.Max(m => m.IsMatch(valuePresentInRequestMessage));
double score = matchers.Max(m => m.IsMatch(valuePresentInRequestMessage));
total.Add(score);
}
}
@@ -3,16 +3,16 @@ using System.Collections.Generic;
using System.Text.RegularExpressions;
using Stef.Validation;
namespace WireMock.RegularExpressions
{
/// <summary>
/// Extension to the <see cref="Regex"/> object, adding support for GUID tokens for matching on.
/// </summary>
namespace WireMock.RegularExpressions;
/// <summary>
/// Extension to the <see cref="Regex"/> object, adding support for GUID tokens for matching on.
/// </summary>
#if !NETSTANDARD1_3
[Serializable]
[Serializable]
#endif
internal class RegexExtended : Regex
{
internal class RegexExtended : Regex
{
/// <inheritdoc cref="Regex"/>
public RegexExtended(string pattern) : this(pattern, RegexOptions.None)
{
@@ -38,7 +38,7 @@ namespace WireMock.RegularExpressions
}
#endif
// 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}\})" },
@@ -86,5 +86,4 @@ namespace WireMock.RegularExpressions
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.
// For more details see 'mock4net/LICENSE.txt' and 'mock4net/readme.md' in this project root.
using JetBrains.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Stef.Validation;
using WireMock.Models;
using WireMock.Types;
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" />
public string ClientIP { get; }
@@ -144,7 +143,7 @@ namespace WireMock
/// <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)
public WireMockList<string>? GetParameter(string key, bool ignoreCase = false)
{
if (Query == null)
{
@@ -155,5 +154,4 @@ namespace WireMock
return query.ContainsKey(key) ? query[key] : null;
}
}
}
@@ -47,6 +47,7 @@ internal class MatcherMapper
bool ignoreCase = matcher.IgnoreCase == true;
bool throwExceptionWhenMatcherFails = _settings.ThrowExceptionWhenMatcherFails == true;
bool useRegexExtended = _settings.UseRegexExtended == true;
bool useRegex = matcher.Regex == true;
switch (matcherName)
{
@@ -79,11 +80,11 @@ internal class MatcherMapper
case nameof(JsonPartialMatcher):
var valueForJsonPartialMatcher = matcher.Pattern ?? matcher.Patterns;
return new JsonPartialMatcher(matchBehaviour, valueForJsonPartialMatcher!, ignoreCase, throwExceptionWhenMatcherFails);
return new JsonPartialMatcher(matchBehaviour, valueForJsonPartialMatcher!, ignoreCase, throwExceptionWhenMatcherFails, useRegex);
case nameof(JsonPartialWildcardMatcher):
var valueForJsonPartialWildcardMatcher = matcher.Pattern ?? matcher.Patterns;
return new JsonPartialWildcardMatcher(matchBehaviour, valueForJsonPartialWildcardMatcher!, ignoreCase, throwExceptionWhenMatcherFails);
return new JsonPartialWildcardMatcher(matchBehaviour, valueForJsonPartialWildcardMatcher!, ignoreCase, throwExceptionWhenMatcherFails, useRegex);
case nameof(JsonPathMatcher):
return new JsonPathMatcher(matchBehaviour, throwExceptionWhenMatcherFails, matchOperator, stringPatterns);
@@ -146,6 +147,17 @@ internal class MatcherMapper
Name = matcher.Name
};
switch (matcher)
{
case JsonPartialMatcher jsonPartialMatcher:
model.Regex = jsonPartialMatcher.Regex;
break;
case JsonPartialWildcardMatcher jsonPartialWildcardMatcher:
model.Regex = jsonPartialWildcardMatcher.Regex;
break;
}
switch (matcher)
{
// If the matcher is a IStringMatcher, get the operator & patterns.
@@ -293,7 +293,7 @@ public partial class WireMockServer
private IResponseMessage SettingsUpdate(IRequestMessage requestMessage)
{
var settings = DeserializeObject<SettingsModel>(requestMessage);
var settings = DeserializeObject<SettingsModel>(requestMessage)!;
// _settings
_settings.AllowBodyForAllHttpMethods = settings.AllowBodyForAllHttpMethods;
@@ -9,9 +9,9 @@ using WireMock.Handlers;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.RegularExpressions;
using WireMock.Types;
#if USE_ASPNETCORE
using Microsoft.Extensions.DependencyInjection;
using WireMock.Types;
#endif
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 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)
{
var namedGroupsDictionary = new Dictionary<string, string>();
@@ -20,5 +24,30 @@ namespace WireMock.Util
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.Collections.Generic;
using System;
using System.IO;
using FluentAssertions;
using Newtonsoft.Json;
@@ -42,6 +41,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialMatcher_WithInvalidStringValue_Should_ThrowException()
{
// Act
// ReSharper disable once ObjectCreationAsStatement
Action action = () => new JsonPartialMatcher(MatchBehaviour.AcceptOnMatch, "{ \"Id\"");
// Assert
@@ -52,6 +52,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialMatcher_WithInvalidObjectValue_Should_ThrowException()
{
// Act
// ReSharper disable once ObjectCreationAsStatement
Action action = () => new JsonPartialMatcher(MatchBehaviour.AcceptOnMatch, new MemoryStream());
// Assert
@@ -102,7 +103,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialMatcher_IsMatch_NullString()
{
// Assign
string s = null;
string? s = null;
var matcher = new JsonPartialMatcher("");
// Act
@@ -116,7 +117,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialMatcher_IsMatch_NullObject()
{
// Assign
object o = null;
object? o = null;
var matcher = new JsonPartialMatcher("");
// Act
@@ -151,17 +152,53 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher(new { Id = 1, Name = "Test" });
// Act
var jobject = new JObject
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
double match = matcher.IsMatch(jObject);
// Assert
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]
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);
// Act
var jobject = new JObject
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "NaMe", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -187,8 +224,8 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher(new { Id = 1, Name = "Test" });
// Act
var jobject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jobject);
var jObject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -201,8 +238,8 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher(new { Id = 1, Name = "TESt" }, true);
// Act
var jobject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jobject);
var jObject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -233,12 +270,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher("{ \"Id\" : 1, \"Name\" : \"Test\" }");
// Act
var jobject = new JObject
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -251,12 +288,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher("{ \"Id\" : 1, \"Name\" : \"test\" }", true);
// Act
var jobject = new JObject
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -269,12 +306,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialMatcher(MatchBehaviour.RejectOnMatch, "{ \"Id\" : 1, \"Name\" : \"Test\" }");
// Act
var jobject = new JObject
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
double match = matcher.IsMatch(jObject);
// Assert
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\" }");
// Act
var jobject = new JObject
var jObject = new JObject
{
{ "preferredAt", new JValue("2019-11-21T10:32:53.2210009+00:00") }
};
double match = matcher.IsMatch(jobject);
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.IO;
using FluentAssertions;
using Newtonsoft.Json;
@@ -8,10 +7,10 @@ using NFluent;
using WireMock.Matchers;
using Xunit;
namespace WireMock.Net.Tests.Matchers
namespace WireMock.Net.Tests.Matchers;
public class JsonPartialWildcardMatcherTests
{
public class JsonPartialWildcardMatcherTests
{
[Fact]
public void JsonPartialWildcardMatcher_GetName()
{
@@ -42,6 +41,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialWildcardMatcher_WithInvalidStringValue_Should_ThrowException()
{
// Act
// ReSharper disable once ObjectCreationAsStatement
Action action = () => new JsonPartialWildcardMatcher(MatchBehaviour.AcceptOnMatch, "{ \"Id\"");
// Assert
@@ -52,6 +52,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialWildcardMatcher_WithInvalidObjectValue_Should_ThrowException()
{
// Act
// ReSharper disable once ObjectCreationAsStatement
Action action = () => new JsonPartialWildcardMatcher(MatchBehaviour.AcceptOnMatch, new MemoryStream());
// Assert
@@ -102,7 +103,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialWildcardMatcher_IsMatch_NullString()
{
// Assign
string s = null;
string? s = null;
var matcher = new JsonPartialWildcardMatcher("");
// Act
@@ -116,7 +117,7 @@ namespace WireMock.Net.Tests.Matchers
public void JsonPartialWildcardMatcher_IsMatch_NullObject()
{
// Assign
object o = null;
object? o = null;
var matcher = new JsonPartialWildcardMatcher("");
// Act
@@ -151,12 +152,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher(new { Id = 1, Name = "Test" });
// Act
var jobject = new JObject
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -169,12 +170,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher(new { id = 1, Name = "test" }, true);
// Act
var jobject = new JObject
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "NaMe", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -187,8 +188,8 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher(new { Id = 1, Name = "Test" });
// Act
var jobject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jobject);
var jObject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -201,8 +202,8 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher(new { Id = 1, Name = "TESt" }, true);
// Act
var jobject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jobject);
var jObject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }");
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -233,12 +234,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher("{ \"Id\" : 1, \"Name\" : \"Test\" }");
// Act
var jobject = new JObject
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -251,12 +252,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher("{ \"Id\" : 1, \"Name\" : \"test\" }", true);
// Act
var jobject = new JObject
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -269,12 +270,12 @@ namespace WireMock.Net.Tests.Matchers
var matcher = new JsonPartialWildcardMatcher(MatchBehaviour.RejectOnMatch, "{ \"Id\" : 1, \"Name\" : \"Test\" }");
// Act
var jobject = new JObject
var jObject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
double match = matcher.IsMatch(jObject);
// Assert
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\" }");
// Act
var jobject = new JObject
var jObject = new JObject
{
{ "preferredAt", new JValue("2019-11-21T10:32:53.2210009+00:00") }
};
double match = matcher.IsMatch(jobject);
double match = matcher.IsMatch(jObject);
// Assert
Assert.Equal(1.0, match);
@@ -396,5 +397,4 @@ namespace WireMock.Net.Tests.Matchers
// Assert
Assert.Equal(0.0, match);
}
}
}
@@ -5,10 +5,10 @@ using WireMock.Matchers.Request;
using WireMock.Models;
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()
{
@@ -165,5 +165,4 @@ namespace WireMock.Net.Tests.RequestMatchers
// Assert
Check.That(score).IsEqualTo(1.0d);
}
}
}
@@ -1,12 +1,12 @@
using NFluent;
using NFluent;
using WireMock.Models;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests
namespace WireMock.Net.Tests;
public class RequestMessageTests
{
public class RequestMessageTests
{
private const string ClientIp = "::1";
[Fact]
@@ -103,5 +103,4 @@ namespace WireMock.Net.Tests
// Assert
Check.That(request.PathSegments).ContainsExactly("a", "b", "c");
}
}
}
@@ -10,11 +10,11 @@ using WireMock.Serialization;
using WireMock.Settings;
using Xunit;
namespace WireMock.Net.Tests.Serialization
namespace WireMock.Net.Tests.Serialization;
public class MatcherMapperTests
{
public class MatcherMapperTests
{
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
private readonly WireMockServerSettings _settings = new();
private readonly MatcherMapper _sut;
public MatcherMapperTests()
@@ -26,7 +26,7 @@ namespace WireMock.Net.Tests.Serialization
public void MatcherMapper_Map_IMatcher_Null()
{
// Act
var model = _sut.Map((IMatcher)null);
var model = _sut.Map((IMatcher?)null);
// Assert
model.Should().BeNull();
@@ -36,7 +36,7 @@ namespace WireMock.Net.Tests.Serialization
public void MatcherMapper_Map_IMatchers_Null()
{
// Act
var model = _sut.Map((IMatcher[])null);
var model = _sut.Map((IMatcher[]?)null);
// Assert
model.Should().BeNull();
@@ -65,7 +65,7 @@ namespace WireMock.Net.Tests.Serialization
matcherMock.Setup(m => m.GetPatterns()).Returns(new AnyOf<string, StringPattern>[] { "p1", "p2" });
// Act
var model = _sut.Map(matcherMock.Object);
var model = _sut.Map(matcherMock.Object)!;
// Assert
model.IgnoreCase.Should().BeNull();
@@ -87,7 +87,7 @@ namespace WireMock.Net.Tests.Serialization
matcherMock.Setup(m => m.GetPatterns()).Returns(new AnyOf<string, StringPattern>[] { pattern });
// Act
var model = _sut.Map(matcherMock.Object);
var model = _sut.Map(matcherMock.Object)!;
// Assert
model.IgnoreCase.Should().BeNull();
@@ -105,7 +105,7 @@ namespace WireMock.Net.Tests.Serialization
matcherMock.Setup(m => m.IgnoreCase).Returns(true);
// Act
var model = _sut.Map(matcherMock.Object);
var model = _sut.Map(matcherMock.Object)!;
// Assert
model.IgnoreCase.Should().BeTrue();
@@ -115,7 +115,7 @@ namespace WireMock.Net.Tests.Serialization
public void MatcherMapper_Map_MatcherModel_Null()
{
// Act
var result = _sut.Map((MatcherModel)null);
var result = _sut.Map((MatcherModel?)null);
// Assert
result.Should().BeNull();
@@ -142,7 +142,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (LinqMatcher)_sut.Map(model);
var matcher = (LinqMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -160,7 +160,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (LinqMatcher)_sut.Map(model);
var matcher = (LinqMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -179,7 +179,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -199,7 +199,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -220,7 +220,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -239,7 +239,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -259,7 +259,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -280,7 +280,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -299,7 +299,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model);
var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -320,7 +320,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model);
var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -339,7 +339,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model);
var matcher = (JsonPartialMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -360,7 +360,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (JsonMatcher)_sut.Map(model);
var matcher = (JsonMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
@@ -375,34 +375,37 @@ namespace WireMock.Net.Tests.Serialization
var model = new MatcherModel
{
Name = "JsonPartialMatcher",
Pattern = pattern
Pattern = pattern,
Regex = true
};
// Act
var matcher = (JsonPartialMatcher)_sut.Map(model);
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_JsonPartialWilcardMatcher_Patterns_As_Object()
public void MatcherMapper_Map_MatcherModel_JsonPartialWildcardMatcher_Patterns_As_Object()
{
// Assign
object pattern = new { X = "*" };
var model = new MatcherModel
{
Name = "JsonPartialWildcardMatcher",
Pattern = pattern
Pattern = pattern,
Regex = false
};
// Act
var matcher = (JsonPartialWildcardMatcher)_sut.Map(model);
var matcher = (JsonPartialWildcardMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.Value.Should().BeEquivalentTo(pattern);
}
matcher.Regex.Should().BeFalse();
}
}
@@ -14,11 +14,11 @@ using WireMock.Serialization;
using WireMock.Settings;
using Xunit;
namespace WireMock.Net.Tests.Serialization
namespace WireMock.Net.Tests.Serialization;
public class MatcherModelMapperTests
{
public class MatcherModelMapperTests
{
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
private readonly WireMockServerSettings _settings = new();
private readonly MatcherMapper _sut;
@@ -39,14 +39,14 @@ namespace WireMock.Net.Tests.Serialization
var sut = new MatcherMapper(new WireMockServerSettings { AllowCSharpCodeMatcher = true });
// Act 1
var matcher1 = (ICSharpCodeMatcher)sut.Map(model);
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);
var matcher2 = (ICSharpCodeMatcher)sut.Map(model)!;
// Assert 2
matcher2.Should().NotBeNull();
@@ -75,7 +75,7 @@ namespace WireMock.Net.Tests.Serialization
public void MatcherModelMapper_Map_Null()
{
// Act
IMatcher matcher = _sut.Map((MatcherModel)null);
IMatcher matcher = _sut.Map((MatcherModel?)null)!;
// Assert
Check.That(matcher).IsNull();
@@ -92,7 +92,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (ExactMatcher)_sut.Map(model);
var matcher = (ExactMatcher)_sut.Map(model)!;
// Assert
matcher.GetPatterns().Should().ContainSingle("x");
@@ -110,18 +110,66 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (ExactMatcher)_sut.Map(model);
var matcher = (ExactMatcher)_sut.Map(model)!;
// Assert
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]
[InlineData(nameof(LinqMatcher))]
[InlineData(nameof(ExactMatcher))]
[InlineData(nameof(ExactObjectMatcher))]
[InlineData(nameof(RegexMatcher))]
[InlineData(nameof(JsonMatcher))]
[InlineData(nameof(JsonPartialMatcher))]
[InlineData(nameof(JsonPartialWildcardMatcher))]
[InlineData(nameof(JsonPathMatcher))]
[InlineData(nameof(JmesPathMatcher))]
[InlineData(nameof(XPathMatcher))]
@@ -143,9 +191,10 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = sut.Map(model);
var matcher = sut.Map(model)!;
// Assert
matcher.Should().NotBeNull();
matcher.ThrowException.Should().BeTrue();
}
@@ -160,7 +209,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (ExactObjectMatcher)_sut.Map(model);
var matcher = (ExactObjectMatcher)_sut.Map(model)!;
// Assert
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);
// Act
var matcher = (WildcardMatcher)sut.Map(model);
var matcher = (WildcardMatcher)sut.Map(model)!;
// Assert
matcher.GetPatterns().Should().HaveCount(1).And.Contain(new AnyOf<string, StringPattern>(stringPattern));
@@ -271,7 +320,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (SimMetricsMatcher)_sut.Map(model);
var matcher = (SimMetricsMatcher)_sut.Map(model)!;
// Assert
Check.That(matcher.GetPatterns()).ContainsExactly("x");
@@ -288,7 +337,7 @@ namespace WireMock.Net.Tests.Serialization
};
// Act
var matcher = (SimMetricsMatcher)_sut.Map(model);
var matcher = (SimMetricsMatcher)_sut.Map(model)!;
// Assert
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[nameof(CustomPathParamMatcher)] = matcherModel =>
{
var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)matcherModel.Pattern);
var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)matcherModel.Pattern!)!;
return new CustomPathParamMatcher(
matcherModel.RejectOnMatch == true ? MatchBehaviour.RejectOnMatch : MatchBehaviour.AcceptOnMatch,
matcherParams.Path, matcherParams.PathParams,
matcherParams.Path,
matcherParams.PathParams,
settings.ThrowExceptionWhenMatcherFails == true
);
};
@@ -370,7 +420,7 @@ namespace WireMock.Net.Tests.Serialization
});
// Act
var model = _sut.Map(matcher);
var model = _sut.Map(matcher)!;
// Assert
using (new AssertionScope())
@@ -378,7 +428,7 @@ namespace WireMock.Net.Tests.Serialization
model.Should().NotBeNull();
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.PathParams.Should().BeEquivalentTo(new Dictionary<string, string>(2)
{
@@ -387,5 +437,4 @@ namespace WireMock.Net.Tests.Serialization
});
}
}
}
}