mirror of
https://github.com/wiremock/WireMock.Net.git
synced 2026-03-22 17:40:33 +01:00
Add MappingBuilder to build mappings in code and export to Models or JSON (#869)
* MappingBuilder * . * ... * sc * t * .
This commit is contained in:
43
src/WireMock.Net/IMappingBuilder.cs
Normal file
43
src/WireMock.Net/IMappingBuilder.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using WireMock.Admin.Mappings;
|
||||
using WireMock.Matchers.Request;
|
||||
using WireMock.Server;
|
||||
|
||||
namespace WireMock;
|
||||
|
||||
/// <summary>
|
||||
/// IMappingBuilder
|
||||
/// </summary>
|
||||
public interface IMappingBuilder
|
||||
{
|
||||
/// <summary>
|
||||
/// The given.
|
||||
/// </summary>
|
||||
/// <param name="requestMatcher">The request matcher.</param>
|
||||
/// <param name="saveToFile">Optional boolean to indicate if this mapping should be saved as static mapping file.</param>
|
||||
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
|
||||
IRespondWithAProvider Given(IRequestMatcher requestMatcher, bool saveToFile = false);
|
||||
|
||||
/// <summary>
|
||||
/// Gets all the mappings as a list.
|
||||
/// </summary>
|
||||
/// <returns>A list from <see cref="MappingModel"/>s.</returns>
|
||||
MappingModel[] GetMappings();
|
||||
|
||||
/// <summary>
|
||||
/// Convert all mappings to JSON.
|
||||
/// </summary>
|
||||
/// <returns>JSON</returns>
|
||||
string ToJson();
|
||||
|
||||
/// <summary>
|
||||
/// Save all mappings as a single JSON to a file.
|
||||
/// </summary>
|
||||
/// <param name="path">The file to write to.</param>
|
||||
void SaveMappingsToFile(string path);
|
||||
|
||||
/// <summary>
|
||||
/// Save all mappings as multiple JSON files (each file is 1 mapping).
|
||||
/// </summary>
|
||||
/// <param name="folder">The folder to write the files to.</param>
|
||||
void SaveMappingsToFolder(string folder);
|
||||
}
|
||||
116
src/WireMock.Net/MappingBuilder.cs
Normal file
116
src/WireMock.Net/MappingBuilder.cs
Normal file
@@ -0,0 +1,116 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json;
|
||||
using Stef.Validation;
|
||||
using WireMock.Admin.Mappings;
|
||||
using WireMock.Matchers.Request;
|
||||
using WireMock.Owin;
|
||||
using WireMock.Serialization;
|
||||
using WireMock.Server;
|
||||
using WireMock.Settings;
|
||||
|
||||
namespace WireMock;
|
||||
|
||||
/// <summary>
|
||||
/// MappingBuilder
|
||||
/// </summary>
|
||||
public class MappingBuilder : IMappingBuilder
|
||||
{
|
||||
private readonly WireMockServerSettings _settings;
|
||||
private readonly IWireMockMiddlewareOptions _options;
|
||||
|
||||
private readonly MappingConverter _mappingConverter;
|
||||
private readonly MappingToFileSaver _mappingToFileSaver;
|
||||
|
||||
/// <summary>
|
||||
/// Create a MappingBuilder
|
||||
/// </summary>
|
||||
/// <param name="settings">The optional <see cref="WireMockServerSettings"/>.</param>
|
||||
public MappingBuilder(WireMockServerSettings? settings = null)
|
||||
{
|
||||
_settings = settings ?? new WireMockServerSettings();
|
||||
_options = WireMockMiddlewareOptionsHelper.InitFromSettings(_settings);
|
||||
|
||||
var matcherMapper = new MatcherMapper(_settings);
|
||||
_mappingConverter = new MappingConverter(matcherMapper);
|
||||
_mappingToFileSaver = new MappingToFileSaver(_settings, _mappingConverter);
|
||||
}
|
||||
|
||||
internal MappingBuilder(
|
||||
WireMockServerSettings settings,
|
||||
IWireMockMiddlewareOptions options,
|
||||
MappingConverter mappingConverter,
|
||||
MappingToFileSaver mappingToFileSaver
|
||||
)
|
||||
{
|
||||
_settings = Guard.NotNull(settings);
|
||||
_options = Guard.NotNull(options);
|
||||
_mappingConverter = Guard.NotNull(mappingConverter);
|
||||
_mappingToFileSaver = Guard.NotNull(mappingToFileSaver);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IRespondWithAProvider Given(IRequestMatcher requestMatcher, bool saveToFile = false)
|
||||
{
|
||||
return new RespondWithAProvider(RegisterMapping, Guard.NotNull(requestMatcher), _settings, saveToFile);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public MappingModel[] GetMappings()
|
||||
{
|
||||
return _options.Mappings.Values.ToArray()
|
||||
.Where(m => !m.IsAdminInterface)
|
||||
.Select(_mappingConverter.ToMappingModel)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ToJson()
|
||||
{
|
||||
return ToJson(GetMappings());
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void SaveMappingsToFile(string path)
|
||||
{
|
||||
_mappingToFileSaver.SaveMappingsToFile(GetNonAdminMappings(), path);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void SaveMappingsToFolder(string? folder)
|
||||
{
|
||||
foreach (var mapping in GetNonAdminMappings().Where(m => !m.IsAdminInterface))
|
||||
{
|
||||
_mappingToFileSaver.SaveMappingToFile(mapping, folder);
|
||||
}
|
||||
}
|
||||
|
||||
private IMapping[] GetNonAdminMappings()
|
||||
{
|
||||
return _options.Mappings.Values.ToArray();
|
||||
}
|
||||
|
||||
private void RegisterMapping(IMapping mapping, bool saveToFile)
|
||||
{
|
||||
// Check a mapping exists with the same Guid. If so, update the datetime and replace it.
|
||||
if (_options.Mappings.ContainsKey(mapping.Guid))
|
||||
{
|
||||
mapping.UpdatedAt = DateTime.UtcNow;
|
||||
_options.Mappings[mapping.Guid] = mapping;
|
||||
}
|
||||
else
|
||||
{
|
||||
_options.Mappings.TryAdd(mapping.Guid, mapping);
|
||||
}
|
||||
|
||||
if (saveToFile)
|
||||
{
|
||||
_mappingToFileSaver.SaveMappingToFile(mapping);
|
||||
}
|
||||
}
|
||||
|
||||
private static string ToJson(object value)
|
||||
{
|
||||
return JsonConvert.SerializeObject(value, JsonSerializationConstants.JsonSerializerSettingsDefault);
|
||||
}
|
||||
}
|
||||
35
src/WireMock.Net/Owin/WireMockMiddlewareOptionsHelper.cs
Normal file
35
src/WireMock.Net/Owin/WireMockMiddlewareOptionsHelper.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using Stef.Validation;
|
||||
using WireMock.Settings;
|
||||
|
||||
namespace WireMock.Owin;
|
||||
|
||||
internal static class WireMockMiddlewareOptionsHelper
|
||||
{
|
||||
public static IWireMockMiddlewareOptions InitFromSettings(WireMockServerSettings settings, IWireMockMiddlewareOptions? options = null)
|
||||
{
|
||||
Guard.NotNull(settings);
|
||||
|
||||
options ??= new WireMockMiddlewareOptions();
|
||||
|
||||
options.FileSystemHandler = settings.FileSystemHandler;
|
||||
options.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit;
|
||||
options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit;
|
||||
options.Logger = settings.Logger;
|
||||
options.DisableJsonBodyParsing = settings.DisableJsonBodyParsing;
|
||||
options.HandleRequestsSynchronously = settings.HandleRequestsSynchronously;
|
||||
options.SaveUnmatchedRequests = settings.SaveUnmatchedRequests;
|
||||
options.DoNotSaveDynamicResponseInLogEntry = settings.DoNotSaveDynamicResponseInLogEntry;
|
||||
options.QueryParameterMultipleValueSupport = settings.QueryParameterMultipleValueSupport;
|
||||
|
||||
if (settings.CustomCertificateDefined)
|
||||
{
|
||||
options.X509StoreName = settings.CertificateSettings!.X509StoreName;
|
||||
options.X509StoreLocation = settings.CertificateSettings.X509StoreLocation;
|
||||
options.X509ThumbprintOrSubjectName = settings.CertificateSettings.X509StoreThumbprintOrSubjectName;
|
||||
options.X509CertificateFilePath = settings.CertificateSettings.X509CertificateFilePath;
|
||||
options.X509CertificatePassword = settings.CertificateSettings.X509CertificatePassword;
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,20 @@ internal class MappingToFileSaver
|
||||
_mappingConverter = Guard.NotNull(mappingConverter);
|
||||
}
|
||||
|
||||
public void SaveMappingsToFile(IMapping[] mappings, string? folder = null)
|
||||
{
|
||||
folder ??= _settings.FileSystemHandler.GetMappingFolder();
|
||||
|
||||
if (!_settings.FileSystemHandler.FolderExists(folder))
|
||||
{
|
||||
_settings.FileSystemHandler.CreateFolder(folder);
|
||||
}
|
||||
|
||||
var models = mappings.Select(_mappingConverter.ToMappingModel).ToArray();
|
||||
|
||||
Save(models, folder);
|
||||
}
|
||||
|
||||
public void SaveMappingToFile(IMapping mapping, string? folder = null)
|
||||
{
|
||||
folder ??= _settings.FileSystemHandler.GetMappingFolder();
|
||||
@@ -31,9 +45,14 @@ internal class MappingToFileSaver
|
||||
var filename = BuildSanitizedFileName(mapping);
|
||||
var path = Path.Combine(folder, filename);
|
||||
|
||||
Save(model, path);
|
||||
}
|
||||
|
||||
private void Save(object value, string path)
|
||||
{
|
||||
_settings.Logger.Info("Saving Mapping file {0}", path);
|
||||
|
||||
_settings.FileSystemHandler.WriteMappingFile(path, JsonConvert.SerializeObject(model, JsonSerializationConstants.JsonSerializerSettingsDefault));
|
||||
_settings.FileSystemHandler.WriteMappingFile(path, JsonConvert.SerializeObject(value, JsonSerializationConstants.JsonSerializerSettingsDefault));
|
||||
}
|
||||
|
||||
private string BuildSanitizedFileName(IMapping mapping, char replaceChar = '_')
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AnyOfTypes;
|
||||
using SimMetrics.Net;
|
||||
using Stef.Validation;
|
||||
using WireMock.Admin.Mappings;
|
||||
using WireMock.Extensions;
|
||||
using WireMock.Matchers;
|
||||
@@ -19,7 +20,7 @@ internal class MatcherMapper
|
||||
|
||||
public MatcherMapper(WireMockServerSettings settings)
|
||||
{
|
||||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||||
_settings = Guard.NotNull(settings);
|
||||
}
|
||||
|
||||
public IMatcher[]? Map(IEnumerable<MatcherModel>? matchers)
|
||||
|
||||
@@ -111,10 +111,7 @@ public partial class WireMockServer
|
||||
[PublicAPI]
|
||||
public void SaveStaticMappings(string? folder = null)
|
||||
{
|
||||
foreach (var mapping in Mappings.Where(m => !m.IsAdminInterface))
|
||||
{
|
||||
_mappingToFileSaver.SaveMappingToFile(mapping, folder);
|
||||
}
|
||||
_mappingBuilder.SaveMappingsToFolder(folder);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IWireMockServer.ReadStaticMappings" />
|
||||
@@ -353,9 +350,9 @@ public partial class WireMockServer
|
||||
return ResponseMessageBuilder.Create("Mappings saved to disk");
|
||||
}
|
||||
|
||||
private IEnumerable<MappingModel> ToMappingModels()
|
||||
private MappingModel[] ToMappingModels()
|
||||
{
|
||||
return Mappings.Where(m => !m.IsAdminInterface).Select(_mappingConverter.ToMappingModel);
|
||||
return _mappingBuilder.GetMappings();
|
||||
}
|
||||
|
||||
private IResponseMessage MappingsGet(IRequestMessage requestMessage)
|
||||
@@ -418,18 +415,15 @@ public partial class WireMockServer
|
||||
try
|
||||
{
|
||||
var mappingModels = DeserializeRequestMessageToArray<MappingModel>(requestMessage);
|
||||
foreach (var mappingModel in mappingModels)
|
||||
foreach (var guid in mappingModels.Where(mm => mm.Guid.HasValue).Select(mm => mm.Guid!.Value))
|
||||
{
|
||||
if (mappingModel.Guid.HasValue)
|
||||
if (DeleteMapping(guid))
|
||||
{
|
||||
if (DeleteMapping(mappingModel.Guid.Value))
|
||||
{
|
||||
deletedGuids.Add(mappingModel.Guid.Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
_settings.Logger.Debug($"Did not find/delete mapping with GUID: {mappingModel.Guid.Value}.");
|
||||
}
|
||||
deletedGuids.Add(guid);
|
||||
}
|
||||
else
|
||||
{
|
||||
_settings.Logger.Debug($"Did not find/delete mapping with GUID: {guid}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -697,7 +691,7 @@ public partial class WireMockServer
|
||||
{
|
||||
return requestMessage.BodyData?.DetectedBodyType switch
|
||||
{
|
||||
BodyType.String => JsonUtils.DeserializeObject<T>(requestMessage.BodyData.BodyAsString),
|
||||
BodyType.String => JsonUtils.DeserializeObject<T>(requestMessage.BodyData.BodyAsString!),
|
||||
|
||||
BodyType.Json when requestMessage.BodyData?.BodyAsJson != null => ((JObject)requestMessage.BodyData.BodyAsJson).ToObject<T>()!,
|
||||
|
||||
@@ -726,7 +720,7 @@ public partial class WireMockServer
|
||||
{
|
||||
if (value is JArray jArray)
|
||||
{
|
||||
return jArray.ToObject<T[]>();
|
||||
return jArray.ToObject<T[]>()!;
|
||||
}
|
||||
|
||||
var singleResult = ((JObject)value).ToObject<T>();
|
||||
|
||||
@@ -38,6 +38,7 @@ public partial class WireMockServer : IWireMockServer
|
||||
private readonly MappingConverter _mappingConverter;
|
||||
private readonly MatcherMapper _matcherMapper;
|
||||
private readonly MappingToFileSaver _mappingToFileSaver;
|
||||
private readonly MappingBuilder _mappingBuilder;
|
||||
|
||||
/// <inheritdoc cref="IWireMockServer.IsStarted" />
|
||||
[PublicAPI]
|
||||
@@ -246,7 +247,7 @@ public partial class WireMockServer : IWireMockServer
|
||||
[PublicAPI]
|
||||
public static WireMockServer StartWithAdminInterfaceAndReadStaticMappings(params string[] urls)
|
||||
{
|
||||
Guard.NotNullOrEmpty(urls, nameof(urls));
|
||||
Guard.NotNullOrEmpty(urls);
|
||||
|
||||
return new WireMockServer(new WireMockServerSettings
|
||||
{
|
||||
@@ -268,7 +269,7 @@ public partial class WireMockServer : IWireMockServer
|
||||
/// <exception cref="TimeoutException">Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}</exception>
|
||||
protected WireMockServer(WireMockServerSettings settings)
|
||||
{
|
||||
_settings = settings;
|
||||
_settings = Guard.NotNull(settings);
|
||||
|
||||
// Set default values if not provided
|
||||
_settings.Logger = settings.Logger ?? new WireMockNullLogger();
|
||||
@@ -305,28 +306,12 @@ public partial class WireMockServer : IWireMockServer
|
||||
}
|
||||
}
|
||||
|
||||
_options.FileSystemHandler = _settings.FileSystemHandler;
|
||||
_options.PreWireMockMiddlewareInit = _settings.PreWireMockMiddlewareInit;
|
||||
_options.PostWireMockMiddlewareInit = _settings.PostWireMockMiddlewareInit;
|
||||
_options.Logger = _settings.Logger;
|
||||
_options.DisableJsonBodyParsing = _settings.DisableJsonBodyParsing;
|
||||
_options.HandleRequestsSynchronously = settings.HandleRequestsSynchronously;
|
||||
_options.SaveUnmatchedRequests = settings.SaveUnmatchedRequests;
|
||||
_options.DoNotSaveDynamicResponseInLogEntry = settings.DoNotSaveDynamicResponseInLogEntry;
|
||||
_options.QueryParameterMultipleValueSupport = settings.QueryParameterMultipleValueSupport;
|
||||
|
||||
if (settings.CustomCertificateDefined)
|
||||
{
|
||||
_options.X509StoreName = settings.CertificateSettings!.X509StoreName;
|
||||
_options.X509StoreLocation = settings.CertificateSettings.X509StoreLocation;
|
||||
_options.X509ThumbprintOrSubjectName = settings.CertificateSettings.X509StoreThumbprintOrSubjectName;
|
||||
_options.X509CertificateFilePath = settings.CertificateSettings.X509CertificateFilePath;
|
||||
_options.X509CertificatePassword = settings.CertificateSettings.X509CertificatePassword;
|
||||
}
|
||||
WireMockMiddlewareOptionsHelper.InitFromSettings(settings, _options);
|
||||
|
||||
_matcherMapper = new MatcherMapper(_settings);
|
||||
_mappingConverter = new MappingConverter(_matcherMapper);
|
||||
_mappingToFileSaver = new MappingToFileSaver(_settings, _mappingConverter);
|
||||
_mappingBuilder = new MappingBuilder(settings, _options, _mappingConverter, _mappingToFileSaver);
|
||||
|
||||
#if USE_ASPNETCORE
|
||||
_options.AdditionalServiceRegistration = _settings.AdditionalServiceRegistration;
|
||||
@@ -538,26 +523,7 @@ public partial class WireMockServer : IWireMockServer
|
||||
[PublicAPI]
|
||||
public IRespondWithAProvider Given(IRequestMatcher requestMatcher, bool saveToFile = false)
|
||||
{
|
||||
return new RespondWithAProvider(RegisterMapping, requestMatcher, _settings, saveToFile);
|
||||
}
|
||||
|
||||
private void RegisterMapping(IMapping mapping, bool saveToFile)
|
||||
{
|
||||
// Check a mapping exists with the same Guid. If so, update the datetime and replace it.
|
||||
if (_options.Mappings.ContainsKey(mapping.Guid))
|
||||
{
|
||||
mapping.UpdatedAt = DateTime.UtcNow;
|
||||
_options.Mappings[mapping.Guid] = mapping;
|
||||
}
|
||||
else
|
||||
{
|
||||
_options.Mappings.TryAdd(mapping.Guid, mapping);
|
||||
}
|
||||
|
||||
if (saveToFile)
|
||||
{
|
||||
_mappingToFileSaver.SaveMappingToFile(mapping);
|
||||
}
|
||||
return _mappingBuilder.Given(requestMatcher, saveToFile);
|
||||
}
|
||||
|
||||
private void InitSettings(WireMockServerSettings settings)
|
||||
|
||||
Reference in New Issue
Block a user