Compare commits

...

11 Commits
1.5.5 ... 1.5.8

Author SHA1 Message Date
Stef Heyenrath
dd1a6fa508 1.5.8 2022-10-16 09:13:18 +02:00
Stef Heyenrath
36037627bc WebHook - Transform Url (#824)
* WebHook - Url

* .
2022-10-15 08:55:05 +02:00
Stef Heyenrath
55afc8041f ExactMatcher : IgnoreCase (#817)
* ...

* mm

* fix some null warnings

* fx
2022-10-15 08:23:58 +02:00
Stef Heyenrath
b523ab9125 Some fixes to WireMock.Net.Assertions (#816)
* Add extra unit test for UsingPost

* .X

* ok

* ok2

* header
2022-10-15 08:21:48 +02:00
Stef Heyenrath
14dd619763 1.5.7 2022-10-11 09:57:11 +02:00
Stef Heyenrath
430c01a461 Add implicit operators to WireMockList (#823)
* Add implicit operators to WireMockList

* .
2022-10-01 10:50:18 +02:00
Stef Heyenrath
f7b04f3234 Add UseDefinedRequestMatchers to ProxyAndRecordSettings (#821)
* .

* UseDefinedRequestMatchers

* ok

* .

* ClientIP

* t

* fix ut

* .

* cf

* cf2
2022-09-30 11:25:11 +02:00
Stef Heyenrath
c0b18631a3 Add option to run the server on http & https (#818)
* HostingProtocol.HttpAndHttps

* .

* .

* .

* HostingScheme
2022-09-26 14:24:45 +02:00
Stef Heyenrath
fd996ab4ed 1.5.6 2022-09-12 20:45:26 +02:00
Stef Heyenrath
a57626c63a 1.5.6 2022-09-12 20:38:45 +02:00
Stef Heyenrath
98a0f2fa28 WebHook : UseFireAndForget + Delay (#803)
* UseFireAndForget

* ...

* delay

* async

* updated code accorsing to proposal

* Change nuget to package reference for WireMock.Net.Console.Net472.Classic, move the new FireAndForget into the main mapping, out of individual webhook mappings making it all or nothing, update tests, change Middleware to await or not the firing of all webhooks. Update models as needed. (#804)

Co-authored-by: Matt Philmon <Matt_Philmon@carmax.com>

* small update

* Tweak middleware and fix bug in example (#806)

Co-authored-by: Matt Philmon <Matt_Philmon@carmax.com>

* .ConfigureAwait(false)

Co-authored-by: mattisking <mattisking@gmail.com>
Co-authored-by: Matt Philmon <Matt_Philmon@carmax.com>
2022-09-12 20:30:40 +02:00
74 changed files with 2563 additions and 1542 deletions

View File

@@ -1,3 +1,23 @@
# 1.5.8 (16 October 2022)
- [#816](https://github.com/WireMock-Net/WireMock.Net/pull/816) - Some fixes to WireMock.Net.Assertions [feature] contributed by [StefH](https://github.com/StefH)
- [#817](https://github.com/WireMock-Net/WireMock.Net/pull/817) - ExactMatcher : IgnoreCase [feature] contributed by [StefH](https://github.com/StefH)
- [#824](https://github.com/WireMock-Net/WireMock.Net/pull/824) - WebHook - Transform Url [feature] contributed by [StefH](https://github.com/StefH)
- [#814](https://github.com/WireMock-Net/WireMock.Net/issues/814) - WithHeader cannot handle multiple requests with the same header key values [bug]
- [#815](https://github.com/WireMock-Net/WireMock.Net/issues/815) - Why does UsingMethod check _callscount? [bug]
- [#822](https://github.com/WireMock-Net/WireMock.Net/issues/822) - Webhook with generic url, body and custom header values [feature]
# 1.5.7 (11 October 2022)
- [#818](https://github.com/WireMock-Net/WireMock.Net/pull/818) - Add option to run the server on http &amp; https [feature] contributed by [StefH](https://github.com/StefH)
- [#821](https://github.com/WireMock-Net/WireMock.Net/pull/821) - Add UseDefinedRequestMatchers to ProxyAndRecordSettings [feature] contributed by [StefH](https://github.com/StefH)
- [#823](https://github.com/WireMock-Net/WireMock.Net/pull/823) - Add implicit operators to WireMockList contributed by [StefH](https://github.com/StefH)
- [#819](https://github.com/WireMock-Net/WireMock.Net/issues/819) - Can I preserve Mapping title and matchers for proxy response? [feature]
# 1.5.6 (12 September 2022)
- [#803](https://github.com/WireMock-Net/WireMock.Net/pull/803) - WebHook : UseFireAndForget + Delay [feature] contributed by [StefH](https://github.com/StefH)
- [#804](https://github.com/WireMock-Net/WireMock.Net/pull/804) - Change nuget to package reference for WireMock.Net.Console.Net472.Cla&#8230; [feature] contributed by [mattisking](https://github.com/mattisking)
- [#806](https://github.com/WireMock-Net/WireMock.Net/pull/806) - Tweak middleware and fix bug in example [feature] contributed by [mattisking](https://github.com/mattisking)
- [#801](https://github.com/WireMock-Net/WireMock.Net/issues/801) - Webhook Delays [feature]
# 1.5.5 (03 September 2022)
- [#798](https://github.com/WireMock-Net/WireMock.Net/pull/798) - Add support to use 'mapping' object in in reponse templating [feature] contributed by [StefH](https://github.com/StefH)
- [#800](https://github.com/WireMock-Net/WireMock.Net/pull/800) - Bump Microsoft.Owin from 4.1.1 to 4.2.2 in /src/WireMock.Net (net46) [dependencies] contributed by [dependabot[bot]](https://github.com/apps/dependabot)

View File

@@ -4,7 +4,7 @@
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>1.5.5</VersionPrefix>
<VersionPrefix>1.5.8</VersionPrefix>
<PackageIcon>WireMock.Net-Logo.png</PackageIcon>
<PackageProjectUrl>https://github.com/WireMock-Net/WireMock.Net</PackageProjectUrl>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>

View File

@@ -1,6 +1,6 @@
rem https://github.com/StefH/GitHubReleaseNotes
SET version=1.5.5
SET version=1.5.8
GitHubReleaseNotes --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc duplicate --version %version% --token %GH_TOKEN%

View File

@@ -1,7 +1,9 @@
# 1.5.5 (03 September 2022)
- #798 Add support to use 'mapping' object in in reponse templating [feature]
- #800 Bump Microsoft.Owin from 4.1.1 to 4.2.2 in /src/WireMock.Net (net46) [dependencies]
- #802 Add assertions for request methods
- #772 How to get matched mapping by HttpRequest or HttpRequestMessage [feature]
# 1.5.8 (16 October 2022)
- #816 Some fixes to WireMock.Net.Assertions [feature]
- #817 ExactMatcher : IgnoreCase [feature]
- #824 WebHook - Transform Url [feature]
- #814 WithHeader cannot handle multiple requests with the same header key values [bug]
- #815 Why does UsingMethod check _callscount? [bug]
- #822 Webhook with generic url, body and custom header values [feature]
The full release notes can be found here: https://github.com/WireMock-Net/WireMock.Net/blob/master/CHANGELOG.md

View File

@@ -0,0 +1,8 @@
{
"profiles": {
"WSL": {
"commandName": "WSL2",
"distributionName": ""
}
}
}

View File

@@ -6,6 +6,7 @@ using System.Threading.Tasks;
using Newtonsoft.Json;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.Models;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
@@ -39,6 +40,19 @@ namespace WireMock.Net.ConsoleApplication
var s = WireMockServer.Start();
s.Stop();
var httpAndHttpsWithPort = WireMockServer.Start(new WireMockServerSettings
{
HostingScheme = HostingScheme.HttpAndHttps,
Port = 12399
});
httpAndHttpsWithPort.Stop();
var httpAndHttpsFree = WireMockServer.Start(new WireMockServerSettings
{
HostingScheme = HostingScheme.HttpAndHttps
});
httpAndHttpsFree.Stop();
string url1 = "http://localhost:9091/";
string url2 = "http://localhost:9092/";
string url3 = "https://localhost:9443/";
@@ -576,6 +590,40 @@ namespace WireMock.Net.ConsoleApplication
};
}));
server.Given(Request.Create().WithPath(new WildcardMatcher("/multi-webhook", true)).UsingPost())
.WithWebhook(new[] {
new Webhook()
{
Request = new WebhookRequest
{
Url = "http://localhost:12345/foo1",
Method = "post",
BodyData = new BodyData
{
BodyAsString = "OK 1!", DetectedBodyType = BodyType.String
},
Delay = 1000
}
},
new Webhook()
{
Request = new WebhookRequest
{
Url = "http://localhost:12345/foo2",
Method = "post",
BodyData = new BodyData
{
BodyAsString = "OK 2!",
DetectedBodyType = BodyType.String
},
MinimumRandomDelay = 3000,
MaximumRandomDelay = 7000
}
}
})
.WithWebhookFireAndForget(true)
.RespondWith(Response.Create().WithBody("a-response"));
System.Console.WriteLine(JsonConvert.SerializeObject(server.MappingModels, Formatting.Indented));
System.Console.WriteLine("Press any key to stop the server");

View File

@@ -342,15 +342,6 @@
<Reference Include="TinyMapper, Version=3.0.1.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\TinyMapper.3.0.3\lib\net40\TinyMapper.dll</HintPath>
</Reference>
<Reference Include="WireMock.Net, Version=1.5.3.0, Culture=neutral, PublicKeyToken=c8d65537854e1f03, processorArchitecture=MSIL">
<HintPath>..\..\packages\WireMock.Net.1.5.3\lib\net461\WireMock.Net.dll</HintPath>
</Reference>
<Reference Include="WireMock.Net.Abstractions, Version=1.5.3.0, Culture=neutral, PublicKeyToken=c8d65537854e1f03, processorArchitecture=MSIL">
<HintPath>..\..\packages\WireMock.Net.Abstractions.1.5.3\lib\net451\WireMock.Net.Abstractions.dll</HintPath>
</Reference>
<Reference Include="WireMock.Org.Abstractions, Version=1.5.3.0, Culture=neutral, PublicKeyToken=c8d65537854e1f03, processorArchitecture=MSIL">
<HintPath>..\..\packages\WireMock.Org.Abstractions.1.5.3\lib\net45\WireMock.Org.Abstractions.dll</HintPath>
</Reference>
<Reference Include="XPath2, Version=1.1.3.0, Culture=neutral, PublicKeyToken=463c6d7fb740c7e5, processorArchitecture=MSIL">
<HintPath>..\..\packages\XPath2.1.1.3\lib\net452\XPath2.dll</HintPath>
</Reference>
@@ -388,6 +379,16 @@
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\WireMock.Net.Abstractions\WireMock.Net.Abstractions.csproj">
<Project>{b6269aac-170a-4346-8b9a-579ded3d9a94}</Project>
<Name>WireMock.Net.Abstractions</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\WireMock.Net\WireMock.Net.csproj">
<Project>{d3804228-91f4-4502-9595-39584e5a01ad}</Project>
<Name>WireMock.Net</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>

View File

@@ -147,9 +147,6 @@
<package id="System.Threading.Tasks.Extensions" version="4.5.1" targetFramework="net472" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net472" />
<package id="TinyMapper" version="3.0.3" targetFramework="net472" />
<package id="WireMock.Net" version="1.5.3" targetFramework="net472" />
<package id="WireMock.Net.Abstractions" version="1.5.3" targetFramework="net472" />
<package id="WireMock.Org.Abstractions" version="1.5.3" targetFramework="net472" />
<package id="XPath2" version="1.1.3" targetFramework="net472" />
<package id="XPath2.Extensions" version="1.1.3" targetFramework="net472" />
</packages>

View File

@@ -1,8 +1,16 @@
{
"profiles": {
"WireMock.Net.StandAlone.NETCoreApp": {
"commandName": "Project",
"commandLineArgs": "--Urls http://localhost:9091 --CorsPolicyOptions AllowAll --WireMockLogger WireMockConsoleLogger"
"profiles": {
"WireMock.Net.StandAlone.NETCoreApp": {
"commandName": "Project",
"commandLineArgs": "--Urls http://localhost:9091 --CorsPolicyOptions AllowAll --WireMockLogger WireMockConsoleLogger"
},
"WireMock.Net.StandAlone.NETCoreAppNoPort": {
"commandName": "Project",
"commandLineArgs": "--CorsPolicyOptions AllowAll --WireMockLogger WireMockConsoleLogger"
},
"WireMock.Net.StandAlone.NETCoreAppWithHostingProtocol": {
"commandName": "Project",
"commandLineArgs": "--HostingProtocol HttpAndHttps --CorsPolicyOptions AllowAll --WireMockLogger WireMockConsoleLogger"
}
}
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 14 KiB

View File

@@ -1,31 +1,39 @@
using System.Collections.Generic;
namespace WireMock.Admin.Mappings
namespace WireMock.Admin.Mappings;
/// <summary>
/// Cookie Model
/// </summary>
[FluentBuilder.AutoGenerateBuilder]
public class CookieModel
{
/// <summary>
/// Cookie Model
/// Gets or sets the name.
/// </summary>
[FluentBuilder.AutoGenerateBuilder]
public class CookieModel
{
/// <summary>
/// Gets or sets the name.
/// </summary>
public string Name { get; set; } = null!;
public string Name { get; set; } = null!;
/// <summary>
/// Gets or sets the matchers.
/// </summary>
public IList<MatcherModel>? Matchers { get; set; }
/// <summary>
/// Gets or sets the matchers.
/// </summary>
public IList<MatcherModel>? Matchers { get; set; }
/// <summary>
/// Gets or sets the ignore case.
/// </summary>
public bool? IgnoreCase { get; set; }
/// <summary>
/// Gets or sets the ignore case.
/// </summary>
public bool? IgnoreCase { get; set; }
/// <summary>
/// Reject on match.
/// </summary>
public bool? RejectOnMatch { get; set; }
}
/// <summary>
/// Reject on match.
/// </summary>
public bool? RejectOnMatch { get; set; }
/// <summary>
/// The Operator to use when matchers are defined. [Optional]
/// - null = Same as "or".
/// - "or" = Only one pattern should match.
/// - "and" = All patterns should match.
/// - "average" = The average value from all patterns.
/// </summary>
public string? MatchOperator { get; set; }
}

View File

@@ -74,4 +74,9 @@ public class MappingModel
/// The Webhooks.
/// </summary>
public WebhookModel[]? Webhooks { get; set; }
/// <summary>
/// Fire and forget for webhooks.
/// </summary>
public bool? UseWebhooksFireAndForget { get; set; }
}

View File

@@ -1,14 +1,13 @@
namespace WireMock.Admin.Mappings
namespace WireMock.Admin.Mappings;
/// <summary>
/// The Webhook
/// </summary>
[FluentBuilder.AutoGenerateBuilder]
public class WebhookModel
{
/// <summary>
/// The Webhook
/// The Webhook Request.
/// </summary>
[FluentBuilder.AutoGenerateBuilder]
public class WebhookModel
{
/// <summary>
/// The Webhook Request.
/// </summary>
public WebhookRequestModel Request { get; set; }
}
public WebhookRequestModel Request { get; set; } = null!;
}

View File

@@ -11,12 +11,12 @@ public class WebhookRequestModel
/// <summary>
/// Gets or sets the Url.
/// </summary>
public string Url { get; set; }
public string Url { get; set; } = null!;
/// <summary>
/// The method
/// </summary>
public string Method { get; set; }
public string Method { get; set; } = null!;
/// <summary>
/// Gets or sets the headers.
@@ -47,4 +47,19 @@ public class WebhookRequestModel
/// The ReplaceNodeOptions to use when transforming a JSON node.
/// </summary>
public string? TransformerReplaceNodeOptions { get; set; }
/// <summary>
/// Gets or sets the delay in milliseconds.
/// </summary>
public int? Delay { get; set; }
/// <summary>
/// Gets or sets the minimum random delay in milliseconds.
/// </summary>
public int? MinimumRandomDelay { get; set; }
/// <summary>
/// Gets or sets the maximum random delay in milliseconds.
/// </summary>
public int? MaximumRandomDelay { get; set; }
}

View File

@@ -54,5 +54,14 @@ namespace WireMock.Admin.Settings
/// Prefer the Proxy Mapping over the saved Mapping (in case SaveMapping is set to <c>true</c>).
/// </summary>
// public bool PreferProxyMapping { get; set; }
/// <summary>
/// When SaveMapping is set to <c>true</c>, this setting can be used to control the behavior of the generated request matchers for the new mapping.
/// - <c>false</c>, the default matchers will be used.
/// - <c>true</c>, the defined mappings in the request wil be used for the new mapping.
///
/// Default value is false.
/// </summary>
public bool UseDefinedRequestMatchers { get; set; }
}
}

View File

@@ -13,12 +13,12 @@ public interface IBodyData
/// <summary>
/// The body (as bytearray).
/// </summary>
byte[] BodyAsBytes { get; set; }
byte[]? BodyAsBytes { get; set; }
/// <summary>
/// Gets or sets the body as a file.
/// </summary>
string BodyAsFile { get; set; }
string? BodyAsFile { get; set; }
/// <summary>
/// Is the body as file cached?
@@ -38,7 +38,7 @@ public interface IBodyData
/// <summary>
/// The body as string, this is defined when BodyAsString or BodyAsJson are not null.
/// </summary>
string BodyAsString { get; set; }
string? BodyAsString { get; set; }
/// <summary>
/// The detected body type (detection based on body content).

View File

@@ -2,46 +2,60 @@ using System.Collections.Generic;
using WireMock.Types;
using WireMock.Util;
namespace WireMock.Models
namespace WireMock.Models;
/// <summary>
/// IWebhookRequest
/// </summary>
public interface IWebhookRequest
{
/// <summary>
/// IWebhookRequest
/// The Webhook Url.
/// </summary>
public interface IWebhookRequest
{
/// <summary>
/// The Webhook Url.
/// </summary>
string Url { get; set; }
string Url { get; set; }
/// <summary>
/// The method to use.
/// </summary>
string Method { get; set; }
/// <summary>
/// The method to use.
/// </summary>
string Method { get; set; }
/// <summary>
/// The Headers to send.
/// </summary>
IDictionary<string, WireMockList<string>>? Headers { get; }
/// <summary>
/// The Headers to send.
/// </summary>
IDictionary<string, WireMockList<string>>? Headers { get; }
/// <summary>
/// The body to send.
/// </summary>
IBodyData? BodyData { get; set; }
/// <summary>
/// The body to send.
/// </summary>
IBodyData? BodyData { get; set; }
/// <summary>
/// Use Transformer.
/// </summary>
bool? UseTransformer { get; set; }
/// <summary>
/// Use Transformer.
/// </summary>
bool? UseTransformer { get; set; }
/// <summary>
/// The transformer type.
/// </summary>
TransformerType TransformerType { get; set; }
/// <summary>
/// The transformer type.
/// </summary>
TransformerType TransformerType { get; set; }
/// <summary>
/// The ReplaceNodeOptions to use when transforming a JSON node.
/// </summary>
ReplaceNodeOptions TransformerReplaceNodeOptions { get; set; }
}
/// <summary>
/// The ReplaceNodeOptions to use when transforming a JSON node.
/// </summary>
ReplaceNodeOptions TransformerReplaceNodeOptions { get; set; }
/// <summary>
/// Gets or sets the delay in milliseconds.
/// </summary>
int? Delay { get; set; }
/// <summary>
/// Gets or sets the minimum random delay in milliseconds.
/// </summary>
int? MinimumRandomDelay { get; set; }
/// <summary>
/// Gets or sets the maximum random delay in milliseconds.
/// </summary>
int? MaximumRandomDelay { get; set; }
}

View File

@@ -0,0 +1,15 @@
using System;
namespace WireMock.Types;
[Flags]
public enum HostingScheme
{
None = 0x0,
Http = 0x1,
Https = 0x2,
HttpAndHttps = Http | Https
}

View File

@@ -1,44 +1,69 @@
using System.Collections.Generic;
using System.Linq;
using System.Collections.Generic;
namespace WireMock.Types
namespace WireMock.Types;
/// <summary>
/// A special List which overrides the ToString() to return first value.
/// </summary>
/// <typeparam name="T">The generic type</typeparam>
/// <seealso cref="List{T}" />
public class WireMockList<T> : List<T>
{
/// <summary>
/// A special List which overrides the ToString() to return first value.
/// Initializes a new instance of the <see cref="WireMockList{T}"/> class.
/// </summary>
/// <typeparam name="T">The generic type</typeparam>
/// <seealso cref="List{T}" />
public class WireMockList<T> : List<T>
public WireMockList()
{
/// <summary>
/// Initializes a new instance of the <see cref="WireMockList{T}"/> class.
/// </summary>
public WireMockList()
{
}
}
/// <summary>
/// Initializes a new instance of the <see cref="WireMockList{T}"/> class.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
public WireMockList(params T[] collection) : base(collection)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WireMockList{T}"/> class.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
public WireMockList(params T[] collection) : base(collection)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WireMockList{T}"/> class.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
public WireMockList(IEnumerable<T> collection) : base(collection)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WireMockList{T}"/> class.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
public WireMockList(IEnumerable<T> collection) : base(collection)
{
}
/// <summary>
/// Returns a <see cref="string" /> that represents this instance.
/// </summary>
public override string ToString()
/// <summary>
/// Operator for setting T
/// </summary>
/// <param name="value">The value to set.</param>
public static implicit operator WireMockList<T>(T value) => new(value);
/// <summary>
/// Operator for setting T[]
/// </summary>
/// <param name="values">The values to set.</param>
public static implicit operator WireMockList<T>(T[] values) => new(values);
/// <summary>
/// Returns a <see cref="string" /> that represents this instance.
/// </summary>
public override string ToString()
{
switch (Count)
{
return this.Any() ? this.First().ToString() : base.ToString();
case 0:
return string.Empty;
case 1:
if (this[0] is string strValue)
{
return strValue;
}
return this[0]?.ToString();
default:
return base.ToString();
}
}
}

View File

@@ -1,97 +1,133 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using FluentAssertions.Execution;
using WireMock.Server;
using WireMock.Types;
// ReSharper disable once CheckNamespace
namespace WireMock.FluentAssertions;
public class WireMockAssertions
{
private readonly IWireMockServer _subject;
private readonly int? _callsCount;
private IReadOnlyList<IRequestMessage> _requestMessages;
private IReadOnlyList<KeyValuePair<string, WireMockList<string>>> _headers;
public WireMockAssertions(IWireMockServer subject, int? callsCount)
{
_subject = subject;
_callsCount = callsCount;
_requestMessages = subject.LogEntries.Select(logEntry => logEntry.RequestMessage).ToList();
_headers = _requestMessages.SelectMany(req => req.Headers).ToList();
}
[CustomAssertion]
public AndConstraint<WireMockAssertions> AtAbsoluteUrl(string absoluteUrl, string because = "", params object[] becauseArgs)
public AndWhichConstraint<WireMockAssertions, string> AtAbsoluteUrl(string absoluteUrl, string because = "", params object[] becauseArgs)
{
Func<IRequestMessage, bool> predicate = request => string.Equals(request.AbsoluteUrl, absoluteUrl, StringComparison.OrdinalIgnoreCase);
var (filter, condition) = BuildFilterAndCondition(predicate);
Execute.Assertion
.BecauseOf(because, becauseArgs)
.Given(() => _subject.LogEntries.Select(x => x.RequestMessage).ToList())
.Given(() => _requestMessages)
.ForCondition(requests => requests.Any())
.FailWith(
"Expected {context:wiremockserver} to have been called at address matching the absolute url {0}{reason}, but no calls were made.",
absoluteUrl)
absoluteUrl
)
.Then
.ForCondition(x => (_callsCount == null && x.Any(y => y.AbsoluteUrl == absoluteUrl)) || (_callsCount == x.Count(y => y.AbsoluteUrl == absoluteUrl)))
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockserver} to have been called at address matching the absolute url {0}{reason}, but didn't find it among the calls to {1}.",
_ => absoluteUrl, requests => requests.Select(request => request.AbsoluteUrl));
_ => absoluteUrl, requests => requests.Select(request => request.AbsoluteUrl)
);
return new AndConstraint<WireMockAssertions>(this);
_requestMessages = filter(_requestMessages).ToList();
return new AndWhichConstraint<WireMockAssertions, string>(this, absoluteUrl);
}
[CustomAssertion]
public AndConstraint<WireMockAssertions> AtUrl(string url, string because = "", params object[] becauseArgs)
public AndWhichConstraint<WireMockAssertions, string> AtUrl(string url, string because = "", params object[] becauseArgs)
{
Func<IRequestMessage, bool> predicate = request => string.Equals(request.Url, url, StringComparison.OrdinalIgnoreCase);
var (filter, condition) = BuildFilterAndCondition(predicate);
Execute.Assertion
.BecauseOf(because, becauseArgs)
.Given(() => _subject.LogEntries.Select(x => x.RequestMessage).ToList())
.Given(() => _requestMessages)
.ForCondition(requests => requests.Any())
.FailWith(
"Expected {context:wiremockserver} to have been called at address matching the url {0}{reason}, but no calls were made.",
url)
.Then
.ForCondition(x => (_callsCount == null && x.Any(y => y.Url == url)) || (_callsCount == x.Count(y => y.Url == url)))
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockserver} to have been called at address matching the url {0}{reason}, but didn't find it among the calls to {1}.",
_ => url, requests => requests.Select(request => request.Url));
_ => url,
requests => requests.Select(request => request.Url)
);
return new AndConstraint<WireMockAssertions>(this);
_requestMessages = filter(_requestMessages).ToList();
return new AndWhichConstraint<WireMockAssertions, string>(this, url);
}
[CustomAssertion]
public AndConstraint<WireMockAssertions> WithProxyUrl(string proxyUrl, string because = "", params object[] becauseArgs)
public AndWhichConstraint<WireMockAssertions, string> WithProxyUrl(string proxyUrl, string because = "", params object[] becauseArgs)
{
Func<IRequestMessage, bool> predicate = request => string.Equals(request.ProxyUrl, proxyUrl, StringComparison.OrdinalIgnoreCase);
var (filter, condition) = BuildFilterAndCondition(predicate);
Execute.Assertion
.BecauseOf(because, becauseArgs)
.Given(() => _subject.LogEntries.Select(x => x.RequestMessage).ToList())
.Given(() => _requestMessages)
.ForCondition(requests => requests.Any())
.FailWith(
"Expected {context:wiremockserver} to have been called with proxy url {0}{reason}, but no calls were made.",
proxyUrl)
proxyUrl
)
.Then
.ForCondition(x => (_callsCount == null && x.Any(y => y.ProxyUrl == proxyUrl)) || (_callsCount == x.Count(y => y.ProxyUrl == proxyUrl)))
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockserver} to have been called with proxy url {0}{reason}, but didn't find it among the calls with {1}.",
_ => proxyUrl, requests => requests.Select(request => request.ProxyUrl));
_ => proxyUrl,
requests => requests
.Select(request => request.ProxyUrl)
);
return new AndConstraint<WireMockAssertions>(this);
_requestMessages = filter(_requestMessages).ToList();
return new AndWhichConstraint<WireMockAssertions, string>(this, proxyUrl);
}
[CustomAssertion]
public AndConstraint<WireMockAssertions> FromClientIP(string clientIP, string because = "", params object[] becauseArgs)
public AndWhichConstraint<WireMockAssertions, string> FromClientIP(string clientIP, string because = "", params object[] becauseArgs)
{
Func<IRequestMessage, bool> predicate = request => string.Equals(request.ClientIP, clientIP, StringComparison.OrdinalIgnoreCase);
var (filter, condition) = BuildFilterAndCondition(predicate);
Execute.Assertion
.BecauseOf(because, becauseArgs)
.Given(() => _subject.LogEntries.Select(x => x.RequestMessage).ToList())
.Given(() => _requestMessages)
.ForCondition(requests => requests.Any())
.FailWith(
"Expected {context:wiremockserver} to have been called from client IP {0}{reason}, but no calls were made.",
clientIP)
.Then
.ForCondition(x => (_callsCount == null && x.Any(y => y.ClientIP == clientIP)) || (_callsCount == x.Count(y => y.ClientIP == clientIP)))
.ForCondition(requests =>
(_callsCount == null && requests.Any(req => req.ClientIP == clientIP)) ||
(_callsCount == requests.Count(req => req.ClientIP == clientIP))
)
.FailWith(
"Expected {context:wiremockserver} to have been called from client IP {0}{reason}, but didn't find it among the calls from IP(s) {1}.",
_ => clientIP, requests => requests.Select(request => request.ClientIP));
return new AndConstraint<WireMockAssertions>(this);
_requestMessages = filter(_requestMessages).ToList();
return new AndWhichConstraint<WireMockAssertions, string>(this, clientIP);
}
[CustomAssertion]
@@ -101,28 +137,25 @@ public class WireMockAssertions
[CustomAssertion]
public AndConstraint<WireMockAssertions> WithHeader(string expectedKey, string[] expectedValues, string because = "", params object[] becauseArgs)
{
var headersDictionary = _subject.LogEntries.SelectMany(x => x.RequestMessage.Headers)
.ToDictionary(x => x.Key, x => x.Value);
using (new AssertionScope("headers from requests sent"))
{
headersDictionary.Should().ContainKey(expectedKey, because, becauseArgs);
_headers.Select(h => h.Key).Should().Contain(expectedKey, because, becauseArgs);
}
using (new AssertionScope($"header \"{expectedKey}\" from requests sent with value(s)"))
{
var headerValues = _headers.First(h => h.Key == expectedKey).Value;
if (expectedValues.Length == 1)
{
headersDictionary[expectedKey].Should().Contain(expectedValues.First());
headerValues.Should().Contain(expectedValues.First(), because, becauseArgs);
}
else
{
var trimmedHeaderValues = string.Join(",", headersDictionary[expectedKey].Select(x => x)).Split(',')
.Select(x => x.Trim())
.ToList();
var trimmedHeaderValues = string.Join(",", headerValues.Select(x => x)).Split(',').Select(x => x.Trim()).ToList();
foreach (var expectedValue in expectedValues)
{
trimmedHeaderValues.Should().Contain(expectedValue);
trimmedHeaderValues.Should().Contain(expectedValue, because, becauseArgs);
}
}
}
@@ -169,19 +202,40 @@ public class WireMockAssertions
[CustomAssertion]
public AndConstraint<WireMockAssertions> UsingMethod(string method, string because = "", params object[] becauseArgs)
{
Func<IRequestMessage, bool> predicate = request => string.Equals(request.Method, method, StringComparison.OrdinalIgnoreCase);
var (filter, condition) = BuildFilterAndCondition(predicate);
Execute.Assertion
.BecauseOf(because, becauseArgs)
.Given(() => _subject.LogEntries.Select(x => x.RequestMessage).ToList())
.Given(() => _requestMessages)
.ForCondition(requests => requests.Any())
.FailWith(
"Expected {context:wiremockserver} to have been called using method {0}{reason}, but no calls were made.",
method)
method
)
.Then
.ForCondition(x => (_callsCount == null && x.Any(y => y.Method == method)) || (_callsCount == x.Count(y => y.Method == method)))
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockserver} to have been called using method {0}{reason}, but didn't find it among the methods {1}.",
_ => method, requests => requests.Select(request => request.Method));
_ => method,
requests => requests.Select(request => request.Method)
);
_requestMessages = filter(_requestMessages).ToList();
return new AndConstraint<WireMockAssertions>(this);
}
private (Func<IReadOnlyList<IRequestMessage>, IReadOnlyList<IRequestMessage>> Filter, Func<IReadOnlyList<IRequestMessage>, bool> Condition) BuildFilterAndCondition(Func<IRequestMessage, bool> predicate)
{
Func<IReadOnlyList<IRequestMessage>, IReadOnlyList<IRequestMessage>> filter = requests => requests.Where(predicate).ToList();
return
(
filter,
requests =>
(_callsCount == null && filter(_requestMessages).Any()) ||
(_callsCount == filter(_requestMessages).Count())
);
}
}

View File

@@ -22,6 +22,7 @@
<!--<DelaySign>true</DelaySign>-->
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<LangVersion>10</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">

View File

@@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Stef.Validation;
using WireMock.Models;
@@ -17,6 +19,7 @@ namespace WireMock.Http;
internal class WebhookSender
{
private const string ClientIp = "::1";
private static readonly ThreadLocal<Random> Random = new(() => new Random(DateTime.UtcNow.Millisecond));
private readonly WireMockServerSettings _settings;
@@ -25,48 +28,58 @@ internal class WebhookSender
_settings = Guard.NotNull(settings);
}
public Task<HttpResponseMessage> SendAsync(HttpClient client, IMapping mapping, IWebhookRequest request, IRequestMessage originalRequestMessage, IResponseMessage originalResponseMessage)
public async Task<HttpResponseMessage> SendAsync(
HttpClient client,
IMapping mapping,
IWebhookRequest webhookRequest,
IRequestMessage originalRequestMessage,
IResponseMessage originalResponseMessage
)
{
Guard.NotNull(client);
Guard.NotNull(mapping);
Guard.NotNull(request);
Guard.NotNull(webhookRequest);
Guard.NotNull(originalRequestMessage);
Guard.NotNull(originalResponseMessage);
IBodyData? bodyData;
IDictionary<string, WireMockList<string>>? headers;
if (request.UseTransformer == true)
string webhookRequestUrl;
if (webhookRequest.UseTransformer == true)
{
ITransformer responseMessageTransformer;
switch (request.TransformerType)
ITransformer transformer;
switch (webhookRequest.TransformerType)
{
case TransformerType.Handlebars:
var factoryHandlebars = new HandlebarsContextFactory(_settings.FileSystemHandler, _settings.HandlebarsRegistrationCallback);
responseMessageTransformer = new Transformer(factoryHandlebars);
transformer = new Transformer(factoryHandlebars);
break;
case TransformerType.Scriban:
case TransformerType.ScribanDotLiquid:
var factoryDotLiquid = new ScribanContextFactory(_settings.FileSystemHandler, request.TransformerType);
responseMessageTransformer = new Transformer(factoryDotLiquid);
var factoryDotLiquid = new ScribanContextFactory(_settings.FileSystemHandler, webhookRequest.TransformerType);
transformer = new Transformer(factoryDotLiquid);
break;
default:
throw new NotImplementedException($"TransformerType '{request.TransformerType}' is not supported.");
throw new NotImplementedException($"TransformerType '{webhookRequest.TransformerType}' is not supported.");
}
(bodyData, headers) = responseMessageTransformer.Transform(mapping, originalRequestMessage, originalResponseMessage, request.BodyData, request.Headers, request.TransformerReplaceNodeOptions);
bodyData = transformer.TransformBody(mapping, originalRequestMessage, originalResponseMessage, webhookRequest.BodyData, webhookRequest.TransformerReplaceNodeOptions);
headers = transformer.TransformHeaders(mapping, originalRequestMessage, originalResponseMessage, webhookRequest.Headers);
webhookRequestUrl = transformer.TransformString(mapping, originalRequestMessage, originalResponseMessage, webhookRequest.Url);
}
else
{
bodyData = request.BodyData;
headers = request.Headers;
bodyData = webhookRequest.BodyData;
headers = webhookRequest.Headers;
webhookRequestUrl = webhookRequest.Url;
}
// Create RequestMessage
var requestMessage = new RequestMessage(
new UrlDetails(request.Url),
request.Method,
new UrlDetails(webhookRequestUrl),
webhookRequest.Method,
ClientIp,
bodyData,
headers?.ToDictionary(x => x.Key, x => x.Value.ToArray())
@@ -76,9 +89,30 @@ internal class WebhookSender
};
// Create HttpRequestMessage
var httpRequestMessage = HttpRequestMessageHelper.Create(requestMessage, request.Url);
var httpRequestMessage = HttpRequestMessageHelper.Create(requestMessage, webhookRequest.Url);
// Delay (if required)
if (TryGetDelay(webhookRequest, out var delay))
{
await Task.Delay(delay.Value).ConfigureAwait(false);
}
// Call the URL
return client.SendAsync(httpRequestMessage);
return await client.SendAsync(httpRequestMessage).ConfigureAwait(false);
}
private static bool TryGetDelay(IWebhookRequest webhookRequest, [NotNullWhen(true)] out int? delay)
{
delay = webhookRequest.Delay;
var minimumDelay = webhookRequest.MinimumRandomDelay;
var maximumDelay = webhookRequest.MaximumRandomDelay;
if (minimumDelay is not null && maximumDelay is not null && maximumDelay >= minimumDelay)
{
delay = Random.Value!.Next(minimumDelay.Value, maximumDelay.Value);
return true;
}
return delay is not null;
}
}

View File

@@ -112,6 +112,11 @@ public interface IMapping
/// </summary>
IWebhook[]? Webhooks { get; }
/// <summary>
/// Use Fire and Forget for the defined webhook(s). [Optional]
/// </summary>
public bool? UseWebhooksFireAndForget { get; set; }
/// <summary>
/// ProvideResponseAsync
/// </summary>

View File

@@ -63,6 +63,9 @@ public class Mapping : IMapping
/// <inheritdoc />
public IWebhook[]? Webhooks { get; }
/// <inheritdoc />
public bool? UseWebhooksFireAndForget { get; set; }
/// <inheritdoc />
public ITimeSettings? TimeSettings { get; }
@@ -82,6 +85,7 @@ public class Mapping : IMapping
/// <param name="nextState">The next state which will occur after the current mapping execution. [Optional]</param>
/// <param name="stateTimes">Only when the current state is executed this number, the next state which will occur. [Optional]</param>
/// <param name="webhooks">The Webhooks. [Optional]</param>
/// <param name="useWebhooksFireAndForget">Use Fire and Forget for the defined webhook(s). [Optional]</param>
/// <param name="timeSettings">The TimeSettings. [Optional]</param>
public Mapping(
Guid guid,
@@ -97,6 +101,7 @@ public class Mapping : IMapping
string? nextState,
int? stateTimes,
IWebhook[]? webhooks,
bool? useWebhooksFireAndForget,
ITimeSettings? timeSettings)
{
Guid = guid;
@@ -112,6 +117,7 @@ public class Mapping : IMapping
NextState = nextState;
StateTimes = stateTimes;
Webhooks = webhooks;
UseWebhooksFireAndForget = useWebhooksFireAndForget;
TimeSettings = timeSettings;
}

View File

@@ -1,7 +1,7 @@
using System;
using System.Linq;
using AnyOfTypes;
using Stef.Validation;
using WireMock.Extensions;
using WireMock.Models;
namespace WireMock.Matchers;
@@ -9,8 +9,8 @@ namespace WireMock.Matchers;
/// <summary>
/// ExactMatcher
/// </summary>
/// <seealso cref="IStringMatcher" />
public class ExactMatcher : IStringMatcher
/// <seealso cref="IStringMatcher" /> and <seealso cref="IIgnoreCaseMatcher" />
public class ExactMatcher : IStringMatcher, IIgnoreCaseMatcher
{
private readonly AnyOf<string, StringPattern>[] _values;
@@ -24,7 +24,16 @@ public class ExactMatcher : IStringMatcher
/// Initializes a new instance of the <see cref="ExactMatcher"/> class.
/// </summary>
/// <param name="values">The values.</param>
public ExactMatcher(params AnyOf<string, StringPattern>[] values) : this(MatchBehaviour.AcceptOnMatch, false, MatchOperator.Or, values)
public ExactMatcher(params AnyOf<string, StringPattern>[] values) : this(MatchBehaviour.AcceptOnMatch, false, false, MatchOperator.Or, values)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ExactMatcher"/> class.
/// </summary>
/// <param name="ignoreCase">Ignore the case from the pattern(s).</param>
/// <param name="values">The values.</param>
public ExactMatcher(bool ignoreCase, params AnyOf<string, StringPattern>[] values) : this(MatchBehaviour.AcceptOnMatch, ignoreCase, false, MatchOperator.Or, values)
{
}
@@ -32,11 +41,13 @@ public class ExactMatcher : IStringMatcher
/// Initializes a new instance of the <see cref="ExactMatcher"/> class.
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="ignoreCase">Ignore the case from the pattern(s).</param>
/// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param>
/// <param name="matchOperator">The <see cref="Matchers.MatchOperator"/> to use. (default = "Or")</param>
/// <param name="values">The values.</param>
public ExactMatcher(
MatchBehaviour matchBehaviour,
bool ignoreCase = false,
bool throwException = false,
MatchOperator matchOperator = MatchOperator.Or,
params AnyOf<string, StringPattern>[] values)
@@ -45,13 +56,18 @@ public class ExactMatcher : IStringMatcher
MatchBehaviour = matchBehaviour;
ThrowException = throwException;
IgnoreCase = ignoreCase;
MatchOperator = matchOperator;
}
/// <inheritdoc cref="IStringMatcher.IsMatch"/>
public double IsMatch(string? input)
{
double score = MatchScores.ToScore(_values.Select(v => v.GetPattern() == input).ToArray(), MatchOperator);
Func<string?, bool> equals = IgnoreCase
? pattern => string.Equals(pattern, input, StringComparison.OrdinalIgnoreCase)
: pattern => pattern == input;
double score = MatchScores.ToScore(_values.Select(v => equals(v)).ToArray(), MatchOperator);
return MatchBehaviourHelper.Convert(MatchBehaviour, score);
}
@@ -66,4 +82,7 @@ public class ExactMatcher : IStringMatcher
/// <inheritdoc cref="IMatcher.Name"/>
public string Name => "ExactMatcher";
/// <inheritdoc />
public bool IgnoreCase { get; }
}

View File

@@ -29,7 +29,7 @@ public class JsonPartialMatcher : AbstractJsonPartialMatcher
/// <inheritdoc />
protected override bool IsMatch(string value, string input)
{
var exactStringMatcher = new ExactMatcher(MatchBehaviour.AcceptOnMatch, ThrowException, MatchOperator.Or, value);
var exactStringMatcher = new ExactMatcher(MatchBehaviour.AcceptOnMatch, IgnoreCase, ThrowException, MatchOperator.Or, value);
return MatchScores.IsPerfect(exactStringMatcher.IsMatch(input));
}
}

View File

@@ -18,5 +18,5 @@ public enum MatchOperator
/// <summary>
/// The average value from all patterns.
/// </summary>
Average,
Average
}

View File

@@ -16,22 +16,22 @@ public class RequestMessageBodyMatcher : IRequestMatcher
/// <summary>
/// The body function
/// </summary>
public Func<string, bool>? Func { get; }
public Func<string?, bool>? Func { get; }
/// <summary>
/// The body data function for byte[]
/// </summary>
public Func<byte[], bool>? DataFunc { get; }
public Func<byte[]?, bool>? DataFunc { get; }
/// <summary>
/// The body data function for json
/// </summary>
public Func<object, bool>? JsonFunc { get; }
public Func<object?, bool>? JsonFunc { get; }
/// <summary>
/// The body data function for BodyData
/// </summary>
public Func<IBodyData, bool>? BodyDataFunc { get; }
public Func<IBodyData?, bool>? BodyDataFunc { get; }
/// <summary>
/// The matchers.
@@ -77,7 +77,7 @@ public class RequestMessageBodyMatcher : IRequestMatcher
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
/// <param name="func">The function.</param>
public RequestMessageBodyMatcher(Func<string, bool> func)
public RequestMessageBodyMatcher(Func<string?, bool> func)
{
Func = Guard.NotNull(func);
}
@@ -86,7 +86,7 @@ public class RequestMessageBodyMatcher : IRequestMatcher
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
/// <param name="func">The function.</param>
public RequestMessageBodyMatcher(Func<byte[], bool> func)
public RequestMessageBodyMatcher(Func<byte[]?, bool> func)
{
DataFunc = Guard.NotNull(func);
}
@@ -95,7 +95,7 @@ public class RequestMessageBodyMatcher : IRequestMatcher
/// Initializes a new instance of the <see cref="RequestMessageBodyMatcher"/> class.
/// </summary>
/// <param name="func">The function.</param>
public RequestMessageBodyMatcher(Func<object, bool> func)
public RequestMessageBodyMatcher(Func<object?, bool> func)
{
JsonFunc = Guard.NotNull(func);
}
@@ -158,9 +158,9 @@ public class RequestMessageBodyMatcher : IRequestMatcher
{
// If the body is a byte array, try to match.
var detectedBodyType = requestMessage.BodyData?.DetectedBodyType;
if (detectedBodyType == BodyType.Bytes || detectedBodyType == BodyType.String)
if (detectedBodyType is BodyType.Bytes or BodyType.String)
{
return exactObjectMatcher.IsMatch(requestMessage.BodyData.BodyAsBytes);
return exactObjectMatcher.IsMatch(requestMessage.BodyData?.BodyAsBytes);
}
}

View File

@@ -1,8 +1,7 @@
using Stef.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Stef.Validation;
namespace WireMock.Matchers.Request;
@@ -13,12 +12,13 @@ namespace WireMock.Matchers.Request;
public class RequestMessageCookieMatcher : IRequestMatcher
{
private readonly MatchBehaviour _matchBehaviour;
private readonly bool _ignoreCase;
/// <summary>
/// The functions
/// </summary>
public Func<IDictionary<string, string>, bool>[] Funcs { get; }
public Func<IDictionary<string, string>, bool>[]? Funcs { get; }
/// <summary>
/// The name
@@ -28,7 +28,7 @@ public class RequestMessageCookieMatcher : IRequestMatcher
/// <value>
/// The matchers.
/// </value>
public IStringMatcher[] Matchers { get; }
public IStringMatcher[]? Matchers { get; }
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageCookieMatcher"/> class.
@@ -37,15 +37,12 @@ public class RequestMessageCookieMatcher : IRequestMatcher
/// <param name="pattern">The pattern.</param>
/// <param name="ignoreCase">Ignore the case from the pattern.</param>
/// <param name="matchBehaviour">The match behaviour.</param>
public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, [NotNull] string pattern, bool ignoreCase)
public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, string name, string pattern, bool ignoreCase)
{
Guard.NotNull(name, nameof(name));
Guard.NotNull(pattern, nameof(pattern));
_matchBehaviour = matchBehaviour;
_ignoreCase = ignoreCase;
Name = name;
Matchers = new IStringMatcher[] { new WildcardMatcher(matchBehaviour, pattern, ignoreCase) };
Name = Guard.NotNull(name);
Matchers = new IStringMatcher[] { new WildcardMatcher(matchBehaviour, Guard.NotNull(pattern), ignoreCase) };
}
/// <summary>
@@ -55,10 +52,10 @@ public class RequestMessageCookieMatcher : IRequestMatcher
/// <param name="name">The name.</param>
/// <param name="patterns">The patterns.</param>
/// <param name="ignoreCase">Ignore the case from the pattern.</param>
public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, bool ignoreCase, [NotNull] params string[] patterns) :
public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, string name, bool ignoreCase, params string[] patterns) :
this(matchBehaviour, name, ignoreCase, patterns.Select(pattern => new WildcardMatcher(matchBehaviour, pattern, ignoreCase)).Cast<IStringMatcher>().ToArray())
{
Guard.NotNull(patterns, nameof(patterns));
Guard.NotNull(patterns);
}
/// <summary>
@@ -68,14 +65,11 @@ public class RequestMessageCookieMatcher : IRequestMatcher
/// <param name="name">The name.</param>
/// <param name="matchers">The matchers.</param>
/// <param name="ignoreCase">Ignore the case from the pattern.</param>
public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, bool ignoreCase, [NotNull] params IStringMatcher[] matchers)
public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, string name, bool ignoreCase, params IStringMatcher[] matchers)
{
Guard.NotNull(name, nameof(name));
Guard.NotNull(matchers, nameof(matchers));
_matchBehaviour = matchBehaviour;
Name = name;
Matchers = matchers;
Name = Guard.NotNull(name);
Matchers = Guard.NotNull(matchers);
_ignoreCase = ignoreCase;
}
@@ -83,11 +77,12 @@ public class RequestMessageCookieMatcher : IRequestMatcher
/// Initializes a new instance of the <see cref="RequestMessageCookieMatcher"/> class.
/// </summary>
/// <param name="funcs">The funcs.</param>
public RequestMessageCookieMatcher([NotNull] params Func<IDictionary<string, string>, bool>[] funcs)
public RequestMessageCookieMatcher(params Func<IDictionary<string, string>, bool>[] funcs)
{
Guard.NotNull(funcs, nameof(funcs));
Guard.NotNull(funcs);
Funcs = funcs;
Name = string.Empty; // Not used when Func, but set to a non-null valid value.
}
/// <inheritdoc />

