Compare commits

...

9 Commits

Author SHA1 Message Date
Stef Heyenrath
444298c28c 1.4.17 2021-07-07 18:31:07 +02:00
Stef Heyenrath
6f42aa99bc Handlebars.Net.Helpers.Humanizer (#617) 2021-07-07 17:02:15 +02:00
Stef Heyenrath
8a9ea1b843 Update FUNDING.yml 2021-07-06 12:13:13 +02:00
Stef Heyenrath
dade24de37 Update FUNDING.yml 2021-07-06 12:12:48 +02:00
Stef Heyenrath
6beaa631f4 Update FUNDING.yml 2021-07-03 09:44:33 +02:00
Stef Heyenrath
282281aa7f 1.4.16 2021-06-05 11:00:51 +02:00
Stef Heyenrath
4052a0ef3b Upgrade Handlebars.Net.Helpers to 2.19 (#616)
* Upgrade Handlebars.Net.Helpers to 2.19

* fix ut
2021-06-05 10:59:09 +02:00
Stef Heyenrath
2ca394b7f6 1.4.15 2021-05-19 12:01:19 +00:00
Stef Heyenrath
b04000bfdd Add support for multiple webhooks (#615) 2021-05-19 13:58:48 +02:00
19 changed files with 477 additions and 286 deletions

4
.github/FUNDING.yml vendored
View File

@@ -1,8 +1,8 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
github: [StefH, WireMock-Net]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
open_collective: # wiremocknet
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry

View File

@@ -1,3 +1,13 @@
# 1.4.17 (07 July 2021)
- [#617](https://github.com/WireMock-Net/WireMock.Net/pull/617) - Add support for Handlebars.Net.Helpers.Humanizer [feature] contributed by [StefH](https://github.com/StefH)
# 1.4.16 (05 June 2021)
- [#616](https://github.com/WireMock-Net/WireMock.Net/pull/616) - Upgrade Handlebars.Net.Helpers to 2.19 [feature] contributed by [StefH](https://github.com/StefH)
# 1.4.15 (19 May 2021)
- [#615](https://github.com/WireMock-Net/WireMock.Net/pull/615) - Add support for multiple webhooks [feature] contributed by [StefH](https://github.com/StefH)
- [#614](https://github.com/WireMock-Net/WireMock.Net/issues/614) - Is it possible to some how send multiple webhooks? [feature]
# 1.4.14 (11 May 2021)
- [#610](https://github.com/WireMock-Net/WireMock.Net/pull/610) - Fix some SonarCloud issues in UnitTests contributed by [StefH](https://github.com/StefH)
- [#611](https://github.com/WireMock-Net/WireMock.Net/pull/611) - Allow to add custom service registrations when using ASP.NET Core [feature] contributed by [starkpl](https://github.com/starkpl)
@@ -77,6 +87,7 @@
- [#549](https://github.com/WireMock-Net/WireMock.Net/issues/549) - WithProxy(...) does not save the mappings to file [bug]
# 1.3.8 (03 December 2020)
- [#539](https://github.com/WireMock-Net/WireMock.Net/pull/539) - Support for partial JSON matching contributed by [gleb-osokin](https://github.com/gleb-osokin)
- [#542](https://github.com/WireMock-Net/WireMock.Net/pull/542) - Create dotnet-wiremock tool [feature] contributed by [StefH](https://github.com/StefH)
- [#543](https://github.com/WireMock-Net/WireMock.Net/pull/543) - Add support for .NET 5 [feature] contributed by [StefH](https://github.com/StefH)
- [#544](https://github.com/WireMock-Net/WireMock.Net/pull/544) - Use Java 11 in Azure Pipelines (needed for SonarCloud) [feature] contributed by [StefH](https://github.com/StefH)
@@ -84,9 +95,6 @@
- [#547](https://github.com/WireMock-Net/WireMock.Net/pull/547) - Fix Proxying with SSL and NetCoreApp3.1 [bug] contributed by [StefH](https://github.com/StefH)
- [#524](https://github.com/WireMock-Net/WireMock.Net/issues/524) - Proxying with SSL Not Working in .NET Core 3.1 [bug]
# 1.3.7 (17 November 2020)
- [#539](https://github.com/WireMock-Net/WireMock.Net/pull/539) - Support for partial JSON matching contributed by [gleb-osokin](https://github.com/gleb-osokin)
# 1.3.6 (10 November 2020)
- [#529](https://github.com/WireMock-Net/WireMock.Net/pull/529) - Add assertions for ClientIP, Url and ProxyUrl [feature] contributed by [akamud](https://github.com/akamud)
- [#535](https://github.com/WireMock-Net/WireMock.Net/pull/535) - WithCallback should use also use enum HttpStatusCode [bug] contributed by [StefH](https://github.com/StefH)

View File

@@ -4,7 +4,7 @@
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>1.4.14</VersionPrefix>
<VersionPrefix>1.4.17</VersionPrefix>
<PackageReleaseNotes>See CHANGELOG.md</PackageReleaseNotes>
<PackageIconUrl>https://raw.githubusercontent.com/WireMock-Net/WireMock.Net/master/WireMock.Net-Logo.png</PackageIconUrl>
<PackageProjectUrl>https://github.com/WireMock-Net/WireMock.Net</PackageProjectUrl>

View File

@@ -1,3 +1,3 @@
https://github.com/StefH/GitHubReleaseNotes
GitHubReleaseNotes --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc --version 1.4.14
GitHubReleaseNotes --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc --version 1.4.17

View File

@@ -16,4 +16,6 @@
<s:Boolean x:Key="/Default/UserDictionary/Words/=Raml/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=randomizer/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Stef/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Webhook/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Webhooks/@EntryIndexedValue">True</s:Boolean>
</wpf:ResourceDictionary>

View File

@@ -57,5 +57,10 @@ namespace WireMock.Admin.Mappings
/// The Webhook.
/// </summary>
public WebhookModel Webhook { get; set; }
/// <summary>
/// The Webhooks.
/// </summary>
public WebhookModel[] Webhooks { get; set; }
}
}

View File

@@ -95,9 +95,9 @@ namespace WireMock
bool LogMapping { get; }
/// <summary>
/// The Webhook.
/// The Webhooks.
/// </summary>
IWebhook Webhook { get; }
IWebhook[] Webhooks { get; }
/// <summary>
/// ProvideResponseAsync

View File

@@ -1,7 +1,6 @@
using System;
using System.Threading.Tasks;
using JetBrains.Annotations;
using WireMock.Admin.Mappings;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.ResponseProviders;
@@ -56,8 +55,8 @@ namespace WireMock
/// <inheritdoc cref="IMapping.LogMapping" />
public bool LogMapping => !(Provider is DynamicResponseProvider || Provider is DynamicAsyncResponseProvider);
/// <inheritdoc cref="IMapping.Webhook" />
public IWebhook Webhook { get; }
/// <inheritdoc cref="IMapping.Webhooks" />
public IWebhook[] Webhooks { get; }
/// <summary>
/// Initializes a new instance of the <see cref="Mapping"/> class.
@@ -73,7 +72,7 @@ namespace WireMock
/// <param name="executionConditionState">State in which the current mapping can occur. [Optional]</param>
/// <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="webhook">The Webhook. [Optional]</param>
/// <param name="webhooks">The Webhooks. [Optional]</param>
public Mapping(
Guid guid,
[CanBeNull] string title,
@@ -86,7 +85,7 @@ namespace WireMock
[CanBeNull] string executionConditionState,
[CanBeNull] string nextState,
[CanBeNull] int? stateTimes,
[CanBeNull] IWebhook webhook)
[CanBeNull] IWebhook[] webhooks)
{
Guid = guid;
Title = title;
@@ -99,7 +98,7 @@ namespace WireMock
ExecutionConditionState = executionConditionState;
NextState = nextState;
StateTimes = stateTimes;
Webhook = webhook;
Webhooks = webhooks;
}
/// <inheritdoc cref="IMapping.ProvideResponseAsync" />

View File

@@ -1,8 +1,4 @@
using System.Collections.Generic;
using JetBrains.Annotations;
using WireMock.Types;
namespace WireMock.Models
namespace WireMock.Models
{
/// <summary>
/// Webhook

View File

@@ -156,9 +156,9 @@ namespace WireMock.Owin
UpdateScenarioState(targetMapping);
}
if (!targetMapping.IsAdminInterface && targetMapping.Webhook != null)
if (!targetMapping.IsAdminInterface && targetMapping.Webhooks?.Length > 0)
{
await SendToWebhookAsync(targetMapping, request, response).ConfigureAwait(false);
await SendToWebhooksAsync(targetMapping, request, response).ConfigureAwait(false);
}
}
catch (Exception ex)
@@ -191,18 +191,21 @@ namespace WireMock.Owin
await CompletedTask;
}
private async Task SendToWebhookAsync(IMapping mapping, RequestMessage request, ResponseMessage response)
private async Task SendToWebhooksAsync(IMapping mapping, RequestMessage request, ResponseMessage response)
{
var httpClientForWebhook = HttpClientBuilder.Build(mapping.Settings.WebhookSettings ?? new WebhookSettings());
var webhookSender = new WebhookSender(mapping.Settings);
for (int index = 0; index < mapping.Webhooks.Length; index++)
{
var httpClientForWebhook = HttpClientBuilder.Build(mapping.Settings.WebhookSettings ?? new WebhookSettings());
var webhookSender = new WebhookSender(mapping.Settings);
try
{
await webhookSender.SendAsync(httpClientForWebhook, mapping.Webhook.Request, request, response).ConfigureAwait(false);
}
catch (Exception ex)
{
_options.Logger.Error($"Sending message to Webhook Mapping '{mapping.Guid}' failed. Exception: {ex}");
try
{
await webhookSender.SendAsync(httpClientForWebhook, mapping.Webhooks[index].Request, request, response).ConfigureAwait(false);
}
catch (Exception ex)
{
_options.Logger.Error($"Sending message to Webhook [{index}] from Mapping '{mapping.Guid}' failed. Exception: {ex}");
}
}
}

View File

@@ -84,10 +84,18 @@ namespace WireMock.Serialization
Response = new ResponseModel
{
Delay = (int?)response.Delay?.TotalMilliseconds
},
Webhook = WebhookMapper.Map(mapping.Webhook)
}
};
if (mapping.Webhooks?.Length == 1)
{
mappingModel.Webhook = WebhookMapper.Map(mapping.Webhooks[0]);
}
else if (mapping.Webhooks?.Length > 1)
{
mappingModel.Webhooks = mapping.Webhooks.Select(WebhookMapper.Map).ToArray();
}
if (bodyMatcher?.Matchers != null)
{
mappingModel.Request.Body = new BodyModel();

View File

@@ -103,14 +103,14 @@ namespace WireMock.Server
IRespondWithAProvider WillSetStateTo(int state, int? times = 1);
/// <summary>
/// Add a Webbook to call after the response has been generated.
/// Add (multiple) Webhook(s) to call after the response has been generated.
/// </summary>
/// <param name="webhook">The Webhook</param>
/// <param name="webhooks">The Webhooks</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithWebhook(IWebhook webhook);
IRespondWithAProvider WithWebhook(params IWebhook[] webhooks);
/// <summary>
/// Add a Webbook to call after the response has been generated.
/// 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>
@@ -129,7 +129,7 @@ namespace WireMock.Server
);
/// <summary>
/// Add a Webbook to call after the response has been generated.
/// 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>

View File

@@ -1,209 +1,212 @@
// This source file is based on mock4net by Alexandre Victoor which is licensed under the Apache 2.0 License.
// For more details see 'mock4net/LICENSE.txt' and 'mock4net/readme.md' in this project root.
using System;
// This source file is based on mock4net by Alexandre Victoor which is licensed under the Apache 2.0 License.
// For more details see 'mock4net/LICENSE.txt' and 'mock4net/readme.md' in this project root.
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.ResponseProviders;
using WireMock.Settings;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.ResponseProviders;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
using WireMock.Validation;
namespace WireMock.Server
{
/// <summary>
/// The respond with a provider.
/// </summary>
internal class RespondWithAProvider : IRespondWithAProvider
{
private int _priority;
private string _title;
private string _path;
private string _executionConditionState;
private string _nextState;
private string _scenario;
private int _timesInSameState = 1;
private readonly RegistrationCallback _registrationCallback;
private readonly IRequestMatcher _requestMatcher;
private readonly IWireMockServerSettings _settings;
private readonly bool _saveToFile;
public Guid Guid { get; private set; } = Guid.NewGuid();
public IWebhook[] Webhooks { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="RespondWithAProvider"/> class.
/// </summary>
/// <param name="registrationCallback">The registration callback.</param>
/// <param name="requestMatcher">The request matcher.</param>
/// <param name="settings">The WireMockServerSettings.</param>
/// <param name="saveToFile">Optional boolean to indicate if this mapping should be saved as static mapping file.</param>
public RespondWithAProvider(RegistrationCallback registrationCallback, IRequestMatcher requestMatcher, IWireMockServerSettings settings, bool saveToFile = false)
{
_registrationCallback = registrationCallback;
_requestMatcher = requestMatcher;
_settings = settings;
_saveToFile = saveToFile;
}
/// <summary>
/// The respond with.
/// </summary>
/// <param name="provider">The provider.</param>
public void RespondWith(IResponseProvider provider)
{
_registrationCallback(new Mapping(Guid, _title, _path, _settings, _requestMatcher, provider, _priority, _scenario, _executionConditionState, _nextState, _timesInSameState, Webhooks), _saveToFile);
}
/// <see cref="IRespondWithAProvider.WithGuid(string)"/>
public IRespondWithAProvider WithGuid(string guid)
{
return WithGuid(Guid.Parse(guid));
}
/// <see cref="IRespondWithAProvider.WithGuid(Guid)"/>
public IRespondWithAProvider WithGuid(Guid guid)
{
Guid = guid;
return this;
}
/// <see cref="IRespondWithAProvider.WithTitle"/>
public IRespondWithAProvider WithTitle(string title)
{
_title = title;
return this;
}
/// <see cref="IRespondWithAProvider.WithPath"/>
public IRespondWithAProvider WithPath(string path)
{
_path = path;
return this;
}
/// <see cref="IRespondWithAProvider.AtPriority"/>
public IRespondWithAProvider AtPriority(int priority)
{
_priority = priority;
return this;
}
/// <see cref="IRespondWithAProvider.InScenario(string)"/>
public IRespondWithAProvider InScenario(string scenario)
{
_scenario = scenario;
return this;
}
/// <see cref="IRespondWithAProvider.InScenario(int)"/>
public IRespondWithAProvider InScenario(int scenario)
{
return InScenario(scenario.ToString());
}
/// <see cref="IRespondWithAProvider.WhenStateIs(string)"/>
public IRespondWithAProvider WhenStateIs(string state)
{
if (string.IsNullOrEmpty(_scenario))
{
throw new NotSupportedException("Unable to set state condition when no scenario is defined.");
}
_executionConditionState = state;
return this;
}
/// <see cref="IRespondWithAProvider.WhenStateIs(int)"/>
public IRespondWithAProvider WhenStateIs(int state)
{
return WhenStateIs(state.ToString());
}
/// <see cref="IRespondWithAProvider.WillSetStateTo(string, int?)"/>
public IRespondWithAProvider WillSetStateTo(string state, int? times = 1)
{
if (string.IsNullOrEmpty(_scenario))
{
throw new NotSupportedException("Unable to set next state when no scenario is defined.");
}
_nextState = state;
_timesInSameState = times ?? 1;
return this;
}
/// <see cref="IRespondWithAProvider.WillSetStateTo(int, int?)"/>
public IRespondWithAProvider WillSetStateTo(int state, int? times = 1)
{
return WillSetStateTo(state.ToString(), times);
}
/// <see cref="IRespondWithAProvider.WithWebhook(IWebhook[])"/>
public IRespondWithAProvider WithWebhook(params IWebhook[] webhooks)
{
Check.HasNoNulls(webhooks, nameof(webhooks));
Webhooks = webhooks;
return this;
}
/// <see cref="IRespondWithAProvider.WithWebhook(string, string, IDictionary{string, WireMockList{string}}, string, bool, TransformerType)"/>
public 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)
{
Webhooks = new[] { InitWebhook(url, method, headers, useTransformer, transformerType) };
namespace WireMock.Server
{
/// <summary>
/// The respond with a provider.
/// </summary>
internal class RespondWithAProvider : IRespondWithAProvider
{
private int _priority;
private string _title;
private string _path;
private string _executionConditionState;
private string _nextState;
private string _scenario;
private int _timesInSameState = 1;
private readonly RegistrationCallback _registrationCallback;
private readonly IRequestMatcher _requestMatcher;
private readonly IWireMockServerSettings _settings;
private readonly bool _saveToFile;
public Guid Guid { get; private set; } = Guid.NewGuid();
public IWebhook Webhook { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="RespondWithAProvider"/> class.
/// </summary>
/// <param name="registrationCallback">The registration callback.</param>
/// <param name="requestMatcher">The request matcher.</param>
/// <param name="settings">The WireMockServerSettings.</param>
/// <param name="saveToFile">Optional boolean to indicate if this mapping should be saved as static mapping file.</param>
public RespondWithAProvider(RegistrationCallback registrationCallback, IRequestMatcher requestMatcher, IWireMockServerSettings settings, bool saveToFile = false)
{
_registrationCallback = registrationCallback;
_requestMatcher = requestMatcher;
_settings = settings;
_saveToFile = saveToFile;
}
/// <summary>
/// The respond with.
/// </summary>
/// <param name="provider">The provider.</param>
public void RespondWith(IResponseProvider provider)
{
_registrationCallback(new Mapping(Guid, _title, _path, _settings, _requestMatcher, provider, _priority, _scenario, _executionConditionState, _nextState, _timesInSameState, Webhook), _saveToFile);
}
/// <see cref="IRespondWithAProvider.WithGuid(string)"/>
public IRespondWithAProvider WithGuid(string guid)
{
return WithGuid(Guid.Parse(guid));
}
/// <see cref="IRespondWithAProvider.WithGuid(Guid)"/>
public IRespondWithAProvider WithGuid(Guid guid)
{
Guid = guid;
return this;
}
/// <see cref="IRespondWithAProvider.WithTitle"/>
public IRespondWithAProvider WithTitle(string title)
{
_title = title;
return this;
}
/// <see cref="IRespondWithAProvider.WithPath"/>
public IRespondWithAProvider WithPath(string path)
{
_path = path;
return this;
}
/// <see cref="IRespondWithAProvider.AtPriority"/>
public IRespondWithAProvider AtPriority(int priority)
{
_priority = priority;
return this;
}
/// <see cref="IRespondWithAProvider.InScenario(string)"/>
public IRespondWithAProvider InScenario(string scenario)
{
_scenario = scenario;
return this;
}
/// <see cref="IRespondWithAProvider.InScenario(int)"/>
public IRespondWithAProvider InScenario(int scenario)
{
return InScenario(scenario.ToString());
}
/// <see cref="IRespondWithAProvider.WhenStateIs(string)"/>
public IRespondWithAProvider WhenStateIs(string state)
{
if (string.IsNullOrEmpty(_scenario))
{
throw new NotSupportedException("Unable to set state condition when no scenario is defined.");
}
_executionConditionState = state;
return this;
}
/// <see cref="IRespondWithAProvider.WhenStateIs(int)"/>
public IRespondWithAProvider WhenStateIs(int state)
{
return WhenStateIs(state.ToString());
}
/// <see cref="IRespondWithAProvider.WillSetStateTo(string, int?)"/>
public IRespondWithAProvider WillSetStateTo(string state, int? times = 1)
{
if (string.IsNullOrEmpty(_scenario))
{
throw new NotSupportedException("Unable to set next state when no scenario is defined.");
}
_nextState = state;
_timesInSameState = times ?? 1;
return this;
}
/// <see cref="IRespondWithAProvider.WillSetStateTo(int, int?)"/>
public IRespondWithAProvider WillSetStateTo(int state, int? times = 1)
{
return WillSetStateTo(state.ToString(), times);
}
/// <see cref="IRespondWithAProvider.WithWebhook(IWebhook)"/>
public IRespondWithAProvider WithWebhook(IWebhook webhook)
{
Webhook = webhook;
return this;
}
/// <see cref="IRespondWithAProvider.WithWebhook(string,string, IDictionary{string, WireMockList{string}}, string, bool, TransformerType)"/>
public 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)
{
Webhook = InitWebhook(url, method, headers, useTransformer, transformerType);
if (body != null)
{
Webhook.Request.BodyData = new BodyData
Webhooks[0].Request.BodyData = new BodyData
{
BodyAsString = body,
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
};
}
return this;
}
return this;
}
/// <see cref="IRespondWithAProvider.WithWebhook(string, string, IDictionary{string, WireMockList{string}}, object, bool, TransformerType)"/>
public 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)
{
Webhook = InitWebhook(url, method, headers, useTransformer, transformerType);
/// <see cref="IRespondWithAProvider.WithWebhook(string, string, IDictionary{string, WireMockList{string}}, object, bool, TransformerType)"/>
public 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)
{
Webhooks = new[] { InitWebhook(url, method, headers, useTransformer, transformerType) };
if (body != null)
{
Webhook.Request.BodyData = new BodyData
Webhooks[0].Request.BodyData = new BodyData
{
BodyAsJson = body,
DetectedBodyType = BodyType.Json,
DetectedBodyTypeFromContentType = BodyType.Json
};
}
return this;
}
}
return this;
}
private IWebhook InitWebhook(
string url,
string method,
@@ -222,6 +225,6 @@ namespace WireMock.Server
TransformerType = transformerType
}
};
}
}
}
}
}

View File

@@ -470,10 +470,15 @@ namespace WireMock.Server
respondProvider = respondProvider.WillSetStateTo(mappingModel.SetStateTo);
}
if (mappingModel.Webhook?.Request != null)
if (mappingModel.Webhook != null)
{
respondProvider = respondProvider.WithWebhook(WebhookMapper.Map(mappingModel.Webhook));
}
else if (mappingModel.Webhooks?.Length > 1)
{
var webhooks = mappingModel.Webhooks.Select(WebhookMapper.Map).ToArray();
respondProvider = respondProvider.WithWebhook(webhooks);
}
respondProvider.RespondWith(responseBuilder);

View File

@@ -121,13 +121,16 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Handlebars.Net.Helpers" Version="2.1.2" />
<PackageReference Include="Handlebars.Net.Helpers.DynamicLinq" Version="2.1.2" />
<PackageReference Include="Handlebars.Net.Helpers.Json" Version="2.1.2" />
<PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.1.2" />
<PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.1.2" />
<PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.1.2" />
<PackageReference Include="Handlebars.Net.Helpers" Version="2.2.0" />
<PackageReference Include="Handlebars.Net.Helpers.DynamicLinq" Version="2.2.0" />
<PackageReference Include="Handlebars.Net.Helpers.Humanizer" Version="2.2.0" />
<PackageReference Include="Handlebars.Net.Helpers.Json" Version="2.2.0" />
<PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.2.0" />
<PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.2.0" />
<PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WireMock.Net.Abstractions\WireMock.Net.Abstractions.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,50 @@
using System;
using System.Threading.Tasks;
using Moq;
using Newtonsoft.Json.Linq;
using NFluent;
using WireMock.Handlers;
using WireMock.Models;
using WireMock.ResponseBuilders;
using WireMock.Settings;
using Xunit;
namespace WireMock.Net.Tests.ResponseBuilders
{
public class ResponseWithHandlebarsHumanizerTests
{
private const string ClientIp = "::1";
private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
public ResponseWithHandlebarsHumanizerTests()
{
_filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
_filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
_settings.FileSystemHandler = _filesystemHandlerMock.Object;
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Humanizer()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
var responseBuilder = Response.Create()
.WithBodyAsJson(new
{
DateTime = string.Format("{{{{[Humanizer.Humanize] \"{0}\" }}}}", DateTime.UtcNow.AddHours(-30).ToString("O"))
})
.WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings);
// Assert
JObject j = JObject.FromObject(response.Message.BodyData.BodyAsJson);
Check.That(j["DateTime"].Value<string>()).IsEqualTo("yesterday");
}
}
}

View File

@@ -65,25 +65,6 @@ namespace WireMock.Net.Tests.ResponseBuilders
Check.That(response.Message.BodyData.BodyAsString).Equals("");
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch_NoMatch_WithDefaultValue()
{
// Assign
var body = new BodyData { BodyAsString = "abc", DetectedBodyType = BodyType.String };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithBody("{{Regex.Match request.body \"^?0$\" \"d\"}}")
.WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings);
// assert
Check.That(response.Message.BodyData.BodyAsString).Equals("d");
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch2()
{
@@ -122,25 +103,6 @@ namespace WireMock.Net.Tests.ResponseBuilders
Check.That(response.Message.BodyData.BodyAsString).Equals("");
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch2_NoMatch_WithDefaultValue()
{
// Assign
var body = new BodyData { BodyAsString = "{{\\test", DetectedBodyType = BodyType.String };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithBody("{{#Regex.Match request.body \"^(?<proto>\\w+)://[^/]+?(?<port>\\d+)/?\" \"x\"}}{{this}}{{/Regex.Match}}")
.WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings);
// assert
Check.That(response.Message.BodyData.BodyAsString).Equals("x");
}
[Fact]
public void Response_ProvideResponseAsync_Handlebars_RegexMatch2_Throws()
{

View File

@@ -24,31 +24,34 @@ namespace WireMock.Net.Tests.Serialization
}
[Fact]
public void ToMappingModel()
public void ToMappingModel_With_SingleWebHook()
{
// Assign
var request = Request.Create();
var response = Response.Create();
var webhook = new Webhook
var webhooks = new IWebhook[]
{
Request = new WebhookRequest
new Webhook
{
Url = "https://test.com",
Headers = new Dictionary<string, WireMockList<string>>
Request = new WebhookRequest
{
{ "Single", new WireMockList<string>("x") },
{ "Multi", new WireMockList<string>("a", "b") }
},
Method = "post",
BodyData = new BodyData
{
BodyAsString = "b",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.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
}
}
}
};
var mapping = new Mapping(Guid.NewGuid(), "", null, _settings, request, response, 0, null, null, null, null, webhook);
var mapping = new Mapping(Guid.NewGuid(), "", null, _settings, request, response, 0, null, null, null, null, webhooks);
// Act
var model = _sut.ToMappingModel(mapping);
@@ -61,6 +64,8 @@ namespace WireMock.Net.Tests.Serialization
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);
@@ -68,6 +73,80 @@ namespace WireMock.Net.Tests.Serialization
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(), "", null, _settings, request, response, 0, null, null, null, null, webhooks
);
// 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_WithPriority_ReturnsPriority()
{

View File

@@ -16,6 +16,74 @@ namespace WireMock.Net.Tests
{
public class WireMockServerWebhookTests
{
[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
{
Request = new WebhookRequest
{
Url = serverReceivingTheWebhook1.Urls[0],
Method = "post",
BodyData = new BodyData
{
BodyAsString = "1",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
}
}
};
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);
string content = await response.Content.ReadAsStringAsync();
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()
{