diff --git a/.gitignore b/.gitignore index 761a9dbe..1aad4b60 100644 --- a/.gitignore +++ b/.gitignore @@ -255,3 +255,5 @@ paket-files/ /test/WireMock.Net.Tests/coverage.opencover.xml /test/WireMock.Net.Tests/coverage.netcoreapp3.1.opencover.xml /test/WireMock.Net.Tests/coverage.net5.0.opencover.xml + +*.received.* \ No newline at end of file diff --git a/examples/WireMock.Net.Console.Net452.Classic/WireMock.Net.Console.Net452.Classic.csproj b/examples/WireMock.Net.Console.Net452.Classic/WireMock.Net.Console.Net452.Classic.csproj index 47c168c6..7fddfe52 100644 --- a/examples/WireMock.Net.Console.Net452.Classic/WireMock.Net.Console.Net452.Classic.csproj +++ b/examples/WireMock.Net.Console.Net452.Classic/WireMock.Net.Console.Net452.Classic.csproj @@ -42,11 +42,11 @@ ..\..\packages\Handlebars.Net.2.1.2\lib\net452\Handlebars.dll - - ..\..\packages\Handlebars.Net.Helpers.2.3.10\lib\net452\Handlebars.Net.Helpers.dll + + ..\..\packages\Handlebars.Net.Helpers.2.3.12\lib\net452\Handlebars.Net.Helpers.dll - - ..\..\packages\Handlebars.Net.Helpers.Core.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Core.dll + + ..\..\packages\Handlebars.Net.Helpers.Core.2.3.12\lib\net452\HandlebarsDotNet.Helpers.Core.dll ..\..\packages\log4net.2.0.15\lib\net45\log4net.dll diff --git a/examples/WireMock.Net.Console.Net452.Classic/packages.config b/examples/WireMock.Net.Console.Net452.Classic/packages.config index 387fdc06..23bb3bd4 100644 --- a/examples/WireMock.Net.Console.Net452.Classic/packages.config +++ b/examples/WireMock.Net.Console.Net452.Classic/packages.config @@ -2,8 +2,8 @@ - - + + diff --git a/examples/WireMock.Net.Console.Net461.Classic/WireMock.Net.Console.Net461.Classic.csproj b/examples/WireMock.Net.Console.Net461.Classic/WireMock.Net.Console.Net461.Classic.csproj index 7d5ae4e9..37c75a32 100644 --- a/examples/WireMock.Net.Console.Net461.Classic/WireMock.Net.Console.Net461.Classic.csproj +++ b/examples/WireMock.Net.Console.Net461.Classic/WireMock.Net.Console.Net461.Classic.csproj @@ -41,11 +41,11 @@ ..\..\packages\Handlebars.Net.2.1.2\lib\net46\Handlebars.dll - - ..\..\packages\Handlebars.Net.Helpers.2.3.10\lib\net452\Handlebars.Net.Helpers.dll + + ..\..\packages\Handlebars.Net.Helpers.2.3.12\lib\net46\Handlebars.Net.Helpers.dll - - ..\..\packages\Handlebars.Net.Helpers.Core.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Core.dll + + ..\..\packages\Handlebars.Net.Helpers.Core.2.3.12\lib\net46\HandlebarsDotNet.Helpers.Core.dll ..\..\packages\log4net.2.0.15\lib\net45\log4net.dll diff --git a/examples/WireMock.Net.Console.Net461.Classic/packages.config b/examples/WireMock.Net.Console.Net461.Classic/packages.config index 7444680b..3b84ffaf 100644 --- a/examples/WireMock.Net.Console.Net461.Classic/packages.config +++ b/examples/WireMock.Net.Console.Net461.Classic/packages.config @@ -2,8 +2,8 @@ - - + + diff --git a/examples/WireMock.Net.Console.Net472.Classic/WireMock.Net.Console.Net472.Classic.csproj b/examples/WireMock.Net.Console.Net472.Classic/WireMock.Net.Console.Net472.Classic.csproj index 90cfff20..66bf7db1 100644 --- a/examples/WireMock.Net.Console.Net472.Classic/WireMock.Net.Console.Net472.Classic.csproj +++ b/examples/WireMock.Net.Console.Net472.Classic/WireMock.Net.Console.Net472.Classic.csproj @@ -49,29 +49,29 @@ ..\..\packages\Handlebars.Net.2.1.2\lib\net46\Handlebars.dll - - ..\..\packages\Handlebars.Net.Helpers.2.3.10\lib\net452\Handlebars.Net.Helpers.dll + + ..\..\packages\Handlebars.Net.Helpers.2.3.12\lib\net46\Handlebars.Net.Helpers.dll - - ..\..\packages\Handlebars.Net.Helpers.Core.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Core.dll + + ..\..\packages\Handlebars.Net.Helpers.Core.2.3.12\lib\net46\HandlebarsDotNet.Helpers.Core.dll - - ..\..\packages\Handlebars.Net.Helpers.DynamicLinq.2.3.10\lib\net452\HandlebarsDotNet.Helpers.DynamicLinq.dll + + ..\..\packages\Handlebars.Net.Helpers.DynamicLinq.2.3.12\lib\net46\HandlebarsDotNet.Helpers.DynamicLinq.dll - - ..\..\packages\Handlebars.Net.Helpers.Humanizer.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Humanizer.dll + + ..\..\packages\Handlebars.Net.Helpers.Humanizer.2.3.12\lib\net46\HandlebarsDotNet.Helpers.Humanizer.dll - - ..\..\packages\Handlebars.Net.Helpers.Json.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Json.dll + + ..\..\packages\Handlebars.Net.Helpers.Json.2.3.12\lib\net46\HandlebarsDotNet.Helpers.Json.dll - - ..\..\packages\Handlebars.Net.Helpers.Random.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Random.dll + + ..\..\packages\Handlebars.Net.Helpers.Random.2.3.12\lib\net46\HandlebarsDotNet.Helpers.Random.dll - - ..\..\packages\Handlebars.Net.Helpers.Xeger.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Xeger.dll + + ..\..\packages\Handlebars.Net.Helpers.Xeger.2.3.12\lib\net46\HandlebarsDotNet.Helpers.Xeger.dll - - ..\..\packages\Handlebars.Net.Helpers.XPath.2.3.10\lib\net452\HandlebarsDotNet.Helpers.XPath.dll + + ..\..\packages\Handlebars.Net.Helpers.XPath.2.3.12\lib\net46\HandlebarsDotNet.Helpers.XPath.dll ..\..\packages\Humanizer.Core.2.14.1\lib\netstandard2.0\Humanizer.dll diff --git a/examples/WireMock.Net.Console.Net472.Classic/packages.config b/examples/WireMock.Net.Console.Net472.Classic/packages.config index 08972055..80bb6850 100644 --- a/examples/WireMock.Net.Console.Net472.Classic/packages.config +++ b/examples/WireMock.Net.Console.Net472.Classic/packages.config @@ -3,14 +3,14 @@ - - - - - - - - + + + + + + + + diff --git a/src/WireMock.Net.Abstractions/Types/MappingConverterType.cs b/src/WireMock.Net.Abstractions/Types/MappingConverterType.cs new file mode 100644 index 00000000..fc6e9392 --- /dev/null +++ b/src/WireMock.Net.Abstractions/Types/MappingConverterType.cs @@ -0,0 +1,11 @@ +namespace WireMock.Types; + +/// +/// +/// +public enum MappingConverterType +{ + Server, + + Builder +} \ No newline at end of file diff --git a/src/WireMock.Net.Abstractions/Types/WireMockList.cs b/src/WireMock.Net.Abstractions/Types/WireMockList.cs index 28f41040..b0a7e4f7 100644 --- a/src/WireMock.Net.Abstractions/Types/WireMockList.cs +++ b/src/WireMock.Net.Abstractions/Types/WireMockList.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; namespace WireMock.Types; @@ -63,7 +64,8 @@ public class WireMockList : List return this[0]?.ToString(); default: - return base.ToString(); + var strings = this.Select(x => x as string ?? x?.ToString()); + return string.Join(", ", strings); } } } \ No newline at end of file diff --git a/src/WireMock.Net/Extensions/EnumExtensions.cs b/src/WireMock.Net/Extensions/EnumExtensions.cs new file mode 100644 index 00000000..a407f16c --- /dev/null +++ b/src/WireMock.Net/Extensions/EnumExtensions.cs @@ -0,0 +1,20 @@ +using System; +using System.Reflection; + +namespace WireMock.Extensions; + +internal static class EnumExtensions +{ + public static string GetFullyQualifiedEnumValue(this T enumValue) + where T : struct, IConvertible + { + var type = typeof(T); + + if (!type.GetTypeInfo().IsEnum) + { + throw new ArgumentException("T must be an enum"); + } + + return $"{type.Namespace}.{type.Name}.{enumValue}"; + } +} \ No newline at end of file diff --git a/src/WireMock.Net/MappingBuilder.cs b/src/WireMock.Net/MappingBuilder.cs index 15651f72..3fda6cea 100644 --- a/src/WireMock.Net/MappingBuilder.cs +++ b/src/WireMock.Net/MappingBuilder.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Newtonsoft.Json; using Stef.Validation; @@ -8,6 +7,7 @@ using WireMock.Owin; using WireMock.Serialization; using WireMock.Server; using WireMock.Settings; +using WireMock.Util; namespace WireMock; @@ -18,9 +18,10 @@ public class MappingBuilder : IMappingBuilder { private readonly WireMockServerSettings _settings; private readonly IWireMockMiddlewareOptions _options; - private readonly MappingConverter _mappingConverter; private readonly MappingToFileSaver _mappingToFileSaver; + private readonly IGuidUtils _guidUtils; + private readonly IDateTimeUtils _dateTimeUtils; /// /// Create a MappingBuilder @@ -34,25 +35,32 @@ public class MappingBuilder : IMappingBuilder var matcherMapper = new MatcherMapper(_settings); _mappingConverter = new MappingConverter(matcherMapper); _mappingToFileSaver = new MappingToFileSaver(_settings, _mappingConverter); + + _guidUtils = new GuidUtils(); + _dateTimeUtils = new DateTimeUtils(); } internal MappingBuilder( WireMockServerSettings settings, IWireMockMiddlewareOptions options, MappingConverter mappingConverter, - MappingToFileSaver mappingToFileSaver + MappingToFileSaver mappingToFileSaver, + IGuidUtils guidUtils, + IDateTimeUtils dateTimeUtils ) { _settings = Guard.NotNull(settings); _options = Guard.NotNull(options); _mappingConverter = Guard.NotNull(mappingConverter); _mappingToFileSaver = Guard.NotNull(mappingToFileSaver); + _guidUtils = Guard.NotNull(guidUtils); + _dateTimeUtils = Guard.NotNull(dateTimeUtils); } /// public IRespondWithAProvider Given(IRequestMatcher requestMatcher, bool saveToFile = false) { - return new RespondWithAProvider(RegisterMapping, Guard.NotNull(requestMatcher), _settings, saveToFile); + return new RespondWithAProvider(RegisterMapping, Guard.NotNull(requestMatcher), _settings, _guidUtils, _dateTimeUtils, saveToFile); } /// @@ -95,7 +103,7 @@ public class MappingBuilder : IMappingBuilder // Check a mapping exists with the same Guid. If so, update the datetime and replace it. if (_options.Mappings.ContainsKey(mapping.Guid)) { - mapping.UpdatedAt = DateTime.UtcNow; + mapping.UpdatedAt = _dateTimeUtils.UtcNow; _options.Mappings[mapping.Guid] = mapping; } else diff --git a/src/WireMock.Net/RequestBuilders/ICookiesRequestBuilder.cs b/src/WireMock.Net/RequestBuilders/ICookiesRequestBuilder.cs index fd5b9aeb..a6105274 100644 --- a/src/WireMock.Net/RequestBuilders/ICookiesRequestBuilder.cs +++ b/src/WireMock.Net/RequestBuilders/ICookiesRequestBuilder.cs @@ -1,85 +1,83 @@ -using JetBrains.Annotations; using System; using System.Collections.Generic; using WireMock.Matchers; -namespace WireMock.RequestBuilders +namespace WireMock.RequestBuilders; + +/// +/// The CookieRequestBuilder interface. +/// +public interface ICookiesRequestBuilder : IParamsRequestBuilder { /// - /// The CookieRequestBuilder interface. + /// WithCookie: matching based on name, pattern and matchBehaviour. /// - public interface ICookiesRequestBuilder : IParamsRequestBuilder - { - /// - /// WithCookie: matching based on name, pattern and matchBehaviour. - /// - /// The name. - /// The pattern. - /// The match behaviour. - /// The . - IRequestBuilder WithCookie([NotNull] string name, string pattern, MatchBehaviour matchBehaviour); + /// The name. + /// The pattern. + /// The match behaviour. + /// The . + IRequestBuilder WithCookie(string name, string pattern, MatchBehaviour matchBehaviour); - /// - /// WithCookie: matching based on name, pattern, ignoreCase and matchBehaviour. - /// - /// The name. - /// The pattern. - /// Ignore the case from the pattern. - /// The match behaviour. - /// The . - IRequestBuilder WithCookie([NotNull] string name, string pattern, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); + /// + /// WithCookie: matching based on name, pattern, ignoreCase and matchBehaviour. + /// + /// The name. + /// The pattern. + /// Ignore the case from the pattern. + /// The match behaviour. + /// The . + IRequestBuilder WithCookie(string name, string pattern, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); - /// - /// WithCookie: matching based on name, patterns and matchBehaviour. - /// - /// The name. - /// The patterns. - /// The match behaviour. - /// The . - IRequestBuilder WithCookie([NotNull] string name, string[] patterns, MatchBehaviour matchBehaviour); + /// + /// WithCookie: matching based on name, patterns and matchBehaviour. + /// + /// The name. + /// The patterns. + /// The match behaviour. + /// The . + IRequestBuilder WithCookie(string name, string[] patterns, MatchBehaviour matchBehaviour); - /// - /// WithCookie: matching based on name, patterns, ignoreCase and matchBehaviour. - /// - /// The name. - /// The patterns. - /// Ignore the case from the pattern. - /// The match behaviour. - /// The . - IRequestBuilder WithCookie([NotNull] string name, string[] patterns, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); + /// + /// WithCookie: matching based on name, patterns, ignoreCase and matchBehaviour. + /// + /// The name. + /// The patterns. + /// Ignore the case from the pattern. + /// The match behaviour. + /// The . + IRequestBuilder WithCookie(string name, string[] patterns, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); - /// - /// WithCookie: matching based on name and IStringMatcher[]. - /// - /// The name. - /// The matchers. - /// The . - IRequestBuilder WithCookie([NotNull] string name, [NotNull] params IStringMatcher[] matchers); + /// + /// WithCookie: matching based on name and IStringMatcher[]. + /// + /// The name. + /// The matchers. + /// The . + IRequestBuilder WithCookie(string name, params IStringMatcher[] matchers); - /// - /// WithCookie: matching based on name, ignoreCase and IStringMatcher[]. - /// - /// The name. - /// Ignore the case from the cookie-keys. - /// The matchers. - /// The . - IRequestBuilder WithCookie([NotNull] string name, bool ignoreCase, [NotNull] params IStringMatcher[] matchers); + /// + /// WithCookie: matching based on name, ignoreCase and IStringMatcher[]. + /// + /// The name. + /// Ignore the case from the cookie-keys. + /// The matchers. + /// The . + IRequestBuilder WithCookie(string name, bool ignoreCase, params IStringMatcher[] matchers); - /// - /// WithCookie: matching based on name, ignoreCase, matchBehaviour and IStringMatcher[]. - /// - /// The name. - /// Ignore the case from the cookie-keys. - /// The match behaviour. - /// The matchers. - /// The . - IRequestBuilder WithCookie([NotNull] string name, bool ignoreCase, MatchBehaviour matchBehaviour, [NotNull] params IStringMatcher[] matchers); + /// + /// WithCookie: matching based on name, ignoreCase, matchBehaviour and IStringMatcher[]. + /// + /// The name. + /// Ignore the case from the cookie-keys. + /// The match behaviour. + /// The matchers. + /// The . + IRequestBuilder WithCookie(string name, bool ignoreCase, MatchBehaviour matchBehaviour, params IStringMatcher[] matchers); - /// - /// WithCookie: matching based on functions. - /// - /// The cookies funcs. - /// The . - IRequestBuilder WithCookie([NotNull] params Func, bool>[] funcs); - } + /// + /// WithCookie: matching based on functions. + /// + /// The cookies funcs. + /// The . + IRequestBuilder WithCookie(params Func, bool>[] funcs); } \ No newline at end of file diff --git a/src/WireMock.Net/Serialization/MappingConverter.cs b/src/WireMock.Net/Serialization/MappingConverter.cs index 97900f61..013d3ebc 100644 --- a/src/WireMock.Net/Serialization/MappingConverter.cs +++ b/src/WireMock.Net/Serialization/MappingConverter.cs @@ -1,9 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text; using System.Threading; using Stef.Validation; using WireMock.Admin.Mappings; +using WireMock.Constants; +using WireMock.Extensions; using WireMock.Matchers; using WireMock.Matchers.Request; using WireMock.Models; @@ -16,6 +19,8 @@ namespace WireMock.Serialization; internal class MappingConverter { + private static readonly string AcceptOnMatch = MatchBehaviour.AcceptOnMatch.GetFullyQualifiedEnumValue(); + private readonly MatcherMapper _mapper; public MappingConverter(MatcherMapper mapper) @@ -23,6 +28,133 @@ internal class MappingConverter _mapper = Guard.NotNull(mapper); } + public string ToCSharpCode(IMapping mapping, MappingConverterSettings? settings = null) + { + settings ??= new MappingConverterSettings(); + + var request = (Request)mapping.RequestMatcher; + var response = (Response)mapping.Provider; + + var clientIPMatcher = request.GetRequestMessageMatcher(); + var pathMatcher = request.GetRequestMessageMatcher(); + var urlMatcher = request.GetRequestMessageMatcher(); + var headerMatchers = request.GetRequestMessageMatchers(); + var cookieMatchers = request.GetRequestMessageMatchers(); + var paramsMatchers = request.GetRequestMessageMatchers(); + var methodMatcher = request.GetRequestMessageMatcher(); + var bodyMatcher = request.GetRequestMessageMatcher(); + + var sb = new StringBuilder(); + + if (settings.ConverterType == MappingConverterType.Server) + { + if (settings.AddStart) + { + sb.AppendLine("var server = WireMockServer.Start();"); + } + sb.AppendLine("server"); + } + else + { + if (settings.AddStart) + { + sb.AppendLine("var builder = new MappingBuilder();"); + } + sb.AppendLine("builder"); + } + + // Request + sb.AppendLine(" .Given(Request.Create()"); + sb.AppendLine($" .UsingMethod({To1Or2Or3Arguments(methodMatcher?.MatchBehaviour, methodMatcher?.MatchOperator, methodMatcher?.Methods, HttpRequestMethod.GET)})"); + + if (pathMatcher is { Matchers: { } }) + { + sb.AppendLine($" .WithPath({To1Or2Arguments(pathMatcher.MatchOperator, pathMatcher.Matchers)})"); + } + else if (urlMatcher is { Matchers: { } }) + { + sb.AppendLine($" .WithUrl({To1Or2Arguments(urlMatcher.MatchOperator, urlMatcher.Matchers)})"); + } + + foreach (var paramsMatcher in paramsMatchers) + { + sb.AppendLine($" .WithParam({To1Or2Or3Arguments(paramsMatcher.Key, paramsMatcher.MatchBehaviour, paramsMatcher.Matchers!)})"); + } + + if (clientIPMatcher is { Matchers: { } }) + { + sb.AppendLine($" .WithClientIP({ToValueArguments(GetStringArray(clientIPMatcher.Matchers))})"); + } + + foreach (var headerMatcher in headerMatchers.Where(h => h.Matchers is { })) + { + var headerBuilder = new StringBuilder($"\"{headerMatcher.Name}\", {ToValueArguments(GetStringArray(headerMatcher.Matchers!))}, true"); + if (headerMatcher.MatchOperator != MatchOperator.Or) + { + headerBuilder.Append($"{AcceptOnMatch}, {headerMatcher.MatchOperator.GetFullyQualifiedEnumValue()}"); + } + sb.AppendLine($" .WithHeader({headerBuilder})"); + } + + foreach (var cookieMatcher in cookieMatchers.Where(h => h.Matchers is { })) + { + sb.AppendLine($" .WithCookie(\"{cookieMatcher.Name}\", {ToValueArguments(GetStringArray(cookieMatcher.Matchers!))}, true)"); + } + + if (bodyMatcher is { Matchers: { } }) + { + var wildcardMatcher = bodyMatcher.Matchers.OfType().FirstOrDefault(); + if (wildcardMatcher is { } && wildcardMatcher.GetPatterns().Any()) + { + sb.AppendLine($" .WithBody({GetString(wildcardMatcher)})"); + } + } + + sb.AppendLine(@" )"); + + // Guid + sb.AppendLine($" .WithGuid(\"{mapping.Guid}\")"); + + // Response + sb.AppendLine(" .RespondWith(Response.Create()"); + + if (response.ResponseMessage.Headers is { }) + { + foreach (var header in response.ResponseMessage.Headers) + { + sb.AppendLine($" .WithHeader(\"{header.Key})\", {ToValueArguments(header.Value.ToArray())})"); + } + } + + if (response.ResponseMessage.BodyData is { }) + { + switch (response.ResponseMessage.BodyData.DetectedBodyType) + { + case BodyType.String: + sb.AppendLine($" .WithBody(\"{response.ResponseMessage.BodyData.BodyAsString}\")"); + break; + } + } + + if (response.Delay is { }) + { + sb.AppendLine($" .WithDelay({response.Delay.Value.TotalMilliseconds})"); + } + else if (response.MinimumDelayMilliseconds > 0 && response.MaximumDelayMilliseconds > 0) + { + sb.AppendLine($" .WithRandomDelay({response.MinimumDelayMilliseconds}, {response.MaximumDelayMilliseconds})"); + } + + if (response.UseTransformer) + { + var transformerArgs = response.TransformerType != TransformerType.Handlebars ? response.TransformerType.GetFullyQualifiedEnumValue() : string.Empty; + sb.AppendLine($" .WithTransformer({transformerArgs})"); + } + sb.AppendLine(@" );"); + + return sb.ToString(); + } + public MappingModel ToMappingModel(IMapping mapping) { var request = (Request)mapping.RequestMatcher; @@ -237,6 +369,64 @@ internal class MappingConverter return mappingModel; } + private static string GetString(IStringMatcher stringMatcher) + { + return stringMatcher.GetPatterns().Select(p => $"\"{p.GetPattern()}\"").First(); + } + + private static string[] GetStringArray(IReadOnlyList stringMatchers) + { + return stringMatchers.SelectMany(m => m.GetPatterns()).Select(p => p.GetPattern()).ToArray(); + } + + private static string To1Or2Or3Arguments(string key, MatchBehaviour? matchBehaviour, IReadOnlyList matchers) + { + var sb = new StringBuilder($"\"{key}\", "); + + if (matchBehaviour.HasValue && matchBehaviour != MatchBehaviour.AcceptOnMatch) + { + sb.AppendFormat("{0}, ", matchBehaviour.Value.GetFullyQualifiedEnumValue()); + } + + sb.AppendFormat("{0}", ToValueArguments(GetStringArray(matchers), string.Empty)); + + return sb.ToString(); + } + + private static string To1Or2Or3Arguments(MatchBehaviour? matchBehaviour, MatchOperator? matchOperator, string[]? values, string defaultValue) + { + var sb = new StringBuilder(); + + if (matchBehaviour.HasValue && matchBehaviour != MatchBehaviour.AcceptOnMatch) + { + sb.AppendFormat("{0}, ", matchBehaviour.Value.GetFullyQualifiedEnumValue()); + } + + return To1Or2Arguments(matchOperator, values, defaultValue); + } + + private static string To1Or2Arguments(MatchOperator? matchOperator, IReadOnlyList matchers) + { + return To1Or2Arguments(matchOperator, GetStringArray(matchers), string.Empty); + } + + private static string To1Or2Arguments(MatchOperator? matchOperator, string[]? values, string defaultValue) + { + var sb = new StringBuilder(); + + if (matchOperator.HasValue && matchOperator != MatchOperator.Or) + { + sb.AppendFormat("{0}, ", matchOperator.Value.GetFullyQualifiedEnumValue()); + } + + return sb.Append(ToValueArguments(values, defaultValue)).ToString(); + } + + private static string ToValueArguments(string[]? values, string defaultValue = "") + { + return values is { } ? string.Join(", ", values.Select(v => $"\"{v}\"")) : $"\"{defaultValue}\""; + } + private static WebProxyModel? MapWebProxy(WebProxySettings? settings) { return settings != null ? new WebProxyModel diff --git a/src/WireMock.Net/Serialization/MappingConverterSettings.cs b/src/WireMock.Net/Serialization/MappingConverterSettings.cs new file mode 100644 index 00000000..9d9f3c98 --- /dev/null +++ b/src/WireMock.Net/Serialization/MappingConverterSettings.cs @@ -0,0 +1,25 @@ +using WireMock.Types; + +namespace WireMock.Serialization; + +/// +/// MappingConverterSettings +/// +public class MappingConverterSettings +{ + /// + /// Use 'Server' or 'Builder'. + /// + /// Default is Server + /// + public MappingConverterType ConverterType { get; set; } + + /// + /// Add "var server = WireMockServer.Start();" + /// or + /// Add "var builder = new MappingBuilder();" + /// + /// Default it's false. + /// + public bool AddStart { get; set; } +} \ No newline at end of file diff --git a/src/WireMock.Net/Server/RespondWithAProvider.cs b/src/WireMock.Net/Server/RespondWithAProvider.cs index 647f2891..7363a7fc 100644 --- a/src/WireMock.Net/Server/RespondWithAProvider.cs +++ b/src/WireMock.Net/Server/RespondWithAProvider.cs @@ -28,9 +28,8 @@ internal class RespondWithAProvider : IRespondWithAProvider private readonly RegistrationCallback _registrationCallback; private readonly IRequestMatcher _requestMatcher; private readonly WireMockServerSettings _settings; + private readonly IDateTimeUtils _dateTimeUtils; private readonly bool _saveToFile; - private readonly IGuidUtils _guidUtils = new GuidUtils(); - private readonly IDateTimeUtils _dateTimeUtils = new DateTimeUtils(); private bool _useWebhookFireAndForget; @@ -46,20 +45,25 @@ internal class RespondWithAProvider : IRespondWithAProvider /// The registration callback. /// The request matcher. /// The WireMockServerSettings. + /// GuidUtils to make unit testing possible. + /// DateTimeUtils to make unit testing possible. /// Optional boolean to indicate if this mapping should be saved as static mapping file. public RespondWithAProvider( RegistrationCallback registrationCallback, IRequestMatcher requestMatcher, WireMockServerSettings settings, + IGuidUtils guidUtils, + IDateTimeUtils dateTimeUtils, bool saveToFile = false ) { _registrationCallback = Guard.NotNull(registrationCallback); _requestMatcher = Guard.NotNull(requestMatcher); _settings = Guard.NotNull(settings); - _saveToFile = Guard.NotNull(saveToFile); + _dateTimeUtils = Guard.NotNull(dateTimeUtils); + _saveToFile = saveToFile; - Guid = _guidUtils.NewGuid(); + Guid = guidUtils.NewGuid(); } /// diff --git a/src/WireMock.Net/Server/WireMockServer.cs b/src/WireMock.Net/Server/WireMockServer.cs index 45db4041..e22d636d 100644 --- a/src/WireMock.Net/Server/WireMockServer.cs +++ b/src/WireMock.Net/Server/WireMockServer.cs @@ -22,6 +22,7 @@ using WireMock.ResponseProviders; using WireMock.Serialization; using WireMock.Settings; using WireMock.Types; +using WireMock.Util; namespace WireMock.Server; @@ -39,6 +40,8 @@ public partial class WireMockServer : IWireMockServer private readonly MatcherMapper _matcherMapper; private readonly MappingToFileSaver _mappingToFileSaver; private readonly MappingBuilder _mappingBuilder; + private readonly IGuidUtils _guidUtils = new GuidUtils(); + private readonly IDateTimeUtils _dateTimeUtils = new DateTimeUtils(); /// [PublicAPI] @@ -315,7 +318,14 @@ public partial class WireMockServer : IWireMockServer _matcherMapper = new MatcherMapper(_settings); _mappingConverter = new MappingConverter(_matcherMapper); _mappingToFileSaver = new MappingToFileSaver(_settings, _mappingConverter); - _mappingBuilder = new MappingBuilder(settings, _options, _mappingConverter, _mappingToFileSaver); + _mappingBuilder = new MappingBuilder( + settings, + _options, + _mappingConverter, + _mappingToFileSaver, + _guidUtils, + _dateTimeUtils + ); #if USE_ASPNETCORE _options.AdditionalServiceRegistration = _settings.AdditionalServiceRegistration; diff --git a/src/WireMock.Net/WireMock.Net.csproj b/src/WireMock.Net/WireMock.Net.csproj index f85dc999..5154eda5 100644 --- a/src/WireMock.Net/WireMock.Net.csproj +++ b/src/WireMock.Net/WireMock.Net.csproj @@ -177,13 +177,13 @@ - - - - - - - + + + + + + + diff --git a/src/WireMock.Org.Abstractions/WireMock.Org.Abstractions.csproj b/src/WireMock.Org.Abstractions/WireMock.Org.Abstractions.csproj index ce6edee0..38eb6255 100644 --- a/src/WireMock.Org.Abstractions/WireMock.Org.Abstractions.csproj +++ b/src/WireMock.Org.Abstractions/WireMock.Org.Abstractions.csproj @@ -23,6 +23,7 @@ true MIT + disable diff --git a/test/WireMock.Net.Tests/.filenesting.json b/test/WireMock.Net.Tests/.filenesting.json new file mode 100644 index 00000000..1f78cba2 --- /dev/null +++ b/test/WireMock.Net.Tests/.filenesting.json @@ -0,0 +1,18 @@ +{ + "help": "https://go.microsoft.com/fwlink/?linkid=866610", + "root": true, + + "dependentFileProviders": { + "add": { + "addedExtension": {}, + "pathSegment": {}, + "fileSuffixToExtension": { + "add": { + ".verified.txt": [ + ".cs" + ] + } + } + } + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Http/ByteArrayContentHelperTests.cs b/test/WireMock.Net.Tests/Http/ByteArrayContentHelperTests.cs index 8f15ead7..4e3e436f 100644 --- a/test/WireMock.Net.Tests/Http/ByteArrayContentHelperTests.cs +++ b/test/WireMock.Net.Tests/Http/ByteArrayContentHelperTests.cs @@ -5,40 +5,39 @@ using FluentAssertions; using WireMock.Http; using Xunit; -namespace WireMock.Net.Tests.Http +namespace WireMock.Net.Tests.Http; + +public class ByteArrayContentHelperTests { - public class ByteArrayContentHelperTests + [Fact] + public async Task ByteArrayContentHelperTests_Create_WithNullContentType() { - [Fact] - public async Task ByteArrayContentHelperTests_Create_WithNullContentType() - { - // Arrange - var content = Encoding.UTF8.GetBytes("test"); + // Arrange + var content = Encoding.UTF8.GetBytes("test"); - // Act - var result = ByteArrayContentHelper.Create(content, null); + // Act + var result = ByteArrayContentHelper.Create(content, null); - // Assert - result.Headers.ContentType.Should().BeNull(); - (await result.ReadAsByteArrayAsync().ConfigureAwait(false)).Should().BeEquivalentTo(content); - } - - [Theory] - [InlineData("application/octet-stream", "application/octet-stream")] - [InlineData("application/soap+xml", "application/soap+xml")] - [InlineData("multipart/form-data; boundary=------------------------x", "multipart/form-data; boundary=------------------------x")] - public async Task ByteArrayContentHelperTests_Create(string test, string expected) - { - // Arrange - var content = Encoding.UTF8.GetBytes("test"); - var contentType = MediaTypeHeaderValue.Parse(test); - - // Act - var result = ByteArrayContentHelper.Create(content, contentType); - - // Assert - result.Headers.ContentType.ToString().Should().Be(expected); - (await result.ReadAsByteArrayAsync().ConfigureAwait(false)).Should().BeEquivalentTo(content); - } + // Assert + result.Headers.ContentType.Should().BeNull(); + (await result.ReadAsByteArrayAsync().ConfigureAwait(false)).Should().BeEquivalentTo(content); } -} + + [Theory] + [InlineData("application/octet-stream", "application/octet-stream")] + [InlineData("application/soap+xml", "application/soap+xml")] + [InlineData("multipart/form-data; boundary=------------------------x", "multipart/form-data; boundary=------------------------x")] + public async Task ByteArrayContentHelperTests_Create(string test, string expected) + { + // Arrange + var content = Encoding.UTF8.GetBytes("test"); + var contentType = MediaTypeHeaderValue.Parse(test); + + // Act + var result = ByteArrayContentHelper.Create(content, contentType); + + // Assert + result.Headers.ContentType.ToString().Should().Be(expected); + (await result.ReadAsByteArrayAsync().ConfigureAwait(false)).Should().BeEquivalentTo(content); + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Http/HttpRequestMessageHelperTests.cs b/test/WireMock.Net.Tests/Http/HttpRequestMessageHelperTests.cs index 689c9efb..5de28dcc 100644 --- a/test/WireMock.Net.Tests/Http/HttpRequestMessageHelperTests.cs +++ b/test/WireMock.Net.Tests/Http/HttpRequestMessageHelperTests.cs @@ -1,164 +1,163 @@ using NFluent; using System.Collections.Generic; using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using WireMock.Http; using WireMock.Models; using WireMock.Types; using WireMock.Util; using Xunit; -namespace WireMock.Net.Tests.Http +namespace WireMock.Net.Tests.Http; + +public class HttpRequestMessageHelperTests { - public class HttpRequestMessageHelperTests + private const string ClientIp = "::1"; + + [Fact] + public void HttpRequestMessageHelper_Create() { - private const string ClientIp = "::1"; + // Assign + var headers = new Dictionary { { "x", new[] { "value-1" } } }; + var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, null, headers); - [Fact] - public void HttpRequestMessageHelper_Create() + // Act + var message = HttpRequestMessageHelper.Create(request, "http://url"); + + // Assert + Check.That(message.Headers.GetValues("x")).ContainsExactly("value-1"); + } + + [Fact] + public async Task HttpRequestMessageHelper_Create_Bytes() + { + // Assign + var body = new BodyData { - // Assign - var headers = new Dictionary { { "x", new[] { "value-1" } } }; - var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, null, headers); + BodyAsBytes = Encoding.UTF8.GetBytes("hi"), + DetectedBodyType = BodyType.Bytes + }; + var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body); - // Act - var message = HttpRequestMessageHelper.Create(request, "http://url"); + // Act + var message = HttpRequestMessageHelper.Create(request, "http://url"); - // Assert - Check.That(message.Headers.GetValues("x")).ContainsExactly("value-1"); - } + // Assert + Check.That(await message.Content.ReadAsByteArrayAsync().ConfigureAwait(false)).ContainsExactly(Encoding.UTF8.GetBytes("hi")); + } - [Fact] - public async Task HttpRequestMessageHelper_Create_Bytes() + [Fact] + public async Task HttpRequestMessageHelper_Create_Json() + { + // Assign + var body = new BodyData { - // Assign - var body = new BodyData - { - BodyAsBytes = Encoding.UTF8.GetBytes("hi"), - DetectedBodyType = BodyType.Bytes - }; - var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body); + BodyAsJson = new { x = 42 }, + DetectedBodyType = BodyType.Json + }; + var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body); - // Act - var message = HttpRequestMessageHelper.Create(request, "http://url"); + // Act + var message = HttpRequestMessageHelper.Create(request, "http://url"); - // Assert - Check.That(await message.Content.ReadAsByteArrayAsync().ConfigureAwait(false)).ContainsExactly(Encoding.UTF8.GetBytes("hi")); - } + // Assert + Check.That(await message.Content.ReadAsStringAsync().ConfigureAwait(false)).Equals("{\"x\":42}"); + } - [Fact] - public async Task HttpRequestMessageHelper_Create_Json() + [Fact] + public async Task HttpRequestMessageHelper_Create_Json_With_ContentType_ApplicationJson() + { + // Assign + var headers = new Dictionary { { "Content-Type", new[] { "application/json" } } }; + var body = new BodyData { - // Assign - var body = new BodyData - { - BodyAsJson = new { x = 42 }, - DetectedBodyType = BodyType.Json - }; - var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body); + BodyAsJson = new { x = 42 }, + DetectedBodyType = BodyType.Json + }; + var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body, headers); - // Act - var message = HttpRequestMessageHelper.Create(request, "http://url"); + // Act + var message = HttpRequestMessageHelper.Create(request, "http://url"); - // Assert - Check.That(await message.Content.ReadAsStringAsync().ConfigureAwait(false)).Equals("{\"x\":42}"); - } + // Assert + Check.That(await message.Content.ReadAsStringAsync().ConfigureAwait(false)).Equals("{\"x\":42}"); + Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/json"); + } - [Fact] - public async Task HttpRequestMessageHelper_Create_Json_With_ContentType_ApplicationJson() + [Fact] + public async Task HttpRequestMessageHelper_Create_Json_With_ContentType_ApplicationJson_UTF8() + { + // Assign + var headers = new Dictionary { { "Content-Type", new[] { "application/json; charset=utf-8" } } }; + var body = new BodyData { - // Assign - var headers = new Dictionary { { "Content-Type", new[] { "application/json" } } }; - var body = new BodyData - { - BodyAsJson = new { x = 42 }, - DetectedBodyType = BodyType.Json - }; - var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body, headers); + BodyAsJson = new { x = 42 }, + DetectedBodyType = BodyType.Json + }; + var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body, headers); - // Act - var message = HttpRequestMessageHelper.Create(request, "http://url"); + // Act + var message = HttpRequestMessageHelper.Create(request, "http://url"); - // Assert - Check.That(await message.Content.ReadAsStringAsync().ConfigureAwait(false)).Equals("{\"x\":42}"); - Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/json"); - } + // Assert + Check.That(await message.Content.ReadAsStringAsync().ConfigureAwait(false)).Equals("{\"x\":42}"); + Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/json; charset=utf-8"); + } - [Fact] - public async Task HttpRequestMessageHelper_Create_Json_With_ContentType_ApplicationJson_UTF8() + [Fact] + public void HttpRequestMessageHelper_Create_String_With_ContentType_ApplicationXml() + { + // Assign + var headers = new Dictionary { { "Content-Type", new[] { "application/xml" } } }; + var body = new BodyData { - // Assign - var headers = new Dictionary { { "Content-Type", new[] { "application/json; charset=utf-8" } } }; - var body = new BodyData - { - BodyAsJson = new { x = 42 }, - DetectedBodyType = BodyType.Json - }; - var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body, headers); + BodyAsString = "hello", + DetectedBodyType = BodyType.String + }; + var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers); - // Act - var message = HttpRequestMessageHelper.Create(request, "http://url"); + // Act + var message = HttpRequestMessageHelper.Create(request, "http://url"); - // Assert - Check.That(await message.Content.ReadAsStringAsync().ConfigureAwait(false)).Equals("{\"x\":42}"); - Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/json; charset=utf-8"); - } + // Assert + Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/xml"); + } - [Fact] - public void HttpRequestMessageHelper_Create_String_With_ContentType_ApplicationXml() + [Fact] + public void HttpRequestMessageHelper_Create_String_With_ContentType_ApplicationXml_UTF8() + { + // Assign + var headers = new Dictionary { { "Content-Type", new[] { "application/xml; charset=UTF-8" } } }; + var body = new BodyData { - // Assign - var headers = new Dictionary { { "Content-Type", new[] { "application/xml" } } }; - var body = new BodyData - { - BodyAsString = "hello", - DetectedBodyType = BodyType.String - }; - var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers); + BodyAsString = "hello", + DetectedBodyType = BodyType.String + }; + var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers); - // Act - var message = HttpRequestMessageHelper.Create(request, "http://url"); + // Act + var message = HttpRequestMessageHelper.Create(request, "http://url"); - // Assert - Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/xml"); - } + // Assert + Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/xml; charset=UTF-8"); + } - [Fact] - public void HttpRequestMessageHelper_Create_String_With_ContentType_ApplicationXml_UTF8() + [Fact] + public void HttpRequestMessageHelper_Create_String_With_ContentType_ApplicationXml_ASCII() + { + // Assign + var headers = new Dictionary { { "Content-Type", new[] { "application/xml; charset=Ascii" } } }; + var body = new BodyData { - // Assign - var headers = new Dictionary { { "Content-Type", new[] { "application/xml; charset=UTF-8" } } }; - var body = new BodyData - { - BodyAsString = "hello", - DetectedBodyType = BodyType.String - }; - var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers); + BodyAsString = "hello", + DetectedBodyType = BodyType.String + }; + var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers); - // Act - var message = HttpRequestMessageHelper.Create(request, "http://url"); + // Act + var message = HttpRequestMessageHelper.Create(request, "http://url"); - // Assert - Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/xml; charset=UTF-8"); - } - - [Fact] - public void HttpRequestMessageHelper_Create_String_With_ContentType_ApplicationXml_ASCII() - { - // Assign - var headers = new Dictionary { { "Content-Type", new[] { "application/xml; charset=Ascii" } } }; - var body = new BodyData - { - BodyAsString = "hello", - DetectedBodyType = BodyType.String - }; - var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers); - - // Act - var message = HttpRequestMessageHelper.Create(request, "http://url"); - - // Assert - Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/xml; charset=Ascii"); - } + // Assert + Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/xml; charset=Ascii"); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Http/StringContentHelperTests.cs b/test/WireMock.Net.Tests/Http/StringContentHelperTests.cs index 5d3e08f5..c5f0fff8 100644 --- a/test/WireMock.Net.Tests/Http/StringContentHelperTests.cs +++ b/test/WireMock.Net.Tests/Http/StringContentHelperTests.cs @@ -1,39 +1,38 @@ -using System.Net.Http.Headers; +using System.Net.Http.Headers; using FluentAssertions; using WireMock.Http; using Xunit; -namespace WireMock.Net.Tests.Http +namespace WireMock.Net.Tests.Http; + +public class StringContentHelperTests { - public class StringContentHelperTests + [Fact] + public void StringContentHelper_Create_WithNullContentType() { - [Fact] - public void StringContentHelper_Create_WithNullContentType() - { - // Act - var result = StringContentHelper.Create("test", null); + // Act + var result = StringContentHelper.Create("test", null); - // Assert - result.Headers.ContentType.Should().BeNull(); - result.ReadAsStringAsync().Result.Should().Be("test"); - } - - [Theory] - [InlineData("application/json", "application/json")] - [InlineData("application/soap+xml", "application/soap+xml")] - [InlineData("application/soap+xml;charset=UTF-8", "application/soap+xml; charset=UTF-8")] - [InlineData("application/soap+xml;charset=UTF-8;action=\"http://myCompany.Customer.Contract/ICustomerService/GetSomeConfiguration\"", "application/soap+xml; charset=UTF-8; action=\"http://myCompany.Customer.Contract/ICustomerService/GetSomeConfiguration\"")] - public void StringContentHelper_Create(string test, string expected) - { - // Arrange - var contentType = MediaTypeHeaderValue.Parse(test); - - // Act - var result = StringContentHelper.Create("test", contentType); - - // Assert - result.Headers.ContentType.ToString().Should().Be(expected); - result.ReadAsStringAsync().Result.Should().Be("test"); - } + // Assert + result.Headers.ContentType.Should().BeNull(); + result.ReadAsStringAsync().Result.Should().Be("test"); } -} + + [Theory] + [InlineData("application/json", "application/json")] + [InlineData("application/soap+xml", "application/soap+xml")] + [InlineData("application/soap+xml;charset=UTF-8", "application/soap+xml; charset=UTF-8")] + [InlineData("application/soap+xml;charset=UTF-8;action=\"http://myCompany.Customer.Contract/ICustomerService/GetSomeConfiguration\"", "application/soap+xml; charset=UTF-8; action=\"http://myCompany.Customer.Contract/ICustomerService/GetSomeConfiguration\"")] + public void StringContentHelper_Create(string test, string expected) + { + // Arrange + var contentType = MediaTypeHeaderValue.Parse(test); + + // Act + var result = StringContentHelper.Create("test", contentType); + + // Assert + result.Headers.ContentType.ToString().Should().Be(expected); + result.ReadAsStringAsync().Result.Should().Be("test"); + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/MappingBuilderTests.GetMappings.verified.txt b/test/WireMock.Net.Tests/MappingBuilderTests.GetMappings.verified.txt new file mode 100644 index 00000000..907f69af --- /dev/null +++ b/test/WireMock.Net.Tests/MappingBuilderTests.GetMappings.verified.txt @@ -0,0 +1,25 @@ +[ + { + Guid: 41372914-1838-4c67-916b-b9aacdd096ce, + UpdatedAt: 2023-01-14 15:16:17, + Request: { + Path: { + Matchers: [ + { + Name: WildcardMatcher, + Pattern: /foo, + IgnoreCase: false + } + ] + }, + Methods: [ + GET + ] + }, + Response: { + BodyDestination: SameAsSource, + Body: { msg: "Hello world!"} + }, + UseWebhooksFireAndForget: false + } +] \ No newline at end of file diff --git a/test/WireMock.Net.Tests/MappingBuilderTests.ToJson.verified.txt b/test/WireMock.Net.Tests/MappingBuilderTests.ToJson.verified.txt new file mode 100644 index 00000000..7aaed7c0 --- /dev/null +++ b/test/WireMock.Net.Tests/MappingBuilderTests.ToJson.verified.txt @@ -0,0 +1,25 @@ +[ + { + Guid: 41372914-1838-4c67-916b-b9aacdd096ce, + UpdatedAt: 2023-01-14T15:16:17, + Request: { + Path: { + Matchers: [ + { + Name: WildcardMatcher, + Pattern: /foo, + IgnoreCase: false + } + ] + }, + Methods: [ + GET + ] + }, + Response: { + BodyDestination: SameAsSource, + Body: { msg: "Hello world!"} + }, + UseWebhooksFireAndForget: false + } +] \ No newline at end of file diff --git a/test/WireMock.Net.Tests/MappingBuilderTests.cs b/test/WireMock.Net.Tests/MappingBuilderTests.cs index fe9b8697..67aa4c20 100644 --- a/test/WireMock.Net.Tests/MappingBuilderTests.cs +++ b/test/WireMock.Net.Tests/MappingBuilderTests.cs @@ -1,5 +1,10 @@ -using FluentAssertions; +#if !(NET452 || NET461 || NETCOREAPP3_1) +using System; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; using Moq; +using VerifyTests; +using VerifyXunit; using WireMock.Handlers; using WireMock.Logging; using WireMock.Owin; @@ -7,13 +12,17 @@ using WireMock.RequestBuilders; using WireMock.ResponseBuilders; using WireMock.Serialization; using WireMock.Settings; +using WireMock.Util; using Xunit; namespace WireMock.Net.Tests; +[UsesVerify] public class MappingBuilderTests { - private static readonly string MappingGuid = "41372914-1838-4c67-916b-b9aacdd096ce"; + private static readonly Guid NewGuid = new("98fae52e-76df-47d9-876f-2ee32e931d9b"); + private const string MappingGuid = "41372914-1838-4c67-916b-b9aacdd096ce"; + private static readonly DateTime UtcNow = new(2023, 1, 14, 15, 16, 17); private readonly Mock _fileSystemHandlerMock; @@ -23,6 +32,12 @@ public class MappingBuilderTests { _fileSystemHandlerMock = new Mock(); + var guidUtilsMock = new Mock(); + guidUtilsMock.Setup(g => g.NewGuid()).Returns(NewGuid); + + var dateTimeUtilsMock = new Mock(); + dateTimeUtilsMock.SetupGet(d => d.UtcNow).Returns(UtcNow); + var settings = new WireMockServerSettings { FileSystemHandler = _fileSystemHandlerMock.Object, @@ -33,7 +48,14 @@ public class MappingBuilderTests var mappingConverter = new MappingConverter(matcherMapper); var mappingToFileSaver = new MappingToFileSaver(settings, mappingConverter); - _sut = new MappingBuilder(settings, options, mappingConverter, mappingToFileSaver); + _sut = new MappingBuilder( + settings, + options, + mappingConverter, + mappingToFileSaver, + guidUtilsMock.Object, + dateTimeUtilsMock.Object + ); _sut.Given(Request.Create() .WithPath("/foo") @@ -45,24 +67,31 @@ public class MappingBuilderTests ); } + [ModuleInitializer] + public static void ModuleInitializer() + { + VerifierSettings.DontScrubGuids(); + VerifierSettings.DontScrubDateTimes(); + } + [Fact] - public void GetMappings() + public Task GetMappings() { // Act var mappings = _sut.GetMappings(); - // Assert - mappings.Should().HaveCount(1); + // Verify + return Verifier.Verify(mappings); } [Fact] - public void ToJson() + public Task ToJson() { // Act var json = _sut.ToJson(); - // Assert - json.Should().NotBeEmpty(); + // Verify + return Verifier.VerifyJson(json); } [Fact] @@ -133,4 +162,5 @@ public class MappingBuilderTests _fileSystemHandlerMock.Verify(fs => fs.WriteMappingFile(It.IsAny(), It.IsAny()), Times.Once); _fileSystemHandlerMock.VerifyNoOtherCalls(); } -} \ No newline at end of file +} +#endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/CSharpCodeMatcherTests.cs b/test/WireMock.Net.Tests/Matchers/CSharpCodeMatcherTests.cs index 03baab83..26fcc3ac 100644 --- a/test/WireMock.Net.Tests/Matchers/CSharpCodeMatcherTests.cs +++ b/test/WireMock.Net.Tests/Matchers/CSharpCodeMatcherTests.cs @@ -2,91 +2,90 @@ using NFluent; using WireMock.Matchers; using Xunit; -namespace WireMock.Net.Tests.Matchers +namespace WireMock.Net.Tests.Matchers; + +public class CSharpCodeMatcherTests { - public class CSharpCodeMatcherTests + [Fact] + public void CSharpCodeMatcher_For_String_SinglePattern_IsMatch_Positive() { - [Fact] - public void CSharpCodeMatcher_For_String_SinglePattern_IsMatch_Positive() + // Assign + string input = "x"; + + // Act + var matcher = new CSharpCodeMatcher("return it == \"x\";"); + + // Assert + Check.That(matcher.IsMatch(input)).IsEqualTo(1.0d); + } + + [Fact] + public void CSharpCodeMatcher_For_String_IsMatch_Negative() + { + // Assign + string input = "y"; + + // Act + var matcher = new CSharpCodeMatcher("return it == \"x\";"); + + // Assert + Check.That(matcher.IsMatch(input)).IsEqualTo(0.0d); + } + + [Fact] + public void CSharpCodeMatcher_For_String_IsMatch_RejectOnMatch() + { + // Assign + string input = "x"; + + // Act + var matcher = new CSharpCodeMatcher(MatchBehaviour.RejectOnMatch, MatchOperator.Or, "return it == \"x\";"); + + // Assert + Check.That(matcher.IsMatch(input)).IsEqualTo(0.0d); + } + + [Fact] + public void CSharpCodeMatcher_For_Object_IsMatch() + { + // Assign + var input = new { - // Assign - string input = "x"; + Id = 9, + Name = "Test" + }; - // Act - var matcher = new CSharpCodeMatcher("return it == \"x\";"); + // Act + var matcher = new CSharpCodeMatcher("return it.Id > 1 && it.Name == \"Test\";"); + double match = matcher.IsMatch(input); - // Assert - Check.That(matcher.IsMatch(input)).IsEqualTo(1.0d); - } + // Assert + Assert.Equal(1.0, match); + } - [Fact] - public void CSharpCodeMatcher_For_String_IsMatch_Negative() - { - // Assign - string input = "y"; + [Fact] + public void CSharpCodeMatcher_GetName() + { + // Assign + var matcher = new CSharpCodeMatcher("x"); - // Act - var matcher = new CSharpCodeMatcher("return it == \"x\";"); + // Act + string name = matcher.Name; - // Assert - Check.That(matcher.IsMatch(input)).IsEqualTo(0.0d); - } + // Assert + Check.That(name).Equals("CSharpCodeMatcher"); + } - [Fact] - public void CSharpCodeMatcher_For_String_IsMatch_RejectOnMatch() - { - // Assign - string input = "x"; + [Fact] + public void CSharpCodeMatcher_GetPatterns() + { + // Assign + var matcher = new CSharpCodeMatcher("x"); - // Act - var matcher = new CSharpCodeMatcher(MatchBehaviour.RejectOnMatch, MatchOperator.Or, "return it == \"x\";"); + // Act + var patterns = matcher.GetPatterns(); - // Assert - Check.That(matcher.IsMatch(input)).IsEqualTo(0.0d); - } - - [Fact] - public void CSharpCodeMatcher_For_Object_IsMatch() - { - // Assign - var input = new - { - Id = 9, - Name = "Test" - }; - - // Act - var matcher = new CSharpCodeMatcher("return it.Id > 1 && it.Name == \"Test\";"); - double match = matcher.IsMatch(input); - - // Assert - Assert.Equal(1.0, match); - } - - [Fact] - public void CSharpCodeMatcher_GetName() - { - // Assign - var matcher = new CSharpCodeMatcher("x"); - - // Act - string name = matcher.Name; - - // Assert - Check.That(name).Equals("CSharpCodeMatcher"); - } - - [Fact] - public void CSharpCodeMatcher_GetPatterns() - { - // Assign - var matcher = new CSharpCodeMatcher("x"); - - // Act - var patterns = matcher.GetPatterns(); - - // Assert - Check.That(patterns).ContainsExactly("x"); - } + // Assert + Check.That(patterns).ContainsExactly("x"); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/ContentTypeMatcherTests.cs b/test/WireMock.Net.Tests/Matchers/ContentTypeMatcherTests.cs index 24a75f05..3bec9227 100644 --- a/test/WireMock.Net.Tests/Matchers/ContentTypeMatcherTests.cs +++ b/test/WireMock.Net.Tests/Matchers/ContentTypeMatcherTests.cs @@ -1,59 +1,57 @@ -using AnyOfTypes; using NFluent; using WireMock.Matchers; using Xunit; -namespace WireMock.Net.Tests.Matchers +namespace WireMock.Net.Tests.Matchers; + +public class ContentTypeMatcherTests { - public class ContentTypeMatcherTests + [Theory] + [InlineData("application/json")] + [InlineData("application/json; charset=ascii")] + [InlineData("application/json; charset=utf-8")] + [InlineData("application/json; charset=UTF-8")] + public void ContentTypeMatcher_IsMatchWithIgnoreCaseFalse_Positive(string contentType) { - [Theory] - [InlineData("application/json")] - [InlineData("application/json; charset=ascii")] - [InlineData("application/json; charset=utf-8")] - [InlineData("application/json; charset=UTF-8")] - public void ContentTypeMatcher_IsMatchWithIgnoreCaseFalse_Positive(string contentType) - { - var matcher = new ContentTypeMatcher("application/json"); - Check.That(matcher.IsMatch(contentType)).IsEqualTo(1.0d); - } + var matcher = new ContentTypeMatcher("application/json"); + Check.That(matcher.IsMatch(contentType)).IsEqualTo(1.0d); + } - [Theory] - [InlineData("application/json")] - [InlineData("application/JSON")] - [InlineData("application/json; CharSet=ascii")] - [InlineData("application/json; charset=utf-8")] - [InlineData("application/json; charset=UTF-8")] - public void ContentTypeMatcher_IsMatchWithIgnoreCaseTrue_Positive(string contentType) - { - var matcher = new ContentTypeMatcher("application/json", true); - Check.That(matcher.IsMatch(contentType)).IsEqualTo(1.0d); - } + [Theory] + [InlineData("application/json")] + [InlineData("application/JSON")] + [InlineData("application/json; CharSet=ascii")] + [InlineData("application/json; charset=utf-8")] + [InlineData("application/json; charset=UTF-8")] + public void ContentTypeMatcher_IsMatchWithIgnoreCaseTrue_Positive(string contentType) + { + var matcher = new ContentTypeMatcher("application/json", true); + Check.That(matcher.IsMatch(contentType)).IsEqualTo(1.0d); + } - [Fact] - public void ContentTypeMatcher_GetName() - { - // Assign - var matcher = new ContentTypeMatcher("x"); + [Fact] + public void ContentTypeMatcher_GetName() + { + // Assign + var matcher = new ContentTypeMatcher("x"); - // Act - string name = matcher.Name; + // Act + string name = matcher.Name; - // Assert - Check.That(name).Equals("ContentTypeMatcher"); - } + // Assert + Check.That(name).Equals("ContentTypeMatcher"); + } - [Fact] - public void ContentTypeMatcher_GetPatterns() - { - // Assign - var matcher = new ContentTypeMatcher("x"); + [Fact] + public void ContentTypeMatcher_GetPatterns() + { + // Assign + var matcher = new ContentTypeMatcher("x"); - // Act - var patterns = matcher.GetPatterns(); + // Act + var patterns = matcher.GetPatterns(); - // Assert - Check.That(patterns).ContainsExactly("x"); - } + // Assert + Check.That(patterns).ContainsExactly("x"); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/ExactObjectMatcherTests.cs b/test/WireMock.Net.Tests/Matchers/ExactObjectMatcherTests.cs index fc1fec21..222e3e77 100644 --- a/test/WireMock.Net.Tests/Matchers/ExactObjectMatcherTests.cs +++ b/test/WireMock.Net.Tests/Matchers/ExactObjectMatcherTests.cs @@ -1,65 +1,64 @@ -using NFluent; +using NFluent; using WireMock.Matchers; using Xunit; -namespace WireMock.Net.Tests.Matchers +namespace WireMock.Net.Tests.Matchers; + +public class ExactObjectMatcherTests { - public class ExactObjectMatcherTests + [Fact] + public void ExactObjectMatcher_GetName() { - [Fact] - public void ExactObjectMatcher_GetName() - { - // Assign - object obj = 1; + // Assign + object obj = 1; - // Act - var matcher = new ExactObjectMatcher(obj); - string name = matcher.Name; + // Act + var matcher = new ExactObjectMatcher(obj); + string name = matcher.Name; - // Assert - Check.That(name).Equals("ExactObjectMatcher"); - } + // Assert + Check.That(name).Equals("ExactObjectMatcher"); + } - [Fact] - public void ExactObjectMatcher_IsMatch_ByteArray() - { - // Assign - object checkValue = new byte[] { 1, 2 }; + [Fact] + public void ExactObjectMatcher_IsMatch_ByteArray() + { + // Assign + object checkValue = new byte[] { 1, 2 }; - // Act - var matcher = new ExactObjectMatcher(new byte[] { 1, 2 }); - double result = matcher.IsMatch(checkValue); + // Act + var matcher = new ExactObjectMatcher(new byte[] { 1, 2 }); + double result = matcher.IsMatch(checkValue); - // Assert - Check.That(result).IsEqualTo(1.0); - } + // Assert + Check.That(result).IsEqualTo(1.0); + } - [Fact] - public void ExactObjectMatcher_IsMatch_AcceptOnMatch() - { - // Assign - object obj = new { x = 500, s = "s" }; + [Fact] + public void ExactObjectMatcher_IsMatch_AcceptOnMatch() + { + // Assign + object obj = new { x = 500, s = "s" }; - // Act - var matcher = new ExactObjectMatcher(obj); - double result = matcher.IsMatch(new { x = 500, s = "s" }); + // Act + var matcher = new ExactObjectMatcher(obj); + double result = matcher.IsMatch(new { x = 500, s = "s" }); - // Assert - Check.That(result).IsEqualTo(1.0); - } + // Assert + Check.That(result).IsEqualTo(1.0); + } - [Fact] - public void ExactObjectMatcher_IsMatch_RejectOnMatch() - { - // Assign - object obj = new { x = 500, s = "s" }; + [Fact] + public void ExactObjectMatcher_IsMatch_RejectOnMatch() + { + // Assign + object obj = new { x = 500, s = "s" }; - // Act - var matcher = new ExactObjectMatcher(MatchBehaviour.RejectOnMatch, obj); - double result = matcher.IsMatch(new { x = 500, s = "s" }); + // Act + var matcher = new ExactObjectMatcher(MatchBehaviour.RejectOnMatch, obj); + double result = matcher.IsMatch(new { x = 500, s = "s" }); - // Assert - Check.That(result).IsEqualTo(0.0); - } + // Assert + Check.That(result).IsEqualTo(0.0); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/JmesPathMatcherTests.cs b/test/WireMock.Net.Tests/Matchers/JmesPathMatcherTests.cs index afdff3f7..09308c1f 100644 --- a/test/WireMock.Net.Tests/Matchers/JmesPathMatcherTests.cs +++ b/test/WireMock.Net.Tests/Matchers/JmesPathMatcherTests.cs @@ -3,164 +3,163 @@ using NFluent; using WireMock.Matchers; using Xunit; -namespace WireMock.Net.Tests.Matchers +namespace WireMock.Net.Tests.Matchers; + +public class JmesPathMatcherTests { - public class JmesPathMatcherTests + [Fact] + public void JmesPathMatcher_GetName() { - [Fact] - public void JmesPathMatcher_GetName() + // Assign + var matcher = new JmesPathMatcher("X"); + + // Act + string name = matcher.Name; + + // Assert + Check.That(name).Equals("JmesPathMatcher"); + } + + [Fact] + public void JmesPathMatcher_GetPatterns() + { + // Assign + var matcher = new JmesPathMatcher("X"); + + // Act + var patterns = matcher.GetPatterns(); + + // Assert + Check.That(patterns).ContainsExactly("X"); + } + + [Fact] + public void JmesPathMatcher_IsMatch_ByteArray() + { + // Assign + var bytes = new byte[0]; + var matcher = new JmesPathMatcher(""); + + // Act + double match = matcher.IsMatch(bytes); + + // Assert + Check.That(match).IsEqualTo(0); + } + + [Fact] + public void JmesPathMatcher_IsMatch_NullString() + { + // Assign + string? s = null; + var matcher = new JmesPathMatcher(""); + + // Act + double match = matcher.IsMatch(s); + + // Assert + Check.That(match).IsEqualTo(0); + } + + [Fact] + public void JmesPathMatcher_IsMatch_NullObject() + { + // Assign + object? o = null; + var matcher = new JmesPathMatcher(""); + + // Act + double match = matcher.IsMatch(o); + + // Assert + Check.That(match).IsEqualTo(0); + } + + [Fact] + public void JmesPathMatcher_IsMatch_String_Exception_Mismatch() + { + // Assign + var matcher = new JmesPathMatcher("xxx"); + + // Act + double match = matcher.IsMatch(""); + + // Assert + Check.That(match).IsEqualTo(0); + } + + [Fact] + public void JmesPathMatcher_IsMatch_Object_Exception_Mismatch() + { + // Assign + var matcher = new JmesPathMatcher(""); + + // Act + double match = matcher.IsMatch("x"); + + // Assert + Check.That(match).IsEqualTo(0); + } + + [Fact] + public void JmesPathMatcher_IsMatch_AnonymousObject() + { + // Assign + var matcher = new JmesPathMatcher("things.name == 'RequiredThing'"); + + // Act + double match = matcher.IsMatch(new { things = new { name = "RequiredThing" } }); + + // Assert + Check.That(match).IsEqualTo(1); + } + + [Fact] + public void JmesPathMatcher_IsMatch_JObject() + { + // Assign + string[] patterns = { "things.x == 'RequiredThing'" }; + var matcher = new JmesPathMatcher(patterns); + + // Act + var sub = new JObject { - // Assign - var matcher = new JmesPathMatcher("X"); - - // Act - string name = matcher.Name; - - // Assert - Check.That(name).Equals("JmesPathMatcher"); - } - - [Fact] - public void JmesPathMatcher_GetPatterns() + { "x", new JValue("RequiredThing") } + }; + var jobject = new JObject { - // Assign - var matcher = new JmesPathMatcher("X"); + { "Id", new JValue(1) }, + { "things", sub } + }; + double match = matcher.IsMatch(jobject); - // Act - var patterns = matcher.GetPatterns(); + // Assert + Check.That(match).IsEqualTo(1); + } - // Assert - Check.That(patterns).ContainsExactly("X"); - } + [Fact] + public void JmesPathMatcher_IsMatch_JObject_Parsed() + { + // Assign + var matcher = new JmesPathMatcher("things.x == 'RequiredThing'"); - [Fact] - public void JmesPathMatcher_IsMatch_ByteArray() - { - // Assign - var bytes = new byte[0]; - var matcher = new JmesPathMatcher(""); + // Act + double match = matcher.IsMatch(JObject.Parse("{ \"things\": { \"x\": \"RequiredThing\" } }")); - // Act - double match = matcher.IsMatch(bytes); + // Assert + Check.That(match).IsEqualTo(1); + } - // Assert - Check.That(match).IsEqualTo(0); - } + [Fact] + public void JmesPathMatcher_IsMatch_RejectOnMatch() + { + // Assign + var matcher = new JmesPathMatcher(MatchBehaviour.RejectOnMatch, false, MatchOperator.Or, "things.x == 'RequiredThing'"); - [Fact] - public void JmesPathMatcher_IsMatch_NullString() - { - // Assign - string? s = null; - var matcher = new JmesPathMatcher(""); + // Act + double match = matcher.IsMatch(JObject.Parse("{ \"things\": { \"x\": \"RequiredThing\" } }")); - // Act - double match = matcher.IsMatch(s); - - // Assert - Check.That(match).IsEqualTo(0); - } - - [Fact] - public void JmesPathMatcher_IsMatch_NullObject() - { - // Assign - object? o = null; - var matcher = new JmesPathMatcher(""); - - // Act - double match = matcher.IsMatch(o); - - // Assert - Check.That(match).IsEqualTo(0); - } - - [Fact] - public void JmesPathMatcher_IsMatch_String_Exception_Mismatch() - { - // Assign - var matcher = new JmesPathMatcher("xxx"); - - // Act - double match = matcher.IsMatch(""); - - // Assert - Check.That(match).IsEqualTo(0); - } - - [Fact] - public void JmesPathMatcher_IsMatch_Object_Exception_Mismatch() - { - // Assign - var matcher = new JmesPathMatcher(""); - - // Act - double match = matcher.IsMatch("x"); - - // Assert - Check.That(match).IsEqualTo(0); - } - - [Fact] - public void JmesPathMatcher_IsMatch_AnonymousObject() - { - // Assign - var matcher = new JmesPathMatcher("things.name == 'RequiredThing'"); - - // Act - double match = matcher.IsMatch(new { things = new { name = "RequiredThing" } }); - - // Assert - Check.That(match).IsEqualTo(1); - } - - [Fact] - public void JmesPathMatcher_IsMatch_JObject() - { - // Assign - string[] patterns = { "things.x == 'RequiredThing'" }; - var matcher = new JmesPathMatcher(patterns); - - // Act - var sub = new JObject - { - { "x", new JValue("RequiredThing") } - }; - var jobject = new JObject - { - { "Id", new JValue(1) }, - { "things", sub } - }; - double match = matcher.IsMatch(jobject); - - // Assert - Check.That(match).IsEqualTo(1); - } - - [Fact] - public void JmesPathMatcher_IsMatch_JObject_Parsed() - { - // Assign - var matcher = new JmesPathMatcher("things.x == 'RequiredThing'"); - - // Act - double match = matcher.IsMatch(JObject.Parse("{ \"things\": { \"x\": \"RequiredThing\" } }")); - - // Assert - Check.That(match).IsEqualTo(1); - } - - [Fact] - public void JmesPathMatcher_IsMatch_RejectOnMatch() - { - // Assign - var matcher = new JmesPathMatcher(MatchBehaviour.RejectOnMatch, false, MatchOperator.Or, "things.x == 'RequiredThing'"); - - // Act - double match = matcher.IsMatch(JObject.Parse("{ \"things\": { \"x\": \"RequiredThing\" } }")); - - // Assert - Check.That(match).IsEqualTo(0.0); - } + // Assert + Check.That(match).IsEqualTo(0.0); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/JsonPartialMatcherTests.cs b/test/WireMock.Net.Tests/Matchers/JsonPartialMatcherTests.cs index 02f20137..bf76ce5b 100644 --- a/test/WireMock.Net.Tests/Matchers/JsonPartialMatcherTests.cs +++ b/test/WireMock.Net.Tests/Matchers/JsonPartialMatcherTests.cs @@ -7,416 +7,415 @@ using NFluent; using WireMock.Matchers; using Xunit; -namespace WireMock.Net.Tests.Matchers +namespace WireMock.Net.Tests.Matchers; + +public class JsonPartialMatcherTests { - public class JsonPartialMatcherTests + [Fact] + public void JsonPartialMatcher_GetName() { - [Fact] - public void JsonPartialMatcher_GetName() - { - // Assign - var matcher = new JsonPartialMatcher("{}"); + // Assign + var matcher = new JsonPartialMatcher("{}"); - // Act - string name = matcher.Name; + // Act + string name = matcher.Name; - // Assert - Check.That(name).Equals("JsonPartialMatcher"); - } - - [Fact] - public void JsonPartialMatcher_GetValue() - { - // Assign - var matcher = new JsonPartialMatcher("{}"); - - // Act - object value = matcher.Value; - - // Assert - Check.That(value).Equals("{}"); - } - - [Fact] - public void JsonPartialMatcher_WithInvalidStringValue_Should_ThrowException() - { - // Act - // ReSharper disable once ObjectCreationAsStatement - Action action = () => new JsonPartialMatcher(MatchBehaviour.AcceptOnMatch, "{ \"Id\""); - - // Assert - action.Should().Throw(); - } - - [Fact] - public void JsonPartialMatcher_WithInvalidObjectValue_Should_ThrowException() - { - // Act - // ReSharper disable once ObjectCreationAsStatement - Action action = () => new JsonPartialMatcher(MatchBehaviour.AcceptOnMatch, new MemoryStream()); - - // Assert - action.Should().Throw(); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_WithInvalidValue_And_ThrowExceptionIsFalse_Should_ReturnMismatch() - { - // Assign - var matcher = new JsonPartialMatcher(""); - - // Act - double match = matcher.IsMatch(new MemoryStream()); - - // Assert - Check.That(match).IsEqualTo(0); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_WithInvalidValue_And_ThrowExceptionIsTrue_Should_ReturnMismatch() - { - // Assign - var matcher = new JsonPartialMatcher("", false, true); - - // Act - Action action = () => matcher.IsMatch(new MemoryStream()); - - // Assert - action.Should().Throw(); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_ByteArray() - { - // Assign - var bytes = new byte[0]; - var matcher = new JsonPartialMatcher(""); - - // Act - double match = matcher.IsMatch(bytes); - - // Assert - Check.That(match).IsEqualTo(0); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_NullString() - { - // Assign - string? s = null; - var matcher = new JsonPartialMatcher(""); - - // Act - double match = matcher.IsMatch(s); - - // Assert - Check.That(match).IsEqualTo(0); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_NullObject() - { - // Assign - object? o = null; - var matcher = new JsonPartialMatcher(""); - - // Act - double match = matcher.IsMatch(o); - - // Assert - Check.That(match).IsEqualTo(0); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_JArray() - { - // Assign - var matcher = new JsonPartialMatcher(new[] { "x", "y" }); - - // Act - var jArray = new JArray - { - "x", - "y" - }; - double match = matcher.IsMatch(jArray); - - // Assert - Assert.Equal(1.0, match); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_JObject() - { - // Assign - var matcher = new JsonPartialMatcher(new { Id = 1, Name = "Test" }); - - // Act - var jObject = new JObject - { - { "Id", new JValue(1) }, - { "Name", new JValue("Test") } - }; - double match = matcher.IsMatch(jObject); - - // Assert - Assert.Equal(1.0, match); - } - - [Fact] - public void 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() - { - // Assign - var matcher = new JsonPartialMatcher(new { id = 1, Name = "test" }, true); - - // Act - var jObject = new JObject - { - { "Id", new JValue(1) }, - { "NaMe", new JValue("Test") } - }; - double match = matcher.IsMatch(jObject); - - // Assert - Assert.Equal(1.0, match); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_JObjectParsed() - { - // Assign - var matcher = new JsonPartialMatcher(new { Id = 1, Name = "Test" }); - - // Act - var jObject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }"); - double match = matcher.IsMatch(jObject); - - // Assert - Assert.Equal(1.0, match); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_WithIgnoreCaseTrue_JObjectParsed() - { - // Assign - var matcher = new JsonPartialMatcher(new { Id = 1, Name = "TESt" }, true); - - // Act - var jObject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }"); - double match = matcher.IsMatch(jObject); - - // Assert - Assert.Equal(1.0, match); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_JArrayAsString() - { - // Assign - var matcher = new JsonPartialMatcher("[ \"x\", \"y\" ]"); - - // Act - var jArray = new JArray - { - "x", - "y" - }; - double match = matcher.IsMatch(jArray); - - // Assert - Assert.Equal(1.0, match); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_JObjectAsString() - { - // Assign - var matcher = new JsonPartialMatcher("{ \"Id\" : 1, \"Name\" : \"Test\" }"); - - // Act - var jObject = new JObject - { - { "Id", new JValue(1) }, - { "Name", new JValue("Test") } - }; - double match = matcher.IsMatch(jObject); - - // Assert - Assert.Equal(1.0, match); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_WithIgnoreCaseTrue_JObjectAsString() - { - // Assign - var matcher = new JsonPartialMatcher("{ \"Id\" : 1, \"Name\" : \"test\" }", true); - - // Act - var jObject = new JObject - { - { "Id", new JValue(1) }, - { "Name", new JValue("Test") } - }; - double match = matcher.IsMatch(jObject); - - // Assert - Assert.Equal(1.0, match); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_JObjectAsString_RejectOnMatch() - { - // Assign - var matcher = new JsonPartialMatcher(MatchBehaviour.RejectOnMatch, "{ \"Id\" : 1, \"Name\" : \"Test\" }"); - - // Act - var jObject = new JObject - { - { "Id", new JValue(1) }, - { "Name", new JValue("Test") } - }; - double match = matcher.IsMatch(jObject); - - // Assert - Assert.Equal(0.0, match); - } - - [Fact] - public void JsonPartialMatcher_IsMatch_JObjectWithDateTimeOffsetAsString() - { - // Assign - var matcher = new JsonPartialMatcher("{ \"preferredAt\" : \"2019-11-21T10:32:53.2210009+00:00\" }"); - - // Act - var jObject = new JObject - { - { "preferredAt", new JValue("2019-11-21T10:32:53.2210009+00:00") } - }; - double match = matcher.IsMatch(jObject); - - // Assert - Assert.Equal(1.0, match); - } - - [Theory] - [InlineData("{\"test\":\"abc\"}", "{\"test\":\"abc\",\"other\":\"xyz\"}")] - [InlineData("\"test\"", "\"test\"")] - [InlineData("123", "123")] - [InlineData("[\"test\"]", "[\"test\"]")] - [InlineData("[\"test\"]", "[\"test\", \"other\"]")] - [InlineData("[123]", "[123]")] - [InlineData("[123]", "[123, 456]")] - [InlineData("{ \"test\":\"value\" }", "{\"test\":\"value\",\"other\":123}")] - [InlineData("{ \"test\":\"value\" }", "{\"test\":\"value\"}")] - [InlineData("{\"test\":{\"nested\":\"value\"}}", "{\"test\":{\"nested\":\"value\"}}")] - public void JsonPartialMatcher_IsMatch_StringInputValidMatch(string value, string input) - { - // Assign - var matcher = new JsonPartialMatcher(value); - - // Act - double match = matcher.IsMatch(input); - - // Assert - Assert.Equal(1.0, match); - } - - [Theory] - [InlineData("\"test\"", null)] - [InlineData("\"test1\"", "\"test2\"")] - [InlineData("123", "1234")] - [InlineData("[\"test\"]", "[\"test1\"]")] - [InlineData("[\"test\"]", "[\"test1\", \"test2\"]")] - [InlineData("[123]", "[1234]")] - [InlineData("{}", "\"test\"")] - [InlineData("{ \"test\":\"value\" }", "{\"test\":\"value2\"}")] - [InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value1\"}}")] - [InlineData("{\"test\":{\"test1\":\"value\"}}", "{\"test\":{\"test1\":\"value1\"}}")] - [InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value1\"}}]")] - public void JsonPartialMatcher_IsMatch_StringInputWithInvalidMatch(string value, string input) - { - // Assign - var matcher = new JsonPartialMatcher(value); - - // Act - double match = matcher.IsMatch(input); - - // Assert - Assert.Equal(0.0, match); - } - - [Theory] - [InlineData("{ \"test.nested\":123 }", "{\"test\":{\"nested\":123}}")] - [InlineData("{ \"test.nested\":[123, 456] }", "{\"test\":{\"nested\":[123, 456]}}")] - [InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value\"}}")] - [InlineData("{ \"['name.with.dot']\":\"value\" }", "{\"name.with.dot\":\"value\"}")] - [InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value\"}}]")] - [InlineData("[{ \"['name.with.dot']\":\"value\" }]", "[{\"name.with.dot\":\"value\"}]")] - public void JsonPartialMatcher_IsMatch_ValueAsJPathValidMatch(string value, string input) - { - // Assign - var matcher = new JsonPartialMatcher(value); - - // Act - double match = matcher.IsMatch(input); - - // Assert - Assert.Equal(1.0, match); - } - - [Theory] - [InlineData("{ \"test.nested\":123 }", "{\"test\":{\"nested\":456}}")] - [InlineData("{ \"test.nested\":[123, 456] }", "{\"test\":{\"nested\":[1, 2]}}")] - [InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value1\"}}")] - [InlineData("{ \"['name.with.dot']\":\"value\" }", "{\"name.with.dot\":\"value1\"}")] - [InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value1\"}}]")] - [InlineData("[{ \"['name.with.dot']\":\"value\" }]", "[{\"name.with.dot\":\"value1\"}]")] - public void JsonPartialMatcher_IsMatch_ValueAsJPathInvalidMatch(string value, string input) - { - // Assign - var matcher = new JsonPartialMatcher(value); - - // Act - double match = matcher.IsMatch(input); - - // Assert - Assert.Equal(0.0, match); - } + // Assert + Check.That(name).Equals("JsonPartialMatcher"); } -} + + [Fact] + public void JsonPartialMatcher_GetValue() + { + // Assign + var matcher = new JsonPartialMatcher("{}"); + + // Act + object value = matcher.Value; + + // Assert + Check.That(value).Equals("{}"); + } + + [Fact] + public void JsonPartialMatcher_WithInvalidStringValue_Should_ThrowException() + { + // Act + // ReSharper disable once ObjectCreationAsStatement + Action action = () => new JsonPartialMatcher(MatchBehaviour.AcceptOnMatch, "{ \"Id\""); + + // Assert + action.Should().Throw(); + } + + [Fact] + public void JsonPartialMatcher_WithInvalidObjectValue_Should_ThrowException() + { + // Act + // ReSharper disable once ObjectCreationAsStatement + Action action = () => new JsonPartialMatcher(MatchBehaviour.AcceptOnMatch, new MemoryStream()); + + // Assert + action.Should().Throw(); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_WithInvalidValue_And_ThrowExceptionIsFalse_Should_ReturnMismatch() + { + // Assign + var matcher = new JsonPartialMatcher(""); + + // Act + double match = matcher.IsMatch(new MemoryStream()); + + // Assert + Check.That(match).IsEqualTo(0); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_WithInvalidValue_And_ThrowExceptionIsTrue_Should_ReturnMismatch() + { + // Assign + var matcher = new JsonPartialMatcher("", false, true); + + // Act + Action action = () => matcher.IsMatch(new MemoryStream()); + + // Assert + action.Should().Throw(); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_ByteArray() + { + // Assign + var bytes = new byte[0]; + var matcher = new JsonPartialMatcher(""); + + // Act + double match = matcher.IsMatch(bytes); + + // Assert + Check.That(match).IsEqualTo(0); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_NullString() + { + // Assign + string? s = null; + var matcher = new JsonPartialMatcher(""); + + // Act + double match = matcher.IsMatch(s); + + // Assert + Check.That(match).IsEqualTo(0); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_NullObject() + { + // Assign + object? o = null; + var matcher = new JsonPartialMatcher(""); + + // Act + double match = matcher.IsMatch(o); + + // Assert + Check.That(match).IsEqualTo(0); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_JArray() + { + // Assign + var matcher = new JsonPartialMatcher(new[] { "x", "y" }); + + // Act + var jArray = new JArray + { + "x", + "y" + }; + double match = matcher.IsMatch(jArray); + + // Assert + Assert.Equal(1.0, match); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_JObject() + { + // Assign + var matcher = new JsonPartialMatcher(new { Id = 1, Name = "Test" }); + + // Act + var jObject = new JObject + { + { "Id", new JValue(1) }, + { "Name", new JValue("Test") } + }; + double match = matcher.IsMatch(jObject); + + // Assert + Assert.Equal(1.0, match); + } + + [Fact] + public void 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() + { + // Assign + var matcher = new JsonPartialMatcher(new { id = 1, Name = "test" }, true); + + // Act + var jObject = new JObject + { + { "Id", new JValue(1) }, + { "NaMe", new JValue("Test") } + }; + double match = matcher.IsMatch(jObject); + + // Assert + Assert.Equal(1.0, match); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_JObjectParsed() + { + // Assign + var matcher = new JsonPartialMatcher(new { Id = 1, Name = "Test" }); + + // Act + var jObject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }"); + double match = matcher.IsMatch(jObject); + + // Assert + Assert.Equal(1.0, match); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_WithIgnoreCaseTrue_JObjectParsed() + { + // Assign + var matcher = new JsonPartialMatcher(new { Id = 1, Name = "TESt" }, true); + + // Act + var jObject = JObject.Parse("{ \"Id\" : 1, \"Name\" : \"Test\" }"); + double match = matcher.IsMatch(jObject); + + // Assert + Assert.Equal(1.0, match); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_JArrayAsString() + { + // Assign + var matcher = new JsonPartialMatcher("[ \"x\", \"y\" ]"); + + // Act + var jArray = new JArray + { + "x", + "y" + }; + double match = matcher.IsMatch(jArray); + + // Assert + Assert.Equal(1.0, match); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_JObjectAsString() + { + // Assign + var matcher = new JsonPartialMatcher("{ \"Id\" : 1, \"Name\" : \"Test\" }"); + + // Act + var jObject = new JObject + { + { "Id", new JValue(1) }, + { "Name", new JValue("Test") } + }; + double match = matcher.IsMatch(jObject); + + // Assert + Assert.Equal(1.0, match); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_WithIgnoreCaseTrue_JObjectAsString() + { + // Assign + var matcher = new JsonPartialMatcher("{ \"Id\" : 1, \"Name\" : \"test\" }", true); + + // Act + var jObject = new JObject + { + { "Id", new JValue(1) }, + { "Name", new JValue("Test") } + }; + double match = matcher.IsMatch(jObject); + + // Assert + Assert.Equal(1.0, match); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_JObjectAsString_RejectOnMatch() + { + // Assign + var matcher = new JsonPartialMatcher(MatchBehaviour.RejectOnMatch, "{ \"Id\" : 1, \"Name\" : \"Test\" }"); + + // Act + var jObject = new JObject + { + { "Id", new JValue(1) }, + { "Name", new JValue("Test") } + }; + double match = matcher.IsMatch(jObject); + + // Assert + Assert.Equal(0.0, match); + } + + [Fact] + public void JsonPartialMatcher_IsMatch_JObjectWithDateTimeOffsetAsString() + { + // Assign + var matcher = new JsonPartialMatcher("{ \"preferredAt\" : \"2019-11-21T10:32:53.2210009+00:00\" }"); + + // Act + var jObject = new JObject + { + { "preferredAt", new JValue("2019-11-21T10:32:53.2210009+00:00") } + }; + double match = matcher.IsMatch(jObject); + + // Assert + Assert.Equal(1.0, match); + } + + [Theory] + [InlineData("{\"test\":\"abc\"}", "{\"test\":\"abc\",\"other\":\"xyz\"}")] + [InlineData("\"test\"", "\"test\"")] + [InlineData("123", "123")] + [InlineData("[\"test\"]", "[\"test\"]")] + [InlineData("[\"test\"]", "[\"test\", \"other\"]")] + [InlineData("[123]", "[123]")] + [InlineData("[123]", "[123, 456]")] + [InlineData("{ \"test\":\"value\" }", "{\"test\":\"value\",\"other\":123}")] + [InlineData("{ \"test\":\"value\" }", "{\"test\":\"value\"}")] + [InlineData("{\"test\":{\"nested\":\"value\"}}", "{\"test\":{\"nested\":\"value\"}}")] + public void JsonPartialMatcher_IsMatch_StringInputValidMatch(string value, string input) + { + // Assign + var matcher = new JsonPartialMatcher(value); + + // Act + double match = matcher.IsMatch(input); + + // Assert + Assert.Equal(1.0, match); + } + + [Theory] + [InlineData("\"test\"", null)] + [InlineData("\"test1\"", "\"test2\"")] + [InlineData("123", "1234")] + [InlineData("[\"test\"]", "[\"test1\"]")] + [InlineData("[\"test\"]", "[\"test1\", \"test2\"]")] + [InlineData("[123]", "[1234]")] + [InlineData("{}", "\"test\"")] + [InlineData("{ \"test\":\"value\" }", "{\"test\":\"value2\"}")] + [InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value1\"}}")] + [InlineData("{\"test\":{\"test1\":\"value\"}}", "{\"test\":{\"test1\":\"value1\"}}")] + [InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value1\"}}]")] + public void JsonPartialMatcher_IsMatch_StringInputWithInvalidMatch(string value, string input) + { + // Assign + var matcher = new JsonPartialMatcher(value); + + // Act + double match = matcher.IsMatch(input); + + // Assert + Assert.Equal(0.0, match); + } + + [Theory] + [InlineData("{ \"test.nested\":123 }", "{\"test\":{\"nested\":123}}")] + [InlineData("{ \"test.nested\":[123, 456] }", "{\"test\":{\"nested\":[123, 456]}}")] + [InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value\"}}")] + [InlineData("{ \"['name.with.dot']\":\"value\" }", "{\"name.with.dot\":\"value\"}")] + [InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value\"}}]")] + [InlineData("[{ \"['name.with.dot']\":\"value\" }]", "[{\"name.with.dot\":\"value\"}]")] + public void JsonPartialMatcher_IsMatch_ValueAsJPathValidMatch(string value, string input) + { + // Assign + var matcher = new JsonPartialMatcher(value); + + // Act + double match = matcher.IsMatch(input); + + // Assert + Assert.Equal(1.0, match); + } + + [Theory] + [InlineData("{ \"test.nested\":123 }", "{\"test\":{\"nested\":456}}")] + [InlineData("{ \"test.nested\":[123, 456] }", "{\"test\":{\"nested\":[1, 2]}}")] + [InlineData("{ \"test.nested\":\"value\" }", "{\"test\":{\"nested\":\"value1\"}}")] + [InlineData("{ \"['name.with.dot']\":\"value\" }", "{\"name.with.dot\":\"value1\"}")] + [InlineData("[{ \"test.nested\":\"value\" }]", "[{\"test\":{\"nested\":\"value1\"}}]")] + [InlineData("[{ \"['name.with.dot']\":\"value\" }]", "[{\"name.with.dot\":\"value1\"}]")] + public void JsonPartialMatcher_IsMatch_ValueAsJPathInvalidMatch(string value, string input) + { + // Assign + var matcher = new JsonPartialMatcher(value); + + // Act + double match = matcher.IsMatch(input); + + // Assert + Assert.Equal(0.0, match); + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/LinqMatcherTests.cs b/test/WireMock.Net.Tests/Matchers/LinqMatcherTests.cs index 1f15de17..d85a8498 100644 --- a/test/WireMock.Net.Tests/Matchers/LinqMatcherTests.cs +++ b/test/WireMock.Net.Tests/Matchers/LinqMatcherTests.cs @@ -3,110 +3,109 @@ using NFluent; using WireMock.Matchers; using Xunit; -namespace WireMock.Net.Tests.Matchers +namespace WireMock.Net.Tests.Matchers; + +public class LinqMatcherTests { - public class LinqMatcherTests + [Fact] + public void LinqMatcher_For_String_SinglePattern_IsMatch_Positive() { - [Fact] - public void LinqMatcher_For_String_SinglePattern_IsMatch_Positive() + // Assign + string input = "2018-08-31 13:59:59"; + + // Act + var matcher = new LinqMatcher("DateTime.Parse(it) > \"2018-08-01 13:50:00\""); + + // Assert + Check.That(matcher.IsMatch(input)).IsEqualTo(1.0d); + } + + [Fact] + public void LinqMatcher_For_String_IsMatch_Negative() + { + // Assign + string input = "2018-08-31 13:59:59"; + + // Act + var matcher = new LinqMatcher("DateTime.Parse(it) > \"2019-01-01 00:00:00\""); + + // Assert + Check.That(matcher.IsMatch(input)).IsEqualTo(0.0d); + } + + [Fact] + public void LinqMatcher_For_String_IsMatch_RejectOnMatch() + { + // Assign + string input = "2018-08-31 13:59:59"; + + // Act + var matcher = new LinqMatcher(MatchBehaviour.RejectOnMatch, "DateTime.Parse(it) > \"2018-08-01 13:50:00\""); + + // Assert + Check.That(matcher.IsMatch(input)).IsEqualTo(0.0d); + } + + [Fact] + public void LinqMatcher_For_Object_IsMatch() + { + // Assign + var input = new { - // Assign - string input = "2018-08-31 13:59:59"; + Id = 9, + Name = "Test" + }; - // Act - var matcher = new LinqMatcher("DateTime.Parse(it) > \"2018-08-01 13:50:00\""); + // Act + var matcher = new LinqMatcher("Id > 1 AND Name == \"Test\""); + double match = matcher.IsMatch(input); - // Assert - Check.That(matcher.IsMatch(input)).IsEqualTo(1.0d); - } + // Assert + Assert.Equal(1.0, match); + } - [Fact] - public void LinqMatcher_For_String_IsMatch_Negative() + [Fact] + public void LinqMatcher_For_JObject_IsMatch() + { + // Assign + var input = new JObject { - // Assign - string input = "2018-08-31 13:59:59"; + { "IntegerId", new JValue(9) }, + { "LongId", new JValue(long.MaxValue) }, + { "Name", new JValue("Test") } + }; - // Act - var matcher = new LinqMatcher("DateTime.Parse(it) > \"2019-01-01 00:00:00\""); + // Act + var matcher = new LinqMatcher("IntegerId > 1 AND LongId > 1 && Name == \"Test\""); + double match = matcher.IsMatch(input); - // Assert - Check.That(matcher.IsMatch(input)).IsEqualTo(0.0d); - } + // Assert + Assert.Equal(1.0, match); + } - [Fact] - public void LinqMatcher_For_String_IsMatch_RejectOnMatch() - { - // Assign - string input = "2018-08-31 13:59:59"; + [Fact] + public void LinqMatcher_GetName() + { + // Assign + var matcher = new LinqMatcher("x"); - // Act - var matcher = new LinqMatcher(MatchBehaviour.RejectOnMatch, "DateTime.Parse(it) > \"2018-08-01 13:50:00\""); + // Act + string name = matcher.Name; - // Assert - Check.That(matcher.IsMatch(input)).IsEqualTo(0.0d); - } + // Assert + Check.That(name).Equals("LinqMatcher"); + } - [Fact] - public void LinqMatcher_For_Object_IsMatch() - { - // Assign - var input = new - { - Id = 9, - Name = "Test" - }; + [Fact] + public void LinqMatcher_GetPatterns() + { + // Assign + var matcher = new LinqMatcher("x"); - // Act - var matcher = new LinqMatcher("Id > 1 AND Name == \"Test\""); - double match = matcher.IsMatch(input); + // Act + var patterns = matcher.GetPatterns(); - // Assert - Assert.Equal(1.0, match); - } - - [Fact] - public void LinqMatcher_For_JObject_IsMatch() - { - // Assign - var input = new JObject - { - { "IntegerId", new JValue(9) }, - { "LongId", new JValue(long.MaxValue) }, - { "Name", new JValue("Test") } - }; - - // Act - var matcher = new LinqMatcher("IntegerId > 1 AND LongId > 1 && Name == \"Test\""); - double match = matcher.IsMatch(input); - - // Assert - Assert.Equal(1.0, match); - } - - [Fact] - public void LinqMatcher_GetName() - { - // Assign - var matcher = new LinqMatcher("x"); - - // Act - string name = matcher.Name; - - // Assert - Check.That(name).Equals("LinqMatcher"); - } - - [Fact] - public void LinqMatcher_GetPatterns() - { - // Assign - var matcher = new LinqMatcher("x"); - - // Act - var patterns = matcher.GetPatterns(); - - // Assert - Check.That(patterns).ContainsExactly("x"); - } + // Assert + Check.That(patterns).ContainsExactly("x"); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/MatchBehaviourHelperTests.cs b/test/WireMock.Net.Tests/Matchers/MatchBehaviourHelperTests.cs index f941bee2..d4da50e0 100644 --- a/test/WireMock.Net.Tests/Matchers/MatchBehaviourHelperTests.cs +++ b/test/WireMock.Net.Tests/Matchers/MatchBehaviourHelperTests.cs @@ -1,25 +1,24 @@ -using NFluent; +using NFluent; using WireMock.Matchers; using Xunit; -namespace WireMock.Net.Tests.Matchers -{ - public class MatchBehaviourHelperTests - { - [Fact] - public void MatchBehaviourHelper_Convert_AcceptOnMatch() - { - Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.AcceptOnMatch, 0.0)).IsEqualTo(0.0); - Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.AcceptOnMatch, 0.5)).IsEqualTo(0.5); - Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.AcceptOnMatch, 1.0)).IsEqualTo(1.0); - } +namespace WireMock.Net.Tests.Matchers; - [Fact] - public void MatchBehaviourHelper_Convert_RejectOnMatch() - { - Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.RejectOnMatch, 0.0)).IsEqualTo(1.0); - Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.RejectOnMatch, 0.5)).IsEqualTo(0.0); - Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.RejectOnMatch, 1.0)).IsEqualTo(0.0); - } +public class MatchBehaviourHelperTests +{ + [Fact] + public void MatchBehaviourHelper_Convert_AcceptOnMatch() + { + Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.AcceptOnMatch, 0.0)).IsEqualTo(0.0); + Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.AcceptOnMatch, 0.5)).IsEqualTo(0.5); + Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.AcceptOnMatch, 1.0)).IsEqualTo(1.0); } -} + + [Fact] + public void MatchBehaviourHelper_Convert_RejectOnMatch() + { + Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.RejectOnMatch, 0.0)).IsEqualTo(1.0); + Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.RejectOnMatch, 0.5)).IsEqualTo(0.0); + Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.RejectOnMatch, 1.0)).IsEqualTo(0.0); + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/NotNullOrEmptyMatcherTests.cs b/test/WireMock.Net.Tests/Matchers/NotNullOrEmptyMatcherTests.cs index 151fec55..38a8e8e5 100644 --- a/test/WireMock.Net.Tests/Matchers/NotNullOrEmptyMatcherTests.cs +++ b/test/WireMock.Net.Tests/Matchers/NotNullOrEmptyMatcherTests.cs @@ -3,82 +3,81 @@ using NFluent; using WireMock.Matchers; using Xunit; -namespace WireMock.Net.Tests.Matchers +namespace WireMock.Net.Tests.Matchers; + +public class NotNullOrEmptyMatcherTests { - public class NotNullOrEmptyMatcherTests + [Fact] + public void NotNullOrEmptyMatcher_GetName() { - [Fact] - public void NotNullOrEmptyMatcher_GetName() - { - // Act - var matcher = new NotNullOrEmptyMatcher(); - string name = matcher.Name; + // Act + var matcher = new NotNullOrEmptyMatcher(); + string name = matcher.Name; - // Assert - Check.That(name).Equals("NotNullOrEmptyMatcher"); - } + // Assert + Check.That(name).Equals("NotNullOrEmptyMatcher"); + } - [Theory] - [InlineData(null, 0.0)] - [InlineData(new byte[0], 0.0)] - [InlineData(new byte[] { 48 }, 1.0)] - public void NotNullOrEmptyMatcher_IsMatch_ByteArray(byte[] data, double expected) - { - // Act - var matcher = new NotNullOrEmptyMatcher(); - double result = matcher.IsMatch(data); + [Theory] + [InlineData(null, 0.0)] + [InlineData(new byte[0], 0.0)] + [InlineData(new byte[] { 48 }, 1.0)] + public void NotNullOrEmptyMatcher_IsMatch_ByteArray(byte[] data, double expected) + { + // Act + var matcher = new NotNullOrEmptyMatcher(); + double result = matcher.IsMatch(data); - // Assert - result.Should().Be(expected); - } + // Assert + result.Should().Be(expected); + } - [Theory] - [InlineData(null, 0.0)] - [InlineData("", 0.0)] - [InlineData("x", 1.0)] - public void NotNullOrEmptyMatcher_IsMatch_String(string @string, double expected) - { - // Act - var matcher = new NotNullOrEmptyMatcher(); - double result = matcher.IsMatch(@string); + [Theory] + [InlineData(null, 0.0)] + [InlineData("", 0.0)] + [InlineData("x", 1.0)] + public void NotNullOrEmptyMatcher_IsMatch_String(string @string, double expected) + { + // Act + var matcher = new NotNullOrEmptyMatcher(); + double result = matcher.IsMatch(@string); - // Assert - result.Should().Be(expected); - } + // Assert + result.Should().Be(expected); + } - [Theory] - [InlineData(null, 0.0)] - [InlineData("", 0.0)] - [InlineData("x", 1.0)] - public void NotNullOrEmptyMatcher_IsMatch_StringAsObject(string @string, double expected) - { - // Act - var matcher = new NotNullOrEmptyMatcher(); - double result = matcher.IsMatch((object)@string); + [Theory] + [InlineData(null, 0.0)] + [InlineData("", 0.0)] + [InlineData("x", 1.0)] + public void NotNullOrEmptyMatcher_IsMatch_StringAsObject(string @string, double expected) + { + // Act + var matcher = new NotNullOrEmptyMatcher(); + double result = matcher.IsMatch((object)@string); - // Assert - result.Should().Be(expected); - } + // Assert + result.Should().Be(expected); + } - [Fact] - public void NotNullOrEmptyMatcher_IsMatch_Json() - { - // Act - var matcher = new NotNullOrEmptyMatcher(); - double result = matcher.IsMatch(new { x = "x" }); + [Fact] + public void NotNullOrEmptyMatcher_IsMatch_Json() + { + // Act + var matcher = new NotNullOrEmptyMatcher(); + double result = matcher.IsMatch(new { x = "x" }); - // Assert - result.Should().Be(1.0); - } + // Assert + result.Should().Be(1.0); + } - [Fact] - public void NotNullOrEmptyMatcher_GetPatterns_Should_Return_EmptyArray() - { - // Act - var patterns = new NotNullOrEmptyMatcher().GetPatterns(); + [Fact] + public void NotNullOrEmptyMatcher_GetPatterns_Should_Return_EmptyArray() + { + // Act + var patterns = new NotNullOrEmptyMatcher().GetPatterns(); - // Assert - patterns.Should().BeEmpty(); - } + // Assert + patterns.Should().BeEmpty(); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/RegexMatcherTests.cs b/test/WireMock.Net.Tests/Matchers/RegexMatcherTests.cs index f39fea64..552dbc68 100644 --- a/test/WireMock.Net.Tests/Matchers/RegexMatcherTests.cs +++ b/test/WireMock.Net.Tests/Matchers/RegexMatcherTests.cs @@ -4,124 +4,123 @@ using NFluent; using WireMock.Matchers; using Xunit; -namespace WireMock.Net.Tests.Matchers +namespace WireMock.Net.Tests.Matchers; + +public class RegexMatcherTests { - public class RegexMatcherTests + [Fact] + public void RegexMatcher_GetName() { - [Fact] - public void RegexMatcher_GetName() - { - // Assign - var matcher = new RegexMatcher(""); + // Assign + var matcher = new RegexMatcher(""); - // Act - string name = matcher.Name; + // Act + string name = matcher.Name; - // Assert - Check.That(name).Equals("RegexMatcher"); - } + // Assert + Check.That(name).Equals("RegexMatcher"); + } - [Fact] - public void RegexMatcher_GetPatterns() - { - // Assign - var matcher = new RegexMatcher("X"); + [Fact] + public void RegexMatcher_GetPatterns() + { + // Assign + var matcher = new RegexMatcher("X"); - // Act - var patterns = matcher.GetPatterns(); + // Act + var patterns = matcher.GetPatterns(); - // Assert - Check.That(patterns).ContainsExactly("X"); - } + // Assert + Check.That(patterns).ContainsExactly("X"); + } - [Fact] - public void RegexMatcher_GetIgnoreCase() - { - // Act - bool case1 = new RegexMatcher("X").IgnoreCase; - bool case2 = new RegexMatcher("X", true).IgnoreCase; + [Fact] + public void RegexMatcher_GetIgnoreCase() + { + // Act + bool case1 = new RegexMatcher("X").IgnoreCase; + bool case2 = new RegexMatcher("X", true).IgnoreCase; - // Assert - Check.That(case1).IsFalse(); - Check.That(case2).IsTrue(); - } + // Assert + Check.That(case1).IsFalse(); + Check.That(case2).IsTrue(); + } - [Fact] - public void RegexMatcher_IsMatch() - { - // Assign - var matcher = new RegexMatcher("H.*o"); + [Fact] + public void RegexMatcher_IsMatch() + { + // Assign + var matcher = new RegexMatcher("H.*o"); - // Act - double result = matcher.IsMatch("Hello world!"); + // Act + double result = matcher.IsMatch("Hello world!"); - // Assert - Check.That(result).IsEqualTo(1.0d); - } + // Assert + Check.That(result).IsEqualTo(1.0d); + } - [Fact] - public void RegexMatcher_IsMatch_NullInput() - { - // Assign - var matcher = new RegexMatcher("H.*o"); + [Fact] + public void RegexMatcher_IsMatch_NullInput() + { + // Assign + var matcher = new RegexMatcher("H.*o"); - // Act - double result = matcher.IsMatch(null); + // Act + double result = matcher.IsMatch(null); - // Assert - Check.That(result).IsEqualTo(0.0d); - } + // Assert + Check.That(result).IsEqualTo(0.0d); + } - [Fact] - public void RegexMatcher_IsMatch_RegexExtended_Guid() - { - // Assign - var matcher = new RegexMatcher(@"\GUIDB", true); + [Fact] + public void RegexMatcher_IsMatch_RegexExtended_Guid() + { + // Assign + var matcher = new RegexMatcher(@"\GUIDB", true); - // Act - double result = matcher.IsMatch(Guid.NewGuid().ToString("B")); + // Act + double result = matcher.IsMatch(Guid.NewGuid().ToString("B")); - // Assert - result.Should().Be(1.0); - } + // Assert + result.Should().Be(1.0); + } - [Fact] - public void RegexMatcher_IsMatch_Regex_Guid() - { - // Assign - var matcher = new RegexMatcher(@"\GUIDB", true, false, false); + [Fact] + public void RegexMatcher_IsMatch_Regex_Guid() + { + // Assign + var matcher = new RegexMatcher(@"\GUIDB", true, false, false); - // Act - double result = matcher.IsMatch(Guid.NewGuid().ToString("B")); + // Act + double result = matcher.IsMatch(Guid.NewGuid().ToString("B")); - // Assert - result.Should().Be(0); - } + // Assert + result.Should().Be(0); + } - [Fact] - public void RegexMatcher_IsMatch_IgnoreCase() - { - // Assign - var matcher = new RegexMatcher("H.*o", true); + [Fact] + public void RegexMatcher_IsMatch_IgnoreCase() + { + // Assign + var matcher = new RegexMatcher("H.*o", true); - // Act - double result = matcher.IsMatch("hello"); + // Act + double result = matcher.IsMatch("hello"); - // Assert - Check.That(result).IsEqualTo(1.0d); - } + // Assert + Check.That(result).IsEqualTo(1.0d); + } - [Fact] - public void RegexMatcher_IsMatch_RejectOnMatch() - { - // Assign - var matcher = new RegexMatcher(MatchBehaviour.RejectOnMatch, "h.*o"); + [Fact] + public void RegexMatcher_IsMatch_RejectOnMatch() + { + // Assign + var matcher = new RegexMatcher(MatchBehaviour.RejectOnMatch, "h.*o"); - // Act - double result = matcher.IsMatch("hello"); + // Act + double result = matcher.IsMatch("hello"); - // Assert - Check.That(result).IsEqualTo(0.0); - } + // Assert + Check.That(result).IsEqualTo(0.0); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/RequestMatchResultTests.cs b/test/WireMock.Net.Tests/Matchers/RequestMatchResultTests.cs index c48d7a32..8b13d500 100644 --- a/test/WireMock.Net.Tests/Matchers/RequestMatchResultTests.cs +++ b/test/WireMock.Net.Tests/Matchers/RequestMatchResultTests.cs @@ -1,54 +1,53 @@ -using System.Linq; +using System.Linq; using FluentAssertions; using WireMock.Matchers; using WireMock.Matchers.Request; using Xunit; -namespace WireMock.Net.Tests.Matchers +namespace WireMock.Net.Tests.Matchers; + +public class RequestMatchResultTests { - public class RequestMatchResultTests + [Fact] + public void CompareTo_WithDifferentAverageScore_ReturnsBestMatch() { - [Fact] - public void CompareTo_WithDifferentAverageScore_ReturnsBestMatch() - { - // Arrange - var result1 = new RequestMatchResult(); - result1.AddScore(typeof(WildcardMatcher), 1); - result1.AddScore(typeof(WildcardMatcher), 0.9); + // Arrange + var result1 = new RequestMatchResult(); + result1.AddScore(typeof(WildcardMatcher), 1); + result1.AddScore(typeof(WildcardMatcher), 0.9); - var result2 = new RequestMatchResult(); - result2.AddScore(typeof(LinqMatcher), 1); - result2.AddScore(typeof(LinqMatcher), 1); + var result2 = new RequestMatchResult(); + result2.AddScore(typeof(LinqMatcher), 1); + result2.AddScore(typeof(LinqMatcher), 1); - var results = new[] { result1, result2 }; + var results = new[] { result1, result2 }; - // Act - var best = results.OrderBy(x => x).First(); + // Act + var best = results.OrderBy(x => x).First(); - // Assert - best.Should().Be(result2); - } + // Assert + best.Should().Be(result2); + } - [Fact] - public void CompareTo_WithSameAverageScoreButMoreMatchers_ReturnsMatchWithMoreMatchers() - { - // Arrange - var result1 = new RequestMatchResult(); - result1.AddScore(typeof(WildcardMatcher), 1); - result1.AddScore(typeof(WildcardMatcher), 1); + [Fact] + public void CompareTo_WithSameAverageScoreButMoreMatchers_ReturnsMatchWithMoreMatchers() + { + // Arrange + var result1 = new RequestMatchResult(); + result1.AddScore(typeof(WildcardMatcher), 1); + result1.AddScore(typeof(WildcardMatcher), 1); - var result2 = new RequestMatchResult(); - result2.AddScore(typeof(LinqMatcher), 1); - result2.AddScore(typeof(LinqMatcher), 1); - result2.AddScore(typeof(LinqMatcher), 1); + var result2 = new RequestMatchResult(); + result2.AddScore(typeof(LinqMatcher), 1); + result2.AddScore(typeof(LinqMatcher), 1); + result2.AddScore(typeof(LinqMatcher), 1); - var results = new[] { result1, result2 }; + var results = new[] { result1, result2 }; - // Act - var best = results.OrderBy(x => x).First(); + // Act + var best = results.OrderBy(x => x).First(); - // Assert - best.Should().Be(result2); - } + // Assert + best.Should().Be(result2); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/SimMetricsMatcherTests.cs b/test/WireMock.Net.Tests/Matchers/SimMetricsMatcherTests.cs index e792578d..46319a3e 100644 --- a/test/WireMock.Net.Tests/Matchers/SimMetricsMatcherTests.cs +++ b/test/WireMock.Net.Tests/Matchers/SimMetricsMatcherTests.cs @@ -2,86 +2,85 @@ using NFluent; using WireMock.Matchers; using Xunit; -namespace WireMock.Net.Tests.Matchers +namespace WireMock.Net.Tests.Matchers; + +public class SimMetricsMatcherTests { - public class SimMetricsMatcherTests + [Fact] + public void SimMetricsMatcher_GetName() { - [Fact] - public void SimMetricsMatcher_GetName() - { - // Assign - var matcher = new SimMetricsMatcher("X"); + // Assign + var matcher = new SimMetricsMatcher("X"); - // Act - string name = matcher.Name; + // Act + string name = matcher.Name; - // Assert - Check.That(name).Equals("SimMetricsMatcher.Levenstein"); - } + // Assert + Check.That(name).Equals("SimMetricsMatcher.Levenstein"); + } - [Fact] - public void SimMetricsMatcher_GetPatterns() - { - // Assign - var matcher = new SimMetricsMatcher("X"); + [Fact] + public void SimMetricsMatcher_GetPatterns() + { + // Assign + var matcher = new SimMetricsMatcher("X"); - // Act - var patterns = matcher.GetPatterns(); + // Act + var patterns = matcher.GetPatterns(); - // Assert - Check.That(patterns).ContainsExactly("X"); - } + // Assert + Check.That(patterns).ContainsExactly("X"); + } - [Fact] - public void SimMetricsMatcher_IsMatch_1() - { - // Assign - var matcher = new SimMetricsMatcher("The cat walks in the street."); + [Fact] + public void SimMetricsMatcher_IsMatch_1() + { + // Assign + var matcher = new SimMetricsMatcher("The cat walks in the street."); - // Act - double result = matcher.IsMatch("The car drives in the street."); + // Act + double result = matcher.IsMatch("The car drives in the street."); - // Assert - Check.That(result).IsStrictlyLessThan(1.0).And.IsStrictlyGreaterThan(0.5); - } + // Assert + Check.That(result).IsStrictlyLessThan(1.0).And.IsStrictlyGreaterThan(0.5); + } - [Fact] - public void SimMetricsMatcher_IsMatch_2() - { - // Assign - var matcher = new SimMetricsMatcher("The cat walks in the street."); + [Fact] + public void SimMetricsMatcher_IsMatch_2() + { + // Assign + var matcher = new SimMetricsMatcher("The cat walks in the street."); - // Act - double result = matcher.IsMatch("Hello"); + // Act + double result = matcher.IsMatch("Hello"); - // Assert - Check.That(result).IsStrictlyLessThan(0.1).And.IsStrictlyGreaterThan(0.05); - } + // Assert + Check.That(result).IsStrictlyLessThan(0.1).And.IsStrictlyGreaterThan(0.05); + } - [Fact] - public void SimMetricsMatcher_IsMatch_AcceptOnMatch() - { - // Assign - var matcher = new SimMetricsMatcher("test"); + [Fact] + public void SimMetricsMatcher_IsMatch_AcceptOnMatch() + { + // Assign + var matcher = new SimMetricsMatcher("test"); - // Act - double result = matcher.IsMatch("test"); + // Act + double result = matcher.IsMatch("test"); - // Assert - Check.That(result).IsEqualTo(1.0); - } + // Assert + Check.That(result).IsEqualTo(1.0); + } - [Fact] - public void SimMetricsMatcher_IsMatch_RejectOnMatch() - { - // Assign - var matcher = new SimMetricsMatcher(MatchBehaviour.RejectOnMatch, "test"); + [Fact] + public void SimMetricsMatcher_IsMatch_RejectOnMatch() + { + // Assign + var matcher = new SimMetricsMatcher(MatchBehaviour.RejectOnMatch, "test"); - // Act - double result = matcher.IsMatch("test"); + // Act + double result = matcher.IsMatch("test"); - // Assert - Check.That(result).IsEqualTo(0.0); - } + // Assert + Check.That(result).IsEqualTo(0.0); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Matchers/WildcardMatcherTest.cs b/test/WireMock.Net.Tests/Matchers/WildcardMatcherTest.cs index 6adb2544..c3840854 100644 --- a/test/WireMock.Net.Tests/Matchers/WildcardMatcherTest.cs +++ b/test/WireMock.Net.Tests/Matchers/WildcardMatcherTest.cs @@ -5,135 +5,134 @@ using WireMock.Matchers; using WireMock.Models; using Xunit; -namespace WireMock.Net.Tests.Matchers +namespace WireMock.Net.Tests.Matchers; + +public class WildcardMatcherTest { - public class WildcardMatcherTest + [Fact] + public void WildcardMatcher_IsMatch_With_StringPattern() { - [Fact] - public void WildcardMatcher_IsMatch_With_StringPattern() + // Arrange + var pattern = new StringPattern { - // Arrange - var pattern = new StringPattern - { - Pattern = "*", - PatternAsFile = "pf" - }; + Pattern = "*", + PatternAsFile = "pf" + }; - // Act - var matcher = new WildcardMatcher(pattern); + // Act + var matcher = new WildcardMatcher(pattern); - // Assert - matcher.IsMatch("a").Should().Be(1.0d); - } + // Assert + matcher.IsMatch("a").Should().Be(1.0d); + } - [Fact] - public void WildcardMatcher_IsMatch_With_StringPatterns() + [Fact] + public void WildcardMatcher_IsMatch_With_StringPatterns() + { + // Arrange + AnyOf pattern1 = new StringPattern { - // Arrange - AnyOf pattern1 = new StringPattern - { - Pattern = "a" - }; - AnyOf pattern2 = new StringPattern - { - Pattern = "b" - }; - - // Act - var matcher = new WildcardMatcher(new [] { pattern1, pattern2 }); - - // Assert - matcher.IsMatch("a").Should().Be(1.0d); - } - - [Fact] - public void WildcardMatcher_IsMatch_Positive() + Pattern = "a" + }; + AnyOf pattern2 = new StringPattern { - var tests = new[] - { - new { p = "*", i = "" }, - new { p = "?", i = " "}, - new { p = "*", i = "a "}, - new { p = "*", i = "ab" }, - new { p = "?", i = "a" }, - new { p = "*?", i = "abc" }, - new { p = "?*", i = "abc" }, - new { p = "abc", i = "abc" }, - new { p = "abc*", i = "abc" }, - new { p = "abc*", i = "abcd" }, - new { p = "*abc*", i = "abc" }, - new { p = "*a*bc*", i = "abc" }, - new { p = "*a*b?", i = "aXXXbc" } - }; + Pattern = "b" + }; - foreach (var test in tests) - { - var matcher = new WildcardMatcher(test.p); - matcher.IsMatch(test.i).Should().Be(1.0d, $"Pattern '{test.p}' with value '{test.i}' should be 1.0"); - } - } + // Act + var matcher = new WildcardMatcher(new [] { pattern1, pattern2 }); - [Fact] - public void WildcardMatcher_IsMatch_Negative() + // Assert + matcher.IsMatch("a").Should().Be(1.0d); + } + + [Fact] + public void WildcardMatcher_IsMatch_Positive() + { + var tests = new[] { - var tests = new[] - { - new { p = "*a", i = "" }, - new { p = "a*", i = "" }, - new { p = "?", i = "" }, - new { p = "*b*", i = "a" }, - new { p = "b*a", i = "ab" }, - new { p = "??", i = "a" }, - new { p = "*?", i = "" }, - new { p = "??*", i = "a" }, - new { p = "*abc", i = "abX" }, - new { p = "*abc*", i = "Xbc" }, - new { p = "*a*bc*", i = "ac" } - }; + new { p = "*", i = "" }, + new { p = "?", i = " "}, + new { p = "*", i = "a "}, + new { p = "*", i = "ab" }, + new { p = "?", i = "a" }, + new { p = "*?", i = "abc" }, + new { p = "?*", i = "abc" }, + new { p = "abc", i = "abc" }, + new { p = "abc*", i = "abc" }, + new { p = "abc*", i = "abcd" }, + new { p = "*abc*", i = "abc" }, + new { p = "*a*bc*", i = "abc" }, + new { p = "*a*b?", i = "aXXXbc" } + }; - foreach (var test in tests) - { - var matcher = new WildcardMatcher(test.p); - Check.That(matcher.IsMatch(test.i)).IsEqualTo(0.0); - } - } - - [Fact] - public void WildcardMatcher_GetName() + foreach (var test in tests) { - // Assign - var matcher = new WildcardMatcher("x"); - - // Act - string name = matcher.Name; - - // Assert - Check.That(name).Equals("WildcardMatcher"); - } - - [Fact] - public void WildcardMatcher_GetPatterns() - { - // Assign - var matcher = new WildcardMatcher("x"); - - // Act - var patterns = matcher.GetPatterns(); - - // Assert - Check.That(patterns).ContainsExactly(new AnyOf("x")); - } - - [Fact] - public void WildcardMatcher_IsMatch_RejectOnMatch() - { - // Assign - var matcher = new WildcardMatcher(MatchBehaviour.RejectOnMatch, "m"); - - // Act - double result = matcher.IsMatch("m"); - - Check.That(result).IsEqualTo(0.0); + var matcher = new WildcardMatcher(test.p); + matcher.IsMatch(test.i).Should().Be(1.0d, $"Pattern '{test.p}' with value '{test.i}' should be 1.0"); } } + + [Fact] + public void WildcardMatcher_IsMatch_Negative() + { + var tests = new[] + { + new { p = "*a", i = "" }, + new { p = "a*", i = "" }, + new { p = "?", i = "" }, + new { p = "*b*", i = "a" }, + new { p = "b*a", i = "ab" }, + new { p = "??", i = "a" }, + new { p = "*?", i = "" }, + new { p = "??*", i = "a" }, + new { p = "*abc", i = "abX" }, + new { p = "*abc*", i = "Xbc" }, + new { p = "*a*bc*", i = "ac" } + }; + + foreach (var test in tests) + { + var matcher = new WildcardMatcher(test.p); + Check.That(matcher.IsMatch(test.i)).IsEqualTo(0.0); + } + } + + [Fact] + public void WildcardMatcher_GetName() + { + // Assign + var matcher = new WildcardMatcher("x"); + + // Act + string name = matcher.Name; + + // Assert + Check.That(name).Equals("WildcardMatcher"); + } + + [Fact] + public void WildcardMatcher_GetPatterns() + { + // Assign + var matcher = new WildcardMatcher("x"); + + // Act + var patterns = matcher.GetPatterns(); + + // Assert + Check.That(patterns).ContainsExactly(new AnyOf("x")); + } + + [Fact] + public void WildcardMatcher_IsMatch_RejectOnMatch() + { + // Assign + var matcher = new WildcardMatcher(MatchBehaviour.RejectOnMatch, "m"); + + // Act + double result = matcher.IsMatch("m"); + + Check.That(result).IsEqualTo(0.0); + } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/RegularExpressions/RegexExtendedTests.cs b/test/WireMock.Net.Tests/RegularExpressions/RegexExtendedTests.cs index fdeca434..07d3c6d4 100644 --- a/test/WireMock.Net.Tests/RegularExpressions/RegexExtendedTests.cs +++ b/test/WireMock.Net.Tests/RegularExpressions/RegexExtendedTests.cs @@ -3,98 +3,97 @@ using NFluent; using WireMock.RegularExpressions; using Xunit; -namespace WireMock.Net.Tests.RegularExpressions +namespace WireMock.Net.Tests.RegularExpressions; + +public class RegexExtendedTests { - public class RegexExtendedTests + /// + /// Input guid used for testing + /// + public Guid InputGuid => Guid.NewGuid(); + + [Fact] + public void RegexExtended_GuidB_Pattern() { - /// - /// Input guid used for testing - /// - public Guid InputGuid => Guid.NewGuid(); + var guidbUpper = @".*\GUIDB.*"; + var guidbLower = @".*\guidb.*"; - [Fact] - public void RegexExtended_GuidB_Pattern() - { - var guidbUpper = @".*\GUIDB.*"; - var guidbLower = @".*\guidb.*"; + var inputLower = InputGuid.ToString("B"); + var inputUpper = InputGuid.ToString("B").ToUpper(); + var regexLower = new RegexExtended(guidbLower); + var regexUpper = new RegexExtended(guidbUpper); - var inputLower = InputGuid.ToString("B"); - var inputUpper = InputGuid.ToString("B").ToUpper(); - var regexLower = new RegexExtended(guidbLower); - var regexUpper = new RegexExtended(guidbUpper); - - Check.That(regexLower.IsMatch(inputLower)).Equals(true); - Check.That(regexLower.IsMatch(inputUpper)).Equals(false); - Check.That(regexUpper.IsMatch(inputUpper)).Equals(true); - Check.That(regexUpper.IsMatch(inputLower)).Equals(false); - } - - [Fact] - public void RegexExtended_GuidD_Pattern() - { - var guiddUpper = @".*\GUIDD.*"; - var guiddLower = @".*\guidd.*"; - - var inputLower = InputGuid.ToString("D"); - var inputUpper = InputGuid.ToString("D").ToUpper(); - var regexLower = new RegexExtended(guiddLower); - var regexUpper = new RegexExtended(guiddUpper); - - Check.That(regexLower.IsMatch(inputLower)).Equals(true); - Check.That(regexLower.IsMatch(inputUpper)).Equals(false); - Check.That(regexUpper.IsMatch(inputUpper)).Equals(true); - Check.That(regexUpper.IsMatch(inputLower)).Equals(false); - } - - [Fact] - public void RegexExtended_GuidN_Pattern() - { - var guidnUpper = @".*\GUIDN.*"; - var guidnLower = @".*\guidn.*"; - - var inputLower = InputGuid.ToString("N"); - var inputUpper = InputGuid.ToString("N").ToUpper(); - var regexLower = new RegexExtended(guidnLower); - var regexUpper = new RegexExtended(guidnUpper); - - Check.That(regexLower.IsMatch(inputLower)).Equals(true); - Check.That(regexLower.IsMatch(inputUpper)).Equals(false); - Check.That(regexUpper.IsMatch(inputUpper)).Equals(true); - Check.That(regexUpper.IsMatch(inputLower)).Equals(false); - } - - [Fact] - public void RegexExtended_GuidP_Pattern() - { - var guidpUpper = @".*\GUIDP.*"; - var guidpLower = @".*\guidp.*"; - - var inputLower = InputGuid.ToString("P"); - var inputUpper = InputGuid.ToString("P").ToUpper(); - var regexLower = new RegexExtended(guidpLower); - var regexUpper = new RegexExtended(guidpUpper); - - Check.That(regexLower.IsMatch(inputLower)).Equals(true); - Check.That(regexLower.IsMatch(inputUpper)).Equals(false); - Check.That(regexUpper.IsMatch(inputUpper)).Equals(true); - Check.That(regexUpper.IsMatch(inputLower)).Equals(false); - } - - [Fact] - public void RegexExtended_GuidX_Pattern() - { - var guidxUpper = @".*\GUIDX.*"; - var guidxLower = @".*\guidx.*"; - - var inputLower = InputGuid.ToString("X"); - var inputUpper = InputGuid.ToString("X").ToUpper().Replace("X", "x"); - var regexLower = new RegexExtended(guidxLower); - var regexUpper = new RegexExtended(guidxUpper); - - Check.That(regexLower.IsMatch(inputLower)).Equals(true); - Check.That(regexLower.IsMatch(inputUpper)).Equals(false); - Check.That(regexUpper.IsMatch(inputUpper)).Equals(true); - Check.That(regexUpper.IsMatch(inputLower)).Equals(false); - } + Check.That(regexLower.IsMatch(inputLower)).Equals(true); + Check.That(regexLower.IsMatch(inputUpper)).Equals(false); + Check.That(regexUpper.IsMatch(inputUpper)).Equals(true); + Check.That(regexUpper.IsMatch(inputLower)).Equals(false); } -} + + [Fact] + public void RegexExtended_GuidD_Pattern() + { + var guiddUpper = @".*\GUIDD.*"; + var guiddLower = @".*\guidd.*"; + + var inputLower = InputGuid.ToString("D"); + var inputUpper = InputGuid.ToString("D").ToUpper(); + var regexLower = new RegexExtended(guiddLower); + var regexUpper = new RegexExtended(guiddUpper); + + Check.That(regexLower.IsMatch(inputLower)).Equals(true); + Check.That(regexLower.IsMatch(inputUpper)).Equals(false); + Check.That(regexUpper.IsMatch(inputUpper)).Equals(true); + Check.That(regexUpper.IsMatch(inputLower)).Equals(false); + } + + [Fact] + public void RegexExtended_GuidN_Pattern() + { + var guidnUpper = @".*\GUIDN.*"; + var guidnLower = @".*\guidn.*"; + + var inputLower = InputGuid.ToString("N"); + var inputUpper = InputGuid.ToString("N").ToUpper(); + var regexLower = new RegexExtended(guidnLower); + var regexUpper = new RegexExtended(guidnUpper); + + Check.That(regexLower.IsMatch(inputLower)).Equals(true); + Check.That(regexLower.IsMatch(inputUpper)).Equals(false); + Check.That(regexUpper.IsMatch(inputUpper)).Equals(true); + Check.That(regexUpper.IsMatch(inputLower)).Equals(false); + } + + [Fact] + public void RegexExtended_GuidP_Pattern() + { + var guidpUpper = @".*\GUIDP.*"; + var guidpLower = @".*\guidp.*"; + + var inputLower = InputGuid.ToString("P"); + var inputUpper = InputGuid.ToString("P").ToUpper(); + var regexLower = new RegexExtended(guidpLower); + var regexUpper = new RegexExtended(guidpUpper); + + Check.That(regexLower.IsMatch(inputLower)).Equals(true); + Check.That(regexLower.IsMatch(inputUpper)).Equals(false); + Check.That(regexUpper.IsMatch(inputUpper)).Equals(true); + Check.That(regexUpper.IsMatch(inputLower)).Equals(false); + } + + [Fact] + public void RegexExtended_GuidX_Pattern() + { + var guidxUpper = @".*\GUIDX.*"; + var guidxLower = @".*\guidx.*"; + + var inputLower = InputGuid.ToString("X"); + var inputUpper = InputGuid.ToString("X").ToUpper().Replace("X", "x"); + var regexLower = new RegexExtended(guidxLower); + var regexUpper = new RegexExtended(guidxUpper); + + Check.That(regexLower.IsMatch(inputLower)).Equals(true); + Check.That(regexLower.IsMatch(inputUpper)).Equals(false); + Check.That(regexUpper.IsMatch(inputUpper)).Equals(true); + Check.That(regexUpper.IsMatch(inputLower)).Equals(false); + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderUsingMethodTests.cs b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderUsingMethodTests.cs index 4bfeedc6..d60c0c74 100644 --- a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderUsingMethodTests.cs +++ b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderUsingMethodTests.cs @@ -1,78 +1,77 @@ -using System.Collections.Generic; +using System.Collections.Generic; using NFluent; using WireMock.Matchers.Request; using WireMock.RequestBuilders; using Xunit; -namespace WireMock.Net.Tests.RequestBuilders +namespace WireMock.Net.Tests.RequestBuilders; + +public class RequestBuilderUsingMethodTests { - public class RequestBuilderUsingMethodTests + [Fact] + public void RequestBuilder_UsingConnect() { - [Fact] - public void RequestBuilder_UsingConnect() - { - // Act - var requestBuilder = (Request)Request.Create().UsingConnect(); + // Act + var requestBuilder = (Request)Request.Create().UsingConnect(); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("CONNECT"); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("CONNECT"); + } - [Fact] - public void RequestBuilder_UsingOptions() - { - // Act - var requestBuilder = (Request)Request.Create().UsingOptions(); + [Fact] + public void RequestBuilder_UsingOptions() + { + // Act + var requestBuilder = (Request)Request.Create().UsingOptions(); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("OPTIONS"); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("OPTIONS"); + } - [Fact] - public void RequestBuilder_UsingPatch() - { - // Act - var requestBuilder = (Request)Request.Create().UsingPatch(); + [Fact] + public void RequestBuilder_UsingPatch() + { + // Act + var requestBuilder = (Request)Request.Create().UsingPatch(); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("PATCH"); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("PATCH"); + } - [Fact] - public void RequestBuilder_UsingTrace() - { - // Act - var requestBuilder = (Request)Request.Create().UsingTrace(); + [Fact] + public void RequestBuilder_UsingTrace() + { + // Act + var requestBuilder = (Request)Request.Create().UsingTrace(); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("TRACE"); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("TRACE"); + } - [Fact] - public void RequestBuilder_UsingAnyMethod_ClearsAllOtherMatches() - { - // Assign - var requestBuilder = (Request)Request.Create().UsingGet(); + [Fact] + public void RequestBuilder_UsingAnyMethod_ClearsAllOtherMatches() + { + // Assign + var requestBuilder = (Request)Request.Create().UsingGet(); - // Assert 1 - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageMethodMatcher)); + // Assert 1 + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageMethodMatcher)); - // Act - requestBuilder.UsingAnyMethod(); + // Act + requestBuilder.UsingAnyMethod(); - // Assert 2 - matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(0); - } + // Assert 2 + matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(0); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithBodyTests.cs b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithBodyTests.cs index 08e64373..d4a7c704 100644 --- a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithBodyTests.cs +++ b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithBodyTests.cs @@ -1,4 +1,4 @@ -using FluentAssertions; +using FluentAssertions; using System.Collections.Generic; using System.Linq; using WireMock.Matchers; @@ -6,39 +6,38 @@ using WireMock.Matchers.Request; using WireMock.RequestBuilders; using Xunit; -namespace WireMock.Net.Tests.RequestBuilders +namespace WireMock.Net.Tests.RequestBuilders; + +public class RequestBuilderWithBodyTests { - public class RequestBuilderWithBodyTests + [Fact] + public void RequestBuilder_WithBody_IMatcher() { - [Fact] - public void RequestBuilder_WithBody_IMatcher() - { - // Assign - var matcher = new WildcardMatcher("x"); + // Assign + var matcher = new WildcardMatcher("x"); - // Act - var requestBuilder = (Request)Request.Create().WithBody(matcher); + // Act + var requestBuilder = (Request)Request.Create().WithBody(matcher); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - matchers.Should().HaveCount(1); - ((RequestMessageBodyMatcher)matchers[0]).Matchers.Should().Contain(matcher); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + matchers.Should().HaveCount(1); + ((RequestMessageBodyMatcher)matchers[0]).Matchers.Should().Contain(matcher); + } - [Fact] - public void RequestBuilder_WithBody_IMatchers() - { - // Assign - var matcher1 = new WildcardMatcher("x"); - var matcher2 = new WildcardMatcher("y"); + [Fact] + public void RequestBuilder_WithBody_IMatchers() + { + // Assign + var matcher1 = new WildcardMatcher("x"); + var matcher2 = new WildcardMatcher("y"); - // Act - var requestBuilder = (Request)Request.Create().WithBody(new[] { matcher1, matcher2 }.Cast().ToArray()); + // Act + var requestBuilder = (Request)Request.Create().WithBody(new[] { matcher1, matcher2 }.Cast().ToArray()); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - matchers.Should().HaveCount(1); - ((RequestMessageBodyMatcher)matchers[0]).Matchers.Should().Contain(new[] { matcher1, matcher2 }); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + matchers.Should().HaveCount(1); + ((RequestMessageBodyMatcher)matchers[0]).Matchers.Should().Contain(new[] { matcher1, matcher2 }); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithCookieTests.cs b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithCookieTests.cs index bab09dc2..d5e079b3 100644 --- a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithCookieTests.cs +++ b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithCookieTests.cs @@ -1,48 +1,47 @@ -using System.Collections.Generic; +using System.Collections.Generic; using NFluent; using WireMock.Matchers; using WireMock.Matchers.Request; using WireMock.RequestBuilders; using Xunit; -namespace WireMock.Net.Tests.RequestBuilders +namespace WireMock.Net.Tests.RequestBuilders; + +public class RequestBuilderWithCookieTests { - public class RequestBuilderWithCookieTests + [Fact] + public void RequestBuilder_WithCookie_String_String_Bool_MatchBehaviour() { - [Fact] - public void RequestBuilder_WithCookie_String_String_Bool_MatchBehaviour() - { - // Act - var requestBuilder = (Request)Request.Create().WithCookie("c", "t", true, MatchBehaviour.AcceptOnMatch); + // Act + var requestBuilder = (Request)Request.Create().WithCookie("c", "t", true, MatchBehaviour.AcceptOnMatch); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageCookieMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageCookieMatcher)); + } - [Fact] - public void RequestBuilder_WithCookie_String_IStringMatcher() - { - // Act - var requestBuilder = (Request)Request.Create().WithCookie("c", new ExactMatcher("v")); + [Fact] + public void RequestBuilder_WithCookie_String_IStringMatcher() + { + // Act + var requestBuilder = (Request)Request.Create().WithCookie("c", new ExactMatcher("v")); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageCookieMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageCookieMatcher)); + } - [Fact] - public void RequestBuilder_WithCookie_FuncIDictionary() - { - // Act - var requestBuilder = (Request)Request.Create().WithCookie((IDictionary x) => true); + [Fact] + public void RequestBuilder_WithCookie_FuncIDictionary() + { + // Act + var requestBuilder = (Request)Request.Create().WithCookie((IDictionary x) => true); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageCookieMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageCookieMatcher)); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithHeaderTests.cs b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithHeaderTests.cs index 6a3cb58e..d1ebb3e1 100644 --- a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithHeaderTests.cs +++ b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithHeaderTests.cs @@ -1,84 +1,83 @@ -using System.Collections.Generic; +using System.Collections.Generic; using NFluent; using WireMock.Matchers; using WireMock.Matchers.Request; using WireMock.RequestBuilders; using Xunit; -namespace WireMock.Net.Tests.RequestBuilders +namespace WireMock.Net.Tests.RequestBuilders; + +public class RequestBuilderWithHeaderTests { - public class RequestBuilderWithHeaderTests + [Fact] + public void RequestBuilder_WithHeader_String_String_MatchBehaviour() { - [Fact] - public void RequestBuilder_WithHeader_String_String_MatchBehaviour() - { - // Act - var requestBuilder = (Request)Request.Create().WithHeader("h", "t", MatchBehaviour.AcceptOnMatch); + // Act + var requestBuilder = (Request)Request.Create().WithHeader("h", "t", MatchBehaviour.AcceptOnMatch); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); + } - [Fact] - public void RequestBuilder_WithHeader_String_String_Bool_MatchBehaviour() - { - // Act - var requestBuilder = (Request)Request.Create().WithHeader("h", "t", true, MatchBehaviour.AcceptOnMatch); + [Fact] + public void RequestBuilder_WithHeader_String_String_Bool_MatchBehaviour() + { + // Act + var requestBuilder = (Request)Request.Create().WithHeader("h", "t", true, MatchBehaviour.AcceptOnMatch); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); + } - [Fact] - public void RequestBuilder_WithHeader_String_Strings_MatchBehaviour() - { - // Act - var requestBuilder = (Request)Request.Create().WithHeader("h", new[] { "t1", "t2" }, MatchBehaviour.AcceptOnMatch); + [Fact] + public void RequestBuilder_WithHeader_String_Strings_MatchBehaviour() + { + // Act + var requestBuilder = (Request)Request.Create().WithHeader("h", new[] { "t1", "t2" }, MatchBehaviour.AcceptOnMatch); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); + } - [Fact] - public void RequestBuilder_WithHeader_String_Strings_Bool_MatchBehaviour() - { - // Act - var requestBuilder = (Request)Request.Create().WithHeader("h", new[] { "t1", "t2" }, true, MatchBehaviour.AcceptOnMatch); + [Fact] + public void RequestBuilder_WithHeader_String_Strings_Bool_MatchBehaviour() + { + // Act + var requestBuilder = (Request)Request.Create().WithHeader("h", new[] { "t1", "t2" }, true, MatchBehaviour.AcceptOnMatch); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); + } - [Fact] - public void RequestBuilder_WithHeader_String_IStringMatcher() - { - // Act - var requestBuilder = (Request)Request.Create().WithHeader("h", new ExactMatcher("v")); + [Fact] + public void RequestBuilder_WithHeader_String_IStringMatcher() + { + // Act + var requestBuilder = (Request)Request.Create().WithHeader("h", new ExactMatcher("v")); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); + } - [Fact] - public void RequestBuilder_WithHeader_FuncIDictionary() - { - // Act - var requestBuilder = (Request)Request.Create().WithHeader(x => true); + [Fact] + public void RequestBuilder_WithHeader_FuncIDictionary() + { + // Act + var requestBuilder = (Request)Request.Create().WithHeader(x => true); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithParamTests.cs b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithParamTests.cs index 4d473084..82d7505f 100644 --- a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithParamTests.cs +++ b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithParamTests.cs @@ -1,60 +1,59 @@ -using System.Collections.Generic; +using System.Collections.Generic; using NFluent; using WireMock.Matchers; using WireMock.Matchers.Request; using WireMock.RequestBuilders; using Xunit; -namespace WireMock.Net.Tests.RequestBuilders +namespace WireMock.Net.Tests.RequestBuilders; + +public class RequestBuilderWithParamTests { - public class RequestBuilderWithParamTests + [Fact] + public void RequestBuilder_WithParam_String_MatchBehaviour() { - [Fact] - public void RequestBuilder_WithParam_String_MatchBehaviour() - { - // Act - var requestBuilder = (Request)Request.Create().WithParam("p", MatchBehaviour.AcceptOnMatch); + // Act + var requestBuilder = (Request)Request.Create().WithParam("p", MatchBehaviour.AcceptOnMatch); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher)); + } - [Fact] - public void RequestBuilder_WithParam_String_Strings() - { - // Act - var requestBuilder = (Request)Request.Create().WithParam("p", new[] { "v1", "v2" }); + [Fact] + public void RequestBuilder_WithParam_String_Strings() + { + // Act + var requestBuilder = (Request)Request.Create().WithParam("p", new[] { "v1", "v2" }); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher)); + } - [Fact] - public void RequestBuilder_WithParam_String_IStringMatcher() - { - // Act - var requestBuilder = (Request)Request.Create().WithParam("p", new RegexMatcher("[012]")); + [Fact] + public void RequestBuilder_WithParam_String_IStringMatcher() + { + // Act + var requestBuilder = (Request)Request.Create().WithParam("p", new RegexMatcher("[012]")); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher)); + } - [Fact] - public void RequestBuilder_WithParam_String_MatchBehaviour_IExactMatcher() - { - // Act - var requestBuilder = (Request)Request.Create().WithParam("p", MatchBehaviour.AcceptOnMatch, new ExactMatcher("v")); + [Fact] + public void RequestBuilder_WithParam_String_MatchBehaviour_IExactMatcher() + { + // Act + var requestBuilder = (Request)Request.Create().WithParam("p", MatchBehaviour.AcceptOnMatch, new ExactMatcher("v")); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher)); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithUrlTests.cs b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithUrlTests.cs index 33d5dc7c..f95f0329 100644 --- a/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithUrlTests.cs +++ b/test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithUrlTests.cs @@ -5,56 +5,55 @@ using WireMock.Matchers.Request; using WireMock.RequestBuilders; using Xunit; -namespace WireMock.Net.Tests.RequestBuilders +namespace WireMock.Net.Tests.RequestBuilders; + +public class RequestBuilderWithUrlTests { - public class RequestBuilderWithUrlTests + [Fact] + public void RequestBuilder_WithUrl_Strings() { - [Fact] - public void RequestBuilder_WithUrl_Strings() - { - // Act - var requestBuilder = (Request)Request.Create().WithUrl("http://a", "http://b"); + // Act + var requestBuilder = (Request)Request.Create().WithUrl("http://a", "http://b"); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher)); + } - [Fact] - public void RequestBuilder_WithUrl_MatchBehaviour_Strings() - { - // Act - var requestBuilder = (Request)Request.Create().WithUrl(MatchOperator.Or, "http://a", "http://b"); + [Fact] + public void RequestBuilder_WithUrl_MatchBehaviour_Strings() + { + // Act + var requestBuilder = (Request)Request.Create().WithUrl(MatchOperator.Or, "http://a", "http://b"); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher)); + } - [Fact] - public void RequestBuilder_WithUrl_Funcs() - { - // Act - var requestBuilder = (Request) Request.Create().WithUrl(url => true, url => false); + [Fact] + public void RequestBuilder_WithUrl_Funcs() + { + // Act + var requestBuilder = (Request) Request.Create().WithUrl(url => true, url => false); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher)); + } - [Fact] - public void RequestBuilder_WithUrl_IStringMatchers() - { - // Act - var requestBuilder = (Request) Request.Create().WithUrl(new ExactMatcher("http://a"), new ExactMatcher("http://b")); + [Fact] + public void RequestBuilder_WithUrl_IStringMatchers() + { + // Act + var requestBuilder = (Request) Request.Create().WithUrl(new ExactMatcher("http://a"), new ExactMatcher("http://b")); - // Assert - var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); - Check.That(matchers.Count).IsEqualTo(1); - Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher)); - } + // Assert + var matchers = requestBuilder.GetPrivateFieldValue>("_requestMatchers"); + Check.That(matchers.Count).IsEqualTo(1); + Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher)); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/RequestMatchers/RequestMessageCompositeMatcherTests.cs b/test/WireMock.Net.Tests/RequestMatchers/RequestMessageCompositeMatcherTests.cs index 057f7618..58037c9c 100644 --- a/test/WireMock.Net.Tests/RequestMatchers/RequestMessageCompositeMatcherTests.cs +++ b/test/WireMock.Net.Tests/RequestMatchers/RequestMessageCompositeMatcherTests.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Moq; using NFluent; @@ -6,78 +6,77 @@ using WireMock.Matchers.Request; using WireMock.Models; using Xunit; -namespace WireMock.Net.Tests.RequestMatchers +namespace WireMock.Net.Tests.RequestMatchers; + +public class RequestMessageCompositeMatcherTests { - public class RequestMessageCompositeMatcherTests + private class Helper : RequestMessageCompositeMatcher { - private class Helper : RequestMessageCompositeMatcher + public Helper(IEnumerable requestMatchers, CompositeMatcherType type = CompositeMatcherType.And) : base(requestMatchers, type) { - public Helper(IEnumerable requestMatchers, CompositeMatcherType type = CompositeMatcherType.And) : base(requestMatchers, type) - { - } - } - - [Fact] - public void RequestMessageCompositeMatcher_GetMatchingScore_EmptyArray() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1"); - var matcher = new Helper(Enumerable.Empty()); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsEqualTo(0.0d); - } - - [Fact] - public void RequestMessageCompositeMatcher_GetMatchingScore_CompositeMatcherType_And() - { - // Assign - var requestMatcher1Mock = new Mock(); - requestMatcher1Mock.Setup(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny())).Returns(1.0d); - var requestMatcher2Mock = new Mock(); - requestMatcher2Mock.Setup(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny())).Returns(0.8d); - - var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1"); - var matcher = new Helper(new[] { requestMatcher1Mock.Object, requestMatcher2Mock.Object }); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsEqualTo(0.9d); - - // Verify - requestMatcher1Mock.Verify(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny()), Times.Once); - requestMatcher2Mock.Verify(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny()), Times.Once); - } - - [Fact] - public void RequestMessageCompositeMatcher_GetMatchingScore_CompositeMatcherType_Or() - { - // Assign - var requestMatcher1Mock = new Mock(); - requestMatcher1Mock.Setup(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny())).Returns(1.0d); - var requestMatcher2Mock = new Mock(); - requestMatcher2Mock.Setup(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny())).Returns(0.8d); - - var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1"); - var matcher = new Helper(new[] { requestMatcher1Mock.Object, requestMatcher2Mock.Object }, CompositeMatcherType.Or); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsEqualTo(1.0d); - - // Verify - requestMatcher1Mock.Verify(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny()), Times.Once); - requestMatcher2Mock.Verify(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny()), Times.Once); } } -} + + [Fact] + public void RequestMessageCompositeMatcher_GetMatchingScore_EmptyArray() + { + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1"); + var matcher = new Helper(Enumerable.Empty()); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsEqualTo(0.0d); + } + + [Fact] + public void RequestMessageCompositeMatcher_GetMatchingScore_CompositeMatcherType_And() + { + // Assign + var requestMatcher1Mock = new Mock(); + requestMatcher1Mock.Setup(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny())).Returns(1.0d); + var requestMatcher2Mock = new Mock(); + requestMatcher2Mock.Setup(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny())).Returns(0.8d); + + var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1"); + var matcher = new Helper(new[] { requestMatcher1Mock.Object, requestMatcher2Mock.Object }); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsEqualTo(0.9d); + + // Verify + requestMatcher1Mock.Verify(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny()), Times.Once); + requestMatcher2Mock.Verify(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny()), Times.Once); + } + + [Fact] + public void RequestMessageCompositeMatcher_GetMatchingScore_CompositeMatcherType_Or() + { + // Assign + var requestMatcher1Mock = new Mock(); + requestMatcher1Mock.Setup(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny())).Returns(1.0d); + var requestMatcher2Mock = new Mock(); + requestMatcher2Mock.Setup(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny())).Returns(0.8d); + + var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1"); + var matcher = new Helper(new[] { requestMatcher1Mock.Object, requestMatcher2Mock.Object }, CompositeMatcherType.Or); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsEqualTo(1.0d); + + // Verify + requestMatcher1Mock.Verify(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny()), Times.Once); + requestMatcher2Mock.Verify(rm => rm.GetMatchingScore(It.IsAny(), It.IsAny()), Times.Once); + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/RequestMatchers/RequestMessageCookieMatcherTests.cs b/test/WireMock.Net.Tests/RequestMatchers/RequestMessageCookieMatcherTests.cs index 2b1767a0..85a387c6 100644 --- a/test/WireMock.Net.Tests/RequestMatchers/RequestMessageCookieMatcherTests.cs +++ b/test/WireMock.Net.Tests/RequestMatchers/RequestMessageCookieMatcherTests.cs @@ -1,154 +1,153 @@ -using System.Collections.Generic; +using System.Collections.Generic; using NFluent; using WireMock.Matchers; using WireMock.Matchers.Request; using WireMock.Models; using Xunit; -namespace WireMock.Net.Tests.RequestMatchers +namespace WireMock.Net.Tests.RequestMatchers; + +public class RequestMessageCookieMatcherTests { - public class RequestMessageCookieMatcherTests + [Fact] + public void RequestMessageCookieMatcher_GetMatchingScore_AcceptOnMatch_CookieDoesNotExists() { - [Fact] - public void RequestMessageCookieMatcher_GetMatchingScore_AcceptOnMatch_CookieDoesNotExists() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1"); - var matcher = new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, "c", false, "x"); + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1"); + var matcher = new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, "c", false, "x"); - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); - // Assert - Check.That(score).IsEqualTo(0.0d); - } + // Assert + Check.That(score).IsEqualTo(0.0d); + } - [Fact] - public void RequestMessageCookieMatcher_GetMatchingScore_RejectOnMatch_CookieDoesNotExists() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1"); - var matcher = new RequestMessageCookieMatcher(MatchBehaviour.RejectOnMatch, "c", false, "x"); + [Fact] + public void RequestMessageCookieMatcher_GetMatchingScore_RejectOnMatch_CookieDoesNotExists() + { + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1"); + var matcher = new RequestMessageCookieMatcher(MatchBehaviour.RejectOnMatch, "c", false, "x"); - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); - // Assert - Check.That(score).IsEqualTo(1.0d); - } + // Assert + Check.That(score).IsEqualTo(1.0d); + } - [Fact] - public void RequestMessageCookieMatcher_GetMatchingScore_AcceptOnMatch() - { - // Assign - var cookies = new Dictionary { { "h", "x" } }; - var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); - var matcher = new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, "h", false, "x"); + [Fact] + public void RequestMessageCookieMatcher_GetMatchingScore_AcceptOnMatch() + { + // Assign + var cookies = new Dictionary { { "h", "x" } }; + var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); + var matcher = new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, "h", false, "x"); - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); - // Assert - Check.That(score).IsEqualTo(1.0d); - } + // Assert + Check.That(score).IsEqualTo(1.0d); + } - [Fact] - public void RequestMessageCookieMatcher_GetMatchingScore_RejectOnMatch() - { - // Assign - var cookies = new Dictionary { { "h", "x" } }; - var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); - var matcher = new RequestMessageCookieMatcher(MatchBehaviour.RejectOnMatch, "h", false, "x"); + [Fact] + public void RequestMessageCookieMatcher_GetMatchingScore_RejectOnMatch() + { + // Assign + var cookies = new Dictionary { { "h", "x" } }; + var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); + var matcher = new RequestMessageCookieMatcher(MatchBehaviour.RejectOnMatch, "h", false, "x"); - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); - // Assert - Check.That(score).IsEqualTo(0.0d); - } + // Assert + Check.That(score).IsEqualTo(0.0d); + } - [Fact] - public void RequestMessageCookieMatcher_GetMatchingScore_IStringMatcher_Match() - { - // Assign - var cookies = new Dictionary { { "cook", "x" } }; - var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); - var matcher = new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, "cook", false, new ExactMatcher("x")); + [Fact] + public void RequestMessageCookieMatcher_GetMatchingScore_IStringMatcher_Match() + { + // Assign + var cookies = new Dictionary { { "cook", "x" } }; + var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); + var matcher = new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, "cook", false, new ExactMatcher("x")); - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); - // Assert - Check.That(score).IsEqualTo(1.0d); - } + // Assert + Check.That(score).IsEqualTo(1.0d); + } - [Fact] - public void RequestMessageCookieMatcher_WithMissingCookie_When_RejectOnMatch_Is_True_Should_Match() - { - // Assign - var cookies = new Dictionary { { "cook", "x" } }; - var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); - var matcher = new RequestMessageCookieMatcher(MatchBehaviour.RejectOnMatch, "uhuh", false, new ExactMatcher("x")); + [Fact] + public void RequestMessageCookieMatcher_WithMissingCookie_When_RejectOnMatch_Is_True_Should_Match() + { + // Assign + var cookies = new Dictionary { { "cook", "x" } }; + var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); + var matcher = new RequestMessageCookieMatcher(MatchBehaviour.RejectOnMatch, "uhuh", false, new ExactMatcher("x")); - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); - // Assert - Check.That(score).IsEqualTo(1.0d); - } + // Assert + Check.That(score).IsEqualTo(1.0d); + } - [Fact] - public void RequestMessageCookieMatcher_GetMatchingScore_Func_Match() - { - // Assign - var cookies = new Dictionary { { "cook", "x" } }; - var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); - var matcher = new RequestMessageCookieMatcher(x => x.ContainsKey("cook")); + [Fact] + public void RequestMessageCookieMatcher_GetMatchingScore_Func_Match() + { + // Assign + var cookies = new Dictionary { { "cook", "x" } }; + var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); + var matcher = new RequestMessageCookieMatcher(x => x.ContainsKey("cook")); - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); - // Assert - Check.That(score).IsEqualTo(1.0d); - } + // Assert + Check.That(score).IsEqualTo(1.0d); + } - [Fact] - public void RequestMessageCookieMatcher_GetMatchingScore_CaseIgnoreForCookieValue() - { - // Assign - var cookies = new Dictionary { { "cook", "teST" } }; - var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); - var matcher = new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, "cook", "test", true); + [Fact] + public void RequestMessageCookieMatcher_GetMatchingScore_CaseIgnoreForCookieValue() + { + // Assign + var cookies = new Dictionary { { "cook", "teST" } }; + var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); + var matcher = new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, "cook", "test", true); - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); - // Assert - Check.That(score).IsEqualTo(1.0d); - } + // Assert + Check.That(score).IsEqualTo(1.0d); + } - [Fact] - public void RequestMessageCookieMatcher_GetMatchingScore_CaseIgnoreForCookieName() - { - // Assign - var cookies = new Dictionary { { "cook", "teST" } }; - var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); - var matcher = new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, "CooK", "test", true); + [Fact] + public void RequestMessageCookieMatcher_GetMatchingScore_CaseIgnoreForCookieName() + { + // Assign + var cookies = new Dictionary { { "cook", "teST" } }; + var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", null, null, cookies); + var matcher = new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, "CooK", "test", true); - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); - // Assert - Check.That(score).IsEqualTo(1.0d); - } + // Assert + Check.That(score).IsEqualTo(1.0d); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/RequestMatchers/RequestMessageParamMatcherTests.cs b/test/WireMock.Net.Tests/RequestMatchers/RequestMessageParamMatcherTests.cs index 58a929b1..98a630d7 100644 --- a/test/WireMock.Net.Tests/RequestMatchers/RequestMessageParamMatcherTests.cs +++ b/test/WireMock.Net.Tests/RequestMatchers/RequestMessageParamMatcherTests.cs @@ -7,193 +7,192 @@ using WireMock.Owin; using WireMock.Types; using Xunit; -namespace WireMock.Net.Tests.RequestMatchers +namespace WireMock.Net.Tests.RequestMatchers; + +public class RequestMessageParamMatcherTests { - public class RequestMessageParamMatcherTests + [Fact] + public void RequestMessageParamMatcher_GetMatchingScore_IgnoreCaseKeyWithValuesPresentInUrl_And_With1StringValues_Returns1_0() { - [Fact] - public void RequestMessageParamMatcher_GetMatchingScore_IgnoreCaseKeyWithValuesPresentInUrl_And_With1StringValues_Returns1_0() + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1"), "GET", "127.0.0.1"); + var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "KeY", true, new[] { "test1" }); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsEqualTo(1.0d); + } + + [Fact] + public void RequestMessageParamMatcher_GetMatchingScore_KeyWith1ValuePresentInUrl_And_With2Strings_Or_Returns0_5() + { + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1"), "GET", "127.0.0.1"); + var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" }); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsEqualTo(0.5d); + } + + [Fact] + public void RequestMessageParamMatcher_GetMatchingScore_KeyWith3ValuesPresentInUrl_And_With1ExactStringWith2Patterns_Returns0_66() + { + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2,test3"), "GET", "127.0.0.1"); + var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new IStringMatcher[] { new ExactMatcher("test1", "test2") }); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsCloseTo(0.66d, 0.1d); + } + + [Fact] + public void RequestMessageParamMatcher_GetMatchingScore_KeyWith2ValuesPresentInUrl_And_With1ExactStringWith3Patterns_Returns0_66() + { + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2"), "GET", "127.0.0.1"); + var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new IStringMatcher[] { new ExactMatcher("test1", "test2", "test3") }); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsCloseTo(0.66d, 0.1d); + } + + [Fact] + public void RequestMessageParamMatcher_GetMatchingScore_KeyWith2ValuesPresentInUrl_And_With2Strings_Returns1_0() + { + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2"), "GET", "127.0.0.1"); + var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" }); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsEqualTo(1.0d); + } + + [Fact] + public void RequestMessageParamMatcher_GetMatchingScore_KeyWith2ValuesPresentInUrl_And_With2ExactStringMatchers_Returns1_0() + { + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2"), "GET", "127.0.0.1"); + var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new IStringMatcher[] { new ExactMatcher("test1"), new ExactMatcher("test2") }); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsEqualTo(1.0d); + } + + [Fact] + public void RequestMessageParamMatcher_GetMatchingScore_KeyWithValuesPresentInUrl_MatchOnKeyWithValues_PartialMatch() + { + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test0,test2"), "GET", "127.0.0.1"); + var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" }); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsEqualTo(0.5d); + } + + [Fact] + public void RequestMessageParamMatcher_GetMatchingScore_OnlyKeyPresentInUrl_MatchOnKeyWithValues_Fails() + { + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key"), "GET", "127.0.0.1"); + var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" }); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsEqualTo(0.0d); + } + + [Fact] + public void RequestMessageParamMatcher_GetMatchingScore_OnlyKeyPresentInUrl_MatchOnKey() + { + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key"), "GET", "127.0.0.1"); + var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsEqualTo(1.0d); + } + + [Fact] + public void RequestMessageParamMatcher_GetMatchingScore_OnlyKeyPresentInUrl_MatchOnKeyWithEmptyArray() + { + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key"), "GET", "127.0.0.1"); + var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new string[] { }); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsEqualTo(1.0d); + } + + [Fact] + public void RequestMessageParamMatcher_GetMatchingScore_KeyWithValuePresentInUrl_MatchOnKey() + { + // Assign + var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=frank@contoso.com"), "GET", "127.0.0.1"); + var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false); + + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); + + // Assert + Check.That(score).IsEqualTo(1.0d); + } + + // Issue #849 + [Fact] + public void RequestMessageParamMatcher_With1ParamContainingComma_Using_QueryParameterMultipleValueSupport_NoComma() + { + // Assign + var options = new WireMockMiddlewareOptions { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1"), "GET", "127.0.0.1"); - var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "KeY", true, new[] { "test1" }); + QueryParameterMultipleValueSupport = QueryParameterMultipleValueSupport.NoComma + }; + var requestMessage = new RequestMessage(options, new UrlDetails("http://localhost?query=SELECT id, value FROM table WHERE id = 1&test=42"), "GET", "127.0.0.1"); + var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "query", false, "SELECT id, value FROM table WHERE id = 1"); - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); + // Act + var result = new RequestMatchResult(); + double score = matcher.GetMatchingScore(requestMessage, result); - // Assert - Check.That(score).IsEqualTo(1.0d); - } - - [Fact] - public void RequestMessageParamMatcher_GetMatchingScore_KeyWith1ValuePresentInUrl_And_With2Strings_Or_Returns0_5() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1"), "GET", "127.0.0.1"); - var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" }); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsEqualTo(0.5d); - } - - [Fact] - public void RequestMessageParamMatcher_GetMatchingScore_KeyWith3ValuesPresentInUrl_And_With1ExactStringWith2Patterns_Returns0_66() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2,test3"), "GET", "127.0.0.1"); - var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new IStringMatcher[] { new ExactMatcher("test1", "test2") }); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsCloseTo(0.66d, 0.1d); - } - - [Fact] - public void RequestMessageParamMatcher_GetMatchingScore_KeyWith2ValuesPresentInUrl_And_With1ExactStringWith3Patterns_Returns0_66() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2"), "GET", "127.0.0.1"); - var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new IStringMatcher[] { new ExactMatcher("test1", "test2", "test3") }); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsCloseTo(0.66d, 0.1d); - } - - [Fact] - public void RequestMessageParamMatcher_GetMatchingScore_KeyWith2ValuesPresentInUrl_And_With2Strings_Returns1_0() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2"), "GET", "127.0.0.1"); - var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" }); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsEqualTo(1.0d); - } - - [Fact] - public void RequestMessageParamMatcher_GetMatchingScore_KeyWith2ValuesPresentInUrl_And_With2ExactStringMatchers_Returns1_0() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2"), "GET", "127.0.0.1"); - var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new IStringMatcher[] { new ExactMatcher("test1"), new ExactMatcher("test2") }); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsEqualTo(1.0d); - } - - [Fact] - public void RequestMessageParamMatcher_GetMatchingScore_KeyWithValuesPresentInUrl_MatchOnKeyWithValues_PartialMatch() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test0,test2"), "GET", "127.0.0.1"); - var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" }); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsEqualTo(0.5d); - } - - [Fact] - public void RequestMessageParamMatcher_GetMatchingScore_OnlyKeyPresentInUrl_MatchOnKeyWithValues_Fails() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key"), "GET", "127.0.0.1"); - var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" }); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsEqualTo(0.0d); - } - - [Fact] - public void RequestMessageParamMatcher_GetMatchingScore_OnlyKeyPresentInUrl_MatchOnKey() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key"), "GET", "127.0.0.1"); - var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsEqualTo(1.0d); - } - - [Fact] - public void RequestMessageParamMatcher_GetMatchingScore_OnlyKeyPresentInUrl_MatchOnKeyWithEmptyArray() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key"), "GET", "127.0.0.1"); - var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new string[] { }); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsEqualTo(1.0d); - } - - [Fact] - public void RequestMessageParamMatcher_GetMatchingScore_KeyWithValuePresentInUrl_MatchOnKey() - { - // Assign - var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=frank@contoso.com"), "GET", "127.0.0.1"); - var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - Check.That(score).IsEqualTo(1.0d); - } - - // Issue #849 - [Fact] - public void RequestMessageParamMatcher_With1ParamContainingComma_Using_QueryParameterMultipleValueSupport_NoComma() - { - // Assign - var options = new WireMockMiddlewareOptions - { - QueryParameterMultipleValueSupport = QueryParameterMultipleValueSupport.NoComma - }; - var requestMessage = new RequestMessage(options, new UrlDetails("http://localhost?query=SELECT id, value FROM table WHERE id = 1&test=42"), "GET", "127.0.0.1"); - var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "query", false, "SELECT id, value FROM table WHERE id = 1"); - - // Act - var result = new RequestMatchResult(); - double score = matcher.GetMatchingScore(requestMessage, result); - - // Assert - score.Should().Be(1.0); - } + // Assert + score.Should().Be(1.0); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_BodyTypeBytes.verified.txt b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_BodyTypeBytes.verified.txt new file mode 100644 index 00000000..f6cd9dbc --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_BodyTypeBytes.verified.txt @@ -0,0 +1,16 @@ +{ + Request: { + ClientIP: ::1, + Path: /, + AbsolutePath: /, + Url: http://localhost/, + AbsoluteUrl: http://localhost/, + Method: post, + BodyAsBytes: AA==, + DetectedBodyType: Bytes + }, + Response: { + BodyAsBytes: AA==, + DetectedBodyType: Bytes + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_ResponseBodyTypeFile.verified.txt b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_ResponseBodyTypeFile.verified.txt new file mode 100644 index 00000000..188dffb8 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_ResponseBodyTypeFile.verified.txt @@ -0,0 +1,14 @@ +{ + Request: { + ClientIP: ::1, + Path: /, + AbsolutePath: /, + Url: http://localhost/, + AbsoluteUrl: http://localhost/, + Method: get + }, + Response: { + BodyAsFile: test, + DetectedBodyType: File + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WhenFuncIsUsed_And_DoNotSaveDynamicResponseInLogEntry_Is_True_Should_NotSave_StringResponse.verified.txt b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WhenFuncIsUsed_And_DoNotSaveDynamicResponseInLogEntry_Is_True_Should_NotSave_StringResponse.verified.txt new file mode 100644 index 00000000..445dde15 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WhenFuncIsUsed_And_DoNotSaveDynamicResponseInLogEntry_Is_True_Should_NotSave_StringResponse.verified.txt @@ -0,0 +1,16 @@ +{ + Request: { + ClientIP: ::1, + Path: /, + AbsolutePath: /, + Url: http://localhost/, + AbsoluteUrl: http://localhost/, + Method: post, + BodyAsBytes: AA==, + DetectedBodyType: Bytes + }, + Response: { + Body: Func, + DetectedBodyType: String + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WithFault.verified.txt b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WithFault.verified.txt new file mode 100644 index 00000000..e658eed8 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WithFault.verified.txt @@ -0,0 +1,16 @@ +{ + Request: { + ClientIP: ::1, + Path: /, + AbsolutePath: /, + Url: http://localhost/, + AbsoluteUrl: http://localhost/, + Method: get + }, + Response: { + BodyAsFile: test, + DetectedBodyType: File, + FaultType: EMPTY_RESPONSE, + FaultPercentage: 0.5 + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.cs b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.cs index 76b46e99..b083fb12 100644 --- a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.cs +++ b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.cs @@ -1,7 +1,10 @@ -using FluentAssertions; -using NFluent; +#if !(NET452 || NET461) +using System.Threading.Tasks; +using VerifyTests; +using VerifyXunit; using WireMock.Logging; using WireMock.Models; +using WireMock.Net.Tests.VerifyExtensions; using WireMock.Owin; using WireMock.ResponseBuilders; using WireMock.Serialization; @@ -11,8 +14,15 @@ using Xunit; namespace WireMock.Net.Tests.Serialization; +[UsesVerify] public class LogEntryMapperTests { + private static readonly VerifySettings VerifySettings = new(); + static LogEntryMapperTests() + { + VerifySettings.Init(); + } + private readonly IWireMockMiddlewareOptions _options = new WireMockMiddlewareOptions(); private readonly LogEntryMapper _sut; @@ -23,7 +33,7 @@ public class LogEntryMapperTests } [Fact] - public void LogEntryMapper_Map_LogEntry_Check_BodyTypeBytes() + public Task LogEntryMapper_Map_LogEntry_Check_BodyTypeBytes() { // Assign var logEntry = new LogEntry @@ -51,23 +61,12 @@ public class LogEntryMapperTests // Act var result = _sut.Map(logEntry); - // Assert - Check.That(result.Request.DetectedBodyType).IsEqualTo("Bytes"); - Check.That(result.Request.DetectedBodyTypeFromContentType).IsNull(); - Check.That(result.Request.BodyAsBytes).ContainsExactly(new byte[] { 0 }); - Check.That(result.Request.Body).IsNull(); - Check.That(result.Request.BodyAsJson).IsNull(); - - Check.That(result.Response.DetectedBodyType).IsEqualTo(BodyType.Bytes); - Check.That(result.Response.DetectedBodyTypeFromContentType).IsNull(); - Check.That(result.Response.BodyAsBytes).ContainsExactly(new byte[] { 0 }); - Check.That(result.Response.Body).IsNull(); - Check.That(result.Response.BodyAsJson).IsNull(); - Check.That(result.Response.BodyAsFile).IsNull(); + // Verify + return Verifier.Verify(result, VerifySettings); } [Fact] - public void LogEntryMapper_Map_LogEntry_Check_ResponseBodyTypeFile() + public Task LogEntryMapper_Map_LogEntry_Check_ResponseBodyTypeFile() { // Assign var logEntry = new LogEntry @@ -86,23 +85,12 @@ public class LogEntryMapperTests // Act var result = _sut.Map(logEntry); - // Assert - Check.That(result.Request.DetectedBodyType).IsNull(); - Check.That(result.Request.DetectedBodyTypeFromContentType).IsNull(); - Check.That(result.Request.BodyAsBytes).IsNull(); - Check.That(result.Request.Body).IsNull(); - Check.That(result.Request.BodyAsJson).IsNull(); - - Check.That(result.Response.DetectedBodyType).IsEqualTo(BodyType.File); - Check.That(result.Response.DetectedBodyTypeFromContentType).IsNull(); - Check.That(result.Request.BodyAsBytes).IsNull(); - Check.That(result.Response.Body).IsNull(); - Check.That(result.Response.BodyAsJson).IsNull(); - Check.That(result.Response.BodyAsFile).IsEqualTo("test"); + // Verify + return Verifier.Verify(result, VerifySettings); } [Fact] - public void LogEntryMapper_Map_LogEntry_WithFault() + public Task LogEntryMapper_Map_LogEntry_WithFault() { // Assign var logEntry = new LogEntry @@ -123,13 +111,12 @@ public class LogEntryMapperTests // Act var result = _sut.Map(logEntry); - // Assert - result.Response.FaultType.Should().Be("EMPTY_RESPONSE"); - result.Response.FaultPercentage.Should().Be(0.5); + // Verify + return Verifier.Verify(result, VerifySettings); } [Fact] - public void LogEntryMapper_Map_LogEntry_WhenFuncIsUsed_And_DoNotSaveDynamicResponseInLogEntry_Is_True_Should_NotSave_StringResponse() + public Task LogEntryMapper_Map_LogEntry_WhenFuncIsUsed_And_DoNotSaveDynamicResponseInLogEntry_Is_True_Should_NotSave_StringResponse() { // Assign var options = new WireMockMiddlewareOptions @@ -163,7 +150,8 @@ public class LogEntryMapperTests // Act var result = new LogEntryMapper(options).Map(logEntry); - // Assert - result.Response.Body.Should().Be(isFuncUsed); + // Verify + return Verifier.Verify(result, VerifySettings); } -} \ No newline at end of file +} +#endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode.cs b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode.cs new file mode 100644 index 00000000..0966c926 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode.cs @@ -0,0 +1,127 @@ +#if !(NET452 || NET461 || NETCOREAPP3_1) +using System; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using FluentAssertions; +using VerifyTests; +using VerifyXunit; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; +using WireMock.Serialization; +using WireMock.Types; +using Xunit; + +namespace WireMock.Net.Tests.Serialization; + +[UsesVerify] +public partial class MappingConverterTests +{ + + [ModuleInitializer] + public static void ModuleInitializer() + { + VerifierSettings.DontScrubGuids(); + VerifierSettings.DontScrubDateTimes(); + } + + [Fact] + public Task ToCSharpCode_With_Builder_And_AddStartIsTrue() + { + // Assign + var mapping = CreateMapping(); + + // Act + var code = _sut.ToCSharpCode(mapping, new MappingConverterSettings + { + AddStart = true, + ConverterType = MappingConverterType.Builder + }); + + // Assert + code.Should().NotBeEmpty(); + + // Verify + return Verifier.Verify(code); + } + + [Fact] + public Task ToCSharpCode_With_Builder_And_AddStartIsFalse() + { + // Assign + var mapping = CreateMapping(); + + // Act + var code = _sut.ToCSharpCode(mapping, new MappingConverterSettings + { + AddStart = false, + ConverterType = MappingConverterType.Builder + }); + + // Assert + code.Should().NotBeEmpty(); + + // Verify + return Verifier.Verify(code); + } + + [Fact] + public Task ToCSharpCode_With_Server_And_AddStartIsTrue() + { + // Assign + var mapping = CreateMapping(); + + // Act + var code = _sut.ToCSharpCode(mapping, new MappingConverterSettings + { + AddStart = true, + ConverterType = MappingConverterType.Server + }); + + // Assert + code.Should().NotBeEmpty(); + + // Verify + return Verifier.Verify(code); + } + + [Fact] + public Task ToCSharpCode_With_Server_And_AddStartIsFalse() + { + // Assign + var mapping = CreateMapping(); + + // Act + var code = _sut.ToCSharpCode(mapping, new MappingConverterSettings + { + AddStart = false, + ConverterType = MappingConverterType.Server + }); + + // Assert + code.Should().NotBeEmpty(); + + // Verify + return Verifier.Verify(code); + } + + private Mapping CreateMapping() + { + var guid = new Guid("8e7b9ab7-e18e-4502-8bc9-11e6679811cc"); + var request = Request.Create() + .UsingGet() + .WithPath("test_path") + .WithParam("q", "42") + .WithClientIP("112.123.100.99") + .WithHeader("h-key", "h-value") + .WithCookie("c-key", "c-value") + .WithBody("b"); + var response = Response.Create() + .WithHeader("Keep-Alive", "test") + .WithBody("bbb") + .WithDelay(12345) + .WithTransformer(); + + return new Mapping(guid, _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null); + } +} +#endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode_With_Builder_And_AddStartIsFalse.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode_With_Builder_And_AddStartIsFalse.verified.txt new file mode 100644 index 00000000..19739c17 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode_With_Builder_And_AddStartIsFalse.verified.txt @@ -0,0 +1,17 @@ +builder + .Given(Request.Create() + .UsingMethod("GET") + .WithPath("test_path") + .WithParam("q", "42") + .WithClientIP("112.123.100.99") + .WithHeader("h-key", "h-value", true) + .WithCookie("c-key", "c-value", true) + .WithBody("b") + ) + .WithGuid("8e7b9ab7-e18e-4502-8bc9-11e6679811cc") + .RespondWith(Response.Create() + .WithHeader("Keep-Alive)", "test") + .WithBody("bbb") + .WithDelay(12345) + .WithTransformer() + ); diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode_With_Builder_And_AddStartIsTrue.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode_With_Builder_And_AddStartIsTrue.verified.txt new file mode 100644 index 00000000..95b1a6c4 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode_With_Builder_And_AddStartIsTrue.verified.txt @@ -0,0 +1,18 @@ +var builder = new MappingBuilder(); +builder + .Given(Request.Create() + .UsingMethod("GET") + .WithPath("test_path") + .WithParam("q", "42") + .WithClientIP("112.123.100.99") + .WithHeader("h-key", "h-value", true) + .WithCookie("c-key", "c-value", true) + .WithBody("b") + ) + .WithGuid("8e7b9ab7-e18e-4502-8bc9-11e6679811cc") + .RespondWith(Response.Create() + .WithHeader("Keep-Alive)", "test") + .WithBody("bbb") + .WithDelay(12345) + .WithTransformer() + ); diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode_With_Server_And_AddStartIsFalse.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode_With_Server_And_AddStartIsFalse.verified.txt new file mode 100644 index 00000000..779a9172 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode_With_Server_And_AddStartIsFalse.verified.txt @@ -0,0 +1,17 @@ +server + .Given(Request.Create() + .UsingMethod("GET") + .WithPath("test_path") + .WithParam("q", "42") + .WithClientIP("112.123.100.99") + .WithHeader("h-key", "h-value", true) + .WithCookie("c-key", "c-value", true) + .WithBody("b") + ) + .WithGuid("8e7b9ab7-e18e-4502-8bc9-11e6679811cc") + .RespondWith(Response.Create() + .WithHeader("Keep-Alive)", "test") + .WithBody("bbb") + .WithDelay(12345) + .WithTransformer() + ); diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode_With_Server_And_AddStartIsTrue.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode_With_Server_And_AddStartIsTrue.verified.txt new file mode 100644 index 00000000..894a8860 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode_With_Server_And_AddStartIsTrue.verified.txt @@ -0,0 +1,18 @@ +var server = WireMockServer.Start(); +server + .Given(Request.Create() + .UsingMethod("GET") + .WithPath("test_path") + .WithParam("q", "42") + .WithClientIP("112.123.100.99") + .WithHeader("h-key", "h-value", true) + .WithCookie("c-key", "c-value", true) + .WithBody("b") + ) + .WithGuid("8e7b9ab7-e18e-4502-8bc9-11e6679811cc") + .RespondWith(Response.Create() + .WithHeader("Keep-Alive)", "test") + .WithBody("bbb") + .WithDelay(12345) + .WithTransformer() + ); diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel.verified.txt new file mode 100644 index 00000000..fe4b89ea --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel.verified.txt @@ -0,0 +1,12 @@ +{ + Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, + UpdatedAt: 2022-12-04 11:12:13, + Title: , + Description: , + Priority: 42, + Request: {}, + Response: { + Delay: 1000 + }, + UseWebhooksFireAndForget: false +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithPriority_ReturnsPriority.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithPriority_ReturnsPriority.verified.txt new file mode 100644 index 00000000..0a6b8bac --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithPriority_ReturnsPriority.verified.txt @@ -0,0 +1,17 @@ +{ + Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, + UpdatedAt: 2022-12-04 11:12:13, + Title: , + Description: , + Priority: 42, + Request: {}, + Response: { + BodyAsJson: { + x: x + }, + UseTransformer: true, + TransformerType: Handlebars, + TransformerReplaceNodeOptions: Evaluate + }, + UseWebhooksFireAndForget: false +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomDelay_ReturnsCorrectModel.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomDelay_ReturnsCorrectModel.verified.txt new file mode 100644 index 00000000..8c26e558 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomDelay_ReturnsCorrectModel.verified.txt @@ -0,0 +1,13 @@ +{ + Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, + UpdatedAt: 2022-12-04 11:12:13, + Title: , + Description: , + Priority: 42, + Request: {}, + Response: { + MinimumRandomDelay: 1000, + MaximumRandomDelay: 2000 + }, + UseWebhooksFireAndForget: false +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel.verified.txt new file mode 100644 index 00000000..4d78b3cc --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel.verified.txt @@ -0,0 +1,13 @@ +{ + Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, + UpdatedAt: 2022-12-04 11:12:13, + Title: , + Description: , + Priority: 42, + Request: {}, + Response: { + MinimumRandomDelay: 1000, + MaximumRandomDelay: 60000 + }, + UseWebhooksFireAndForget: false +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings.verified.txt new file mode 100644 index 00000000..cec4691f --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings.verified.txt @@ -0,0 +1,15 @@ +{ + Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, + UpdatedAt: 2022-12-04 11:12:13, + TimeSettings: { + Start: 2023-01-14 15:16:17, + End: 2023-01-14 15:17:57, + TTL: 100 + }, + Title: , + Description: , + Priority: 42, + Request: {}, + Response: {}, + UseWebhooksFireAndForget: false +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel.verified.txt new file mode 100644 index 00000000..08cd7116 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel.verified.txt @@ -0,0 +1,9 @@ +{ + Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, + UpdatedAt: 2022-12-04 11:12:13, + Title: my-title, + Description: my-description, + Request: {}, + Response: {}, + UseWebhooksFireAndForget: false +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_MultipleWebHooks.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_MultipleWebHooks.verified.txt new file mode 100644 index 00000000..a7b1ca9f --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_MultipleWebHooks.verified.txt @@ -0,0 +1,34 @@ +{ + Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, + UpdatedAt: 2022-12-04 11:12:13, + Title: , + Description: , + Request: {}, + Response: {}, + Webhooks: [ + { + Request: { + Url: https://test1.com, + Method: post, + Headers: { + One: x + }, + Body: 1, + TransformerReplaceNodeOptions: EvaluateAndTryToConvert + } + }, + { + Request: { + Url: https://test2.com, + Method: post, + Headers: { + First: x, + Second: a, b + }, + Body: 2, + TransformerReplaceNodeOptions: EvaluateAndTryToConvert + } + } + ], + UseWebhooksFireAndForget: true +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_SingleWebHook.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_SingleWebHook.verified.txt new file mode 100644 index 00000000..d721319a --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_SingleWebHook.verified.txt @@ -0,0 +1,21 @@ +{ + Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, + UpdatedAt: 2022-12-04 11:12:13, + Title: , + Description: , + Request: {}, + Response: {}, + Webhook: { + Request: { + Url: https://test.com, + Method: post, + Headers: { + Multi: a, b, + Single: x + }, + Body: b, + TransformerReplaceNodeOptions: EvaluateAndTryToConvert + } + }, + UseWebhooksFireAndForget: false +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.cs b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.cs index a765f7ac..2c077eb8 100644 --- a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.cs +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.cs @@ -1,7 +1,12 @@ +#if !(NET452 || NET461 || NETCOREAPP3_1) using System; using System.Collections.Generic; +using System.Runtime.CompilerServices; using System.Threading; +using System.Threading.Tasks; using FluentAssertions; +using VerifyTests; +using VerifyXunit; using WireMock.Models; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; @@ -13,9 +18,10 @@ using Xunit; namespace WireMock.Net.Tests.Serialization; -public class MappingConverterTests +public partial class MappingConverterTests { - private readonly DateTime _updatedAt = new(2022, 12, 4); + private readonly Guid _guid = new("c8eeaf99-d5c4-4341-8543-4597c3fd40d9"); + private readonly DateTime _updatedAt = new(2022, 12, 4, 11, 12, 13); private readonly WireMockServerSettings _settings = new(); private readonly MappingConverter _sut; @@ -26,7 +32,7 @@ public class MappingConverterTests } [Fact] - public void ToMappingModel_With_SingleWebHook() + public Task ToMappingModel_With_SingleWebHook() { // Assign var request = Request.Create(); @@ -53,7 +59,7 @@ public class MappingConverterTests } } }; - var mapping = new Mapping(Guid.NewGuid(), _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 0, null, null, null, null, webhooks, false, null); + var mapping = new Mapping(_guid, _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 0, null, null, null, null, webhooks, false, null); // Act var model = _sut.ToMappingModel(mapping); @@ -74,10 +80,13 @@ public class MappingConverterTests model.Webhook.Request.Headers.Should().HaveCount(2); model.Webhook.Request.Body.Should().Be("b"); model.Webhook.Request.BodyAsJson.Should().BeNull(); + + // Verify + return Verifier.Verify(model); } [Fact] - public void ToMappingModel_With_MultipleWebHooks() + public Task ToMappingModel_With_MultipleWebHooks() { // Assign var request = Request.Create(); @@ -123,7 +132,7 @@ public class MappingConverterTests } } }; - var mapping = new Mapping(Guid.NewGuid(), _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 0, null, null, null, null, webhooks, true, null); + var mapping = new Mapping(_guid, _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 0, null, null, null, null, webhooks, true, null); // Act var model = _sut.ToMappingModel(mapping); @@ -148,17 +157,20 @@ public class MappingConverterTests model.Webhooks[1].Request.Url.Should().Be("https://test2.com"); model.Webhooks[1].Request.Headers.Should().HaveCount(2); model.Webhooks[1].Request.Body.Should().Be("2"); + + // Verify + return Verifier.Verify(model); } [Fact] - public void ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel() + public Task ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel() { // Assign var title = "my-title"; var description = "my-description"; var request = Request.Create(); var response = Response.Create(); - var mapping = new Mapping(Guid.NewGuid(), _updatedAt, title, description, null, _settings, request, response, 0, null, null, null, null, null, false, null); + var mapping = new Mapping(_guid, _updatedAt, title, description, null, _settings, request, response, 0, null, null, null, null, null, false, null); // Act var model = _sut.ToMappingModel(mapping); @@ -167,15 +179,18 @@ public class MappingConverterTests model.Should().NotBeNull(); model.Title.Should().Be(title); model.Description.Should().Be(description); + + // Verify + return Verifier.Verify(model); } [Fact] - public void ToMappingModel_WithPriority_ReturnsPriority() + public Task ToMappingModel_WithPriority_ReturnsPriority() { // Assign var request = Request.Create(); var response = Response.Create().WithBodyAsJson(new { x = "x" }).WithTransformer(); - var mapping = new Mapping(Guid.NewGuid(), _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null); + var mapping = new Mapping(_guid, _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null); // Act var model = _sut.ToMappingModel(mapping); @@ -184,13 +199,16 @@ public class MappingConverterTests model.Should().NotBeNull(); model.Priority.Should().Be(42); model.Response.UseTransformer.Should().BeTrue(); + + // Verify + return Verifier.Verify(model); } [Fact] - public void ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings() + public Task ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings() { // Assign - var start = DateTime.Now; + var start = new DateTime(2023, 1, 14, 15, 16, 17); var ttl = 100; var end = start.AddSeconds(ttl); var request = Request.Create(); @@ -201,7 +219,7 @@ public class MappingConverterTests End = end, TTL = ttl }; - var mapping = new Mapping(Guid.NewGuid(), _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, timeSettings); + var mapping = new Mapping(_guid, _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, timeSettings); // Act var model = _sut.ToMappingModel(mapping); @@ -212,6 +230,9 @@ public class MappingConverterTests model.TimeSettings!.Start.Should().Be(start); model.TimeSettings.End.Should().Be(end); model.TimeSettings.TTL.Should().Be(ttl); + + // Verify + return Verifier.Verify(model); } [Fact] @@ -241,13 +262,13 @@ public class MappingConverterTests } [Fact] - public void ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel() + public Task ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel() { // Assign var delay = 1000; var request = Request.Create(); var response = Response.Create().WithDelay(delay); - var mapping = new Mapping(Guid.NewGuid(), _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null); + var mapping = new Mapping(_guid, _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null); // Act var model = _sut.ToMappingModel(mapping); @@ -255,16 +276,19 @@ public class MappingConverterTests // Assert model.Should().NotBeNull(); model.Response.Delay.Should().Be(delay); + + // Verify + return Verifier.Verify(model); } [Fact] - public void ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel() + public Task ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel() { // Assign int minimumDelay = 1000; var request = Request.Create(); var response = Response.Create().WithRandomDelay(minimumDelay); - var mapping = new Mapping(Guid.NewGuid(), _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null); + var mapping = new Mapping(_guid, _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null); // Act var model = _sut.ToMappingModel(mapping); @@ -274,17 +298,20 @@ public class MappingConverterTests model.Response.Delay.Should().BeNull(); model.Response.MinimumRandomDelay.Should().Be(minimumDelay); model.Response.MaximumRandomDelay.Should().Be(60_000); + + // Verify + return Verifier.Verify(model); } [Fact] - public void ToMappingModel_WithRandomDelay_ReturnsCorrectModel() + public Task ToMappingModel_WithRandomDelay_ReturnsCorrectModel() { // Assign int minimumDelay = 1000; int maximumDelay = 2000; var request = Request.Create(); var response = Response.Create().WithRandomDelay(minimumDelay, maximumDelay); - var mapping = new Mapping(Guid.NewGuid(), _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null); + var mapping = new Mapping(_guid, _updatedAt, string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null); // Act var model = _sut.ToMappingModel(mapping); @@ -294,5 +321,9 @@ public class MappingConverterTests model.Response.Delay.Should().BeNull(); model.Response.MinimumRandomDelay.Should().Be(minimumDelay); model.Response.MaximumRandomDelay.Should().Be(maximumDelay); + + // Verify + return Verifier.Verify(model); } -} \ No newline at end of file +} +#endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.ToMapping_UseDefinedRequestMatchers_True.verified.txt b/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.ToMapping_UseDefinedRequestMatchers_True.verified.txt new file mode 100644 index 00000000..eacb131b --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.ToMapping_UseDefinedRequestMatchers_True.verified.txt @@ -0,0 +1,75 @@ +{ + Guid: ff55ac0a-fea9-4d7b-be74-5e483a2c1305, + UpdatedAt: 2022-12-04, + Title: my title, + Description: my description, + Priority: -2000000, + Request: { + Path: { + Matchers: [ + { + Name: WildcardMatcher, + Pattern: x, + IgnoreCase: false + } + ] + }, + Methods: [ + POST + ], + Headers: [ + { + Name: Content-Type, + Matchers: [ + { + Name: ContentTypeMatcher, + Pattern: text/plain, + IgnoreCase: false + } + ] + } + ], + Cookies: [ + { + Name: c, + Matchers: [ + { + Name: WildcardMatcher, + Pattern: x, + IgnoreCase: true + } + ] + } + ], + Params: [ + { + Name: p1, + Matchers: [ + { + Name: ExactMatcher, + Pattern: p1-v, + IgnoreCase: false + } + ] + }, + { + Name: p2, + Matchers: [ + { + Name: ExactMatcher, + Pattern: p2-v, + IgnoreCase: false + } + ] + } + ], + Body: { + Matcher: { + Name: RegexMatcher, + Pattern: Auth, + IgnoreCase: false + } + } + }, + Response: {} +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.cs b/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.cs index 6f85a98b..58dcb1b9 100644 --- a/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.cs +++ b/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.cs @@ -1,8 +1,10 @@ +#if !(NET452 || NET461 || NETCOREAPP3_1) using System; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; using Moq; -using Newtonsoft.Json; -using System.IO; -using FluentAssertions; +using VerifyTests; +using VerifyXunit; using WireMock.Matchers; using WireMock.RequestBuilders; using WireMock.Serialization; @@ -12,6 +14,7 @@ using Xunit; namespace WireMock.Net.Tests.Serialization; +[UsesVerify] public class ProxyMappingConverterTests { private readonly WireMockServerSettings _settings = new(); @@ -33,8 +36,15 @@ public class ProxyMappingConverterTests _sut = new ProxyMappingConverter(_settings, guidUtilsMock.Object, dateTimeUtilsMock.Object); } + [ModuleInitializer] + public static void ModuleInitializer() + { + VerifierSettings.DontScrubGuids(); + VerifierSettings.DontScrubDateTimes(); + } + [Fact] - public void ToMapping_UseDefinedRequestMatchers_True() + public Task ToMapping_UseDefinedRequestMatchers_True() { // Arrange var proxyAndRecordSettings = new ProxyAndRecordSettings @@ -49,7 +59,7 @@ public class ProxyMappingConverterTests .WithParam("p2", "p2-v") .WithHeader("Content-Type", new ContentTypeMatcher("text/plain")) .WithCookie("c", "x") - .WithBody(new RegexMatcher("AuthAuth")); var mappingMock = new Mock(); mappingMock.SetupGet(m => m.RequestMatcher).Returns(request); @@ -65,9 +75,9 @@ public class ProxyMappingConverterTests // Assert var model = _mappingConverter.ToMappingModel(proxyMapping); - var json = JsonConvert.SerializeObject(model, JsonSerializationConstants.JsonSerializerSettingsDefault); - var expected = File.ReadAllText(Path.Combine("../../../", "Serialization", "files", "proxy.json")); - json.Should().Be(expected); + // Verify + return Verifier.Verify(model); } -} \ No newline at end of file +} +#endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.WebhookMapper_Map_WebhookModel_BodyAsJson.verified.txt b/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.WebhookMapper_Map_WebhookModel_BodyAsJson.verified.txt new file mode 100644 index 00000000..89d05413 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.WebhookMapper_Map_WebhookModel_BodyAsJson.verified.txt @@ -0,0 +1,21 @@ +{ + Request: { + Url: https://localhost, + Method: get, + Headers: { + x: [ + y + ] + }, + BodyData: { + BodyAsJson: { + n: 12345 + }, + DetectedBodyType: Json, + DetectedBodyTypeFromContentType: Bytes + }, + Delay: 4, + MinimumRandomDelay: 5, + MaximumRandomDelay: 6 + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsFalse.verified.txt b/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsFalse.verified.txt new file mode 100644 index 00000000..ef76076f --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsFalse.verified.txt @@ -0,0 +1,16 @@ +{ + Request: { + Url: https://localhost, + Method: get, + Headers: { + x: [ + y + ] + }, + BodyData: { + BodyAsString: test, + DetectedBodyType: String, + DetectedBodyTypeFromContentType: Bytes + } + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsTrue.verified.txt b/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsTrue.verified.txt new file mode 100644 index 00000000..a0537232 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsTrue.verified.txt @@ -0,0 +1,18 @@ +{ + Request: { + Url: https://localhost, + Method: get, + Headers: { + x: [ + y + ] + }, + BodyData: { + BodyAsString: test, + DetectedBodyType: String, + DetectedBodyTypeFromContentType: Bytes + }, + UseTransformer: true, + TransformerReplaceNodeOptions: Evaluate + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.WebhookMapper_Map_Webhook_To_Model.verified.txt b/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.WebhookMapper_Map_Webhook_To_Model.verified.txt new file mode 100644 index 00000000..2eec042c --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.WebhookMapper_Map_Webhook_To_Model.verified.txt @@ -0,0 +1,16 @@ +{ + Request: { + Url: https://localhost, + Method: get, + Headers: { + x: y + }, + BodyAsJson: { + n: 12345 + }, + TransformerReplaceNodeOptions: EvaluateAndTryToConvert, + Delay: 4, + MinimumRandomDelay: 5, + MaximumRandomDelay: 6 + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.cs b/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.cs index 54d35956..26cd8d52 100644 --- a/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.cs +++ b/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.cs @@ -1,5 +1,9 @@ +#if !(NET452 || NET461 || NETCOREAPP3_1) using System.Collections.Generic; -using FluentAssertions; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using VerifyTests; +using VerifyXunit; using WireMock.Admin.Mappings; using WireMock.Models; using WireMock.Serialization; @@ -9,10 +13,18 @@ using Xunit; namespace WireMock.Net.Tests.Serialization; +[UsesVerify] public class WebhookMapperTests { + [ModuleInitializer] + public static void ModuleInitializer() + { + VerifierSettings.DontScrubGuids(); + VerifierSettings.DontScrubDateTimes(); + } + [Fact] - public void WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsFalse() + public Task WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsFalse() { // Assign var model = new WebhookModel @@ -32,17 +44,12 @@ public class WebhookMapperTests var result = WebhookMapper.Map(model); - result.Request.Url.Should().Be("https://localhost"); - result.Request.Method.Should().Be("get"); - result.Request.Headers.Should().HaveCount(1); - result.Request.BodyData!.BodyAsJson.Should().BeNull(); - result.Request.BodyData.BodyAsString.Should().Be("test"); - result.Request.BodyData.DetectedBodyType.Should().Be(BodyType.String); - result.Request.UseTransformer.Should().BeNull(); + // Verify + return Verifier.Verify(result); } [Fact] - public void WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsTrue() + public Task WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsTrue() { // Assign var model = new WebhookModel @@ -62,18 +69,12 @@ public class WebhookMapperTests var result = WebhookMapper.Map(model); - result.Request.Url.Should().Be("https://localhost"); - result.Request.Method.Should().Be("get"); - result.Request.Headers.Should().HaveCount(1); - result.Request.BodyData!.BodyAsJson.Should().BeNull(); - result.Request.BodyData.BodyAsString.Should().Be("test"); - result.Request.BodyData.DetectedBodyType.Should().Be(BodyType.String); - result.Request.UseTransformer.Should().BeTrue(); - result.Request.TransformerType.Should().Be(TransformerType.Handlebars); + // Verify + return Verifier.Verify(result); } [Fact] - public void WebhookMapper_Map_WebhookModel_BodyAsJson() + public Task WebhookMapper_Map_WebhookModel_BodyAsJson() { // Assign var model = new WebhookModel @@ -95,19 +96,12 @@ public class WebhookMapperTests var result = WebhookMapper.Map(model); - result.Request.Url.Should().Be("https://localhost"); - result.Request.Method.Should().Be("get"); - result.Request.Headers.Should().HaveCount(1); - result.Request.BodyData!.BodyAsString.Should().BeNull(); - result.Request.BodyData.BodyAsJson.Should().NotBeNull(); - result.Request.BodyData.DetectedBodyType.Should().Be(BodyType.Json); - result.Request.Delay.Should().Be(4); - result.Request.MinimumRandomDelay.Should().Be(5); - result.Request.MaximumRandomDelay.Should().Be(6); + // Verify + return Verifier.Verify(result); } [Fact] - public void WebhookMapper_Map_Webhook_To_Model() + public Task WebhookMapper_Map_Webhook_To_Model() { // Assign var webhook = new Webhook @@ -134,12 +128,8 @@ public class WebhookMapperTests var result = WebhookMapper.Map(webhook); - result.Request.Url.Should().Be("https://localhost"); - result.Request.Method.Should().Be("get"); - result.Request.Headers.Should().HaveCount(1); - result.Request.BodyAsJson.Should().NotBeNull(); - result.Request.Delay.Should().Be(4); - result.Request.MinimumRandomDelay.Should().Be(5); - result.Request.MaximumRandomDelay.Should().Be(6); + // Verify + return Verifier.Verify(result); } -} \ No newline at end of file +} +#endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/files/proxy.json b/test/WireMock.Net.Tests/Serialization/files/proxy.json deleted file mode 100644 index e7703f65..00000000 --- a/test/WireMock.Net.Tests/Serialization/files/proxy.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "Guid": "ff55ac0a-fea9-4d7b-be74-5e483a2c1305", - "UpdatedAt": "2022-12-04T00:00:00", - "Title": "my title", - "Description": "my description", - "Priority": -2000000, - "Request": { - "Path": { - "Matchers": [ - { - "Name": "WildcardMatcher", - "Pattern": "x", - "IgnoreCase": false - } - ] - }, - "Methods": [ - "POST" - ], - "Headers": [ - { - "Name": "Content-Type", - "Matchers": [ - { - "Name": "ContentTypeMatcher", - "Pattern": "text/plain", - "IgnoreCase": false - } - ] - } - ], - "Cookies": [ - { - "Name": "c", - "Matchers": [ - { - "Name": "WildcardMatcher", - "Pattern": "x", - "IgnoreCase": true - } - ] - } - ], - "Params": [ - { - "Name": "p1", - "Matchers": [ - { - "Name": "ExactMatcher", - "Pattern": "p1-v", - "IgnoreCase": false - } - ] - }, - { - "Name": "p2", - "Matchers": [ - { - "Name": "ExactMatcher", - "Pattern": "p2-v", - "IgnoreCase": false - } - ] - } - ], - "Body": { - "Matcher": { - "Name": "RegexMatcher", - "Pattern": "Authhello", BodyType.String, BodyType.String)] - [InlineData("something", "hello", BodyType.String, BodyType.Bytes)] - public async Task BodyParser_Parse_ContentTypeString(string contentType, string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType) + [Theory] + [InlineData("application/xml", "hello", BodyType.String, BodyType.String)] + [InlineData("something", "hello", BodyType.String, BodyType.Bytes)] + public async Task BodyParser_Parse_ContentTypeString(string contentType, string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType) + { + // Arrange + var bodyParserSettings = new BodyParserSettings { - // Arrange - var bodyParserSettings = new BodyParserSettings - { - Stream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString)), - ContentType = contentType, - DeserializeJson = true - }; + Stream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString)), + ContentType = contentType, + DeserializeJson = true + }; - // Act - var body = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); + // Act + var body = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); - // Assert - Check.That(body.BodyAsBytes).IsNotNull(); - Check.That(body.BodyAsJson).IsNull(); - Check.That(body.BodyAsString).Equals(bodyAsString); - Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); - Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType); - } + // Assert + Check.That(body.BodyAsBytes).IsNotNull(); + Check.That(body.BodyAsJson).IsNull(); + Check.That(body.BodyAsString).Equals(bodyAsString); + Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); + Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType); + } - [Theory] - [InlineData(new byte[] { 34, 97, 34 }, BodyType.Json)] - [InlineData(new byte[] { 97 }, BodyType.String)] - [InlineData(new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }, BodyType.Bytes)] - public async Task BodyParser_Parse_DetectedBodyType(byte[] content, BodyType detectedBodyType) + [Theory] + [InlineData(new byte[] { 34, 97, 34 }, BodyType.Json)] + [InlineData(new byte[] { 97 }, BodyType.String)] + [InlineData(new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }, BodyType.Bytes)] + public async Task BodyParser_Parse_DetectedBodyType(byte[] content, BodyType detectedBodyType) + { + // arrange + var bodyParserSettings = new BodyParserSettings { - // arrange - var bodyParserSettings = new BodyParserSettings - { - Stream = new MemoryStream(content), - ContentType = null, - DeserializeJson = true - }; + Stream = new MemoryStream(content), + ContentType = null, + DeserializeJson = true + }; - // act - var body = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); + // act + var body = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); - // assert - Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); - } + // assert + Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); + } - [Theory] - [InlineData(new byte[] { 34, 97, 34 }, BodyType.String)] - [InlineData(new byte[] { 97 }, BodyType.String)] - [InlineData(new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }, BodyType.Bytes)] - public async Task BodyParser_Parse_DetectedBodyTypeNoJsonParsing(byte[] content, BodyType detectedBodyType) + [Theory] + [InlineData(new byte[] { 34, 97, 34 }, BodyType.String)] + [InlineData(new byte[] { 97 }, BodyType.String)] + [InlineData(new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }, BodyType.Bytes)] + public async Task BodyParser_Parse_DetectedBodyTypeNoJsonParsing(byte[] content, BodyType detectedBodyType) + { + // arrange + var bodyParserSettings = new BodyParserSettings { - // arrange - var bodyParserSettings = new BodyParserSettings - { - Stream = new MemoryStream(content), - ContentType = null, - DeserializeJson = false - }; + Stream = new MemoryStream(content), + ContentType = null, + DeserializeJson = false + }; - // act - var body = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); + // act + var body = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); - // assert - Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); - } + // assert + Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); + } - [Fact] - public async Task BodyParser_Parse_WithUTF8EncodingAndContentTypeMultipart_DetectedBodyTypeEqualsString() - { - // Arrange - string contentType = "multipart/form-data"; - string body = @" + [Fact] + public async Task BodyParser_Parse_WithUTF8EncodingAndContentTypeMultipart_DetectedBodyTypeEqualsString() + { + // Arrange + string contentType = "multipart/form-data"; + string body = @" -----------------------------9051914041544843365972754266 Content-Disposition: form-data; name=""text"" @@ -131,163 +131,162 @@ Content-Type: text/html -----------------------------9051914041544843365972754266--"; - var bodyParserSettings = new BodyParserSettings - { - Stream = new MemoryStream(Encoding.UTF8.GetBytes(body)), - ContentType = contentType, - DeserializeJson = true - }; - - // Act - var result = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); - - // Assert - Check.That(result.DetectedBodyType).IsEqualTo(BodyType.String); - Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart); - Check.That(result.BodyAsBytes).IsNotNull(); - Check.That(result.BodyAsJson).IsNull(); - Check.That(result.BodyAsString).IsNotNull(); - } - - [Fact] - public async Task BodyParser_Parse_WithUTF16EncodingAndContentTypeMultipart_DetectedBodyTypeEqualsString() + var bodyParserSettings = new BodyParserSettings { - // Arrange - string contentType = "multipart/form-data"; - string body = char.ConvertFromUtf32(0x1D161); //U+1D161 = MUSICAL SYMBOL SIXTEENTH NOTE - var bodyParserSettings = new BodyParserSettings - { - Stream = new MemoryStream(Encoding.UTF8.GetBytes(body)), - ContentType = contentType, - DeserializeJson = true - }; + Stream = new MemoryStream(Encoding.UTF8.GetBytes(body)), + ContentType = contentType, + DeserializeJson = true + }; - // Act - var result = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); + // Act + var result = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); - // Assert - Check.That(result.DetectedBodyType).IsEqualTo(BodyType.Bytes); - Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart); - Check.That(result.BodyAsBytes).IsNotNull(); - Check.That(result.BodyAsJson).IsNull(); - Check.That(result.BodyAsString).IsNull(); - } + // Assert + Check.That(result.DetectedBodyType).IsEqualTo(BodyType.String); + Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart); + Check.That(result.BodyAsBytes).IsNotNull(); + Check.That(result.BodyAsJson).IsNull(); + Check.That(result.BodyAsString).IsNotNull(); + } - [Theory] - [InlineData("hello", BodyType.String, BodyType.Bytes)] - public async Task BodyParser_Parse_ContentTypeIsNull(string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType) + [Fact] + public async Task BodyParser_Parse_WithUTF16EncodingAndContentTypeMultipart_DetectedBodyTypeEqualsString() + { + // Arrange + string contentType = "multipart/form-data"; + string body = char.ConvertFromUtf32(0x1D161); //U+1D161 = MUSICAL SYMBOL SIXTEENTH NOTE + var bodyParserSettings = new BodyParserSettings { - // Arrange - var bodyParserSettings = new BodyParserSettings - { - Stream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString)), - ContentType = null, - DeserializeJson = true - }; + Stream = new MemoryStream(Encoding.UTF8.GetBytes(body)), + ContentType = contentType, + DeserializeJson = true + }; - // Act - var body = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); + // Act + var result = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); - // Assert - Check.That(body.BodyAsBytes).IsNotNull(); - Check.That(body.BodyAsJson).IsNull(); - Check.That(body.BodyAsString).Equals(bodyAsString); - Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); - Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType); - } + // Assert + Check.That(result.DetectedBodyType).IsEqualTo(BodyType.Bytes); + Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart); + Check.That(result.BodyAsBytes).IsNotNull(); + Check.That(result.BodyAsJson).IsNull(); + Check.That(result.BodyAsString).IsNull(); + } - [Theory] - [InlineData("gzip")] - [InlineData("deflate")] - public async Task BodyParser_Parse_ContentEncoding_GZip_And_DecompressGzipAndDeflate_Is_True_Should_Decompress(string compression) + [Theory] + [InlineData("hello", BodyType.String, BodyType.Bytes)] + public async Task BodyParser_Parse_ContentTypeIsNull(string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType) + { + // Arrange + var bodyParserSettings = new BodyParserSettings { - // Arrange - var bytes = Encoding.ASCII.GetBytes("0"); - var compressed = CompressionUtils.Compress(compression, bytes); - var bodyParserSettings = new BodyParserSettings - { - Stream = new MemoryStream(compressed), - ContentType = "text/plain", - DeserializeJson = false, - ContentEncoding = compression.ToUpperInvariant(), - DecompressGZipAndDeflate = true - }; + Stream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString)), + ContentType = null, + DeserializeJson = true + }; - // Act - var result = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); + // Act + var body = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); - // Assert - result.DetectedBodyType.Should().Be(BodyType.String); - result.DetectedBodyTypeFromContentType.Should().Be(BodyType.String); - result.BodyAsBytes.Should().BeEquivalentTo(new byte[] { 48 }); - result.BodyAsJson.Should().BeNull(); - result.BodyAsString.Should().Be("0"); - result.DetectedCompression.Should().Be(compression); - } + // Assert + Check.That(body.BodyAsBytes).IsNotNull(); + Check.That(body.BodyAsJson).IsNull(); + Check.That(body.BodyAsString).Equals(bodyAsString); + Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); + Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType); + } - [Theory] - [InlineData("gzip")] - [InlineData("deflate")] - public async Task BodyParser_Parse_ContentEncoding_GZip_And_DecompressGzipAndDeflate_Is_False_Should_Not_Decompress(string compression) + [Theory] + [InlineData("gzip")] + [InlineData("deflate")] + public async Task BodyParser_Parse_ContentEncoding_GZip_And_DecompressGzipAndDeflate_Is_True_Should_Decompress(string compression) + { + // Arrange + var bytes = Encoding.ASCII.GetBytes("0"); + var compressed = CompressionUtils.Compress(compression, bytes); + var bodyParserSettings = new BodyParserSettings { - // Arrange - var bytes = Encoding.ASCII.GetBytes(Guid.NewGuid().ToString()); - var compressed = CompressionUtils.Compress(compression, bytes); - var bodyParserSettings = new BodyParserSettings - { - Stream = new MemoryStream(compressed), - ContentType = "text/plain", - DeserializeJson = false, - ContentEncoding = compression.ToUpperInvariant(), - DecompressGZipAndDeflate = false - }; + Stream = new MemoryStream(compressed), + ContentType = "text/plain", + DeserializeJson = false, + ContentEncoding = compression.ToUpperInvariant(), + DecompressGZipAndDeflate = true + }; - // Act - var result = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); + // Act + var result = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); - // Assert - result.BodyAsBytes.Should().BeEquivalentTo(compressed); - result.DetectedCompression.Should().BeNull(); - } + // Assert + result.DetectedBodyType.Should().Be(BodyType.String); + result.DetectedBodyTypeFromContentType.Should().Be(BodyType.String); + result.BodyAsBytes.Should().BeEquivalentTo(new byte[] { 48 }); + result.BodyAsJson.Should().BeNull(); + result.BodyAsString.Should().Be("0"); + result.DetectedCompression.Should().Be(compression); + } - [Theory] - [InlineData("HEAD", false)] - [InlineData("GET", false)] - [InlineData("PUT", true)] - [InlineData("POST", true)] - [InlineData("DELETE", true)] - [InlineData("TRACE", false)] - [InlineData("OPTIONS", true)] - [InlineData("CONNECT", false)] - [InlineData("PATCH", true)] - public void BodyParser_ShouldParseBodyForMethodAndAllowAllIsFalse_ExpectedResultForKnownMethods(string method, bool resultShouldBe) + [Theory] + [InlineData("gzip")] + [InlineData("deflate")] + public async Task BodyParser_Parse_ContentEncoding_GZip_And_DecompressGzipAndDeflate_Is_False_Should_Not_Decompress(string compression) + { + // Arrange + var bytes = Encoding.ASCII.GetBytes(Guid.NewGuid().ToString()); + var compressed = CompressionUtils.Compress(compression, bytes); + var bodyParserSettings = new BodyParserSettings { - Check.That(BodyParser.ShouldParseBody(method, false)).Equals(resultShouldBe); - } + Stream = new MemoryStream(compressed), + ContentType = "text/plain", + DeserializeJson = false, + ContentEncoding = compression.ToUpperInvariant(), + DecompressGZipAndDeflate = false + }; - [Theory] - [InlineData("HEAD")] - [InlineData("GET")] - [InlineData("PUT")] - [InlineData("POST")] - [InlineData("DELETE")] - [InlineData("TRACE")] - [InlineData("OPTIONS")] - [InlineData("CONNECT")] - [InlineData("PATCH")] - [InlineData("REPORT")] - [InlineData("SOME-UNKNOWN-METHOD")] - public void BodyParser_ShouldParseBodyForMethodAndAllowAllIsTrue_ExpectedResultShouldBeTrue(string method) - { - Check.That(BodyParser.ShouldParseBody(method, true)).IsTrue(); - } + // Act + var result = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false); - [Theory] - [InlineData("REPORT")] - [InlineData("SOME-UNKNOWN-METHOD")] - public void BodyParser_ShouldParseBody_DefaultIsTrueForUnknownMethods(string method) - { - Check.That(BodyParser.ShouldParseBody(method, false)).IsTrue(); - } + // Assert + result.BodyAsBytes.Should().BeEquivalentTo(compressed); + result.DetectedCompression.Should().BeNull(); + } + + [Theory] + [InlineData("HEAD", false)] + [InlineData("GET", false)] + [InlineData("PUT", true)] + [InlineData("POST", true)] + [InlineData("DELETE", true)] + [InlineData("TRACE", false)] + [InlineData("OPTIONS", true)] + [InlineData("CONNECT", false)] + [InlineData("PATCH", true)] + public void BodyParser_ShouldParseBodyForMethodAndAllowAllIsFalse_ExpectedResultForKnownMethods(string method, bool resultShouldBe) + { + Check.That(BodyParser.ShouldParseBody(method, false)).Equals(resultShouldBe); + } + + [Theory] + [InlineData("HEAD")] + [InlineData("GET")] + [InlineData("PUT")] + [InlineData("POST")] + [InlineData("DELETE")] + [InlineData("TRACE")] + [InlineData("OPTIONS")] + [InlineData("CONNECT")] + [InlineData("PATCH")] + [InlineData("REPORT")] + [InlineData("SOME-UNKNOWN-METHOD")] + public void BodyParser_ShouldParseBodyForMethodAndAllowAllIsTrue_ExpectedResultShouldBeTrue(string method) + { + Check.That(BodyParser.ShouldParseBody(method, true)).IsTrue(); + } + + [Theory] + [InlineData("REPORT")] + [InlineData("SOME-UNKNOWN-METHOD")] + public void BodyParser_ShouldParseBody_DefaultIsTrueForUnknownMethods(string method) + { + Check.That(BodyParser.ShouldParseBody(method, false)).IsTrue(); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Util/BytesEncodingUtilsTests.cs b/test/WireMock.Net.Tests/Util/BytesEncodingUtilsTests.cs index bbd0d5d0..5a945fde 100644 --- a/test/WireMock.Net.Tests/Util/BytesEncodingUtilsTests.cs +++ b/test/WireMock.Net.Tests/Util/BytesEncodingUtilsTests.cs @@ -1,30 +1,29 @@ -using System.Text; +using System.Text; using FluentAssertions; using WireMock.Util; using Xunit; -namespace WireMock.Net.Tests.Util +namespace WireMock.Net.Tests.Util; + +public class BytesEncodingUtilsTests { - public class BytesEncodingUtilsTests + [Fact] + public void TryGetEncoding_UTF32() { - [Fact] - public void TryGetEncoding_UTF32() - { - var result = BytesEncodingUtils.TryGetEncoding(new byte[] { 0xff, 0xfe, 0x00, 0x00 }, out Encoding encoding); + var result = BytesEncodingUtils.TryGetEncoding(new byte[] { 0xff, 0xfe, 0x00, 0x00 }, out Encoding encoding); - // Assert - result.Should().BeTrue(); - encoding.CodePage.Should().Be(Encoding.UTF32.CodePage); - } + // Assert + result.Should().BeTrue(); + encoding.CodePage.Should().Be(Encoding.UTF32.CodePage); + } - [Fact] - public void TryGetEncoding_Invalid() - { - var result = BytesEncodingUtils.TryGetEncoding(new byte[] { 0xff }, out Encoding encoding); + [Fact] + public void TryGetEncoding_Invalid() + { + var result = BytesEncodingUtils.TryGetEncoding(new byte[] { 0xff }, out Encoding encoding); - // Assert - result.Should().BeFalse(); - encoding.Should().BeNull(); - } + // Assert + result.Should().BeFalse(); + encoding.Should().BeNull(); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Util/HttpStatusRangeParserTests.cs b/test/WireMock.Net.Tests/Util/HttpStatusRangeParserTests.cs index 0eed338a..214de23c 100644 --- a/test/WireMock.Net.Tests/Util/HttpStatusRangeParserTests.cs +++ b/test/WireMock.Net.Tests/Util/HttpStatusRangeParserTests.cs @@ -1,75 +1,74 @@ -using FluentAssertions; +using FluentAssertions; using System; using System.Net; using WireMock.Util; using Xunit; -namespace WireMock.Net.Tests.Util +namespace WireMock.Net.Tests.Util; + +/// +/// Based on https://raw.githubusercontent.com/tmenier/Flurl/129565361e135e639f1d44a35a78aea4302ac6ca/Test/Flurl.Test/Http/HttpStatusRangeParserTests.cs +/// +public class HttpStatusRangeParserTests { - /// - /// Based on https://raw.githubusercontent.com/tmenier/Flurl/129565361e135e639f1d44a35a78aea4302ac6ca/Test/Flurl.Test/Http/HttpStatusRangeParserTests.cs - /// - public class HttpStatusRangeParserTests + [Theory] + [InlineData("4**", 399, false)] + [InlineData("4**", 400, true)] + [InlineData("4**", 499, true)] + [InlineData("4**", 500, false)] + + [InlineData("4xx", 399, false)] + [InlineData("4xx", 400, true)] + [InlineData("4xx", 499, true)] + [InlineData("4xx", 500, false)] + + [InlineData("4XX", 399, false)] + [InlineData("4XX", 400, true)] + [InlineData("4XX", 499, true)] + [InlineData("4XX", 500, false)] + + [InlineData("400-499", 399, false)] + [InlineData("400-499", 400, true)] + [InlineData("400-499", 499, true)] + [InlineData("400-499", 500, false)] + + [InlineData("100,3xx,600", 100, true)] + [InlineData("100,3xx,600", 101, false)] + [InlineData("100,3xx,600", 300, true)] + [InlineData("100,3xx,600", 399, true)] + [InlineData("100,3xx,600", 400, false)] + [InlineData("100,3xx,600", 600, true)] + + [InlineData("400-409,490-499", 399, false)] + [InlineData("400-409,490-499", 405, true)] + [InlineData("400-409,490-499", 450, false)] + [InlineData("400-409,490-499", 495, true)] + [InlineData("400-409,490-499", 500, false)] + + [InlineData("*", 0, true)] + [InlineData(",,,*", 9999, true)] + + [InlineData("", 0, false)] + [InlineData(",,,", 9999, false)] + + [InlineData(null, 399, true)] + public void HttpStatusRangeParser_ValidPattern_IsMatch(string pattern, int value, bool expectedResult) { - [Theory] - [InlineData("4**", 399, false)] - [InlineData("4**", 400, true)] - [InlineData("4**", 499, true)] - [InlineData("4**", 500, false)] + HttpStatusRangeParser.IsMatch(pattern, value).Should().Be(expectedResult); + } - [InlineData("4xx", 399, false)] - [InlineData("4xx", 400, true)] - [InlineData("4xx", 499, true)] - [InlineData("4xx", 500, false)] + [Fact] + public void HttpStatusRangeParser_ValidPattern_HttpStatusCode_IsMatch() + { + HttpStatusRangeParser.IsMatch("4xx", HttpStatusCode.BadRequest).Should().BeTrue(); + } - [InlineData("4XX", 399, false)] - [InlineData("4XX", 400, true)] - [InlineData("4XX", 499, true)] - [InlineData("4XX", 500, false)] - - [InlineData("400-499", 399, false)] - [InlineData("400-499", 400, true)] - [InlineData("400-499", 499, true)] - [InlineData("400-499", 500, false)] - - [InlineData("100,3xx,600", 100, true)] - [InlineData("100,3xx,600", 101, false)] - [InlineData("100,3xx,600", 300, true)] - [InlineData("100,3xx,600", 399, true)] - [InlineData("100,3xx,600", 400, false)] - [InlineData("100,3xx,600", 600, true)] - - [InlineData("400-409,490-499", 399, false)] - [InlineData("400-409,490-499", 405, true)] - [InlineData("400-409,490-499", 450, false)] - [InlineData("400-409,490-499", 495, true)] - [InlineData("400-409,490-499", 500, false)] - - [InlineData("*", 0, true)] - [InlineData(",,,*", 9999, true)] - - [InlineData("", 0, false)] - [InlineData(",,,", 9999, false)] - - [InlineData(null, 399, true)] - public void HttpStatusRangeParser_ValidPattern_IsMatch(string pattern, int value, bool expectedResult) - { - HttpStatusRangeParser.IsMatch(pattern, value).Should().Be(expectedResult); - } - - [Fact] - public void HttpStatusRangeParser_ValidPattern_HttpStatusCode_IsMatch() - { - HttpStatusRangeParser.IsMatch("4xx", HttpStatusCode.BadRequest).Should().BeTrue(); - } - - [Theory] - [InlineData("-100")] - [InlineData("100-")] - [InlineData("1yy")] - public void HttpStatusRangeParser_InvalidPattern_ThrowsException(string pattern) - { - Assert.Throws(() => HttpStatusRangeParser.IsMatch(pattern, 100)); - } + [Theory] + [InlineData("-100")] + [InlineData("100-")] + [InlineData("1yy")] + public void HttpStatusRangeParser_InvalidPattern_ThrowsException(string pattern) + { + Assert.Throws(() => HttpStatusRangeParser.IsMatch(pattern, 100)); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Util/StringUtilsTests.cs b/test/WireMock.Net.Tests/Util/StringUtilsTests.cs index 0afd2e90..4a9ca6c9 100644 --- a/test/WireMock.Net.Tests/Util/StringUtilsTests.cs +++ b/test/WireMock.Net.Tests/Util/StringUtilsTests.cs @@ -2,103 +2,102 @@ using FluentAssertions; using WireMock.Util; using Xunit; -namespace WireMock.Net.Tests.Util +namespace WireMock.Net.Tests.Util; + +public class StringUtilsTests { - public class StringUtilsTests + [Theory] + [InlineData("'s")] + [InlineData("\"s")] + public void StringUtils_TryParseQuotedString_With_UnexpectedUnclosedString_Returns_False(string input) { - [Theory] - [InlineData("'s")] - [InlineData("\"s")] - public void StringUtils_TryParseQuotedString_With_UnexpectedUnclosedString_Returns_False(string input) - { - // Act - bool valid = StringUtils.TryParseQuotedString(input, out var result, out var quote); + // Act + bool valid = StringUtils.TryParseQuotedString(input, out var result, out var quote); - // Assert - valid.Should().BeFalse(); - } + // Assert + valid.Should().BeFalse(); + } - [Theory] - [InlineData("")] - [InlineData(null)] - [InlineData("x")] - public void StringUtils_TryParseQuotedString_With_InvalidStringLength_Returns_False(string input) - { - // Act - bool valid = StringUtils.TryParseQuotedString(input, out var result, out var quote); + [Theory] + [InlineData("")] + [InlineData(null)] + [InlineData("x")] + public void StringUtils_TryParseQuotedString_With_InvalidStringLength_Returns_False(string input) + { + // Act + bool valid = StringUtils.TryParseQuotedString(input, out var result, out var quote); - // Assert - valid.Should().BeFalse(); - } + // Assert + valid.Should().BeFalse(); + } - [Theory] - [InlineData("xx")] - [InlineData(" ")] - public void StringUtils_TryParseQuotedString_With_InvalidStringQuoteCharacter_Returns_False(string input) - { - // Act - bool valid = StringUtils.TryParseQuotedString(input, out var result, out var quote); + [Theory] + [InlineData("xx")] + [InlineData(" ")] + public void StringUtils_TryParseQuotedString_With_InvalidStringQuoteCharacter_Returns_False(string input) + { + // Act + bool valid = StringUtils.TryParseQuotedString(input, out var result, out var quote); - // Assert - valid.Should().BeFalse(); - } + // Assert + valid.Should().BeFalse(); + } - [Fact] - public void StringUtils_TryParseQuotedString_With_UnexpectedUnrecognizedEscapeSequence_Returns_False() - { - // Arrange - string input = new string(new[] { '"', '\\', 'u', '?', '"' }); + [Fact] + public void StringUtils_TryParseQuotedString_With_UnexpectedUnrecognizedEscapeSequence_Returns_False() + { + // Arrange + string input = new string(new[] { '"', '\\', 'u', '?', '"' }); - // Act - bool valid = StringUtils.TryParseQuotedString(input, out var result, out var quote); + // Act + bool valid = StringUtils.TryParseQuotedString(input, out var result, out var quote); - // Assert - valid.Should().BeFalse(); - } + // Assert + valid.Should().BeFalse(); + } - [Theory] - [InlineData("''", "")] - [InlineData("'s'", "s")] - [InlineData("'\\\\'", "\\")] - [InlineData("'\\n'", "\n")] - public void StringUtils_TryParseQuotedString_SingleQuotedString(string input, string expectedResult) - { - // Act - bool valid = StringUtils.TryParseQuotedString(input, out var result, out var quote); + [Theory] + [InlineData("''", "")] + [InlineData("'s'", "s")] + [InlineData("'\\\\'", "\\")] + [InlineData("'\\n'", "\n")] + public void StringUtils_TryParseQuotedString_SingleQuotedString(string input, string expectedResult) + { + // Act + bool valid = StringUtils.TryParseQuotedString(input, out var result, out var quote); - // Assert - valid.Should().BeTrue(); - result.Should().Be(expectedResult); - quote.Should().Be('\''); - } + // Assert + valid.Should().BeTrue(); + result.Should().Be(expectedResult); + quote.Should().Be('\''); + } - [Theory] - [InlineData("\"\"", "")] - [InlineData("\"\\\\\"", "\\")] - [InlineData("\"\\n\"", "\n")] - [InlineData("\"\\\\n\"", "\\n")] - [InlineData("\"\\\\new\"", "\\new")] - [InlineData("\"[]\"", "[]")] - [InlineData("\"()\"", "()")] - [InlineData("\"(\\\"\\\")\"", "(\"\")")] - [InlineData("\"/\"", "/")] - [InlineData("\"a\"", "a")] - [InlineData("\"This \\\"is\\\" a test.\"", "This \"is\" a test.")] - [InlineData(@"""This \""is\"" b test.""", @"This ""is"" b test.")] - [InlineData("\"ab\\\"cd\"", "ab\"cd")] - [InlineData("\"\\\"\"", "\"")] - [InlineData("\"\\\"\\\"\"", "\"\"")] - [InlineData("\"AB YZ 19 \uD800\udc05 \u00e4\"", "AB YZ 19 \uD800\udc05 \u00e4")] - [InlineData("\"\\\\\\\\192.168.1.1\\\\audio\\\\new\"", "\\\\192.168.1.1\\audio\\new")] - public void StringUtils_TryParseQuotedString_DoubleQuotedString(string input, string expectedResult) - { - // Act - bool valid = StringUtils.TryParseQuotedString(input, out var result, out var quote); + [Theory] + [InlineData("\"\"", "")] + [InlineData("\"\\\\\"", "\\")] + [InlineData("\"\\n\"", "\n")] + [InlineData("\"\\\\n\"", "\\n")] + [InlineData("\"\\\\new\"", "\\new")] + [InlineData("\"[]\"", "[]")] + [InlineData("\"()\"", "()")] + [InlineData("\"(\\\"\\\")\"", "(\"\")")] + [InlineData("\"/\"", "/")] + [InlineData("\"a\"", "a")] + [InlineData("\"This \\\"is\\\" a test.\"", "This \"is\" a test.")] + [InlineData(@"""This \""is\"" b test.""", @"This ""is"" b test.")] + [InlineData("\"ab\\\"cd\"", "ab\"cd")] + [InlineData("\"\\\"\"", "\"")] + [InlineData("\"\\\"\\\"\"", "\"\"")] + [InlineData("\"AB YZ 19 \uD800\udc05 \u00e4\"", "AB YZ 19 \uD800\udc05 \u00e4")] + [InlineData("\"\\\\\\\\192.168.1.1\\\\audio\\\\new\"", "\\\\192.168.1.1\\audio\\new")] + public void StringUtils_TryParseQuotedString_DoubleQuotedString(string input, string expectedResult) + { + // Act + bool valid = StringUtils.TryParseQuotedString(input, out var result, out var quote); - // Assert - valid.Should().BeTrue(); - result.Should().Be(expectedResult); - quote.Should().Be('"'); - } + // Assert + valid.Should().BeTrue(); + result.Should().Be(expectedResult); + quote.Should().Be('"'); } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Util/UrlUtilsTests.cs b/test/WireMock.Net.Tests/Util/UrlUtilsTests.cs index e4ec478b..f398f40f 100644 --- a/test/WireMock.Net.Tests/Util/UrlUtilsTests.cs +++ b/test/WireMock.Net.Tests/Util/UrlUtilsTests.cs @@ -1,4 +1,4 @@ -using System; +using System; #if NET452 using Microsoft.Owin; #else @@ -8,50 +8,49 @@ using NFluent; using WireMock.Util; using Xunit; -namespace WireMock.Net.Tests.Util +namespace WireMock.Net.Tests.Util; + +public class UrlUtilsTests { - public class UrlUtilsTests + [Fact] + public void UriUtils_CreateUri_WithValidPathString() { - [Fact] - public void UriUtils_CreateUri_WithValidPathString() - { - // Assign - Uri uri = new Uri("https://localhost:1234/a/b?x=0"); + // Assign + Uri uri = new Uri("https://localhost:1234/a/b?x=0"); - // Act - var result = UrlUtils.Parse(uri, new PathString("/a")); + // Act + var result = UrlUtils.Parse(uri, new PathString("/a")); - // Assert - Check.That(result.Url.ToString()).Equals("https://localhost:1234/b?x=0"); - Check.That(result.AbsoluteUrl.ToString()).Equals("https://localhost:1234/a/b?x=0"); - } - - [Fact] - public void UriUtils_CreateUri_WithEmptyPathString() - { - // Assign - Uri uri = new Uri("https://localhost:1234/a/b?x=0"); - - // Act - var result = UrlUtils.Parse(uri, new PathString()); - - // Assert - Check.That(result.Url.ToString()).Equals("https://localhost:1234/a/b?x=0"); - Check.That(result.AbsoluteUrl.ToString()).Equals("https://localhost:1234/a/b?x=0"); - } - - [Fact] - public void UriUtils_CreateUri_WithDifferentPathString() - { - // Assign - Uri uri = new Uri("https://localhost:1234/a/b?x=0"); - - // Act - var result = UrlUtils.Parse(uri, new PathString("/test")); - - // Assert - Check.That(result.Url.ToString()).Equals("https://localhost:1234/a/b?x=0"); - Check.That(result.AbsoluteUrl.ToString()).Equals("https://localhost:1234/a/b?x=0"); - } + // Assert + Check.That(result.Url.ToString()).Equals("https://localhost:1234/b?x=0"); + Check.That(result.AbsoluteUrl.ToString()).Equals("https://localhost:1234/a/b?x=0"); } -} + + [Fact] + public void UriUtils_CreateUri_WithEmptyPathString() + { + // Assign + Uri uri = new Uri("https://localhost:1234/a/b?x=0"); + + // Act + var result = UrlUtils.Parse(uri, new PathString()); + + // Assert + Check.That(result.Url.ToString()).Equals("https://localhost:1234/a/b?x=0"); + Check.That(result.AbsoluteUrl.ToString()).Equals("https://localhost:1234/a/b?x=0"); + } + + [Fact] + public void UriUtils_CreateUri_WithDifferentPathString() + { + // Assign + Uri uri = new Uri("https://localhost:1234/a/b?x=0"); + + // Act + var result = UrlUtils.Parse(uri, new PathString("/test")); + + // Assert + Check.That(result.Url.ToString()).Equals("https://localhost:1234/a/b?x=0"); + Check.That(result.AbsoluteUrl.ToString()).Equals("https://localhost:1234/a/b?x=0"); + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/VerifyExtensions/VerifySettingsExtensions.cs b/test/WireMock.Net.Tests/VerifyExtensions/VerifySettingsExtensions.cs new file mode 100644 index 00000000..51e0fbad --- /dev/null +++ b/test/WireMock.Net.Tests/VerifyExtensions/VerifySettingsExtensions.cs @@ -0,0 +1,15 @@ +#if !(NET452 || NET461) +using VerifyTests; + +namespace WireMock.Net.Tests.VerifyExtensions; + +internal static class VerifySettingsExtensions +{ + public static void Init(this VerifySettings verifySettings) + { + verifySettings.DontScrubDateTimes(); + verifySettings.DontScrubDateTimes(); + verifySettings.UseDirectory($"{typeof(T).Name}.Verify"); + } +} +#endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj b/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj index 152a2743..ad560bd3 100644 --- a/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj +++ b/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj @@ -24,6 +24,18 @@ NETFRAMEWORK + + + + + + + + @@ -41,12 +53,6 @@ - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -66,10 +72,23 @@ + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + - + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + @@ -81,9 +100,6 @@ PreserveNewest - - PreserveNewest - PreserveNewest @@ -108,7 +124,6 @@ - \ No newline at end of file diff --git a/test/WireMock.Net.Tests/WireMockServer.Admin.cs b/test/WireMock.Net.Tests/WireMockServer.Admin.cs index 96f13347..40c54165 100644 --- a/test/WireMock.Net.Tests/WireMockServer.Admin.cs +++ b/test/WireMock.Net.Tests/WireMockServer.Admin.cs @@ -146,7 +146,7 @@ public class WireMockServerAdminTests string responseBodyFilePath = Path.Combine(GetCurrentFolder(), "responsebody.json"); - dynamic jsonObj = JsonConvert.DeserializeObject(json); + dynamic jsonObj = JsonConvert.DeserializeObject(json)!; jsonObj["Response"]["BodyAsFile"] = responseBodyFilePath; string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented); diff --git a/test/WireMock.Net.Tests/WithMapping/WireMockServerWithMappingTests.cs b/test/WireMock.Net.Tests/WithMapping/WireMockServerWithMappingTests.cs index c6b93c66..948b6ed5 100644 --- a/test/WireMock.Net.Tests/WithMapping/WireMockServerWithMappingTests.cs +++ b/test/WireMock.Net.Tests/WithMapping/WireMockServerWithMappingTests.cs @@ -1,65 +1,65 @@ -using System; +using System; using FluentAssertions; using WireMock.Admin.Mappings; using WireMock.Server; using Xunit; -namespace WireMock.Net.Tests.WithMapping +namespace WireMock.Net.Tests.WithMapping; + +public class WireMockServerWithMappingTests { - public class WireMockServerWithMappingTests + [Fact] + public void WireMockServer_WithMappingAsModel_Should_Add_Mapping() { - [Fact] - public void WireMockServer_WithMappingAsModel_Should_Add_Mapping() + // Arrange + var guid = Guid.NewGuid(); + var pattern = "hello wiremock"; + var path = "/foo"; + var response = "OK"; + var mapping = new MappingModel { - // Arrange - var guid = Guid.NewGuid(); - var pattern = "hello wiremock"; - var path = "/foo"; - var response = "OK"; - var mapping = new MappingModel + Guid = guid, + Request = new RequestModel { - Guid = guid, - Request = new RequestModel + Path = path, + Body = new BodyModel { - Path = path, - Body = new BodyModel + Matcher = new MatcherModel { - Matcher = new MatcherModel - { - Name = "ExactMatcher", - Pattern = pattern - } + Name = "ExactMatcher", + Pattern = pattern } - }, - Response = new ResponseModel - { - Body = response, - StatusCode = 201 } - }; + }, + Response = new ResponseModel + { + Body = response, + StatusCode = 201 + } + }; - var server = WireMockServer.Start(); + var server = WireMockServer.Start(); - // Act - server.WithMapping(mapping); + // Act + server.WithMapping(mapping); - // Assert - server.MappingModels.Should().HaveCount(1).And.Contain(m => - m.Guid == guid && - //((PathModel)m.Request.Path).Matchers.OfType().First().GetPatterns().First() == "/foo*" - // m.Request.Body.Matchers.OfType().First().GetPatterns().First() == pattern && - m.Response.Body == response && - (int)m.Response.StatusCode == 201 - ); + // Assert + server.MappingModels.Should().HaveCount(1).And.Contain(m => + m.Guid == guid && + //((PathModel)m.Request.Path).Matchers.OfType().First().GetPatterns().First() == "/foo*" + // m.Request.Body.Matchers.OfType().First().GetPatterns().First() == pattern && + m.Response.Body == response && + (int?)m.Response.StatusCode == 201 + ); - server.Stop(); - } + server.Stop(); + } - [Fact] - public void WireMockServer_WithMappingAsJson_Should_Add_Mapping() - { - // Arrange - var mapping = @"{ + [Fact] + public void WireMockServer_WithMappingAsJson_Should_Add_Mapping() + { + // Arrange + var mapping = @"{ ""Guid"": ""532889c2-f84d-4dc8-b847-9ea2c6aca7d5"", ""Request"": { ""Path"": ""/pet"", @@ -78,25 +78,25 @@ namespace WireMock.Net.Tests.WithMapping } }"; - var server = WireMockServer.Start(); + var server = WireMockServer.Start(); - // Act - server.WithMapping(mapping); + // Act + server.WithMapping(mapping); - // Assert - server.MappingModels.Should().HaveCount(1).And.Contain(m => - m.Guid == Guid.Parse("532889c2-f84d-4dc8-b847-9ea2c6aca7d5") && - (int)m.Response.StatusCode == 201 - ); + // Assert + server.MappingModels.Should().HaveCount(1).And.Contain(m => + m.Guid == Guid.Parse("532889c2-f84d-4dc8-b847-9ea2c6aca7d5") && + (int?)m.Response.StatusCode == 201 + ); - server.Stop(); - } + server.Stop(); + } - [Fact] - public void WireMockServer_WithMappingsAsJson_Should_Add_Mapping() - { - // Arrange - var mapping = @"[ + [Fact] + public void WireMockServer_WithMappingsAsJson_Should_Add_Mapping() + { + // Arrange + var mapping = @"[ { ""Guid"": ""532889c2-f84d-4dc8-b847-9ea2c6aca7d1"", ""Request"": { @@ -117,15 +117,14 @@ namespace WireMock.Net.Tests.WithMapping } ]"; - var server = WireMockServer.Start(); + var server = WireMockServer.Start(); - // Act - server.WithMapping(mapping); + // Act + server.WithMapping(mapping); - // Assert - server.MappingModels.Should().HaveCount(2); + // Assert + server.MappingModels.Should().HaveCount(2); - server.Stop(); - } + server.Stop(); } } \ No newline at end of file