View File

@@ -11,7 +11,10 @@ namespace WireMock.Matchers.Request;
/// </summary>
public class RequestMessageParamMatcher : IRequestMatcher
{
private readonly MatchBehaviour _matchBehaviour;
/// <summary>
/// MatchBehaviour
/// </summary>
public MatchBehaviour MatchBehaviour { get; }
/// <summary>
/// The funcs
@@ -21,7 +24,7 @@ public class RequestMessageParamMatcher : IRequestMatcher
/// <summary>
/// The key
/// </summary>
public string? Key { get; }
public string Key { get; } = string.Empty;
/// <summary>
/// Defines if the key should be matched using case-ignore.
@@ -50,7 +53,7 @@ public class RequestMessageParamMatcher : IRequestMatcher
/// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <param name="values">The values.</param>
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, string key, bool ignoreCase, string[]? values) : this(matchBehaviour, key, ignoreCase, values?.Select(value => new ExactMatcher(matchBehaviour, false, MatchOperator.And, value)).Cast<IStringMatcher>().ToArray())
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, string key, bool ignoreCase, string[]? values) : this(matchBehaviour, key, ignoreCase, values?.Select(value => new ExactMatcher(matchBehaviour, ignoreCase, false, MatchOperator.And, value)).Cast<IStringMatcher>().ToArray())
{
}
@@ -63,7 +66,7 @@ public class RequestMessageParamMatcher : IRequestMatcher
/// <param name="matchers">The matchers.</param>
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, string key, bool ignoreCase, IStringMatcher[]? matchers)
{
_matchBehaviour = matchBehaviour;
MatchBehaviour = matchBehaviour;
Key = Guard.NotNull(key);
IgnoreCase = ignoreCase;
Matchers = matchers;
@@ -81,7 +84,7 @@ public class RequestMessageParamMatcher : IRequestMatcher
/// <inheritdoc />
public double GetMatchingScore(IRequestMessage requestMessage, IRequestMatchResult requestMatchResult)
{
double score = MatchBehaviourHelper.Convert(_matchBehaviour, IsMatch(requestMessage));
double score = MatchBehaviourHelper.Convert(MatchBehaviour, IsMatch(requestMessage));
return requestMatchResult.AddScore(GetType(), score);
}

View File

@@ -11,7 +11,7 @@ namespace WireMock.Util
/// <inheritdoc cref="IBodyData.Encoding" />
public Encoding? Encoding { get; set; }
/// <inheritdoc cref="IBodyData.BodyAsBytes" />
/// <inheritdoc />
public string? BodyAsString { get; set; }
/// <inheritdoc cref="IBodyData.BodyAsJson" />

View File

@@ -1,11 +1,10 @@
namespace WireMock.Models
namespace WireMock.Models;
/// <summary>
/// Webhook
/// </summary>
public class Webhook : IWebhook
{
/// <summary>
/// Webhook
/// </summary>
public class Webhook : IWebhook
{
/// <inheritdoc cref="IWebhook.Request"/>
public IWebhookRequest Request { get; set; }
}
/// <inheritdoc />
public IWebhookRequest Request { get; set; } = null!;
}

View File

@@ -2,32 +2,40 @@ using System.Collections.Generic;
using WireMock.Types;
using WireMock.Util;
namespace WireMock.Models
namespace WireMock.Models;
/// <summary>
/// WebhookRequest
/// </summary>
public class WebhookRequest : IWebhookRequest
{
/// <summary>
/// WebhookRequest
/// </summary>
public class WebhookRequest : IWebhookRequest
{
/// <inheritdoc cref="IWebhookRequest.Url"/>
public string Url { get; set; }
/// <inheritdoc />
public string Url { get; set; } = null!;
/// <inheritdoc cref="IWebhookRequest.Method"/>
public string Method { get; set; }
/// <inheritdoc />
public string Method { get; set; } = null!;
/// <inheritdoc cref="IWebhookRequest.Headers"/>
public IDictionary<string, WireMockList<string>>? Headers { get; set; }
/// <inheritdoc />
public IDictionary<string, WireMockList<string>>? Headers { get; set; }
/// <inheritdoc cref="IWebhookRequest.BodyData"/>
public IBodyData? BodyData { get; set; }
/// <inheritdoc />
public IBodyData? BodyData { get; set; }
/// <inheritdoc cref="IWebhookRequest.UseTransformer"/>
public bool? UseTransformer { get; set; }
/// <inheritdoc />
public bool? UseTransformer { get; set; }
/// <inheritdoc cref="IWebhookRequest.TransformerType"/>
public TransformerType TransformerType { get; set; }
/// <inheritdoc />
public TransformerType TransformerType { get; set; }
/// <inheritdoc cref="IWebhookRequest.TransformerReplaceNodeOptions"/>
public ReplaceNodeOptions TransformerReplaceNodeOptions { get; set; }
}
/// <inheritdoc />
public ReplaceNodeOptions TransformerReplaceNodeOptions { get; set; }
/// <inheritdoc />
public int? Delay { get; set; }
/// <inheritdoc />
public int? MinimumRandomDelay { get; set; }
/// <inheritdoc />
public int? MaximumRandomDelay { get; set; }
}

View File

@@ -107,7 +107,7 @@ namespace WireMock.Owin
{
try
{
var appLifetime = (IApplicationLifetime)_host.Services.GetService(typeof(IApplicationLifetime));
var appLifetime = _host.Services.GetRequiredService<IApplicationLifetime>();
appLifetime.ApplicationStarted.Register(() =>
{
var addresses = _host.ServerFeatures

View File

@@ -1,12 +1,15 @@
namespace WireMock.Owin;
/// <summary>
/// https://en.wikipedia.org/wiki/Uniform_Resource_Identifier
/// </summary>
internal struct HostUrlDetails
{
public bool IsHttps { get; set; }
public string Url { get; set; }
public string Protocol { get; set; }
public string Scheme { get; set; }
public string Host { get; set; }

View File

@@ -1,34 +1,49 @@
using System.Collections.Generic;
using WireMock.Types;
using WireMock.Util;
namespace WireMock.Owin;
internal class HostUrlOptions
{
private const string LOCALHOST = "localhost";
private const string Localhost = "localhost";
public ICollection<string>? Urls { get; set; }
public int? Port { get; set; }
public bool UseSSL { get; set; }
public int? HttpsPort { get; set; }
public ICollection<HostUrlDetails> GetDetails()
public HostingScheme HostingScheme { get; set; }
public IReadOnlyList<HostUrlDetails> GetDetails()
{
var list = new List<HostUrlDetails>();
if (Urls == null)
{
int port = Port > 0 ? Port.Value : FindFreeTcpPort();
string protocol = UseSSL ? "https" : "http";
list.Add(new HostUrlDetails { IsHttps = UseSSL, Url = $"{protocol}://{LOCALHOST}:{port}", Protocol = protocol, Host = LOCALHOST, Port = port });
if (HostingScheme is HostingScheme.Http or HostingScheme.Https)
{
var port = Port > 0 ? Port.Value : FindFreeTcpPort();
var scheme = HostingScheme == HostingScheme.Https ? "https" : "http";
list.Add(new HostUrlDetails { IsHttps = HostingScheme == HostingScheme.Https, Url = $"{scheme}://{Localhost}:{port}", Scheme = scheme, Host = Localhost, Port = port });
}
if (HostingScheme == HostingScheme.HttpAndHttps)
{
var httpPort = Port > 0 ? Port.Value : FindFreeTcpPort();
list.Add(new HostUrlDetails { IsHttps = false, Url = $"http://{Localhost}:{httpPort}", Scheme = "http", Host = Localhost, Port = httpPort });
var httpsPort = FindFreeTcpPort(); // In this scenario, always get a free port for https.
list.Add(new HostUrlDetails { IsHttps = true, Url = $"https://{Localhost}:{httpsPort}", Scheme = "https", Host = Localhost, Port = httpsPort });
}
}
else
{
foreach (string url in Urls)
{
if (PortUtils.TryExtract(url, out bool isHttps, out var protocol, out var host, out int port))
if (PortUtils.TryExtract(url, out var isHttps, out var protocol, out var host, out var port))
{
list.Add(new HostUrlDetails { IsHttps = isHttps, Url = url, Protocol = protocol, Host = host, Port = port });
list.Add(new HostUrlDetails { IsHttps = isHttps, Url = url, Scheme = protocol, Host = host, Port = port });
}
}
}

View File

@@ -11,8 +11,8 @@ using WireMock.Serialization;
using WireMock.Types;
using WireMock.ResponseBuilders;
using WireMock.Settings;
using System.Collections.Generic;
#if !USE_ASPNETCORE
using Microsoft.Owin;
using IContext = Microsoft.Owin.IOwinContext;
using OwinMiddleware = Microsoft.Owin.OwinMiddleware;
using Next = Microsoft.Owin.OwinMiddleware;
@@ -201,20 +201,46 @@ namespace WireMock.Owin
private async Task SendToWebhooksAsync(IMapping mapping, IRequestMessage request, IResponseMessage response)
{
var tasks = new List<Func<Task>>();
for (int index = 0; index < mapping.Webhooks?.Length; index++)
{
var httpClientForWebhook = HttpClientBuilder.Build(mapping.Settings.WebhookSettings ?? new WebhookSettings());
var webhookSender = new WebhookSender(mapping.Settings);
var webhookRequest = mapping.Webhooks[index].Request;
var webHookIndex = index;
tasks.Add(async () =>
{
try
{
await webhookSender.SendAsync(httpClientForWebhook, mapping, webhookRequest, request, response).ConfigureAwait(false);
}
catch (Exception ex)
{
_options.Logger.Error($"Sending message to Webhook [{webHookIndex}] from Mapping '{mapping.Guid}' failed. Exception: {ex}");
}
});
}
if (mapping.UseWebhooksFireAndForget == true)
{
try
{
await webhookSender.SendAsync(httpClientForWebhook, mapping, mapping.Webhooks[index].Request, request, response).ConfigureAwait(false);
// Do not wait
await Task.Run(() =>
{
Task.WhenAll(tasks.Select(async task => await task.Invoke())).ConfigureAwait(false);
});
}
catch (Exception ex)
catch
{
_options.Logger.Error($"Sending message to Webhook [{index}] from Mapping '{mapping.Guid}' failed. Exception: {ex}");
// Ignore
}
}
else
{
await Task.WhenAll(tasks.Select(async task => await task.Invoke())).ConfigureAwait(false);
}
}
private void UpdateScenarioState(IMapping mapping)

View File

@@ -1,14 +1,15 @@
using Stef.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Stef.Validation;
using WireMock.Constants;
using WireMock.Http;
using WireMock.Matchers;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Serialization;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
@@ -18,13 +19,16 @@ namespace WireMock.Proxy;
internal class ProxyHelper
{
private readonly WireMockServerSettings _settings;
private readonly ProxyMappingConverter _proxyMappingConverter;
public ProxyHelper(WireMockServerSettings settings)
{
_settings = Guard.NotNull(settings);
_proxyMappingConverter = new ProxyMappingConverter(settings, new GuidUtils());
}
public async Task<(IResponseMessage Message, IMapping? Mapping)> SendAsync(
IMapping? mapping,
ProxyAndRecordSettings proxyAndRecordSettings,
HttpClient client,
IRequestMessage requestMessage,
@@ -49,14 +53,14 @@ internal class ProxyHelper
var responseMessage = await HttpResponseMessageHelper.CreateAsync(httpResponseMessage, requiredUri, originalUri, deserializeJson, decompressGzipAndDeflate).ConfigureAwait(false);
IMapping? mapping = null;
IMapping? newMapping = null;
if (HttpStatusRangeParser.IsMatch(proxyAndRecordSettings.SaveMappingForStatusCodePattern, responseMessage.StatusCode) &&
(proxyAndRecordSettings.SaveMapping || proxyAndRecordSettings.SaveMappingToFile))
{
mapping = ToMapping(proxyAndRecordSettings, requestMessage, responseMessage);
newMapping = _proxyMappingConverter.ToMapping(mapping, proxyAndRecordSettings, requestMessage, responseMessage);
}
return (responseMessage, mapping);
return (responseMessage, newMapping);
}
private IMapping ToMapping(ProxyAndRecordSettings proxyAndRecordSettings, IRequestMessage requestMessage, ResponseMessage responseMessage)
@@ -94,7 +98,7 @@ internal class ProxyHelper
break;
case BodyType.String:
request.WithBody(new ExactMatcher(MatchBehaviour.AcceptOnMatch, throwExceptionWhenMatcherFails, MatchOperator.Or, requestMessage.BodyData.BodyAsString));
request.WithBody(new ExactMatcher(MatchBehaviour.AcceptOnMatch, false, throwExceptionWhenMatcherFails, MatchOperator.Or, requestMessage.BodyData.BodyAsString));
break;
case BodyType.Bytes:
@@ -119,6 +123,7 @@ internal class ProxyHelper
nextState: null,
stateTimes: null,
webhooks: null,
useWebhooksFireAndForget: null,
timeSettings: null
);
}

View File

@@ -20,7 +20,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, bool, MatchBehaviour)"/>
public IRequestBuilder WithParam(string key, bool ignoreCase, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
Guard.NotNull(key, nameof(key));
Guard.NotNull(key);
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase));
return this;

View File

@@ -271,6 +271,7 @@ public partial class Response : IResponseBuilder
var proxyHelper = new ProxyHelper(settings);
return await proxyHelper.SendAsync(
mapping,
ProxyAndRecordSettings,
_httpClientForProxy,
requestMessage,

View File

@@ -39,7 +39,7 @@ public class ResponseMessage : IResponseMessage
public void AddHeader(string name, string value)
{
Headers ??= new Dictionary<string, WireMockList<string>>();
Headers.Add(name, new WireMockList<string>(value));
Headers.Add(name, value);
}
/// <inheritdoc cref="IResponseMessage.AddHeader(string, string[])" />
@@ -52,6 +52,6 @@ public class ResponseMessage : IResponseMessage
? values.Union(existingValues).ToArray()
: values;
Headers[name] = new WireMockList<string>(newHeaderValues);
Headers[name] = newHeaderValues;
}
}

View File

@@ -20,7 +20,7 @@ internal class MappingConverter
public MappingConverter(MatcherMapper mapper)
{
_mapper = Guard.NotNull(mapper, nameof(mapper));
_mapper = Guard.NotNull(mapper);
}
public MappingModel ToMappingModel(IMapping mapping)
@@ -43,6 +43,7 @@ internal class MappingConverter
TimeSettings = TimeSettingsMapper.Map(mapping.TimeSettings),
Title = mapping.Title,
Description = mapping.Description,
UseWebhooksFireAndForget = mapping.UseWebhooksFireAndForget,
Priority = mapping.Priority != 0 ? mapping.Priority : null,
Scenario = mapping.Scenario,
WhenStateIs = mapping.ExecutionConditionState,
@@ -168,7 +169,7 @@ internal class MappingConverter
mappingModel.Response.BodyDestination = response.ResponseMessage.BodyDestination;
mappingModel.Response.StatusCode = response.ResponseMessage.StatusCode;
if (response.ResponseMessage.Headers != null && response.ResponseMessage.Headers.Count > 0)
if (response.ResponseMessage.Headers is { Count: > 0 })
{
mappingModel.Response.Headers = MapHeaders(response.ResponseMessage.Headers);
}
@@ -250,8 +251,15 @@ internal class MappingConverter
var newDictionary = new Dictionary<string, object>();
foreach (var entry in dictionary)
{
object value = entry.Value.Count == 1 ? entry.Value.ToString() : entry.Value;
newDictionary.Add(entry.Key, value);
// ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
if (entry.Value.Count == 1)
{
newDictionary.Add(entry.Key, entry.Value.ToString());
}
else
{
newDictionary.Add(entry.Key, entry.Value);
}
}
return newDictionary;

View File

@@ -66,7 +66,7 @@ internal class MatcherMapper
return new LinqMatcher(matchBehaviour, throwExceptionWhenMatcherFails, matchOperator, stringPatterns);
case nameof(ExactMatcher):
return new ExactMatcher(matchBehaviour, throwExceptionWhenMatcherFails, matchOperator, stringPatterns);
return new ExactMatcher(matchBehaviour, ignoreCase, throwExceptionWhenMatcherFails, matchOperator, stringPatterns);
case nameof(ExactObjectMatcher):
return CreateExactObjectMatcher(matchBehaviour, stringPatterns[0], throwExceptionWhenMatcherFails);

View File

@@ -0,0 +1,181 @@
using Stef.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using WireMock.Constants;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
namespace WireMock.Serialization;
internal class ProxyMappingConverter
{
private readonly WireMockServerSettings _settings;
private readonly IGuidUtils _guidUtils;
public ProxyMappingConverter(WireMockServerSettings settings, IGuidUtils guidUtils)
{
_settings = Guard.NotNull(settings);
_guidUtils = Guard.NotNull(guidUtils);
}
public IMapping ToMapping(IMapping? mapping, ProxyAndRecordSettings proxyAndRecordSettings, IRequestMessage requestMessage, ResponseMessage responseMessage)
{
var request = (Request?)mapping?.RequestMatcher;
var clientIPMatcher = request?.GetRequestMessageMatcher<RequestMessageClientIPMatcher>();
var pathMatcher = request?.GetRequestMessageMatcher<RequestMessagePathMatcher>();
var headerMatchers = request?.GetRequestMessageMatchers<RequestMessageHeaderMatcher>();
var cookieMatchers = request?.GetRequestMessageMatchers<RequestMessageCookieMatcher>();
var paramMatchers = request?.GetRequestMessageMatchers<RequestMessageParamMatcher>();
var methodMatcher = request?.GetRequestMessageMatcher<RequestMessageMethodMatcher>();
var bodyMatcher = request?.GetRequestMessageMatcher<RequestMessageBodyMatcher>();
var useDefinedRequestMatchers = proxyAndRecordSettings.UseDefinedRequestMatchers;
var excludedHeaders = new List<string>(proxyAndRecordSettings.ExcludedHeaders ?? new string[] { }) { "Cookie" };
var excludedCookies = proxyAndRecordSettings.ExcludedCookies ?? new string[] { };
var newRequest = Request.Create();
// ClientIP
if (useDefinedRequestMatchers && clientIPMatcher?.Matchers is not null)
{
newRequest.WithClientIP(clientIPMatcher.MatchOperator, clientIPMatcher.Matchers.ToArray());
}
// Path
if (useDefinedRequestMatchers && pathMatcher?.Matchers is not null)
{
newRequest.WithPath(pathMatcher.MatchOperator, pathMatcher.Matchers.ToArray());
}
else
{
newRequest.WithPath(requestMessage.Path);
}
// Method
if (useDefinedRequestMatchers && methodMatcher is not null)
{
newRequest.UsingMethod(methodMatcher.Methods);
}
else
{
newRequest.UsingMethod(requestMessage.Method);
}
// QueryParams
if (useDefinedRequestMatchers && paramMatchers is not null)
{
foreach (var paramMatcher in paramMatchers)
{
newRequest.WithParam(paramMatcher.Key, paramMatcher.MatchBehaviour, paramMatcher.Matchers!.ToArray());
}
}
else
{
requestMessage.Query?.Loop((key, value) => newRequest.WithParam(key, false, value.ToArray()));
}
// Cookies
if (useDefinedRequestMatchers && cookieMatchers is not null)
{
foreach (var cookieMatcher in cookieMatchers.Where(hm => hm.Matchers is not null))
{
if (!excludedCookies.Contains(cookieMatcher.Name, StringComparer.OrdinalIgnoreCase))
{
newRequest.WithCookie(cookieMatcher.Name, cookieMatcher.Matchers!);
}
}
}
else
{
requestMessage.Cookies?.Loop((key, value) =>
{
if (!excludedCookies.Contains(key, StringComparer.OrdinalIgnoreCase))
{
newRequest.WithCookie(key, value);
}
});
}
// Headers
if (useDefinedRequestMatchers && headerMatchers is not null)
{
foreach (var headerMatcher in headerMatchers.Where(hm => hm.Matchers is not null))
{
if (!excludedHeaders.Contains(headerMatcher.Name, StringComparer.OrdinalIgnoreCase))
{
newRequest.WithHeader(headerMatcher.Name, headerMatcher.Matchers!);
}
}
}
else
{
requestMessage.Headers?.Loop((key, value) =>
{
if (!excludedHeaders.Contains(key, StringComparer.OrdinalIgnoreCase))
{
newRequest.WithHeader(key, value.ToArray());
}
});
}
// Body
bool throwExceptionWhenMatcherFails = _settings.ThrowExceptionWhenMatcherFails == true;
if (useDefinedRequestMatchers && bodyMatcher?.Matchers is not null)
{
newRequest.WithBody(bodyMatcher.Matchers);
}
else
{
switch (requestMessage.BodyData?.DetectedBodyType)
{
case BodyType.Json:
newRequest.WithBody(new JsonMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsJson!, true, throwExceptionWhenMatcherFails));
break;
case BodyType.String:
newRequest.WithBody(new ExactMatcher(MatchBehaviour.AcceptOnMatch, true, throwExceptionWhenMatcherFails, MatchOperator.Or, requestMessage.BodyData.BodyAsString!));
break;
case BodyType.Bytes:
newRequest.WithBody(new ExactObjectMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsBytes!, throwExceptionWhenMatcherFails));
break;
}
}
// Title
var title = useDefinedRequestMatchers && !string.IsNullOrEmpty(mapping?.Title) ?
mapping!.Title :
$"Proxy Mapping for {requestMessage.Method} {requestMessage.Path}";
// Description
var description = useDefinedRequestMatchers && !string.IsNullOrEmpty(mapping?.Description) ?
mapping!.Description :
$"Proxy Mapping for {requestMessage.Method} {requestMessage.Path}";
return new Mapping
(
guid: _guidUtils.NewGuid(),
title: title,
description: description,
path: null,
settings: _settings,
requestMatcher: newRequest,
provider: Response.Create(responseMessage),
priority: WireMockConstants.ProxyPriority, // This was 0
scenario: null,
executionConditionState: null,
nextState: null,
stateTimes: null,
webhooks: null,
useWebhooksFireAndForget: null,
timeSettings: null
);
}
}

View File

@@ -20,6 +20,9 @@ internal static class WebhookMapper
{
Url = model.Request.Url,
Method = model.Request.Method,
Delay = model.Request.Delay,
MinimumRandomDelay = model.Request.MinimumRandomDelay,
MaximumRandomDelay = model.Request.MaximumRandomDelay,
Headers = model.Request.Headers?.ToDictionary(x => x.Key, x => new WireMockList<string>(x.Value)) ?? new Dictionary<string, WireMockList<string>>()
}
};
@@ -27,6 +30,7 @@ internal static class WebhookMapper
if (model.Request.UseTransformer == true)
{
webhook.Request.UseTransformer = true;
if (!Enum.TryParse<TransformerType>(model.Request.TransformerType, out var transformerType))
{
transformerType = TransformerType.Handlebars;
@@ -37,7 +41,6 @@ internal static class WebhookMapper
{
option = ReplaceNodeOptions.None;
}
webhook.Request.TransformerReplaceNodeOptions = option;
}
@@ -72,7 +75,7 @@ internal static class WebhookMapper
public static WebhookModel Map(IWebhook webhook)
{
Guard.NotNull(webhook);
var model = new WebhookModel
{
Request = new WebhookRequestModel
@@ -82,7 +85,10 @@ internal static class WebhookMapper
Headers = webhook.Request.Headers?.ToDictionary(x => x.Key, x => x.Value.ToString()),
UseTransformer = webhook.Request.UseTransformer,
TransformerType = webhook.Request.UseTransformer == true ? webhook.Request.TransformerType.ToString() : null,
TransformerReplaceNodeOptions = webhook.Request.TransformerReplaceNodeOptions.ToString()
TransformerReplaceNodeOptions = webhook.Request.TransformerReplaceNodeOptions.ToString(),
Delay = webhook.Request.Delay,
MinimumRandomDelay = webhook.Request.MinimumRandomDelay,
MaximumRandomDelay = webhook.Request.MaximumRandomDelay,
}
};

View File

@@ -1,164 +1,169 @@
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using WireMock.Models;
using WireMock.ResponseProviders;
using WireMock.Types;
namespace WireMock.Server
namespace WireMock.Server;
/// <summary>
/// IRespondWithAProvider
/// </summary>
public interface IRespondWithAProvider
{
/// <summary>
/// IRespondWithAProvider
/// Gets the unique identifier for this mapping.
/// </summary>
public interface IRespondWithAProvider
{
/// <summary>
/// Gets the unique identifier for this mapping.
/// </summary>
Guid Guid { get; }
Guid Guid { get; }
/// <summary>
/// Define a unique identifier for this mapping.
/// </summary>
/// <param name="guid">The unique identifier.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithGuid(Guid guid);
/// <summary>
/// Define a unique identifier for this mapping.
/// </summary>
/// <param name="guid">The unique identifier.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithGuid(Guid guid);
/// <summary>
/// Define the TimeSettings for this mapping.
/// </summary>
/// <param name="timeSettings">The TimeSettings.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithTimeSettings(ITimeSettings timeSettings);
/// <summary>
/// Define the TimeSettings for this mapping.
/// </summary>
/// <param name="timeSettings">The TimeSettings.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithTimeSettings(ITimeSettings timeSettings);
/// <summary>
/// Define a unique title for this mapping.
/// </summary>
/// <param name="title">The unique title.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithTitle(string title);
/// <summary>
/// Define a unique title for this mapping.
/// </summary>
/// <param name="title">The unique title.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithTitle(string title);
/// <summary>
/// Define a description for this mapping.
/// </summary>
/// <param name="description">The description.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithDescription(string description);
/// <summary>
/// Define a description for this mapping.
/// </summary>
/// <param name="description">The description.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithDescription(string description);
/// <summary>
/// Define the full filepath for this mapping.
/// </summary>
/// <param name="path">The full filepath.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithPath(string path);
/// <summary>
/// Define the full filepath for this mapping.
/// </summary>
/// <param name="path">The full filepath.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithPath(string path);
/// <summary>
/// Define a unique identifier for this mapping.
/// </summary>
/// <param name="guid">The unique identifier.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithGuid(string guid);
/// <summary>
/// Define a unique identifier for this mapping.
/// </summary>
/// <param name="guid">The unique identifier.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithGuid(string guid);
/// <summary>
/// Define the priority for this mapping.
/// </summary>
/// <param name="priority">The priority.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider AtPriority(int priority);
/// <summary>
/// Define the priority for this mapping.
/// </summary>
/// <param name="priority">The priority.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider AtPriority(int priority);
/// <summary>
/// The respond with.
/// </summary>
/// <param name="provider">The provider.</param>
void RespondWith(IResponseProvider provider);
/// <summary>
/// The respond with.
/// </summary>
/// <param name="provider">The provider.</param>
void RespondWith(IResponseProvider provider);
/// <summary>
/// Sets the the scenario.
/// </summary>
/// <param name="scenario">The scenario.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider InScenario(string scenario);
/// <summary>
/// Sets the the scenario.
/// </summary>
/// <param name="scenario">The scenario.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider InScenario(string scenario);
/// <summary>
/// Sets the the scenario with an integer value.
/// </summary>
/// <param name="scenario">The scenario.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider InScenario(int scenario);
/// <summary>
/// Sets the the scenario with an integer value.
/// </summary>
/// <param name="scenario">The scenario.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider InScenario(int scenario);
/// <summary>
/// Execute this respond only in case the current state is equal to specified one.
/// </summary>
/// <param name="state">Any object which identifies the current state</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WhenStateIs(string state);
/// <summary>
/// Execute this respond only in case the current state is equal to specified one.
/// </summary>
/// <param name="state">Any object which identifies the current state</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WhenStateIs(string state);
/// <summary>
/// Execute this respond only in case the current state is equal to specified one.
/// </summary>
/// <param name="state">Any object which identifies the current state</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WhenStateIs(int state);
/// <summary>
/// Execute this respond only in case the current state is equal to specified one.
/// </summary>
/// <param name="state">Any object which identifies the current state</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WhenStateIs(int state);
/// <summary>
/// Once this mapping is executed the state will be changed to specified one.
/// </summary>
/// <param name="state">Any object which identifies the new state</param>
/// <param name="times">The number of times this match should be matched before the state will be changed to the specified one. Default value is 1.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WillSetStateTo(string state, int? times = 1);
/// <summary>
/// Once this mapping is executed the state will be changed to specified one.
/// </summary>
/// <param name="state">Any object which identifies the new state</param>
/// <param name="times">The number of times this match should be matched before the state will be changed to the specified one. Default value is 1.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WillSetStateTo(string state, int? times = 1);
/// <summary>
/// Once this mapping is executed the state will be changed to specified one.
/// </summary>
/// <param name="state">Any object which identifies the new state</param>
/// <param name="times">The number of times this match should be matched before the state will be changed to the specified one. Default value is 1.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WillSetStateTo(int state, int? times = 1);
/// <summary>
/// Once this mapping is executed the state will be changed to specified one.
/// </summary>
/// <param name="state">Any object which identifies the new state</param>
/// <param name="times">The number of times this match should be matched before the state will be changed to the specified one. Default value is 1.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WillSetStateTo(int state, int? times = 1);
/// <summary>
/// Add (multiple) Webhook(s) to call after the response has been generated.
/// </summary>
/// <param name="webhooks">The Webhooks</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithWebhook(params IWebhook[] webhooks);
/// <summary>
/// Add (multiple) Webhook(s) to call after the response has been generated.
/// </summary>
/// <param name="webhooks">The Webhooks</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithWebhook(params IWebhook[] webhooks);
/// <summary>
/// Add a Webhook to call after the response has been generated.
/// </summary>
/// <param name="url">The Webhook Url</param>
/// <param name="method">The method to use. [optional]</param>
/// <param name="headers">The Headers to send. [optional]</param>
/// <param name="body">The body (as string) to send. [optional]</param>
/// <param name="useTransformer">Use Transformer. [optional]</param>
/// <param name="transformerType">The transformer type. [optional]</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithWebhook(
[NotNull] string url,
[CanBeNull] string method = "post",
[CanBeNull] IDictionary<string, WireMockList<string>> headers = null,
[CanBeNull] string body = null,
bool useTransformer = true,
TransformerType transformerType = TransformerType.Handlebars
);
/// <summary>
/// Support FireAndForget for any configured Webhooks
/// </summary>
/// <param name="UseWebhooksFireAndForget"></param>
/// <returns></returns>
IRespondWithAProvider WithWebhookFireAndForget(bool UseWebhooksFireAndForget);
/// <summary>
/// Add a Webhook to call after the response has been generated.
/// </summary>
/// <param name="url">The Webhook Url</param>
/// <param name="method">The method to use. [optional]</param>
/// <param name="headers">The Headers to send. [optional]</param>
/// <param name="body">The body (as json) to send. [optional]</param>
/// <param name="useTransformer">Use Transformer. [optional]</param>
/// <param name="transformerType">The transformer type. [optional]</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithWebhook(
[NotNull] string url,
[CanBeNull] string method = "post",
[CanBeNull] IDictionary<string, WireMockList<string>> headers = null,
[CanBeNull] object body = null,
bool useTransformer = true,
TransformerType transformerType = TransformerType.Handlebars
);
}
/// <summary>
/// Add a Webhook to call after the response has been generated.
/// </summary>
/// <param name="url">The Webhook Url</param>
/// <param name="method">The method to use. [optional]</param>
/// <param name="headers">The Headers to send. [optional]</param>
/// <param name="body">The body (as string) to send. [optional]</param>
/// <param name="useTransformer">Use Transformer. [optional]</param>
/// <param name="transformerType">The transformer type. [optional]</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithWebhook(
string url,
string? method = "post",
IDictionary<string, WireMockList<string>>? headers = null,
string? body = null,
bool useTransformer = true,
TransformerType transformerType = TransformerType.Handlebars
);
/// <summary>
/// Add a Webhook to call after the response has been generated.
/// </summary>
/// <param name="url">The Webhook Url</param>
/// <param name="method">The method to use. [optional]</param>
/// <param name="headers">The Headers to send. [optional]</param>
/// <param name="body">The body (as json) to send. [optional]</param>
/// <param name="useTransformer">Use Transformer. [optional]</param>
/// <param name="transformerType">The transformer type. [optional]</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithWebhook(
string url,
string? method = "post",
IDictionary<string, WireMockList<string>>? headers = null,
object? body = null,
bool useTransformer = true,
TransformerType transformerType = TransformerType.Handlebars
);
}

