Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webhook #591

Merged
merged 22 commits into from
Mar 24, 2021
128 changes: 64 additions & 64 deletions examples/WireMock.Net.StandAlone.NETCoreApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,40 +1,40 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using log4net;
using log4net.Config;
using log4net.Repository;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using log4net;
using log4net.Config;
using log4net.Repository;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;
using WireMock.Util;
namespace WireMock.Net.StandAlone.NETCoreApp
{
static class Program
{
private static readonly ILoggerRepository LogRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
// private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
private static int sleepTime = 30000;
private static WireMockServer _server;
static void Main(string[] args)
{
XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));

namespace WireMock.Net.StandAlone.NETCoreApp
{
static class Program
{
private static readonly ILoggerRepository LogRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
// private static readonly ILog Log = LogManager.GetLogger(typeof(Program));

private static int sleepTime = 30000;
private static WireMockServer _server;

static void Main(string[] args)
{
XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));

if (!WireMockServerSettingsParser.TryParseArguments(args, out var settings, new WireMockLog4NetLogger()))
{
return;
}

settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));
_server = WireMockServer.Start(settings);
settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));

_server = WireMockServer.Start(settings);

_server.Given(Request.Create().WithPath("/api/sap")
.UsingPost()
.WithBody((IBodyData xmlData) => {
Expand All @@ -43,37 +43,37 @@ static void Main(string[] args)
}))
.RespondWith(Response.Create().WithStatusCode(System.Net.HttpStatusCode.OK));

_server
.Given(Request.Create()
.UsingAnyMethod())
.RespondWith(Response.Create()
.WithTransformer()
.WithBody("{{Random Type=\"Integer\" Min=100 Max=999999}} {{DateTime.Now}} {{DateTime.Now \"yyyy-MMM\"}} {{String.Format (DateTime.Now) \"MMM-dd\"}}"));
Console.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down");
Console.CancelKeyPress += (s, e) =>
{
Stop("CancelKeyPress");
};
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
{
Stop("AssemblyLoadContext.Default.Unloading");
};
while (true)
{
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server running : {_server.IsStarted}");
Thread.Sleep(sleepTime);
}
}
private static void Stop(string why)
{
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server stopping because '{why}'");
_server.Stop();
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server stopped");
}
}
_server
.Given(Request.Create()
.UsingAnyMethod())
.RespondWith(Response.Create()
.WithTransformer()
.WithBody("{{Random Type=\"Integer\" Min=100 Max=999999}} {{DateTime.Now}} {{DateTime.Now \"yyyy-MMM\"}} {{String.Format (DateTime.Now) \"MMM-dd\"}}"));

Console.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down");

Console.CancelKeyPress += (s, e) =>
{
Stop("CancelKeyPress");
};

System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
{
Stop("AssemblyLoadContext.Default.Unloading");
};

while (true)
{
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server running : {_server.IsStarted}");
Thread.Sleep(sleepTime);
}
}

private static void Stop(string why)
{
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server stopping because '{why}'");
_server.Stop();
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server stopped");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"profiles": {
"WireMock.Net.StandAlone.NETCoreApp": {
"commandName": "Project",
"commandLineArgs": "--Urls https://localhost:10080 --WireMockLogger WireMockConsoleLogger"
"commandLineArgs": "--Urls http://localhost:9091 --WireMockLogger WireMockConsoleLogger"
}
}
}
5 changes: 5 additions & 0 deletions src/WireMock.Net.Abstractions/Admin/Mappings/MappingModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,10 @@ public class MappingModel
/// Saves this mapping as a static mapping file.
/// </summary>
public bool? SaveToFile { get; set; }

