diff --git a/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs b/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs index 41e82c15..02dd6679 100644 --- a/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs +++ b/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs @@ -106,8 +106,19 @@ namespace WireMock.Net.ConsoleApplication //server.SetAzureADAuthentication("6c2a4722-f3b9-4970-b8fc-fac41e29stef", "8587fde1-7824-42c7-8592-faf92b04stef"); // server.AllowPartialMapping(); + server + .Given(Request.Create() + .UsingMethod("GET") + .WithPath("/foo1") + .WithParam("p1", "xyz") + ) + .WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05") + .RespondWith(Response.Create() + .WithBody("Hello World") + ); server.Given(Request.Create().WithPath(MatchOperator.Or, "/mypath", "/mypath1", "/mypath2").UsingPost()) + .WithGuid("86984b0e-2516-4935-a2ef-b45bf4820d7d") .RespondWith(Response.Create() .WithHeader("Content-Type", "application/json") .WithBodyAsJson("{{JsonPath.SelectToken request.body \"..name\"}}") @@ -380,7 +391,7 @@ namespace WireMock.Net.ConsoleApplication // http://localhost:9091/trans?start=1000&stop=1&stop=2 server .Given(Request.Create().WithPath("/trans").UsingGet()) - .WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05") + .WithGuid("90356dba-b36c-469a-a17e-669cd84f1f06") .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") diff --git a/src/WireMock.Net.Abstractions/IRequestMessage.cs b/src/WireMock.Net.Abstractions/IRequestMessage.cs index 87905071..543229fe 100644 --- a/src/WireMock.Net.Abstractions/IRequestMessage.cs +++ b/src/WireMock.Net.Abstractions/IRequestMessage.cs @@ -78,6 +78,11 @@ public interface IRequestMessage /// IDictionary>? Query { get; } + /// + /// Gets the query. + /// + IDictionary>? QueryIgnoreCase { get; } + /// /// Gets the raw query. /// diff --git a/src/WireMock.Net.Abstractions/Server/IWireMockServer.cs b/src/WireMock.Net.Abstractions/Server/IWireMockServer.cs index 2775049b..f29e5dca 100644 --- a/src/WireMock.Net.Abstractions/Server/IWireMockServer.cs +++ b/src/WireMock.Net.Abstractions/Server/IWireMockServer.cs @@ -3,212 +3,227 @@ using System.Collections.Generic; using System.Collections.Specialized; using WireMock.Admin.Mappings; using WireMock.Logging; +using WireMock.Types; -namespace WireMock.Server +namespace WireMock.Server; + +/// +/// The fluent mock server interface. +/// +public interface IWireMockServer : IDisposable { /// - /// The fluent mock server interface. + /// Gets a value indicating whether this server is started. /// - public interface IWireMockServer : IDisposable - { - /// - /// Gets a value indicating whether this server is started. - /// - bool IsStarted { get; } + bool IsStarted { get; } - /// - /// Gets the request logs. - /// - IEnumerable LogEntries { get; } + /// + /// Gets the request logs. + /// + IEnumerable LogEntries { get; } - /// - /// Gets the mappings as MappingModels. - /// - IEnumerable MappingModels { get; } + /// + /// Gets the mappings as MappingModels. + /// + IEnumerable MappingModels { get; } - // - // Gets the mappings. - // - //[PublicAPI] - //IEnumerable Mappings { get; } + // + // Gets the mappings. + // + //[PublicAPI] + //IEnumerable Mappings { get; } - /// - /// Gets the ports. - /// - List Ports { get; } + /// + /// Gets the ports. + /// + List Ports { get; } - /// - /// Gets the first port. - /// - int Port { get; } + /// + /// Gets the first port. + /// + int Port { get; } - /// - /// Gets the urls. - /// - string[] Urls { get; } + /// + /// Gets the urls. + /// + string[] Urls { get; } - /// - /// Gets the first url. - /// - string? Url { get; } + /// + /// Gets the first url. + /// + string? Url { get; } - /// - /// Gets the consumer. - /// - string? Consumer { get; } + /// + /// Gets the consumer. + /// + string? Consumer { get; } - /// - /// Gets the provider. - /// - string? Provider { get; } + /// + /// Gets the provider. + /// + string? Provider { get; } - //ConcurrentDictionary Scenarios { get; } + //ConcurrentDictionary Scenarios { get; } - /// - /// Occurs when [log entries changed]. - /// - event NotifyCollectionChangedEventHandler LogEntriesChanged; + /// + /// Occurs when [log entries changed]. + /// + event NotifyCollectionChangedEventHandler LogEntriesChanged; - /// - /// Adds a 'catch all mapping' - /// - /// - matches all Paths and any Methods - /// - priority is set to 1000 - /// - responds with a 404 "No matching mapping found" - /// - void AddCatchAllMapping(); + /// + /// Adds a 'catch all mapping' + /// + /// - matches all Paths and any Methods + /// - priority is set to 1000 + /// - responds with a 404 "No matching mapping found" + /// + void AddCatchAllMapping(); - /// - /// The add request processing delay. - /// - /// The delay. - void AddGlobalProcessingDelay(TimeSpan delay); + /// + /// The add request processing delay. + /// + /// The delay. + void AddGlobalProcessingDelay(TimeSpan delay); - /// - /// Allows the partial mapping. - /// - void AllowPartialMapping(bool allow = true); + /// + /// Allows the partial mapping. + /// + void AllowPartialMapping(bool allow = true); - /// - /// Deletes a LogEntry. - /// - /// The unique identifier. - bool DeleteLogEntry(Guid guid); + /// + /// Deletes a LogEntry. + /// + /// The unique identifier. + bool DeleteLogEntry(Guid guid); - /// - /// Deletes the mapping. - /// - /// The unique identifier. - bool DeleteMapping(Guid guid); + /// + /// Deletes the mapping. + /// + /// The unique identifier. + bool DeleteMapping(Guid guid); - //IEnumerable FindLogEntries([NotNull] params IRequestMatcher[] matchers); + //IEnumerable FindLogEntries([NotNull] params IRequestMatcher[] matchers); - // IRespondWithAProvider Given(IRequestMatcher requestMatcher, bool saveToFile = false); + // IRespondWithAProvider Given(IRequestMatcher requestMatcher, bool saveToFile = false); - /// - /// Reads a static mapping file and adds or updates a single mapping. - /// - /// Calling this method manually forces WireMock.Net to read and apply the specified static mapping file. - /// - /// The path to the static mapping file. - bool ReadStaticMappingAndAddOrUpdate(string path); + /// + /// Reads a static mapping file and adds or updates a single mapping. + /// + /// Calling this method manually forces WireMock.Net to read and apply the specified static mapping file. + /// + /// The path to the static mapping file. + bool ReadStaticMappingAndAddOrUpdate(string path); - /// - /// Reads the static mappings from a folder. - /// (This method is also used when WireMockServerSettings.ReadStaticMappings is set to true. - /// - /// Calling this method manually forces WireMock.Net to read and apply all static mapping files in the specified folder. - /// - /// The optional folder. If not defined, use {CurrentFolder}/__admin/mappings - void ReadStaticMappings(string? folder = null); + /// + /// Reads the static mappings from a folder. + /// (This method is also used when WireMockServerSettings.ReadStaticMappings is set to true. + /// + /// Calling this method manually forces WireMock.Net to read and apply all static mapping files in the specified folder. + /// + /// The optional folder. If not defined, use {CurrentFolder}/__admin/mappings + void ReadStaticMappings(string? folder = null); - /// - /// Removes the authentication. - /// - void RemoveAuthentication(); + /// + /// Removes the authentication. + /// + void RemoveAuthentication(); - /// - /// Resets LogEntries and Mappings. - /// - void Reset(); + /// + /// Resets LogEntries and Mappings. + /// + void Reset(); - /// - /// Resets the Mappings. - /// - void ResetMappings(); + /// + /// Resets the Mappings. + /// + void ResetMappings(); - /// - /// Resets all Scenarios. - /// - void ResetScenarios(); + /// + /// Resets all Scenarios. + /// + void ResetScenarios(); - /// - /// Resets a specific Scenario by the name. - /// - bool ResetScenario(string name); + /// + /// Resets a specific Scenario by the name. + /// + bool ResetScenario(string name); - /// - /// Resets the LogEntries. - /// - void ResetLogEntries(); + /// + /// Resets the LogEntries. + /// + void ResetLogEntries(); - /// - /// Saves the static mappings. - /// - /// The optional folder. If not defined, use {CurrentFolder}/__admin/mappings - void SaveStaticMappings(string? folder = null); + /// + /// Saves the static mappings. + /// + /// The optional folder. If not defined, use {CurrentFolder}/__admin/mappings + void SaveStaticMappings(string? folder = null); - /// - /// Sets the basic authentication. - /// - /// The Tenant. - /// The Audience or Resource. - void SetAzureADAuthentication(string tenant, string audience); + /// + /// Sets the basic authentication. + /// + /// The Tenant. + /// The Audience or Resource. + void SetAzureADAuthentication(string tenant, string audience); - /// - /// Sets the basic authentication. - /// - /// The username. - /// The password. - void SetBasicAuthentication(string username, string password); + /// + /// Sets the basic authentication. + /// + /// The username. + /// The password. + void SetBasicAuthentication(string username, string password); - /// - /// Sets the maximum RequestLog count. - /// - /// The maximum RequestLog count. - void SetMaxRequestLogCount(int? maxRequestLogCount); + /// + /// Sets the maximum RequestLog count. + /// + /// The maximum RequestLog count. + void SetMaxRequestLogCount(int? maxRequestLogCount); - /// - /// Sets RequestLog expiration in hours. - /// - /// The RequestLog expiration in hours. - void SetRequestLogExpirationDuration(int? requestLogExpirationDuration); + /// + /// Sets RequestLog expiration in hours. + /// + /// The RequestLog expiration in hours. + void SetRequestLogExpirationDuration(int? requestLogExpirationDuration); - /// - /// Stop this server. - /// - void Stop(); + /// + /// Stop this server. + /// + void Stop(); - /// - /// Watches the static mappings for changes. - /// - /// The optional folder. If not defined, use {CurrentFolder}/__admin/mappings - void WatchStaticMappings(string? folder = null); + /// + /// Watches the static mappings for changes. + /// + /// The optional folder. If not defined, use {CurrentFolder}/__admin/mappings + void WatchStaticMappings(string? folder = null); - /// - /// Register the mappings (via ). - /// - /// This can be used if you have 1 or more defined and want to register these in WireMock.Net directly instead of using the fluent syntax. - /// - /// The MappingModels - IWireMockServer WithMapping(params MappingModel[] mappings); + /// + /// Register the mappings (via ). + /// + /// This can be used if you have 1 or more defined and want to register these in WireMock.Net directly instead of using the fluent syntax. + /// + /// The MappingModels + IWireMockServer WithMapping(params MappingModel[] mappings); - /// - /// Register the mappings (via json string). - /// - /// This can be used if you the mappings as json string defined and want to register these in WireMock.Net directly instead of using the fluent syntax. - /// - /// The mapping(s) as json string. - IWireMockServer WithMapping(string mappings); - } + /// + /// Register the mappings (via json string). + /// + /// This can be used if you the mappings as json string defined and want to register these in WireMock.Net directly instead of using the fluent syntax. + /// + /// The mapping(s) as json string. + IWireMockServer WithMapping(string mappings); + + /// + /// Get the C# code for a mapping. + /// + /// The Mapping Guid. + /// The + /// C# code (null in case the mapping is not found) + string? MappingToCSharpCode(Guid guid, MappingConverterType converterType); + + /// + /// Get the C# code for all mappings. + /// + /// The + /// C# code + public string MappingsToCSharpCode(MappingConverterType converterType); } \ No newline at end of file diff --git a/src/WireMock.Net.RestClient/IWireMockAdminApi.cs b/src/WireMock.Net.RestClient/IWireMockAdminApi.cs index 65a62bb4..39c9ac86 100644 --- a/src/WireMock.Net.RestClient/IWireMockAdminApi.cs +++ b/src/WireMock.Net.RestClient/IWireMockAdminApi.cs @@ -7,6 +7,7 @@ using WireMock.Admin.Mappings; using WireMock.Admin.Requests; using WireMock.Admin.Scenarios; using WireMock.Admin.Settings; +using WireMock.Types; namespace WireMock.Client { @@ -52,6 +53,13 @@ namespace WireMock.Client [Get("mappings")] Task> GetMappingsAsync(); + /// + /// Get the C# code from all mappings + /// + /// C# code + [Get("mappings/code")] + Task GetMappingsCodeAsync([Query] MappingConverterType mappingConverterType = MappingConverterType.Server); + /// /// Add a new mapping. /// @@ -97,6 +105,15 @@ namespace WireMock.Client [Get("mappings/{guid}")] Task GetMappingAsync([Path] Guid guid); + /// + /// Get the C# code from a mapping based on the guid + /// + /// The Guid + /// The optional mappingConverterType (can be Server or Builder) + /// C# code + [Get("mappings/code/{guid}")] + Task GetMappingCodeAsync([Path] Guid guid, [Query] MappingConverterType mappingConverterType = MappingConverterType.Server); + /// /// Update a mapping based on the guid /// diff --git a/src/WireMock.Net/Constants/WireMockConstants.cs b/src/WireMock.Net/Constants/WireMockConstants.cs index 04294a67..2a03f6f9 100644 --- a/src/WireMock.Net/Constants/WireMockConstants.cs +++ b/src/WireMock.Net/Constants/WireMockConstants.cs @@ -7,4 +7,5 @@ internal static class WireMockConstants public const int ProxyPriority = -2_000_000; public const string ContentTypeJson = "application/json"; + public const string ContentTypeTextPlain = "text/plain"; } \ No newline at end of file diff --git a/src/WireMock.Net/IMappingBuilder.cs b/src/WireMock.Net/IMappingBuilder.cs index cea40033..50618690 100644 --- a/src/WireMock.Net/IMappingBuilder.cs +++ b/src/WireMock.Net/IMappingBuilder.cs @@ -1,6 +1,8 @@ +using System; using WireMock.Admin.Mappings; using WireMock.Matchers.Request; using WireMock.Server; +using WireMock.Types; namespace WireMock; @@ -40,4 +42,19 @@ public interface IMappingBuilder /// /// The folder to write the files to. void SaveMappingsToFolder(string folder); + + /// + /// Get the C# code for a mapping. + /// + /// The Mapping Guid. + /// The + /// C# code (null in case the mapping is not found) + string? ToCSharpCode(Guid guid, MappingConverterType converterType); + + /// + /// Get the C# code for all mappings. + /// + /// The + /// C# code + public string ToCSharpCode(MappingConverterType converterType); } \ No newline at end of file diff --git a/src/WireMock.Net/MappingBuilder.cs b/src/WireMock.Net/MappingBuilder.cs index 3fda6cea..66ad1d4b 100644 --- a/src/WireMock.Net/MappingBuilder.cs +++ b/src/WireMock.Net/MappingBuilder.cs @@ -1,4 +1,6 @@ +using System; using System.Linq; +using System.Text; using Newtonsoft.Json; using Stef.Validation; using WireMock.Admin.Mappings; @@ -7,6 +9,7 @@ using WireMock.Owin; using WireMock.Serialization; using WireMock.Server; using WireMock.Settings; +using WireMock.Types; using WireMock.Util; namespace WireMock; @@ -66,10 +69,12 @@ public class MappingBuilder : IMappingBuilder /// public MappingModel[] GetMappings() { - return _options.Mappings.Values.ToArray() - .Where(m => !m.IsAdminInterface) - .Select(_mappingConverter.ToMappingModel) - .ToArray(); + return GetMappingsInternal().Select(_mappingConverter.ToMappingModel).ToArray(); + } + + internal IMapping[] GetMappingsInternal() + { + return _options.Mappings.Values.ToArray().Where(m => !m.IsAdminInterface).ToArray(); } /// @@ -78,6 +83,37 @@ public class MappingBuilder : IMappingBuilder return ToJson(GetMappings()); } + /// + public string? ToCSharpCode(Guid guid, MappingConverterType converterType) + { + var mapping = GetMappingsInternal().FirstOrDefault(m => m.Guid == guid); + if (mapping is null) + { + return null; + } + + var settings = new MappingConverterSettings { AddStart = true, ConverterType = converterType }; + return _mappingConverter.ToCSharpCode(mapping, settings); + } + + /// + public string ToCSharpCode(MappingConverterType converterType) + { + var sb = new StringBuilder(); + bool addStart = true; + foreach (var mapping in GetMappingsInternal()) + { + sb.AppendLine(_mappingConverter.ToCSharpCode(mapping, new MappingConverterSettings { AddStart = addStart, ConverterType = converterType })); + + if (addStart) + { + addStart = false; + } + } + + return sb.ToString(); + } + /// public void SaveMappingsToFile(string path) { diff --git a/src/WireMock.Net/RequestMessage.cs b/src/WireMock.Net/RequestMessage.cs index 811ed239..1b0c368b 100644 --- a/src/WireMock.Net/RequestMessage.cs +++ b/src/WireMock.Net/RequestMessage.cs @@ -56,9 +56,12 @@ public class RequestMessage : IRequestMessage /// public IDictionary? Cookies { get; } - /// + /// public IDictionary>? Query { get; } + /// + public IDictionary>? QueryIgnoreCase { get; } + /// public string RawQuery { get; } @@ -171,6 +174,7 @@ public class RequestMessage : IRequestMessage Cookies = cookies; RawQuery = urlDetails.Url.Query; Query = QueryStringParser.Parse(RawQuery, options?.QueryParameterMultipleValueSupport); + QueryIgnoreCase = new Dictionary>(Query, StringComparer.OrdinalIgnoreCase); #if USE_ASPNETCORE ClientCertificate = clientCertificate; #endif diff --git a/src/WireMock.Net/Serialization/MappingConverter.cs b/src/WireMock.Net/Serialization/MappingConverter.cs index 013d3ebc..4bc1b4a8 100644 --- a/src/WireMock.Net/Serialization/MappingConverter.cs +++ b/src/WireMock.Net/Serialization/MappingConverter.cs @@ -33,7 +33,7 @@ internal class MappingConverter settings ??= new MappingConverterSettings(); var request = (Request)mapping.RequestMatcher; - var response = (Response)mapping.Provider; + var response = (Response) mapping.Provider; var clientIPMatcher = request.GetRequestMessageMatcher(); var pathMatcher = request.GetRequestMessageMatcher(); diff --git a/src/WireMock.Net/Server/RespondWithAProvider.cs b/src/WireMock.Net/Server/RespondWithAProvider.cs index 7363a7fc..ed9436b9 100644 --- a/src/WireMock.Net/Server/RespondWithAProvider.cs +++ b/src/WireMock.Net/Server/RespondWithAProvider.cs @@ -31,7 +31,7 @@ internal class RespondWithAProvider : IRespondWithAProvider private readonly IDateTimeUtils _dateTimeUtils; private readonly bool _saveToFile; - private bool _useWebhookFireAndForget; + private bool? _useWebhookFireAndForget; public Guid Guid { get; private set; } diff --git a/src/WireMock.Net/Server/WireMockServer.Admin.cs b/src/WireMock.Net/Server/WireMockServer.Admin.cs index 2190af56..04227f41 100644 --- a/src/WireMock.Net/Server/WireMockServer.Admin.cs +++ b/src/WireMock.Net/Server/WireMockServer.Admin.cs @@ -32,6 +32,7 @@ public partial class WireMockServer private const int EnhancedFileSystemWatcherTimeoutMs = 1000; private const string AdminFiles = "/__admin/files"; private const string AdminMappings = "/__admin/mappings"; + private const string AdminMappingsCode = "/__admin/mappings/code"; private const string AdminMappingsWireMockOrg = "/__admin/mappings/wiremock.org"; private const string AdminRequests = "/__admin/requests"; private const string AdminSettings = "/__admin/settings"; @@ -41,6 +42,7 @@ public partial class WireMockServer private static readonly Guid ProxyMappingGuid = new("e59914fd-782e-428e-91c1-4810ffb86567"); private static readonly RegexMatcher AdminRequestContentTypeJson = new ContentTypeMatcher(WireMockConstants.ContentTypeJson, true); private static readonly RegexMatcher AdminMappingsGuidPathMatcher = new(@"^\/__admin\/mappings\/([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$"); + private static readonly RegexMatcher AdminMappingsCodeGuidPathMatcher = new(@"^\/__admin\/mappings\/code\/([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$"); private static readonly RegexMatcher AdminRequestsGuidPathMatcher = new(@"^\/__admin\/requests\/([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$"); private static readonly RegexMatcher AdminScenariosNameMatcher = new(@"^\/__admin\/scenarios\/.+$"); private static readonly RegexMatcher AdminScenariosNameWithResetMatcher = new(@"^\/__admin\/scenarios\/.+\/reset$"); @@ -57,9 +59,14 @@ public partial class WireMockServer // __admin/mappings Given(Request.Create().WithPath(AdminMappings).UsingGet()).AtPriority(WireMockConstants.AdminPriority).RespondWith(new DynamicResponseProvider(MappingsGet)); Given(Request.Create().WithPath(AdminMappings).UsingPost().WithHeader(HttpKnownHeaderNames.ContentType, AdminRequestContentTypeJson)).AtPriority(WireMockConstants.AdminPriority).RespondWith(new DynamicResponseProvider(MappingsPost)); - Given(Request.Create().WithPath(AdminMappingsWireMockOrg).UsingPost().WithHeader(HttpKnownHeaderNames.ContentType, AdminRequestContentTypeJson)).AtPriority(WireMockConstants.AdminPriority).RespondWith(new DynamicResponseProvider(MappingsPostWireMockOrg)); Given(Request.Create().WithPath(AdminMappings).UsingDelete()).AtPriority(WireMockConstants.AdminPriority).RespondWith(new DynamicResponseProvider(MappingsDelete)); + // __admin/mappings/code + Given(Request.Create().WithPath(AdminMappingsCode).UsingGet()).AtPriority(WireMockConstants.AdminPriority).RespondWith(new DynamicResponseProvider(MappingsCodeGet)); + + // __admin/mappings/wiremock.org + Given(Request.Create().WithPath(AdminMappingsWireMockOrg).UsingPost().WithHeader(HttpKnownHeaderNames.ContentType, AdminRequestContentTypeJson)).AtPriority(WireMockConstants.AdminPriority).RespondWith(new DynamicResponseProvider(MappingsPostWireMockOrg)); + // __admin/mappings/reset Given(Request.Create().WithPath(AdminMappings + "/reset").UsingPost()).AtPriority(WireMockConstants.AdminPriority).RespondWith(new DynamicResponseProvider(MappingsReset)); @@ -68,6 +75,9 @@ public partial class WireMockServer Given(Request.Create().WithPath(AdminMappingsGuidPathMatcher).UsingPut().WithHeader(HttpKnownHeaderNames.ContentType, AdminRequestContentTypeJson)).AtPriority(WireMockConstants.AdminPriority).RespondWith(new DynamicResponseProvider(MappingPut)); Given(Request.Create().WithPath(AdminMappingsGuidPathMatcher).UsingDelete()).AtPriority(WireMockConstants.AdminPriority).RespondWith(new DynamicResponseProvider(MappingDelete)); + // __admin/mappings/code/{guid} + Given(Request.Create().WithPath(AdminMappingsCodeGuidPathMatcher).UsingGet()).AtPriority(WireMockConstants.AdminPriority).RespondWith(new DynamicResponseProvider(MappingCodeGet)); + // __admin/mappings/save Given(Request.Create().WithPath($"{AdminMappings}/save").UsingPost()).AtPriority(WireMockConstants.AdminPriority).RespondWith(new DynamicResponseProvider(MappingsSave)); @@ -286,13 +296,11 @@ public partial class WireMockServer #region Mapping/{guid} private IResponseMessage MappingGet(IRequestMessage requestMessage) { - Guid guid = ParseGuidFromRequestMessage(requestMessage); - var mapping = Mappings.FirstOrDefault(m => !m.IsAdminInterface && m.Guid == guid); - + var mapping = FindMappingByGuid(requestMessage); if (mapping == null) { _settings.Logger.Warn("HttpStatusCode set to 404 : Mapping not found"); - return ResponseMessageBuilder.Create("Mapping not found", 404); + return ResponseMessageBuilder.Create("Mapping not found", HttpStatusCode.NotFound); } var model = _mappingConverter.ToMappingModel(mapping); @@ -300,31 +308,71 @@ public partial class WireMockServer return ToJson(model); } + private IResponseMessage MappingCodeGet(IRequestMessage requestMessage) + { + if (TryParseGuidFromRequestMessage(requestMessage, out var guid)) + { + var code = _mappingBuilder.ToCSharpCode(guid, GetMappingConverterType(requestMessage)); + if (code is null) + { + _settings.Logger.Warn("HttpStatusCode set to 404 : Mapping not found"); + return ResponseMessageBuilder.Create("Mapping not found", HttpStatusCode.NotFound); + } + + return ToResponseMessage(code); + } + + _settings.Logger.Warn("HttpStatusCode set to 400"); + return ResponseMessageBuilder.Create("GUID is missing", HttpStatusCode.BadRequest); + } + + private static MappingConverterType GetMappingConverterType(IRequestMessage requestMessage) + { + var mappingConverterType = MappingConverterType.Server; + + if (requestMessage.QueryIgnoreCase?.TryGetValue(nameof(MappingConverterType), out var values) == true && + Enum.TryParse(values.FirstOrDefault(), true, out MappingConverterType parsed)) + { + mappingConverterType = parsed; + } + + return mappingConverterType; + } + + private IMapping? FindMappingByGuid(IRequestMessage requestMessage) + { + return TryParseGuidFromRequestMessage(requestMessage, out var guid) ? Mappings.FirstOrDefault(m => !m.IsAdminInterface && m.Guid == guid) : null; + } + private IResponseMessage MappingPut(IRequestMessage requestMessage) { - Guid guid = ParseGuidFromRequestMessage(requestMessage); + if (TryParseGuidFromRequestMessage(requestMessage, out var guid)) + { + var mappingModel = DeserializeObject(requestMessage); + var guidFromPut = ConvertMappingAndRegisterAsRespondProvider(mappingModel, guid); - var mappingModel = DeserializeObject(requestMessage); - Guid? guidFromPut = ConvertMappingAndRegisterAsRespondProvider(mappingModel, guid); + return ResponseMessageBuilder.Create("Mapping added or updated", HttpStatusCode.OK, guidFromPut); + } - return ResponseMessageBuilder.Create("Mapping added or updated", HttpStatusCode.OK, guidFromPut); + _settings.Logger.Warn("HttpStatusCode set to 404 : Mapping not found"); + return ResponseMessageBuilder.Create("Mapping not found", HttpStatusCode.NotFound); } private IResponseMessage MappingDelete(IRequestMessage requestMessage) { - Guid guid = ParseGuidFromRequestMessage(requestMessage); - - if (DeleteMapping(guid)) + if (TryParseGuidFromRequestMessage(requestMessage, out var guid) && DeleteMapping(guid)) { return ResponseMessageBuilder.Create("Mapping removed", HttpStatusCode.OK, guid); } + _settings.Logger.Warn("HttpStatusCode set to 404 : Mapping not found"); return ResponseMessageBuilder.Create("Mapping not found", HttpStatusCode.NotFound); } - private static Guid ParseGuidFromRequestMessage(IRequestMessage requestMessage) + private static bool TryParseGuidFromRequestMessage(IRequestMessage requestMessage, out Guid guid) { - return Guid.Parse(requestMessage.Path.Substring(AdminMappings.Length + 1)); + var lastPart = requestMessage.Path.Split('/').LastOrDefault(); + return Guid.TryParse(lastPart, out guid); } #endregion Mapping/{guid} @@ -360,6 +408,15 @@ public partial class WireMockServer return ToJson(ToMappingModels()); } + private IResponseMessage MappingsCodeGet(IRequestMessage requestMessage) + { + var converterType = GetMappingConverterType(requestMessage); + + var code = _mappingBuilder.ToCSharpCode(converterType); + + return ToResponseMessage(code); + } + private IResponseMessage MappingsPost(IRequestMessage requestMessage) { try @@ -464,30 +521,29 @@ public partial class WireMockServer #region Request/{guid} private IResponseMessage RequestGet(IRequestMessage requestMessage) { - Guid guid = ParseGuidFromRequestMessage(requestMessage); - var entry = LogEntries.FirstOrDefault(r => !r.RequestMessage.Path.StartsWith("/__admin/") && r.Guid == guid); - - if (entry == null) + if (TryParseGuidFromRequestMessage(requestMessage, out var guid)) { - _settings.Logger.Warn("HttpStatusCode set to 404 : Request not found"); - return ResponseMessageBuilder.Create("Request not found", 404); + var entry = LogEntries.FirstOrDefault(r => !r.RequestMessage.Path.StartsWith("/__admin/") && r.Guid == guid); + if (entry is { }) + { + var model = new LogEntryMapper(_options).Map(entry); + return ToJson(model); + } } - var model = new LogEntryMapper(_options).Map(entry); - - return ToJson(model); + _settings.Logger.Warn("HttpStatusCode set to 404 : Request not found"); + return ResponseMessageBuilder.Create("Request not found", HttpStatusCode.NotFound); } private IResponseMessage RequestDelete(IRequestMessage requestMessage) { - Guid guid = ParseGuidFromRequestMessage(requestMessage); - - if (DeleteLogEntry(guid)) + if (TryParseGuidFromRequestMessage(requestMessage, out var guid) && DeleteLogEntry(guid)) { return ResponseMessageBuilder.Create("Request removed"); } - return ResponseMessageBuilder.Create("Request not found", 404); + _settings.Logger.Warn("HttpStatusCode set to 404 : Request not found"); + return ResponseMessageBuilder.Create("Request not found", HttpStatusCode.NotFound); } #endregion Request/{guid} @@ -564,7 +620,7 @@ public partial class WireMockServer return ResetScenario(name) ? ResponseMessageBuilder.Create("Scenario reset") : - ResponseMessageBuilder.Create($"No scenario found by name '{name}'.", 404); + ResponseMessageBuilder.Create($"No scenario found by name '{name}'.", HttpStatusCode.NotFound); } #endregion @@ -687,6 +743,20 @@ public partial class WireMockServer }; } + private static ResponseMessage ToResponseMessage(string text) + { + return new ResponseMessage + { + BodyData = new BodyData + { + DetectedBodyType = BodyType.String, + BodyAsString = text + }, + StatusCode = (int)HttpStatusCode.OK, + Headers = new Dictionary> { { HttpKnownHeaderNames.ContentType, new WireMockList(WireMockConstants.ContentTypeTextPlain) } } + }; + } + private static T DeserializeObject(IRequestMessage requestMessage) where T : new() { return requestMessage.BodyData?.DetectedBodyType switch diff --git a/src/WireMock.Net/Server/WireMockServer.cs b/src/WireMock.Net/Server/WireMockServer.cs index e22d636d..5e97ac5b 100644 --- a/src/WireMock.Net/Server/WireMockServer.cs +++ b/src/WireMock.Net/Server/WireMockServer.cs @@ -540,6 +540,20 @@ public partial class WireMockServer : IWireMockServer return _mappingBuilder.Given(requestMatcher, saveToFile); } + /// + [PublicAPI] + public string? MappingToCSharpCode(Guid guid, MappingConverterType converterType) + { + return _mappingBuilder.ToCSharpCode(guid, converterType); + } + + /// + [PublicAPI] + public string MappingsToCSharpCode(MappingConverterType converterType) + { + return _mappingBuilder.ToCSharpCode(converterType); + } + private void InitSettings(WireMockServerSettings settings) { if (settings.AllowBodyForAllHttpMethods == true) diff --git a/test/WireMock.Net.Tests/.filenesting.json b/test/WireMock.Net.Tests/.filenesting.json.old similarity index 100% rename from test/WireMock.Net.Tests/.filenesting.json rename to test/WireMock.Net.Tests/.filenesting.json.old diff --git a/test/WireMock.Net.Tests/MappingBuilderTests.GetMappings.verified.txt b/test/WireMock.Net.Tests/MappingBuilderTests.GetMappings.verified.txt index 907f69af..5efb791a 100644 --- a/test/WireMock.Net.Tests/MappingBuilderTests.GetMappings.verified.txt +++ b/test/WireMock.Net.Tests/MappingBuilderTests.GetMappings.verified.txt @@ -1,6 +1,6 @@ [ { - Guid: 41372914-1838-4c67-916b-b9aacdd096ce, + Guid: Guid_1, UpdatedAt: 2023-01-14 15:16:17, Request: { Path: { @@ -19,7 +19,6 @@ Response: { BodyDestination: SameAsSource, Body: { msg: "Hello world!"} - }, - UseWebhooksFireAndForget: false + } } ] \ No newline at end of file diff --git a/test/WireMock.Net.Tests/MappingBuilderTests.ToJson.verified.txt b/test/WireMock.Net.Tests/MappingBuilderTests.ToJson.verified.txt index 7aaed7c0..d1754173 100644 --- a/test/WireMock.Net.Tests/MappingBuilderTests.ToJson.verified.txt +++ b/test/WireMock.Net.Tests/MappingBuilderTests.ToJson.verified.txt @@ -1,6 +1,6 @@ [ { - Guid: 41372914-1838-4c67-916b-b9aacdd096ce, + Guid: Guid_1, UpdatedAt: 2023-01-14T15:16:17, Request: { Path: { @@ -19,7 +19,6 @@ Response: { BodyDestination: SameAsSource, Body: { msg: "Hello world!"} - }, - UseWebhooksFireAndForget: false + } } ] \ No newline at end of file diff --git a/test/WireMock.Net.Tests/MappingBuilderTests.cs b/test/WireMock.Net.Tests/MappingBuilderTests.cs index 67aa4c20..c0bf92a3 100644 --- a/test/WireMock.Net.Tests/MappingBuilderTests.cs +++ b/test/WireMock.Net.Tests/MappingBuilderTests.cs @@ -1,12 +1,12 @@ #if !(NET452 || NET461 || NETCOREAPP3_1) using System; -using System.Runtime.CompilerServices; using System.Threading.Tasks; using Moq; using VerifyTests; using VerifyXunit; using WireMock.Handlers; using WireMock.Logging; +using WireMock.Net.Tests.VerifyExtensions; using WireMock.Owin; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; @@ -20,6 +20,12 @@ namespace WireMock.Net.Tests; [UsesVerify] public class MappingBuilderTests { + private static readonly VerifySettings VerifySettings = new(); + static MappingBuilderTests() + { + VerifySettings.Init(); + } + private static readonly Guid NewGuid = new("98fae52e-76df-47d9-876f-2ee32e931d9b"); private const string MappingGuid = "41372914-1838-4c67-916b-b9aacdd096ce"; private static readonly DateTime UtcNow = new(2023, 1, 14, 15, 16, 17); @@ -67,13 +73,6 @@ public class MappingBuilderTests ); } - [ModuleInitializer] - public static void ModuleInitializer() - { - VerifierSettings.DontScrubGuids(); - VerifierSettings.DontScrubDateTimes(); - } - [Fact] public Task GetMappings() { @@ -81,7 +80,7 @@ public class MappingBuilderTests var mappings = _sut.GetMappings(); // Verify - return Verifier.Verify(mappings); + return Verifier.Verify(mappings, VerifySettings); } [Fact] @@ -91,7 +90,7 @@ public class MappingBuilderTests var json = _sut.ToJson(); // Verify - return Verifier.VerifyJson(json); + return Verifier.VerifyJson(json, VerifySettings); } [Fact] diff --git a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_BodyTypeBytes.verified.txt b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_BodyTypeBytes.verified.txt similarity index 100% rename from test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_BodyTypeBytes.verified.txt rename to test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_BodyTypeBytes.verified.txt diff --git a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_ResponseBodyTypeFile.verified.txt b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_ResponseBodyTypeFile.verified.txt similarity index 100% rename from test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_ResponseBodyTypeFile.verified.txt rename to test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_Check_ResponseBodyTypeFile.verified.txt diff --git a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WhenFuncIsUsed_And_DoNotSaveDynamicResponseInLogEntry_Is_True_Should_NotSave_StringResponse.verified.txt b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WhenFuncIsUsed_And_DoNotSaveDynamicResponseInLogEntry_Is_True_Should_NotSave_StringResponse.verified.txt similarity index 100% rename from test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WhenFuncIsUsed_And_DoNotSaveDynamicResponseInLogEntry_Is_True_Should_NotSave_StringResponse.verified.txt rename to test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WhenFuncIsUsed_And_DoNotSaveDynamicResponseInLogEntry_Is_True_Should_NotSave_StringResponse.verified.txt diff --git a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WithFault.verified.txt b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WithFault.verified.txt similarity index 100% rename from test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.Verify/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WithFault.verified.txt rename to test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.LogEntryMapper_Map_LogEntry_WithFault.verified.txt diff --git a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.cs b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.cs index b083fb12..8b98903b 100644 --- a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.cs +++ b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.cs @@ -20,7 +20,7 @@ public class LogEntryMapperTests private static readonly VerifySettings VerifySettings = new(); static LogEntryMapperTests() { - VerifySettings.Init(); + VerifySettings.Init(); } private readonly IWireMockMiddlewareOptions _options = new WireMockMiddlewareOptions(); diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode.cs b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode.cs index 0966c926..361c56b7 100644 --- a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode.cs +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToCSharpCode.cs @@ -1,10 +1,10 @@ #if !(NET452 || NET461 || NETCOREAPP3_1) using System; -using System.Runtime.CompilerServices; using System.Threading.Tasks; using FluentAssertions; using VerifyTests; using VerifyXunit; +using WireMock.Net.Tests.VerifyExtensions; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; using WireMock.Serialization; @@ -16,12 +16,10 @@ namespace WireMock.Net.Tests.Serialization; [UsesVerify] public partial class MappingConverterTests { - - [ModuleInitializer] - public static void ModuleInitializer() + private static readonly VerifySettings VerifySettings = new(); + static MappingConverterTests() { - VerifierSettings.DontScrubGuids(); - VerifierSettings.DontScrubDateTimes(); + VerifySettings.Init(); } [Fact] @@ -41,7 +39,7 @@ public partial class MappingConverterTests code.Should().NotBeEmpty(); // Verify - return Verifier.Verify(code); + return Verifier.Verify(code, VerifySettings); } [Fact] @@ -61,7 +59,7 @@ public partial class MappingConverterTests code.Should().NotBeEmpty(); // Verify - return Verifier.Verify(code); + return Verifier.Verify(code, VerifySettings); } [Fact] @@ -81,7 +79,7 @@ public partial class MappingConverterTests code.Should().NotBeEmpty(); // Verify - return Verifier.Verify(code); + return Verifier.Verify(code, VerifySettings); } [Fact] @@ -101,7 +99,7 @@ public partial class MappingConverterTests code.Should().NotBeEmpty(); // Verify - return Verifier.Verify(code); + return Verifier.Verify(code, VerifySettings); } private Mapping CreateMapping() diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel.verified.txt index fe4b89ea..5f282702 100644 --- a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel.verified.txt +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel.verified.txt @@ -1,12 +1 @@ -{ - Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, - UpdatedAt: 2022-12-04 11:12:13, - Title: , - Description: , - Priority: 42, - Request: {}, - Response: { - Delay: 1000 - }, - UseWebhooksFireAndForget: false -} \ No newline at end of file + \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithDelayAsMilliSeconds_ReturnsCorrectModel.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithDelayAsMilliSeconds_ReturnsCorrectModel.verified.txt new file mode 100644 index 00000000..7b68b627 --- /dev/null +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithDelayAsMilliSeconds_ReturnsCorrectModel.verified.txt @@ -0,0 +1,12 @@ +{ + Guid: Guid_1, + UpdatedAt: DateTime_1, + Title: , + Description: , + Priority: 42, + Request: {}, + Response: { + Delay: 1000 + }, + UseWebhooksFireAndForget: false +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithPriority_ReturnsPriority.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithPriority_ReturnsPriority.verified.txt index 0a6b8bac..8c23c1f9 100644 --- a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithPriority_ReturnsPriority.verified.txt +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithPriority_ReturnsPriority.verified.txt @@ -1,6 +1,6 @@ { - Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, - UpdatedAt: 2022-12-04 11:12:13, + Guid: Guid_1, + UpdatedAt: DateTime_1, Title: , Description: , Priority: 42, diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomDelay_ReturnsCorrectModel.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomDelay_ReturnsCorrectModel.verified.txt index 8c26e558..03a336f1 100644 --- a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomDelay_ReturnsCorrectModel.verified.txt +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomDelay_ReturnsCorrectModel.verified.txt @@ -1,6 +1,6 @@ { - Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, - UpdatedAt: 2022-12-04 11:12:13, + Guid: Guid_1, + UpdatedAt: DateTime_1, Title: , Description: , Priority: 42, diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel.verified.txt index 4d78b3cc..b94d7558 100644 --- a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel.verified.txt +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithRandomMinimumDelay_ReturnsCorrectModel.verified.txt @@ -1,6 +1,6 @@ -{ - Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, - UpdatedAt: 2022-12-04 11:12:13, +{ + Guid: Guid_1, + UpdatedAt: DateTime_1, Title: , Description: , Priority: 42, diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings.verified.txt index cec4691f..98e43889 100644 --- a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings.verified.txt +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTimeSettings_ReturnsCorrectTimeSettings.verified.txt @@ -1,5 +1,5 @@ { - Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, + Guid: Guid_1, UpdatedAt: 2022-12-04 11:12:13, TimeSettings: { Start: 2023-01-14 15:16:17, diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel.verified.txt index 08cd7116..98d103a2 100644 --- a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel.verified.txt +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_WithTitle_And_Description_ReturnsCorrectModel.verified.txt @@ -1,6 +1,6 @@ { - Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, - UpdatedAt: 2022-12-04 11:12:13, + Guid: Guid_1, + UpdatedAt: DateTime_1, Title: my-title, Description: my-description, Request: {}, diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_MultipleWebHooks.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_MultipleWebHooks.verified.txt index a7b1ca9f..3cc32d7e 100644 --- a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_MultipleWebHooks.verified.txt +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_MultipleWebHooks.verified.txt @@ -1,6 +1,6 @@ { - Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, - UpdatedAt: 2022-12-04 11:12:13, + Guid: Guid_1, + UpdatedAt: DateTime_1, Title: , Description: , Request: {}, diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_SingleWebHook.verified.txt b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_SingleWebHook.verified.txt index d721319a..d81e52b7 100644 --- a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_SingleWebHook.verified.txt +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.ToMappingModel_With_SingleWebHook.verified.txt @@ -1,6 +1,6 @@ { - Guid: c8eeaf99-d5c4-4341-8543-4597c3fd40d9, - UpdatedAt: 2022-12-04 11:12:13, + Guid: Guid_1, + UpdatedAt: DateTime_1, Title: , Description: , Request: {}, diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.cs b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.cs index 2c077eb8..4c1561db 100644 --- a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.cs +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.cs @@ -1,11 +1,9 @@ #if !(NET452 || NET461 || NETCOREAPP3_1) using System; using System.Collections.Generic; -using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using FluentAssertions; -using VerifyTests; using VerifyXunit; using WireMock.Models; using WireMock.RequestBuilders; @@ -232,7 +230,7 @@ public partial class MappingConverterTests model.TimeSettings.TTL.Should().Be(ttl); // Verify - return Verifier.Verify(model); + return Verifier.Verify(model, VerifySettings); } [Fact] @@ -262,7 +260,7 @@ public partial class MappingConverterTests } [Fact] - public Task ToMappingModel_WithDelayAsMilleSeconds_ReturnsCorrectModel() + public Task ToMappingModel_WithDelayAsMilliSeconds_ReturnsCorrectModel() { // Assign var delay = 1000; diff --git a/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.ToMapping_UseDefinedRequestMatchers_True.verified.txt b/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.ToMapping_UseDefinedRequestMatchers_True.verified.txt index eacb131b..1e023f54 100644 --- a/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.ToMapping_UseDefinedRequestMatchers_True.verified.txt +++ b/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.ToMapping_UseDefinedRequestMatchers_True.verified.txt @@ -1,5 +1,5 @@ -{ - Guid: ff55ac0a-fea9-4d7b-be74-5e483a2c1305, +{ + Guid: Guid_1, UpdatedAt: 2022-12-04, Title: my title, Description: my description, diff --git a/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.cs b/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.cs index 58dcb1b9..58861f70 100644 --- a/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.cs +++ b/test/WireMock.Net.Tests/Serialization/ProxyMappingConverterTests.cs @@ -1,11 +1,11 @@ #if !(NET452 || NET461 || NETCOREAPP3_1) using System; -using System.Runtime.CompilerServices; using System.Threading.Tasks; using Moq; using VerifyTests; using VerifyXunit; using WireMock.Matchers; +using WireMock.Net.Tests.VerifyExtensions; using WireMock.RequestBuilders; using WireMock.Serialization; using WireMock.Settings; @@ -17,6 +17,12 @@ namespace WireMock.Net.Tests.Serialization; [UsesVerify] public class ProxyMappingConverterTests { + private static readonly VerifySettings VerifySettings = new(); + static ProxyMappingConverterTests() + { + VerifySettings.Init(); + } + private readonly WireMockServerSettings _settings = new(); private readonly MappingConverter _mappingConverter; @@ -36,13 +42,6 @@ public class ProxyMappingConverterTests _sut = new ProxyMappingConverter(_settings, guidUtilsMock.Object, dateTimeUtilsMock.Object); } - [ModuleInitializer] - public static void ModuleInitializer() - { - VerifierSettings.DontScrubGuids(); - VerifierSettings.DontScrubDateTimes(); - } - [Fact] public Task ToMapping_UseDefinedRequestMatchers_True() { @@ -77,7 +76,7 @@ public class ProxyMappingConverterTests var model = _mappingConverter.ToMappingModel(proxyMapping); // Verify - return Verifier.Verify(model); + return Verifier.Verify(model, VerifySettings); } } #endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.cs b/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.cs index 26cd8d52..a6a9c0fb 100644 --- a/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.cs +++ b/test/WireMock.Net.Tests/Serialization/WebhookMapperTests.cs @@ -1,11 +1,11 @@ #if !(NET452 || NET461 || NETCOREAPP3_1) using System.Collections.Generic; -using System.Runtime.CompilerServices; using System.Threading.Tasks; using VerifyTests; using VerifyXunit; using WireMock.Admin.Mappings; using WireMock.Models; +using WireMock.Net.Tests.VerifyExtensions; using WireMock.Serialization; using WireMock.Types; using WireMock.Util; @@ -16,11 +16,10 @@ namespace WireMock.Net.Tests.Serialization; [UsesVerify] public class WebhookMapperTests { - [ModuleInitializer] - public static void ModuleInitializer() + private static readonly VerifySettings VerifySettings = new(); + static WebhookMapperTests() { - VerifierSettings.DontScrubGuids(); - VerifierSettings.DontScrubDateTimes(); + VerifySettings.Init(); } [Fact] @@ -45,7 +44,7 @@ public class WebhookMapperTests var result = WebhookMapper.Map(model); // Verify - return Verifier.Verify(result); + return Verifier.Verify(result, VerifySettings); } [Fact] @@ -70,7 +69,7 @@ public class WebhookMapperTests var result = WebhookMapper.Map(model); // Verify - return Verifier.Verify(result); + return Verifier.Verify(result, VerifySettings); } [Fact] @@ -97,7 +96,7 @@ public class WebhookMapperTests var result = WebhookMapper.Map(model); // Verify - return Verifier.Verify(result); + return Verifier.Verify(result, VerifySettings); } [Fact] @@ -129,7 +128,7 @@ public class WebhookMapperTests var result = WebhookMapper.Map(webhook); // Verify - return Verifier.Verify(result); + return Verifier.Verify(result, VerifySettings); } } #endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/VerifyExtensions/VerifyNewtonsoftJson.cs b/test/WireMock.Net.Tests/VerifyExtensions/VerifyNewtonsoftJson.cs new file mode 100644 index 00000000..eef5ab9f --- /dev/null +++ b/test/WireMock.Net.Tests/VerifyExtensions/VerifyNewtonsoftJson.cs @@ -0,0 +1,42 @@ +#if !(NET452 || NET461) +using System.Collections.Generic; +using System.Collections.Specialized; +using Newtonsoft.Json.Linq; +using VerifyTests; + +namespace WireMock.Net.Tests.VerifyExtensions; + +internal static class VerifyNewtonsoftJson +{ + public static void Enable(VerifySettings verifySettings) + { + // InnerVerifier.ThrowIfVerifyHasBeenRun(); + + verifySettings + .AddExtraSettings(_ => + { + var converters = _.Converters; + converters.Add(new JArrayConverter()); + converters.Add(new JObjectConverter()); + }); + } +} + +internal class JArrayConverter : WriteOnlyJsonConverter +{ + public override void Write(VerifyJsonWriter writer, JArray value) + { + var list = value.ToObject>()!; + writer.Serialize(list); + } +} + +internal class JObjectConverter : WriteOnlyJsonConverter +{ + public override void Write(VerifyJsonWriter writer, JObject value) + { + var dictionary = value.ToObject()!; + writer.Serialize(dictionary); + } +} +#endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/VerifyExtensions/VerifySettingsExtensions.cs b/test/WireMock.Net.Tests/VerifyExtensions/VerifySettingsExtensions.cs index 51e0fbad..3be311c6 100644 --- a/test/WireMock.Net.Tests/VerifyExtensions/VerifySettingsExtensions.cs +++ b/test/WireMock.Net.Tests/VerifyExtensions/VerifySettingsExtensions.cs @@ -5,11 +5,13 @@ namespace WireMock.Net.Tests.VerifyExtensions; internal static class VerifySettingsExtensions { - public static void Init(this VerifySettings verifySettings) + public static void Init(this VerifySettings verifySettings) { verifySettings.DontScrubDateTimes(); verifySettings.DontScrubDateTimes(); - verifySettings.UseDirectory($"{typeof(T).Name}.Verify"); + // verifySettings.UseDirectory($"{typeof(T).Name}.Verify"); + + VerifyNewtonsoftJson.Enable(verifySettings); } } #endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj b/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj index ad560bd3..f1ac2262 100644 --- a/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj +++ b/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj @@ -61,7 +61,7 @@ - + diff --git a/test/WireMock.Net.Tests/WireMockAdminApiTests.IWireMockAdminApi_GetMappingAsync_WithBodyModelMatcherModel_WithoutMethods_ShouldReturnCorrectMappingModel.verified.txt b/test/WireMock.Net.Tests/WireMockAdminApiTests.IWireMockAdminApi_GetMappingAsync_WithBodyModelMatcherModel_WithoutMethods_ShouldReturnCorrectMappingModel.verified.txt new file mode 100644 index 00000000..8dbeadf1 --- /dev/null +++ b/test/WireMock.Net.Tests/WireMockAdminApiTests.IWireMockAdminApi_GetMappingAsync_WithBodyModelMatcherModel_WithoutMethods_ShouldReturnCorrectMappingModel.verified.txt @@ -0,0 +1,26 @@ +{ + Guid: 90356dba-b36c-469a-a17e-669cd84f1f05, + UpdatedAt: DateTime_1, + Request: { + Path: { + Matchers: [ + { + Name: WildcardMatcher, + Pattern: /1, + IgnoreCase: false + } + ] + }, + Body: { + Matcher: { + Name: RegexMatcher, + Pattern: hello, + IgnoreCase: true + } + } + }, + Response: { + Body: world + }, + UseWebhooksFireAndForget: false +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/WireMockAdminApiTests.IWireMockAdminApi_GetMappingByGuidAsync.verified.txt b/test/WireMock.Net.Tests/WireMockAdminApiTests.IWireMockAdminApi_GetMappingByGuidAsync.verified.txt new file mode 100644 index 00000000..bec7ec6d --- /dev/null +++ b/test/WireMock.Net.Tests/WireMockAdminApiTests.IWireMockAdminApi_GetMappingByGuidAsync.verified.txt @@ -0,0 +1,35 @@ +{ + Guid: 90356dba-b36c-469a-a17e-669cd84f1f05, + UpdatedAt: DateTime_1, + Request: { + Path: { + Matchers: [ + { + Name: WildcardMatcher, + Pattern: /foo1, + IgnoreCase: false + } + ] + }, + Methods: [ + GET + ], + Params: [ + { + Name: p1, + Matchers: [ + { + Name: ExactMatcher, + Pattern: xyz, + IgnoreCase: false + } + ] + } + ] + }, + Response: { + StatusCode: 200, + BodyDestination: SameAsSource, + Body: 1 + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/WireMockAdminApiTests.IWireMockAdminApi_GetMappingCodeByGuidAsync.verified.txt b/test/WireMock.Net.Tests/WireMockAdminApiTests.IWireMockAdminApi_GetMappingCodeByGuidAsync.verified.txt new file mode 100644 index 00000000..8218840f --- /dev/null +++ b/test/WireMock.Net.Tests/WireMockAdminApiTests.IWireMockAdminApi_GetMappingCodeByGuidAsync.verified.txt @@ -0,0 +1,11 @@ +var server = WireMockServer.Start(); +server + .Given(Request.Create() + .UsingMethod("GET") + .WithPath("/foo1") + .WithParam("p1", "xyz") + ) + .WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05") + .RespondWith(Response.Create() + .WithBody("1") + ); diff --git a/test/WireMock.Net.Tests/WireMockAdminApiTests.IWireMockAdminApi_GetMappingsCode.verified.txt b/test/WireMock.Net.Tests/WireMockAdminApiTests.IWireMockAdminApi_GetMappingsCode.verified.txt new file mode 100644 index 00000000..af1acc88 --- /dev/null +++ b/test/WireMock.Net.Tests/WireMockAdminApiTests.IWireMockAdminApi_GetMappingsCode.verified.txt @@ -0,0 +1,24 @@ +var server = WireMockServer.Start(); +server + .Given(Request.Create() + .UsingMethod("GET") + .WithPath("/foo1") + .WithParam("p1", "xyz") + ) + .WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05") + .RespondWith(Response.Create() + .WithBody("1") + ); + +server + .Given(Request.Create() + .UsingMethod("GET") + .WithPath("/foo2") + .WithParam("p2", "abc") + ) + .WithGuid("1b731398-4a5b-457f-a6e3-d65e541c428f") + .RespondWith(Response.Create() + .WithHeader("hk)", "hv") + .WithBody("2") + ); + diff --git a/test/WireMock.Net.Tests/WireMockAdminApiTests.cs b/test/WireMock.Net.Tests/WireMockAdminApiTests.cs index d3b4ff1c..55a60812 100644 --- a/test/WireMock.Net.Tests/WireMockAdminApiTests.cs +++ b/test/WireMock.Net.Tests/WireMockAdminApiTests.cs @@ -1,4 +1,4 @@ -#if !NET452 && !NET461 +#if !(NET452 || NET461 || NETCOREAPP3_1) using System; using System.Linq; using System.Net.Http; @@ -9,20 +9,32 @@ using FluentAssertions; using Moq; using NFluent; using RestEase; +using VerifyTests; +using VerifyXunit; using WireMock.Admin.Mappings; using WireMock.Admin.Settings; using WireMock.Client; using WireMock.Handlers; using WireMock.Logging; using WireMock.Models; +using WireMock.Net.Tests.VerifyExtensions; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; using WireMock.Server; using WireMock.Settings; using Xunit; namespace WireMock.Net.Tests; +[UsesVerify] public class WireMockAdminApiTests { + private static readonly VerifySettings VerifySettings = new(); + static WireMockAdminApiTests() + { + VerifyNewtonsoftJson.Enable(VerifySettings); + } + [Fact] public async Task IWireMockAdminApi_GetSettingsAsync() { @@ -298,9 +310,9 @@ public class WireMockAdminApiTests public async Task IWireMockAdminApi_GetMappingAsync_WithBodyModelMatcherModel_WithoutMethods_ShouldReturnCorrectMappingModel() { // Arrange - var guid = Guid.NewGuid(); + var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05"); var server = WireMockServer.StartWithAdminInterface(); - var api = RestClient.For(server.Urls[0]); + var api = RestClient.For(server.Url); // Act var model = new MappingModel @@ -330,9 +342,8 @@ public class WireMockAdminApiTests mapping.Should().NotBeNull(); var getMappingResult = await api.GetMappingAsync(guid).ConfigureAwait(false); - getMappingResult.Should().NotBeNull(); - getMappingResult.Request.Body.Should().BeEquivalentTo(model.Request.Body); + await Verifier.Verify(getMappingResult, VerifySettings).DontScrubGuids(); server.Stop(); } @@ -629,5 +640,125 @@ public class WireMockAdminApiTests var status = await api.ResetScenarioAsync(name).ConfigureAwait(false); status.Status.Should().Be("No scenario found by name 'x'."); } + + [Fact] + public async Task IWireMockAdminApi_GetMappingByGuidAsync() + { + // Arrange + var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05"); + var server = WireMockServer.StartWithAdminInterface(); + + server + .Given( + Request.Create() + .WithPath("/foo1") + .WithParam("p1", "xyz") + .UsingGet() + ) + .WithGuid(guid) + .RespondWith( + Response.Create() + .WithStatusCode(200) + .WithBody("1") + ); + + // Act + var api = RestClient.For(server.Url); + var getMappingResult = await api.GetMappingAsync(guid).ConfigureAwait(false); + + // Assert + var mapping = server.Mappings.FirstOrDefault(m => m.Guid == guid); + mapping.Should().NotBeNull(); + + await Verifier.Verify(getMappingResult, VerifySettings).DontScrubGuids(); + + server.Stop(); + } + + [Fact] + public async Task IWireMockAdminApi_GetMappingCodeByGuidAsync() + { + // Arrange + var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05"); + var server = WireMockServer.StartWithAdminInterface(); + + server + .Given( + Request.Create() + .WithPath("/foo1") + .WithParam("p1", "xyz") + .UsingGet() + ) + .WithGuid(guid) + .RespondWith( + Response.Create() + .WithStatusCode(200) + .WithBody("1") + ); + + // Act + var api = RestClient.For(server.Url); + + var mappings = await api.GetMappingsAsync().ConfigureAwait(false); + mappings.Should().HaveCount(1); + + var code = await api.GetMappingCodeAsync(guid).ConfigureAwait(false); + + // Assert + await Verifier.Verify(code).DontScrubDateTimes().DontScrubGuids(); + + server.Stop(); + } + + [Fact] + public async Task IWireMockAdminApi_GetMappingsCode() + { + // Arrange + var guid1 = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05"); + var guid2 = Guid.Parse("1b731398-4a5b-457f-a6e3-d65e541c428f"); + var server = WireMockServer.StartWithAdminInterface(); + + server + .Given( + Request.Create() + .WithPath("/foo1") + .WithParam("p1", "xyz") + .UsingGet() + ) + .WithGuid(guid1) + .RespondWith( + Response.Create() + .WithStatusCode(200) + .WithBody("1") + ); + + server + .Given( + Request.Create() + .WithPath("/foo2") + .WithParam("p2", "abc") + .UsingGet() + ) + .WithGuid(guid2) + .RespondWith( + Response.Create() + .WithStatusCode(201) + .WithHeader("hk", "hv") + .WithBody("2") + ); + + // Act + var api = RestClient.For(server.Url); + + var mappings = await api.GetMappingsAsync().ConfigureAwait(false); + mappings.Should().HaveCount(2); + + var code = await api.GetMappingsCodeAsync().ConfigureAwait(false); + + // Assert + await Verifier.Verify(code).DontScrubDateTimes().DontScrubGuids(); + + server.Stop(); + } } #endif \ No newline at end of file diff --git a/test/WireMock.Net.Tests/WireMockServer.Proxy.cs b/test/WireMock.Net.Tests/WireMockServer.Proxy.cs index 430a9b44..667d3ab6 100644 --- a/test/WireMock.Net.Tests/WireMockServer.Proxy.cs +++ b/test/WireMock.Net.Tests/WireMockServer.Proxy.cs @@ -117,7 +117,7 @@ public class WireMockServerProxyTests } // Assert - server.Mappings.Should().HaveCount(30); + server.Mappings.Should().HaveCount(32); } [Fact] diff --git a/test/WireMock.Net.Tests/WireMockServer.Settings.cs b/test/WireMock.Net.Tests/WireMockServer.Settings.cs index fe1d13dc..83413879 100644 --- a/test/WireMock.Net.Tests/WireMockServer.Settings.cs +++ b/test/WireMock.Net.Tests/WireMockServer.Settings.cs @@ -10,187 +10,186 @@ using WireMock.Server; using WireMock.Settings; using Xunit; -namespace WireMock.Net.Tests +namespace WireMock.Net.Tests; + +public class WireMockServerSettingsTests { - public class WireMockServerSettingsTests + private readonly Mock _loggerMock; + + public WireMockServerSettingsTests() { - private readonly Mock _loggerMock; + _loggerMock = new Mock(); + _loggerMock.Setup(l => l.Info(It.IsAny(), It.IsAny())); + } - public WireMockServerSettingsTests() + [Fact] + public void WireMockServer_WireMockServerSettings_StartAdminInterfaceTrue_BasicAuthenticationIsSet() + { + // Assign and Act + var server = WireMockServer.Start(new WireMockServerSettings { - _loggerMock = new Mock(); - _loggerMock.Setup(l => l.Info(It.IsAny(), It.IsAny())); - } + StartAdminInterface = true, + AdminUsername = "u", + AdminPassword = "p" + }); - [Fact] - public void WireMockServer_WireMockServerSettings_StartAdminInterfaceTrue_BasicAuthenticationIsSet() + // Assert + var options = server.GetPrivateFieldValue("_options"); + options.AuthenticationMatcher.Should().NotBeNull().And.BeOfType(); + } + + [Fact] + public void WireMockServer_WireMockServerSettings_StartAdminInterfaceTrue_AzureADAuthenticationIsSet() + { + // Assign and Act + var server = WireMockServer.Start(new WireMockServerSettings { - // Assign and Act - var server = WireMockServer.Start(new WireMockServerSettings + StartAdminInterface = true, + AdminAzureADTenant = "t", + AdminAzureADAudience = "a" + }); + + // Assert + var options = server.GetPrivateFieldValue("_options"); + options.AuthenticationMatcher.Should().NotBeNull().And.BeOfType(); + } + + [Fact] + public void WireMockServer_WireMockServerSettings_StartAdminInterfaceFalse_BasicAuthenticationIsNotSet() + { + // Assign and Act + var server = WireMockServer.Start(new WireMockServerSettings + { + StartAdminInterface = false, + AdminUsername = "u", + AdminPassword = "p" + }); + + // Assert + var options = server.GetPrivateFieldValue("_options"); + Check.That(options.AuthenticationMatcher).IsNull(); + } + + [Fact] + public void WireMockServer_WireMockServerSettings_PriorityFromAllAdminMappingsIsLow_When_StartAdminInterface_IsTrue() + { + // Assign and Act + var server = WireMockServer.Start(new WireMockServerSettings + { + StartAdminInterface = true + }); + + // Assert + server.Mappings.Should().NotBeNull(); + server.Mappings.Should().HaveCount(30); + server.Mappings.All(m => m.Priority == WireMockConstants.AdminPriority).Should().BeTrue(); + } + + [Fact] + public void WireMockServer_WireMockServerSettings_ProxyAndRecordSettings_ProxyPriority_IsMinus2000000_When_StartAdminInterface_IsTrue() + { + // Assign and Act + var server = WireMockServer.Start(new WireMockServerSettings + { + StartAdminInterface = true, + ProxyAndRecordSettings = new ProxyAndRecordSettings { - StartAdminInterface = true, - AdminUsername = "u", - AdminPassword = "p" - }); + Url = "www.google.com" + } + }); - // Assert - var options = server.GetPrivateFieldValue("_options"); - options.AuthenticationMatcher.Should().NotBeNull().And.BeOfType(); - } + // Assert + server.Mappings.Should().NotBeNull(); + server.Mappings.Should().HaveCount(31); - [Fact] - public void WireMockServer_WireMockServerSettings_StartAdminInterfaceTrue_AzureADAuthenticationIsSet() + server.Mappings.Count(m => m.Priority == WireMockConstants.AdminPriority).Should().Be(30); + server.Mappings.Count(m => m.Priority == WireMockConstants.ProxyPriority).Should().Be(1); + } + + [Fact] + public void WireMockServer_WireMockServerSettings_ProxyAndRecordSettings_ProxyPriority_Is0_When_StartAdminInterface_IsFalse() + { + // Assign and Act + var server = WireMockServer.Start(new WireMockServerSettings { - // Assign and Act - var server = WireMockServer.Start(new WireMockServerSettings + ProxyAndRecordSettings = new ProxyAndRecordSettings { - StartAdminInterface = true, - AdminAzureADTenant = "t", - AdminAzureADAudience = "a" - }); + Url = "www.google.com" + } + }); - // Assert - var options = server.GetPrivateFieldValue("_options"); - options.AuthenticationMatcher.Should().NotBeNull().And.BeOfType(); - } + // Assert + var mappings = server.Mappings.ToArray(); + Check.That(mappings.Count()).IsEqualTo(1); + Check.That(mappings[0].Priority).IsEqualTo(0); + } - [Fact] - public void WireMockServer_WireMockServerSettings_StartAdminInterfaceFalse_BasicAuthenticationIsNotSet() + [Fact] + public void WireMockServer_WireMockServerSettings_AllowPartialMapping() + { + // Assign and Act + var server = WireMockServer.Start(new WireMockServerSettings { - // Assign and Act - var server = WireMockServer.Start(new WireMockServerSettings - { - StartAdminInterface = false, - AdminUsername = "u", - AdminPassword = "p" - }); + Logger = _loggerMock.Object, + AllowPartialMapping = true + }); - // Assert - var options = server.GetPrivateFieldValue("_options"); - Check.That(options.AuthenticationMatcher).IsNull(); - } + // Assert + var options = server.GetPrivateFieldValue("_options"); + Check.That(options.AllowPartialMapping).Equals(true); - [Fact] - public void WireMockServer_WireMockServerSettings_PriorityFromAllAdminMappingsIsLow_When_StartAdminInterface_IsTrue() + // Verify + _loggerMock.Verify(l => l.Info(It.IsAny(), It.IsAny())); + } + + [Fact] + public void WireMockServer_WireMockServerSettings_AllowBodyForAllHttpMethods() + { + // Assign and Act + var server = WireMockServer.Start(new WireMockServerSettings { - // Assign and Act - var server = WireMockServer.Start(new WireMockServerSettings - { - StartAdminInterface = true - }); + Logger = _loggerMock.Object, + AllowBodyForAllHttpMethods = true + }); - // Assert - server.Mappings.Should().NotBeNull(); - server.Mappings.Should().HaveCount(28); - server.Mappings.All(m => m.Priority == WireMockConstants.AdminPriority).Should().BeTrue(); - } + // Assert + var options = server.GetPrivateFieldValue("_options"); + Check.That(options.AllowBodyForAllHttpMethods).Equals(true); - [Fact] - public void WireMockServer_WireMockServerSettings_ProxyAndRecordSettings_ProxyPriority_IsMinus2000000_When_StartAdminInterface_IsTrue() + // Verify + _loggerMock.Verify(l => l.Info(It.Is(s => s.Contains("AllowBodyForAllHttpMethods") && s.Contains("True")))); + } + + [Fact] + public void WireMockServer_WireMockServerSettings_AllowOnlyDefinedHttpStatusCodeInResponse() + { + // Assign and Act + var server = WireMockServer.Start(new WireMockServerSettings { - // Assign and Act - var server = WireMockServer.Start(new WireMockServerSettings - { - StartAdminInterface = true, - ProxyAndRecordSettings = new ProxyAndRecordSettings - { - Url = "www.google.com" - } - }); + Logger = _loggerMock.Object, + AllowOnlyDefinedHttpStatusCodeInResponse = true + }); - // Assert - server.Mappings.Should().NotBeNull(); - server.Mappings.Should().HaveCount(29); + // Assert + var options = server.GetPrivateFieldValue("_options"); + Check.That(options.AllowOnlyDefinedHttpStatusCodeInResponse).Equals(true); - server.Mappings.Count(m => m.Priority == WireMockConstants.AdminPriority).Should().Be(28); - server.Mappings.Count(m => m.Priority == WireMockConstants.ProxyPriority).Should().Be(1); - } + // Verify + _loggerMock.Verify(l => l.Info(It.Is(s => s.Contains("AllowOnlyDefinedHttpStatusCodeInResponse") && s.Contains("True")))); + } - [Fact] - public void WireMockServer_WireMockServerSettings_ProxyAndRecordSettings_ProxyPriority_Is0_When_StartAdminInterface_IsFalse() + [Fact] + public void WireMockServer_WireMockServerSettings_RequestLogExpirationDuration() + { + // Assign and Act + var server = WireMockServer.Start(new WireMockServerSettings { - // Assign and Act - var server = WireMockServer.Start(new WireMockServerSettings - { - ProxyAndRecordSettings = new ProxyAndRecordSettings - { - Url = "www.google.com" - } - }); + Logger = _loggerMock.Object, + RequestLogExpirationDuration = 1 + }); - // Assert - var mappings = server.Mappings.ToArray(); - Check.That(mappings.Count()).IsEqualTo(1); - Check.That(mappings[0].Priority).IsEqualTo(0); - } - - [Fact] - public void WireMockServer_WireMockServerSettings_AllowPartialMapping() - { - // Assign and Act - var server = WireMockServer.Start(new WireMockServerSettings - { - Logger = _loggerMock.Object, - AllowPartialMapping = true - }); - - // Assert - var options = server.GetPrivateFieldValue("_options"); - Check.That(options.AllowPartialMapping).Equals(true); - - // Verify - _loggerMock.Verify(l => l.Info(It.IsAny(), It.IsAny())); - } - - [Fact] - public void WireMockServer_WireMockServerSettings_AllowBodyForAllHttpMethods() - { - // Assign and Act - var server = WireMockServer.Start(new WireMockServerSettings - { - Logger = _loggerMock.Object, - AllowBodyForAllHttpMethods = true - }); - - // Assert - var options = server.GetPrivateFieldValue("_options"); - Check.That(options.AllowBodyForAllHttpMethods).Equals(true); - - // Verify - _loggerMock.Verify(l => l.Info(It.Is(s => s.Contains("AllowBodyForAllHttpMethods") && s.Contains("True")))); - } - - [Fact] - public void WireMockServer_WireMockServerSettings_AllowOnlyDefinedHttpStatusCodeInResponse() - { - // Assign and Act - var server = WireMockServer.Start(new WireMockServerSettings - { - Logger = _loggerMock.Object, - AllowOnlyDefinedHttpStatusCodeInResponse = true - }); - - // Assert - var options = server.GetPrivateFieldValue("_options"); - Check.That(options.AllowOnlyDefinedHttpStatusCodeInResponse).Equals(true); - - // Verify - _loggerMock.Verify(l => l.Info(It.Is(s => s.Contains("AllowOnlyDefinedHttpStatusCodeInResponse") && s.Contains("True")))); - } - - [Fact] - public void WireMockServer_WireMockServerSettings_RequestLogExpirationDuration() - { - // Assign and Act - var server = WireMockServer.Start(new WireMockServerSettings - { - Logger = _loggerMock.Object, - RequestLogExpirationDuration = 1 - }); - - // Assert - var options = server.GetPrivateFieldValue("_options"); - Check.That(options.RequestLogExpirationDuration).IsEqualTo(1); - } + // Assert + var options = server.GetPrivateFieldValue("_options"); + Check.That(options.RequestLogExpirationDuration).IsEqualTo(1); } } \ No newline at end of file