View File

@@ -30,6 +30,8 @@ internal class RespondWithAProvider : IRespondWithAProvider
private readonly WireMockServerSettings _settings;
private readonly bool _saveToFile;
private bool _useWebhookFireAndForget = false;
public Guid Guid { get; private set; } = Guid.NewGuid();
public IWebhook[]? Webhooks { get; private set; }
@@ -57,7 +59,7 @@ internal class RespondWithAProvider : IRespondWithAProvider
/// <param name="provider">The provider.</param>
public void RespondWith(IResponseProvider provider)
{
_registrationCallback(new Mapping(Guid, _title, _description, _path, _settings, _requestMatcher, provider, _priority, _scenario, _executionConditionState, _nextState, _timesInSameState, Webhooks, TimeSettings), _saveToFile);
_registrationCallback(new Mapping(Guid, _title, _description, _path, _settings, _requestMatcher, provider, _priority, _scenario, _executionConditionState, _nextState, _timesInSameState, Webhooks, _useWebhookFireAndForget, TimeSettings), _saveToFile);
}
/// <inheritdoc />
@@ -233,6 +235,13 @@ internal class RespondWithAProvider : IRespondWithAProvider
return this;
}
public IRespondWithAProvider WithWebhookFireAndForget(bool useWebhooksFireAndForget)
{
_useWebhookFireAndForget = useWebhooksFireAndForget;
return this;
}
private static IWebhook InitWebhook(
string url,
string method,

View File

@@ -236,6 +236,7 @@ public partial class WireMockServer
var proxyHelper = new ProxyHelper(settings);
var (responseMessage, mapping) = await proxyHelper.SendAsync(
null,
_settings.ProxyAndRecordSettings!,
_httpClientForProxy!,
requestMessage,

View File

@@ -198,7 +198,7 @@ public partial class WireMockServer
{
foreach (var cookieModel in requestModel.Cookies.Where(c => c.Matchers != null))
{
requestBuilder = requestBuilder.WithCookie(
requestBuilder = requestBuilder.WithCookie(
cookieModel.Name,
cookieModel.IgnoreCase == true,
cookieModel.RejectOnMatch == true ? MatchBehaviour.RejectOnMatch : MatchBehaviour.AcceptOnMatch,

View File

@@ -21,6 +21,7 @@ using WireMock.RequestBuilders;
using WireMock.ResponseProviders;
using WireMock.Serialization;
using WireMock.Settings;
using WireMock.Types;
namespace WireMock.Server;
@@ -48,7 +49,7 @@ public partial class WireMockServer : IWireMockServer
/// <inheritdoc />
[PublicAPI]
public int Port => Ports?.FirstOrDefault() ?? default(int);
public int Port => Ports?.FirstOrDefault() ?? default;
/// <inheritdoc />
[PublicAPI]
@@ -269,11 +270,22 @@ public partial class WireMockServer : IWireMockServer
}
else
{
urlOptions = new HostUrlOptions
if (settings.HostingScheme is not null)
{
UseSSL = settings.UseSSL == true,
Port = settings.Port
};
urlOptions = new HostUrlOptions
{
HostingScheme = settings.HostingScheme.Value,
Port = settings.Port
};
}
else
{
urlOptions = new HostUrlOptions
{
HostingScheme = settings.UseSSL == true ? HostingScheme.Https : HostingScheme.Http,
Port = settings.Port
};
}
}
_options.FileSystemHandler = _settings.FileSystemHandler;

View File

@@ -49,4 +49,13 @@ public class ProxyAndRecordSettings : HttpClientSettings
/// </summary>
//[PublicAPI]
//public bool PreferProxyMapping { get; set; }
/// <summary>
/// When SaveMapping is set to <c>true</c>, this setting can be used to control the behavior of the generated request matchers for the new mapping.
/// - <c>false</c>, the default matchers will be used.
/// - <c>true</c>, the defined mappings in the request wil be used for the new mapping.
///
/// Default value is false.
/// </summary>
public bool UseDefinedRequestMatchers { get; set; }
}

View File

@@ -94,6 +94,26 @@ internal class SimpleCommandLineParser
}, defaultValue);
}
public TEnum? GetEnumValue<TEnum>(string name)
where TEnum : struct
{
return GetValue(name, values =>
{
var value = values.FirstOrDefault();
return Enum.TryParse<TEnum>(value, true, out var enumValue) ? enumValue : (TEnum?)null;
});
}
public TEnum GetEnumValue<TEnum>(string name, TEnum defaultValue)
where TEnum : struct
{
return GetValue(name, values =>
{
var value = values.FirstOrDefault();
return Enum.TryParse<TEnum>(value, true, out var enumValue) ? enumValue : defaultValue;
}, defaultValue);
}
public string GetStringValue(string name, string defaultValue)
{
return GetValue(name, values => values.FirstOrDefault() ?? defaultValue, defaultValue);

View File

@@ -9,6 +9,7 @@ using WireMock.Handlers;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.RegularExpressions;
using WireMock.Types;
#if USE_ASPNETCORE
using Microsoft.Extensions.DependencyInjection;
using WireMock.Types;
@@ -22,7 +23,7 @@ namespace WireMock.Settings
public class WireMockServerSettings
{
/// <summary>
/// Gets or sets the port.
/// Gets or sets the http port.
/// </summary>
[PublicAPI]
public int? Port { get; set; }
@@ -34,6 +35,12 @@ namespace WireMock.Settings
[PublicAPI]
public bool? UseSSL { get; set; }
/// <summary>
/// Defines on which scheme (http/https) to host. (This overrides the <c>UseSSL</c> value).
/// </summary>
[PublicAPI]
public HostingScheme? HostingScheme { get; set; }
/// <summary>
/// Gets or sets whether to start admin interface.
/// </summary>

View File

@@ -54,14 +54,11 @@ public static class WireMockServerSettingsParser
UseRegexExtended = parser.GetBoolValue(nameof(WireMockServerSettings.UseRegexExtended), true),
WatchStaticMappings = parser.GetBoolValue("WatchStaticMappings"),
WatchStaticMappingsInSubdirectories = parser.GetBoolValue("WatchStaticMappingsInSubdirectories"),
HostingScheme = parser.GetEnumValue<HostingScheme>(nameof(WireMockServerSettings.HostingScheme))
};
#if USE_ASPNETCORE
settings.CorsPolicyOptions = parser.GetValue(nameof(WireMockServerSettings.CorsPolicyOptions), values =>
{
var value = string.Join(string.Empty, values);
return Enum.TryParse<CorsPolicyOptions>(value, true, out var corsPolicyOptions) ? corsPolicyOptions : CorsPolicyOptions.None;
});
settings.CorsPolicyOptions = parser.GetEnumValue(nameof(WireMockServerSettings.CorsPolicyOptions), CorsPolicyOptions.None);
#endif
if (logger != null)
@@ -77,7 +74,7 @@ public static class WireMockServerSettingsParser
{
settings.Port = parser.GetIntValue(nameof(WireMockServerSettings.Port));
}
else
else if (settings.HostingScheme is null)
{
settings.Urls = parser.GetValues("Urls", new[] { "http://*:9091/" });
}
@@ -95,7 +92,8 @@ public static class WireMockServerSettingsParser
SaveMapping = parser.GetBoolValue("SaveMapping"),
SaveMappingForStatusCodePattern = parser.GetStringValue("SaveMappingForStatusCodePattern", "*"),
SaveMappingToFile = parser.GetBoolValue("SaveMappingToFile"),
Url = proxyUrl
UseDefinedRequestMatchers = parser.GetBoolValue(nameof(ProxyAndRecordSettings.UseDefinedRequestMatchers)),
Url = proxyUrl!
};
string? proxyAddress = parser.GetStringValue("WebProxyAddress");
@@ -103,7 +101,7 @@ public static class WireMockServerSettingsParser
{
settings.ProxyAndRecordSettings.WebProxySettings = new WebProxySettings
{
Address = proxyAddress,
Address = proxyAddress!,
UserName = parser.GetStringValue("WebProxyUserName"),
Password = parser.GetStringValue("WebProxyPassword")
};

View File

@@ -8,5 +8,9 @@ interface ITransformer
{
ResponseMessage Transform(IMapping mapping, IRequestMessage requestMessage, IResponseMessage original, bool useTransformerForBodyAsFile, ReplaceNodeOptions options);
(IBodyData? BodyData, IDictionary<string, WireMockList<string>>? Headers) Transform(IMapping mapping, IRequestMessage originalRequestMessage, IResponseMessage originalResponseMessage, IBodyData? bodyData, IDictionary<string, WireMockList<string>>? headers, ReplaceNodeOptions options);
IBodyData? TransformBody(IMapping mapping, IRequestMessage originalRequestMessage, IResponseMessage originalResponseMessage, IBodyData? bodyData, ReplaceNodeOptions options);
IDictionary<string, WireMockList<string>>? TransformHeaders(IMapping mapping, IRequestMessage originalRequestMessage, IResponseMessage originalResponseMessage, IDictionary<string, WireMockList<string>>? headers);
string TransformString(IMapping mapping, IRequestMessage originalRequestMessage, IResponseMessage originalResponseMessage, string? value);
}

View File

@@ -0,0 +1,13 @@
using System.Diagnostics.CodeAnalysis;
namespace WireMock.Transformers;
[SuppressMessage("ReSharper", "InconsistentNaming")]
internal struct TransformModel
{
public IMapping mapping { get; set; }
public IRequestMessage request { get; set; }
public IResponseMessage? response { get; set; }
}

View File

@@ -1,9 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Stef.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using WireMock.Types;
using WireMock.Util;
@@ -18,22 +18,14 @@ internal class Transformer : ITransformer
_factory = Guard.NotNull(factory);
}
public (IBodyData? BodyData, IDictionary<string, WireMockList<string>>? Headers) Transform(
public IBodyData? TransformBody(
IMapping mapping,
IRequestMessage originalRequestMessage,
IResponseMessage originalResponseMessage,
IBodyData? bodyData,
IDictionary<string, WireMockList<string>>? headers,
ReplaceNodeOptions options)
{
var transformerContext = _factory.Create();
var model = new
{
mapping,
request = originalRequestMessage,
response = originalResponseMessage
};
var (transformerContext, model) = Create(mapping, originalRequestMessage, originalResponseMessage);
IBodyData? newBodyData = null;
if (bodyData?.DetectedBodyType != null)
@@ -41,20 +33,42 @@ internal class Transformer : ITransformer
newBodyData = TransformBodyData(transformerContext, options, model, bodyData, false);
}
return (newBodyData, TransformHeaders(transformerContext, model, headers));
return newBodyData;
}
public IDictionary<string, WireMockList<string>>? TransformHeaders(
IMapping mapping,
IRequestMessage originalRequestMessage,
IResponseMessage originalResponseMessage,
IDictionary<string, WireMockList<string>>? headers
)
{
var (transformerContext, model) = Create(mapping, originalRequestMessage, originalResponseMessage);
return TransformHeaders(transformerContext, model, headers);
}
public string TransformString(
IMapping mapping,
IRequestMessage originalRequestMessage,
IResponseMessage originalResponseMessage,
string? value
)
{
if (value is null)
{
return string.Empty;
}
var (transformerContext, model) = Create(mapping, originalRequestMessage, originalResponseMessage);
return transformerContext.ParseAndRender(value, model);
}
public ResponseMessage Transform(IMapping mapping, IRequestMessage requestMessage, IResponseMessage original, bool useTransformerForBodyAsFile, ReplaceNodeOptions options)
{
var transformerContext = _factory.Create();
var responseMessage = new ResponseMessage();
var model = new
{
mapping,
request = requestMessage
};
var (transformerContext, model) = Create(mapping, requestMessage, null);
if (original.BodyData?.DetectedBodyType != null)
{
@@ -85,7 +99,17 @@ internal class Transformer : ITransformer
return responseMessage;
}
private static IBodyData? TransformBodyData(ITransformerContext transformerContext, ReplaceNodeOptions options, object model, IBodyData original, bool useTransformerForBodyAsFile)
private (ITransformerContext TransformerContext, TransformModel Model) Create(IMapping mapping, IRequestMessage request, IResponseMessage? response)
{
return (_factory.Create(), new TransformModel
{
mapping = mapping,
request = request,
response = response
});
}
private static IBodyData? TransformBodyData(ITransformerContext transformerContext, ReplaceNodeOptions options, TransformModel model, IBodyData original, bool useTransformerForBodyAsFile)
{
return original.DetectedBodyType switch
{
@@ -96,7 +120,7 @@ internal class Transformer : ITransformer
};
}
private static IDictionary<string, WireMockList<string>> TransformHeaders(ITransformerContext transformerContext, object model, IDictionary<string, WireMockList<string>>? original)
private static IDictionary<string, WireMockList<string>> TransformHeaders(ITransformerContext transformerContext, TransformModel model, IDictionary<string, WireMockList<string>>? original)
{
if (original == null)
{

View File

@@ -17,6 +17,7 @@ public static class DictionaryExtensions
/// <param name="dictionary">The dictionary to loop (can be null).</param>
/// <param name="action">The action.</param>
public static void Loop<TKey, TValue>(this IDictionary<TKey, TValue>? dictionary, Action<TKey, TValue> action)
where TKey : notnull
{
Guard.NotNull(action);

View File

@@ -0,0 +1,16 @@
using System;
namespace WireMock.Util;
internal interface IGuidUtils
{
Guid NewGuid();
}
internal class GuidUtils : IGuidUtils
{
public Guid NewGuid()
{
return Guid.NewGuid();
}
}

View File

@@ -32,7 +32,7 @@ internal static class TypeBuilderUtils
CreateGetSetMethods(typeBuilder, property.Key, property.Value);
}
var type = typeBuilder.CreateTypeInfo().AsType();
var type = typeBuilder.CreateTypeInfo()!.AsType();
Types.TryAdd(properties, type);
@@ -43,6 +43,7 @@ internal static class TypeBuilderUtils
/// https://stackoverflow.com/questions/3804367/testing-for-equality-between-dictionaries-in-c-sharp
/// </summary>
private static bool Compare<TKey, TValue>(IDictionary<TKey, TValue> dict1, IDictionary<TKey, TValue> dict2)
where TKey : notnull
{
if (dict1 == dict2)
{

View File

@@ -24,11 +24,11 @@ public class WireMockAssertionsTests : IDisposable
public WireMockAssertionsTests()
{
_server = WireMockServer.Start();
_server.Given(Request.Create().UsingAnyMethod())
.RespondWith(Response.Create().WithSuccess());
_server.Given(Request.Create().UsingAnyMethod()).RespondWith(Response.Create().WithSuccess());
_portUsed = _server.Ports.First();
_httpClient = new HttpClient { BaseAddress = new Uri(_server.Urls[0]) };
_httpClient = new HttpClient { BaseAddress = new Uri(_server.Url!) };
}
[Fact]
@@ -61,6 +61,18 @@ public class WireMockAssertionsTests : IDisposable
.AtAbsoluteUrl($"http://localhost:{_portUsed}/anyurl");
}
[Fact]
public async Task HaveReceived1Calls_AtAbsoluteUrlUsingPost_WhenAPostCallWasMadeToAbsoluteUrl_Should_BeOK()
{
await _httpClient.PostAsync("anyurl", new StringContent("")).ConfigureAwait(false);
_server.Should()
.HaveReceived(1).Calls()
.AtAbsoluteUrl($"http://localhost:{_portUsed}/anyurl")
.And
.UsingPost();
}
[Fact]
public async Task HaveReceived2Calls_AtAbsoluteUrl_WhenACallWasMadeToAbsoluteUrl_Should_BeOK()
{
@@ -123,15 +135,20 @@ public class WireMockAssertionsTests : IDisposable
}
[Fact]
public async Task HaveReceivedACall_WithHeader_WhenACallWasMadeWithExpectedHeaderAmongMultipleHeaderValues_Should_BeOK()
public async Task HaveReceivedACall_WithHeader_WhenMultipleCallsWereMadeWithExpectedHeaderAmongMultipleHeaderValues_Should_BeOK()
{
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
await _httpClient.GetAsync("").ConfigureAwait(false);
await _httpClient.GetAsync("1").ConfigureAwait(false);
_httpClient.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("EN"));
await _httpClient.GetAsync("2").ConfigureAwait(false);
_server.Should()
.HaveReceivedACall()
.WithHeader("Accept", new[] { "application/xml", "application/json" });
.WithHeader("Accept", new[] { "application/xml", "application/json" })
.And
.WithHeader("Accept-Language", new[] { "EN" });
}
[Fact]
@@ -145,7 +162,7 @@ public class WireMockAssertionsTests : IDisposable
act.Should().Throw<Exception>()
.And.Message.Should()
.Contain("to contain key \"Authorization\".");
.Contain("to contain \"Authorization\".");
}
[Fact]
@@ -431,16 +448,90 @@ public class WireMockAssertionsTests : IDisposable
.UsingOptions();
}
[Fact]
public async Task HaveReceivedACall_UsingPost_WhenACallWasMadeUsingPost_Should_BeOK()
[Theory]
[InlineData("POST")]
[InlineData("Post")]
public async Task HaveReceivedACall_UsingPost_WhenACallWasMadeUsingPost_Should_BeOK(string method)
{
await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod("POST"), "anyurl")).ConfigureAwait(false);
await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod(method), "anyurl")).ConfigureAwait(false);
_server.Should()
.HaveReceivedACall()
.UsingPost();
}
[Fact]
public async Task HaveReceived1Calls_AtAbsoluteUrlUsingPost_ShouldChain()
{
// Arrange
var server = WireMockServer.Start();
server
.Given(Request.Create().WithPath("/a").UsingGet())
.RespondWith(Response.Create().WithBody("A response").WithStatusCode(HttpStatusCode.OK));
server
.Given(Request.Create().WithPath("/b").UsingPost())
.RespondWith(Response.Create().WithBody("B response").WithStatusCode(HttpStatusCode.OK));
server
.Given(Request.Create().WithPath("/c").UsingPost())
.RespondWith(Response.Create().WithBody("C response").WithStatusCode(HttpStatusCode.OK));
// Act
var httpClient = new HttpClient();
await httpClient.GetAsync($"{server.Url}/a");
await httpClient.PostAsync($"{server.Url}/b", new StringContent("B"));
await httpClient.PostAsync($"{server.Url}/c", new StringContent("C"));
// Assert
server
.Should()
.HaveReceived(1)
.Calls()
.AtUrl($"{server.Url}/a")
.And
.UsingGet();
server
.Should()
.HaveReceived(1)
.Calls()
.AtUrl($"{server.Url}/b")
.And
.UsingPost();
server
.Should()
.HaveReceived(1)
.Calls()
.AtUrl($"{server.Url}/c")
.And
.UsingPost();
server
.Should()
.HaveReceived(3)
.Calls();
server
.Should()
.HaveReceived(1)
.Calls()
.UsingGet();
server
.Should()
.HaveReceived(2)
.Calls()
.UsingPost();
server.Stop();
}
[Fact]
public async Task HaveReceivedACall_UsingPatch_WhenACallWasMadeUsingPatch_Should_BeOK()
{

View File

@@ -2,141 +2,153 @@ using NFluent;
using WireMock.Matchers;
using Xunit;
namespace WireMock.Net.Tests.Matchers
namespace WireMock.Net.Tests.Matchers;
public class ExactMatcherTests
{
public class ExactMatcherTests
[Fact]
public void ExactMatcher_GetName()
{
[Fact]
public void ExactMatcher_GetName()
{
// Assign
var matcher = new ExactMatcher("X");
// Assign
var matcher = new ExactMatcher("X");
// Act
string name = matcher.Name;
// Act
string name = matcher.Name;
// Assert
Check.That(name).Equals("ExactMatcher");
}
// Assert
Check.That(name).Equals("ExactMatcher");
}
[Fact]
public void ExactMatcher_GetPatterns()
{
// Assign
var matcher = new ExactMatcher("X");
[Fact]
public void ExactMatcher_GetPatterns()
{
// Assign
var matcher = new ExactMatcher("X");
// Act
var patterns = matcher.GetPatterns();
// Act
var patterns = matcher.GetPatterns();
// Assert
Check.That(patterns).ContainsExactly("X");
}
// Assert
Check.That(patterns).ContainsExactly("X");
}
[Fact]
public void ExactMatcher_IsMatch_WithSinglePattern_ReturnsMatch1_0()
{
// Assign
var matcher = new ExactMatcher("x");
[Fact]
public void ExactMatcher_IsMatch_IgnoreCase()
{
// Assign
var matcher = new ExactMatcher(true, "x");
// Act
double result = matcher.IsMatch("x");
// Act
double result = matcher.IsMatch("X");
// Assert
Check.That(result).IsEqualTo(1.0);
}
// Assert
Check.That(result).IsEqualTo(1.0);
}
[Fact]
public void ExactMatcher_IsMatch_WithSinglePattern_ReturnsMatch0_0()
{
// Assign
var matcher = new ExactMatcher("x");
[Fact]
public void ExactMatcher_IsMatch_WithSinglePattern_ReturnsMatch1_0()
{
// Assign
var matcher = new ExactMatcher("x");
// Act
double result = matcher.IsMatch("y");
// Act
double result = matcher.IsMatch("x");
// Assert
Check.That(result).IsEqualTo(0.0);
}
// Assert
Check.That(result).IsEqualTo(1.0);
}
[Fact]
public void ExactMatcher_IsMatch_WithMultiplePatterns_Or_ReturnsMatch_1_0()
{
// Assign
var matcher = new ExactMatcher("x", "y");
[Fact]
public void ExactMatcher_IsMatch_WithSinglePattern_ReturnsMatch0_0()
{
// Assign
var matcher = new ExactMatcher("x");
// Act
double result = matcher.IsMatch("x");
// Act
double result = matcher.IsMatch("y");
// Assert
Check.That(result).IsEqualTo(1.0);
}
// Assert
Check.That(result).IsEqualTo(0.0);
}
[Fact]
public void ExactMatcher_IsMatch_WithMultiplePatterns_And_ReturnsMatch_0_0()
{
// Assign
var matcher = new ExactMatcher("x", "y");
[Fact]
public void ExactMatcher_IsMatch_WithMultiplePatterns_Or_ReturnsMatch_1_0()
{
// Assign
var matcher = new ExactMatcher("x", "y");
// Act
double result = matcher.IsMatch("x");
// Act
double result = matcher.IsMatch("x");
// Assert
Check.That(result).IsEqualTo(1.0);
}
// Assert
Check.That(result).IsEqualTo(1.0);
}
[Theory]
[InlineData(MatchOperator.Or, 1.0d)]
[InlineData(MatchOperator.And, 0.0d)]
[InlineData(MatchOperator.Average, 0.5d)]
public void ExactMatcher_IsMatch_WithMultiplePatterns_Average_ReturnsMatch(MatchOperator matchOperator, double score)
{
// Assign
var matcher = new ExactMatcher(MatchBehaviour.AcceptOnMatch, false, matchOperator, "x", "y");
[Fact]
public void ExactMatcher_IsMatch_WithMultiplePatterns_And_ReturnsMatch_0_0()
{
// Assign
var matcher = new ExactMatcher("x", "y");
// Act
double result = matcher.IsMatch("x");
// Act
double result = matcher.IsMatch("x");
// Assert
Check.That(result).IsEqualTo(score);
}
// Assert
Check.That(result).IsEqualTo(1.0);
}
[Fact]
public void ExactMatcher_IsMatch_SinglePattern()
{
// Assign
var matcher = new ExactMatcher("cat");
[Theory]
[InlineData(MatchOperator.Or, 1.0d)]
[InlineData(MatchOperator.And, 0.0d)]
[InlineData(MatchOperator.Average, 0.5d)]
public void ExactMatcher_IsMatch_WithMultiplePatterns_Average_ReturnsMatch(MatchOperator matchOperator, double score)
{
// Assign
var matcher = new ExactMatcher(MatchBehaviour.AcceptOnMatch, false, false, matchOperator, "x", "y");
// Act
double result = matcher.IsMatch("caR");
// Act
double result = matcher.IsMatch("x");
// Assert
Check.That(result).IsEqualTo(0.0);
}
// Assert
Check.That(result).IsEqualTo(score);
}
[Fact]
public void ExactMatcher_IsMatch_SinglePattern_AcceptOnMatch()
{
// Assign
var matcher = new ExactMatcher(MatchBehaviour.AcceptOnMatch, false, MatchOperator.Or, "cat");
[Fact]
public void ExactMatcher_IsMatch_SinglePattern()
{
// Assign
var matcher = new ExactMatcher("cat");
// Act
double result = matcher.IsMatch("cat");
// Act
double result = matcher.IsMatch("caR");
// Assert
Check.That(result).IsEqualTo(1.0);
}
// Assert
Check.That(result).IsEqualTo(0.0);
}
[Fact]
public void ExactMatcher_IsMatch_SinglePattern_RejectOnMatch()
{
// Assign
var matcher = new ExactMatcher(MatchBehaviour.RejectOnMatch, false, MatchOperator.Or, "cat");
[Fact]
public void ExactMatcher_IsMatch_SinglePattern_AcceptOnMatch()
{
// Assign
var matcher = new ExactMatcher(MatchBehaviour.AcceptOnMatch, false, false, MatchOperator.Or, "cat");
// Act
double result = matcher.IsMatch("cat");
// Act
double result = matcher.IsMatch("cat");
// Assert
Check.That(result).IsEqualTo(0.0);
}
// Assert
Check.That(result).IsEqualTo(1.0);
}
[Fact]
public void ExactMatcher_IsMatch_SinglePattern_RejectOnMatch()
{
// Assign
var matcher = new ExactMatcher(MatchBehaviour.RejectOnMatch, false, false, MatchOperator.Or, "cat");
// Act
double result = matcher.IsMatch("cat");
// Assert
Check.That(result).IsEqualTo(0.0);
}
}

View File

@@ -1,4 +1,4 @@
using System.Threading.Tasks;
using System.Threading.Tasks;
using Moq;
using NFluent;
using WireMock.Owin;
@@ -18,7 +18,6 @@ namespace WireMock.Net.Tests.Owin
{
private readonly Mock<IWireMockMiddlewareOptions> _optionsMock;
private readonly Mock<IOwinResponseMapper> _responseMapperMock;
private readonly Mock<IContext> _contextMock;
private readonly GlobalExceptionMiddleware _sut;
@@ -35,10 +34,10 @@ namespace WireMock.Net.Tests.Owin
}
[Fact]
public void GlobalExceptionMiddleware_Invoke_NullAsNext_Throws()
public void GlobalExceptionMiddleware_Invoke_NullAsNext_DoesNotInvokeNextAndDoesNotThrow()
{
// Act
Check.ThatAsyncCode(() => _sut.Invoke(_contextMock.Object)).ThrowsAny();
Check.ThatAsyncCode(() => _sut.Invoke(null)).DoesNotThrow();
}
}
}
}