/// <summary>
/// The Webhook.
/// </summary>
public WebhookModel Webhook { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Collections.Generic;
using WireMock.Types;

namespace WireMock.Admin.Mappings
{
Expand Down
13 changes: 13 additions & 0 deletions src/WireMock.Net.Abstractions/Admin/Mappings/WebhookModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace WireMock.Admin.Mappings
{
/// <summary>
/// The Webhook
/// </summary>
public class WebhookModel
{
/// <summary>
/// The Webhook Request.
/// </summary>
public WebhookRequestModel Request { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System.Collections.Generic;

namespace WireMock.Admin.Mappings
{
/// <summary>
/// RequestModel
/// </summary>
public class WebhookRequestModel
{
/// <summary>
/// Gets or sets the Url.
/// </summary>
public string Url { get; set; }

/// <summary>
/// The methods
/// </summary>
public string Method { get; set; }

/// <summary>
/// Gets or sets the headers.
/// </summary>
public IDictionary<string, string> Headers { get; set; }

/// <summary>
/// Gets or sets the body.
/// </summary>
public string Body { get; set; }

/// <summary>
/// Gets or sets the body (as JSON object).
/// </summary>
public object BodyAsJson { get; set; }

/// <summary>
/// Use ResponseMessage Transformer.
/// </summary>
public bool? UseTransformer { get; set; }

/// <summary>
/// Gets the type of the transformer.
/// </summary>
public string TransformerType { get; set; }
}
}
13 changes: 13 additions & 0 deletions src/WireMock.Net.Abstractions/Models/IWebhook.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace WireMock.Models
{
/// <summary>
/// IWebhook
/// </summary>
public interface IWebhook
{
/// <summary>
/// Request
/// </summary>
IWebhookRequest Request { get; set; }
}
}
42 changes: 42 additions & 0 deletions src/WireMock.Net.Abstractions/Models/IWebhookRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Collections.Generic;
using WireMock.Types;
using WireMock.Util;

namespace WireMock.Models
{
/// <summary>
/// IWebhookRequest
/// </summary>
public interface IWebhookRequest
{
/// <summary>
/// The Webhook Url.
/// </summary>
string Url { 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 body to send.
/// </summary>
IBodyData BodyData { get; set; }

/// <summary>
/// Use Transformer.
/// </summary>
bool? UseTransformer { get; set; }

/// <summary>
/// The transformer type.
/// </summary>
TransformerType TransformerType { get; set; }
}
}
2 changes: 1 addition & 1 deletion src/WireMock.Net/Http/HttpClientBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace WireMock.Http
{
internal static class HttpClientBuilder
{
public static HttpClient Build(IProxyAndRecordSettings settings)
public static HttpClient Build(IHttpClientSettings settings)
{
#if NETSTANDARD || NETCOREAPP3_1 || NET5_0
var handler = new HttpClientHandler
Expand Down
85 changes: 85 additions & 0 deletions src/WireMock.Net/Http/WebhookSender.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using JetBrains.Annotations;
using WireMock.Models;
using WireMock.Settings;
using WireMock.Transformers;
using WireMock.Transformers.Handlebars;
using WireMock.Transformers.Scriban;
using WireMock.Types;
using WireMock.Util;
using WireMock.Validation;

namespace WireMock.Http
{
internal class WebhookSender
{
private const string ClientIp = "::1";

private readonly IWireMockServerSettings _settings;

public WebhookSender(IWireMockServerSettings settings)
{
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
}

public Task<HttpResponseMessage> SendAsync([NotNull] HttpClient client, [NotNull] IWebhookRequest request, [NotNull] RequestMessage originalRequestMessage, [NotNull] ResponseMessage originalResponseMessage)
{
Check.NotNull(client, nameof(client));
Check.NotNull(request, nameof(request));
Check.NotNull(originalRequestMessage, nameof(originalRequestMessage));
Check.NotNull(originalResponseMessage, nameof(originalResponseMessage));

IBodyData bodyData;
IDictionary<string, WireMockList<string>> headers;
if (request.UseTransformer == true)
{
ITransformer responseMessageTransformer;
switch (request.TransformerType)
{
case TransformerType.Handlebars:
var factoryHandlebars = new HandlebarsContextFactory(_settings.FileSystemHandler, _settings.HandlebarsRegistrationCallback);
responseMessageTransformer = new Transformer(factoryHandlebars);
break;

case TransformerType.Scriban:
case TransformerType.ScribanDotLiquid:
var factoryDotLiquid = new ScribanContextFactory(_settings.FileSystemHandler, request.TransformerType);
responseMessageTransformer = new Transformer(factoryDotLiquid);
break;

default:
throw new NotImplementedException($"TransformerType '{request.TransformerType}' is not supported.");
}

(bodyData, headers) = responseMessageTransformer.Transform(originalRequestMessage, originalResponseMessage, request.BodyData, request.Headers);
}
else
{
bodyData = request.BodyData;
headers = request.Headers;
}

// Create RequestMessage
var requestMessage = new RequestMessage(
new UrlDetails(request.Url),
request.Method,
ClientIp,
bodyData,
headers?.ToDictionary(x => x.Key, x => x.Value.ToArray())
)
{
DateTime = DateTime.UtcNow
};

// Create HttpRequestMessage
var httpRequestMessage = HttpRequestMessageHelper.Create(requestMessage, request.Url);

// Call the URL
return client.SendAsync(httpRequestMessage);
}
}
}
Loading