Generate C# code from Mapping (#842)

* 1

* .

* v

* .

* .

* -

* b

* res b

* Fix UT

* .

* Verify

* v

* ...

* .

* .

* dir

* m
This commit is contained in:
Stef Heyenrath
2023-01-24 16:45:47 +01:00
committed by GitHub
parent b4c8779d68
commit 770a670e53
83 changed files with 3792 additions and 2942 deletions
+2
View File
@@ -255,3 +255,5 @@ paket-files/
/test/WireMock.Net.Tests/coverage.opencover.xml /test/WireMock.Net.Tests/coverage.opencover.xml
/test/WireMock.Net.Tests/coverage.netcoreapp3.1.opencover.xml /test/WireMock.Net.Tests/coverage.netcoreapp3.1.opencover.xml
/test/WireMock.Net.Tests/coverage.net5.0.opencover.xml /test/WireMock.Net.Tests/coverage.net5.0.opencover.xml
*.received.*
@@ -42,11 +42,11 @@
<Reference Include="Handlebars, Version=2.1.2.0, Culture=neutral, PublicKeyToken=22225d0bf33cd661, processorArchitecture=MSIL"> <Reference Include="Handlebars, Version=2.1.2.0, Culture=neutral, PublicKeyToken=22225d0bf33cd661, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.2.1.2\lib\net452\Handlebars.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.2.1.2\lib\net452\Handlebars.dll</HintPath>
</Reference> </Reference>
<Reference Include="Handlebars.Net.Helpers, Version=2.3.10.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="Handlebars.Net.Helpers, Version=2.3.12.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.2.3.10\lib\net452\Handlebars.Net.Helpers.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.2.3.12\lib\net452\Handlebars.Net.Helpers.dll</HintPath>
</Reference> </Reference>
<Reference Include="HandlebarsDotNet.Helpers.Core, Version=2.3.10.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="HandlebarsDotNet.Helpers.Core, Version=2.3.12.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.Core.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Core.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.Core.2.3.12\lib\net452\HandlebarsDotNet.Helpers.Core.dll</HintPath>
</Reference> </Reference>
<Reference Include="log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> <Reference Include="log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath> <HintPath>..\..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath>
@@ -2,8 +2,8 @@
<packages> <packages>
<package id="AnyOf" version="0.3.0" targetFramework="net452" /> <package id="AnyOf" version="0.3.0" targetFramework="net452" />
<package id="Handlebars.Net" version="2.1.2" targetFramework="net452" /> <package id="Handlebars.Net" version="2.1.2" targetFramework="net452" />
<package id="Handlebars.Net.Helpers" version="2.3.10" targetFramework="net452" /> <package id="Handlebars.Net.Helpers" version="2.3.12" targetFramework="net452" />
<package id="Handlebars.Net.Helpers.Core" version="2.3.10" targetFramework="net452" /> <package id="Handlebars.Net.Helpers.Core" version="2.3.12" targetFramework="net452" />
<package id="log4net" version="2.0.15" targetFramework="net452" /> <package id="log4net" version="2.0.15" targetFramework="net452" />
<package id="Microsoft.Owin.Host.HttpListener" version="3.1.0" targetFramework="net452" /> <package id="Microsoft.Owin.Host.HttpListener" version="3.1.0" targetFramework="net452" />
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net452" /> <package id="Newtonsoft.Json" version="13.0.1" targetFramework="net452" />
@@ -41,11 +41,11 @@
<Reference Include="Handlebars, Version=2.1.2.0, Culture=neutral, PublicKeyToken=22225d0bf33cd661, processorArchitecture=MSIL"> <Reference Include="Handlebars, Version=2.1.2.0, Culture=neutral, PublicKeyToken=22225d0bf33cd661, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.2.1.2\lib\net46\Handlebars.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.2.1.2\lib\net46\Handlebars.dll</HintPath>
</Reference> </Reference>
<Reference Include="Handlebars.Net.Helpers, Version=2.3.10.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="Handlebars.Net.Helpers, Version=2.3.12.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.2.3.10\lib\net452\Handlebars.Net.Helpers.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.2.3.12\lib\net46\Handlebars.Net.Helpers.dll</HintPath>
</Reference> </Reference>
<Reference Include="HandlebarsDotNet.Helpers.Core, Version=2.3.10.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="HandlebarsDotNet.Helpers.Core, Version=2.3.12.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.Core.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Core.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.Core.2.3.12\lib\net46\HandlebarsDotNet.Helpers.Core.dll</HintPath>
</Reference> </Reference>
<Reference Include="log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> <Reference Include="log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath> <HintPath>..\..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath>
@@ -2,8 +2,8 @@
<packages> <packages>
<package id="AnyOf" version="0.3.0" targetFramework="net461" /> <package id="AnyOf" version="0.3.0" targetFramework="net461" />
<package id="Handlebars.Net" version="2.1.2" targetFramework="net461" /> <package id="Handlebars.Net" version="2.1.2" targetFramework="net461" />
<package id="Handlebars.Net.Helpers" version="2.3.10" targetFramework="net461" /> <package id="Handlebars.Net.Helpers" version="2.3.12" targetFramework="net461" />
<package id="Handlebars.Net.Helpers.Core" version="2.3.10" targetFramework="net461" /> <package id="Handlebars.Net.Helpers.Core" version="2.3.12" targetFramework="net461" />
<package id="log4net" version="2.0.15" targetFramework="net461" /> <package id="log4net" version="2.0.15" targetFramework="net461" />
<package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="2.2.0" targetFramework="net461" /> <package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="2.2.0" targetFramework="net461" />
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net461" /> <package id="Newtonsoft.Json" version="13.0.1" targetFramework="net461" />
@@ -49,29 +49,29 @@
<Reference Include="Handlebars, Version=2.1.2.0, Culture=neutral, PublicKeyToken=22225d0bf33cd661, processorArchitecture=MSIL"> <Reference Include="Handlebars, Version=2.1.2.0, Culture=neutral, PublicKeyToken=22225d0bf33cd661, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.2.1.2\lib\net46\Handlebars.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.2.1.2\lib\net46\Handlebars.dll</HintPath>
</Reference> </Reference>
<Reference Include="Handlebars.Net.Helpers, Version=2.3.10.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="Handlebars.Net.Helpers, Version=2.3.12.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.2.3.10\lib\net452\Handlebars.Net.Helpers.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.2.3.12\lib\net46\Handlebars.Net.Helpers.dll</HintPath>
</Reference> </Reference>
<Reference Include="HandlebarsDotNet.Helpers.Core, Version=2.3.10.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="HandlebarsDotNet.Helpers.Core, Version=2.3.12.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.Core.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Core.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.Core.2.3.12\lib\net46\HandlebarsDotNet.Helpers.Core.dll</HintPath>
</Reference> </Reference>
<Reference Include="HandlebarsDotNet.Helpers.DynamicLinq, Version=2.3.10.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="HandlebarsDotNet.Helpers.DynamicLinq, Version=2.3.12.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.DynamicLinq.2.3.10\lib\net452\HandlebarsDotNet.Helpers.DynamicLinq.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.DynamicLinq.2.3.12\lib\net46\HandlebarsDotNet.Helpers.DynamicLinq.dll</HintPath>
</Reference> </Reference>
<Reference Include="HandlebarsDotNet.Helpers.Humanizer, Version=2.3.10.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="HandlebarsDotNet.Helpers.Humanizer, Version=2.3.12.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.Humanizer.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Humanizer.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.Humanizer.2.3.12\lib\net46\HandlebarsDotNet.Helpers.Humanizer.dll</HintPath>
</Reference> </Reference>
<Reference Include="HandlebarsDotNet.Helpers.Json, Version=2.3.10.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="HandlebarsDotNet.Helpers.Json, Version=2.3.12.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.Json.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Json.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.Json.2.3.12\lib\net46\HandlebarsDotNet.Helpers.Json.dll</HintPath>
</Reference> </Reference>
<Reference Include="HandlebarsDotNet.Helpers.Random, Version=2.3.10.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="HandlebarsDotNet.Helpers.Random, Version=2.3.12.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.Random.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Random.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.Random.2.3.12\lib\net46\HandlebarsDotNet.Helpers.Random.dll</HintPath>
</Reference> </Reference>
<Reference Include="HandlebarsDotNet.Helpers.Xeger, Version=2.3.10.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="HandlebarsDotNet.Helpers.Xeger, Version=2.3.12.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.Xeger.2.3.10\lib\net452\HandlebarsDotNet.Helpers.Xeger.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.Xeger.2.3.12\lib\net46\HandlebarsDotNet.Helpers.Xeger.dll</HintPath>
</Reference> </Reference>
<Reference Include="HandlebarsDotNet.Helpers.XPath, Version=2.3.10.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="HandlebarsDotNet.Helpers.XPath, Version=2.3.12.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.XPath.2.3.10\lib\net452\HandlebarsDotNet.Helpers.XPath.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.XPath.2.3.12\lib\net46\HandlebarsDotNet.Helpers.XPath.dll</HintPath>
</Reference> </Reference>
<Reference Include="Humanizer, Version=2.14.0.0, Culture=neutral, PublicKeyToken=979442b78dfc278e, processorArchitecture=MSIL"> <Reference Include="Humanizer, Version=2.14.0.0, Culture=neutral, PublicKeyToken=979442b78dfc278e, processorArchitecture=MSIL">
<HintPath>..\..\packages\Humanizer.Core.2.14.1\lib\netstandard2.0\Humanizer.dll</HintPath> <HintPath>..\..\packages\Humanizer.Core.2.14.1\lib\netstandard2.0\Humanizer.dll</HintPath>
@@ -3,14 +3,14 @@
<package id="AnyOf" version="0.3.0" targetFramework="net472" /> <package id="AnyOf" version="0.3.0" targetFramework="net472" />
<package id="Fare" version="2.2.1" targetFramework="net472" /> <package id="Fare" version="2.2.1" targetFramework="net472" />
<package id="Handlebars.Net" version="2.1.2" targetFramework="net472" /> <package id="Handlebars.Net" version="2.1.2" targetFramework="net472" />
<package id="Handlebars.Net.Helpers" version="2.3.10" targetFramework="net472" /> <package id="Handlebars.Net.Helpers" version="2.3.12" targetFramework="net472" />
<package id="Handlebars.Net.Helpers.Core" version="2.3.10" targetFramework="net472" /> <package id="Handlebars.Net.Helpers.Core" version="2.3.12" targetFramework="net472" />
<package id="Handlebars.Net.Helpers.DynamicLinq" version="2.3.10" targetFramework="net472" /> <package id="Handlebars.Net.Helpers.DynamicLinq" version="2.3.12" targetFramework="net472" />
<package id="Handlebars.Net.Helpers.Humanizer" version="2.3.10" targetFramework="net472" /> <package id="Handlebars.Net.Helpers.Humanizer" version="2.3.12" targetFramework="net472" />
<package id="Handlebars.Net.Helpers.Json" version="2.3.10" targetFramework="net472" /> <package id="Handlebars.Net.Helpers.Json" version="2.3.12" targetFramework="net472" />
<package id="Handlebars.Net.Helpers.Random" version="2.3.10" targetFramework="net472" /> <package id="Handlebars.Net.Helpers.Random" version="2.3.12" targetFramework="net472" />
<package id="Handlebars.Net.Helpers.Xeger" version="2.3.10" targetFramework="net472" /> <package id="Handlebars.Net.Helpers.Xeger" version="2.3.12" targetFramework="net472" />
<package id="Handlebars.Net.Helpers.XPath" version="2.3.10" targetFramework="net472" /> <package id="Handlebars.Net.Helpers.XPath" version="2.3.12" targetFramework="net472" />
<package id="Humanizer" version="2.14.1" targetFramework="net472" /> <package id="Humanizer" version="2.14.1" targetFramework="net472" />
<package id="Humanizer.Core" version="2.14.1" targetFramework="net472" /> <package id="Humanizer.Core" version="2.14.1" targetFramework="net472" />
<package id="Humanizer.Core.af" version="2.14.1" targetFramework="net472" /> <package id="Humanizer.Core.af" version="2.14.1" targetFramework="net472" />
@@ -0,0 +1,11 @@
namespace WireMock.Types;
/// <summary>
///
/// </summary>
public enum MappingConverterType
{
Server,
Builder
}
@@ -1,4 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
namespace WireMock.Types; namespace WireMock.Types;
@@ -63,7 +64,8 @@ public class WireMockList<T> : List<T>
return this[0]?.ToString(); return this[0]?.ToString();
default: default:
return base.ToString(); var strings = this.Select(x => x as string ?? x?.ToString());
return string.Join(", ", strings);
} }
} }
} }
@@ -0,0 +1,20 @@
using System;
using System.Reflection;
namespace WireMock.Extensions;
internal static class EnumExtensions
{
public static string GetFullyQualifiedEnumValue<T>(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}";
}
}
+13 -5
View File
@@ -1,4 +1,3 @@
using System;
using System.Linq; using System.Linq;
using Newtonsoft.Json; using Newtonsoft.Json;
using Stef.Validation; using Stef.Validation;
@@ -8,6 +7,7 @@ using WireMock.Owin;
using WireMock.Serialization; using WireMock.Serialization;
using WireMock.Server; using WireMock.Server;
using WireMock.Settings; using WireMock.Settings;
using WireMock.Util;
namespace WireMock; namespace WireMock;
@@ -18,9 +18,10 @@ public class MappingBuilder : IMappingBuilder
{ {
private readonly WireMockServerSettings _settings; private readonly WireMockServerSettings _settings;
private readonly IWireMockMiddlewareOptions _options; private readonly IWireMockMiddlewareOptions _options;
private readonly MappingConverter _mappingConverter; private readonly MappingConverter _mappingConverter;
private readonly MappingToFileSaver _mappingToFileSaver; private readonly MappingToFileSaver _mappingToFileSaver;
private readonly IGuidUtils _guidUtils;
private readonly IDateTimeUtils _dateTimeUtils;
/// <summary> /// <summary>
/// Create a MappingBuilder /// Create a MappingBuilder
@@ -34,25 +35,32 @@ public class MappingBuilder : IMappingBuilder
var matcherMapper = new MatcherMapper(_settings); var matcherMapper = new MatcherMapper(_settings);
_mappingConverter = new MappingConverter(matcherMapper); _mappingConverter = new MappingConverter(matcherMapper);
_mappingToFileSaver = new MappingToFileSaver(_settings, _mappingConverter); _mappingToFileSaver = new MappingToFileSaver(_settings, _mappingConverter);
_guidUtils = new GuidUtils();
_dateTimeUtils = new DateTimeUtils();
} }
internal MappingBuilder( internal MappingBuilder(
WireMockServerSettings settings, WireMockServerSettings settings,
IWireMockMiddlewareOptions options, IWireMockMiddlewareOptions options,
MappingConverter mappingConverter, MappingConverter mappingConverter,
MappingToFileSaver mappingToFileSaver MappingToFileSaver mappingToFileSaver,
IGuidUtils guidUtils,
IDateTimeUtils dateTimeUtils
) )
{ {
_settings = Guard.NotNull(settings); _settings = Guard.NotNull(settings);
_options = Guard.NotNull(options); _options = Guard.NotNull(options);
_mappingConverter = Guard.NotNull(mappingConverter); _mappingConverter = Guard.NotNull(mappingConverter);
_mappingToFileSaver = Guard.NotNull(mappingToFileSaver); _mappingToFileSaver = Guard.NotNull(mappingToFileSaver);
_guidUtils = Guard.NotNull(guidUtils);
_dateTimeUtils = Guard.NotNull(dateTimeUtils);
} }
/// <inheritdoc /> /// <inheritdoc />
public IRespondWithAProvider Given(IRequestMatcher requestMatcher, bool saveToFile = false) 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);
} }
/// <inheritdoc /> /// <inheritdoc />
@@ -95,7 +103,7 @@ public class MappingBuilder : IMappingBuilder
// Check a mapping exists with the same Guid. If so, update the datetime and replace it. // Check a mapping exists with the same Guid. If so, update the datetime and replace it.
if (_options.Mappings.ContainsKey(mapping.Guid)) if (_options.Mappings.ContainsKey(mapping.Guid))
{ {
mapping.UpdatedAt = DateTime.UtcNow; mapping.UpdatedAt = _dateTimeUtils.UtcNow;
_options.Mappings[mapping.Guid] = mapping; _options.Mappings[mapping.Guid] = mapping;
} }
else else
@@ -1,10 +1,9 @@
using JetBrains.Annotations;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using WireMock.Matchers; using WireMock.Matchers;
namespace WireMock.RequestBuilders namespace WireMock.RequestBuilders;
{
/// <summary> /// <summary>
/// The CookieRequestBuilder interface. /// The CookieRequestBuilder interface.
/// </summary> /// </summary>
@@ -17,7 +16,7 @@ namespace WireMock.RequestBuilders
/// <param name="pattern">The pattern.</param> /// <param name="pattern">The pattern.</param>
/// <param name="matchBehaviour">The match behaviour.</param> /// <param name="matchBehaviour">The match behaviour.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithCookie([NotNull] string name, string pattern, MatchBehaviour matchBehaviour); IRequestBuilder WithCookie(string name, string pattern, MatchBehaviour matchBehaviour);
/// <summary> /// <summary>
/// WithCookie: matching based on name, pattern, ignoreCase and matchBehaviour. /// WithCookie: matching based on name, pattern, ignoreCase and matchBehaviour.
@@ -27,7 +26,7 @@ namespace WireMock.RequestBuilders
/// <param name="ignoreCase">Ignore the case from the pattern.</param> /// <param name="ignoreCase">Ignore the case from the pattern.</param>
/// <param name="matchBehaviour">The match behaviour.</param> /// <param name="matchBehaviour">The match behaviour.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithCookie([NotNull] string name, string pattern, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); IRequestBuilder WithCookie(string name, string pattern, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary> /// <summary>
/// WithCookie: matching based on name, patterns and matchBehaviour. /// WithCookie: matching based on name, patterns and matchBehaviour.
@@ -36,7 +35,7 @@ namespace WireMock.RequestBuilders
/// <param name="patterns">The patterns.</param> /// <param name="patterns">The patterns.</param>
/// <param name="matchBehaviour">The match behaviour.</param> /// <param name="matchBehaviour">The match behaviour.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithCookie([NotNull] string name, string[] patterns, MatchBehaviour matchBehaviour); IRequestBuilder WithCookie(string name, string[] patterns, MatchBehaviour matchBehaviour);
/// <summary> /// <summary>
/// WithCookie: matching based on name, patterns, ignoreCase and matchBehaviour. /// WithCookie: matching based on name, patterns, ignoreCase and matchBehaviour.
@@ -46,7 +45,7 @@ namespace WireMock.RequestBuilders
/// <param name="ignoreCase">Ignore the case from the pattern.</param> /// <param name="ignoreCase">Ignore the case from the pattern.</param>
/// <param name="matchBehaviour">The match behaviour.</param> /// <param name="matchBehaviour">The match behaviour.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithCookie([NotNull] string name, string[] patterns, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); IRequestBuilder WithCookie(string name, string[] patterns, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary> /// <summary>
/// WithCookie: matching based on name and IStringMatcher[]. /// WithCookie: matching based on name and IStringMatcher[].
@@ -54,7 +53,7 @@ namespace WireMock.RequestBuilders
/// <param name="name">The name.</param> /// <param name="name">The name.</param>
/// <param name="matchers">The matchers.</param> /// <param name="matchers">The matchers.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithCookie([NotNull] string name, [NotNull] params IStringMatcher[] matchers); IRequestBuilder WithCookie(string name, params IStringMatcher[] matchers);
/// <summary> /// <summary>
/// WithCookie: matching based on name, ignoreCase and IStringMatcher[]. /// WithCookie: matching based on name, ignoreCase and IStringMatcher[].
@@ -63,7 +62,7 @@ namespace WireMock.RequestBuilders
/// <param name="ignoreCase">Ignore the case from the cookie-keys.</param> /// <param name="ignoreCase">Ignore the case from the cookie-keys.</param>
/// <param name="matchers">The matchers.</param> /// <param name="matchers">The matchers.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithCookie([NotNull] string name, bool ignoreCase, [NotNull] params IStringMatcher[] matchers); IRequestBuilder WithCookie(string name, bool ignoreCase, params IStringMatcher[] matchers);
/// <summary> /// <summary>
/// WithCookie: matching based on name, ignoreCase, matchBehaviour and IStringMatcher[]. /// WithCookie: matching based on name, ignoreCase, matchBehaviour and IStringMatcher[].
@@ -73,13 +72,12 @@ namespace WireMock.RequestBuilders
/// <param name="matchBehaviour">The match behaviour.</param> /// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="matchers">The matchers.</param> /// <param name="matchers">The matchers.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithCookie([NotNull] string name, bool ignoreCase, MatchBehaviour matchBehaviour, [NotNull] params IStringMatcher[] matchers); IRequestBuilder WithCookie(string name, bool ignoreCase, MatchBehaviour matchBehaviour, params IStringMatcher[] matchers);
/// <summary> /// <summary>
/// WithCookie: matching based on functions. /// WithCookie: matching based on functions.
/// </summary> /// </summary>
/// <param name="funcs">The cookies funcs.</param> /// <param name="funcs">The cookies funcs.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithCookie([NotNull] params Func<IDictionary<string, string>, bool>[] funcs); IRequestBuilder WithCookie(params Func<IDictionary<string, string>, bool>[] funcs);
}
} }
@@ -1,9 +1,12 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
using Stef.Validation; using Stef.Validation;
using WireMock.Admin.Mappings; using WireMock.Admin.Mappings;
using WireMock.Constants;
using WireMock.Extensions;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.Models; using WireMock.Models;
@@ -16,6 +19,8 @@ namespace WireMock.Serialization;
internal class MappingConverter internal class MappingConverter
{ {
private static readonly string AcceptOnMatch = MatchBehaviour.AcceptOnMatch.GetFullyQualifiedEnumValue();
private readonly MatcherMapper _mapper; private readonly MatcherMapper _mapper;
public MappingConverter(MatcherMapper mapper) public MappingConverter(MatcherMapper mapper)
@@ -23,6 +28,133 @@ internal class MappingConverter
_mapper = Guard.NotNull(mapper); _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<RequestMessageClientIPMatcher>();
var pathMatcher = request.GetRequestMessageMatcher<RequestMessagePathMatcher>();
var urlMatcher = request.GetRequestMessageMatcher<RequestMessageUrlMatcher>();
var headerMatchers = request.GetRequestMessageMatchers<RequestMessageHeaderMatcher>();
var cookieMatchers = request.GetRequestMessageMatchers<RequestMessageCookieMatcher>();
var paramsMatchers = request.GetRequestMessageMatchers<RequestMessageParamMatcher>();
var methodMatcher = request.GetRequestMessageMatcher<RequestMessageMethodMatcher>();
var bodyMatcher = request.GetRequestMessageMatcher<RequestMessageBodyMatcher>();
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<WildcardMatcher>().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) public MappingModel ToMappingModel(IMapping mapping)
{ {
var request = (Request)mapping.RequestMatcher; var request = (Request)mapping.RequestMatcher;
@@ -237,6 +369,64 @@ internal class MappingConverter
return mappingModel; return mappingModel;
} }
private static string GetString(IStringMatcher stringMatcher)
{
return stringMatcher.GetPatterns().Select(p => $"\"{p.GetPattern()}\"").First();
}
private static string[] GetStringArray(IReadOnlyList<IStringMatcher> stringMatchers)
{
return stringMatchers.SelectMany(m => m.GetPatterns()).Select(p => p.GetPattern()).ToArray();
}
private static string To1Or2Or3Arguments(string key, MatchBehaviour? matchBehaviour, IReadOnlyList<IStringMatcher> 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<IStringMatcher> 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) private static WebProxyModel? MapWebProxy(WebProxySettings? settings)
{ {
return settings != null ? new WebProxyModel return settings != null ? new WebProxyModel
@@ -0,0 +1,25 @@
using WireMock.Types;
namespace WireMock.Serialization;
/// <summary>
/// MappingConverterSettings
/// </summary>
public class MappingConverterSettings
{
/// <summary>
/// Use 'Server' or 'Builder'.
///
/// Default is Server
/// </summary>
public MappingConverterType ConverterType { get; set; }
/// <summary>
/// Add "var server = WireMockServer.Start();"
/// or
/// Add "var builder = new MappingBuilder();"
///
/// Default it's false.
/// </summary>
public bool AddStart { get; set; }
}
@@ -28,9 +28,8 @@ internal class RespondWithAProvider : IRespondWithAProvider
private readonly RegistrationCallback _registrationCallback; private readonly RegistrationCallback _registrationCallback;
private readonly IRequestMatcher _requestMatcher; private readonly IRequestMatcher _requestMatcher;
private readonly WireMockServerSettings _settings; private readonly WireMockServerSettings _settings;
private readonly IDateTimeUtils _dateTimeUtils;
private readonly bool _saveToFile; private readonly bool _saveToFile;
private readonly IGuidUtils _guidUtils = new GuidUtils();
private readonly IDateTimeUtils _dateTimeUtils = new DateTimeUtils();
private bool _useWebhookFireAndForget; private bool _useWebhookFireAndForget;
@@ -46,20 +45,25 @@ internal class RespondWithAProvider : IRespondWithAProvider
/// <param name="registrationCallback">The registration callback.</param> /// <param name="registrationCallback">The registration callback.</param>
/// <param name="requestMatcher">The request matcher.</param> /// <param name="requestMatcher">The request matcher.</param>
/// <param name="settings">The WireMockServerSettings.</param> /// <param name="settings">The WireMockServerSettings.</param>
/// <param name="guidUtils">GuidUtils to make unit testing possible.</param>
/// <param name="dateTimeUtils">DateTimeUtils to make unit testing possible.</param>
/// <param name="saveToFile">Optional boolean to indicate if this mapping should be saved as static mapping file.</param> /// <param name="saveToFile">Optional boolean to indicate if this mapping should be saved as static mapping file.</param>
public RespondWithAProvider( public RespondWithAProvider(
RegistrationCallback registrationCallback, RegistrationCallback registrationCallback,
IRequestMatcher requestMatcher, IRequestMatcher requestMatcher,
WireMockServerSettings settings, WireMockServerSettings settings,
IGuidUtils guidUtils,
IDateTimeUtils dateTimeUtils,
bool saveToFile = false bool saveToFile = false
) )
{ {
_registrationCallback = Guard.NotNull(registrationCallback); _registrationCallback = Guard.NotNull(registrationCallback);
_requestMatcher = Guard.NotNull(requestMatcher); _requestMatcher = Guard.NotNull(requestMatcher);
_settings = Guard.NotNull(settings); _settings = Guard.NotNull(settings);
_saveToFile = Guard.NotNull(saveToFile); _dateTimeUtils = Guard.NotNull(dateTimeUtils);
_saveToFile = saveToFile;
Guid = _guidUtils.NewGuid(); Guid = guidUtils.NewGuid();
} }
/// <summary> /// <summary>
+11 -1
View File
@@ -22,6 +22,7 @@ using WireMock.ResponseProviders;
using WireMock.Serialization; using WireMock.Serialization;
using WireMock.Settings; using WireMock.Settings;
using WireMock.Types; using WireMock.Types;
using WireMock.Util;
namespace WireMock.Server; namespace WireMock.Server;
@@ -39,6 +40,8 @@ public partial class WireMockServer : IWireMockServer
private readonly MatcherMapper _matcherMapper; private readonly MatcherMapper _matcherMapper;
private readonly MappingToFileSaver _mappingToFileSaver; private readonly MappingToFileSaver _mappingToFileSaver;
private readonly MappingBuilder _mappingBuilder; private readonly MappingBuilder _mappingBuilder;
private readonly IGuidUtils _guidUtils = new GuidUtils();
private readonly IDateTimeUtils _dateTimeUtils = new DateTimeUtils();
/// <inheritdoc cref="IWireMockServer.IsStarted" /> /// <inheritdoc cref="IWireMockServer.IsStarted" />
[PublicAPI] [PublicAPI]
@@ -315,7 +318,14 @@ public partial class WireMockServer : IWireMockServer
_matcherMapper = new MatcherMapper(_settings); _matcherMapper = new MatcherMapper(_settings);
_mappingConverter = new MappingConverter(_matcherMapper); _mappingConverter = new MappingConverter(_matcherMapper);
_mappingToFileSaver = new MappingToFileSaver(_settings, _mappingConverter); _mappingToFileSaver = new MappingToFileSaver(_settings, _mappingConverter);
_mappingBuilder = new MappingBuilder(settings, _options, _mappingConverter, _mappingToFileSaver); _mappingBuilder = new MappingBuilder(
settings,
_options,
_mappingConverter,
_mappingToFileSaver,
_guidUtils,
_dateTimeUtils
);
#if USE_ASPNETCORE #if USE_ASPNETCORE
_options.AdditionalServiceRegistration = _settings.AdditionalServiceRegistration; _options.AdditionalServiceRegistration = _settings.AdditionalServiceRegistration;
+7 -7
View File
@@ -177,13 +177,13 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Handlebars.Net.Helpers" Version="2.3.11" /> <PackageReference Include="Handlebars.Net.Helpers" Version="2.3.12" />
<PackageReference Include="Handlebars.Net.Helpers.DynamicLinq" Version="2.3.11" /> <PackageReference Include="Handlebars.Net.Helpers.DynamicLinq" Version="2.3.12" />
<PackageReference Include="Handlebars.Net.Helpers.Humanizer" Version="2.3.11" /> <PackageReference Include="Handlebars.Net.Helpers.Humanizer" Version="2.3.12" />
<PackageReference Include="Handlebars.Net.Helpers.Json" Version="2.3.11" /> <PackageReference Include="Handlebars.Net.Helpers.Json" Version="2.3.12" />
<PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.3.11" /> <PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.3.12" />
<PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.3.11" /> <PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.3.12" />
<PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.3.11" /> <PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.3.12" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -23,6 +23,7 @@
<!--<DelaySign>true</DelaySign>--> <!--<DelaySign>true</DelaySign>-->
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign> <PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageLicenseExpression>MIT</PackageLicenseExpression>
<Nullable>disable</Nullable>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
+18
View File
@@ -0,0 +1,18 @@
{
"help": "https://go.microsoft.com/fwlink/?linkid=866610",
"root": true,
"dependentFileProviders": {
"add": {
"addedExtension": {},
"pathSegment": {},
"fileSuffixToExtension": {
"add": {
".verified.txt": [
".cs"
]
}
}
}
}
}
@@ -5,8 +5,8 @@ using FluentAssertions;
using WireMock.Http; using WireMock.Http;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Http namespace WireMock.Net.Tests.Http;
{
public class ByteArrayContentHelperTests public class ByteArrayContentHelperTests
{ {
[Fact] [Fact]
@@ -41,4 +41,3 @@ namespace WireMock.Net.Tests.Http
(await result.ReadAsByteArrayAsync().ConfigureAwait(false)).Should().BeEquivalentTo(content); (await result.ReadAsByteArrayAsync().ConfigureAwait(false)).Should().BeEquivalentTo(content);
} }
} }
}
@@ -8,8 +8,8 @@ using WireMock.Types;
using WireMock.Util; using WireMock.Util;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Http namespace WireMock.Net.Tests.Http;
{
public class HttpRequestMessageHelperTests public class HttpRequestMessageHelperTests
{ {
private const string ClientIp = "::1"; private const string ClientIp = "::1";
@@ -161,4 +161,3 @@ namespace WireMock.Net.Tests.Http
Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/xml; charset=Ascii"); Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/xml; charset=Ascii");
} }
} }
}
@@ -1,10 +1,10 @@
using System.Net.Http.Headers; using System.Net.Http.Headers;
using FluentAssertions; using FluentAssertions;
using WireMock.Http; using WireMock.Http;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Http namespace WireMock.Net.Tests.Http;
{
public class StringContentHelperTests public class StringContentHelperTests
{ {
[Fact] [Fact]
@@ -36,4 +36,3 @@ namespace WireMock.Net.Tests.Http
result.ReadAsStringAsync().Result.Should().Be("test"); result.ReadAsStringAsync().Result.Should().Be("test");
} }
} }
}
@@ -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
}
]
@@ -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
}
]
+39 -9
View File
@@ -1,5 +1,10 @@
using FluentAssertions; #if !(NET452 || NET461 || NETCOREAPP3_1)
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Moq; using Moq;
using VerifyTests;
using VerifyXunit;
using WireMock.Handlers; using WireMock.Handlers;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Owin; using WireMock.Owin;
@@ -7,13 +12,17 @@ using WireMock.RequestBuilders;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Serialization; using WireMock.Serialization;
using WireMock.Settings; using WireMock.Settings;
using WireMock.Util;
using Xunit; using Xunit;
namespace WireMock.Net.Tests; namespace WireMock.Net.Tests;
[UsesVerify]
public class MappingBuilderTests 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<IFileSystemHandler> _fileSystemHandlerMock; private readonly Mock<IFileSystemHandler> _fileSystemHandlerMock;
@@ -23,6 +32,12 @@ public class MappingBuilderTests
{ {
_fileSystemHandlerMock = new Mock<IFileSystemHandler>(); _fileSystemHandlerMock = new Mock<IFileSystemHandler>();
var guidUtilsMock = new Mock<IGuidUtils>();
guidUtilsMock.Setup(g => g.NewGuid()).Returns(NewGuid);
var dateTimeUtilsMock = new Mock<IDateTimeUtils>();
dateTimeUtilsMock.SetupGet(d => d.UtcNow).Returns(UtcNow);
var settings = new WireMockServerSettings var settings = new WireMockServerSettings
{ {
FileSystemHandler = _fileSystemHandlerMock.Object, FileSystemHandler = _fileSystemHandlerMock.Object,
@@ -33,7 +48,14 @@ public class MappingBuilderTests
var mappingConverter = new MappingConverter(matcherMapper); var mappingConverter = new MappingConverter(matcherMapper);
var mappingToFileSaver = new MappingToFileSaver(settings, mappingConverter); 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() _sut.Given(Request.Create()
.WithPath("/foo") .WithPath("/foo")
@@ -45,24 +67,31 @@ public class MappingBuilderTests
); );
} }
[ModuleInitializer]
public static void ModuleInitializer()
{
VerifierSettings.DontScrubGuids();
VerifierSettings.DontScrubDateTimes();
}
[Fact] [Fact]
public void GetMappings() public Task GetMappings()
{ {
// Act // Act
var mappings = _sut.GetMappings(); var mappings = _sut.GetMappings();
// Assert // Verify
mappings.Should().HaveCount(1); return Verifier.Verify(mappings);
} }
[Fact] [Fact]
public void ToJson() public Task ToJson()
{ {
// Act // Act
var json = _sut.ToJson(); var json = _sut.ToJson();
// Assert // Verify
json.Should().NotBeEmpty(); return Verifier.VerifyJson(json);
} }
[Fact] [Fact]
@@ -134,3 +163,4 @@ public class MappingBuilderTests
_fileSystemHandlerMock.VerifyNoOtherCalls(); _fileSystemHandlerMock.VerifyNoOtherCalls();
} }
} }
#endif
@@ -2,8 +2,8 @@ using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
{
public class CSharpCodeMatcherTests public class CSharpCodeMatcherTests
{ {
[Fact] [Fact]
@@ -89,4 +89,3 @@ namespace WireMock.Net.Tests.Matchers
Check.That(patterns).ContainsExactly("x"); Check.That(patterns).ContainsExactly("x");
} }
} }
}
@@ -1,10 +1,9 @@
using AnyOfTypes;
using NFluent; using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
{
public class ContentTypeMatcherTests public class ContentTypeMatcherTests
{ {
[Theory] [Theory]
@@ -56,4 +55,3 @@ namespace WireMock.Net.Tests.Matchers
Check.That(patterns).ContainsExactly("x"); Check.That(patterns).ContainsExactly("x");
} }
} }
}
@@ -1,9 +1,9 @@
using NFluent; using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
{
public class ExactObjectMatcherTests public class ExactObjectMatcherTests
{ {
[Fact] [Fact]
@@ -62,4 +62,3 @@ namespace WireMock.Net.Tests.Matchers
Check.That(result).IsEqualTo(0.0); Check.That(result).IsEqualTo(0.0);
} }
} }
}
@@ -3,8 +3,8 @@ using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
{
public class JmesPathMatcherTests public class JmesPathMatcherTests
{ {
[Fact] [Fact]
@@ -163,4 +163,3 @@ namespace WireMock.Net.Tests.Matchers
Check.That(match).IsEqualTo(0.0); Check.That(match).IsEqualTo(0.0);
} }
} }
}
@@ -7,8 +7,8 @@ using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
{
public class JsonPartialMatcherTests public class JsonPartialMatcherTests
{ {
[Fact] [Fact]
@@ -419,4 +419,3 @@ namespace WireMock.Net.Tests.Matchers
Assert.Equal(0.0, match); Assert.Equal(0.0, match);
} }
} }
}
@@ -3,8 +3,8 @@ using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
{
public class LinqMatcherTests public class LinqMatcherTests
{ {
[Fact] [Fact]
@@ -109,4 +109,3 @@ namespace WireMock.Net.Tests.Matchers
Check.That(patterns).ContainsExactly("x"); Check.That(patterns).ContainsExactly("x");
} }
} }
}
@@ -1,9 +1,9 @@
using NFluent; using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
{
public class MatchBehaviourHelperTests public class MatchBehaviourHelperTests
{ {
[Fact] [Fact]
@@ -22,4 +22,3 @@ namespace WireMock.Net.Tests.Matchers
Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.RejectOnMatch, 1.0)).IsEqualTo(0.0); Check.That(MatchBehaviourHelper.Convert(MatchBehaviour.RejectOnMatch, 1.0)).IsEqualTo(0.0);
} }
} }
}
@@ -3,8 +3,8 @@ using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
{
public class NotNullOrEmptyMatcherTests public class NotNullOrEmptyMatcherTests
{ {
[Fact] [Fact]
@@ -81,4 +81,3 @@ namespace WireMock.Net.Tests.Matchers
patterns.Should().BeEmpty(); patterns.Should().BeEmpty();
} }
} }
}
@@ -4,8 +4,8 @@ using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
{
public class RegexMatcherTests public class RegexMatcherTests
{ {
[Fact] [Fact]
@@ -124,4 +124,3 @@ namespace WireMock.Net.Tests.Matchers
Check.That(result).IsEqualTo(0.0); Check.That(result).IsEqualTo(0.0);
} }
} }
}
@@ -1,11 +1,11 @@
using System.Linq; using System.Linq;
using FluentAssertions; using FluentAssertions;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
{
public class RequestMatchResultTests public class RequestMatchResultTests
{ {
[Fact] [Fact]
@@ -51,4 +51,3 @@ namespace WireMock.Net.Tests.Matchers
best.Should().Be(result2); best.Should().Be(result2);
} }
} }
}
@@ -2,8 +2,8 @@ using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
{
public class SimMetricsMatcherTests public class SimMetricsMatcherTests
{ {
[Fact] [Fact]
@@ -84,4 +84,3 @@ namespace WireMock.Net.Tests.Matchers
Check.That(result).IsEqualTo(0.0); Check.That(result).IsEqualTo(0.0);
} }
} }
}
@@ -5,8 +5,8 @@ using WireMock.Matchers;
using WireMock.Models; using WireMock.Models;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Matchers namespace WireMock.Net.Tests.Matchers;
{
public class WildcardMatcherTest public class WildcardMatcherTest
{ {
[Fact] [Fact]
@@ -136,4 +136,3 @@ namespace WireMock.Net.Tests.Matchers
Check.That(result).IsEqualTo(0.0); Check.That(result).IsEqualTo(0.0);
} }
} }
}
@@ -3,8 +3,8 @@ using NFluent;
using WireMock.RegularExpressions; using WireMock.RegularExpressions;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.RegularExpressions namespace WireMock.Net.Tests.RegularExpressions;
{
public class RegexExtendedTests public class RegexExtendedTests
{ {
/// <summary> /// <summary>
@@ -97,4 +97,3 @@ namespace WireMock.Net.Tests.RegularExpressions
Check.That(regexUpper.IsMatch(inputLower)).Equals(false); Check.That(regexUpper.IsMatch(inputLower)).Equals(false);
} }
} }
}
@@ -1,11 +1,11 @@
using System.Collections.Generic; using System.Collections.Generic;
using NFluent; using NFluent;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.RequestBuilders namespace WireMock.Net.Tests.RequestBuilders;
{
public class RequestBuilderUsingMethodTests public class RequestBuilderUsingMethodTests
{ {
[Fact] [Fact]
@@ -75,4 +75,3 @@ namespace WireMock.Net.Tests.RequestBuilders
Check.That(matchers.Count).IsEqualTo(0); Check.That(matchers.Count).IsEqualTo(0);
} }
} }
}
@@ -1,4 +1,4 @@
using FluentAssertions; using FluentAssertions;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using WireMock.Matchers; using WireMock.Matchers;
@@ -6,8 +6,8 @@ using WireMock.Matchers.Request;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.RequestBuilders namespace WireMock.Net.Tests.RequestBuilders;
{
public class RequestBuilderWithBodyTests public class RequestBuilderWithBodyTests
{ {
[Fact] [Fact]
@@ -41,4 +41,3 @@ namespace WireMock.Net.Tests.RequestBuilders
((RequestMessageBodyMatcher)matchers[0]).Matchers.Should().Contain(new[] { matcher1, matcher2 }); ((RequestMessageBodyMatcher)matchers[0]).Matchers.Should().Contain(new[] { matcher1, matcher2 });
} }
} }
}
@@ -1,12 +1,12 @@
using System.Collections.Generic; using System.Collections.Generic;
using NFluent; using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.RequestBuilders namespace WireMock.Net.Tests.RequestBuilders;
{
public class RequestBuilderWithCookieTests public class RequestBuilderWithCookieTests
{ {
[Fact] [Fact]
@@ -45,4 +45,3 @@ namespace WireMock.Net.Tests.RequestBuilders
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageCookieMatcher)); Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageCookieMatcher));
} }
} }
}
@@ -1,12 +1,12 @@
using System.Collections.Generic; using System.Collections.Generic;
using NFluent; using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.RequestBuilders namespace WireMock.Net.Tests.RequestBuilders;
{
public class RequestBuilderWithHeaderTests public class RequestBuilderWithHeaderTests
{ {
[Fact] [Fact]
@@ -81,4 +81,3 @@ namespace WireMock.Net.Tests.RequestBuilders
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher)); Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher));
} }
} }
}
@@ -1,12 +1,12 @@
using System.Collections.Generic; using System.Collections.Generic;
using NFluent; using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.RequestBuilders namespace WireMock.Net.Tests.RequestBuilders;
{
public class RequestBuilderWithParamTests public class RequestBuilderWithParamTests
{ {
[Fact] [Fact]
@@ -57,4 +57,3 @@ namespace WireMock.Net.Tests.RequestBuilders
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher)); Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher));
} }
} }
}
@@ -5,8 +5,8 @@ using WireMock.Matchers.Request;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.RequestBuilders namespace WireMock.Net.Tests.RequestBuilders;
{
public class RequestBuilderWithUrlTests public class RequestBuilderWithUrlTests
{ {
[Fact] [Fact]
@@ -57,4 +57,3 @@ namespace WireMock.Net.Tests.RequestBuilders
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher)); Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher));
} }
} }
}
@@ -1,4 +1,4 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Moq; using Moq;
using NFluent; using NFluent;
@@ -6,8 +6,8 @@ using WireMock.Matchers.Request;
using WireMock.Models; using WireMock.Models;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.RequestMatchers namespace WireMock.Net.Tests.RequestMatchers;
{
public class RequestMessageCompositeMatcherTests public class RequestMessageCompositeMatcherTests
{ {
private class Helper : RequestMessageCompositeMatcher private class Helper : RequestMessageCompositeMatcher
@@ -80,4 +80,3 @@ namespace WireMock.Net.Tests.RequestMatchers
requestMatcher2Mock.Verify(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>()), Times.Once); requestMatcher2Mock.Verify(rm => rm.GetMatchingScore(It.IsAny<RequestMessage>(), It.IsAny<RequestMatchResult>()), Times.Once);
} }
} }
}
@@ -1,12 +1,12 @@
using System.Collections.Generic; using System.Collections.Generic;
using NFluent; using NFluent;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.Models; using WireMock.Models;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.RequestMatchers namespace WireMock.Net.Tests.RequestMatchers;
{
public class RequestMessageCookieMatcherTests public class RequestMessageCookieMatcherTests
{ {
[Fact] [Fact]
@@ -151,4 +151,3 @@ namespace WireMock.Net.Tests.RequestMatchers
Check.That(score).IsEqualTo(1.0d); Check.That(score).IsEqualTo(1.0d);
} }
} }
}
@@ -7,8 +7,8 @@ using WireMock.Owin;
using WireMock.Types; using WireMock.Types;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.RequestMatchers namespace WireMock.Net.Tests.RequestMatchers;
{
public class RequestMessageParamMatcherTests public class RequestMessageParamMatcherTests
{ {
[Fact] [Fact]
@@ -196,4 +196,3 @@ namespace WireMock.Net.Tests.RequestMatchers
score.Should().Be(1.0); score.Should().Be(1.0);
} }
} }
}
@@ -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
}
}
@@ -0,0 +1,14 @@
{
Request: {
ClientIP: ::1,
Path: /,
AbsolutePath: /,
Url: http://localhost/,
AbsoluteUrl: http://localhost/,
Method: get
},
Response: {
BodyAsFile: test,
DetectedBodyType: File
}
}
@@ -0,0 +1,16 @@
{
Request: {
ClientIP: ::1,
Path: /,
AbsolutePath: /,
Url: http://localhost/,
AbsoluteUrl: http://localhost/,
Method: post,
BodyAsBytes: AA==,
DetectedBodyType: Bytes
},
Response: {
Body: Func<IRequestMessage, string>,
DetectedBodyType: String
}
}
@@ -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
}
}
@@ -1,7 +1,10 @@
using FluentAssertions; #if !(NET452 || NET461)
using NFluent; using System.Threading.Tasks;
using VerifyTests;
using VerifyXunit;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Models; using WireMock.Models;
using WireMock.Net.Tests.VerifyExtensions;
using WireMock.Owin; using WireMock.Owin;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Serialization; using WireMock.Serialization;
@@ -11,8 +14,15 @@ using Xunit;
namespace WireMock.Net.Tests.Serialization; namespace WireMock.Net.Tests.Serialization;
[UsesVerify]
public class LogEntryMapperTests public class LogEntryMapperTests
{ {
private static readonly VerifySettings VerifySettings = new();
static LogEntryMapperTests()
{
VerifySettings.Init<LogEntryMapperTests>();
}
private readonly IWireMockMiddlewareOptions _options = new WireMockMiddlewareOptions(); private readonly IWireMockMiddlewareOptions _options = new WireMockMiddlewareOptions();
private readonly LogEntryMapper _sut; private readonly LogEntryMapper _sut;
@@ -23,7 +33,7 @@ public class LogEntryMapperTests
} }
[Fact] [Fact]
public void LogEntryMapper_Map_LogEntry_Check_BodyTypeBytes() public Task LogEntryMapper_Map_LogEntry_Check_BodyTypeBytes()
{ {
// Assign // Assign
var logEntry = new LogEntry var logEntry = new LogEntry
@@ -51,23 +61,12 @@ public class LogEntryMapperTests
// Act // Act
var result = _sut.Map(logEntry); var result = _sut.Map(logEntry);
// Assert // Verify
Check.That(result.Request.DetectedBodyType).IsEqualTo("Bytes"); return Verifier.Verify(result, VerifySettings);
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();
} }
[Fact] [Fact]
public void LogEntryMapper_Map_LogEntry_Check_ResponseBodyTypeFile() public Task LogEntryMapper_Map_LogEntry_Check_ResponseBodyTypeFile()
{ {
// Assign // Assign
var logEntry = new LogEntry var logEntry = new LogEntry
@@ -86,23 +85,12 @@ public class LogEntryMapperTests
// Act // Act
var result = _sut.Map(logEntry); var result = _sut.Map(logEntry);
// Assert // Verify
Check.That(result.Request.DetectedBodyType).IsNull(); return Verifier.Verify(result, VerifySettings);
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");
} }
[Fact] [Fact]
public void LogEntryMapper_Map_LogEntry_WithFault() public Task LogEntryMapper_Map_LogEntry_WithFault()
{ {
// Assign // Assign
var logEntry = new LogEntry var logEntry = new LogEntry
@@ -123,13 +111,12 @@ public class LogEntryMapperTests
// Act // Act
var result = _sut.Map(logEntry); var result = _sut.Map(logEntry);
// Assert // Verify
result.Response.FaultType.Should().Be("EMPTY_RESPONSE"); return Verifier.Verify(result, VerifySettings);
result.Response.FaultPercentage.Should().Be(0.5);
} }
[Fact] [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 // Assign
var options = new WireMockMiddlewareOptions var options = new WireMockMiddlewareOptions
@@ -163,7 +150,8 @@ public class LogEntryMapperTests
// Act // Act
var result = new LogEntryMapper(options).Map(logEntry); var result = new LogEntryMapper(options).Map(logEntry);
// Assert // Verify
result.Response.Body.Should().Be(isFuncUsed); return Verifier.Verify(result, VerifySettings);
} }
} }
#endif
@@ -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
@@ -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()
);
@@ -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()
);
@@ -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()
);
@@ -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()
);
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -1,7 +1,12 @@
#if !(NET452 || NET461 || NETCOREAPP3_1)
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
using FluentAssertions; using FluentAssertions;
using VerifyTests;
using VerifyXunit;
using WireMock.Models; using WireMock.Models;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
@@ -13,9 +18,10 @@ using Xunit;
namespace WireMock.Net.Tests.Serialization; 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 WireMockServerSettings _settings = new();
private readonly MappingConverter _sut; private readonly MappingConverter _sut;
@@ -26,7 +32,7 @@ public class MappingConverterTests
} }
[Fact] [Fact]
public void ToMappingModel_With_SingleWebHook() public Task ToMappingModel_With_SingleWebHook()
{ {
// Assign // Assign
var request = Request.Create(); 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 // Act
var model = _sut.ToMappingModel(mapping); var model = _sut.ToMappingModel(mapping);
@@ -74,10 +80,13 @@ public class MappingConverterTests
model.Webhook.Request.Headers.Should().HaveCount(2); model.Webhook.Request.Headers.Should().HaveCount(2);
model.Webhook.Request.Body.Should().Be("b"); model.Webhook.Request.Body.Should().Be("b");
model.Webhook.Request.BodyAsJson.Should().BeNull(); model.Webhook.Request.BodyAsJson.Should().BeNull();
// Verify
return Verifier.Verify(model);
} }
[Fact] [Fact]
public void ToMappingModel_With_MultipleWebHooks() public Task ToMappingModel_With_MultipleWebHooks()
{ {
// Assign // Assign
var request = Request.Create(); 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 // Act
var model = _sut.ToMappingModel(mapping); 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.Url.Should().Be("https://test2.com");
model.Webhooks[1].Request.Headers.Should().HaveCount(2); model.Webhooks[1].Request.Headers.Should().HaveCount(2);
model.Webhooks[1].Request.Body.Should().Be("2"); model.Webhooks[1].Request.Body.Should().Be("2");
// Verify
return Verifier.Verify(model);
} }
[Fact] [Fact]
public void ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel() public Task ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel()
{ {
// Assign // Assign
var title = "my-title"; var title = "my-title";
var description = "my-description"; var description = "my-description";
var request = Request.Create(); var request = Request.Create();
var response = Response.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 // Act
var model = _sut.ToMappingModel(mapping); var model = _sut.ToMappingModel(mapping);
@@ -167,15 +179,18 @@ public class MappingConverterTests
model.Should().NotBeNull(); model.Should().NotBeNull();
model.Title.Should().Be(title); model.Title.Should().Be(title);
model.Description.Should().Be(description); model.Description.Should().Be(description);
// Verify
return Verifier.Verify(model);
} }
[Fact] [Fact]
public void ToMappingModel_WithPriority_ReturnsPriority() public Task ToMappingModel_WithPriority_ReturnsPriority()
{ {
// Assign // Assign
var request = Request.Create(); var request = Request.Create();
var response = Response.Create().WithBodyAsJson(new { x = "x" }).WithTransformer(); 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 // Act
var model = _sut.ToMappingModel(mapping); var model = _sut.ToMappingModel(mapping);
@@ -184,13 +199,16 @@ public class MappingConverterTests
model.Should().NotBeNull(); model.Should().NotBeNull();
model.Priority.Should().Be(42); model.Priority.Should().Be(42);
model.Response.UseTransformer.Should().BeTrue(); model.Response.UseTransformer.Should().BeTrue();
// Verify
return Verifier.Verify(model);
} }
[Fact] [Fact]
public void ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings() public Task ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings()
{ {
// Assign // Assign
var start = DateTime.Now; var start = new DateTime(2023, 1, 14, 15, 16, 17);
var ttl = 100; var ttl = 100;
var end = start.AddSeconds(ttl); var end = start.AddSeconds(ttl);
var request = Request.Create(); var request = Request.Create();
@@ -201,7 +219,7 @@ public class MappingConverterTests
End = end, End = end,
TTL = ttl 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 // Act
var model = _sut.ToMappingModel(mapping); var model = _sut.ToMappingModel(mapping);
@@ -212,6 +230,9 @@ public class MappingConverterTests
model.TimeSettings!.Start.Should().Be(start); model.TimeSettings!.Start.Should().Be(start);
model.TimeSettings.End.Should().Be(end); model.TimeSettings.End.Should().Be(end);
model.TimeSettings.TTL.Should().Be(ttl); model.TimeSettings.TTL.Should().Be(ttl);
// Verify
return Verifier.Verify(model);
} }
[Fact] [Fact]
@@ -241,13 +262,13 @@ public class MappingConverterTests
} }
[Fact] [Fact]
public void ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel() public Task ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel()
{ {
// Assign // Assign
var delay = 1000; var delay = 1000;
var request = Request.Create(); var request = Request.Create();
var response = Response.Create().WithDelay(delay); 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 // Act
var model = _sut.ToMappingModel(mapping); var model = _sut.ToMappingModel(mapping);
@@ -255,16 +276,19 @@ public class MappingConverterTests
// Assert // Assert
model.Should().NotBeNull(); model.Should().NotBeNull();
model.Response.Delay.Should().Be(delay); model.Response.Delay.Should().Be(delay);
// Verify
return Verifier.Verify(model);
} }
[Fact] [Fact]
public void ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel() public Task ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel()
{ {
// Assign // Assign
int minimumDelay = 1000; int minimumDelay = 1000;
var request = Request.Create(); var request = Request.Create();
var response = Response.Create().WithRandomDelay(minimumDelay); 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 // Act
var model = _sut.ToMappingModel(mapping); var model = _sut.ToMappingModel(mapping);
@@ -274,17 +298,20 @@ public class MappingConverterTests
model.Response.Delay.Should().BeNull(); model.Response.Delay.Should().BeNull();
model.Response.MinimumRandomDelay.Should().Be(minimumDelay); model.Response.MinimumRandomDelay.Should().Be(minimumDelay);
model.Response.MaximumRandomDelay.Should().Be(60_000); model.Response.MaximumRandomDelay.Should().Be(60_000);
// Verify
return Verifier.Verify(model);
} }
[Fact] [Fact]
public void ToMappingModel_WithRandomDelay_ReturnsCorrectModel() public Task ToMappingModel_WithRandomDelay_ReturnsCorrectModel()
{ {
// Assign // Assign
int minimumDelay = 1000; int minimumDelay = 1000;
int maximumDelay = 2000; int maximumDelay = 2000;
var request = Request.Create(); var request = Request.Create();
var response = Response.Create().WithRandomDelay(minimumDelay, maximumDelay); 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 // Act
var model = _sut.ToMappingModel(mapping); var model = _sut.ToMappingModel(mapping);
@@ -294,5 +321,9 @@ public class MappingConverterTests
model.Response.Delay.Should().BeNull(); model.Response.Delay.Should().BeNull();
model.Response.MinimumRandomDelay.Should().Be(minimumDelay); model.Response.MinimumRandomDelay.Should().Be(minimumDelay);
model.Response.MaximumRandomDelay.Should().Be(maximumDelay); model.Response.MaximumRandomDelay.Should().Be(maximumDelay);
// Verify
return Verifier.Verify(model);
} }
} }
#endif
@@ -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: <RequestType>Auth</RequestType>,
IgnoreCase: false
}
}
},
Response: {}
}
@@ -1,8 +1,10 @@
#if !(NET452 || NET461 || NETCOREAPP3_1)
using System; using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Moq; using Moq;
using Newtonsoft.Json; using VerifyTests;
using System.IO; using VerifyXunit;
using FluentAssertions;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using WireMock.Serialization; using WireMock.Serialization;
@@ -12,6 +14,7 @@ using Xunit;
namespace WireMock.Net.Tests.Serialization; namespace WireMock.Net.Tests.Serialization;
[UsesVerify]
public class ProxyMappingConverterTests public class ProxyMappingConverterTests
{ {
private readonly WireMockServerSettings _settings = new(); private readonly WireMockServerSettings _settings = new();
@@ -33,8 +36,15 @@ public class ProxyMappingConverterTests
_sut = new ProxyMappingConverter(_settings, guidUtilsMock.Object, dateTimeUtilsMock.Object); _sut = new ProxyMappingConverter(_settings, guidUtilsMock.Object, dateTimeUtilsMock.Object);
} }
[ModuleInitializer]
public static void ModuleInitializer()
{
VerifierSettings.DontScrubGuids();
VerifierSettings.DontScrubDateTimes();
}
[Fact] [Fact]
public void ToMapping_UseDefinedRequestMatchers_True() public Task ToMapping_UseDefinedRequestMatchers_True()
{ {
// Arrange // Arrange
var proxyAndRecordSettings = new ProxyAndRecordSettings var proxyAndRecordSettings = new ProxyAndRecordSettings
@@ -49,7 +59,7 @@ public class ProxyMappingConverterTests
.WithParam("p2", "p2-v") .WithParam("p2", "p2-v")
.WithHeader("Content-Type", new ContentTypeMatcher("text/plain")) .WithHeader("Content-Type", new ContentTypeMatcher("text/plain"))
.WithCookie("c", "x") .WithCookie("c", "x")
.WithBody(new RegexMatcher("<RequestType>Auth</RequestType")); .WithBody(new RegexMatcher("<RequestType>Auth</RequestType>"));
var mappingMock = new Mock<IMapping>(); var mappingMock = new Mock<IMapping>();
mappingMock.SetupGet(m => m.RequestMatcher).Returns(request); mappingMock.SetupGet(m => m.RequestMatcher).Returns(request);
@@ -65,9 +75,9 @@ public class ProxyMappingConverterTests
// Assert // Assert
var model = _mappingConverter.ToMappingModel(proxyMapping); 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);
} }
} }
#endif
@@ -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
}
}
@@ -0,0 +1,16 @@
{
Request: {
Url: https://localhost,
Method: get,
Headers: {
x: [
y
]
},
BodyData: {
BodyAsString: test,
DetectedBodyType: String,
DetectedBodyTypeFromContentType: Bytes
}
}
}
@@ -0,0 +1,18 @@
{
Request: {
Url: https://localhost,
Method: get,
Headers: {
x: [
y
]
},
BodyData: {
BodyAsString: test,
DetectedBodyType: String,
DetectedBodyTypeFromContentType: Bytes
},
UseTransformer: true,
TransformerReplaceNodeOptions: Evaluate
}
}
@@ -0,0 +1,16 @@
{
Request: {
Url: https://localhost,
Method: get,
Headers: {
x: y
},
BodyAsJson: {
n: 12345
},
TransformerReplaceNodeOptions: EvaluateAndTryToConvert,
Delay: 4,
MinimumRandomDelay: 5,
MaximumRandomDelay: 6
}
}
@@ -1,5 +1,9 @@
#if !(NET452 || NET461 || NETCOREAPP3_1)
using System.Collections.Generic; using System.Collections.Generic;
using FluentAssertions; using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using VerifyTests;
using VerifyXunit;
using WireMock.Admin.Mappings; using WireMock.Admin.Mappings;
using WireMock.Models; using WireMock.Models;
using WireMock.Serialization; using WireMock.Serialization;
@@ -9,10 +13,18 @@ using Xunit;
namespace WireMock.Net.Tests.Serialization; namespace WireMock.Net.Tests.Serialization;
[UsesVerify]
public class WebhookMapperTests public class WebhookMapperTests
{ {
[ModuleInitializer]
public static void ModuleInitializer()
{
VerifierSettings.DontScrubGuids();
VerifierSettings.DontScrubDateTimes();
}
[Fact] [Fact]
public void WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsFalse() public Task WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsFalse()
{ {
// Assign // Assign
var model = new WebhookModel var model = new WebhookModel
@@ -32,17 +44,12 @@ public class WebhookMapperTests
var result = WebhookMapper.Map(model); var result = WebhookMapper.Map(model);
result.Request.Url.Should().Be("https://localhost"); // Verify
result.Request.Method.Should().Be("get"); return Verifier.Verify(result);
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();
} }
[Fact] [Fact]
public void WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsTrue() public Task WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsTrue()
{ {
// Assign // Assign
var model = new WebhookModel var model = new WebhookModel
@@ -62,18 +69,12 @@ public class WebhookMapperTests
var result = WebhookMapper.Map(model); var result = WebhookMapper.Map(model);
result.Request.Url.Should().Be("https://localhost"); // Verify
result.Request.Method.Should().Be("get"); return Verifier.Verify(result);
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);
} }
[Fact] [Fact]
public void WebhookMapper_Map_WebhookModel_BodyAsJson() public Task WebhookMapper_Map_WebhookModel_BodyAsJson()
{ {
// Assign // Assign
var model = new WebhookModel var model = new WebhookModel
@@ -95,19 +96,12 @@ public class WebhookMapperTests
var result = WebhookMapper.Map(model); var result = WebhookMapper.Map(model);
result.Request.Url.Should().Be("https://localhost"); // Verify
result.Request.Method.Should().Be("get"); return Verifier.Verify(result);
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);
} }
[Fact] [Fact]
public void WebhookMapper_Map_Webhook_To_Model() public Task WebhookMapper_Map_Webhook_To_Model()
{ {
// Assign // Assign
var webhook = new Webhook var webhook = new Webhook
@@ -134,12 +128,8 @@ public class WebhookMapperTests
var result = WebhookMapper.Map(webhook); var result = WebhookMapper.Map(webhook);
result.Request.Url.Should().Be("https://localhost"); // Verify
result.Request.Method.Should().Be("get"); return Verifier.Verify(result);
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);
} }
} }
#endif
@@ -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": "<RequestType>Auth</RequestType",
"IgnoreCase": false
}
}
},
"Response": {}
}
@@ -9,8 +9,8 @@ using WireMock.Types;
using WireMock.Util; using WireMock.Util;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Util namespace WireMock.Net.Tests.Util;
{
public class BodyParserTests public class BodyParserTests
{ {
[Theory] [Theory]
@@ -290,4 +290,3 @@ Content-Type: text/html
Check.That(BodyParser.ShouldParseBody(method, false)).IsTrue(); Check.That(BodyParser.ShouldParseBody(method, false)).IsTrue();
} }
} }
}
@@ -1,10 +1,10 @@
using System.Text; using System.Text;
using FluentAssertions; using FluentAssertions;
using WireMock.Util; using WireMock.Util;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Util namespace WireMock.Net.Tests.Util;
{
public class BytesEncodingUtilsTests public class BytesEncodingUtilsTests
{ {
[Fact] [Fact]
@@ -27,4 +27,3 @@ namespace WireMock.Net.Tests.Util
encoding.Should().BeNull(); encoding.Should().BeNull();
} }
} }
}
@@ -1,11 +1,11 @@
using FluentAssertions; using FluentAssertions;
using System; using System;
using System.Net; using System.Net;
using WireMock.Util; using WireMock.Util;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Util namespace WireMock.Net.Tests.Util;
{
/// <summary> /// <summary>
/// Based on https://raw.githubusercontent.com/tmenier/Flurl/129565361e135e639f1d44a35a78aea4302ac6ca/Test/Flurl.Test/Http/HttpStatusRangeParserTests.cs /// Based on https://raw.githubusercontent.com/tmenier/Flurl/129565361e135e639f1d44a35a78aea4302ac6ca/Test/Flurl.Test/Http/HttpStatusRangeParserTests.cs
/// </summary> /// </summary>
@@ -72,4 +72,3 @@ namespace WireMock.Net.Tests.Util
Assert.Throws<ArgumentException>(() => HttpStatusRangeParser.IsMatch(pattern, 100)); Assert.Throws<ArgumentException>(() => HttpStatusRangeParser.IsMatch(pattern, 100));
} }
} }
}
@@ -2,8 +2,8 @@ using FluentAssertions;
using WireMock.Util; using WireMock.Util;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Util namespace WireMock.Net.Tests.Util;
{
public class StringUtilsTests public class StringUtilsTests
{ {
[Theory] [Theory]
@@ -101,4 +101,3 @@ namespace WireMock.Net.Tests.Util
quote.Should().Be('"'); quote.Should().Be('"');
} }
} }
}
@@ -1,4 +1,4 @@
using System; using System;
#if NET452 #if NET452
using Microsoft.Owin; using Microsoft.Owin;
#else #else
@@ -8,8 +8,8 @@ using NFluent;
using WireMock.Util; using WireMock.Util;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Util namespace WireMock.Net.Tests.Util;
{
public class UrlUtilsTests public class UrlUtilsTests
{ {
[Fact] [Fact]
@@ -54,4 +54,3 @@ namespace WireMock.Net.Tests.Util
Check.That(result.AbsoluteUrl.ToString()).Equals("https://localhost:1234/a/b?x=0"); Check.That(result.AbsoluteUrl.ToString()).Equals("https://localhost:1234/a/b?x=0");
} }
} }
}
@@ -0,0 +1,15 @@
#if !(NET452 || NET461)
using VerifyTests;
namespace WireMock.Net.Tests.VerifyExtensions;
internal static class VerifySettingsExtensions
{
public static void Init<T>(this VerifySettings verifySettings)
{
verifySettings.DontScrubDateTimes();
verifySettings.DontScrubDateTimes();
verifySettings.UseDirectory($"{typeof(T).Name}.Verify");
}
}
#endif
@@ -24,6 +24,18 @@
<DefineConstants>NETFRAMEWORK</DefineConstants> <DefineConstants>NETFRAMEWORK</DefineConstants>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<!-- https://stackoverflow.com/questions/59406201/filenesting-not-working-for-class-or-shared-library-projects -->
<ProjectCapability Include="ConfigurableFileNesting" />
<ProjectCapability Include="ConfigurableFileNestingFeatureEnabled" />
</ItemGroup>
<!--<ItemGroup>
<Compile Update="**\*.*.verified.txt">
<DependentUpon>$([System.String]::Copy((Filename)*.cs))</DependentUpon>
</Compile>
</ItemGroup>-->
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\src\WireMock.Net.Abstractions\WireMock.Net.Abstractions.csproj" /> <ProjectReference Include="..\..\src\WireMock.Net.Abstractions\WireMock.Net.Abstractions.csproj" />
<ProjectReference Include="..\..\src\WireMock.Net.FluentAssertions\WireMock.Net.FluentAssertions.csproj" /> <ProjectReference Include="..\..\src\WireMock.Net.FluentAssertions\WireMock.Net.FluentAssertions.csproj" />
@@ -41,12 +53,6 @@
</PackageReference> </PackageReference>
<PackageReference Include="CultureAwareTesting.xUnit" Version="0.0.1" /> <PackageReference Include="CultureAwareTesting.xUnit" Version="0.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.core" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.2.0"> <PackageReference Include="coverlet.collector" Version="3.2.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -66,10 +72,23 @@
<PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="3.1.0" /> <PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="3.1.0" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="FluentAssertions" Version="5.10.3" /> <PackageReference Include="FluentAssertions" Version="5.10.3" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.core" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net461'"> <ItemGroup Condition="'$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net461'">
<PackageReference Include="FluentAssertions" Version="6.7.0" /> <PackageReference Include="FluentAssertions" Version="6.9.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.core" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Verify.Xunit" Version="19.6.0" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' != 'net452'"> <ItemGroup Condition="'$(TargetFramework)' != 'net452'">
@@ -81,9 +100,6 @@
<None Update="responsebody.json"> <None Update="responsebody.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<None Update="Serialization\files\proxy.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings.org\*.json"> <None Update="__admin\mappings.org\*.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
@@ -108,7 +124,6 @@
<ItemGroup> <ItemGroup>
<Folder Include="Pact\files\" /> <Folder Include="Pact\files\" />
<Folder Include="Serialization\files\" />
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -146,7 +146,7 @@ public class WireMockServerAdminTests
string responseBodyFilePath = Path.Combine(GetCurrentFolder(), "responsebody.json"); string responseBodyFilePath = Path.Combine(GetCurrentFolder(), "responsebody.json");
dynamic jsonObj = JsonConvert.DeserializeObject(json); dynamic jsonObj = JsonConvert.DeserializeObject(json)!;
jsonObj["Response"]["BodyAsFile"] = responseBodyFilePath; jsonObj["Response"]["BodyAsFile"] = responseBodyFilePath;
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented); string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
@@ -1,11 +1,11 @@
using System; using System;
using FluentAssertions; using FluentAssertions;
using WireMock.Admin.Mappings; using WireMock.Admin.Mappings;
using WireMock.Server; using WireMock.Server;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.WithMapping namespace WireMock.Net.Tests.WithMapping;
{
public class WireMockServerWithMappingTests public class WireMockServerWithMappingTests
{ {
[Fact] [Fact]
@@ -49,7 +49,7 @@ namespace WireMock.Net.Tests.WithMapping
//((PathModel)m.Request.Path).Matchers.OfType<WildcardMatcher>().First().GetPatterns().First() == "/foo*" //((PathModel)m.Request.Path).Matchers.OfType<WildcardMatcher>().First().GetPatterns().First() == "/foo*"
// m.Request.Body.Matchers.OfType<ExactMatcher>().First().GetPatterns().First() == pattern && // m.Request.Body.Matchers.OfType<ExactMatcher>().First().GetPatterns().First() == pattern &&
m.Response.Body == response && m.Response.Body == response &&
(int)m.Response.StatusCode == 201 (int?)m.Response.StatusCode == 201
); );
server.Stop(); server.Stop();
@@ -86,7 +86,7 @@ namespace WireMock.Net.Tests.WithMapping
// Assert // Assert
server.MappingModels.Should().HaveCount(1).And.Contain(m => server.MappingModels.Should().HaveCount(1).And.Contain(m =>
m.Guid == Guid.Parse("532889c2-f84d-4dc8-b847-9ea2c6aca7d5") && m.Guid == Guid.Parse("532889c2-f84d-4dc8-b847-9ea2c6aca7d5") &&
(int)m.Response.StatusCode == 201 (int?)m.Response.StatusCode == 201
); );
server.Stop(); server.Stop();
@@ -128,4 +128,3 @@ namespace WireMock.Net.Tests.WithMapping
server.Stop(); server.Stop();
} }
} }
}