View File

@@ -176,7 +176,7 @@ namespace WireMock.Net.Tests.Owin
_mappingMock.SetupGet(m => m.Provider).Returns(responseBuilder);
_mappingMock.SetupGet(m => m.Settings).Returns(settings);
var newMappingFromProxy = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, settings, Request.Create(), Response.Create(), 0, null, null, null, null, null, null);
var newMappingFromProxy = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, settings, Request.Create(), Response.Create(), 0, null, null, null, null, null, false, null);
_mappingMock.Setup(m => m.ProvideResponseAsync(It.IsAny<RequestMessage>())).ReturnsAsync((new ResponseMessage(), newMappingFromProxy));
var requestBuilder = Request.Create().UsingAnyMethod();
@@ -230,7 +230,7 @@ namespace WireMock.Net.Tests.Owin
_mappingMock.SetupGet(m => m.Provider).Returns(responseBuilder);
_mappingMock.SetupGet(m => m.Settings).Returns(settings);
var newMappingFromProxy = new Mapping(Guid.NewGuid(), "my-title", "my-description", null, settings, Request.Create(), Response.Create(), 0, null, null, null, null, null, null);
var newMappingFromProxy = new Mapping(Guid.NewGuid(), "my-title", "my-description", null, settings, Request.Create(), Response.Create(), 0, null, null, null, null, null, false, null);
_mappingMock.Setup(m => m.ProvideResponseAsync(It.IsAny<RequestMessage>())).ReturnsAsync((new ResponseMessage(), newMappingFromProxy));
var requestBuilder = Request.Create().UsingAnyMethod();

View File

@@ -13,455 +13,454 @@ using WireMock.Types;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.RequestMatchers
namespace WireMock.Net.Tests.RequestMatchers;
public class RequestMessageBodyMatcherTests
{
public class RequestMessageBodyMatcherTests
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_IStringMatcher()
{
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_IStringMatcher()
// Assign
var body = new BodyData
{
// Assign
var body = new BodyData
BodyAsString = "b",
DetectedBodyType = BodyType.String
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(1d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1d);
// Verify
stringMatcherMock.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock.Verify(m => m.IsMatch("b"), Times.Once);
}
[Theory]
[InlineData(1d, 1d, 1d)]
[InlineData(0d, 1d, 1d)]
[InlineData(1d, 0d, 1d)]
[InlineData(0d, 0d, 0d)]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_IStringMatchers_Or(double one, double two, double expected)
{
// Assign
var body = new BodyData
{
BodyAsString = "b",
DetectedBodyType = BodyType.String
};
var stringMatcherMock1 = new Mock<IStringMatcher>();
stringMatcherMock1.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(one);
var stringMatcherMock2 = new Mock<IStringMatcher>();
stringMatcherMock2.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(two);
var matchers = new[] { stringMatcherMock1.Object, stringMatcherMock2.Object };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(MatchOperator.Or, matchers.Cast<IMatcher>().ToArray());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(expected);
// Verify
stringMatcherMock1.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock1.Verify(m => m.IsMatch("b"), Times.Once);
stringMatcherMock2.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock2.Verify(m => m.IsMatch("b"), Times.Once);
stringMatcherMock2.VerifyNoOtherCalls();
}
[Theory]
[InlineData(1d, 1d, 1d)]
[InlineData(0d, 1d, 0d)]
[InlineData(1d, 0d, 0d)]
[InlineData(0d, 0d, 0d)]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_IStringMatchers_And(double one, double two, double expected)
{
// Assign
var body = new BodyData
{
BodyAsString = "b",
DetectedBodyType = BodyType.String
};
var stringMatcherMock1 = new Mock<IStringMatcher>();
stringMatcherMock1.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(one);
var stringMatcherMock2 = new Mock<IStringMatcher>();
stringMatcherMock2.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(two);
var matchers = new[] { stringMatcherMock1.Object, stringMatcherMock2.Object };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(MatchOperator.And, matchers.Cast<IMatcher>().ToArray());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(expected);
// Verify
stringMatcherMock1.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock1.Verify(m => m.IsMatch("b"), Times.Once);
stringMatcherMock2.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock2.Verify(m => m.IsMatch("b"), Times.Once);
stringMatcherMock2.VerifyNoOtherCalls();
}
[Theory]
[InlineData(1d, 1d, 1d)]
[InlineData(0d, 1d, 0.5d)]
[InlineData(1d, 0d, 0.5d)]
[InlineData(0d, 0d, 0d)]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_IStringMatchers_Average(double one, double two, double expected)
{
// Assign
var body = new BodyData
{
BodyAsString = "b",
DetectedBodyType = BodyType.String
};
var stringMatcherMock1 = new Mock<IStringMatcher>();
stringMatcherMock1.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(one);
var stringMatcherMock2 = new Mock<IStringMatcher>();
stringMatcherMock2.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(two);
var matchers = new[] { stringMatcherMock1.Object, stringMatcherMock2.Object };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(MatchOperator.Average, matchers.Cast<IMatcher>().ToArray());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(expected);
// Verify
stringMatcherMock1.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock1.Verify(m => m.IsMatch("b"), Times.Once);
stringMatcherMock2.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock2.Verify(m => m.IsMatch("b"), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsBytes = new byte[] { 1 },
DetectedBodyType = BodyType.Bytes
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.0d);
// Verify
stringMatcherMock.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Never);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = new { value = 42 },
DetectedBodyType = BodyType.Json
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(1.0d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
// Verify
stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_and_BodyAsString_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = new { value = 42 },
BodyAsString = "orig",
DetectedBodyType = BodyType.Json
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(1d);
stringMatcherMock.SetupGet(m => m.MatchOperator).Returns(MatchOperator.Or);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1d);
// Verify
stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_IObjectMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = 42,
DetectedBodyType = BodyType.Json
};
var objectMatcherMock = new Mock<IObjectMatcher>();
objectMatcherMock.Setup(m => m.IsMatch(It.IsAny<object>())).Returns(1d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(objectMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1d);
// Verify
objectMatcherMock.Verify(m => m.IsMatch(42), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_CSharpCodeMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = new { value = 42 },
DetectedBodyType = BodyType.Json
};
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(new CSharpCodeMatcher(MatchBehaviour.AcceptOnMatch, MatchOperator.Or, "return it.value == 42;"));
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
}
[Theory]
[InlineData(null, 0.0)]
[InlineData(new byte[0], 0.0)]
[InlineData(new byte[] { 48 }, 1.0)]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_NotNullOrEmptyObjectMatcher(byte[] bytes, double expected)
{
// Assign
var body = new BodyData
{
BodyAsBytes = bytes,
DetectedBodyType = BodyType.Bytes
};
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(new NotNullOrEmptyMatcher());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
score.Should().Be(expected);
}
[Theory]
[InlineData(null, 0.0)]
[InlineData("", 0.0)]
[InlineData("x", 1.0)]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_NotNullOrEmptyObjectMatcher(string data, double expected)
{
// Assign
var body = new BodyData
{
BodyAsString = data,
DetectedBodyType = BodyType.String
};
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(new NotNullOrEmptyMatcher());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
score.Should().Be(expected);
}
[Theory]
[InlineData(new byte[] { 1 })]
[InlineData(new byte[] { 48 })]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_IObjectMatcher(byte[] bytes)
{
// Assign
var body = new BodyData
{
BodyAsBytes = bytes,
DetectedBodyType = BodyType.Bytes
};
var objectMatcherMock = new Mock<IObjectMatcher>();
objectMatcherMock.Setup(m => m.IsMatch(It.IsAny<object>())).Returns(1.0d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(objectMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
// Verify
objectMatcherMock.Verify(m => m.IsMatch(It.IsAny<byte[]>()), Times.Once);
}
[Theory]
[MemberData(nameof(MatchingScoreData))]
public async Task RequestMessageBodyMatcher_GetMatchingScore_Funcs_Matching(object body, RequestMessageBodyMatcher matcher, bool shouldMatch)
{
// assign
BodyData bodyData;
if (body is byte[] b)
{
var bodyParserSettings = new BodyParserSettings
{
BodyAsString = "b",
DetectedBodyType = BodyType.String
Stream = new MemoryStream(b),
ContentType = null,
DeserializeJson = true
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(1d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1d);
// Verify
stringMatcherMock.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock.Verify(m => m.IsMatch("b"), Times.Once);
bodyData = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false);
}
[Theory]
[InlineData(1d, 1d, 1d)]
[InlineData(0d, 1d, 1d)]
[InlineData(1d, 0d, 1d)]
[InlineData(0d, 0d, 0d)]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_IStringMatchers_Or(double one, double two, double expected)
else if (body is string s)
{
// Assign
var body = new BodyData
var bodyParserSettings = new BodyParserSettings
{
BodyAsString = "b",
DetectedBodyType = BodyType.String
Stream = new MemoryStream(Encoding.UTF8.GetBytes(s)),
ContentType = null,
DeserializeJson = true
};
var stringMatcherMock1 = new Mock<IStringMatcher>();
stringMatcherMock1.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(one);
var stringMatcherMock2 = new Mock<IStringMatcher>();
stringMatcherMock2.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(two);
var matchers = new[] { stringMatcherMock1.Object, stringMatcherMock2.Object };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(MatchOperator.Or, matchers.Cast<IMatcher>().ToArray());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(expected);
// Verify
stringMatcherMock1.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock1.Verify(m => m.IsMatch("b"), Times.Once);
stringMatcherMock2.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock2.Verify(m => m.IsMatch("b"), Times.Once);
stringMatcherMock2.VerifyNoOtherCalls();
bodyData = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false);
}
else
{
throw new Exception();
}
[Theory]
[InlineData(1d, 1d, 1d)]
[InlineData(0d, 1d, 0d)]
[InlineData(1d, 0d, 0d)]
[InlineData(0d, 0d, 0d)]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_IStringMatchers_And(double one, double two, double expected)
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", bodyData);
// act
var result = new RequestMatchResult();
var score = matcher.GetMatchingScore(requestMessage, result);
// assert
Check.That(score).IsEqualTo(shouldMatch ? 1d : 0d);
}
public static TheoryData<object, RequestMessageBodyMatcher, bool> MatchingScoreData
{
get
{
// Assign
var body = new BodyData
var json = "{'a':'b'}";
var str = "HelloWorld";
var bytes = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00 };
return new TheoryData<object, RequestMessageBodyMatcher, bool>
{
BodyAsString = "b",
DetectedBodyType = BodyType.String
// JSON match +++
{json, new RequestMessageBodyMatcher((object? o) => ((dynamic) o!).a == "b"), true},
{json, new RequestMessageBodyMatcher((string? s) => s == json), true},
{json, new RequestMessageBodyMatcher((byte[]? b) => b.SequenceEqual(Encoding.UTF8.GetBytes(json))), true},
// JSON no match ---
{json, new RequestMessageBodyMatcher((object? o) => false), false},
{json, new RequestMessageBodyMatcher((string? s) => false), false},
{json, new RequestMessageBodyMatcher((byte[]? b) => false), false},
{json, new RequestMessageBodyMatcher(), false },
// string match +++
{str, new RequestMessageBodyMatcher((object? o) => o == null), true},
{str, new RequestMessageBodyMatcher((string? s) => s == str), true},
{str, new RequestMessageBodyMatcher((byte[]? b) => b.SequenceEqual(Encoding.UTF8.GetBytes(str))), true},
// string no match ---
{str, new RequestMessageBodyMatcher((object? o) => false), false},
{str, new RequestMessageBodyMatcher((string? s) => false), false},
{str, new RequestMessageBodyMatcher((byte[]? b) => false), false},
{str, new RequestMessageBodyMatcher(), false },
// binary match +++
{bytes, new RequestMessageBodyMatcher((object? o) => o == null), true},
{bytes, new RequestMessageBodyMatcher((string? s) => s == null), true},
{bytes, new RequestMessageBodyMatcher((byte[]? b) => b.SequenceEqual(bytes)), true},
// binary no match ---
{bytes, new RequestMessageBodyMatcher((object? o) => false), false},
{bytes, new RequestMessageBodyMatcher((string? s) => false), false},
{bytes, new RequestMessageBodyMatcher((byte[]? b) => false), false},
{bytes, new RequestMessageBodyMatcher(), false },
};
var stringMatcherMock1 = new Mock<IStringMatcher>();
stringMatcherMock1.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(one);
var stringMatcherMock2 = new Mock<IStringMatcher>();
stringMatcherMock2.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(two);
var matchers = new[] { stringMatcherMock1.Object, stringMatcherMock2.Object };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(MatchOperator.And, matchers.Cast<IMatcher>().ToArray());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(expected);
// Verify
stringMatcherMock1.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock1.Verify(m => m.IsMatch("b"), Times.Once);
stringMatcherMock2.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock2.Verify(m => m.IsMatch("b"), Times.Once);
stringMatcherMock2.VerifyNoOtherCalls();
}
[Theory]
[InlineData(1d, 1d, 1d)]
[InlineData(0d, 1d, 0.5d)]
[InlineData(1d, 0d, 0.5d)]
[InlineData(0d, 0d, 0d)]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_IStringMatchers_Average(double one, double two, double expected)
{
// Assign
var body = new BodyData
{
BodyAsString = "b",
DetectedBodyType = BodyType.String
};
var stringMatcherMock1 = new Mock<IStringMatcher>();
stringMatcherMock1.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(one);
var stringMatcherMock2 = new Mock<IStringMatcher>();
stringMatcherMock2.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(two);
var matchers = new[] { stringMatcherMock1.Object, stringMatcherMock2.Object };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(MatchOperator.Average, matchers.Cast<IMatcher>().ToArray());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(expected);
// Verify
stringMatcherMock1.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock1.Verify(m => m.IsMatch("b"), Times.Once);
stringMatcherMock2.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock2.Verify(m => m.IsMatch("b"), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsBytes = new byte[] { 1 },
DetectedBodyType = BodyType.Bytes
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.0d);
// Verify
stringMatcherMock.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Never);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = new { value = 42 },
DetectedBodyType = BodyType.Json
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(1.0d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
// Verify
stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_and_BodyAsString_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = new { value = 42 },
BodyAsString = "orig",
DetectedBodyType = BodyType.Json
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(1d);
stringMatcherMock.SetupGet(m => m.MatchOperator).Returns(MatchOperator.Or);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1d);
// Verify
stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_IObjectMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = 42,
DetectedBodyType = BodyType.Json
};
var objectMatcherMock = new Mock<IObjectMatcher>();
objectMatcherMock.Setup(m => m.IsMatch(It.IsAny<object>())).Returns(1d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(objectMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1d);
// Verify
objectMatcherMock.Verify(m => m.IsMatch(42), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_CSharpCodeMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = new { value = 42 },
DetectedBodyType = BodyType.Json
};
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(new CSharpCodeMatcher(MatchBehaviour.AcceptOnMatch, MatchOperator.Or, "return it.value == 42;"));
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
}
[Theory]
[InlineData(null, 0.0)]
[InlineData(new byte[0], 0.0)]
[InlineData(new byte[] { 48 }, 1.0)]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_NotNullOrEmptyObjectMatcher(byte[] bytes, double expected)
{
// Assign
var body = new BodyData
{
BodyAsBytes = bytes,
DetectedBodyType = BodyType.Bytes
};
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(new NotNullOrEmptyMatcher());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
score.Should().Be(expected);
}
[Theory]
[InlineData(null, 0.0)]
[InlineData("", 0.0)]
[InlineData("x", 1.0)]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_NotNullOrEmptyObjectMatcher(string data, double expected)
{
// Assign
var body = new BodyData
{
BodyAsString = data,
DetectedBodyType = BodyType.String
};
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(new NotNullOrEmptyMatcher());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
score.Should().Be(expected);
}
[Theory]
[InlineData(new byte[] { 1 })]
[InlineData(new byte[] { 48 })]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_IObjectMatcher(byte[] bytes)
{
// Assign
var body = new BodyData
{
BodyAsBytes = bytes,
DetectedBodyType = BodyType.Bytes
};
var objectMatcherMock = new Mock<IObjectMatcher>();
objectMatcherMock.Setup(m => m.IsMatch(It.IsAny<object>())).Returns(1.0d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(objectMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
// Verify
objectMatcherMock.Verify(m => m.IsMatch(It.IsAny<byte[]>()), Times.Once);
}
[Theory]
[MemberData(nameof(MatchingScoreData))]
public async Task RequestMessageBodyMatcher_GetMatchingScore_Funcs_Matching(object body, RequestMessageBodyMatcher matcher, bool shouldMatch)
{
// assign
BodyData bodyData;
if (body is byte[] b)
{
var bodyParserSettings = new BodyParserSettings
{
Stream = new MemoryStream(b),
ContentType = null,
DeserializeJson = true
};
bodyData = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false);
}
else if (body is string s)
{
var bodyParserSettings = new BodyParserSettings
{
Stream = new MemoryStream(Encoding.UTF8.GetBytes(s)),
ContentType = null,
DeserializeJson = true
};
bodyData = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false);
}
else
{
throw new Exception();
}
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", bodyData);
// act
var result = new RequestMatchResult();
var score = matcher.GetMatchingScore(requestMessage, result);
// assert
Check.That(score).IsEqualTo(shouldMatch ? 1d : 0d);
}
public static TheoryData<object, RequestMessageBodyMatcher, bool> MatchingScoreData
{
get
{
var json = "{'a':'b'}";
var str = "HelloWorld";
var bytes = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00 };
return new TheoryData<object, RequestMessageBodyMatcher, bool>
{
// JSON match +++
{json, new RequestMessageBodyMatcher((object o) => ((dynamic) o).a == "b"), true},
{json, new RequestMessageBodyMatcher((string s) => s == json), true},
{json, new RequestMessageBodyMatcher((byte[] b) => b.SequenceEqual(Encoding.UTF8.GetBytes(json))), true},
// JSON no match ---
{json, new RequestMessageBodyMatcher((object o) => false), false},
{json, new RequestMessageBodyMatcher((string s) => false), false},
{json, new RequestMessageBodyMatcher((byte[] b) => false), false},
{json, new RequestMessageBodyMatcher(), false },
// string match +++
{str, new RequestMessageBodyMatcher((object o) => o == null), true},
{str, new RequestMessageBodyMatcher((string s) => s == str), true},
{str, new RequestMessageBodyMatcher((byte[] b) => b.SequenceEqual(Encoding.UTF8.GetBytes(str))), true},
// string no match ---
{str, new RequestMessageBodyMatcher((object o) => false), false},
{str, new RequestMessageBodyMatcher((string s) => false), false},
{str, new RequestMessageBodyMatcher((byte[] b) => false), false},
{str, new RequestMessageBodyMatcher(), false },
// binary match +++
{bytes, new RequestMessageBodyMatcher((object o) => o == null), true},
{bytes, new RequestMessageBodyMatcher((string s) => s == null), true},
{bytes, new RequestMessageBodyMatcher((byte[] b) => b.SequenceEqual(bytes)), true},
// binary no match ---
{bytes, new RequestMessageBodyMatcher((object o) => false), false},
{bytes, new RequestMessageBodyMatcher((string s) => false), false},
{bytes, new RequestMessageBodyMatcher((byte[] b) => false), false},
{bytes, new RequestMessageBodyMatcher(), false },
};
}
}
}
}
}

View File

@@ -80,7 +80,7 @@ public class ResponseWithTransformerTests
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test http://localhost/foo /foo POSt");
Check.That(response.Message.BodyData!.BodyAsString).Equals("test http://localhost/foo /foo POSt");
}
[Theory]
@@ -104,7 +104,7 @@ public class ResponseWithTransformerTests
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("url=http://localhost/a/b absoluteurl=http://localhost/wiremock/a/b path=/a/b absolutepath=/wiremock/a/b");
Check.That(response.Message.BodyData!.BodyAsString).Equals("url=http://localhost/a/b absoluteurl=http://localhost/wiremock/a/b path=/a/b absolutepath=/wiremock/a/b");
}
[Fact]
@@ -122,7 +122,7 @@ public class ResponseWithTransformerTests
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("a wiremock");
Check.That(response.Message.BodyData!.BodyAsString).Equals("a wiremock");
}
[Theory(Skip = "Invalid token `OpenBracket`")]
@@ -142,7 +142,7 @@ public class ResponseWithTransformerTests
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("a wiremock");
Check.That(response.Message.BodyData!.BodyAsString).Equals("a wiremock");
}
[Fact]
@@ -164,7 +164,7 @@ public class ResponseWithTransformerTests
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test keya=1,2 idx=1 idx=2 keyb=5");
Check.That(response.Message.BodyData!.BodyAsString).Equals("test keya=1,2 idx=1 idx=2 keyb=5");
}
[Theory(Skip = "Invalid token `OpenBracket`")]
@@ -188,7 +188,7 @@ public class ResponseWithTransformerTests
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test keya=1 idx=1 idx=2 keyb=5");
Check.That(response.Message.BodyData!.BodyAsString).Equals("test keya=1 idx=1 idx=2 keyb=5");
}
[Fact]
@@ -211,7 +211,7 @@ public class ResponseWithTransformerTests
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.BodyData!.BodyAsString).Equals("test");
Check.That(response.Message.StatusCode).Equals("400");
}
@@ -237,7 +237,7 @@ public class ResponseWithTransformerTests
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.BodyData!.BodyAsString).Equals("test");
Check.That(response.Message.StatusCode).Equals("400");
}
@@ -263,7 +263,7 @@ public class ResponseWithTransformerTests
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.BodyData!.BodyAsString).Equals("test");
Check.That(response.Message.StatusCode).Equals(null);
}
@@ -331,7 +331,7 @@ public class ResponseWithTransformerTests
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.BodyData!.BodyAsString).Equals("test");
Check.That(response.Message.Headers).ContainsKey("x");
Check.That(response.Message.Headers["x"]).Contains("text/plain");
Check.That(response.Message.Headers["x"]).Contains("http://localhost/foo");
@@ -356,7 +356,7 @@ public class ResponseWithTransformerTests
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.BodyData!.BodyAsString).Equals("test");
Check.That(response.Message.Headers).ContainsKey("x");
Check.That(response.Message.Headers["x"]).Contains("text/plain");
Check.That(response.Message.Headers["x"]).Contains("http://localhost/foo");
@@ -384,7 +384,7 @@ public class ResponseWithTransformerTests
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test http://localhost:1234 1234 http localhost");
Check.That(response.Message.BodyData!.BodyAsString).Equals("test http://localhost:1234 1234 http localhost");
}
[Theory]
@@ -644,7 +644,7 @@ public class ResponseWithTransformerTests
// Assert
Check.That(response.Message.BodyData.BodyAsFile).Equals(@"c:\1\test.xml");
Check.That(response.Message.BodyData.DetectedBodyType).Equals(BodyType.String);
Check.That(response.Message.BodyData.BodyAsString).Equals("<xml MyUniqueNumber=\"1\"></xml>");
Check.That(response.Message.BodyData!.BodyAsString).Equals("<xml MyUniqueNumber=\"1\"></xml>");
}
[Theory]

View File

@@ -11,286 +11,287 @@ using WireMock.Types;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.Serialization
namespace WireMock.Net.Tests.Serialization;
public class MappingConverterTests
{
public class MappingConverterTests
private readonly WireMockServerSettings _settings = new();
private readonly MappingConverter _sut;
public MappingConverterTests()
{
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
_sut = new MappingConverter(new MatcherMapper(_settings));
}
private readonly MappingConverter _sut;
public MappingConverterTests()
[Fact]
public void ToMappingModel_With_SingleWebHook()
{
// Assign
var request = Request.Create();
var response = Response.Create();
var webhooks = new IWebhook[]
{
_sut = new MappingConverter(new MatcherMapper(_settings));
}
[Fact]
public void ToMappingModel_With_SingleWebHook()
{
// Assign
var request = Request.Create();
var response = Response.Create();
var webhooks = new IWebhook[]
new Webhook
{
new Webhook
Request = new WebhookRequest
{
Request = new WebhookRequest
Url = "https://test.com",
Headers = new Dictionary<string, WireMockList<string>>
{
Url = "https://test.com",
Headers = new Dictionary<string, WireMockList<string>>
{
{ "Single", new WireMockList<string>("x") },
{ "Multi", new WireMockList<string>("a", "b") }
},
Method = "post",
BodyData = new BodyData
{
BodyAsString = "b",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
}
{ "Single", new WireMockList<string>("x") },
{ "Multi", new WireMockList<string>("a", "b") }
},
Method = "post",
BodyData = new BodyData
{
BodyAsString = "b",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
}
}
};
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 0, null, null, null, null, webhooks, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Priority.Should().BeNull();
model.Response.BodyAsJsonIndented.Should().BeNull();
model.Response.UseTransformer.Should().BeNull();
model.Response.Headers.Should().BeNull();
model.Webhooks.Should().BeNull();
model.Webhook.Request.Method.Should().Be("post");
model.Webhook.Request.Url.Should().Be("https://test.com");
model.Webhook.Request.Headers.Should().HaveCount(2);
model.Webhook.Request.Body.Should().Be("b");
model.Webhook.Request.BodyAsJson.Should().BeNull();
}
[Fact]
public void ToMappingModel_With_MultipleWebHooks()
{
// Assign
var request = Request.Create();
var response = Response.Create();
var webhooks = new IWebhook[]
{
new Webhook
{
Request = new WebhookRequest
{
Url = "https://test1.com",
Headers = new Dictionary<string, WireMockList<string>>
{
{ "One", new WireMockList<string>("x") }
},
Method = "post",
BodyData = new BodyData
{
BodyAsString = "1",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
}
}
},
new Webhook
{
Request = new WebhookRequest
{
Url = "https://test2.com",
Headers = new Dictionary<string, WireMockList<string>>
{
{ "First", new WireMockList<string>("x") },
{ "Second", new WireMockList<string>("a", "b") }
},
Method = "post",
BodyData = new BodyData
{
BodyAsString = "2",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
}
}
}
};
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 0, null, null, null, null, webhooks, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Priority.Should().BeNull();
model.Response.BodyAsJsonIndented.Should().BeNull();
model.Response.UseTransformer.Should().BeNull();
model.Response.Headers.Should().BeNull();
model.Webhook.Should().BeNull();
model.Webhooks[0].Request.Method.Should().Be("post");
model.Webhooks[0].Request.Url.Should().Be("https://test1.com");
model.Webhooks[0].Request.Headers.Should().HaveCount(1);
model.Webhooks[0].Request.Body.Should().Be("1");
model.Webhooks[1].Request.Method.Should().Be("post");
model.Webhooks[1].Request.Url.Should().Be("https://test2.com");
model.Webhooks[1].Request.Headers.Should().HaveCount(2);
model.Webhooks[1].Request.Body.Should().Be("2");
}
[Fact]
public void ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel()
{
// Assign
var title = "my-title";
var description = "my-description";
var request = Request.Create();
var response = Response.Create();
var mapping = new Mapping(Guid.NewGuid(), title, description, null, _settings, request, response, 0, null, null, null, null, null, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Title.Should().Be(title);
model.Description.Should().Be(description);
}
[Fact]
public void ToMappingModel_WithPriority_ReturnsPriority()
{
// Assign
var request = Request.Create();
var response = Response.Create().WithBodyAsJson(new { x = "x" }).WithTransformer();
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Priority.Should().Be(42);
model.Response.UseTransformer.Should().BeTrue();
}
[Fact]
public void ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings()
{
// Assign
var start = DateTime.Now;
var ttl = 100;
var end = start.AddSeconds(ttl);
var request = Request.Create();
var response = Response.Create();
var timeSettings = new TimeSettings
{
Start = start,
End = end,
TTL = ttl
};
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, timeSettings);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.TimeSettings.Should().NotBeNull();
model.TimeSettings.Start.Should().Be(start);
model.TimeSettings.End.Should().Be(end);
model.TimeSettings.TTL.Should().Be(ttl);
}
[Fact]
public void ToMappingModel_WithDelayAsTimeSpan_ReturnsCorrectModel()
{
// Arrange
var tests = new[]
{
new { Delay = Timeout.InfiniteTimeSpan, Expected = (int) TimeSpan.MaxValue.TotalMilliseconds },
new { Delay = TimeSpan.FromSeconds(1), Expected = 1000},
new { Delay = TimeSpan.MaxValue, Expected = (int) TimeSpan.MaxValue.TotalMilliseconds }
};
foreach (var test in tests)
{
var request = Request.Create();
var response = Response.Create().WithDelay(test.Delay);
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, string.Empty, _settings, request, response, 42, null, null, null, null, null, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Response.Delay.Should().Be(test.Expected);
}
}
};
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 0, null, null, null, null, webhooks, false, null);
[Fact]
public void ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel()
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Priority.Should().BeNull();
model.Response.BodyAsJsonIndented.Should().BeNull();
model.Response.UseTransformer.Should().BeNull();
model.Response.Headers.Should().BeNull();
model.UseWebhooksFireAndForget.Should().BeFalse();
model.Webhooks.Should().BeNull();
model.Webhook!.Request.Method.Should().Be("post");
model.Webhook.Request.Url.Should().Be("https://test.com");
model.Webhook.Request.Headers.Should().HaveCount(2);
model.Webhook.Request.Body.Should().Be("b");
model.Webhook.Request.BodyAsJson.Should().BeNull();
}
[Fact]
public void ToMappingModel_With_MultipleWebHooks()
{
// Assign
var request = Request.Create();
var response = Response.Create();
var webhooks = new IWebhook[]
{
new Webhook
{
Request = new WebhookRequest
{
Url = "https://test1.com",
Headers = new Dictionary<string, WireMockList<string>>
{
{ "One", new WireMockList<string>("x") }
},
Method = "post",
BodyData = new BodyData
{
BodyAsString = "1",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
}
}
},
new Webhook
{
Request = new WebhookRequest
{
Url = "https://test2.com",
Headers = new Dictionary<string, WireMockList<string>>
{
{ "First", new WireMockList<string>("x") },
{ "Second", new WireMockList<string>("a", "b") }
},
Method = "post",
BodyData = new BodyData
{
BodyAsString = "2",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
}
}
}
};
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 0, null, null, null, null, webhooks, true, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Priority.Should().BeNull();
model.Response.BodyAsJsonIndented.Should().BeNull();
model.Response.UseTransformer.Should().BeNull();
model.Response.Headers.Should().BeNull();
model.UseWebhooksFireAndForget.Should().BeTrue();
model.Webhook.Should().BeNull();
model.Webhooks![0].Request.Method.Should().Be("post");
model.Webhooks[0].Request.Url.Should().Be("https://test1.com");
model.Webhooks[0].Request.Headers.Should().HaveCount(1);
model.Webhooks[0].Request.Body.Should().Be("1");
model.Webhooks[1].Request.Method.Should().Be("post");
model.Webhooks[1].Request.Url.Should().Be("https://test2.com");
model.Webhooks[1].Request.Headers.Should().HaveCount(2);
model.Webhooks[1].Request.Body.Should().Be("2");
}
[Fact]
public void ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel()
{
// Assign
var title = "my-title";
var description = "my-description";
var request = Request.Create();
var response = Response.Create();
var mapping = new Mapping(Guid.NewGuid(), title, description, null, _settings, request, response, 0, null, null, null, null, null, false, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Title.Should().Be(title);
model.Description.Should().Be(description);
}
[Fact]
public void ToMappingModel_WithPriority_ReturnsPriority()
{
// Assign
var request = Request.Create();
var response = Response.Create().WithBodyAsJson(new { x = "x" }).WithTransformer();
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Priority.Should().Be(42);
model.Response.UseTransformer.Should().BeTrue();
}
[Fact]
public void ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings()
{
// Assign
var start = DateTime.Now;
var ttl = 100;
var end = start.AddSeconds(ttl);
var request = Request.Create();
var response = Response.Create();
var timeSettings = new TimeSettings
{
Start = start,
End = end,
TTL = ttl
};
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, timeSettings);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.TimeSettings!.Should().NotBeNull();
model.TimeSettings!.Start.Should().Be(start);
model.TimeSettings.End.Should().Be(end);
model.TimeSettings.TTL.Should().Be(ttl);
}
[Fact]
public void ToMappingModel_WithDelayAsTimeSpan_ReturnsCorrectModel()
{
// Arrange
var tests = new[]
{
new { Delay = Timeout.InfiniteTimeSpan, Expected = (int) TimeSpan.MaxValue.TotalMilliseconds },
new { Delay = TimeSpan.FromSeconds(1), Expected = 1000 },
new { Delay = TimeSpan.MaxValue, Expected = (int) TimeSpan.MaxValue.TotalMilliseconds }
};
foreach (var test in tests)
{
// Assign
var delay = 1000;
var request = Request.Create();
var response = Response.Create().WithDelay(delay);
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, null);
var response = Response.Create().WithDelay(test.Delay);
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, string.Empty, _settings, request, response, 42, null, null, null, null, null, false, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Response.Delay.Should().Be(delay);
}
[Fact]
public void ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel()
{
// Assign
int minimumDelay = 1000;
var request = Request.Create();
var response = Response.Create().WithRandomDelay(minimumDelay);
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Response.Delay.Should().BeNull();
model.Response.MinimumRandomDelay.Should().Be(minimumDelay);
model.Response.MaximumRandomDelay.Should().Be(60_000);
}
[Fact]
public void ToMappingModel_WithRandomDelay_ReturnsCorrectModel()
{
// Assign
int minimumDelay = 1000;
int maximumDelay = 2000;
var request = Request.Create();
var response = Response.Create().WithRandomDelay(minimumDelay, maximumDelay);
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Response.Delay.Should().BeNull();
model.Response.MinimumRandomDelay.Should().Be(minimumDelay);
model.Response.MaximumRandomDelay.Should().Be(maximumDelay);
model.Response.Delay.Should().Be(test.Expected);
}
}
[Fact]
public void ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel()
{
// Assign
var delay = 1000;
var request = Request.Create();
var response = Response.Create().WithDelay(delay);
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Response.Delay.Should().Be(delay);
}
[Fact]
public void ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel()
{
// Assign
int minimumDelay = 1000;
var request = Request.Create();
var response = Response.Create().WithRandomDelay(minimumDelay);
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Response.Delay.Should().BeNull();
model.Response.MinimumRandomDelay.Should().Be(minimumDelay);
model.Response.MaximumRandomDelay.Should().Be(60_000);
}
[Fact]
public void ToMappingModel_WithRandomDelay_ReturnsCorrectModel()
{
// Assign
int minimumDelay = 1000;
int maximumDelay = 2000;
var request = Request.Create();
var response = Response.Create().WithRandomDelay(minimumDelay, maximumDelay);
var mapping = new Mapping(Guid.NewGuid(), string.Empty, string.Empty, null, _settings, request, response, 42, null, null, null, null, null, false, null);
// Act
var model = _sut.ToMappingModel(mapping);
// Assert
model.Should().NotBeNull();
model.Response.Delay.Should().BeNull();
model.Response.MinimumRandomDelay.Should().Be(minimumDelay);
model.Response.MaximumRandomDelay.Should().Be(maximumDelay);
}
}

View File

@@ -408,4 +408,24 @@ public class MatcherMapperTests
matcher.Value.Should().BeEquivalentTo(pattern);
matcher.Regex.Should().BeFalse();
}
[Fact]
public void MatcherMapper_Map_MatcherModel_ExactMatcher_Pattern()
{
// Assign
var model = new MatcherModel
{
Name = "ExactMatcher",
Pattern = "p",
IgnoreCase = true
};
// Act
var matcher = (ExactMatcher)_sut.Map(model)!;
// Assert
matcher.MatchBehaviour.Should().Be(MatchBehaviour.AcceptOnMatch);
matcher.GetPatterns().Should().Contain("p");
matcher.IgnoreCase.Should().BeTrue();
}
}

View File

@@ -0,0 +1,70 @@
using System;
using Moq;
using Newtonsoft.Json;
using System.IO;
using FluentAssertions;
using WireMock.Matchers;
using WireMock.RequestBuilders;
using WireMock.Serialization;
using WireMock.Settings;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.Serialization;
public class ProxyMappingConverterTests
{
private readonly WireMockServerSettings _settings = new();
private readonly MappingConverter _mappingConverter;
private readonly ProxyMappingConverter _sut;
public ProxyMappingConverterTests()
{
var guidUtilsMock = new Mock<IGuidUtils>();
guidUtilsMock.Setup(g => g.NewGuid()).Returns(Guid.Parse("ff55ac0a-fea9-4d7b-be74-5e483a2c1305"));
_mappingConverter = new MappingConverter(new MatcherMapper(_settings));
_sut = new ProxyMappingConverter(_settings, guidUtilsMock.Object);
}
[Fact]
public void ToMapping_UseDefinedRequestMatchers_True()
{
// Arrange
var proxyAndRecordSettings = new ProxyAndRecordSettings
{
UseDefinedRequestMatchers = true
};
var request = Request.Create()
.UsingPost()
.WithPath("x")
.WithParam("p1", "p1-v")
.WithParam("p2", "p2-v")
.WithHeader("Content-Type", new ContentTypeMatcher("text/plain"))
.WithCookie("c", "x")
.WithBody(new RegexMatcher("<RequestType>Auth</RequestType"));
var mappingMock = new Mock<IMapping>();
mappingMock.SetupGet(m => m.RequestMatcher).Returns(request);
mappingMock.SetupGet(m => m.Title).Returns("my title");
mappingMock.SetupGet(m => m.Description).Returns("my description");
var requestMessageMock = new Mock<IRequestMessage>();
var responseMessage = new ResponseMessage();
// Act
var proxyMapping = _sut.ToMapping(mappingMock.Object, proxyAndRecordSettings, requestMessageMock.Object, responseMessage);
// Assert
var model = _mappingConverter.ToMappingModel(proxyMapping);
var json = JsonConvert.SerializeObject(model, JsonSerializationConstants.JsonSerializerSettingsDefault);
var expected = File.ReadAllText(Path.Combine("../../../", "Serialization", "files", "proxy.json"));
json.Should().Be(expected);
}
}

View File

@@ -1,101 +1,145 @@
using System.Collections.Generic;
using System.Collections.Generic;
using FluentAssertions;
using WireMock.Admin.Mappings;
using WireMock.Models;
using WireMock.Serialization;
using WireMock.Types;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.Serialization
namespace WireMock.Net.Tests.Serialization;
public class WebhookMapperTests
{
public class WebhookMapperTests
[Fact]
public void WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsFalse()
{
[Fact]
public void WebhookMapper_Map_Model_BodyAsString_And_UseTransformerIsFalse()
// Assign
var model = new WebhookModel
{
// Assign
var model = new WebhookModel
Request = new WebhookRequestModel
{
Request = new WebhookRequestModel
Url = "https://localhost",
Method = "get",
Headers = new Dictionary<string, string>
{
Url = "https://localhost",
Method = "get",
Headers = new Dictionary<string, string>
{
{ "x", "y" }
},
Body = "test",
UseTransformer = false
}
};
{ "x", "y" }
},
Body = "test",
UseTransformer = false
}
};
var result = WebhookMapper.Map(model);
var result = WebhookMapper.Map(model);
result.Request.Url.Should().Be("https://localhost");
result.Request.Method.Should().Be("get");
result.Request.Headers.Should().HaveCount(1);
result.Request.BodyData.BodyAsJson.Should().BeNull();
result.Request.BodyData.BodyAsString.Should().Be("test");
result.Request.BodyData.DetectedBodyType.Should().Be(BodyType.String);
result.Request.UseTransformer.Should().BeNull();
}
[Fact]
public void WebhookMapper_Map_Model_BodyAsString_And_UseTransformerIsTrue()
{
// Assign
var model = new WebhookModel
{
Request = new WebhookRequestModel
{
Url = "https://localhost",
Method = "get",
Headers = new Dictionary<string, string>
{
{ "x", "y" }
},
Body = "test",
UseTransformer = true
}
};
var result = WebhookMapper.Map(model);
result.Request.Url.Should().Be("https://localhost");
result.Request.Method.Should().Be("get");
result.Request.Headers.Should().HaveCount(1);
result.Request.BodyData.BodyAsJson.Should().BeNull();
result.Request.BodyData.BodyAsString.Should().Be("test");
result.Request.BodyData.DetectedBodyType.Should().Be(BodyType.String);
result.Request.UseTransformer.Should().BeTrue();
result.Request.TransformerType.Should().Be(TransformerType.Handlebars);
}
[Fact]
public void WebhookMapper_Map_Model_BodyAsJson()
{
// Assign
var model = new WebhookModel
{
Request = new WebhookRequestModel
{
Url = "https://localhost",
Method = "get",
Headers = new Dictionary<string, string>
{
{ "x", "y" }
},
BodyAsJson = new { n = 12345 }
}
};
var result = WebhookMapper.Map(model);
result.Request.Url.Should().Be("https://localhost");
result.Request.Method.Should().Be("get");
result.Request.Headers.Should().HaveCount(1);
result.Request.BodyData.BodyAsString.Should().BeNull();
result.Request.BodyData.BodyAsJson.Should().NotBeNull();
result.Request.BodyData.DetectedBodyType.Should().Be(BodyType.Json);
}
result.Request.Url.Should().Be("https://localhost");
result.Request.Method.Should().Be("get");
result.Request.Headers.Should().HaveCount(1);
result.Request.BodyData!.BodyAsJson.Should().BeNull();
result.Request.BodyData.BodyAsString.Should().Be("test");
result.Request.BodyData.DetectedBodyType.Should().Be(BodyType.String);
result.Request.UseTransformer.Should().BeNull();
}
}
[Fact]
public void WebhookMapper_Map_WebhookModel_BodyAsString_And_UseTransformerIsTrue()
{
// Assign
var model = new WebhookModel
{
Request = new WebhookRequestModel
{
Url = "https://localhost",
Method = "get",
Headers = new Dictionary<string, string>
{
{ "x", "y" }
},
Body = "test",
UseTransformer = true
}
};
var result = WebhookMapper.Map(model);
result.Request.Url.Should().Be("https://localhost");
result.Request.Method.Should().Be("get");
result.Request.Headers.Should().HaveCount(1);
result.Request.BodyData!.BodyAsJson.Should().BeNull();
result.Request.BodyData.BodyAsString.Should().Be("test");
result.Request.BodyData.DetectedBodyType.Should().Be(BodyType.String);
result.Request.UseTransformer.Should().BeTrue();
result.Request.TransformerType.Should().Be(TransformerType.Handlebars);
}
[Fact]
public void WebhookMapper_Map_WebhookModel_BodyAsJson()
{
// Assign
var model = new WebhookModel
{
Request = new WebhookRequestModel
{
Url = "https://localhost",
Method = "get",
Headers = new Dictionary<string, string>
{
{ "x", "y" }
},
BodyAsJson = new { n = 12345 },
Delay = 4,
MinimumRandomDelay = 5,
MaximumRandomDelay = 6
},
};
var result = WebhookMapper.Map(model);
result.Request.Url.Should().Be("https://localhost");
result.Request.Method.Should().Be("get");
result.Request.Headers.Should().HaveCount(1);
result.Request.BodyData!.BodyAsString.Should().BeNull();
result.Request.BodyData.BodyAsJson.Should().NotBeNull();
result.Request.BodyData.DetectedBodyType.Should().Be(BodyType.Json);
result.Request.Delay.Should().Be(4);
result.Request.MinimumRandomDelay.Should().Be(5);
result.Request.MaximumRandomDelay.Should().Be(6);
}
[Fact]
public void WebhookMapper_Map_Webhook_To_Model()
{
// Assign
var webhook = new Webhook
{
Request = new WebhookRequest
{
Url = "https://localhost",
Method = "get",
Headers = new Dictionary<string, WireMockList<string>>
{
{ "x", new WireMockList<string>("y") }
},
BodyData = new BodyData
{
BodyAsJson = new { n = 12345 },
DetectedBodyType = BodyType.Json,
DetectedBodyTypeFromContentType = BodyType.Json
},
Delay = 4,
MinimumRandomDelay = 5,
MaximumRandomDelay = 6
}
};
var result = WebhookMapper.Map(webhook);
result.Request.Url.Should().Be("https://localhost");
result.Request.Method.Should().Be("get");
result.Request.Headers.Should().HaveCount(1);
result.Request.BodyAsJson.Should().NotBeNull();
result.Request.Delay.Should().Be(4);
result.Request.MinimumRandomDelay.Should().Be(5);
result.Request.MaximumRandomDelay.Should().Be(6);
}
}

View File

@@ -0,0 +1,74 @@
{
"Guid": "ff55ac0a-fea9-4d7b-be74-5e483a2c1305",
"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": {}
}

View File

@@ -10,9 +10,6 @@
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<ProjectGuid>{31DC2EF8-C3FE-467D-84BE-FB5D956E612E}</ProjectGuid>
<!--<SonarQubeTestProject>True</SonarQubeTestProject>
<SonarQubeExclude>True</SonarQubeExclude>-->
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>../../src/WireMock.Net/WireMock.Net.snk</AssemblyOriginatorKeyFile>
<!--<DelaySign>true</DelaySign>-->
@@ -38,7 +35,6 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<!--<PackageReference Include="Mapster" Version="7.2.0" />-->
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
@@ -53,17 +49,11 @@
<PackageReference Include="Moq" Version="4.17.2" />
<PackageReference Include="System.Threading" Version="4.3.0" />
<PackageReference Include="RestEase" Version="1.5.7" />
<!--<PackageReference Include="RandomDataGenerator.Net" Version="1.0.14" />-->
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="NFluent" Version="2.8.0" />
<!--<PackageReference Include="OpenCover" Version="4.7.922" />-->
<!--<PackageReference Include="ReportGenerator" Version="4.8.1" />-->
<PackageReference Include="SimMetrics.Net" Version="1.0.5" />
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.2.19" />
<!--<PackageReference Include="StrongNamer" Version="0.2.5" />-->
<PackageReference Include="AnyOf" Version="0.3.0" />
<!--<PackageReference Include="TinyMapper" Version="3.0.3" />-->
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net452' or '$(TargetFramework)' == 'net461'">
@@ -85,6 +75,9 @@
<None Update="responsebody.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Serialization\files\proxy.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings.org\*.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
@@ -105,6 +98,7 @@
<ItemGroup>
<Folder Include="Pact\files\" />
<Folder Include="Serialization\files\" />
</ItemGroup>
</Project>

View File

@@ -1,3 +1,6 @@
using FluentAssertions;
using Moq;
using NFluent;
using System;
using System.Linq;
using System.Net;
@@ -5,11 +8,9 @@ using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using NFluent;
using WireMock.Admin.Mappings;
using WireMock.Constants;
using WireMock.Handlers;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
@@ -119,6 +120,61 @@ public class WireMockServerProxyTests
server.Mappings.Should().HaveCount(28);
}
[Fact]
public async Task WireMockServer_Proxy_With_SaveMappingToFile_Is_True_ShouldSaveMappingToFile()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var title = "IndexFile";
var description = "IndexFile_Test";
var stringBody = "<pretendXml>value</pretendXml>";
var serverForProxyForwarding = WireMockServer.Start();
var fileSystemHandlerMock = new Mock<IFileSystemHandler>();
fileSystemHandlerMock.Setup(f => f.GetMappingFolder()).Returns("m");
var settings = new WireMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = serverForProxyForwarding.Urls[0],
SaveMapping = false,
SaveMappingToFile = true
},
FileSystemHandler = fileSystemHandlerMock.Object
};
var server = WireMockServer.Start(settings);
server.Given(Request.Create()
.WithPath("/*")
.WithBody(new RegexMatcher(stringBody)))
.WithTitle(title)
.WithDescription(description)
.AtPriority(WireMockConstants.ProxyPriority)
.RespondWith(Response.Create().WithProxy(new ProxyAndRecordSettings
{
Url = serverForProxyForwarding.Urls[0],
SaveMapping = false,
SaveMappingToFile = true,
UseDefinedRequestMatchers = true,
}));
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent(stringBody)
};
var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
await new HttpClient(httpClientHandler).SendAsync(requestMessage).ConfigureAwait(false);
// Assert
server.Mappings.Should().HaveCount(2);
// Verify
fileSystemHandlerMock.Verify(f => f.WriteMappingFile($"m{System.IO.Path.DirectorySeparatorChar}{title}.json", It.IsRegex(stringBody)), Times.Once);
}
[Fact]
public async Task WireMockServer_Proxy_With_SaveMapping_Is_False_And_SaveMappingToFile_Is_True_ShouldSaveMappingToFile()
{
@@ -735,8 +791,6 @@ public class WireMockServerProxyTests
content.Should().NotBeEmpty();
server.LogEntries.Should().HaveCount(1);
var status = ((StatusModel)server.LogEntries.First().ResponseMessage.BodyData.BodyAsJson).Status;
server.Stop();
}
}

View File

@@ -12,190 +12,190 @@ using WireMock.Types;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests
namespace WireMock.Net.Tests;
public class WireMockServerWebhookTests
{
public class WireMockServerWebhookTests
[Fact]
public async Task WireMockServer_WithWebhooks_Should_Send_Message_To_Webhooks()
{
[Fact]
public async Task WireMockServer_WithWebhooks_Should_Send_Message_To_Webhooks()
// Assign
var serverReceivingTheWebhook1 = WireMockServer.Start();
serverReceivingTheWebhook1.Given(Request.Create().UsingPost()).RespondWith(Response.Create().WithStatusCode(200));
var serverReceivingTheWebhook2 = WireMockServer.Start();
serverReceivingTheWebhook2.Given(Request.Create().UsingPost()).RespondWith(Response.Create().WithStatusCode(200));
var webhook1 = new Webhook
{
// Assign
var serverReceivingTheWebhook1 = WireMockServer.Start();
serverReceivingTheWebhook1.Given(Request.Create().UsingPost()).RespondWith(Response.Create().WithStatusCode(200));
Request = new WebhookRequest
{
Url = serverReceivingTheWebhook1.Urls[0],
Method = "post",
BodyData = new BodyData
{
BodyAsString = "1",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
}
}
};
var serverReceivingTheWebhook2 = WireMockServer.Start();
serverReceivingTheWebhook2.Given(Request.Create().UsingPost()).RespondWith(Response.Create().WithStatusCode(200));
var webhook2 = new Webhook
{
Request = new WebhookRequest
{
Url = serverReceivingTheWebhook2.Urls[0],
Method = "post",
BodyData = new BodyData
{
BodyAsString = "2",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
}
}
};
var webhook1 = new Webhook
// Act
var server = WireMockServer.Start();
server.Given(Request.Create().UsingPost())
.WithWebhook(webhook1, webhook2)
.RespondWith(Response.Create().WithBody("a-response"));
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}/TST"),
Content = new StringContent("test")
};
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
serverReceivingTheWebhook1.LogEntries.Should().HaveCount(1);
serverReceivingTheWebhook2.LogEntries.Should().HaveCount(1);
server.Dispose();
serverReceivingTheWebhook1.Dispose();
serverReceivingTheWebhook2.Dispose();
}
[Fact]
public async Task WireMockServer_WithWebhook_Should_Send_Message_To_Webhook()
{
// Assign
var serverReceivingTheWebhook = WireMockServer.Start();
serverReceivingTheWebhook.Given(Request.Create().WithPath("x").UsingPost()).RespondWith(Response.Create().WithStatusCode(200));
// Act
var server = WireMockServer.Start();
server.Given(Request.Create().UsingPost())
.WithWebhook(new Webhook
{
Request = new WebhookRequest
{
Url = serverReceivingTheWebhook1.Urls[0],
Url = serverReceivingTheWebhook.Url! + "/{{request.Query.q}}",
Method = "post",
BodyData = new BodyData
{
BodyAsString = "1",
BodyAsString = "abc",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
}
},
UseTransformer = true
}
};
})
.RespondWith(Response.Create().WithBody("a-response"));
var webhook2 = new Webhook
{
Request = new WebhookRequest
{
Url = serverReceivingTheWebhook2.Urls[0],
Method = "post",
BodyData = new BodyData
{
BodyAsString = "2",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
}
}
};
// Act
var server = WireMockServer.Start();
server.Given(Request.Create().UsingPost())
.WithWebhook(webhook1, webhook2)
.RespondWith(Response.Create().WithBody("a-response"));
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}/TST"),
Content = new StringContent("test")
};
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
serverReceivingTheWebhook1.LogEntries.Should().HaveCount(1);
serverReceivingTheWebhook2.LogEntries.Should().HaveCount(1);
server.Dispose();
serverReceivingTheWebhook1.Dispose();
serverReceivingTheWebhook2.Dispose();
}
[Fact]
public async Task WireMockServer_WithWebhook_Should_Send_Message_To_Webhook()
var request = new HttpRequestMessage
{
// Assign
var serverReceivingTheWebhook = WireMockServer.Start();
serverReceivingTheWebhook.Given(Request.Create().UsingPost()).RespondWith(Response.Create().WithStatusCode(200));
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}/TST?q=x"),
Content = new StringContent("test")
};
// Act
var server = WireMockServer.Start();
server.Given(Request.Create().UsingPost())
.WithWebhook(new Webhook
{
Request = new WebhookRequest
{
Url = serverReceivingTheWebhook.Urls[0],
Method = "post",
BodyData = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
}
}
})
.RespondWith(Response.Create().WithBody("a-response"));
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}/TST"),
Content = new StringContent("test")
};
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
serverReceivingTheWebhook.LogEntries.Should().HaveCount(1);
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
server.Dispose();
serverReceivingTheWebhook.Dispose();
}
serverReceivingTheWebhook.LogEntries.Should().HaveCount(1);
[Fact]
public async Task WireMockServer_WithWebhookArgs_Should_Send_StringMessage_To_Webhook()
{
// Assign
var serverReceivingTheWebhook = WireMockServer.Start();
serverReceivingTheWebhook.Given(Request.Create().UsingPost()).RespondWith(Response.Create().WithStatusCode(200));
server.Dispose();
serverReceivingTheWebhook.Dispose();
}
// Act
var server = WireMockServer.Start();
server.Given(Request.Create().UsingPost())
.WithWebhook(serverReceivingTheWebhook.Urls[0], "post", null, "OK !", true, TransformerType.Handlebars)
.RespondWith(Response.Create().WithBody("a-response"));
[Fact]
public async Task WireMockServer_WithWebhookArgs_Should_Send_StringMessage_To_Webhook()
var request = new HttpRequestMessage
{
// Assign
var serverReceivingTheWebhook = WireMockServer.Start();
serverReceivingTheWebhook.Given(Request.Create().UsingPost()).RespondWith(Response.Create().WithStatusCode(200));
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}/TST"),
Content = new StringContent("test")
};
// Act
var server = WireMockServer.Start();
server.Given(Request.Create().UsingPost())
.WithWebhook(serverReceivingTheWebhook.Urls[0], "post", null, "OK !", true, TransformerType.Handlebars)
.RespondWith(Response.Create().WithBody("a-response"));
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}/TST"),
Content = new StringContent("test")
};
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
serverReceivingTheWebhook.LogEntries.Should().HaveCount(1);
serverReceivingTheWebhook.LogEntries.First().RequestMessage.Body.Should().Be("OK !");
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
server.Dispose();
serverReceivingTheWebhook.Dispose();
}
serverReceivingTheWebhook.LogEntries.Should().HaveCount(1);
serverReceivingTheWebhook.LogEntries.First().RequestMessage.Body.Should().Be("OK !");
[Fact]
public async Task WireMockServer_WithWebhookArgs_Should_Send_JsonMessage_To_Webhook()
{
// Assign
var serverReceivingTheWebhook = WireMockServer.Start();
serverReceivingTheWebhook.Given(Request.Create().UsingPost()).RespondWith(Response.Create().WithStatusCode(200));
server.Dispose();
serverReceivingTheWebhook.Dispose();
}
// Act
var server = WireMockServer.Start();
server.Given(Request.Create().UsingPost())
.WithWebhook(serverReceivingTheWebhook.Urls[0], "post", null, new { Status = "OK" }, true, TransformerType.Handlebars)
.RespondWith(Response.Create().WithBody("a-response"));
[Fact]
public async Task WireMockServer_WithWebhookArgs_Should_Send_JsonMessage_To_Webhook()
var request = new HttpRequestMessage
{
// Assign
var serverReceivingTheWebhook = WireMockServer.Start();
serverReceivingTheWebhook.Given(Request.Create().UsingPost()).RespondWith(Response.Create().WithStatusCode(200));
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}/TST"),
Content = new StringContent("test")
};
// Act
var server = WireMockServer.Start();
server.Given(Request.Create().UsingPost())
.WithWebhook(serverReceivingTheWebhook.Urls[0], "post", null, new { Status = "OK" }, true, TransformerType.Handlebars)
.RespondWith(Response.Create().WithBody("a-response"));
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}/TST"),
Content = new StringContent("test")
};
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
serverReceivingTheWebhook.LogEntries.Should().HaveCount(1);
serverReceivingTheWebhook.LogEntries.First().RequestMessage.Body.Should().Be("{\"Status\":\"OK\"}");
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
serverReceivingTheWebhook.LogEntries.Should().HaveCount(1);
serverReceivingTheWebhook.LogEntries.First().RequestMessage.Body.Should().Be("{\"Status\":\"OK\"}");
server.Dispose();
serverReceivingTheWebhook.Dispose();
}
server.Dispose();
serverReceivingTheWebhook.Dispose();
}
}