From d971144426bbf1761dcc4c24da5e3d9870267dd5 Mon Sep 17 00:00:00 2001 From: Stef Heyenrath Date: Fri, 27 Dec 2019 16:01:13 +0100 Subject: [PATCH] WireMock.Net version 1.1.x (#363) * refactor * rename api * -preview-01 * logger * move * RandomDataGenerator.Net * . * ISettings * renames... * refactor CommandlineParser logic * remove standalone * Remove Interfaces * Update tests * WireMock.Net.StandAlone * . * fix * . * _settings * Admin * WireMock.Net.Abstractions * fix build * rename WireMockServer * fix compile errors --- Directory.Build.props | 2 +- README.md | 15 +- WireMock.Net Solution.sln | 115 +- examples/WireMock.Net.Client/Program.cs | 4 +- .../WireMock.Net.Client.csproj | 4 +- .../WireMock.Net.Console.NETCoreApp2.csproj | 4 + .../MainApp.cs | 5 +- ...WireMock.Net.Console.Net452.Classic.csproj | 6 +- ...WireMock.Net.Console.Net461.Classic.csproj | 6 +- .../Program.cs | 4 +- ...eMock.Net.Console.Proxy.NETCoreApp2.csproj | 1 - .../Program.cs | 2 +- .../WireMock.Net.Console.Proxy.Net452.csproj | 4 - .../Program.cs | 2 +- examples/WireMock.Net.Service/Program.cs | 7 +- .../WireMock.Net.Service.csproj | 10 +- .../WireMockLog4NetLogger.cs | 2 +- examples/WireMock.Net.Service/packages.config | 2 +- .../Program.cs | 9 +- .../WireMock.Net.StandAlone.NETCoreApp.csproj | 3 +- .../WireMockLog4NetLogger.cs | 2 +- .../WireMock.Net.StandAlone.Net452/Program.cs | 8 +- .../WireMock.Net.StandAlone.Net452.csproj | 6 +- .../WireMock.Net.StandAlone.Net461/Program.cs | 12 +- .../WireMock.Net.StandAlone.Net461.csproj | 21 +- .../packages.config | 4 +- .../WireMock.Net.WebApplication/Program.cs | 6 +- ...ireMock.Net.WebApplication.NETCore2.csproj | 2 +- .../WireMockService.cs | 10 +- .../appsettings.json | 2 +- .../Admin/Mappings/BodyModel.cs | 0 .../Admin/Mappings/ClientIPModel.cs | 0 .../Admin/Mappings/CookieModel.cs | 0 .../Admin/Mappings/EncodingModel.cs | 0 .../Admin/Mappings/FaultModel.cs | 0 .../Admin/Mappings/HeaderModel.cs | 0 .../Admin/Mappings/MappingModel.cs | 0 .../Admin/Mappings/MatcherModel.cs | 0 .../Admin/Mappings/ParamModel.cs | 0 .../Admin/Mappings/PathModel.cs | 0 .../Admin/Mappings/RequestModel.cs | 0 .../Admin/Mappings/ResponseModel.cs | 5 - .../Admin/Mappings/StatusModel.cs | 0 .../Admin/Mappings/UrlModel.cs | 0 .../Admin/Mappings/WebProxyModel.cs | 0 .../Admin/Requests/LogEntryModel.cs | 0 .../Admin/Requests/LogRequestMatchModel.cs | 0 .../Admin/Requests/LogRequestModel.cs | 2 +- .../Admin/Requests/LogResponseModel.cs | 2 +- .../Admin/Scenarios/ScenarioStateModel.cs | 0 .../Admin/Settings/SettingsModel.cs | 0 .../Handlers/IFileSystemHandler.cs | 0 .../Logging/IWireMockLogger.cs | 0 .../Types}/BodyType.cs | 2 +- .../Types}/WireMockList.cs | 2 +- .../WireMock.Net.Abstractions.csproj | 46 + .../IWireMockAdminApi.cs} | 56 +- .../WireMock.Net.RestClient.csproj | 48 + src/WireMock.Net.StandAlone/StandAloneApp.cs | 70 +- .../WireMock.Net.StandAlone.csproj | 119 +- .../Http/HttpRequestMessageHelper.cs | 8 +- src/WireMock.Net/IMapping.cs | 4 +- .../Logging/WireMockConsoleLogger.cs | 4 +- src/WireMock.Net/Mapping.cs | 10 +- .../Request/RequestMessageBodyMatcher.cs | 2 +- .../Request/RequestMessageHeaderMatcher.cs | 6 +- .../Request/RequestMessageParamMatcher.cs | 2 +- .../Owin/Mappers/OwinResponseMapper.cs | 1 + src/WireMock.Net/Owin/WireMockMiddleware.cs | 2 +- .../RequestBuilders/IParamsRequestBuilder.cs | 2 +- .../RequestBuilders/Request.WithParam.cs | 2 +- src/WireMock.Net/RequestMessage.cs | 1 + .../ResponseBuilders/IBodyResponseBuilder.cs | 13 +- .../IHeadersResponseBuilder.cs | 6 +- src/WireMock.Net/ResponseBuilders/Response.cs | 22 +- src/WireMock.Net/ResponseMessage.cs | 1 + src/WireMock.Net/ResponseMessageBuilder.cs | 1 + .../DynamicAsyncResponseProvider.cs | 2 +- .../DynamicResponseProvider.cs | 2 +- .../ResponseProviders/IResponseProvider.cs | 4 +- .../ProxyAsyncResponseProvider.cs | 8 +- .../Serialization/LogEntryMapper.cs | 1 + .../Serialization/MappingConverter.cs | 1 + .../Serialization/MatcherMapper.cs | 6 +- src/WireMock.Net/Server/FluentMockServer.cs | 487 +------- .../Server/RespondWithAProvider.cs | 6 +- ...erver.Admin.cs => WireMockServer.Admin.cs} | 11 +- ...nFiles.cs => WireMockServer.AdminFiles.cs} | 3 +- ...ntries.cs => WireMockServer.LogEntries.cs} | 198 ++-- src/WireMock.Net/Server/WireMockServer.cs | 477 ++++++++ .../Settings/FluentMockServerSettings.cs | 100 +- .../Settings/IFluentMockServerSettings.cs | 136 +-- .../Settings/IWireMockServerSettings.cs | 141 +++ .../Settings/ProxyAndRecordSettings.cs | 34 +- .../Settings}/SimpleCommandLineParser.cs | 172 +-- .../Settings/WireMockServerSettings.cs | 105 ++ .../Settings/WireMockServerSettingsParser.cs | 89 ++ .../ResponseMessageTransformer.cs | 1 + src/WireMock.Net/Util/BodyData.cs | 1 + src/WireMock.Net/Util/BodyParser.cs | 1 + src/WireMock.Net/Util/QueryStringParser.cs | 3 +- src/WireMock.Net/WireMock.Net.csproj | 13 +- .../Http/HttpRequestMessageHelperTests.cs | 5 +- .../MatchBehaviourHelperTests.cs | 2 +- .../ObservableLogEntriesTest.cs | 16 +- .../Owin/Mappers/OwinResponseMapperTests.cs | 1 + .../Owin/WireMockMiddlewareTests.cs | 4 +- .../RequestMessageBodyMatcherTests.cs | 2 + test/WireMock.Net.Tests/RequestTests.cs | 9 +- .../RequestWithBodyTests.cs | 7 +- .../ResponseBuilders/ResponseCreateTests.cs | 7 +- .../ResponseWithBodyFromFileTests.cs | 2 +- .../ResponseBuilders/ResponseWithBodyTests.cs | 38 +- .../ResponseWithCallbackTests.cs | 8 +- .../ResponseWithFaultTests.cs | 6 +- .../ResponseWithHandlebarsFileTests.cs | 17 +- .../ResponseWithHandlebarsJsonPathTests.cs | 22 +- .../ResponseWithHandlebarsLinqTests.cs | 26 +- .../ResponseWithHandlebarsRandomTests.cs | 17 +- .../ResponseWithHandlebarsRegexTests.cs | 22 +- .../ResponseWithHandlebarsTests.cs | 33 +- .../ResponseWithHandlebarsXegerTests.cs | 6 +- .../ResponseWithHeadersTests.cs | 19 +- .../ResponseWithProxyTests.cs | 16 +- .../Serialization/LogEntryMapperTests.cs | 1 + .../Serialization/MappingConverterTests.cs | 8 +- .../Serialization/MatcherMapperTests.cs | 12 +- .../Serialization/MatcherModelMapperTests.cs | 8 +- .../SimpleCommandLineParserTests.cs | 4 +- .../StatefulBehaviorTests.cs | 14 +- .../Util/BodyParserTests.cs | 1 + .../Util/QueryStringParserTests.cs | 1 + .../WireMock.Net.Tests.csproj | 9 +- ...lientTests.cs => WireMockAdminApiTests.cs} | 1002 ++++++++--------- ...Tests.Admin.cs => WireMockServer.Admin.cs} | 90 +- ...nFiles.cs => WireMockServer.AdminFiles.cs} | 26 +- ...on.cs => WireMockServer.Authentication.cs} | 10 +- ...Tests.Proxy.cs => WireMockServer.Proxy.cs} | 105 +- ...sts.Proxy2.cs => WireMockServer.Proxy2.cs} | 8 +- ...Settings.cs => WireMockServer.Settings.cs} | 38 +- ...kServerTests.cs => WireMockServerTests.cs} | 525 +++++---- 141 files changed, 2549 insertions(+), 2319 deletions(-) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/BodyModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/ClientIPModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/CookieModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/EncodingModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/FaultModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/HeaderModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/MappingModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/MatcherModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/ParamModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/PathModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/RequestModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/ResponseModel.cs (95%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/StatusModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/UrlModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Mappings/WebProxyModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Requests/LogEntryModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Requests/LogRequestMatchModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Requests/LogRequestModel.cs (99%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Requests/LogResponseModel.cs (99%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Scenarios/ScenarioStateModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Admin/Settings/SettingsModel.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Handlers/IFileSystemHandler.cs (100%) rename src/{WireMock.Net => WireMock.Net.Abstractions}/Logging/IWireMockLogger.cs (100%) rename src/{WireMock.Net/Util => WireMock.Net.Abstractions/Types}/BodyType.cs (95%) rename src/{WireMock.Net/Util => WireMock.Net.Abstractions/Types}/WireMockList.cs (98%) create mode 100644 src/WireMock.Net.Abstractions/WireMock.Net.Abstractions.csproj rename src/{WireMock.Net/Client/IFluentMockServerAdmin.cs => WireMock.Net.RestClient/IWireMockAdminApi.cs} (84%) create mode 100644 src/WireMock.Net.RestClient/WireMock.Net.RestClient.csproj rename src/WireMock.Net/Server/{FluentMockServer.Admin.cs => WireMockServer.Admin.cs} (98%) rename src/WireMock.Net/Server/{FluentMockServer.AdminFiles.cs => WireMockServer.AdminFiles.cs} (98%) rename src/WireMock.Net/Server/{FluentMockServer.LogEntries.cs => WireMockServer.LogEntries.cs} (95%) create mode 100644 src/WireMock.Net/Server/WireMockServer.cs create mode 100644 src/WireMock.Net/Settings/IWireMockServerSettings.cs rename src/{WireMock.Net.StandAlone => WireMock.Net/Settings}/SimpleCommandLineParser.cs (95%) create mode 100644 src/WireMock.Net/Settings/WireMockServerSettings.cs create mode 100644 src/WireMock.Net/Settings/WireMockServerSettingsParser.cs rename test/WireMock.Net.Tests/{ => Matchers}/MatchBehaviourHelperTests.cs (96%) rename test/WireMock.Net.Tests/{StandAlone => Settings}/SimpleCommandLineParserTests.cs (97%) rename test/WireMock.Net.Tests/{FluentMockServerAdminRestClientTests.cs => WireMockAdminApiTests.cs} (77%) rename test/WireMock.Net.Tests/{FluentMockServerTests.Admin.cs => WireMockServer.Admin.cs} (83%) rename test/WireMock.Net.Tests/{FLuentMockServerTests.AdminFiles.cs => WireMockServer.AdminFiles.cs} (90%) rename test/WireMock.Net.Tests/{FluentMockServerTests.Authentication.cs => WireMockServer.Authentication.cs} (77%) rename test/WireMock.Net.Tests/{FluentMockServerTests.Proxy.cs => WireMockServer.Proxy.cs} (83%) rename test/WireMock.Net.Tests/{FluentMockServerTests.Proxy2.cs => WireMockServer.Proxy2.cs} (86%) rename test/WireMock.Net.Tests/{FluentMockServerTests.Settings.cs => WireMockServer.Settings.cs} (70%) rename test/WireMock.Net.Tests/{FluentMockServerTests.cs => WireMockServerTests.cs} (79%) diff --git a/Directory.Build.props b/Directory.Build.props index 8cad8a289..b8e12cb08 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -4,7 +4,7 @@ - 1.0.43 + 1.1.0-preview-01 diff --git a/README.md b/README.md index 0d920dd32..eebd858c9 100644 --- a/README.md +++ b/README.md @@ -28,13 +28,14 @@ A C# .NET version based on [mock4net](https://github.com/alexvictoor/mock4net) w |   **Sonar Coverage** | [![Sonar Coverage](https://sonarcloud.io/api/project_badges/measure?project=wiremock&metric=coverage)](https://sonarcloud.io/component_measures?id=wiremock&metric=coverage) | |   **Codecov** | [![codecov](https://codecov.io/gh/WireMock-Net/WireMock.Net/branch/master/graph/badge.svg)](https://codecov.io/gh/WireMock-Net/WireMock.Net) | |   **Coveralls** | [![Coverage Status](https://coveralls.io/repos/github/WireMock-Net/WireMock.Net/badge.svg?branch=master)](https://coveralls.io/github/WireMock-Net/WireMock.Net?branch=master) | -| | -| ***NuGet*** |   | -|   **WireMock.Net** | [![NuGet Badge WireMock.Net](https://buildstats.info/nuget/WireMock.Net)](https://www.nuget.org/packages/WireMock.Net) | -|   **WireMock.Net.StandAlone** | [![NuGet Badge WireMock.Net.StandAlone](https://buildstats.info/nuget/WireMock.Net.StandAlone)](https://www.nuget.org/packages/WireMock.Net.StandAlone) | -| ***MyGet (previews)*** |   | -|   **WireMock.Net** | [![MyGet Badge WireMock.Net](https://buildstats.info/myget/wiremock-net/WireMock.Net)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net) | -|   **WireMock.Net.StandAlone** | [![MyGet Badge WireMock.Net.StandAlone](https://buildstats.info/myget/wiremock-net/WireMock.Net.StandAlone)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.StandAlone) | + +### NuGet packages + +| | Official | Preview | +| - | - | - | +|   **WireMock.Net** | [![NuGet Badge WireMock.Net](https://buildstats.info/nuget/WireMock.Net)](https://www.nuget.org/packages/WireMock.Net) | [![MyGet Badge WireMock.Net](https://buildstats.info/myget/wiremock-net/WireMock.Net)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net) +|   **WireMock.Net.StandAlone** | [![NuGet Badge WireMock.Net](https://buildstats.info/nuget/WireMock.Net.StandAlone)](https://www.nuget.org/packages/WireMock.Net.StandAlone) | [![MyGet Badge WireMock.Net.StandAlone](https://buildstats.info/myget/wiremock-net/WireMock.Net.StandAlone)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.StandAlone) +|   **WireMock.Net.RestClient** | [![NuGet Badge WireMock.Net.RestClient](https://buildstats.info/nuget/WireMock.Net.RestClient)](https://www.nuget.org/packages/WireMock.Net.RestClient) | [![MyGet Badge WireMock.Net.RestClient](https://buildstats.info/myget/wiremock-net/WireMock.Net.RestClient)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.RestClient) ## Development For the supported frameworks and build information, see [this](https://github.com/WireMock-Net/WireMock.Net/wiki/Development-Information) page. diff --git a/WireMock.Net Solution.sln b/WireMock.Net Solution.sln index 8750305e2..c16a58966 100644 --- a/WireMock.Net Solution.sln +++ b/WireMock.Net Solution.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29512.175 +# Visual Studio 15 +VisualStudioVersion = 15.0.28307.902 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{EF242EDF-7133-4277-9A0C-18744DE08707}" EndProject @@ -36,14 +36,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.Console.Proxy. EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.Client", "examples\WireMock.Net.Client\WireMock.Net.Client.csproj", "{058D4B6C-C03E-49D0-91DB-A535B058FA0D}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.StandAlone", "src\WireMock.Net.StandAlone\WireMock.Net.StandAlone.csproj", "{B6269AAC-170A-43D5-8B9A-579DED3D9A95}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.StandAlone.NETCoreApp", "examples\WireMock.Net.StandAlone.NETCoreApp\WireMock.Net.StandAlone.NETCoreApp.csproj", "{10E16614-61CA-48D8-8BDD-664C13913DED}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.StandAlone.Net452", "examples\WireMock.Net.StandAlone.Net452\WireMock.Net.StandAlone.Net452.csproj", "{668F689E-57B4-422E-8846-C0FF643CA999}" - ProjectSection(ProjectDependencies) = postProject - {B6269AAC-170A-43D5-8B9A-579DED3D9A95} = {B6269AAC-170A-43D5-8B9A-579DED3D9A95} - EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.WebApplication.NETCore2", "examples\WireMock.Net.WebApplication\WireMock.Net.WebApplication.NETCore2.csproj", "{049539C1-7A66-4559-AD7A-B1C73B97CBB0}" EndProject @@ -61,82 +56,174 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.Console.Net452 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.Console.NETCoreApp2", "examples\WireMock.Net.Console.NETCoreApp2\WireMock.Net.Console.NETCoreApp2.csproj", "{83645809-9E01-4E81-8733-BA9497554ABF}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.Console.RequestLogTest", "examples\WireMock.Net.Console.RequestLogTest\WireMock.Net.Console.RequestLogTest.csproj", "{A9D039B9-7509-4CF1-9EFD-87EB82998575}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.RestClient", "src\WireMock.Net.RestClient\WireMock.Net.RestClient.csproj", "{B6269AAC-170A-43D6-8B9A-579DED3D9A96}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.Abstractions", "src\WireMock.Net.Abstractions\WireMock.Net.Abstractions.csproj", "{B6269AAC-170A-4346-8B9A-579DED3D9A94}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.StandAlone", "src\WireMock.Net.StandAlone\WireMock.Net.StandAlone.csproj", "{B6269AAC-170A-43D5-8B9A-579DED3D9A95}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.Console.RequestLogTest", "examples\WireMock.Net.Console.RequestLogTest\WireMock.Net.Console.RequestLogTest.csproj", "{A9D039B9-7509-4CF1-9EFD-87EB82998575}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {D3804228-91F4-4502-9595-39584E5A01AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D3804228-91F4-4502-9595-39584E5A01AD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D3804228-91F4-4502-9595-39584E5A01AD}.Debug|x64.ActiveCfg = Debug|Any CPU + {D3804228-91F4-4502-9595-39584E5A01AD}.Debug|x64.Build.0 = Debug|Any CPU {D3804228-91F4-4502-9595-39584E5A01AD}.Release|Any CPU.ActiveCfg = Release|Any CPU {D3804228-91F4-4502-9595-39584E5A01AD}.Release|Any CPU.Build.0 = Release|Any CPU + {D3804228-91F4-4502-9595-39584E5A01AD}.Release|x64.ActiveCfg = Release|Any CPU + {D3804228-91F4-4502-9595-39584E5A01AD}.Release|x64.Build.0 = Release|Any CPU {31DC2EF8-C3FE-467D-84BE-FB5D956E612E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {31DC2EF8-C3FE-467D-84BE-FB5D956E612E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {31DC2EF8-C3FE-467D-84BE-FB5D956E612E}.Debug|x64.ActiveCfg = Debug|Any CPU + {31DC2EF8-C3FE-467D-84BE-FB5D956E612E}.Debug|x64.Build.0 = Debug|Any CPU {31DC2EF8-C3FE-467D-84BE-FB5D956E612E}.Release|Any CPU.ActiveCfg = Release|Any CPU {31DC2EF8-C3FE-467D-84BE-FB5D956E612E}.Release|Any CPU.Build.0 = Release|Any CPU + {31DC2EF8-C3FE-467D-84BE-FB5D956E612E}.Release|x64.ActiveCfg = Release|Any CPU + {31DC2EF8-C3FE-467D-84BE-FB5D956E612E}.Release|x64.Build.0 = Release|Any CPU {FE281639-B014-4C8A-96FA-141164A74713}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FE281639-B014-4C8A-96FA-141164A74713}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FE281639-B014-4C8A-96FA-141164A74713}.Debug|x64.ActiveCfg = Debug|Any CPU + {FE281639-B014-4C8A-96FA-141164A74713}.Debug|x64.Build.0 = Debug|Any CPU {FE281639-B014-4C8A-96FA-141164A74713}.Release|Any CPU.ActiveCfg = Release|Any CPU {FE281639-B014-4C8A-96FA-141164A74713}.Release|Any CPU.Build.0 = Release|Any CPU + {FE281639-B014-4C8A-96FA-141164A74713}.Release|x64.ActiveCfg = Release|Any CPU + {FE281639-B014-4C8A-96FA-141164A74713}.Release|x64.Build.0 = Release|Any CPU {1995E414-F197-4AB4-90C2-68D806B5AF59}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1995E414-F197-4AB4-90C2-68D806B5AF59}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1995E414-F197-4AB4-90C2-68D806B5AF59}.Debug|x64.ActiveCfg = Debug|Any CPU + {1995E414-F197-4AB4-90C2-68D806B5AF59}.Debug|x64.Build.0 = Debug|Any CPU {1995E414-F197-4AB4-90C2-68D806B5AF59}.Release|Any CPU.ActiveCfg = Release|Any CPU {1995E414-F197-4AB4-90C2-68D806B5AF59}.Release|Any CPU.Build.0 = Release|Any CPU + {1995E414-F197-4AB4-90C2-68D806B5AF59}.Release|x64.ActiveCfg = Release|Any CPU + {1995E414-F197-4AB4-90C2-68D806B5AF59}.Release|x64.Build.0 = Release|Any CPU {058D4B6C-C03E-49D0-91DB-A535B058FA0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {058D4B6C-C03E-49D0-91DB-A535B058FA0D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {058D4B6C-C03E-49D0-91DB-A535B058FA0D}.Debug|x64.ActiveCfg = Debug|Any CPU + {058D4B6C-C03E-49D0-91DB-A535B058FA0D}.Debug|x64.Build.0 = Debug|Any CPU {058D4B6C-C03E-49D0-91DB-A535B058FA0D}.Release|Any CPU.ActiveCfg = Release|Any CPU {058D4B6C-C03E-49D0-91DB-A535B058FA0D}.Release|Any CPU.Build.0 = Release|Any CPU - {B6269AAC-170A-43D5-8B9A-579DED3D9A95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B6269AAC-170A-43D5-8B9A-579DED3D9A95}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B6269AAC-170A-43D5-8B9A-579DED3D9A95}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B6269AAC-170A-43D5-8B9A-579DED3D9A95}.Release|Any CPU.Build.0 = Release|Any CPU + {058D4B6C-C03E-49D0-91DB-A535B058FA0D}.Release|x64.ActiveCfg = Release|Any CPU + {058D4B6C-C03E-49D0-91DB-A535B058FA0D}.Release|x64.Build.0 = Release|Any CPU {10E16614-61CA-48D8-8BDD-664C13913DED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {10E16614-61CA-48D8-8BDD-664C13913DED}.Debug|Any CPU.Build.0 = Debug|Any CPU + {10E16614-61CA-48D8-8BDD-664C13913DED}.Debug|x64.ActiveCfg = Debug|Any CPU + {10E16614-61CA-48D8-8BDD-664C13913DED}.Debug|x64.Build.0 = Debug|Any CPU {10E16614-61CA-48D8-8BDD-664C13913DED}.Release|Any CPU.ActiveCfg = Release|Any CPU {10E16614-61CA-48D8-8BDD-664C13913DED}.Release|Any CPU.Build.0 = Release|Any CPU + {10E16614-61CA-48D8-8BDD-664C13913DED}.Release|x64.ActiveCfg = Release|Any CPU + {10E16614-61CA-48D8-8BDD-664C13913DED}.Release|x64.Build.0 = Release|Any CPU {668F689E-57B4-422E-8846-C0FF643CA999}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {668F689E-57B4-422E-8846-C0FF643CA999}.Debug|Any CPU.Build.0 = Debug|Any CPU + {668F689E-57B4-422E-8846-C0FF643CA999}.Debug|x64.ActiveCfg = Debug|Any CPU + {668F689E-57B4-422E-8846-C0FF643CA999}.Debug|x64.Build.0 = Debug|Any CPU {668F689E-57B4-422E-8846-C0FF643CA999}.Release|Any CPU.ActiveCfg = Release|Any CPU {668F689E-57B4-422E-8846-C0FF643CA999}.Release|Any CPU.Build.0 = Release|Any CPU + {668F689E-57B4-422E-8846-C0FF643CA999}.Release|x64.ActiveCfg = Release|Any CPU + {668F689E-57B4-422E-8846-C0FF643CA999}.Release|x64.Build.0 = Release|Any CPU {049539C1-7A66-4559-AD7A-B1C73B97CBB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {049539C1-7A66-4559-AD7A-B1C73B97CBB0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {049539C1-7A66-4559-AD7A-B1C73B97CBB0}.Debug|x64.ActiveCfg = Debug|Any CPU + {049539C1-7A66-4559-AD7A-B1C73B97CBB0}.Debug|x64.Build.0 = Debug|Any CPU {049539C1-7A66-4559-AD7A-B1C73B97CBB0}.Release|Any CPU.ActiveCfg = Release|Any CPU {049539C1-7A66-4559-AD7A-B1C73B97CBB0}.Release|Any CPU.Build.0 = Release|Any CPU + {049539C1-7A66-4559-AD7A-B1C73B97CBB0}.Release|x64.ActiveCfg = Release|Any CPU + {049539C1-7A66-4559-AD7A-B1C73B97CBB0}.Release|x64.Build.0 = Release|Any CPU {26433A8F-BF01-4962-97EB-81BFFBB61096}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {26433A8F-BF01-4962-97EB-81BFFBB61096}.Debug|Any CPU.Build.0 = Debug|Any CPU + {26433A8F-BF01-4962-97EB-81BFFBB61096}.Debug|x64.ActiveCfg = Debug|x64 + {26433A8F-BF01-4962-97EB-81BFFBB61096}.Debug|x64.Build.0 = Debug|x64 {26433A8F-BF01-4962-97EB-81BFFBB61096}.Release|Any CPU.ActiveCfg = Release|Any CPU {26433A8F-BF01-4962-97EB-81BFFBB61096}.Release|Any CPU.Build.0 = Release|Any CPU + {26433A8F-BF01-4962-97EB-81BFFBB61096}.Release|x64.ActiveCfg = Release|x64 + {26433A8F-BF01-4962-97EB-81BFFBB61096}.Release|x64.Build.0 = Release|x64 {23A9AA3C-40FC-42AA-8A5E-05899795A1C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {23A9AA3C-40FC-42AA-8A5E-05899795A1C6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {23A9AA3C-40FC-42AA-8A5E-05899795A1C6}.Debug|x64.ActiveCfg = Debug|Any CPU + {23A9AA3C-40FC-42AA-8A5E-05899795A1C6}.Debug|x64.Build.0 = Debug|Any CPU {23A9AA3C-40FC-42AA-8A5E-05899795A1C6}.Release|Any CPU.ActiveCfg = Release|Any CPU {23A9AA3C-40FC-42AA-8A5E-05899795A1C6}.Release|Any CPU.Build.0 = Release|Any CPU + {23A9AA3C-40FC-42AA-8A5E-05899795A1C6}.Release|x64.ActiveCfg = Release|Any CPU + {23A9AA3C-40FC-42AA-8A5E-05899795A1C6}.Release|x64.Build.0 = Release|Any CPU {3C279524-DB73-4DE3-BEF1-F2B2958C9F65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3C279524-DB73-4DE3-BEF1-F2B2958C9F65}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3C279524-DB73-4DE3-BEF1-F2B2958C9F65}.Debug|x64.ActiveCfg = Debug|Any CPU + {3C279524-DB73-4DE3-BEF1-F2B2958C9F65}.Debug|x64.Build.0 = Debug|Any CPU {3C279524-DB73-4DE3-BEF1-F2B2958C9F65}.Release|Any CPU.ActiveCfg = Release|Any CPU {3C279524-DB73-4DE3-BEF1-F2B2958C9F65}.Release|Any CPU.Build.0 = Release|Any CPU + {3C279524-DB73-4DE3-BEF1-F2B2958C9F65}.Release|x64.ActiveCfg = Release|Any CPU + {3C279524-DB73-4DE3-BEF1-F2B2958C9F65}.Release|x64.Build.0 = Release|Any CPU {7F0B2446-0363-4720-AF46-F47F83B557DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7F0B2446-0363-4720-AF46-F47F83B557DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7F0B2446-0363-4720-AF46-F47F83B557DC}.Debug|x64.ActiveCfg = Debug|Any CPU + {7F0B2446-0363-4720-AF46-F47F83B557DC}.Debug|x64.Build.0 = Debug|Any CPU {7F0B2446-0363-4720-AF46-F47F83B557DC}.Release|Any CPU.ActiveCfg = Release|Any CPU {7F0B2446-0363-4720-AF46-F47F83B557DC}.Release|Any CPU.Build.0 = Release|Any CPU + {7F0B2446-0363-4720-AF46-F47F83B557DC}.Release|x64.ActiveCfg = Release|Any CPU + {7F0B2446-0363-4720-AF46-F47F83B557DC}.Release|x64.Build.0 = Release|Any CPU {1261BB9B-A7D4-456C-8985-3CE560361B8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1261BB9B-A7D4-456C-8985-3CE560361B8E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1261BB9B-A7D4-456C-8985-3CE560361B8E}.Debug|x64.ActiveCfg = Debug|Any CPU + {1261BB9B-A7D4-456C-8985-3CE560361B8E}.Debug|x64.Build.0 = Debug|Any CPU {1261BB9B-A7D4-456C-8985-3CE560361B8E}.Release|Any CPU.ActiveCfg = Release|Any CPU {1261BB9B-A7D4-456C-8985-3CE560361B8E}.Release|Any CPU.Build.0 = Release|Any CPU + {1261BB9B-A7D4-456C-8985-3CE560361B8E}.Release|x64.ActiveCfg = Release|Any CPU + {1261BB9B-A7D4-456C-8985-3CE560361B8E}.Release|x64.Build.0 = Release|Any CPU {668F689E-57B4-422E-8846-C0FF643CA268}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {668F689E-57B4-422E-8846-C0FF643CA268}.Debug|Any CPU.Build.0 = Debug|Any CPU + {668F689E-57B4-422E-8846-C0FF643CA268}.Debug|x64.ActiveCfg = Debug|Any CPU + {668F689E-57B4-422E-8846-C0FF643CA268}.Debug|x64.Build.0 = Debug|Any CPU {668F689E-57B4-422E-8846-C0FF643CA268}.Release|Any CPU.ActiveCfg = Release|Any CPU {668F689E-57B4-422E-8846-C0FF643CA268}.Release|Any CPU.Build.0 = Release|Any CPU + {668F689E-57B4-422E-8846-C0FF643CA268}.Release|x64.ActiveCfg = Release|Any CPU + {668F689E-57B4-422E-8846-C0FF643CA268}.Release|x64.Build.0 = Release|Any CPU {83645809-9E01-4E81-8733-BA9497554ABF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {83645809-9E01-4E81-8733-BA9497554ABF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {83645809-9E01-4E81-8733-BA9497554ABF}.Debug|x64.ActiveCfg = Debug|Any CPU + {83645809-9E01-4E81-8733-BA9497554ABF}.Debug|x64.Build.0 = Debug|Any CPU {83645809-9E01-4E81-8733-BA9497554ABF}.Release|Any CPU.ActiveCfg = Release|Any CPU {83645809-9E01-4E81-8733-BA9497554ABF}.Release|Any CPU.Build.0 = Release|Any CPU + {83645809-9E01-4E81-8733-BA9497554ABF}.Release|x64.ActiveCfg = Release|Any CPU + {83645809-9E01-4E81-8733-BA9497554ABF}.Release|x64.Build.0 = Release|Any CPU + {B6269AAC-170A-43D6-8B9A-579DED3D9A96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B6269AAC-170A-43D6-8B9A-579DED3D9A96}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B6269AAC-170A-43D6-8B9A-579DED3D9A96}.Debug|x64.ActiveCfg = Debug|Any CPU + {B6269AAC-170A-43D6-8B9A-579DED3D9A96}.Debug|x64.Build.0 = Debug|Any CPU + {B6269AAC-170A-43D6-8B9A-579DED3D9A96}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B6269AAC-170A-43D6-8B9A-579DED3D9A96}.Release|Any CPU.Build.0 = Release|Any CPU + {B6269AAC-170A-43D6-8B9A-579DED3D9A96}.Release|x64.ActiveCfg = Release|Any CPU + {B6269AAC-170A-43D6-8B9A-579DED3D9A96}.Release|x64.Build.0 = Release|Any CPU + {B6269AAC-170A-4346-8B9A-579DED3D9A94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B6269AAC-170A-4346-8B9A-579DED3D9A94}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B6269AAC-170A-4346-8B9A-579DED3D9A94}.Debug|x64.ActiveCfg = Debug|Any CPU + {B6269AAC-170A-4346-8B9A-579DED3D9A94}.Debug|x64.Build.0 = Debug|Any CPU + {B6269AAC-170A-4346-8B9A-579DED3D9A94}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B6269AAC-170A-4346-8B9A-579DED3D9A94}.Release|Any CPU.Build.0 = Release|Any CPU + {B6269AAC-170A-4346-8B9A-579DED3D9A94}.Release|x64.ActiveCfg = Release|Any CPU + {B6269AAC-170A-4346-8B9A-579DED3D9A94}.Release|x64.Build.0 = Release|Any CPU + {B6269AAC-170A-43D5-8B9A-579DED3D9A95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B6269AAC-170A-43D5-8B9A-579DED3D9A95}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B6269AAC-170A-43D5-8B9A-579DED3D9A95}.Debug|x64.ActiveCfg = Debug|Any CPU + {B6269AAC-170A-43D5-8B9A-579DED3D9A95}.Debug|x64.Build.0 = Debug|Any CPU + {B6269AAC-170A-43D5-8B9A-579DED3D9A95}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B6269AAC-170A-43D5-8B9A-579DED3D9A95}.Release|Any CPU.Build.0 = Release|Any CPU + {B6269AAC-170A-43D5-8B9A-579DED3D9A95}.Release|x64.ActiveCfg = Release|Any CPU + {B6269AAC-170A-43D5-8B9A-579DED3D9A95}.Release|x64.Build.0 = Release|Any CPU {A9D039B9-7509-4CF1-9EFD-87EB82998575}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A9D039B9-7509-4CF1-9EFD-87EB82998575}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A9D039B9-7509-4CF1-9EFD-87EB82998575}.Debug|x64.ActiveCfg = Debug|Any CPU + {A9D039B9-7509-4CF1-9EFD-87EB82998575}.Debug|x64.Build.0 = Debug|Any CPU {A9D039B9-7509-4CF1-9EFD-87EB82998575}.Release|Any CPU.ActiveCfg = Release|Any CPU {A9D039B9-7509-4CF1-9EFD-87EB82998575}.Release|Any CPU.Build.0 = Release|Any CPU + {A9D039B9-7509-4CF1-9EFD-87EB82998575}.Release|x64.ActiveCfg = Release|Any CPU + {A9D039B9-7509-4CF1-9EFD-87EB82998575}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -147,7 +234,6 @@ Global {FE281639-B014-4C8A-96FA-141164A74713} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {1995E414-F197-4AB4-90C2-68D806B5AF59} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {058D4B6C-C03E-49D0-91DB-A535B058FA0D} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} - {B6269AAC-170A-43D5-8B9A-579DED3D9A95} = {EF242EDF-7133-4277-9A0C-18744DE08707} {10E16614-61CA-48D8-8BDD-664C13913DED} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {668F689E-57B4-422E-8846-C0FF643CA999} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {049539C1-7A66-4559-AD7A-B1C73B97CBB0} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} @@ -158,6 +244,9 @@ Global {1261BB9B-A7D4-456C-8985-3CE560361B8E} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {668F689E-57B4-422E-8846-C0FF643CA268} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {83645809-9E01-4E81-8733-BA9497554ABF} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} + {B6269AAC-170A-43D6-8B9A-579DED3D9A96} = {EF242EDF-7133-4277-9A0C-18744DE08707} + {B6269AAC-170A-4346-8B9A-579DED3D9A94} = {EF242EDF-7133-4277-9A0C-18744DE08707} + {B6269AAC-170A-43D5-8B9A-579DED3D9A95} = {EF242EDF-7133-4277-9A0C-18744DE08707} {A9D039B9-7509-4CF1-9EFD-87EB82998575} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution diff --git a/examples/WireMock.Net.Client/Program.cs b/examples/WireMock.Net.Client/Program.cs index 4d3eb682c..e7ec4015c 100644 --- a/examples/WireMock.Net.Client/Program.cs +++ b/examples/WireMock.Net.Client/Program.cs @@ -12,8 +12,8 @@ class Program { static async Task Main(string[] args) { - // Create an implementation of the IFluentMockServerAdmin and pass in the base URL for the API. - var api = RestClient.For("http://localhost:9091"); + // Create an implementation of the IWireMockAdminApi and pass in the base URL for the API. + var api = RestClient.For("http://localhost:9091"); // Set BASIC Auth var value = Convert.ToBase64String(Encoding.ASCII.GetBytes("a:b")); diff --git a/examples/WireMock.Net.Client/WireMock.Net.Client.csproj b/examples/WireMock.Net.Client/WireMock.Net.Client.csproj index 2a23350bc..9f8d88554 100644 --- a/examples/WireMock.Net.Client/WireMock.Net.Client.csproj +++ b/examples/WireMock.Net.Client/WireMock.Net.Client.csproj @@ -8,10 +8,12 @@ - + + + diff --git a/examples/WireMock.Net.Console.NETCoreApp2/WireMock.Net.Console.NETCoreApp2.csproj b/examples/WireMock.Net.Console.NETCoreApp2/WireMock.Net.Console.NETCoreApp2.csproj index 94bd4eecb..83d0db3f8 100644 --- a/examples/WireMock.Net.Console.NETCoreApp2/WireMock.Net.Console.NETCoreApp2.csproj +++ b/examples/WireMock.Net.Console.NETCoreApp2/WireMock.Net.Console.NETCoreApp2.csproj @@ -18,6 +18,10 @@ + + + + diff --git a/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs b/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs index 55bf86f3f..bda9e782e 100644 --- a/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs +++ b/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs @@ -39,7 +39,7 @@ public static void Run() string url2 = "http://localhost:9092/"; string url3 = "https://localhost:9443/"; - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { AllowCSharpCodeMatcher = true, Urls = new[] { url1, url2, url3 }, @@ -64,7 +64,7 @@ public static void Run() // Uncomment below if you want to use the CustomFileSystemFileHandler // FileSystemHandler = new CustomFileSystemFileHandler() }); - System.Console.WriteLine("FluentMockServer listening at {0}", string.Join(",", server.Urls)); + System.Console.WriteLine("WireMockServer listening at {0}", string.Join(",", server.Urls)); server.SetBasicAuthentication("a", "b"); @@ -468,6 +468,7 @@ public static void Run() DateTimeNowToString = DateTime.Now.ToString("s", CultureInfo.InvariantCulture), Guid1 = "{{Random Type=\"Guid\" Uppercase=false}}", Guid2 = "{{Random Type=\"Guid\"}}", + Guid3 = "{{Random Type=\"Guid\" Format=\"X\"}}", Boolean = "{{Random Type=\"Boolean\"}}", Integer = "{{Random Type=\"Integer\" Min=1000 Max=9999}}", Long = "{{#Random Type=\"Long\" Min=10000000 Max=99999999}}{{this}}{{/Random}}", diff --git a/examples/WireMock.Net.Console.Net452.Classic/WireMock.Net.Console.Net452.Classic.csproj b/examples/WireMock.Net.Console.Net452.Classic/WireMock.Net.Console.Net452.Classic.csproj index be9de74e5..98aa3aac0 100644 --- a/examples/WireMock.Net.Console.Net452.Classic/WireMock.Net.Console.Net452.Classic.csproj +++ b/examples/WireMock.Net.Console.Net452.Classic/WireMock.Net.Console.Net452.Classic.csproj @@ -80,9 +80,9 @@ - - {b6269aac-170a-43d5-8b9a-579ded3d9a95} - WireMock.Net.StandAlone + + {b6269aac-170a-4346-8b9a-579ded3d9a94} + WireMock.Net.Abstractions {d3804228-91f4-4502-9595-39584e5a01ad} diff --git a/examples/WireMock.Net.Console.Net461.Classic/WireMock.Net.Console.Net461.Classic.csproj b/examples/WireMock.Net.Console.Net461.Classic/WireMock.Net.Console.Net461.Classic.csproj index dd6ab5a5d..7ed4828b9 100644 --- a/examples/WireMock.Net.Console.Net461.Classic/WireMock.Net.Console.Net461.Classic.csproj +++ b/examples/WireMock.Net.Console.Net461.Classic/WireMock.Net.Console.Net461.Classic.csproj @@ -76,9 +76,9 @@ - - {b6269aac-170a-43d5-8b9a-579ded3d9a95} - WireMock.Net.StandAlone + + {b6269aac-170a-4346-8b9a-579ded3d9a94} + WireMock.Net.Abstractions {d3804228-91f4-4502-9595-39584e5a01ad} diff --git a/examples/WireMock.Net.Console.Proxy.NETCoreApp2/Program.cs b/examples/WireMock.Net.Console.Proxy.NETCoreApp2/Program.cs index dbbfee784..4f1effe9b 100644 --- a/examples/WireMock.Net.Console.Proxy.NETCoreApp2/Program.cs +++ b/examples/WireMock.Net.Console.Proxy.NETCoreApp2/Program.cs @@ -17,7 +17,7 @@ static void Main(string[] args) RunTestDifferentPort().Wait(20000); // prints "1" RunTestDifferentPort().Wait(20000); // prints "1" - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { Urls = new[] { "http://localhost:9091", "https://localhost:9443" }, StartAdminInterface = true, @@ -44,7 +44,7 @@ static void Main(string[] args) private static async Task RunTestDifferentPort() { - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server.Given(Request.Create().WithPath("/").UsingGet()) .RespondWith(Response.Create().WithStatusCode(200).WithBody("Hello")); diff --git a/examples/WireMock.Net.Console.Proxy.NETCoreApp2/WireMock.Net.Console.Proxy.NETCoreApp2.csproj b/examples/WireMock.Net.Console.Proxy.NETCoreApp2/WireMock.Net.Console.Proxy.NETCoreApp2.csproj index 9e382bda5..a02ff1c67 100644 --- a/examples/WireMock.Net.Console.Proxy.NETCoreApp2/WireMock.Net.Console.Proxy.NETCoreApp2.csproj +++ b/examples/WireMock.Net.Console.Proxy.NETCoreApp2/WireMock.Net.Console.Proxy.NETCoreApp2.csproj @@ -11,7 +11,6 @@ - diff --git a/examples/WireMock.Net.Console.Proxy.Net452/Program.cs b/examples/WireMock.Net.Console.Proxy.Net452/Program.cs index d635c91a1..af5cda2b2 100644 --- a/examples/WireMock.Net.Console.Proxy.Net452/Program.cs +++ b/examples/WireMock.Net.Console.Proxy.Net452/Program.cs @@ -11,7 +11,7 @@ class Program static void Main(string[] args) { string[] urls = { "http://localhost:9091/", "https://localhost:9443/" }; - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { Urls = urls, StartAdminInterface = true, diff --git a/examples/WireMock.Net.Console.Proxy.Net452/WireMock.Net.Console.Proxy.Net452.csproj b/examples/WireMock.Net.Console.Proxy.Net452/WireMock.Net.Console.Proxy.Net452.csproj index 56fc21e44..bce35c0ed 100644 --- a/examples/WireMock.Net.Console.Proxy.Net452/WireMock.Net.Console.Proxy.Net452.csproj +++ b/examples/WireMock.Net.Console.Proxy.Net452/WireMock.Net.Console.Proxy.Net452.csproj @@ -92,10 +92,6 @@ - - {b6269aac-170a-43d5-8b9a-579ded3d9a95} - WireMock.Net.StandAlone - {d3804228-91f4-4502-9595-39584e5a01ad} WireMock.Net diff --git a/examples/WireMock.Net.Console.Record.NETCoreApp/Program.cs b/examples/WireMock.Net.Console.Record.NETCoreApp/Program.cs index 0a2e0cab8..3471b9f3a 100644 --- a/examples/WireMock.Net.Console.Record.NETCoreApp/Program.cs +++ b/examples/WireMock.Net.Console.Record.NETCoreApp/Program.cs @@ -8,7 +8,7 @@ static class Program { static void Main(params string[] args) { - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { Urls = new[] { "http://localhost:9091/", "https://localhost:9443/" }, StartAdminInterface = true, diff --git a/examples/WireMock.Net.Service/Program.cs b/examples/WireMock.Net.Service/Program.cs index ae9abdd92..27e096ff5 100644 --- a/examples/WireMock.Net.Service/Program.cs +++ b/examples/WireMock.Net.Service/Program.cs @@ -3,7 +3,6 @@ using System.IO; using System.ServiceProcess; using WireMock.Net.Service; -using WireMock.Net.StandAlone; using WireMock.Server; using WireMock.Settings; @@ -12,7 +11,7 @@ namespace Wiremock.Net.Service public static class Program { #region Nested classes to support running as service - public const string ServiceName = "Wiremock.Net.Service"; + public const string ServiceName = "WireMock.Net.Service"; public class Service : ServiceBase { @@ -33,7 +32,7 @@ protected override void OnStop() } #endregion - private static FluentMockServer _server; + private static WireMockServer _server; static void Main(string[] args) { @@ -64,7 +63,7 @@ static void Main(string[] args) private static void Start() { - _server = StandAloneApp.Start(new FluentMockServerSettings + _server = WireMockServer.Start(new WireMockServerSettings { Urls = new[] { "http://*:9091/" }, StartAdminInterface = true, diff --git a/examples/WireMock.Net.Service/WireMock.Net.Service.csproj b/examples/WireMock.Net.Service/WireMock.Net.Service.csproj index b694d8710..562d95cc4 100644 --- a/examples/WireMock.Net.Service/WireMock.Net.Service.csproj +++ b/examples/WireMock.Net.Service/WireMock.Net.Service.csproj @@ -56,8 +56,8 @@ ..\..\packages\Owin.1.0\lib\net40\Owin.dll - - ..\..\packages\RestEase.1.4.7\lib\net45\RestEase.dll + + ..\..\packages\RestEase.1.4.10\lib\net45\RestEase.dll ..\..\packages\SimMetrics.Net.1.0.5\lib\net45\SimMetrics.Net.dll @@ -121,9 +121,9 @@ - - {b6269aac-170a-43d5-8b9a-579ded3d9a95} - WireMock.Net.StandAlone + + {b6269aac-170a-4346-8b9a-579ded3d9a94} + WireMock.Net.Abstractions {d3804228-91f4-4502-9595-39584e5a01ad} diff --git a/examples/WireMock.Net.Service/WireMockLog4NetLogger.cs b/examples/WireMock.Net.Service/WireMockLog4NetLogger.cs index a1d7be2c8..3b5058663 100644 --- a/examples/WireMock.Net.Service/WireMockLog4NetLogger.cs +++ b/examples/WireMock.Net.Service/WireMockLog4NetLogger.cs @@ -1,8 +1,8 @@ using log4net; using Newtonsoft.Json; using Wiremock.Net.Service; -using WireMock.Admin.Requests; using WireMock.Logging; +using WireMock.Models.Requests; namespace WireMock.Net.Service { diff --git a/examples/WireMock.Net.Service/packages.config b/examples/WireMock.Net.Service/packages.config index e0ea0153b..af593ee6e 100644 --- a/examples/WireMock.Net.Service/packages.config +++ b/examples/WireMock.Net.Service/packages.config @@ -12,7 +12,7 @@ - + diff --git a/examples/WireMock.Net.StandAlone.NETCoreApp/Program.cs b/examples/WireMock.Net.StandAlone.NETCoreApp/Program.cs index 8d1cffdf5..2af771983 100644 --- a/examples/WireMock.Net.StandAlone.NETCoreApp/Program.cs +++ b/examples/WireMock.Net.StandAlone.NETCoreApp/Program.cs @@ -1,11 +1,13 @@ using System; using System.IO; +using System.Linq; using System.Reflection; using System.Threading; using log4net; using log4net.Config; using log4net.Repository; using WireMock.Server; +using WireMock.Settings; namespace WireMock.Net.StandAlone.NETCoreApp { @@ -15,13 +17,16 @@ static class Program // private static readonly ILog Log = LogManager.GetLogger(typeof(Program)); private static int sleepTime = 30000; - private static FluentMockServer _server; + private static WireMockServer _server; static void Main(string[] args) { XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config")); - _server = StandAloneApp.Start(args, new WireMockLog4NetLogger()); + var settings = WireMockServerSettingsParser.ParseArguments(args, new WireMockLog4NetLogger()); + settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'"))); + + _server = WireMockServer.Start(settings); Console.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down"); diff --git a/examples/WireMock.Net.StandAlone.NETCoreApp/WireMock.Net.StandAlone.NETCoreApp.csproj b/examples/WireMock.Net.StandAlone.NETCoreApp/WireMock.Net.StandAlone.NETCoreApp.csproj index 8dc82ad6a..a240bad70 100644 --- a/examples/WireMock.Net.StandAlone.NETCoreApp/WireMock.Net.StandAlone.NETCoreApp.csproj +++ b/examples/WireMock.Net.StandAlone.NETCoreApp/WireMock.Net.StandAlone.NETCoreApp.csproj @@ -12,7 +12,8 @@ - + + diff --git a/examples/WireMock.Net.StandAlone.NETCoreApp/WireMockLog4NetLogger.cs b/examples/WireMock.Net.StandAlone.NETCoreApp/WireMockLog4NetLogger.cs index 354128a02..033894bb7 100644 --- a/examples/WireMock.Net.StandAlone.NETCoreApp/WireMockLog4NetLogger.cs +++ b/examples/WireMock.Net.StandAlone.NETCoreApp/WireMockLog4NetLogger.cs @@ -1,7 +1,7 @@ using log4net; using Newtonsoft.Json; -using WireMock.Admin.Requests; using WireMock.Logging; +using WireMock.Models.Requests; namespace WireMock.Net.StandAlone.NETCoreApp { diff --git a/examples/WireMock.Net.StandAlone.Net452/Program.cs b/examples/WireMock.Net.StandAlone.Net452/Program.cs index 69d444e4c..83240774d 100644 --- a/examples/WireMock.Net.StandAlone.Net452/Program.cs +++ b/examples/WireMock.Net.StandAlone.Net452/Program.cs @@ -1,6 +1,9 @@ using System; using System.IO; +using System.Linq; using log4net.Config; +using WireMock.Server; +using WireMock.Settings; namespace WireMock.Net.StandAlone.Net452 { @@ -10,7 +13,10 @@ static void Main(params string[] args) { XmlConfigurator.Configure(new FileInfo("log4net.config")); - StandAloneApp.Start(args); + var settings = WireMockServerSettingsParser.ParseArguments(args); + settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'"))); + + WireMockServer.Start(settings); Console.WriteLine("Press any key to stop the server"); Console.ReadKey(); diff --git a/examples/WireMock.Net.StandAlone.Net452/WireMock.Net.StandAlone.Net452.csproj b/examples/WireMock.Net.StandAlone.Net452/WireMock.Net.StandAlone.Net452.csproj index e78379905..3ed45e968 100644 --- a/examples/WireMock.Net.StandAlone.Net452/WireMock.Net.StandAlone.Net452.csproj +++ b/examples/WireMock.Net.StandAlone.Net452/WireMock.Net.StandAlone.Net452.csproj @@ -70,9 +70,9 @@ - - {b6269aac-170a-43d5-8b9a-579ded3d9a95} - WireMock.Net.StandAlone + + {b6269aac-170a-4346-8b9a-579ded3d9a94} + WireMock.Net.Abstractions {d3804228-91f4-4502-9595-39584e5a01ad} diff --git a/examples/WireMock.Net.StandAlone.Net461/Program.cs b/examples/WireMock.Net.StandAlone.Net461/Program.cs index bff20030b..72787ce14 100644 --- a/examples/WireMock.Net.StandAlone.Net461/Program.cs +++ b/examples/WireMock.Net.StandAlone.Net461/Program.cs @@ -1,6 +1,7 @@ using System; -using WireMock.RequestBuilders; -using WireMock.ResponseBuilders; +using System.Linq; +using WireMock.Server; +using WireMock.Settings; namespace WireMock.Net.StandAlone.Net461 { @@ -8,9 +9,10 @@ static class Program { static void Main(string[] args) { - var server = StandAloneApp.Start(args); - server.Given(Request.Create()) - .RespondWith(Response.Create().WithProxy("http://10.10.66.65")); + var settings = WireMockServerSettingsParser.ParseArguments(args); + settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'"))); + + WireMockServer.Start(settings); Console.WriteLine("Press any key to stop the server"); Console.ReadKey(); diff --git a/examples/WireMock.Net.StandAlone.Net461/WireMock.Net.StandAlone.Net461.csproj b/examples/WireMock.Net.StandAlone.Net461/WireMock.Net.StandAlone.Net461.csproj index 4a9309c97..dfdc782fc 100644 --- a/examples/WireMock.Net.StandAlone.Net461/WireMock.Net.StandAlone.Net461.csproj +++ b/examples/WireMock.Net.StandAlone.Net461/WireMock.Net.StandAlone.Net461.csproj @@ -204,8 +204,8 @@ ..\..\packages\Owin.1.0\lib\net40\Owin.dll - - ..\..\packages\RestEase.1.4.7\lib\net45\RestEase.dll + + ..\..\packages\RestEase.1.4.10\lib\net45\RestEase.dll ..\..\packages\SimMetrics.Net.1.0.5\lib\net45\SimMetrics.Net.dll @@ -231,6 +231,7 @@ ..\..\packages\System.Memory.4.5.1\lib\netstandard2.0\System.Memory.dll + ..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.4\lib\net45\System.Net.Http.Formatting.dll @@ -279,12 +280,6 @@ - - ..\..\packages\WireMock.Net.1.0.4.20\lib\net461\WireMock.Net.dll - - - ..\..\packages\WireMock.Net.StandAlone.1.0.4.20\lib\net46\WireMock.Net.StandAlone.dll - ..\..\packages\XPath2.1.0.6.1\lib\net40\XPath2.dll @@ -301,6 +296,16 @@ Designer + + + {b6269aac-170a-4346-8b9a-579ded3d9a94} + WireMock.Net.Abstractions + + + {D3804228-91F4-4502-9595-39584E5A01AD} + WireMock.Net + + diff --git a/examples/WireMock.Net.StandAlone.Net461/packages.config b/examples/WireMock.Net.StandAlone.Net461/packages.config index 679c143cd..e824a2bfc 100644 --- a/examples/WireMock.Net.StandAlone.Net461/packages.config +++ b/examples/WireMock.Net.StandAlone.Net461/packages.config @@ -59,7 +59,7 @@ - + @@ -78,7 +78,5 @@ - - \ No newline at end of file diff --git a/examples/WireMock.Net.WebApplication/Program.cs b/examples/WireMock.Net.WebApplication/Program.cs index 582494f71..ad5f0b2f6 100644 --- a/examples/WireMock.Net.WebApplication/Program.cs +++ b/examples/WireMock.Net.WebApplication/Program.cs @@ -43,9 +43,9 @@ private static void ConfigureServices(IServiceCollection serviceCollection) // Add access to generic IConfigurationRoot serviceCollection.AddSingleton(configuration); - // Add access to IFluentMockServerSettings - var settings = configuration.GetSection("FluentMockServerSettings").Get(); - serviceCollection.AddSingleton(settings); + // Add access to WireMockServerSettings + var settings = configuration.GetSection("WireMockServerSettings").Get(); + serviceCollection.AddSingleton(settings); // Add services serviceCollection.AddTransient(); diff --git a/examples/WireMock.Net.WebApplication/WireMock.Net.WebApplication.NETCore2.csproj b/examples/WireMock.Net.WebApplication/WireMock.Net.WebApplication.NETCore2.csproj index bdfc3416e..5485f7d95 100644 --- a/examples/WireMock.Net.WebApplication/WireMock.Net.WebApplication.NETCore2.csproj +++ b/examples/WireMock.Net.WebApplication/WireMock.Net.WebApplication.NETCore2.csproj @@ -22,7 +22,7 @@ - + diff --git a/examples/WireMock.Net.WebApplication/WireMockService.cs b/examples/WireMock.Net.WebApplication/WireMockService.cs index 97dfb5d9c..486f25b08 100644 --- a/examples/WireMock.Net.WebApplication/WireMockService.cs +++ b/examples/WireMock.Net.WebApplication/WireMockService.cs @@ -1,9 +1,9 @@ using System.Threading; using Microsoft.Extensions.Logging; using Newtonsoft.Json; -using WireMock.Admin.Requests; using WireMock.Logging; -using WireMock.Net.StandAlone; +using WireMock.Models.Requests; +using WireMock.Server; using WireMock.Settings; namespace WireMock.Net.WebApplication @@ -13,7 +13,7 @@ public class WireMockService : IWireMockService private static int sleepTime = 30000; private readonly ILogger _logger; - private readonly IFluentMockServerSettings _settings; + private readonly WireMockServerSettings _settings; private class Logger : IWireMockLogger { @@ -51,7 +51,7 @@ public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminreques } } - public WireMockService(ILogger logger, IFluentMockServerSettings settings) + public WireMockService(ILogger logger, WireMockServerSettings settings) { _logger = logger; _settings = settings; @@ -63,7 +63,7 @@ public void Run() { _logger.LogInformation("WireMock.Net server starting"); - StandAloneApp.Start(_settings); + WireMockServer.Start(_settings); _logger.LogInformation($"WireMock.Net server settings {JsonConvert.SerializeObject(_settings)}"); diff --git a/examples/WireMock.Net.WebApplication/appsettings.json b/examples/WireMock.Net.WebApplication/appsettings.json index dd16180ef..4b33bb6af 100644 --- a/examples/WireMock.Net.WebApplication/appsettings.json +++ b/examples/WireMock.Net.WebApplication/appsettings.json @@ -12,7 +12,7 @@ } } }, - "FluentMockServerSettings": { + "WireMockServerSettings": { "AdminUsername": "a", "AdminPassword": "b", "StartAdminInterface": true diff --git a/src/WireMock.Net/Admin/Mappings/BodyModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/BodyModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/BodyModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/BodyModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/ClientIPModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/ClientIPModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/ClientIPModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/ClientIPModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/CookieModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/CookieModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/CookieModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/CookieModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/EncodingModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/EncodingModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/EncodingModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/EncodingModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/FaultModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/FaultModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/FaultModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/FaultModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/HeaderModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/HeaderModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/HeaderModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/HeaderModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/MappingModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/MappingModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/MappingModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/MappingModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/MatcherModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/MatcherModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/MatcherModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/MatcherModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/ParamModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/ParamModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/ParamModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/ParamModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/PathModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/PathModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/PathModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/PathModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/RequestModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/RequestModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/RequestModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/RequestModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/ResponseModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/ResponseModel.cs similarity index 95% rename from src/WireMock.Net/Admin/Mappings/ResponseModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/ResponseModel.cs index e9c831b48..1c73ff556 100644 --- a/src/WireMock.Net/Admin/Mappings/ResponseModel.cs +++ b/src/WireMock.Net.Abstractions/Admin/Mappings/ResponseModel.cs @@ -22,11 +22,6 @@ public class ResponseModel /// public string Body { get; set; } - /// - /// Gets or sets the body. - /// - public string BodyFromBase64 { get; set; } - /// /// Gets or sets the body (as JSON object). /// diff --git a/src/WireMock.Net/Admin/Mappings/StatusModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/StatusModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/StatusModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/StatusModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/UrlModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/UrlModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/UrlModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/UrlModel.cs diff --git a/src/WireMock.Net/Admin/Mappings/WebProxyModel.cs b/src/WireMock.Net.Abstractions/Admin/Mappings/WebProxyModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Mappings/WebProxyModel.cs rename to src/WireMock.Net.Abstractions/Admin/Mappings/WebProxyModel.cs diff --git a/src/WireMock.Net/Admin/Requests/LogEntryModel.cs b/src/WireMock.Net.Abstractions/Admin/Requests/LogEntryModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Requests/LogEntryModel.cs rename to src/WireMock.Net.Abstractions/Admin/Requests/LogEntryModel.cs diff --git a/src/WireMock.Net/Admin/Requests/LogRequestMatchModel.cs b/src/WireMock.Net.Abstractions/Admin/Requests/LogRequestMatchModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Requests/LogRequestMatchModel.cs rename to src/WireMock.Net.Abstractions/Admin/Requests/LogRequestMatchModel.cs diff --git a/src/WireMock.Net/Admin/Requests/LogRequestModel.cs b/src/WireMock.Net.Abstractions/Admin/Requests/LogRequestModel.cs similarity index 99% rename from src/WireMock.Net/Admin/Requests/LogRequestModel.cs rename to src/WireMock.Net.Abstractions/Admin/Requests/LogRequestModel.cs index 0a926377e..e63eb76d8 100644 --- a/src/WireMock.Net/Admin/Requests/LogRequestModel.cs +++ b/src/WireMock.Net.Abstractions/Admin/Requests/LogRequestModel.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using WireMock.Admin.Mappings; -using WireMock.Util; +using WireMock.Types; namespace WireMock.Admin.Requests { diff --git a/src/WireMock.Net/Admin/Requests/LogResponseModel.cs b/src/WireMock.Net.Abstractions/Admin/Requests/LogResponseModel.cs similarity index 99% rename from src/WireMock.Net/Admin/Requests/LogResponseModel.cs rename to src/WireMock.Net.Abstractions/Admin/Requests/LogResponseModel.cs index 3986ee56d..61ec80568 100644 --- a/src/WireMock.Net/Admin/Requests/LogResponseModel.cs +++ b/src/WireMock.Net.Abstractions/Admin/Requests/LogResponseModel.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; using WireMock.Admin.Mappings; -using WireMock.Util; +using WireMock.Types; namespace WireMock.Admin.Requests { diff --git a/src/WireMock.Net/Admin/Scenarios/ScenarioStateModel.cs b/src/WireMock.Net.Abstractions/Admin/Scenarios/ScenarioStateModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Scenarios/ScenarioStateModel.cs rename to src/WireMock.Net.Abstractions/Admin/Scenarios/ScenarioStateModel.cs diff --git a/src/WireMock.Net/Admin/Settings/SettingsModel.cs b/src/WireMock.Net.Abstractions/Admin/Settings/SettingsModel.cs similarity index 100% rename from src/WireMock.Net/Admin/Settings/SettingsModel.cs rename to src/WireMock.Net.Abstractions/Admin/Settings/SettingsModel.cs diff --git a/src/WireMock.Net/Handlers/IFileSystemHandler.cs b/src/WireMock.Net.Abstractions/Handlers/IFileSystemHandler.cs similarity index 100% rename from src/WireMock.Net/Handlers/IFileSystemHandler.cs rename to src/WireMock.Net.Abstractions/Handlers/IFileSystemHandler.cs diff --git a/src/WireMock.Net/Logging/IWireMockLogger.cs b/src/WireMock.Net.Abstractions/Logging/IWireMockLogger.cs similarity index 100% rename from src/WireMock.Net/Logging/IWireMockLogger.cs rename to src/WireMock.Net.Abstractions/Logging/IWireMockLogger.cs diff --git a/src/WireMock.Net/Util/BodyType.cs b/src/WireMock.Net.Abstractions/Types/BodyType.cs similarity index 95% rename from src/WireMock.Net/Util/BodyType.cs rename to src/WireMock.Net.Abstractions/Types/BodyType.cs index 6c8d2e05d..d90f34fb9 100644 --- a/src/WireMock.Net/Util/BodyType.cs +++ b/src/WireMock.Net.Abstractions/Types/BodyType.cs @@ -1,4 +1,4 @@ -namespace WireMock.Util +namespace WireMock.Types { /// /// The BodyType diff --git a/src/WireMock.Net/Util/WireMockList.cs b/src/WireMock.Net.Abstractions/Types/WireMockList.cs similarity index 98% rename from src/WireMock.Net/Util/WireMockList.cs rename to src/WireMock.Net.Abstractions/Types/WireMockList.cs index 64812e9d0..d85e51dc5 100644 --- a/src/WireMock.Net/Util/WireMockList.cs +++ b/src/WireMock.Net.Abstractions/Types/WireMockList.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -namespace WireMock.Util +namespace WireMock.Types { /// /// A special List which overrides the ToString() to return first value. diff --git a/src/WireMock.Net.Abstractions/WireMock.Net.Abstractions.csproj b/src/WireMock.Net.Abstractions/WireMock.Net.Abstractions.csproj new file mode 100644 index 000000000..85b1b2faa --- /dev/null +++ b/src/WireMock.Net.Abstractions/WireMock.Net.Abstractions.csproj @@ -0,0 +1,46 @@ + + + + Commonly used interfaces, models, enumerations and types. + WireMock.Net.Abstractions + Stef Heyenrath + netstandard1.0;netstandard2.0;net45 + true + WireMock.Net.Abstractions + WireMock.Net.Abstractions + wiremock;interfaces;models;classes;enumerations;types + See CHANGELOG.md + https://raw.githubusercontent.com/WireMock-Net/WireMock.Net/master/WireMock.Net-Logo.png + https://github.com/WireMock-Net/WireMock.Net + MIT + git + https://github.com/WireMock-Net/WireMock.Net + ../../WireMock.Net-Logo.ico + WireMock + + {B6269AAC-170A-4346-8B9A-579DED3D9A94} + true + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + true + true + ../WireMock.Net/WireMock.Net.ruleset + true + ../WireMock.Net/WireMock.Net.snk + + true + + + + $(MSBuildProjectDirectory)=/ + + + + + + all + + + + \ No newline at end of file diff --git a/src/WireMock.Net/Client/IFluentMockServerAdmin.cs b/src/WireMock.Net.RestClient/IWireMockAdminApi.cs similarity index 84% rename from src/WireMock.Net/Client/IFluentMockServerAdmin.cs rename to src/WireMock.Net.RestClient/IWireMockAdminApi.cs index 1328a906d..17c67f413 100644 --- a/src/WireMock.Net/Client/IFluentMockServerAdmin.cs +++ b/src/WireMock.Net.RestClient/IWireMockAdminApi.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using WireMock.Admin.Mappings; using WireMock.Admin.Requests; +using WireMock.Admin.Scenarios; using WireMock.Admin.Settings; namespace WireMock.Client @@ -12,7 +13,8 @@ namespace WireMock.Client /// /// The RestEase interface which defines all admin commands. /// - public interface IFluentMockServerAdmin + [BasePath("__admin")] + public interface IWireMockAdminApi { /// /// Authentication header @@ -24,14 +26,14 @@ public interface IFluentMockServerAdmin /// Get the settings. /// /// SettingsModel - [Get("__admin/settings")] + [Get("settings")] Task GetSettingsAsync(); /// /// Update the settings. /// /// SettingsModel - [Put("__admin/settings")] + [Put("settings")] [Header("Content-Type", "application/json")] Task PutSettingsAsync([Body] SettingsModel settings); @@ -39,7 +41,7 @@ public interface IFluentMockServerAdmin /// Update the settings /// /// SettingsModel - [Post("__admin/settings")] + [Post("settings")] [Header("Content-Type", "application/json")] Task PostSettingsAsync([Body] SettingsModel settings); @@ -47,14 +49,14 @@ public interface IFluentMockServerAdmin /// Get the mappings. /// /// MappingModels - [Get("__admin/mappings")] + [Get("mappings")] Task> GetMappingsAsync(); /// /// Add a new mapping. /// /// MappingModel - [Post("__admin/mappings")] + [Post("mappings")] [Header("Content-Type", "application/json")] Task PostMappingAsync([Body] MappingModel mapping); @@ -62,14 +64,14 @@ public interface IFluentMockServerAdmin /// Add new mappings. /// /// MappingModels - [Post("__admin/mappings")] + [Post("mappings")] [Header("Content-Type", "application/json")] Task PostMappingsAsync([Body] IList mappings); /// /// Delete all mappings. /// - [Delete("__admin/mappings")] + [Delete("mappings")] Task DeleteMappingsAsync(); /// @@ -84,7 +86,7 @@ public interface IFluentMockServerAdmin /// /// The Guid /// MappingModel - [Get("__admin/mappings/{guid}")] + [Get("mappings/{guid}")] Task GetMappingAsync([Path] Guid guid); /// @@ -92,7 +94,7 @@ public interface IFluentMockServerAdmin /// /// The Guid /// MappingModel - [Put("__admin/mappings/{guid}")] + [Put("mappings/{guid}")] [Header("Content-Type", "application/json")] Task PutMappingAsync([Path] Guid guid, [Body] MappingModel mapping); @@ -100,32 +102,32 @@ public interface IFluentMockServerAdmin /// Delete a mapping based on the guid /// /// The Guid - [Delete("__admin/mappings/{guid}")] + [Delete("mappings/{guid}")] Task DeleteMappingAsync([Path] Guid guid); /// /// Save the mappings /// - [Post("__admin/mappings/save")] + [Post("mappings/save")] Task SaveMappingAsync(); /// /// Get the requests. /// /// LogRequestModels - [Get("__admin/requests")] + [Get("requests")] Task> GetRequestsAsync(); /// /// Delete all requests. /// - [Delete("__admin/requests")] + [Delete("requests")] Task DeleteRequestsAsync(); /// /// Delete (reset) all requests. /// - [Post("__admin/requests/reset")] + [Post("requests/reset")] Task ResetRequestsAsync(); /// @@ -133,40 +135,40 @@ public interface IFluentMockServerAdmin /// /// The Guid /// MappingModel - [Get("__admin/requests/{guid}")] + [Get("requests/{guid}")] Task GetRequestAsync([Path] Guid guid); /// /// Delete a request based on the guid /// /// The Guid - [Delete("__admin/requests/{guid}")] + [Delete("requests/{guid}")] Task DeleteRequestAsync([Path] Guid guid); /// /// Find a request based on the criteria /// /// The RequestModel - [Post("__admin/requests/find")] + [Post("requests/find")] [Header("Content-Type", "application/json")] Task> FindRequestsAsync([Body] RequestModel model); /// /// Get all scenarios /// - [Get("__admin/scenarios")] - Task> GetScenariosAsync(); + [Get("scenarios")] + Task> GetScenariosAsync(); /// /// Delete (reset) all scenarios /// - [Delete("__admin/scenarios")] + [Delete("scenarios")] Task DeleteScenariosAsync(); /// /// Delete (reset) all scenarios /// - [Post("__admin/scenarios")] + [Post("scenarios")] Task ResetScenariosAsync(); /// @@ -174,7 +176,7 @@ public interface IFluentMockServerAdmin /// /// The filename /// The body - [Post("__admin/files/{filename}")] + [Post("files/{filename}")] Task PostFileAsync([Path] string filename, [Body] string body); /// @@ -182,28 +184,28 @@ public interface IFluentMockServerAdmin /// /// The filename /// The body - [Put("__admin/files/{filename}")] + [Put("files/{filename}")] Task PutFileAsync([Path] string filename, [Body] string body); /// /// Get the content of an existing File /// /// The filename - [Get("__admin/files/{filename}")] + [Get("files/{filename}")] Task GetFileAsync([Path] string filename); /// /// Delete an existing File /// /// The filename - [Delete("__admin/files/{filename}")] + [Delete("files/{filename}")] Task DeleteFileAsync([Path] string filename); /// /// Check if a file exists /// /// The filename - [Head("__admin/files/{filename}")] + [Head("files/{filename}")] Task FileExistsAsync([Path] string filename); } } \ No newline at end of file diff --git a/src/WireMock.Net.RestClient/WireMock.Net.RestClient.csproj b/src/WireMock.Net.RestClient/WireMock.Net.RestClient.csproj new file mode 100644 index 000000000..5981f8a2b --- /dev/null +++ b/src/WireMock.Net.RestClient/WireMock.Net.RestClient.csproj @@ -0,0 +1,48 @@ + + + + A RestClient using RestEase to access the admin interface. + WireMock.Net.RestClient + Stef Heyenrath + netstandard1.1;netstandard2.0;net45 + true + WireMock.Net.RestClient + WireMock.Net.RestClient + wiremock;rest;client;restclient;restease;rest;json + See CHANGELOG.md + https://raw.githubusercontent.com/WireMock-Net/WireMock.Net/master/WireMock.Net-Logo.png + https://github.com/WireMock-Net/WireMock.Net + MIT + git + https://github.com/WireMock-Net/WireMock.Net + ../../WireMock.Net-Logo.ico + WireMock.Client + + {B6269AAC-170A-43D6-8B9A-579DED3D9A96} + true + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + true + true + ../WireMock.Net/WireMock.Net.ruleset + true + ../WireMock.Net/WireMock.Net.snk + + true + + + + $(MSBuildProjectDirectory)=/ + true + + + + + + + + + + + \ No newline at end of file diff --git a/src/WireMock.Net.StandAlone/StandAloneApp.cs b/src/WireMock.Net.StandAlone/StandAloneApp.cs index 21c597c6f..0c8cf1ce3 100644 --- a/src/WireMock.Net.StandAlone/StandAloneApp.cs +++ b/src/WireMock.Net.StandAlone/StandAloneApp.cs @@ -17,11 +17,11 @@ public static class StandAloneApp /// /// The FluentMockServerSettings [PublicAPI] - public static FluentMockServer Start([NotNull] IFluentMockServerSettings settings) + public static WireMockServer Start([NotNull] FluentMockServerSettings settings) { Check.NotNull(settings, nameof(settings)); - var server = FluentMockServer.Start(settings); + var server = WireMockServer.Start(settings); settings.Logger.Info("WireMock.Net server listening at {0}", string.Join(",", server.Urls)); @@ -34,73 +34,11 @@ public static FluentMockServer Start([NotNull] IFluentMockServerSettings setting /// The commandline arguments /// The logger [PublicAPI] - public static FluentMockServer Start([NotNull] string[] args, [CanBeNull] IWireMockLogger logger = null) + public static WireMockServer Start([NotNull] string[] args, [CanBeNull] IWireMockLogger logger = null) { Check.NotNull(args, nameof(args)); - var parser = new SimpleCommandLineParser(); - parser.Parse(args); - - var settings = new FluentMockServerSettings - { - StartAdminInterface = parser.GetBoolValue("StartAdminInterface", true), - ReadStaticMappings = parser.GetBoolValue("ReadStaticMappings"), - WatchStaticMappings = parser.GetBoolValue("WatchStaticMappings"), - WatchStaticMappingsInSubdirectories = parser.GetBoolValue("WatchStaticMappingsInSubdirectories"), - AllowPartialMapping = parser.GetBoolValue("AllowPartialMapping"), - AdminUsername = parser.GetStringValue("AdminUsername"), - AdminPassword = parser.GetStringValue("AdminPassword"), - MaxRequestLogCount = parser.GetIntValue("MaxRequestLogCount"), - RequestLogExpirationDuration = parser.GetIntValue("RequestLogExpirationDuration"), - AllowCSharpCodeMatcher = parser.GetBoolValue("AllowCSharpCodeMatcher"), - AllowBodyForAllHttpMethods = parser.GetBoolValue("AllowBodyForAllHttpMethods") - }; - - if (logger != null) - { - settings.Logger = logger; - } - - if (parser.GetStringValue("WireMockLogger") == "WireMockConsoleLogger") - { - settings.Logger = new WireMockConsoleLogger(); - } - - if (parser.Contains("Port")) - { - settings.Port = parser.GetIntValue("Port"); - } - else - { - settings.Urls = parser.GetValues("Urls", new[] { "http://*:9091/" }); - } - - string proxyURL = parser.GetStringValue("ProxyURL"); - if (!string.IsNullOrEmpty(proxyURL)) - { - settings.ProxyAndRecordSettings = new ProxyAndRecordSettings - { - Url = proxyURL, - SaveMapping = parser.GetBoolValue("SaveMapping"), - SaveMappingToFile = parser.GetBoolValue("SaveMappingToFile"), - SaveMappingForStatusCodePattern = parser.GetStringValue("SaveMappingForStatusCodePattern"), - ClientX509Certificate2ThumbprintOrSubjectName = parser.GetStringValue("ClientX509Certificate2ThumbprintOrSubjectName"), - BlackListedHeaders = parser.GetValues("BlackListedHeaders"), - BlackListedCookies = parser.GetValues("BlackListedCookies"), - AllowAutoRedirect = parser.GetBoolValue("AllowAutoRedirect") - }; - - string proxyAddress = parser.GetStringValue("WebProxyAddress"); - if (!string.IsNullOrEmpty(proxyAddress)) - { - settings.ProxyAndRecordSettings.WebProxySettings = new WebProxySettings - { - Address = proxyAddress, - UserName = parser.GetStringValue("WebProxyUserName"), - Password = parser.GetStringValue("WebProxyPassword") - }; - } - } + var settings = (FluentMockServerSettings) WireMockServerSettingsParser.ParseArguments(args); settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'"))); diff --git a/src/WireMock.Net.StandAlone/WireMock.Net.StandAlone.csproj b/src/WireMock.Net.StandAlone/WireMock.Net.StandAlone.csproj index 451f9c483..eb5acdacd 100644 --- a/src/WireMock.Net.StandAlone/WireMock.Net.StandAlone.csproj +++ b/src/WireMock.Net.StandAlone/WireMock.Net.StandAlone.csproj @@ -1,61 +1,60 @@ - - - Lightweight StandAlone Http Mocking Server for .Net. - WireMock.Net.StandAlone - Stef Heyenrath - - net451;net452;net46;net461;netstandard1.3;netstandard2.0 - true - WireMock.Net.StandAlone - WireMock.Net.StandAlone - tdd;mock;http;wiremock;test;server;unittest - See CHANGELOG.md - https://raw.githubusercontent.com/WireMock-Net/WireMock.Net/master/WireMock.Net-Logo.png - https://github.com/WireMock-Net/WireMock.Net - MIT - git - https://github.com/WireMock-Net/WireMock.Net - ../../WireMock.Net-Logo.ico - WireMock.Net.StandAlone - - {B6269AAC-170A-43D5-8B9A-579DED3D9A95} - true - $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb - true - true - WireMock.Net.StandAlone.ruleset - true - ../WireMock.Net/WireMock.Net.snk - - true - - - - $(MSBuildProjectDirectory)=/ - true - - - - NETSTANDARD;USE_ASPNETCORE - - - - USE_ASPNETCORE;NET46 - - - - - All - - - all - runtime; build; native; contentfiles; analyzers - - - - - - + + + Lightweight StandAlone Http Mocking Server for .Net. + WireMock.Net.StandAlone + Stef Heyenrath + net451;net452;net46;net461;netstandard1.3;netstandard2.0 + true + WireMock.Net.StandAlone + WireMock.Net.StandAlone + tdd;mock;http;wiremock;test;server;unittest + See CHANGELOG.md + https://raw.githubusercontent.com/WireMock-Net/WireMock.Net/master/WireMock.Net-Logo.png + https://github.com/WireMock-Net/WireMock.Net + MIT + git + https://github.com/WireMock-Net/WireMock.Net + ../../WireMock.Net-Logo.ico + WireMock.Net.StandAlone + + {B6269AAC-170A-43D5-8B9A-579DED3D9A95} + true + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + true + true + WireMock.Net.StandAlone.ruleset + true + ../WireMock.Net/WireMock.Net.snk + + true + + + + $(MSBuildProjectDirectory)=/ + true + + + + NETSTANDARD;USE_ASPNETCORE + + + + USE_ASPNETCORE;NET46 + + + + + All + + + all + runtime; build; native; contentfiles; analyzers + + + + + + \ No newline at end of file diff --git a/src/WireMock.Net/Http/HttpRequestMessageHelper.cs b/src/WireMock.Net/Http/HttpRequestMessageHelper.cs index 456a3bd29..ba86beadf 100644 --- a/src/WireMock.Net/Http/HttpRequestMessageHelper.cs +++ b/src/WireMock.Net/Http/HttpRequestMessageHelper.cs @@ -1,11 +1,11 @@ -using System; +using JetBrains.Annotations; +using Newtonsoft.Json; +using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; -using JetBrains.Annotations; -using Newtonsoft.Json; -using WireMock.Util; +using WireMock.Types; using WireMock.Validation; namespace WireMock.Http diff --git a/src/WireMock.Net/IMapping.cs b/src/WireMock.Net/IMapping.cs index 0f92cfaef..8da094c4d 100644 --- a/src/WireMock.Net/IMapping.cs +++ b/src/WireMock.Net/IMapping.cs @@ -62,9 +62,9 @@ public interface IMapping IResponseProvider Provider { get; } /// - /// The FluentMockServerSettings. + /// The WireMockServerSettings. /// - IFluentMockServerSettings Settings { get; } + IWireMockServerSettings Settings { get; } /// /// Is State started ? diff --git a/src/WireMock.Net/Logging/WireMockConsoleLogger.cs b/src/WireMock.Net/Logging/WireMockConsoleLogger.cs index ea38fffc4..51dc8c838 100644 --- a/src/WireMock.Net/Logging/WireMockConsoleLogger.cs +++ b/src/WireMock.Net/Logging/WireMockConsoleLogger.cs @@ -1,5 +1,5 @@ -using System; -using Newtonsoft.Json; +using Newtonsoft.Json; +using System; using WireMock.Admin.Requests; namespace WireMock.Logging diff --git a/src/WireMock.Net/Mapping.cs b/src/WireMock.Net/Mapping.cs index 81ebaa14d..343c5efdc 100644 --- a/src/WireMock.Net/Mapping.cs +++ b/src/WireMock.Net/Mapping.cs @@ -1,6 +1,6 @@ -using JetBrains.Annotations; -using System; +using System; using System.Threading.Tasks; +using JetBrains.Annotations; using WireMock.Matchers.Request; using WireMock.ResponseProviders; using WireMock.Settings; @@ -40,7 +40,7 @@ public class Mapping : IMapping public IResponseProvider Provider { get; } /// - public IFluentMockServerSettings Settings { get; } + public IWireMockServerSettings Settings { get; } /// public bool IsStartState => Scenario == null || Scenario != null && NextState != null && ExecutionConditionState == null; @@ -57,7 +57,7 @@ public class Mapping : IMapping /// The unique identifier. /// The unique title (can be null). /// The full file path from this mapping title (can be null). - /// The FluentMockServerSettings. + /// The WireMockServerSettings. /// The request matcher. /// The provider. /// The priority for this mapping. @@ -65,7 +65,7 @@ public class Mapping : IMapping /// State in which the current mapping can occur. [Optional] /// The next state which will occur after the current mapping execution. [Optional] public Mapping(Guid guid, [CanBeNull] string title, [CanBeNull] string path, - [NotNull] IFluentMockServerSettings settings, [NotNull] IRequestMatcher requestMatcher, [NotNull] IResponseProvider provider, + [NotNull] IWireMockServerSettings settings, [NotNull] IRequestMatcher requestMatcher, [NotNull] IResponseProvider provider, int priority, [CanBeNull] string scenario, [CanBeNull] string executionConditionState, [CanBeNull] string nextState) { Guid = guid; diff --git a/src/WireMock.Net/Matchers/Request/RequestMessageBodyMatcher.cs b/src/WireMock.Net/Matchers/Request/RequestMessageBodyMatcher.cs index b73e7e3a7..c22349962 100644 --- a/src/WireMock.Net/Matchers/Request/RequestMessageBodyMatcher.cs +++ b/src/WireMock.Net/Matchers/Request/RequestMessageBodyMatcher.cs @@ -1,7 +1,7 @@ using JetBrains.Annotations; using System; using System.Linq; -using WireMock.Util; +using WireMock.Types; using WireMock.Validation; namespace WireMock.Matchers.Request diff --git a/src/WireMock.Net/Matchers/Request/RequestMessageHeaderMatcher.cs b/src/WireMock.Net/Matchers/Request/RequestMessageHeaderMatcher.cs index d60c30fd7..c0b6ceba0 100644 --- a/src/WireMock.Net/Matchers/Request/RequestMessageHeaderMatcher.cs +++ b/src/WireMock.Net/Matchers/Request/RequestMessageHeaderMatcher.cs @@ -1,8 +1,8 @@ -using System; +using JetBrains.Annotations; +using System; using System.Collections.Generic; using System.Linq; -using JetBrains.Annotations; -using WireMock.Util; +using WireMock.Types; using WireMock.Validation; namespace WireMock.Matchers.Request diff --git a/src/WireMock.Net/Matchers/Request/RequestMessageParamMatcher.cs b/src/WireMock.Net/Matchers/Request/RequestMessageParamMatcher.cs index 603bf9804..db4860638 100644 --- a/src/WireMock.Net/Matchers/Request/RequestMessageParamMatcher.cs +++ b/src/WireMock.Net/Matchers/Request/RequestMessageParamMatcher.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Linq; -using WireMock.Util; +using WireMock.Types; using WireMock.Validation; namespace WireMock.Matchers.Request diff --git a/src/WireMock.Net/Owin/Mappers/OwinResponseMapper.cs b/src/WireMock.Net/Owin/Mappers/OwinResponseMapper.cs index a19353e3b..d7c0e18b5 100644 --- a/src/WireMock.Net/Owin/Mappers/OwinResponseMapper.cs +++ b/src/WireMock.Net/Owin/Mappers/OwinResponseMapper.cs @@ -9,6 +9,7 @@ using WireMock.Handlers; using WireMock.Http; using WireMock.ResponseBuilders; +using WireMock.Types; using WireMock.Util; using WireMock.Validation; #if !USE_ASPNETCORE diff --git a/src/WireMock.Net/Owin/WireMockMiddleware.cs b/src/WireMock.Net/Owin/WireMockMiddleware.cs index b572e24e3..580a78578 100644 --- a/src/WireMock.Net/Owin/WireMockMiddleware.cs +++ b/src/WireMock.Net/Owin/WireMockMiddleware.cs @@ -3,11 +3,11 @@ using WireMock.Logging; using System.Linq; using WireMock.Matchers; -using WireMock.Util; using Newtonsoft.Json; using WireMock.Http; using WireMock.Owin.Mappers; using WireMock.Serialization; +using WireMock.Types; using WireMock.Validation; #if !USE_ASPNETCORE using Microsoft.Owin; diff --git a/src/WireMock.Net/RequestBuilders/IParamsRequestBuilder.cs b/src/WireMock.Net/RequestBuilders/IParamsRequestBuilder.cs index 381fec3b1..f58222941 100644 --- a/src/WireMock.Net/RequestBuilders/IParamsRequestBuilder.cs +++ b/src/WireMock.Net/RequestBuilders/IParamsRequestBuilder.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using WireMock.Matchers; -using WireMock.Util; +using WireMock.Types; namespace WireMock.RequestBuilders { diff --git a/src/WireMock.Net/RequestBuilders/Request.WithParam.cs b/src/WireMock.Net/RequestBuilders/Request.WithParam.cs index af2142c8b..a3933dac9 100644 --- a/src/WireMock.Net/RequestBuilders/Request.WithParam.cs +++ b/src/WireMock.Net/RequestBuilders/Request.WithParam.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using WireMock.Matchers; using WireMock.Matchers.Request; -using WireMock.Util; +using WireMock.Types; using WireMock.Validation; namespace WireMock.RequestBuilders diff --git a/src/WireMock.Net/RequestMessage.cs b/src/WireMock.Net/RequestMessage.cs index 9e92062f0..090d49b87 100644 --- a/src/WireMock.Net/RequestMessage.cs +++ b/src/WireMock.Net/RequestMessage.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Net; using WireMock.Models; +using WireMock.Types; using WireMock.Util; using WireMock.Validation; diff --git a/src/WireMock.Net/ResponseBuilders/IBodyResponseBuilder.cs b/src/WireMock.Net/ResponseBuilders/IBodyResponseBuilder.cs index b61c4bb11..bde25125f 100644 --- a/src/WireMock.Net/ResponseBuilders/IBodyResponseBuilder.cs +++ b/src/WireMock.Net/ResponseBuilders/IBodyResponseBuilder.cs @@ -1,6 +1,6 @@ -using System; +using JetBrains.Annotations; +using System; using System.Text; -using JetBrains.Annotations; namespace WireMock.ResponseBuilders { @@ -53,15 +53,6 @@ public interface IBodyResponseBuilder : IFaultResponseBuilder /// A . IResponseBuilder WithBodyAsJson([NotNull] object body, bool indented); - /// - /// WithBody : Create a string response based on a Base64 string (which will be decoded to a normal string). - /// - /// The body. - /// The Encoding. - /// A . - [Obsolete("Should not be used, will be removed in future.")] - IResponseBuilder WithBodyFromBase64([NotNull] string bodyAsBase64, [CanBeNull] Encoding encoding = null); - /// /// WithBodyFromFile : Create a ... response based on a File. /// diff --git a/src/WireMock.Net/ResponseBuilders/IHeadersResponseBuilder.cs b/src/WireMock.Net/ResponseBuilders/IHeadersResponseBuilder.cs index edb02a17c..3590576a0 100644 --- a/src/WireMock.Net/ResponseBuilders/IHeadersResponseBuilder.cs +++ b/src/WireMock.Net/ResponseBuilders/IHeadersResponseBuilder.cs @@ -1,6 +1,6 @@ -using System.Collections.Generic; -using JetBrains.Annotations; -using WireMock.Util; +using JetBrains.Annotations; +using System.Collections.Generic; +using WireMock.Types; namespace WireMock.ResponseBuilders { diff --git a/src/WireMock.Net/ResponseBuilders/Response.cs b/src/WireMock.Net/ResponseBuilders/Response.cs index 6de72e4d0..18197e910 100644 --- a/src/WireMock.Net/ResponseBuilders/Response.cs +++ b/src/WireMock.Net/ResponseBuilders/Response.cs @@ -11,6 +11,7 @@ using WireMock.ResponseProviders; using WireMock.Settings; using WireMock.Transformers; +using WireMock.Types; using WireMock.Util; using WireMock.Validation; @@ -287,23 +288,6 @@ public IResponseBuilder WithBodyAsJson(object body, bool indented) return WithBodyAsJson(body, null, indented); } - /// - public IResponseBuilder WithBodyFromBase64(string bodyAsBase64, Encoding encoding = null) - { - Check.NotNull(bodyAsBase64, nameof(bodyAsBase64)); - - encoding = encoding ?? Encoding.UTF8; - - ResponseMessage.BodyData = new BodyData - { - Encoding = encoding, - DetectedBodyType = BodyType.String, - BodyAsString = encoding.GetString(Convert.FromBase64String(bodyAsBase64)) - }; - - return this; - } - /// public IResponseBuilder WithTransformer(bool transformContentFromBodyAsFile = false) { @@ -346,8 +330,8 @@ private IResponseBuilder WithCallbackInternal(bool withCallbackUsed, Func - public async Task ProvideResponseAsync(RequestMessage requestMessage, IFluentMockServerSettings settings) + /// + public async Task ProvideResponseAsync(RequestMessage requestMessage, IWireMockServerSettings settings) { Check.NotNull(requestMessage, nameof(requestMessage)); Check.NotNull(settings, nameof(settings)); diff --git a/src/WireMock.Net/ResponseMessage.cs b/src/WireMock.Net/ResponseMessage.cs index 669ef1293..798d6d708 100644 --- a/src/WireMock.Net/ResponseMessage.cs +++ b/src/WireMock.Net/ResponseMessage.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Linq; using WireMock.ResponseBuilders; +using WireMock.Types; using WireMock.Util; using WireMock.Validation; diff --git a/src/WireMock.Net/ResponseMessageBuilder.cs b/src/WireMock.Net/ResponseMessageBuilder.cs index 1e2139764..b5d1e2e1a 100644 --- a/src/WireMock.Net/ResponseMessageBuilder.cs +++ b/src/WireMock.Net/ResponseMessageBuilder.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using WireMock.Admin.Mappings; using WireMock.Http; +using WireMock.Types; using WireMock.Util; namespace WireMock diff --git a/src/WireMock.Net/ResponseProviders/DynamicAsyncResponseProvider.cs b/src/WireMock.Net/ResponseProviders/DynamicAsyncResponseProvider.cs index b1880b33e..230701a88 100644 --- a/src/WireMock.Net/ResponseProviders/DynamicAsyncResponseProvider.cs +++ b/src/WireMock.Net/ResponseProviders/DynamicAsyncResponseProvider.cs @@ -13,7 +13,7 @@ public DynamicAsyncResponseProvider(Func> _responseMessageFunc = responseMessageFunc; } - public Task ProvideResponseAsync(RequestMessage requestMessage, IFluentMockServerSettings settings) + public Task ProvideResponseAsync(RequestMessage requestMessage, IWireMockServerSettings settings) { return _responseMessageFunc(requestMessage); } diff --git a/src/WireMock.Net/ResponseProviders/DynamicResponseProvider.cs b/src/WireMock.Net/ResponseProviders/DynamicResponseProvider.cs index 2a88d26dd..01396f5e6 100644 --- a/src/WireMock.Net/ResponseProviders/DynamicResponseProvider.cs +++ b/src/WireMock.Net/ResponseProviders/DynamicResponseProvider.cs @@ -13,7 +13,7 @@ public DynamicResponseProvider(Func responseMes _responseMessageFunc = responseMessageFunc; } - public Task ProvideResponseAsync(RequestMessage requestMessage, IFluentMockServerSettings settings) + public Task ProvideResponseAsync(RequestMessage requestMessage, IWireMockServerSettings settings) { return Task.FromResult(_responseMessageFunc(requestMessage)); } diff --git a/src/WireMock.Net/ResponseProviders/IResponseProvider.cs b/src/WireMock.Net/ResponseProviders/IResponseProvider.cs index 4b0615477..9b71f2c15 100644 --- a/src/WireMock.Net/ResponseProviders/IResponseProvider.cs +++ b/src/WireMock.Net/ResponseProviders/IResponseProvider.cs @@ -13,8 +13,8 @@ public interface IResponseProvider /// The provide response. /// /// The request. - /// The FluentMockServerSettings. + /// The WireMockServerSettings. /// The . - Task ProvideResponseAsync([NotNull] RequestMessage requestMessage, [NotNull] IFluentMockServerSettings settings); + Task ProvideResponseAsync([NotNull] RequestMessage requestMessage, [NotNull] IWireMockServerSettings settings); } } \ No newline at end of file diff --git a/src/WireMock.Net/ResponseProviders/ProxyAsyncResponseProvider.cs b/src/WireMock.Net/ResponseProviders/ProxyAsyncResponseProvider.cs index aee6e7a7c..fb4b6c6d0 100644 --- a/src/WireMock.Net/ResponseProviders/ProxyAsyncResponseProvider.cs +++ b/src/WireMock.Net/ResponseProviders/ProxyAsyncResponseProvider.cs @@ -6,16 +6,16 @@ namespace WireMock.ResponseProviders { internal class ProxyAsyncResponseProvider : IResponseProvider { - private readonly Func> _responseMessageFunc; - private readonly IFluentMockServerSettings _settings; + private readonly Func> _responseMessageFunc; + private readonly IWireMockServerSettings _settings; - public ProxyAsyncResponseProvider(Func> responseMessageFunc, IFluentMockServerSettings settings) + public ProxyAsyncResponseProvider(Func> responseMessageFunc, IWireMockServerSettings settings) { _responseMessageFunc = responseMessageFunc; _settings = settings; } - public Task ProvideResponseAsync(RequestMessage requestMessage, IFluentMockServerSettings settings) + public Task ProvideResponseAsync(RequestMessage requestMessage, IWireMockServerSettings settings) { return _responseMessageFunc(requestMessage, _settings); } diff --git a/src/WireMock.Net/Serialization/LogEntryMapper.cs b/src/WireMock.Net/Serialization/LogEntryMapper.cs index 5fceb2469..9ea871f6f 100644 --- a/src/WireMock.Net/Serialization/LogEntryMapper.cs +++ b/src/WireMock.Net/Serialization/LogEntryMapper.cs @@ -2,6 +2,7 @@ using WireMock.Admin.Mappings; using WireMock.Admin.Requests; using WireMock.Logging; +using WireMock.Types; using WireMock.ResponseBuilders; using WireMock.Util; diff --git a/src/WireMock.Net/Serialization/MappingConverter.cs b/src/WireMock.Net/Serialization/MappingConverter.cs index 383d4135f..b88b0d849 100644 --- a/src/WireMock.Net/Serialization/MappingConverter.cs +++ b/src/WireMock.Net/Serialization/MappingConverter.cs @@ -7,6 +7,7 @@ using WireMock.Settings; using WireMock.Util; using WireMock.Validation; +using WireMock.Types; namespace WireMock.Serialization { diff --git a/src/WireMock.Net/Serialization/MatcherMapper.cs b/src/WireMock.Net/Serialization/MatcherMapper.cs index 2cab19b61..45a86dce8 100644 --- a/src/WireMock.Net/Serialization/MatcherMapper.cs +++ b/src/WireMock.Net/Serialization/MatcherMapper.cs @@ -12,9 +12,9 @@ namespace WireMock.Serialization { internal class MatcherMapper { - private readonly IFluentMockServerSettings _settings; + private readonly IWireMockServerSettings _settings; - public MatcherMapper(IFluentMockServerSettings settings) + public MatcherMapper(IWireMockServerSettings settings) { Check.NotNull(settings, nameof(settings)); _settings = settings; @@ -47,7 +47,7 @@ public IMatcher Map([CanBeNull] MatcherModel matcher) return new CSharpCodeMatcher(matchBehaviour, stringPatterns); } - throw new NotSupportedException("It's not allowed to use the 'CSharpCodeMatcher' because FluentMockServerSettings.AllowCSharpCodeMatcher is not set to 'true'."); + throw new NotSupportedException("It's not allowed to use the 'CSharpCodeMatcher' because IWireMockServerSettings.AllowCSharpCodeMatcher is not set to 'true'."); case "LinqMatcher": return new LinqMatcher(matchBehaviour, stringPatterns); diff --git a/src/WireMock.Net/Server/FluentMockServer.cs b/src/WireMock.Net/Server/FluentMockServer.cs index 6e26e0895..acb35e94b 100644 --- a/src/WireMock.Net/Server/FluentMockServer.cs +++ b/src/WireMock.Net/Server/FluentMockServer.cs @@ -1,478 +1,11 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using JetBrains.Annotations; -using Newtonsoft.Json; -using WireMock.Admin.Mappings; -using WireMock.Exceptions; -using WireMock.Handlers; -using WireMock.Logging; -using WireMock.Matchers; -using WireMock.Matchers.Request; -using WireMock.Owin; -using WireMock.RequestBuilders; -using WireMock.ResponseProviders; -using WireMock.Serialization; -using WireMock.Settings; -using WireMock.Util; -using WireMock.Validation; - -namespace WireMock.Server -{ - /// - /// The fluent mock server. - /// - public partial class FluentMockServer : IDisposable - { - private const int ServerStartDelayInMs = 100; - - private readonly IFluentMockServerSettings _settings; - private readonly IOwinSelfHost _httpServer; - private readonly IWireMockMiddlewareOptions _options = new WireMockMiddlewareOptions(); - private readonly MappingConverter _mappingConverter; - private readonly MatcherMapper _matcherMapper; - - /// - /// Gets a value indicating whether this server is started. - /// - [PublicAPI] - public bool IsStarted => _httpServer != null && _httpServer.IsStarted; - - /// - /// Gets the ports. - /// - [PublicAPI] - public List Ports { get; } - - /// - /// Gets the urls. - /// - [PublicAPI] - public string[] Urls { get; } - - /// - /// Gets the mappings. - /// - [PublicAPI] - public IEnumerable Mappings => _options.Mappings.Values.ToArray(); - - /// - /// Gets the mappings as MappingModels. - /// - [PublicAPI] - public IEnumerable MappingModels => ToMappingModels(); - - /// - /// Gets the scenarios. - /// - [PublicAPI] - public ConcurrentDictionary Scenarios => new ConcurrentDictionary(_options.Scenarios); - - #region IDisposable Members - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool disposing) - { - if (_httpServer != null) - { - _httpServer.StopAsync(); - } - } - #endregion - - #region Start/Stop - /// - /// Starts the specified settings. - /// - /// The FluentMockServerSettings. - /// The . - [PublicAPI] - public static FluentMockServer Start([NotNull] IFluentMockServerSettings settings) - { - Check.NotNull(settings, nameof(settings)); - - return new FluentMockServer(settings); - } - - /// - /// Start this FluentMockServer. - /// - /// The port. - /// The SSL support. - /// The . - [PublicAPI] - public static FluentMockServer Start([CanBeNull] int? port = 0, bool ssl = false) - { - return new FluentMockServer(new FluentMockServerSettings - { - Port = port, - UseSSL = ssl - }); - } - - /// - /// Start this FluentMockServer. - /// - /// The urls to listen on. - /// The . - [PublicAPI] - public static FluentMockServer Start(params string[] urls) - { - Check.NotNullOrEmpty(urls, nameof(urls)); - - return new FluentMockServer(new FluentMockServerSettings - { - Urls = urls - }); - } - - /// - /// Start this FluentMockServer with the admin interface. - /// - /// The port. - /// The SSL support. - /// The . - [PublicAPI] - public static FluentMockServer StartWithAdminInterface(int? port = 0, bool ssl = false) - { - return new FluentMockServer(new FluentMockServerSettings - { - Port = port, - UseSSL = ssl, - StartAdminInterface = true - }); - } - - /// - /// Start this FluentMockServer with the admin interface. - /// - /// The urls. - /// The . - [PublicAPI] - public static FluentMockServer StartWithAdminInterface(params string[] urls) - { - Check.NotNullOrEmpty(urls, nameof(urls)); - - return new FluentMockServer(new FluentMockServerSettings - { - Urls = urls, - StartAdminInterface = true - }); - } - - /// - /// Start this FluentMockServer with the admin interface and read static mappings. - /// - /// The urls. - /// The . - [PublicAPI] - public static FluentMockServer StartWithAdminInterfaceAndReadStaticMappings(params string[] urls) - { - Check.NotNullOrEmpty(urls, nameof(urls)); - - return new FluentMockServer(new FluentMockServerSettings - { - Urls = urls, - StartAdminInterface = true, - ReadStaticMappings = true - }); - } - - private FluentMockServer(IFluentMockServerSettings settings) - { - _settings = settings; - - // Set default values if not provided - _settings.Logger = settings.Logger ?? new WireMockNullLogger(); - _settings.FileSystemHandler = settings.FileSystemHandler ?? new LocalFileSystemHandler(); - - _settings.Logger.Info("WireMock.Net by Stef Heyenrath (https://github.com/WireMock-Net/WireMock.Net)"); - _settings.Logger.Debug("WireMock.Net server settings {0}", JsonConvert.SerializeObject(settings, Formatting.Indented)); - - if (settings.Urls != null) - { - Urls = settings.Urls.ToArray(); - } - else - { - int port = settings.Port > 0 ? settings.Port.Value : PortUtils.FindFreeTcpPort(); - Urls = new[] { $"{(settings.UseSSL == true ? "https" : "http")}://localhost:{port}" }; - } - - _options.FileSystemHandler = _settings.FileSystemHandler; - _options.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit; - _options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit; - _options.Logger = _settings.Logger; - - _matcherMapper = new MatcherMapper(_settings); - _mappingConverter = new MappingConverter(_matcherMapper); - -#if USE_ASPNETCORE - _httpServer = new AspNetCoreSelfHost(_options, Urls); -#else - _httpServer = new OwinSelfHost(_options, Urls); -#endif - Ports = _httpServer.Ports; - - var startTask = _httpServer.StartAsync(); - - using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout)) - { - while (!_httpServer.IsStarted) - { - // Throw exception if service start fails - if (_httpServer.RunningException != null) - { - throw new WireMockException($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException); - } - - if (ctsStartTimeout.IsCancellationRequested) - { - // In case of an aggregate exception, throw the exception. - if (startTask.Exception != null) - { - throw new WireMockException($"Service start failed with error: {startTask.Exception.Message}", startTask.Exception); - } - - // Else throw TimeoutException - throw new TimeoutException($"Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}"); - } - - ctsStartTimeout.Token.WaitHandle.WaitOne(ServerStartDelayInMs); - } - } - - if (settings.AllowBodyForAllHttpMethods == true) - { - _options.AllowBodyForAllHttpMethods = _settings.AllowBodyForAllHttpMethods; - _settings.Logger.Info("AllowBodyForAllHttpMethods is set to {0}", _settings.AllowBodyForAllHttpMethods == true); - } - - if (settings.AllowPartialMapping == true) - { - AllowPartialMapping(); - } - - if (settings.StartAdminInterface == true) - { - if (!string.IsNullOrEmpty(settings.AdminUsername) && !string.IsNullOrEmpty(settings.AdminPassword)) - { - SetBasicAuthentication(settings.AdminUsername, settings.AdminPassword); - } - - InitAdmin(); - } - - if (settings.ReadStaticMappings == true) - { - ReadStaticMappings(); - } - - if (settings.WatchStaticMappings == true) - { - WatchStaticMappings(); - } - - if (settings.ProxyAndRecordSettings != null) - { - InitProxyAndRecord(settings); - } - - if (settings.RequestLogExpirationDuration != null) - { - SetRequestLogExpirationDuration(settings.RequestLogExpirationDuration); - } - - if (settings.MaxRequestLogCount != null) - { - SetMaxRequestLogCount(settings.MaxRequestLogCount); - } - } - - /// - /// Stop this server. - /// - [PublicAPI] - public void Stop() - { - var result = _httpServer?.StopAsync(); - result?.Wait(); // wait for stop to actually happen - } - #endregion - - /// - /// Adds the catch all mapping. - /// - [PublicAPI] - public void AddCatchAllMapping() - { - Given(Request.Create().WithPath("/*").UsingAnyMethod()) - .WithGuid(Guid.Parse("90008000-0000-4444-a17e-669cd84f1f05")) - .AtPriority(1000) - .RespondWith(new DynamicResponseProvider(request => ResponseMessageBuilder.Create("No matching mapping found", 404))); - } - - /// - /// Resets LogEntries and Mappings. - /// - [PublicAPI] - public void Reset() - { - ResetLogEntries(); - - ResetMappings(); - } - - /// - /// Resets the Mappings. - /// - [PublicAPI] - public void ResetMappings() - { - foreach (var nonAdmin in _options.Mappings.ToArray().Where(m => !m.Value.IsAdminInterface)) - { - _options.Mappings.TryRemove(nonAdmin.Key, out _); - } - } - - /// - /// Deletes the mapping. - /// - /// The unique identifier. - [PublicAPI] - public bool DeleteMapping(Guid guid) - { - // Check a mapping exists with the same GUID, if so, remove it. - if (_options.Mappings.ContainsKey(guid)) - { - return _options.Mappings.TryRemove(guid, out _); - } - - return false; - } - - private bool DeleteMapping(string path) - { - // Check a mapping exists with the same path, if so, remove it. - var mapping = _options.Mappings.ToArray().FirstOrDefault(entry => string.Equals(entry.Value.Path, path, StringComparison.OrdinalIgnoreCase)); - return DeleteMapping(mapping.Key); - } - - /// - /// The add request processing delay. - /// - /// The delay. - [PublicAPI] - public void AddGlobalProcessingDelay(TimeSpan delay) - { - _options.RequestProcessingDelay = delay; - } - - /// - /// Allows the partial mapping. - /// - [PublicAPI] - public void AllowPartialMapping(bool allow = true) - { - _settings.Logger.Info("AllowPartialMapping is set to {0}", allow); - _options.AllowPartialMapping = allow; - } - - /// - /// Sets the basic authentication. - /// - /// The username. - /// The password. - [PublicAPI] - public void SetBasicAuthentication([NotNull] string username, [NotNull] string password) - { - Check.NotNull(username, nameof(username)); - Check.NotNull(password, nameof(password)); - - string authorization = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); - _options.AuthorizationMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, "^(?i)BASIC " + authorization + "$"); - } - - /// - /// Removes the basic authentication. - /// - [PublicAPI] - public void RemoveBasicAuthentication() - { - _options.AuthorizationMatcher = null; - } - - /// - /// Sets the maximum RequestLog count. - /// - /// The maximum RequestLog count. - [PublicAPI] - public void SetMaxRequestLogCount([CanBeNull] int? maxRequestLogCount) - { - _options.MaxRequestLogCount = maxRequestLogCount; - } - - /// - /// Sets RequestLog expiration in hours. - /// - /// The RequestLog expiration in hours. - [PublicAPI] - public void SetRequestLogExpirationDuration([CanBeNull] int? requestLogExpirationDuration) - { - _options.RequestLogExpirationDuration = requestLogExpirationDuration; - } - - /// - /// Resets the Scenarios. - /// - [PublicAPI] - public void ResetScenarios() - { - _options.Scenarios.Clear(); - } - - /// - /// The given. - /// - /// The request matcher. - /// Optional boolean to indicate if this mapping should be saved as static mapping file. - /// The . - [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, replace it. - if (_options.Mappings.ContainsKey(mapping.Guid)) - { - _options.Mappings[mapping.Guid] = mapping; - } - else - { - _options.Mappings.TryAdd(mapping.Guid, mapping); - } - - if (saveToFile) - { - SaveMappingToFile(mapping); - } - } - } +using WireMock.Settings; + +namespace WireMock.Server +{ + public class FluentMockServer : WireMockServer + { + public FluentMockServer(IFluentMockServerSettings settings) : base((IWireMockServerSettings) settings) + { + } + } } \ No newline at end of file diff --git a/src/WireMock.Net/Server/RespondWithAProvider.cs b/src/WireMock.Net/Server/RespondWithAProvider.cs index d259a9d46..e436b3ba7 100644 --- a/src/WireMock.Net/Server/RespondWithAProvider.cs +++ b/src/WireMock.Net/Server/RespondWithAProvider.cs @@ -18,7 +18,7 @@ internal class RespondWithAProvider : IRespondWithAProvider private string _scenario; private readonly RegistrationCallback _registrationCallback; private readonly IRequestMatcher _requestMatcher; - private readonly IFluentMockServerSettings _settings; + private readonly IWireMockServerSettings _settings; private readonly bool _saveToFile; public Guid Guid { get; private set; } = Guid.NewGuid(); @@ -28,9 +28,9 @@ internal class RespondWithAProvider : IRespondWithAProvider /// /// The registration callback. /// The request matcher. - /// The FluentMockServerSettings. + /// The WireMockServerSettings. /// Optional boolean to indicate if this mapping should be saved as static mapping file. - public RespondWithAProvider(RegistrationCallback registrationCallback, IRequestMatcher requestMatcher, IFluentMockServerSettings settings, bool saveToFile = false) + public RespondWithAProvider(RegistrationCallback registrationCallback, IRequestMatcher requestMatcher, IWireMockServerSettings settings, bool saveToFile = false) { _registrationCallback = registrationCallback; _requestMatcher = requestMatcher; diff --git a/src/WireMock.Net/Server/FluentMockServer.Admin.cs b/src/WireMock.Net/Server/WireMockServer.Admin.cs similarity index 98% rename from src/WireMock.Net/Server/FluentMockServer.Admin.cs rename to src/WireMock.Net/Server/WireMockServer.Admin.cs index 8da29c7d3..3768b4a51 100644 --- a/src/WireMock.Net/Server/FluentMockServer.Admin.cs +++ b/src/WireMock.Net/Server/WireMockServer.Admin.cs @@ -20,6 +20,7 @@ using WireMock.ResponseProviders; using WireMock.Serialization; using WireMock.Settings; +using WireMock.Types; using WireMock.Util; using WireMock.Validation; @@ -28,7 +29,7 @@ namespace WireMock.Server /// /// The fluent mock server. /// - public partial class FluentMockServer + public partial class WireMockServer { private const int EnhancedFileSystemWatcherTimeoutMs = 1000; private const int AdminPriority = int.MinValue; @@ -254,7 +255,7 @@ public bool ReadStaticMappingAndAddOrUpdate([NotNull] string path) #region Proxy and Record private HttpClient _httpClientForProxy; - private void InitProxyAndRecord(IFluentMockServerSettings settings) + private void InitProxyAndRecord(IWireMockServerSettings settings) { _httpClientForProxy = HttpClientHelper.CreateHttpClient(settings.ProxyAndRecordSettings); @@ -267,7 +268,7 @@ private void InitProxyAndRecord(IFluentMockServerSettings settings) respondProvider.RespondWith(new ProxyAsyncResponseProvider(ProxyAndRecordAsync, settings)); } - private async Task ProxyAndRecordAsync(RequestMessage requestMessage, IFluentMockServerSettings settings) + private async Task ProxyAndRecordAsync(RequestMessage requestMessage, IWireMockServerSettings settings) { var requestUri = new Uri(requestMessage.Url); var proxyUri = new Uri(settings.ProxyAndRecordSettings.Url); @@ -850,10 +851,6 @@ private IResponseBuilder InitResponseBuilder(ResponseModel responseModel) { responseBuilder = responseBuilder.WithBodyAsJson(responseModel.BodyAsJson, ToEncoding(responseModel.BodyEncoding), responseModel.BodyAsJsonIndented == true); } - else if (responseModel.BodyFromBase64 != null) - { - responseBuilder = responseBuilder.WithBodyFromBase64(responseModel.BodyFromBase64, ToEncoding(responseModel.BodyEncoding)); - } else if (responseModel.BodyAsFile != null) { responseBuilder = responseBuilder.WithBodyFromFile(responseModel.BodyAsFile); diff --git a/src/WireMock.Net/Server/FluentMockServer.AdminFiles.cs b/src/WireMock.Net/Server/WireMockServer.AdminFiles.cs similarity index 98% rename from src/WireMock.Net/Server/FluentMockServer.AdminFiles.cs rename to src/WireMock.Net/Server/WireMockServer.AdminFiles.cs index 40dc6374c..fb0548aa6 100644 --- a/src/WireMock.Net/Server/FluentMockServer.AdminFiles.cs +++ b/src/WireMock.Net/Server/WireMockServer.AdminFiles.cs @@ -2,11 +2,12 @@ using System.Linq; using System.Text; using WireMock.Matchers; +using WireMock.Types; using WireMock.Util; namespace WireMock.Server { - public partial class FluentMockServer + public partial class WireMockServer { private readonly RegexMatcher _adminFilesFilenamePathMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, @"^\/__admin\/files\/.*$"); private static readonly Encoding[] FileBodyIsString = { Encoding.UTF8, Encoding.ASCII }; diff --git a/src/WireMock.Net/Server/FluentMockServer.LogEntries.cs b/src/WireMock.Net/Server/WireMockServer.LogEntries.cs similarity index 95% rename from src/WireMock.Net/Server/FluentMockServer.LogEntries.cs rename to src/WireMock.Net/Server/WireMockServer.LogEntries.cs index 25b7da47b..340307f12 100644 --- a/src/WireMock.Net/Server/FluentMockServer.LogEntries.cs +++ b/src/WireMock.Net/Server/WireMockServer.LogEntries.cs @@ -1,100 +1,100 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.Linq; -using JetBrains.Annotations; -using WireMock.Logging; -using WireMock.Matchers; -using WireMock.Matchers.Request; - -namespace WireMock.Server -{ - public partial class FluentMockServer - { - /// - /// Occurs when [log entries changed]. - /// - [PublicAPI] - public event NotifyCollectionChangedEventHandler LogEntriesChanged - { - add - { - _options.LogEntries.CollectionChanged += (sender, eventRecordArgs) => - { - try - { - value(sender, eventRecordArgs); - } - catch (Exception exception) - { - _options.Logger.Error("Error calling the LogEntriesChanged event handler: {0}", exception.Message); - } - }; - } - - remove => _options.LogEntries.CollectionChanged -= value; - } - - /// - /// Gets the request logs. - /// - [PublicAPI] - public IEnumerable LogEntries => new ReadOnlyCollection(_options.LogEntries.ToList()); - - /// - /// The search log-entries based on matchers. - /// - /// The matchers. - /// The . - [PublicAPI] - public IEnumerable FindLogEntries([NotNull] params IRequestMatcher[] matchers) - { - var results = new Dictionary(); - - foreach (var log in _options.LogEntries.ToList()) - { - var requestMatchResult = new RequestMatchResult(); - foreach (var matcher in matchers) - { - matcher.GetMatchingScore(log.RequestMessage, requestMatchResult); - } - - if (requestMatchResult.AverageTotalScore > MatchScores.AlmostPerfect) - { - results.Add(log, requestMatchResult); - } - } - - return new ReadOnlyCollection(results.OrderBy(x => x.Value).Select(x => x.Key).ToList()); - } - - /// - /// Resets the LogEntries. - /// - [PublicAPI] - public void ResetLogEntries() - { - _options.LogEntries.Clear(); - } - - /// - /// Deletes a LogEntry. - /// - /// The unique identifier. - [PublicAPI] - public bool DeleteLogEntry(Guid guid) - { - // Check a logentry exists with the same GUID, if so, remove it. - var existing = _options.LogEntries.ToList().FirstOrDefault(m => m.Guid == guid); - if (existing != null) - { - _options.LogEntries.Remove(existing); - return true; - } - - return false; - } - } +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Linq; +using JetBrains.Annotations; +using WireMock.Logging; +using WireMock.Matchers; +using WireMock.Matchers.Request; + +namespace WireMock.Server +{ + public partial class WireMockServer + { + /// + /// Occurs when [log entries changed]. + /// + [PublicAPI] + public event NotifyCollectionChangedEventHandler LogEntriesChanged + { + add + { + _options.LogEntries.CollectionChanged += (sender, eventRecordArgs) => + { + try + { + value(sender, eventRecordArgs); + } + catch (Exception exception) + { + _options.Logger.Error("Error calling the LogEntriesChanged event handler: {0}", exception.Message); + } + }; + } + + remove => _options.LogEntries.CollectionChanged -= value; + } + + /// + /// Gets the request logs. + /// + [PublicAPI] + public IEnumerable LogEntries => new ReadOnlyCollection(_options.LogEntries.ToList()); + + /// + /// The search log-entries based on matchers. + /// + /// The matchers. + /// The . + [PublicAPI] + public IEnumerable FindLogEntries([NotNull] params IRequestMatcher[] matchers) + { + var results = new Dictionary(); + + foreach (var log in _options.LogEntries.ToList()) + { + var requestMatchResult = new RequestMatchResult(); + foreach (var matcher in matchers) + { + matcher.GetMatchingScore(log.RequestMessage, requestMatchResult); + } + + if (requestMatchResult.AverageTotalScore > MatchScores.AlmostPerfect) + { + results.Add(log, requestMatchResult); + } + } + + return new ReadOnlyCollection(results.OrderBy(x => x.Value).Select(x => x.Key).ToList()); + } + + /// + /// Resets the LogEntries. + /// + [PublicAPI] + public void ResetLogEntries() + { + _options.LogEntries.Clear(); + } + + /// + /// Deletes a LogEntry. + /// + /// The unique identifier. + [PublicAPI] + public bool DeleteLogEntry(Guid guid) + { + // Check a logentry exists with the same GUID, if so, remove it. + var existing = _options.LogEntries.ToList().FirstOrDefault(m => m.Guid == guid); + if (existing != null) + { + _options.LogEntries.Remove(existing); + return true; + } + + return false; + } + } } \ No newline at end of file diff --git a/src/WireMock.Net/Server/WireMockServer.cs b/src/WireMock.Net/Server/WireMockServer.cs new file mode 100644 index 000000000..1dde57313 --- /dev/null +++ b/src/WireMock.Net/Server/WireMockServer.cs @@ -0,0 +1,477 @@ +using JetBrains.Annotations; +using Newtonsoft.Json; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using WireMock.Admin.Mappings; +using WireMock.Exceptions; +using WireMock.Handlers; +using WireMock.Logging; +using WireMock.Matchers; +using WireMock.Matchers.Request; +using WireMock.Owin; +using WireMock.RequestBuilders; +using WireMock.ResponseProviders; +using WireMock.Serialization; +using WireMock.Settings; +using WireMock.Util; +using WireMock.Validation; + +namespace WireMock.Server +{ + /// + /// The fluent mock server. + /// + public partial class WireMockServer : IDisposable + { + private const int ServerStartDelayInMs = 100; + + private readonly IWireMockServerSettings _settings; + private readonly IOwinSelfHost _httpServer; + private readonly IWireMockMiddlewareOptions _options = new WireMockMiddlewareOptions(); + private readonly MappingConverter _mappingConverter; + private readonly MatcherMapper _matcherMapper; + + /// + /// Gets a value indicating whether this server is started. + /// + [PublicAPI] + public bool IsStarted => _httpServer != null && _httpServer.IsStarted; + + /// + /// Gets the ports. + /// + [PublicAPI] + public List Ports { get; } + + /// + /// Gets the urls. + /// + [PublicAPI] + public string[] Urls { get; } + + /// + /// Gets the mappings. + /// + [PublicAPI] + public IEnumerable Mappings => _options.Mappings.Values.ToArray(); + + /// + /// Gets the mappings as MappingModels. + /// + [PublicAPI] + public IEnumerable MappingModels => ToMappingModels(); + + /// + /// Gets the scenarios. + /// + [PublicAPI] + public ConcurrentDictionary Scenarios => new ConcurrentDictionary(_options.Scenarios); + + #region IDisposable Members + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if (_httpServer != null) + { + _httpServer.StopAsync(); + } + } + #endregion + + #region Start/Stop + /// + /// Starts the specified settings. + /// + /// The WireMockServerSettings. + /// The . + [PublicAPI] + public static WireMockServer Start([NotNull] IWireMockServerSettings settings) + { + Check.NotNull(settings, nameof(settings)); + + return new WireMockServer(settings); + } + + /// + /// Start this WireMockServer. + /// + /// The port. + /// The SSL support. + /// The . + [PublicAPI] + public static WireMockServer Start([CanBeNull] int? port = 0, bool ssl = false) + { + return new WireMockServer(new WireMockServerSettings + { + Port = port, + UseSSL = ssl + }); + } + + /// + /// Start this WireMockServer. + /// + /// The urls to listen on. + /// The . + [PublicAPI] + public static WireMockServer Start(params string[] urls) + { + Check.NotNullOrEmpty(urls, nameof(urls)); + + return new WireMockServer(new WireMockServerSettings + { + Urls = urls + }); + } + + /// + /// Start this WireMockServer with the admin interface. + /// + /// The port. + /// The SSL support. + /// The . + [PublicAPI] + public static WireMockServer StartWithAdminInterface(int? port = 0, bool ssl = false) + { + return new WireMockServer(new WireMockServerSettings + { + Port = port, + UseSSL = ssl, + StartAdminInterface = true + }); + } + + /// + /// Start this WireMockServer with the admin interface. + /// + /// The urls. + /// The . + [PublicAPI] + public static WireMockServer StartWithAdminInterface(params string[] urls) + { + Check.NotNullOrEmpty(urls, nameof(urls)); + + return new WireMockServer(new WireMockServerSettings + { + Urls = urls, + StartAdminInterface = true + }); + } + + /// + /// Start this WireMockServer with the admin interface and read static mappings. + /// + /// The urls. + /// The . + [PublicAPI] + public static WireMockServer StartWithAdminInterfaceAndReadStaticMappings(params string[] urls) + { + Check.NotNullOrEmpty(urls, nameof(urls)); + + return new WireMockServer(new WireMockServerSettings + { + Urls = urls, + StartAdminInterface = true, + ReadStaticMappings = true + }); + } + protected WireMockServer(IWireMockServerSettings settings) + { + _settings = settings; + + // Set default values if not provided + _settings.Logger = settings.Logger ?? new WireMockNullLogger(); + _settings.FileSystemHandler = settings.FileSystemHandler ?? new LocalFileSystemHandler(); + + _settings.Logger.Info("WireMock.Net by Stef Heyenrath (https://github.com/WireMock-Net/WireMock.Net)"); + _settings.Logger.Debug("WireMock.Net server settings {0}", JsonConvert.SerializeObject(settings, Formatting.Indented)); + + if (settings.Urls != null) + { + Urls = settings.Urls.ToArray(); + } + else + { + int port = settings.Port > 0 ? settings.Port.Value : PortUtils.FindFreeTcpPort(); + Urls = new[] { $"{(settings.UseSSL == true ? "https" : "http")}://localhost:{port}" }; + } + + _options.FileSystemHandler = _settings.FileSystemHandler; + _options.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit; + _options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit; + _options.Logger = _settings.Logger; + + _matcherMapper = new MatcherMapper(_settings); + _mappingConverter = new MappingConverter(_matcherMapper); + +#if USE_ASPNETCORE + _httpServer = new AspNetCoreSelfHost(_options, Urls); +#else + _httpServer = new OwinSelfHost(_options, Urls); +#endif + Ports = _httpServer.Ports; + + var startTask = _httpServer.StartAsync(); + + using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout)) + { + while (!_httpServer.IsStarted) + { + // Throw exception if service start fails + if (_httpServer.RunningException != null) + { + throw new WireMockException($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException); + } + + if (ctsStartTimeout.IsCancellationRequested) + { + // In case of an aggregate exception, throw the exception. + if (startTask.Exception != null) + { + throw new WireMockException($"Service start failed with error: {startTask.Exception.Message}", startTask.Exception); + } + + // Else throw TimeoutException + throw new TimeoutException($"Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}"); + } + + ctsStartTimeout.Token.WaitHandle.WaitOne(ServerStartDelayInMs); + } + } + + if (settings.AllowBodyForAllHttpMethods == true) + { + _options.AllowBodyForAllHttpMethods = _settings.AllowBodyForAllHttpMethods; + _settings.Logger.Info("AllowBodyForAllHttpMethods is set to {0}", _settings.AllowBodyForAllHttpMethods == true); + } + + if (settings.AllowPartialMapping == true) + { + AllowPartialMapping(); + } + + if (settings.StartAdminInterface == true) + { + if (!string.IsNullOrEmpty(settings.AdminUsername) && !string.IsNullOrEmpty(settings.AdminPassword)) + { + SetBasicAuthentication(settings.AdminUsername, settings.AdminPassword); + } + + InitAdmin(); + } + + if (settings.ReadStaticMappings == true) + { + ReadStaticMappings(); + } + + if (settings.WatchStaticMappings == true) + { + WatchStaticMappings(); + } + + if (settings.ProxyAndRecordSettings != null) + { + InitProxyAndRecord(settings); + } + + if (settings.RequestLogExpirationDuration != null) + { + SetRequestLogExpirationDuration(settings.RequestLogExpirationDuration); + } + + if (settings.MaxRequestLogCount != null) + { + SetMaxRequestLogCount(settings.MaxRequestLogCount); + } + } + + /// + /// Stop this server. + /// + [PublicAPI] + public void Stop() + { + var result = _httpServer?.StopAsync(); + result?.Wait(); // wait for stop to actually happen + } + #endregion + + /// + /// Adds the catch all mapping. + /// + [PublicAPI] + public void AddCatchAllMapping() + { + Given(Request.Create().WithPath("/*").UsingAnyMethod()) + .WithGuid(Guid.Parse("90008000-0000-4444-a17e-669cd84f1f05")) + .AtPriority(1000) + .RespondWith(new DynamicResponseProvider(request => ResponseMessageBuilder.Create("No matching mapping found", 404))); + } + + /// + /// Resets LogEntries and Mappings. + /// + [PublicAPI] + public void Reset() + { + ResetLogEntries(); + + ResetMappings(); + } + + /// + /// Resets the Mappings. + /// + [PublicAPI] + public void ResetMappings() + { + foreach (var nonAdmin in _options.Mappings.ToArray().Where(m => !m.Value.IsAdminInterface)) + { + _options.Mappings.TryRemove(nonAdmin.Key, out _); + } + } + + /// + /// Deletes the mapping. + /// + /// The unique identifier. + [PublicAPI] + public bool DeleteMapping(Guid guid) + { + // Check a mapping exists with the same GUID, if so, remove it. + if (_options.Mappings.ContainsKey(guid)) + { + return _options.Mappings.TryRemove(guid, out _); + } + + return false; + } + + private bool DeleteMapping(string path) + { + // Check a mapping exists with the same path, if so, remove it. + var mapping = _options.Mappings.ToArray().FirstOrDefault(entry => string.Equals(entry.Value.Path, path, StringComparison.OrdinalIgnoreCase)); + return DeleteMapping(mapping.Key); + } + + /// + /// The add request processing delay. + /// + /// The delay. + [PublicAPI] + public void AddGlobalProcessingDelay(TimeSpan delay) + { + _options.RequestProcessingDelay = delay; + } + + /// + /// Allows the partial mapping. + /// + [PublicAPI] + public void AllowPartialMapping(bool allow = true) + { + _settings.Logger.Info("AllowPartialMapping is set to {0}", allow); + _options.AllowPartialMapping = allow; + } + + /// + /// Sets the basic authentication. + /// + /// The username. + /// The password. + [PublicAPI] + public void SetBasicAuthentication([NotNull] string username, [NotNull] string password) + { + Check.NotNull(username, nameof(username)); + Check.NotNull(password, nameof(password)); + + string authorization = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); + _options.AuthorizationMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, "^(?i)BASIC " + authorization + "$"); + } + + /// + /// Removes the basic authentication. + /// + [PublicAPI] + public void RemoveBasicAuthentication() + { + _options.AuthorizationMatcher = null; + } + + /// + /// Sets the maximum RequestLog count. + /// + /// The maximum RequestLog count. + [PublicAPI] + public void SetMaxRequestLogCount([CanBeNull] int? maxRequestLogCount) + { + _options.MaxRequestLogCount = maxRequestLogCount; + } + + /// + /// Sets RequestLog expiration in hours. + /// + /// The RequestLog expiration in hours. + [PublicAPI] + public void SetRequestLogExpirationDuration([CanBeNull] int? requestLogExpirationDuration) + { + _options.RequestLogExpirationDuration = requestLogExpirationDuration; + } + + /// + /// Resets the Scenarios. + /// + [PublicAPI] + public void ResetScenarios() + { + _options.Scenarios.Clear(); + } + + /// + /// The given. + /// + /// The request matcher. + /// Optional boolean to indicate if this mapping should be saved as static mapping file. + /// The . + [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, replace it. + if (_options.Mappings.ContainsKey(mapping.Guid)) + { + _options.Mappings[mapping.Guid] = mapping; + } + else + { + _options.Mappings.TryAdd(mapping.Guid, mapping); + } + + if (saveToFile) + { + SaveMappingToFile(mapping); + } + } + } +} \ No newline at end of file diff --git a/src/WireMock.Net/Settings/FluentMockServerSettings.cs b/src/WireMock.Net/Settings/FluentMockServerSettings.cs index 072f5aca5..d21b366eb 100644 --- a/src/WireMock.Net/Settings/FluentMockServerSettings.cs +++ b/src/WireMock.Net/Settings/FluentMockServerSettings.cs @@ -1,105 +1,9 @@ -using HandlebarsDotNet; -using JetBrains.Annotations; -using Newtonsoft.Json; -using System; -using WireMock.Handlers; -using WireMock.Logging; - -namespace WireMock.Settings +namespace WireMock.Settings { /// /// FluentMockServerSettings /// - public class FluentMockServerSettings : IFluentMockServerSettings + public class FluentMockServerSettings : WireMockServerSettings { - /// - [PublicAPI] - public int? Port { get; set; } - - /// - [PublicAPI] - // ReSharper disable once InconsistentNaming - public bool? UseSSL { get; set; } - - /// - [PublicAPI] - public bool? StartAdminInterface { get; set; } - - /// - [PublicAPI] - public bool? ReadStaticMappings { get; set; } - - /// - [PublicAPI] - public bool? WatchStaticMappings { get; set; } - - /// - [PublicAPI] - public bool? WatchStaticMappingsInSubdirectories { get; set; } - - /// - [PublicAPI] - public IProxyAndRecordSettings ProxyAndRecordSettings { get; set; } - - /// - [PublicAPI] - public string[] Urls { get; set; } - - /// - [PublicAPI] - public int StartTimeout { get; set; } = 10000; - - /// - [PublicAPI] - public bool? AllowPartialMapping { get; set; } - - /// - [PublicAPI] - public string AdminUsername { get; set; } - - /// - [PublicAPI] - public string AdminPassword { get; set; } - - /// - [PublicAPI] - public int? RequestLogExpirationDuration { get; set; } - - /// - [PublicAPI] - public int? MaxRequestLogCount { get; set; } - - /// - [PublicAPI] - [JsonIgnore] - public Action PreWireMockMiddlewareInit { get; set; } - - /// - [PublicAPI] - [JsonIgnore] - public Action PostWireMockMiddlewareInit { get; set; } - - /// - [PublicAPI] - [JsonIgnore] - public IWireMockLogger Logger { get; set; } = new WireMockNullLogger(); - - /// - [PublicAPI] - [JsonIgnore] - public IFileSystemHandler FileSystemHandler { get; set; } - - /// - [PublicAPI] - [JsonIgnore] - public Action HandlebarsRegistrationCallback { get; set; } - - /// - [PublicAPI] - public bool? AllowCSharpCodeMatcher { get; set; } - - /// - [PublicAPI] - public bool? AllowBodyForAllHttpMethods { get; set; } } } \ No newline at end of file diff --git a/src/WireMock.Net/Settings/IFluentMockServerSettings.cs b/src/WireMock.Net/Settings/IFluentMockServerSettings.cs index ee10c4d11..1d255a47a 100644 --- a/src/WireMock.Net/Settings/IFluentMockServerSettings.cs +++ b/src/WireMock.Net/Settings/IFluentMockServerSettings.cs @@ -1,141 +1,9 @@ -using System; -using HandlebarsDotNet; -using JetBrains.Annotations; -using WireMock.Handlers; -using WireMock.Logging; - -namespace WireMock.Settings +namespace WireMock.Settings { /// /// IFluentMockServerSettings /// - public interface IFluentMockServerSettings + public interface IFluentMockServerSettings : IWireMockServerSettings { - /// - /// Gets or sets the port. - /// - [PublicAPI] - int? Port { get; set; } - - /// - /// Gets or sets the use SSL. - /// - // ReSharper disable once InconsistentNaming - [PublicAPI] - bool? UseSSL { get; set; } - - /// - /// Gets or sets whether to start admin interface. - /// - [PublicAPI] - bool? StartAdminInterface { get; set; } - - /// - /// Gets or sets if the static mappings should be read at startup. - /// - [PublicAPI] - bool? ReadStaticMappings { get; set; } - - /// - /// Watch the static mapping files + folder for changes when running. - /// - [PublicAPI] - bool? WatchStaticMappings { get; set; } - - /// - /// A value indicating whether subdirectories within the static mappings path should be monitored. - /// - [PublicAPI] - bool? WatchStaticMappingsInSubdirectories { get; set; } - - /// - /// Gets or sets if the proxy and record settings. - /// - [PublicAPI] - IProxyAndRecordSettings ProxyAndRecordSettings { get; set; } - - /// - /// Gets or sets the urls. - /// - [PublicAPI] - string[] Urls { get; set; } - - /// - /// StartTimeout - /// - [PublicAPI] - int StartTimeout { get; set; } - - /// - /// Allow Partial Mapping (default set to false). - /// - [PublicAPI] - bool? AllowPartialMapping { get; set; } - - /// - /// The username needed for __admin access. - /// - [PublicAPI] - string AdminUsername { get; set; } - - /// - /// The password needed for __admin access. - /// - [PublicAPI] - string AdminPassword { get; set; } - - /// - /// The RequestLog expiration in hours (optional). - /// - [PublicAPI] - int? RequestLogExpirationDuration { get; set; } - - /// - /// The MaxRequestLog count (optional). - /// - [PublicAPI] - int? MaxRequestLogCount { get; set; } - - /// - /// Action which is called (with the IAppBuilder or IApplicationBuilder) before the internal WireMockMiddleware is initialized. [Optional] - /// - [PublicAPI] - Action PreWireMockMiddlewareInit { get; set; } - - /// - /// Action which is called (with the IAppBuilder or IApplicationBuilder) after the internal WireMockMiddleware is initialized. [Optional] - /// - [PublicAPI] - Action PostWireMockMiddlewareInit { get; set; } - - /// - /// The IWireMockLogger which logs Debug, Info, Warning or Error - /// - [PublicAPI] - IWireMockLogger Logger { get; set; } - - /// - /// Handler to interact with the file system to read and write static mapping files. - /// - [PublicAPI] - IFileSystemHandler FileSystemHandler { get; set; } - - /// - /// Action which can be used to add additional Handlebars registrations. [Optional] - /// - [PublicAPI] - Action HandlebarsRegistrationCallback { get; set; } - - /// - /// Allow the usage of CSharpCodeMatcher (default is not allowed). - /// - [PublicAPI] - bool? AllowCSharpCodeMatcher { get; set; } - - /// - /// Allow a Body for all HTTP Methods. (default set to false). - /// - [PublicAPI] - bool? AllowBodyForAllHttpMethods { get; set; } } } \ No newline at end of file diff --git a/src/WireMock.Net/Settings/IWireMockServerSettings.cs b/src/WireMock.Net/Settings/IWireMockServerSettings.cs new file mode 100644 index 000000000..6d76c1cbe --- /dev/null +++ b/src/WireMock.Net/Settings/IWireMockServerSettings.cs @@ -0,0 +1,141 @@ +using System; +using HandlebarsDotNet; +using JetBrains.Annotations; +using WireMock.Handlers; +using WireMock.Logging; + +namespace WireMock.Settings +{ + /// + /// IWireMockServerSettings + /// + public interface IWireMockServerSettings + { + /// + /// Gets or sets the port. + /// + [PublicAPI] + int? Port { get; set; } + + /// + /// Gets or sets the use SSL. + /// + // ReSharper disable once InconsistentNaming + [PublicAPI] + bool? UseSSL { get; set; } + + /// + /// Gets or sets whether to start admin interface. + /// + [PublicAPI] + bool? StartAdminInterface { get; set; } + + /// + /// Gets or sets if the static mappings should be read at startup. + /// + [PublicAPI] + bool? ReadStaticMappings { get; set; } + + /// + /// Watch the static mapping files + folder for changes when running. + /// + [PublicAPI] + bool? WatchStaticMappings { get; set; } + + /// + /// A value indicating whether subdirectories within the static mappings path should be monitored. + /// + [PublicAPI] + bool? WatchStaticMappingsInSubdirectories { get; set; } + + /// + /// Gets or sets if the proxy and record settings. + /// + [PublicAPI] + IProxyAndRecordSettings ProxyAndRecordSettings { get; set; } + + /// + /// Gets or sets the urls. + /// + [PublicAPI] + string[] Urls { get; set; } + + /// + /// StartTimeout + /// + [PublicAPI] + int StartTimeout { get; set; } + + /// + /// Allow Partial Mapping (default set to false). + /// + [PublicAPI] + bool? AllowPartialMapping { get; set; } + + /// + /// The username needed for __admin access. + /// + [PublicAPI] + string AdminUsername { get; set; } + + /// + /// The password needed for __admin access. + /// + [PublicAPI] + string AdminPassword { get; set; } + + /// + /// The RequestLog expiration in hours (optional). + /// + [PublicAPI] + int? RequestLogExpirationDuration { get; set; } + + /// + /// The MaxRequestLog count (optional). + /// + [PublicAPI] + int? MaxRequestLogCount { get; set; } + + /// + /// Action which is called (with the IAppBuilder or IApplicationBuilder) before the internal WireMockMiddleware is initialized. [Optional] + /// + [PublicAPI] + Action PreWireMockMiddlewareInit { get; set; } + + /// + /// Action which is called (with the IAppBuilder or IApplicationBuilder) after the internal WireMockMiddleware is initialized. [Optional] + /// + [PublicAPI] + Action PostWireMockMiddlewareInit { get; set; } + + /// + /// The IWireMockLogger which logs Debug, Info, Warning or Error + /// + [PublicAPI] + IWireMockLogger Logger { get; set; } + + /// + /// Handler to interact with the file system to read and write static mapping files. + /// + [PublicAPI] + IFileSystemHandler FileSystemHandler { get; set; } + + /// + /// Action which can be used to add additional Handlebars registrations. [Optional] + /// + [PublicAPI] + Action HandlebarsRegistrationCallback { get; set; } + + /// + /// Allow the usage of CSharpCodeMatcher (default is not allowed). + /// + [PublicAPI] + bool? AllowCSharpCodeMatcher { get; set; } + + /// + /// Allow a Body for all HTTP Methods. (default set to false). + /// + [PublicAPI] + bool? AllowBodyForAllHttpMethods { get; set; } + } +} \ No newline at end of file diff --git a/src/WireMock.Net/Settings/ProxyAndRecordSettings.cs b/src/WireMock.Net/Settings/ProxyAndRecordSettings.cs index a4be77766..f802ad44b 100644 --- a/src/WireMock.Net/Settings/ProxyAndRecordSettings.cs +++ b/src/WireMock.Net/Settings/ProxyAndRecordSettings.cs @@ -7,31 +7,47 @@ namespace WireMock.Settings /// public class ProxyAndRecordSettings : IProxyAndRecordSettings { - /// + /// + /// The URL to proxy. + /// [PublicAPI] public string Url { get; set; } - /// + /// + /// Save the mapping for each request/response to the internal Mappings. + /// [PublicAPI] public bool SaveMapping { get; set; } = true; - /// + /// + /// Save the mapping for each request/response also to a file. (Note that SaveMapping must also be set to true.) + /// [PublicAPI] - public string SaveMappingForStatusCodePattern { get; set; } = "*"; + public bool SaveMappingToFile { get; set; } = true; - /// + /// + /// Only save request/response to the internal Mappings if the status code is included in this pattern. (Note that SaveMapping must also be set to true.) + /// The pattern can contain a single value like "200", but also ranges like "2xx", "100,300,600" or "100-299,6xx" are supported. + /// [PublicAPI] - public bool SaveMappingToFile { get; set; } = true; + public string SaveMappingForStatusCodePattern { get; set; } = "*"; - /// + /// + /// The clientCertificate thumbprint or subject name fragment to use. + /// Example thumbprint : "D2DBF135A8D06ACCD0E1FAD9BFB28678DF7A9818". Example subject name: "www.google.com"" + /// [PublicAPI] public string ClientX509Certificate2ThumbprintOrSubjectName { get; set; } - /// + /// + /// Defines a list from headers which will excluded from the saved mappings. + /// [PublicAPI] public string[] BlackListedHeaders { get; set; } - /// + /// + /// Defines a list of cookies which will excluded from the saved mappings. + /// [PublicAPI] public string[] BlackListedCookies { get; set; } diff --git a/src/WireMock.Net.StandAlone/SimpleCommandLineParser.cs b/src/WireMock.Net/Settings/SimpleCommandLineParser.cs similarity index 95% rename from src/WireMock.Net.StandAlone/SimpleCommandLineParser.cs rename to src/WireMock.Net/Settings/SimpleCommandLineParser.cs index 44ddf2d88..063b2c46c 100644 --- a/src/WireMock.Net.StandAlone/SimpleCommandLineParser.cs +++ b/src/WireMock.Net/Settings/SimpleCommandLineParser.cs @@ -1,87 +1,87 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace WireMock.Net.StandAlone -{ - // Based on http://blog.gauffin.org/2014/12/simple-command-line-parser/ - internal class SimpleCommandLineParser - { - private const string Sigil = "--"; - - private IDictionary Arguments { get; } = new Dictionary(); - - public void Parse(string[] arguments) - { - string currentName = null; - - var values = new List(); - - // Split a single argument on a space character to fix issue (e.g. Azure Service Fabric) when an argument is supplied like "--x abc" or '--x abc' - foreach (string arg in arguments.SelectMany(arg => arg.Split(' '))) - { - if (arg.StartsWith(Sigil)) - { - if (!string.IsNullOrEmpty(currentName)) - { - Arguments[currentName] = values.ToArray(); - } - - values.Clear(); - currentName = arg.Substring(Sigil.Length); - } - else if (string.IsNullOrEmpty(currentName)) - { - Arguments[arg] = new string[0]; - } - else - { - values.Add(arg); - } - } - - if (!string.IsNullOrEmpty(currentName)) - { - Arguments[currentName] = values.ToArray(); - } - } - - public bool Contains(string name) - { - return Arguments.ContainsKey(name); - } - - public string[] GetValues(string name, string[] defaultValue = null) - { - return Contains(name) ? Arguments[name] : defaultValue; - } - - public T GetValue(string name, Func func, T defaultValue = default(T)) - { - return Contains(name) ? func(Arguments[name]) : defaultValue; - } - - public bool GetBoolValue(string name, bool defaultValue = false) - { - return GetValue(name, values => - { - string value = values.FirstOrDefault(); - return !string.IsNullOrEmpty(value) ? bool.Parse(value) : defaultValue; - }, defaultValue); - } - - public int? GetIntValue(string name, int? defaultValue = null) - { - return GetValue(name, values => - { - string value = values.FirstOrDefault(); - return !string.IsNullOrEmpty(value) ? int.Parse(value) : defaultValue; - }, defaultValue); - } - - public string GetStringValue(string name, string defaultValue = null) - { - return GetValue(name, values => values.FirstOrDefault() ?? defaultValue, defaultValue); - } - } +using System; +using System.Collections.Generic; +using System.Linq; + +namespace WireMock.Settings +{ + // Based on http://blog.gauffin.org/2014/12/simple-command-line-parser/ + internal class SimpleCommandLineParser + { + private const string Sigil = "--"; + + private IDictionary Arguments { get; } = new Dictionary(); + + public void Parse(string[] arguments) + { + string currentName = null; + + var values = new List(); + + // Split a single argument on a space character to fix issue (e.g. Azure Service Fabric) when an argument is supplied like "--x abc" or '--x abc' + foreach (string arg in arguments.SelectMany(arg => arg.Split(' '))) + { + if (arg.StartsWith(Sigil)) + { + if (!string.IsNullOrEmpty(currentName)) + { + Arguments[currentName] = values.ToArray(); + } + + values.Clear(); + currentName = arg.Substring(Sigil.Length); + } + else if (string.IsNullOrEmpty(currentName)) + { + Arguments[arg] = new string[0]; + } + else + { + values.Add(arg); + } + } + + if (!string.IsNullOrEmpty(currentName)) + { + Arguments[currentName] = values.ToArray(); + } + } + + public bool Contains(string name) + { + return Arguments.ContainsKey(name); + } + + public string[] GetValues(string name, string[] defaultValue = null) + { + return Contains(name) ? Arguments[name] : defaultValue; + } + + public T GetValue(string name, Func func, T defaultValue = default(T)) + { + return Contains(name) ? func(Arguments[name]) : defaultValue; + } + + public bool GetBoolValue(string name, bool defaultValue = false) + { + return GetValue(name, values => + { + string value = values.FirstOrDefault(); + return !string.IsNullOrEmpty(value) ? bool.Parse(value) : defaultValue; + }, defaultValue); + } + + public int? GetIntValue(string name, int? defaultValue = null) + { + return GetValue(name, values => + { + string value = values.FirstOrDefault(); + return !string.IsNullOrEmpty(value) ? int.Parse(value) : defaultValue; + }, defaultValue); + } + + public string GetStringValue(string name, string defaultValue = null) + { + return GetValue(name, values => values.FirstOrDefault() ?? defaultValue, defaultValue); + } + } } \ No newline at end of file diff --git a/src/WireMock.Net/Settings/WireMockServerSettings.cs b/src/WireMock.Net/Settings/WireMockServerSettings.cs new file mode 100644 index 000000000..b379dd830 --- /dev/null +++ b/src/WireMock.Net/Settings/WireMockServerSettings.cs @@ -0,0 +1,105 @@ +using HandlebarsDotNet; +using JetBrains.Annotations; +using System; +using Newtonsoft.Json; +using WireMock.Handlers; +using WireMock.Logging; + +namespace WireMock.Settings +{ + /// + /// WireMockServerSettings + /// + public class WireMockServerSettings : IWireMockServerSettings + { + /// + [PublicAPI] + public int? Port { get; set; } + + /// + // ReSharper disable once InconsistentNaming + [PublicAPI] + public bool? UseSSL { get; set; } + + /// + [PublicAPI] + public bool? StartAdminInterface { get; set; } + + /// + [PublicAPI] + public bool? ReadStaticMappings { get; set; } + + /// + [PublicAPI] + public bool? WatchStaticMappings { get; set; } + + /// + [PublicAPI] + public bool? WatchStaticMappingsInSubdirectories { get; set; } + + /// + [PublicAPI] + public IProxyAndRecordSettings ProxyAndRecordSettings { get; set; } + + /// + [PublicAPI] + public string[] Urls { get; set; } + + /// + [PublicAPI] + public int StartTimeout { get; set; } = 10000; + + /// + [PublicAPI] + public bool? AllowPartialMapping { get; set; } + + /// + [PublicAPI] + public string AdminUsername { get; set; } + + /// + [PublicAPI] + public string AdminPassword { get; set; } + + /// + [PublicAPI] + public int? RequestLogExpirationDuration { get; set; } + + /// + [PublicAPI] + public int? MaxRequestLogCount { get; set; } + + /// + [PublicAPI] + [JsonIgnore] + public Action PreWireMockMiddlewareInit { get; set; } + + /// + [PublicAPI] + [JsonIgnore] + public Action PostWireMockMiddlewareInit { get; set; } + + /// + [PublicAPI] + [JsonIgnore] + public IWireMockLogger Logger { get; set; } + + /// + [PublicAPI] + [JsonIgnore] + public IFileSystemHandler FileSystemHandler { get; set; } + + /// + [PublicAPI] + [JsonIgnore] + public Action HandlebarsRegistrationCallback { get; set; } + + /// + [PublicAPI] + public bool? AllowCSharpCodeMatcher { get; set; } + + /// + [PublicAPI] + public bool? AllowBodyForAllHttpMethods { get; set; } + } +} \ No newline at end of file diff --git a/src/WireMock.Net/Settings/WireMockServerSettingsParser.cs b/src/WireMock.Net/Settings/WireMockServerSettingsParser.cs new file mode 100644 index 000000000..90a525307 --- /dev/null +++ b/src/WireMock.Net/Settings/WireMockServerSettingsParser.cs @@ -0,0 +1,89 @@ +using JetBrains.Annotations; +using WireMock.Logging; +using WireMock.Validation; + +namespace WireMock.Settings +{ + /// + /// A static helper class to parse commandline arguments into IWireMockServerSettings. + /// + public static class WireMockServerSettingsParser + { + /// + /// Parse commandline arguments into WireMockServerSettings. + /// + /// The commandline arguments + /// The logger (optional, can be null) + [PublicAPI] + public static IWireMockServerSettings ParseArguments([NotNull] string[] args, [CanBeNull] IWireMockLogger logger = null) + { + Check.HasNoNulls(args, nameof(args)); + + var parser = new SimpleCommandLineParser(); + parser.Parse(args); + + var settings = new WireMockServerSettings + { + StartAdminInterface = parser.GetBoolValue("StartAdminInterface", true), + ReadStaticMappings = parser.GetBoolValue("ReadStaticMappings"), + WatchStaticMappings = parser.GetBoolValue("WatchStaticMappings"), + AllowPartialMapping = parser.GetBoolValue("AllowPartialMapping"), + WatchStaticMappingsInSubdirectories = parser.GetBoolValue("WatchStaticMappingsInSubdirectories"), + AdminUsername = parser.GetStringValue("AdminUsername"), + AdminPassword = parser.GetStringValue("AdminPassword"), + MaxRequestLogCount = parser.GetIntValue("MaxRequestLogCount"), + RequestLogExpirationDuration = parser.GetIntValue("RequestLogExpirationDuration"), + AllowCSharpCodeMatcher = parser.GetBoolValue("AllowCSharpCodeMatcher"), + AllowBodyForAllHttpMethods = parser.GetBoolValue("AllowBodyForAllHttpMethods") + }; + + if (logger != null) + { + settings.Logger = logger; + } + + if (parser.GetStringValue("WireMockLogger") == "WireMockConsoleLogger") + { + settings.Logger = new WireMockConsoleLogger(); + } + + if (parser.Contains("Port")) + { + settings.Port = parser.GetIntValue("Port"); + } + else + { + settings.Urls = parser.GetValues("Urls", new[] { "http://*:9091/" }); + } + + string proxyURL = parser.GetStringValue("ProxyURL"); + if (!string.IsNullOrEmpty(proxyURL)) + { + settings.ProxyAndRecordSettings = new ProxyAndRecordSettings + { + Url = proxyURL, + SaveMapping = parser.GetBoolValue("SaveMapping"), + SaveMappingToFile = parser.GetBoolValue("SaveMappingToFile"), + SaveMappingForStatusCodePattern = parser.GetStringValue("SaveMappingForStatusCodePattern"), + ClientX509Certificate2ThumbprintOrSubjectName = parser.GetStringValue("ClientX509Certificate2ThumbprintOrSubjectName"), + BlackListedHeaders = parser.GetValues("BlackListedHeaders"), + BlackListedCookies = parser.GetValues("BlackListedCookies"), + AllowAutoRedirect = parser.GetBoolValue("AllowAutoRedirect") + }; + + string proxyAddress = parser.GetStringValue("WebProxyAddress"); + if (!string.IsNullOrEmpty(proxyAddress)) + { + settings.ProxyAndRecordSettings.WebProxySettings = new WebProxySettings + { + Address = proxyAddress, + UserName = parser.GetStringValue("WebProxyUserName"), + Password = parser.GetStringValue("WebProxyPassword") + }; + } + } + + return settings; + } + } +} \ No newline at end of file diff --git a/src/WireMock.Net/Transformers/ResponseMessageTransformer.cs b/src/WireMock.Net/Transformers/ResponseMessageTransformer.cs index c7bc75104..39c1acfc8 100644 --- a/src/WireMock.Net/Transformers/ResponseMessageTransformer.cs +++ b/src/WireMock.Net/Transformers/ResponseMessageTransformer.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Linq; +using WireMock.Types; using WireMock.Util; using WireMock.Validation; diff --git a/src/WireMock.Net/Util/BodyData.cs b/src/WireMock.Net/Util/BodyData.cs index 965dd9b28..4cb6bc09d 100644 --- a/src/WireMock.Net/Util/BodyData.cs +++ b/src/WireMock.Net/Util/BodyData.cs @@ -1,4 +1,5 @@ using System.Text; +using WireMock.Types; namespace WireMock.Util { diff --git a/src/WireMock.Net/Util/BodyParser.cs b/src/WireMock.Net/Util/BodyParser.cs index c9e5acb18..19ff326f3 100644 --- a/src/WireMock.Net/Util/BodyParser.cs +++ b/src/WireMock.Net/Util/BodyParser.cs @@ -7,6 +7,7 @@ using JetBrains.Annotations; using Newtonsoft.Json; using WireMock.Matchers; +using WireMock.Types; using WireMock.Validation; namespace WireMock.Util diff --git a/src/WireMock.Net/Util/QueryStringParser.cs b/src/WireMock.Net/Util/QueryStringParser.cs index b4f1b039d..279b62900 100644 --- a/src/WireMock.Net/Util/QueryStringParser.cs +++ b/src/WireMock.Net/Util/QueryStringParser.cs @@ -1,7 +1,8 @@ using System; +using System.Net; using System.Collections.Generic; using System.Linq; -using System.Net; +using WireMock.Types; namespace WireMock.Util { diff --git a/src/WireMock.Net/WireMock.Net.csproj b/src/WireMock.Net/WireMock.Net.csproj index 6518f6eeb..98855ee8f 100644 --- a/src/WireMock.Net/WireMock.Net.csproj +++ b/src/WireMock.Net/WireMock.Net.csproj @@ -65,17 +65,12 @@ - - - - - - All + + all - all runtime; build; native; contentfiles; analyzers @@ -144,4 +139,8 @@ + + + + \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Http/HttpRequestMessageHelperTests.cs b/test/WireMock.Net.Tests/Http/HttpRequestMessageHelperTests.cs index dd645b5fb..671a1444f 100644 --- a/test/WireMock.Net.Tests/Http/HttpRequestMessageHelperTests.cs +++ b/test/WireMock.Net.Tests/Http/HttpRequestMessageHelperTests.cs @@ -1,8 +1,9 @@ -using System.Collections.Generic; +using NFluent; +using System.Collections.Generic; using System.Text; -using NFluent; using WireMock.Http; using WireMock.Models; +using WireMock.Types; using WireMock.Util; using Xunit; diff --git a/test/WireMock.Net.Tests/MatchBehaviourHelperTests.cs b/test/WireMock.Net.Tests/Matchers/MatchBehaviourHelperTests.cs similarity index 96% rename from test/WireMock.Net.Tests/MatchBehaviourHelperTests.cs rename to test/WireMock.Net.Tests/Matchers/MatchBehaviourHelperTests.cs index 191901890..f941bee2f 100644 --- a/test/WireMock.Net.Tests/MatchBehaviourHelperTests.cs +++ b/test/WireMock.Net.Tests/Matchers/MatchBehaviourHelperTests.cs @@ -2,7 +2,7 @@ using WireMock.Matchers; using Xunit; -namespace WireMock.Net.Tests +namespace WireMock.Net.Tests.Matchers { public class MatchBehaviourHelperTests { diff --git a/test/WireMock.Net.Tests/ObservableLogEntriesTest.cs b/test/WireMock.Net.Tests/ObservableLogEntriesTest.cs index 13c657ded..8252c85de 100644 --- a/test/WireMock.Net.Tests/ObservableLogEntriesTest.cs +++ b/test/WireMock.Net.Tests/ObservableLogEntriesTest.cs @@ -19,18 +19,18 @@ namespace WireMock.Net.Tests public class ObservableLogEntriesTest { [Fact] - public async void FluentMockServer_LogEntriesChanged_WithException_Should_LogError() + public async void WireMockServer_LogEntriesChanged_WithException_Should_LogError() { // Assign string path = $"/log_{Guid.NewGuid()}"; var loggerMock = new Mock(); loggerMock.Setup(l => l.Error(It.IsAny(), It.IsAny())); - var settings = new FluentMockServerSettings + var settings = new WireMockServerSettings { Logger = loggerMock.Object }; - var server = FluentMockServer.Start(settings); - + var server = WireMockServer.Start(settings); + server .Given(Request.Create() .WithPath(path) @@ -48,11 +48,11 @@ public async void FluentMockServer_LogEntriesChanged_WithException_Should_LogErr } [Fact] - public async void FluentMockServer_LogEntriesChanged() + public async void WireMockServer_LogEntriesChanged() { // Assign string path = $"/log_{Guid.NewGuid()}"; - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create() @@ -72,13 +72,13 @@ public async void FluentMockServer_LogEntriesChanged() } [Fact] - public async Task FluentMockServer_LogEntriesChanged_Parallel() + public async Task WireMockServer_LogEntriesChanged_Parallel() { int expectedCount = 10; // Assign string path = $"/log_p_{Guid.NewGuid()}"; - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create() diff --git a/test/WireMock.Net.Tests/Owin/Mappers/OwinResponseMapperTests.cs b/test/WireMock.Net.Tests/Owin/Mappers/OwinResponseMapperTests.cs index 5c5f8ef7b..373804c4b 100644 --- a/test/WireMock.Net.Tests/Owin/Mappers/OwinResponseMapperTests.cs +++ b/test/WireMock.Net.Tests/Owin/Mappers/OwinResponseMapperTests.cs @@ -7,6 +7,7 @@ using WireMock.Handlers; using WireMock.Owin.Mappers; using WireMock.ResponseBuilders; +using WireMock.Types; using WireMock.Util; #if NET452 using Microsoft.Owin; diff --git a/test/WireMock.Net.Tests/Owin/WireMockMiddlewareTests.cs b/test/WireMock.Net.Tests/Owin/WireMockMiddlewareTests.cs index bcb4764e8..9c1eb3261 100644 --- a/test/WireMock.Net.Tests/Owin/WireMockMiddlewareTests.cs +++ b/test/WireMock.Net.Tests/Owin/WireMockMiddlewareTests.cs @@ -4,15 +4,15 @@ using System.Threading.Tasks; using Moq; using Xunit; -using WireMock.Admin.Mappings; using WireMock.Models; using WireMock.Owin; using WireMock.Owin.Mappers; using WireMock.Util; -using WireMock.Admin.Requests; using WireMock.Logging; using WireMock.Matchers; using System.Collections.Generic; +using WireMock.Admin.Mappings; +using WireMock.Admin.Requests; #if NET452 using Microsoft.Owin; using IContext = Microsoft.Owin.IOwinContext; diff --git a/test/WireMock.Net.Tests/RequestMatchers/RequestMessageBodyMatcherTests.cs b/test/WireMock.Net.Tests/RequestMatchers/RequestMessageBodyMatcherTests.cs index 7403f7722..6921847df 100644 --- a/test/WireMock.Net.Tests/RequestMatchers/RequestMessageBodyMatcherTests.cs +++ b/test/WireMock.Net.Tests/RequestMatchers/RequestMessageBodyMatcherTests.cs @@ -6,9 +6,11 @@ using Moq; using Newtonsoft.Json; using NFluent; +using System.Linq; using WireMock.Matchers; using WireMock.Matchers.Request; using WireMock.Models; +using WireMock.Types; using WireMock.Util; using Xunit; diff --git a/test/WireMock.Net.Tests/RequestTests.cs b/test/WireMock.Net.Tests/RequestTests.cs index ee900ffe0..32081267b 100644 --- a/test/WireMock.Net.Tests/RequestTests.cs +++ b/test/WireMock.Net.Tests/RequestTests.cs @@ -1,10 +1,11 @@ -using System.Collections.Generic; -using NFluent; -using Xunit; -using WireMock.RequestBuilders; +using NFluent; +using System.Collections.Generic; using WireMock.Matchers.Request; using WireMock.Models; +using WireMock.RequestBuilders; +using WireMock.Types; using WireMock.Util; +using Xunit; namespace WireMock.Net.Tests { diff --git a/test/WireMock.Net.Tests/RequestWithBodyTests.cs b/test/WireMock.Net.Tests/RequestWithBodyTests.cs index b496851da..82d4420f3 100644 --- a/test/WireMock.Net.Tests/RequestWithBodyTests.cs +++ b/test/WireMock.Net.Tests/RequestWithBodyTests.cs @@ -1,11 +1,12 @@ -using System; -using System.Text; -using Newtonsoft.Json; +using Newtonsoft.Json; using NFluent; +using System; +using System.Text; using WireMock.Matchers; using WireMock.Matchers.Request; using WireMock.Models; using WireMock.RequestBuilders; +using WireMock.Types; using WireMock.Util; using Xunit; diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseCreateTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseCreateTests.cs index e61af72bb..b2ae10ee5 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseCreateTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseCreateTests.cs @@ -1,6 +1,5 @@ -using Moq; +using System.Threading.Tasks; using NFluent; -using System.Threading.Tasks; using WireMock.Models; using WireMock.ResponseBuilders; using WireMock.Settings; @@ -10,7 +9,7 @@ namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseCreateTests { - private readonly Mock _settingsMock = new Mock(); + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); [Fact] public async Task Response_Create_Func() @@ -22,7 +21,7 @@ public async Task Response_Create_Func() var response = Response.Create(() => responseMessage); // Act - var providedResponse = await response.ProvideResponseAsync(request, _settingsMock.Object); + var providedResponse = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(providedResponse).Equals(responseMessage); diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithBodyFromFileTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithBodyFromFileTests.cs index b116053e4..56eaefb3e 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithBodyFromFileTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithBodyFromFileTests.cs @@ -16,7 +16,7 @@ public class ResponseWithBodyFromFileTests public async Task Response_ProvideResponse_WithBodyFromFile() { // Arrange - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); string path = Path.Combine(Directory.GetCurrentDirectory(), "__admin", "mappings", "MyXmlResponse.xml"); diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithBodyTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithBodyTests.cs index 6880de6ec..2295453d4 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithBodyTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithBodyTests.cs @@ -1,12 +1,12 @@ -using Moq; -using Newtonsoft.Json.Linq; -using NFluent; -using System; +using System; using System.Text; using System.Threading.Tasks; +using Newtonsoft.Json.Linq; +using NFluent; using WireMock.Models; using WireMock.ResponseBuilders; using WireMock.Settings; +using WireMock.Types; using WireMock.Util; using Xunit; @@ -14,7 +14,7 @@ namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithBodyTests { - private readonly Mock _settingsMock = new Mock(); + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private const string ClientIp = "::1"; [Fact] @@ -31,7 +31,7 @@ public async Task Response_ProvideResponse_WithBody_Bytes_Encoding_Destination_S var response = Response.Create().WithBody(new byte[] { 48, 49 }, BodyDestinationFormat.String, Encoding.ASCII); // act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // then Check.That(responseMessage.BodyData.BodyAsString).Equals("01"); @@ -53,7 +53,7 @@ public async Task Response_ProvideResponse_WithBody_Bytes_Encoding_Destination_B var response = Response.Create().WithBody(new byte[] { 48, 49 }, BodyDestinationFormat.SameAsSource, Encoding.ASCII); // act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // then Check.That(responseMessage.BodyData.BodyAsBytes).ContainsExactly(new byte[] { 48, 49 }); @@ -75,7 +75,7 @@ public async Task Response_ProvideResponse_WithBody_String_Encoding() var response = Response.Create().WithBody("test", null, Encoding.ASCII); // act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // then Check.That(responseMessage.BodyData.BodyAsString).Equals("test"); @@ -97,7 +97,7 @@ public async Task Response_ProvideResponse_WithBody_Object_Encoding() var response = Response.Create().WithBodyAsJson(x, Encoding.ASCII); // act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // then Check.That(responseMessage.BodyData.BodyAsJson).Equals(x); @@ -119,7 +119,7 @@ public async Task Response_ProvideResponse_WithBody_Object_Indented() var response = Response.Create().WithBodyAsJson(x, true); // act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // then Check.That(responseMessage.BodyData.BodyAsJson).Equals(x); @@ -135,7 +135,7 @@ public async Task Response_ProvideResponse_WithBody_String_SameAsSource_Encoding var response = Response.Create().WithBody("r", BodyDestinationFormat.SameAsSource, Encoding.ASCII); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsBytes).IsNull(); @@ -153,7 +153,7 @@ public async Task Response_ProvideResponse_WithBody_String_Bytes_Encoding() var response = Response.Create().WithBody("r", BodyDestinationFormat.Bytes, Encoding.ASCII); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).IsNull(); @@ -171,7 +171,7 @@ public async Task Response_ProvideResponse_WithBody_String_Json_Encoding() var response = Response.Create().WithBody("{ \"value\": 42 }", BodyDestinationFormat.Json, Encoding.ASCII); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).IsNull(); @@ -193,7 +193,7 @@ public async Task Response_ProvideResponse_WithBody_Func() .WithBody(req => $"path: {req.Path}"); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).IsEqualTo("path: /test"); @@ -221,8 +221,8 @@ public async Task Response_ProvideResponse_WithJsonBodyAndTransform_Func() .WithTransformer(); // Act - var response1Message = await response.ProvideResponseAsync(request1, _settingsMock.Object); - var response2Message = await response.ProvideResponseAsync(request2, _settingsMock.Object); + var response1Message = await response.ProvideResponseAsync(request1, _settings); + var response2Message = await response.ProvideResponseAsync(request2, _settings); // Assert Check.That(((JToken)response1Message.BodyData.BodyAsJson).SelectToken("id")?.Value()).IsEqualTo(request1Id); @@ -246,7 +246,7 @@ public async Task Response_ProvideResponse_WithBodyAsFile() var response = Response.Create().WithStatusCode(200).WithBody(fileContents); - var provideResponseAsync = await response.ProvideResponseAsync(request1, _settingsMock.Object); + var provideResponseAsync = await response.ProvideResponseAsync(request1, _settings); Check.That(provideResponseAsync.StatusCode).IsEqualTo(200); Check.That(provideResponseAsync.BodyData.BodyAsString).Contains(fileContents); @@ -262,7 +262,7 @@ public async Task Response_ProvideResponse_WithResponseAsFile() var response = Response.Create().WithStatusCode(200).WithBody(fileContents); - var provideResponseAsync = await response.ProvideResponseAsync(request1, _settingsMock.Object); + var provideResponseAsync = await response.ProvideResponseAsync(request1, _settings); Check.That(provideResponseAsync.StatusCode).IsEqualTo(200); Check.That(provideResponseAsync.BodyData.BodyAsString).Contains(fileContents); @@ -278,7 +278,7 @@ public async Task Response_ProvideResponse_WithResponseDeleted() var response = Response.Create().WithStatusCode(200).WithBody("File deleted."); - var provideResponseAsync = await response.ProvideResponseAsync(request1, _settingsMock.Object); + var provideResponseAsync = await response.ProvideResponseAsync(request1, _settings); Check.That(provideResponseAsync.StatusCode).IsEqualTo(200); Check.That(provideResponseAsync.BodyData.BodyAsString).Contains("File deleted."); diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithCallbackTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithCallbackTests.cs index e956eef71..25c7c3310 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithCallbackTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithCallbackTests.cs @@ -1,9 +1,9 @@ -using Moq; +using System.Threading.Tasks; using NFluent; -using System.Threading.Tasks; using WireMock.Models; using WireMock.ResponseBuilders; using WireMock.Settings; +using WireMock.Types; using WireMock.Util; using Xunit; @@ -11,7 +11,7 @@ namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithCallbackTests { - private readonly Mock _settingsMock = new Mock(); + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); [Fact] public async Task Response_WithCallback() @@ -21,7 +21,7 @@ public async Task Response_WithCallback() var response = Response.Create().WithCallback(req => new ResponseMessage { BodyData = new BodyData { DetectedBodyType = BodyType.String, BodyAsString = req.Path + "Bar" }, StatusCode = 302 }); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).IsEqualTo("/fooBar"); diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithFaultTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithFaultTests.cs index 53c27e357..437ae6a60 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithFaultTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithFaultTests.cs @@ -10,7 +10,7 @@ namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithFaultTests { - private readonly Mock _settingsMock = new Mock(); + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private const string ClientIp = "::1"; [Theory] @@ -23,7 +23,7 @@ public async Task Response_ProvideResponse_WithFault(FaultType faultType) // Act var response = Response.Create().WithFault(faultType); - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert responseMessage.FaultType.Should().Be(faultType); @@ -39,7 +39,7 @@ public async Task Response_ProvideResponse_WithFault_IncludingPercentage(FaultTy // Act var response = Response.Create().WithFault(faultType, percentage); - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert responseMessage.FaultType.Should().Be(faultType); diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsFileTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsFileTests.cs index 42e87c7ff..10dd3ec25 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsFileTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsFileTests.cs @@ -1,8 +1,8 @@ -using Moq; +using System; +using System.Threading.Tasks; +using Moq; using Newtonsoft.Json.Linq; using NFluent; -using System; -using System.Threading.Tasks; using WireMock.Handlers; using WireMock.Models; using WireMock.ResponseBuilders; @@ -14,7 +14,7 @@ namespace WireMock.Net.Tests.ResponseBuilders public class ResponseWithHandlebarsFileTests { private readonly Mock _filesystemHandlerMock; - private readonly Mock _settingsMock; + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private const string ClientIp = "::1"; public ResponseWithHandlebarsFileTests() @@ -22,8 +22,7 @@ public ResponseWithHandlebarsFileTests() _filesystemHandlerMock = new Mock(MockBehavior.Strict); _filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny())).Returns("abc"); - _settingsMock = new Mock(); - _settingsMock.SetupGet(s => s.FileSystemHandler).Returns(_filesystemHandlerMock.Object); + _settings.FileSystemHandler = _filesystemHandlerMock.Object; } [Fact] @@ -40,7 +39,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_File() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -65,7 +64,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_File_Replace() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -90,7 +89,7 @@ public void Response_ProvideResponseAsync_Handlebars_File_WithMissingArgument_Th .WithTransformer(); // Act - Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settingsMock.Object)).Throws(); + Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settings)).Throws(); // Verify _filesystemHandlerMock.Verify(fs => fs.ReadResponseBodyAsString(It.IsAny()), Times.Never); diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsJsonPathTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsJsonPathTests.cs index 2f3ba32a8..1b7eedc9e 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsJsonPathTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsJsonPathTests.cs @@ -1,11 +1,11 @@ -using Moq; +using System; +using System.Threading.Tasks; using Newtonsoft.Json.Linq; using NFluent; -using System; -using System.Threading.Tasks; using WireMock.Models; using WireMock.ResponseBuilders; using WireMock.Settings; +using WireMock.Types; using WireMock.Util; using Xunit; @@ -13,7 +13,7 @@ namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithHandlebarsJsonPathTests { - private readonly Mock _settingsMock = new Mock(); + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private const string ClientIp = "::1"; [Fact] @@ -63,7 +63,7 @@ public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Objec .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -89,7 +89,7 @@ public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Numbe .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -143,7 +143,7 @@ public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Reque .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).Equals($"{{{Environment.NewLine} \"Name\": \"Acme Co\",{Environment.NewLine} \"Products\": [{Environment.NewLine} {{{Environment.NewLine} \"Name\": \"Anvil\",{Environment.NewLine} \"Price\": 50{Environment.NewLine} }}{Environment.NewLine} ]{Environment.NewLine}}}"); @@ -196,7 +196,7 @@ public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Reque .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).Equals($"{{{Environment.NewLine} \"Name\": \"Acme Co\",{Environment.NewLine} \"Products\": [{Environment.NewLine} {{{Environment.NewLine} \"Name\": \"Anvil\",{Environment.NewLine} \"Price\": 50{Environment.NewLine} }}{Environment.NewLine} ]{Environment.NewLine}}}"); @@ -249,7 +249,7 @@ public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectTokens_Requ .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).Equals("%0:Anvil%%1:Elbow Grease%"); @@ -302,7 +302,7 @@ public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectTokens_Requ .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).Equals("%0:Anvil%%1:Elbow Grease%"); @@ -331,7 +331,7 @@ public void Response_ProvideResponse_Handlebars_JsonPath_SelectTokens_Throws() .WithTransformer(); // Act - Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settingsMock.Object)).Throws(); + Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settings)).Throws(); } } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsLinqTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsLinqTests.cs index 88ebf699e..72dc99fbe 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsLinqTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsLinqTests.cs @@ -1,11 +1,11 @@ -using Moq; +using System; +using System.Threading.Tasks; using Newtonsoft.Json.Linq; using NFluent; -using System; -using System.Threading.Tasks; using WireMock.Models; using WireMock.ResponseBuilders; using WireMock.Settings; +using WireMock.Types; using WireMock.Util; using Xunit; @@ -13,7 +13,7 @@ namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithHandlebarsLinqTests { - private readonly Mock _settingsMock = new Mock(); + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); [Fact] public async Task Response_ProvideResponse_Handlebars_Linq1_String0() @@ -29,7 +29,7 @@ public async Task Response_ProvideResponse_Handlebars_Linq1_String0() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -59,7 +59,7 @@ public async Task Response_ProvideResponse_Handlebars_Linq1_String1() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -89,7 +89,7 @@ public async Task Response_ProvideResponse_Handlebars_Linq1_String2() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -119,7 +119,7 @@ public async Task Response_ProvideResponse_Handlebars_Linq2_Object() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -144,7 +144,7 @@ public void Response_ProvideResponse_Handlebars_Linq_Throws_NotSupportedExceptio .WithTransformer(); // Act - Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settingsMock.Object)).Throws(); + Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settings)).Throws(); } [Fact] @@ -160,7 +160,7 @@ public void Response_ProvideResponse_Handlebars_Linq1_Throws_ArgumentNullExcepti .WithTransformer(); // Act - Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settingsMock.Object)).Throws(); + Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settings)).Throws(); } [Fact] @@ -176,7 +176,7 @@ public void Response_ProvideResponse_Handlebars_Linq1_Throws_ArgumentException() .WithTransformer(); // Act - Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settingsMock.Object)).Throws(); + Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settings)).Throws(); } [Fact] @@ -200,7 +200,7 @@ public async void Response_ProvideResponse_Handlebars_Linq1_ParseError_Returns_E .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -228,7 +228,7 @@ public async void Response_ProvideResponse_Handlebars_Linq2_ParseError_Returns_E .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsRandomTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsRandomTests.cs index db29129a5..08837988b 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsRandomTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsRandomTests.cs @@ -1,8 +1,7 @@ -using Moq; +using System.Linq; +using System.Threading.Tasks; using Newtonsoft.Json.Linq; using NFluent; -using System.Linq; -using System.Threading.Tasks; using WireMock.Models; using WireMock.ResponseBuilders; using WireMock.Settings; @@ -12,7 +11,7 @@ namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithHandlebarsRandomTests { - private readonly Mock _settingsMock = new Mock(); + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private const string ClientIp = "::1"; [Fact] @@ -32,7 +31,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_Random1() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -55,7 +54,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_Random1_Boolean() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -77,7 +76,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_Random1_Guid() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -101,7 +100,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_Random1_StringList() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -123,7 +122,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_Random2() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsRegexTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsRegexTests.cs index b47bb54f2..c719e4388 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsRegexTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsRegexTests.cs @@ -1,10 +1,10 @@ -using Moq; -using NFluent; -using System; +using System; using System.Threading.Tasks; +using NFluent; using WireMock.Models; using WireMock.ResponseBuilders; using WireMock.Settings; +using WireMock.Types; using WireMock.Util; using Xunit; @@ -12,7 +12,7 @@ namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithHandlebarsRegexTests { - private readonly Mock _settingsMock = new Mock(); + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private const string ClientIp = "::1"; [Fact] @@ -28,7 +28,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // assert Check.That(responseMessage.BodyData.BodyAsString).Equals("abc"); @@ -47,7 +47,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch_NoMatch() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // assert Check.That(responseMessage.BodyData.BodyAsString).Equals(""); @@ -66,7 +66,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch_NoMatch_Wi .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // assert Check.That(responseMessage.BodyData.BodyAsString).Equals("d"); @@ -85,7 +85,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch2() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // assert Check.That(responseMessage.BodyData.BodyAsString).Equals("5000-https"); @@ -104,7 +104,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch2_NoMatch() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // assert Check.That(responseMessage.BodyData.BodyAsString).Equals(""); @@ -123,7 +123,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_RegexMatch2_NoMatch_W .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // assert Check.That(responseMessage.BodyData.BodyAsString).Equals("x"); @@ -142,7 +142,7 @@ public void Response_ProvideResponseAsync_Handlebars_RegexMatch2_Throws() .WithTransformer(); // Act and Assert - Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settingsMock.Object)).Throws(); + Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settings)).Throws(); } } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsTests.cs index 6a6bc5e00..bca4e544a 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsTests.cs @@ -9,6 +9,7 @@ using WireMock.Models; using WireMock.ResponseBuilders; using WireMock.Settings; +using WireMock.Types; using WireMock.Util; using Xunit; #if NET452 @@ -21,7 +22,7 @@ namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithHandlebarsTests { - private readonly Mock _settingsMock = new Mock(); + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private const string ClientIp = "::1"; [Fact] @@ -40,7 +41,7 @@ public async Task Response_ProvideResponse_Handlebars_UrlPathVerb() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).Equals("test http://localhost/foo /foo POSt"); @@ -58,7 +59,7 @@ public async Task Response_ProvideResponse_Handlebars_UrlPath() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).Equals("http://localhost/a/b http://localhost/wiremock/a/b /a/b /wiremock/a/b"); @@ -76,7 +77,7 @@ public async Task Response_ProvideResponse_Handlebars_PathSegments() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).Equals("a wiremock"); @@ -98,7 +99,7 @@ public async Task Response_ProvideResponse_Handlebars_Query() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).Equals("test keya=1 idx=1 idx=2 keyb=5"); @@ -118,7 +119,7 @@ public async Task Response_ProvideResponse_Handlebars_Header() var response = Response.Create().WithHeader("x", "{{request.headers.Content-Type}}").WithBody("test").WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).Equals("test"); @@ -140,7 +141,7 @@ public async Task Response_ProvideResponse_Handlebars_Headers() var response = Response.Create().WithHeader("x", "{{request.headers.Content-Type}}", "{{request.url}}").WithBody("test").WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).Equals("test"); @@ -165,7 +166,7 @@ public async Task Response_ProvideResponse_Handlebars_Origin_Port_Protocol_Host( .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).Equals("test http://localhost:1234 1234 http localhost"); @@ -189,7 +190,7 @@ public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsObj .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson)).Equals("{\"x\":\"test /foo_object\"}"); @@ -213,7 +214,7 @@ public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsArr .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson)).Equals("[\"first\",\"/foo_array\",\"test 1\",\"test 2\",\"last\"]"); @@ -230,7 +231,7 @@ public async Task Response_ProvideResponse_Handlebars_WithBodyAsFile() .WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\\test.xml"); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsFile).Equals(@"c:\1\test.xml"); @@ -243,7 +244,7 @@ public async Task Response_ProvideResponse_Handlebars_WithBodyAsFile_And_Transfo var filesystemHandlerMock = new Mock(MockBehavior.Strict); filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny())).Returns(""); - _settingsMock.SetupGet(s => s.FileSystemHandler).Returns(filesystemHandlerMock.Object); + _settings.FileSystemHandler = filesystemHandlerMock.Object; var request = new RequestMessage(new UrlDetails("http://localhost/foo?MyUniqueNumber=1"), "GET", ClientIp); @@ -252,7 +253,7 @@ public async Task Response_ProvideResponse_Handlebars_WithBodyAsFile_And_Transfo .WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\\test.xml"); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsFile).Equals(@"c:\1\test.xml"); @@ -281,7 +282,7 @@ public async Task Response_ProvideResponse_Handlebars_WithBodyAsFile_JsonPath() .WithBodyFromFile(@"c:\\{{JsonPath.SelectToken request.body " + jsonPath + "}}\\test.json"); // why use a \\ here ? // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsFile).Equals(@"c:\1\test.json"); @@ -305,7 +306,7 @@ public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsNor .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson)).Equals("\"test\""); @@ -329,7 +330,7 @@ public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsHan .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson)).Equals("{\"name\":\"WireMock\"}"); diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsXegerTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsXegerTests.cs index dd8053d6d..e5f19b922 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsXegerTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsXegerTests.cs @@ -11,7 +11,7 @@ namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithHandlebarsXegerTests { - private readonly Mock _settingsMock = new Mock(); + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private const string ClientIp = "::1"; [Fact] @@ -29,7 +29,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_Xeger1() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); @@ -52,7 +52,7 @@ public async Task Response_ProvideResponseAsync_Handlebars_Xeger2() .WithTransformer(); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson); diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHeadersTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHeadersTests.cs index a6be05d2a..217eb325e 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHeadersTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHeadersTests.cs @@ -1,18 +1,17 @@ -using Moq; -using NFluent; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; +using NFluent; using WireMock.Models; using WireMock.ResponseBuilders; using WireMock.Settings; -using WireMock.Util; +using WireMock.Types; using Xunit; namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithHeadersTests { - private readonly Mock _settingsMock = new Mock(); + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private const string ClientIp = "::1"; [Theory] @@ -26,7 +25,7 @@ public async Task Response_ProvideResponse_WithHeader_SingleValue(string headerN IResponseBuilder builder = Response.Create().WithHeader(headerName, headerValue); // Act - var response = await builder.ProvideResponseAsync(requestMock, _settingsMock.Object); + var response = await builder.ProvideResponseAsync(requestMock, _settings); // Assert Check.That(response.Headers[headerName].ToString()).Equals(headerValue); @@ -42,7 +41,7 @@ public async Task Response_ProvideResponse_WithHeader_MultipleValues(string head IResponseBuilder builder = Response.Create().WithHeader(headerName, headerValues); // Act - var response = await builder.ProvideResponseAsync(requestMock, _settingsMock.Object); + var response = await builder.ProvideResponseAsync(requestMock, _settings); // Assert Check.That(response.Headers[headerName].ToArray()).Equals(headerValues); @@ -57,7 +56,7 @@ public async Task Response_ProvideResponse_WithHeaders_SingleValue() var response = Response.Create().WithHeaders(headers); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.Headers["h"]).ContainsExactly("x"); @@ -72,7 +71,7 @@ public async Task Response_ProvideResponse_WithHeaders_MultipleValues() var response = Response.Create().WithHeaders(headers); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.Headers["h"]).ContainsExactly("x"); @@ -87,7 +86,7 @@ public async Task Response_ProvideResponse_WithHeaders_WiremockList() var response = Response.Create().WithHeaders(headers); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.Headers["h"]).ContainsExactly("x"); diff --git a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithProxyTests.cs b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithProxyTests.cs index d25b4680b..9219e2cd5 100644 --- a/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithProxyTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithProxyTests.cs @@ -1,14 +1,14 @@ -using Moq; -using NFluent; -using System; +using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; +using NFluent; using WireMock.Models; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; using WireMock.Server; using WireMock.Settings; +using WireMock.Types; using WireMock.Util; using Xunit; @@ -16,15 +16,15 @@ namespace WireMock.Net.Tests.ResponseBuilders { public class ResponseWithProxyTests : IDisposable { - private readonly Mock _settingsMock = new Mock(); - private readonly FluentMockServer _server; + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); + private readonly WireMockServer _server; private readonly Guid _guid; public ResponseWithProxyTests() { _guid = Guid.NewGuid(); - _server = FluentMockServer.Start(); + _server = WireMockServer.Start(); _server.Given(Request.Create().UsingPost().WithPath($"/{_guid}")) .RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 42 }).WithHeader("Content-Type", "application/json")); } @@ -38,7 +38,7 @@ public async Task Response_WithProxy() var response = Response.Create().WithProxy(_server.Urls[0]); // Act - var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object); + var responseMessage = await response.ProvideResponseAsync(request, _settings); // Assert Check.That(responseMessage.BodyData.BodyAsString).IsEqualTo("{\"p\":42}"); @@ -65,7 +65,7 @@ public void Response_WithProxy_WebProxySettings() // Act var request = new RequestMessage(new UrlDetails($"{_server.Urls[0]}/{_guid}"), "GET", "::1"); - Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settingsMock.Object)).Throws(); + Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settings)).Throws(); } public void Dispose() diff --git a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.cs b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.cs index 6838e40f4..0248c7b29 100644 --- a/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.cs +++ b/test/WireMock.Net.Tests/Serialization/LogEntryMapperTests.cs @@ -4,6 +4,7 @@ using WireMock.Models; using WireMock.ResponseBuilders; using WireMock.Serialization; +using WireMock.Types; using WireMock.Util; using Xunit; diff --git a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.cs b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.cs index e3935941c..95f2e667c 100644 --- a/test/WireMock.Net.Tests/Serialization/MappingConverterTests.cs +++ b/test/WireMock.Net.Tests/Serialization/MappingConverterTests.cs @@ -11,13 +11,13 @@ namespace WireMock.Net.Tests.Serialization { public class MappingConverterTests { - private readonly Mock _settingsMock = new Mock(); + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private readonly MappingConverter _sut; public MappingConverterTests() { - _sut = new MappingConverter(new MatcherMapper(_settingsMock.Object)); + _sut = new MappingConverter(new MatcherMapper(_settings)); } [Fact] @@ -26,7 +26,7 @@ public void ToMappingModel() // Assign var request = Request.Create(); var response = Response.Create(); - var mapping = new Mapping(Guid.NewGuid(), "", null, _settingsMock.Object, request, response, 0, null, null, null); + var mapping = new Mapping(Guid.NewGuid(), "", null, _settings, request, response, 0, null, null, null); // Act var model = _sut.ToMappingModel(mapping); @@ -44,7 +44,7 @@ public void ToMappingModel_WithPriority_ReturnsPriority() // Assign var request = Request.Create(); var response = Response.Create().WithBodyAsJson(new { x = "x" }).WithTransformer(); - var mapping = new Mapping(Guid.NewGuid(), "", null, _settingsMock.Object, request, response, 42, null, null, null); + var mapping = new Mapping(Guid.NewGuid(), "", null, _settings, request, response, 42, null, null, null); // Act var model = _sut.ToMappingModel(mapping); diff --git a/test/WireMock.Net.Tests/Serialization/MatcherMapperTests.cs b/test/WireMock.Net.Tests/Serialization/MatcherMapperTests.cs index 2da75e4d9..2ebacdf8a 100644 --- a/test/WireMock.Net.Tests/Serialization/MatcherMapperTests.cs +++ b/test/WireMock.Net.Tests/Serialization/MatcherMapperTests.cs @@ -1,6 +1,6 @@ -using System; -using Moq; +using Moq; using NFluent; +using System; using WireMock.Admin.Mappings; using WireMock.Matchers; using WireMock.Serialization; @@ -11,16 +11,12 @@ namespace WireMock.Net.Tests.Serialization { public class MatcherMapperTests { - private readonly Mock _settingsMock; - + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private readonly MatcherMapper _sut; public MatcherMapperTests() { - _settingsMock = new Mock(); - _settingsMock.SetupAllProperties(); - - _sut = new MatcherMapper(_settingsMock.Object); + _sut = new MatcherMapper(_settings); } [Fact] diff --git a/test/WireMock.Net.Tests/Serialization/MatcherModelMapperTests.cs b/test/WireMock.Net.Tests/Serialization/MatcherModelMapperTests.cs index e98878ce3..5de718ac8 100644 --- a/test/WireMock.Net.Tests/Serialization/MatcherModelMapperTests.cs +++ b/test/WireMock.Net.Tests/Serialization/MatcherModelMapperTests.cs @@ -1,5 +1,4 @@ using System; -using Moq; using NFluent; using WireMock.Admin.Mappings; using WireMock.Matchers; @@ -11,16 +10,13 @@ namespace WireMock.Net.Tests.Serialization { public class MatcherModelMapperTests { - private readonly Mock _settingsMock; + private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private readonly MatcherMapper _sut; public MatcherModelMapperTests() { - _settingsMock = new Mock(); - _settingsMock.SetupAllProperties(); - - _sut = new MatcherMapper(_settingsMock.Object); + _sut = new MatcherMapper(_settings); } [Fact] diff --git a/test/WireMock.Net.Tests/StandAlone/SimpleCommandLineParserTests.cs b/test/WireMock.Net.Tests/Settings/SimpleCommandLineParserTests.cs similarity index 97% rename from test/WireMock.Net.Tests/StandAlone/SimpleCommandLineParserTests.cs rename to test/WireMock.Net.Tests/Settings/SimpleCommandLineParserTests.cs index 0fbd48745..17ad2690a 100644 --- a/test/WireMock.Net.Tests/StandAlone/SimpleCommandLineParserTests.cs +++ b/test/WireMock.Net.Tests/Settings/SimpleCommandLineParserTests.cs @@ -1,8 +1,8 @@ using NFluent; -using WireMock.Net.StandAlone; +using WireMock.Settings; using Xunit; -namespace WireMock.Net.Tests.StandAlone +namespace WireMock.Net.Tests.Settings { public class SimpleCommandLineParserTests { diff --git a/test/WireMock.Net.Tests/StatefulBehaviorTests.cs b/test/WireMock.Net.Tests/StatefulBehaviorTests.cs index 9b511da53..4f5c4e6f7 100644 --- a/test/WireMock.Net.Tests/StatefulBehaviorTests.cs +++ b/test/WireMock.Net.Tests/StatefulBehaviorTests.cs @@ -18,7 +18,7 @@ public async Task Scenarios_Should_skip_non_relevant_states() { // given string path = $"/foo_{Guid.NewGuid()}"; - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path).UsingGet()) @@ -38,7 +38,7 @@ public async Task Scenarios_Should_process_request_if_equals_state_and_single_st { // given string path = $"/foo_{Guid.NewGuid()}"; - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path).UsingGet()) @@ -66,7 +66,7 @@ public async Task Scenarios_Should_Respect_Int_Valued_Scenarios_and_States() { // given string path = $"/foo_{Guid.NewGuid()}"; - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path).UsingGet()) @@ -94,7 +94,7 @@ public async Task Scenarios_Should_Respect_Mixed_String_Scenario_and_Int_State() { // given string path = $"/foo_{Guid.NewGuid()}"; - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path).UsingGet()) @@ -122,7 +122,7 @@ public async Task Scenarios_Should_Respect_Mixed_Int_Scenario_and_String_Scenari { // given string path = $"/foo_{Guid.NewGuid()}"; - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path).UsingGet()) @@ -149,7 +149,7 @@ public async Task Scenarios_Should_Respect_Mixed_Int_Scenario_and_String_Scenari public async Task Scenarios_TodoList_Example() { // Assign - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath("/todo/items").UsingGet()) @@ -203,7 +203,7 @@ public async Task Scenarios_TodoList_Example() public async Task Scenarios_Should_process_request_if_equals_state_and_multiple_state_defined() { // Assign - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath("/state1").UsingGet()) diff --git a/test/WireMock.Net.Tests/Util/BodyParserTests.cs b/test/WireMock.Net.Tests/Util/BodyParserTests.cs index 70369e0ff..b64401654 100644 --- a/test/WireMock.Net.Tests/Util/BodyParserTests.cs +++ b/test/WireMock.Net.Tests/Util/BodyParserTests.cs @@ -2,6 +2,7 @@ using System.IO; using System.Text; using System.Threading.Tasks; +using WireMock.Types; using WireMock.Util; using Xunit; diff --git a/test/WireMock.Net.Tests/Util/QueryStringParserTests.cs b/test/WireMock.Net.Tests/Util/QueryStringParserTests.cs index 3fccb783d..14b3a0ff0 100644 --- a/test/WireMock.Net.Tests/Util/QueryStringParserTests.cs +++ b/test/WireMock.Net.Tests/Util/QueryStringParserTests.cs @@ -1,5 +1,6 @@ using FluentAssertions; using System.Collections.Generic; +using WireMock.Types; using WireMock.Util; using Xunit; diff --git a/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj b/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj index ec43cd296..68ec5c766 100644 --- a/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj +++ b/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj @@ -25,11 +25,8 @@ - - - - - + + @@ -41,7 +38,7 @@ - + diff --git a/test/WireMock.Net.Tests/FluentMockServerAdminRestClientTests.cs b/test/WireMock.Net.Tests/WireMockAdminApiTests.cs similarity index 77% rename from test/WireMock.Net.Tests/FluentMockServerAdminRestClientTests.cs rename to test/WireMock.Net.Tests/WireMockAdminApiTests.cs index 117680b4c..e921dddf1 100644 --- a/test/WireMock.Net.Tests/FluentMockServerAdminRestClientTests.cs +++ b/test/WireMock.Net.Tests/WireMockAdminApiTests.cs @@ -1,502 +1,502 @@ -using System; -using System.Linq; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Threading.Tasks; -using Moq; -using NFluent; -using RestEase; -using WireMock.Admin.Mappings; -using WireMock.Admin.Settings; -using WireMock.Client; -using WireMock.Handlers; -using WireMock.Logging; -using WireMock.Server; -using WireMock.Settings; -using Xunit; - -namespace WireMock.Net.Tests -{ - public class FluentMockServerAdminRestClientTests - { - [Fact] - public async Task IFluentMockServerAdmin_GetSettingsAsync() - { - // Arrange - var server = FluentMockServer.StartWithAdminInterface(); - var api = RestClient.For(server.Urls[0]); - - // Act - var settings = await api.GetSettingsAsync(); - Check.That(settings).IsNotNull(); - } - - [Fact] - public async Task IFluentMockServerAdmin_PostSettingsAsync() - { - // Arrange - var server = FluentMockServer.StartWithAdminInterface(); - var api = RestClient.For(server.Urls[0]); - - // Act - var settings = new SettingsModel(); - var status = await api.PostSettingsAsync(settings); - Check.That(status.Status).Equals("Settings updated"); - } - - [Fact] - public async Task IFluentMockServerAdmin_PutSettingsAsync() - { - // Arrange - var server = FluentMockServer.StartWithAdminInterface(); - var api = RestClient.For(server.Urls[0]); - - // Act - var settings = new SettingsModel(); - var status = await api.PutSettingsAsync(settings); - Check.That(status.Status).Equals("Settings updated"); - } - - // https://github.com/WireMock-Net/WireMock.Net/issues/325 - [Fact] - public async Task IFluentMockServerAdmin_PutMappingAsync() - { - // Arrange - var server = FluentMockServer.StartWithAdminInterface(); - var api = RestClient.For(server.Urls[0]); - - // Act - var model = new MappingModel - { - Request = new RequestModel { Path = "/1" }, - Response = new ResponseModel { Body = "txt", StatusCode = 200 }, - Priority = 500, - Title = "test" - }; - var result = await api.PutMappingAsync(new Guid("a0000000-0000-0000-0000-000000000000"), model); - - // Assert - Check.That(result).IsNotNull(); - Check.That(result.Status).Equals("Mapping added or updated"); - Check.That(result.Guid).IsNotNull(); - - var mapping = server.Mappings.Single(m => m.Priority == 500); - Check.That(mapping).IsNotNull(); - Check.That(mapping.Title).Equals("test"); - - server.Stop(); - } - - [Fact] - public async Task IFluentMockServerAdmin_PostMappingAsync() - { - // Arrange - var server = FluentMockServer.StartWithAdminInterface(); - var api = RestClient.For(server.Urls[0]); - - // Act - var model = new MappingModel - { - Request = new RequestModel { Path = "/1" }, - Response = new ResponseModel { Body = "txt", StatusCode = 200 }, - Priority = 500, - Title = "test" - }; - var result = await api.PostMappingAsync(model); - - // Assert - Check.That(result).IsNotNull(); - Check.That(result.Status).IsNotNull(); - Check.That(result.Guid).IsNotNull(); - - var mapping = server.Mappings.Single(m => m.Priority == 500); - Check.That(mapping).IsNotNull(); - Check.That(mapping.Title).Equals("test"); - - server.Stop(); - } - - [Fact] - public async Task IFluentMockServerAdmin_PostMappingsAsync() - { - // Arrange - var server = FluentMockServer.StartWithAdminInterface(); - var api = RestClient.For(server.Urls[0]); - - // Act - var model1 = new MappingModel - { - Request = new RequestModel { Path = "/1" }, - Response = new ResponseModel { Body = "txt 1" }, - Title = "test 1" - }; - var model2 = new MappingModel - { - Request = new RequestModel { Path = "/2" }, - Response = new ResponseModel { Body = "txt 2" }, - Title = "test 2" - }; - var result = await api.PostMappingsAsync(new[] { model1, model2 }); - - // Assert - Check.That(result).IsNotNull(); - Check.That(result.Status).IsNotNull(); - Check.That(result.Guid).IsNull(); - Check.That(server.Mappings.Where(m => !m.IsAdminInterface)).HasSize(2); - - server.Stop(); - } - - [Fact] - public async Task IFluentMockServerAdmin_FindRequestsAsync() - { - // Arrange - var server = FluentMockServer.Start(new FluentMockServerSettings - { - StartAdminInterface = true, - Logger = new WireMockNullLogger() - }); - var serverUrl = "http://localhost:" + server.Ports[0]; - await new HttpClient().GetAsync(serverUrl + "/foo"); - var api = RestClient.For(serverUrl); - - // Act - var requests = await api.FindRequestsAsync(new RequestModel { Methods = new[] { "GET" } }); - - // Assert - Check.That(requests).HasSize(1); - var requestLogged = requests.First(); - Check.That(requestLogged.Request.Method).IsEqualTo("GET"); - Check.That(requestLogged.Request.Body).IsNull(); - Check.That(requestLogged.Request.Path).IsEqualTo("/foo"); - } - - [Fact] - public async Task IFluentMockServerAdmin_GetRequestsAsync() - { - // Arrange - var server = FluentMockServer.Start(new FluentMockServerSettings - { - StartAdminInterface = true, - Logger = new WireMockNullLogger() - }); - var serverUrl = "http://localhost:" + server.Ports[0]; - await new HttpClient().GetAsync(serverUrl + "/foo"); - var api = RestClient.For(serverUrl); - - // Act - var requests = await api.GetRequestsAsync(); - - // Assert - Check.That(requests).HasSize(1); - var requestLogged = requests.First(); - Check.That(requestLogged.Request.Method).IsEqualTo("GET"); - Check.That(requestLogged.Request.Body).IsNull(); - Check.That(requestLogged.Request.Path).IsEqualTo("/foo"); - } - - [Fact] - public async Task IFluentMockServerAdmin_GetRequestsAsync_JsonApi() - { - // Arrange - var server = FluentMockServer.Start(new FluentMockServerSettings - { - StartAdminInterface = true, - Logger = new WireMockNullLogger() - }); - string serverUrl = server.Urls[0]; - string data = "{\"data\":[{\"type\":\"program\",\"attributes\":{\"alias\":\"T000001\",\"title\":\"Title Group Entity\"}}]}"; - string jsonApiAcceptHeader = "application/vnd.api+json"; - string jsonApiContentType = "application/vnd.api+json"; - - var request = new HttpRequestMessage(HttpMethod.Post, serverUrl); - request.Headers.Accept.Clear(); - request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(jsonApiAcceptHeader)); - request.Content = new StringContent(data); - request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType); - - var response = await new HttpClient().SendAsync(request); - Check.That(response).IsNotNull(); - - var api = RestClient.For(serverUrl); - - // Act - var requests = await api.GetRequestsAsync(); - - // Assert - Check.That(requests).HasSize(1); - var requestLogged = requests.First(); - Check.That(requestLogged.Request.Method).IsEqualTo("POST"); - Check.That(requestLogged.Request.Body).IsNotNull(); - Check.That(requestLogged.Request.Body).Contains("T000001"); - } - - [Fact] - public async Task IFluentMockServerAdmin_GetRequestsAsync_Json() - { - // Arrange - var server = FluentMockServer.Start(new FluentMockServerSettings - { - StartAdminInterface = true, - Logger = new WireMockNullLogger() - }); - string serverUrl = server.Urls[0]; - string data = "{\"alias\": \"T000001\"}"; - string jsonAcceptHeader = "application/json"; - string jsonApiContentType = "application/json"; - - var request = new HttpRequestMessage(HttpMethod.Post, serverUrl); - request.Headers.Accept.Clear(); - request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(jsonAcceptHeader)); - request.Content = new StringContent(data); - request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType); - var response = await new HttpClient().SendAsync(request); - Check.That(response).IsNotNull(); - - var api = RestClient.For(serverUrl); - - // Act - var requests = await api.GetRequestsAsync(); - - // Assert - Check.That(requests).HasSize(1); - var requestLogged = requests.First(); - Check.That(requestLogged.Request.Method).IsEqualTo("POST"); - Check.That(requestLogged.Request.Body).IsNotNull(); - Check.That(requestLogged.Request.Body).Contains("T000001"); - } - - [Fact] - public async Task IFluentMockServerAdmin_PostFileAsync_Ascii() - { - // Arrange - var filesystemHandlerMock = new Mock(MockBehavior.Strict); - filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("__admin/mappings"); - filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny())).Returns(true); - filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny(), It.IsAny())); - - var server = FluentMockServer.Start(new FluentMockServerSettings - { - UseSSL = false, - StartAdminInterface = true, - FileSystemHandler = filesystemHandlerMock.Object - }); - - var api = RestClient.For(server.Urls[0]); - - // Act - var request = await api.PostFileAsync("filename.txt", "abc"); - - // Assert - Check.That(request.Guid).IsNull(); - Check.That(request.Status).Contains("File"); - - // Verify - filesystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Once); - filesystemHandlerMock.Verify(fs => fs.FolderExists(It.IsAny()), Times.Once); - filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is(p => p == "filename.txt"), It.IsAny()), Times.Once); - filesystemHandlerMock.VerifyNoOtherCalls(); - - server.Stop(); - } - - [Fact] - public async Task IFluentMockServerAdmin_PutFileAsync_Ascii() - { - // Arrange - var filesystemHandlerMock = new Mock(MockBehavior.Strict); - filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(true); - filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny(), It.IsAny())); - - var server = FluentMockServer.Start(new FluentMockServerSettings - { - UseSSL = false, - StartAdminInterface = true, - FileSystemHandler = filesystemHandlerMock.Object - }); - - var api = RestClient.For(server.Urls[0]); - - // Act - var request = await api.PutFileAsync("filename.txt", "abc-abc"); - - // Assert - Check.That(request.Guid).IsNull(); - Check.That(request.Status).Contains("File"); - - // Verify - filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is(p => p == "filename.txt"), It.IsAny()), Times.Once); - filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); - filesystemHandlerMock.VerifyNoOtherCalls(); - - server.Stop(); - } - - [Fact] - public void IFluentMockServerAdmin_PutFileAsync_NotFound() - { - // Arrange - var filesystemHandlerMock = new Mock(MockBehavior.Strict); - filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(false); - - var server = FluentMockServer.Start(new FluentMockServerSettings - { - UseSSL = false, - StartAdminInterface = true, - FileSystemHandler = filesystemHandlerMock.Object - }); - - var api = RestClient.For(server.Urls[0]); - - // Act and Assert - Check.ThatAsyncCode(() => api.PutFileAsync("filename.txt", "xxx")).Throws(); - - // Verify - filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); - filesystemHandlerMock.VerifyNoOtherCalls(); - - server.Stop(); - } - - [Fact] - public void IFluentMockServerAdmin_GetFileAsync_NotFound() - { - // Arrange - var filesystemHandlerMock = new Mock(MockBehavior.Strict); - filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(false); - filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny())).Returns(Encoding.ASCII.GetBytes("Here's a string.")); - - var server = FluentMockServer.Start(new FluentMockServerSettings - { - UseSSL = false, - StartAdminInterface = true, - FileSystemHandler = filesystemHandlerMock.Object - }); - - var api = RestClient.For(server.Urls[0]); - - // Act and Assert - Check.ThatAsyncCode(() => api.GetFileAsync("filename.txt")).Throws(); - - // Verify - filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); - filesystemHandlerMock.VerifyNoOtherCalls(); - - server.Stop(); - } - - [Fact] - public async Task IFluentMockServerAdmin_GetFileAsync_Found() - { - // Arrange - string data = "Here's a string."; - var filesystemHandlerMock = new Mock(MockBehavior.Strict); - filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(true); - filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny())).Returns(Encoding.ASCII.GetBytes(data)); - - var server = FluentMockServer.Start(new FluentMockServerSettings - { - UseSSL = false, - StartAdminInterface = true, - FileSystemHandler = filesystemHandlerMock.Object - }); - - var api = RestClient.For(server.Urls[0]); - - // Act - string file = await api.GetFileAsync("filename.txt"); - - // Assert - Check.That(file).Equals(data); - - // Verify - filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); - filesystemHandlerMock.Verify(fs => fs.ReadFile(It.Is(p => p == "filename.txt")), Times.Once); - filesystemHandlerMock.VerifyNoOtherCalls(); - - server.Stop(); - } - - [Fact] - public async Task IFluentMockServerAdmin_DeleteFileAsync_Ok() - { - // Arrange - var filesystemHandlerMock = new Mock(MockBehavior.Strict); - filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(true); - filesystemHandlerMock.Setup(fs => fs.DeleteFile(It.IsAny())); - - var server = FluentMockServer.Start(new FluentMockServerSettings - { - UseSSL = false, - StartAdminInterface = true, - FileSystemHandler = filesystemHandlerMock.Object - }); - - var api = RestClient.For(server.Urls[0]); - - // Act - await api.DeleteFileAsync("filename.txt"); - - // Verify - filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); - filesystemHandlerMock.Verify(fs => fs.DeleteFile(It.Is(p => p == "filename.txt")), Times.Once); - filesystemHandlerMock.VerifyNoOtherCalls(); - - server.Stop(); - } - - [Fact] - public void IFluentMockServerAdmin_DeleteFileAsync_NotFound() - { - // Arrange - var filesystemHandlerMock = new Mock(MockBehavior.Strict); - filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(false); - filesystemHandlerMock.Setup(fs => fs.DeleteFile(It.IsAny())); - - var server = FluentMockServer.Start(new FluentMockServerSettings - { - UseSSL = false, - StartAdminInterface = true, - FileSystemHandler = filesystemHandlerMock.Object - }); - - var api = RestClient.For(server.Urls[0]); - - // Act and Assert - Check.ThatAsyncCode(() => api.DeleteFileAsync("filename.txt")).Throws(); - - // Verify - filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); - filesystemHandlerMock.VerifyNoOtherCalls(); - - server.Stop(); - } - - [Fact] - public void IFluentMockServerAdmin_FileExistsAsync_NotFound() - { - // Arrange - var filesystemHandlerMock = new Mock(MockBehavior.Strict); - filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(false); - - var server = FluentMockServer.Start(new FluentMockServerSettings - { - UseSSL = false, - StartAdminInterface = true, - FileSystemHandler = filesystemHandlerMock.Object - }); - - var api = RestClient.For(server.Urls[0]); - - // Act and Assert - Check.ThatAsyncCode(() => api.FileExistsAsync("filename.txt")).Throws(); - - // Verify - filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); - filesystemHandlerMock.VerifyNoOtherCalls(); - - server.Stop(); - } - } +using System; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +using Moq; +using NFluent; +using RestEase; +using WireMock.Admin.Mappings; +using WireMock.Admin.Settings; +using WireMock.Client; +using WireMock.Handlers; +using WireMock.Logging; +using WireMock.Server; +using WireMock.Settings; +using Xunit; + +namespace WireMock.Net.Tests +{ + public class WireMockAdminApiTests + { + [Fact] + public async Task IWireMockAdminApi_GetSettingsAsync() + { + // Arrange + var server = WireMockServer.StartWithAdminInterface(); + var api = RestClient.For(server.Urls[0]); + + // Act + var settings = await api.GetSettingsAsync(); + Check.That(settings).IsNotNull(); + } + + [Fact] + public async Task IWireMockAdminApi_PostSettingsAsync() + { + // Arrange + var server = WireMockServer.StartWithAdminInterface(); + var api = RestClient.For(server.Urls[0]); + + // Act + var settings = new SettingsModel(); + var status = await api.PostSettingsAsync(settings); + Check.That(status.Status).Equals("Settings updated"); + } + + [Fact] + public async Task IWireMockAdminApi_PutSettingsAsync() + { + // Arrange + var server = WireMockServer.StartWithAdminInterface(); + var api = RestClient.For(server.Urls[0]); + + // Act + var settings = new SettingsModel(); + var status = await api.PutSettingsAsync(settings); + Check.That(status.Status).Equals("Settings updated"); + } + + // https://github.com/WireMock-Net/WireMock.Net/issues/325 + [Fact] + public async Task IWireMockAdminApi_PutMappingAsync() + { + // Arrange + var server = WireMockServer.StartWithAdminInterface(); + var api = RestClient.For(server.Urls[0]); + + // Act + var model = new MappingModel + { + Request = new RequestModel { Path = "/1" }, + Response = new ResponseModel { Body = "txt", StatusCode = 200 }, + Priority = 500, + Title = "test" + }; + var result = await api.PutMappingAsync(new Guid("a0000000-0000-0000-0000-000000000000"), model); + + // Assert + Check.That(result).IsNotNull(); + Check.That(result.Status).Equals("Mapping added or updated"); + Check.That(result.Guid).IsNotNull(); + + var mapping = server.Mappings.Single(m => m.Priority == 500); + Check.That(mapping).IsNotNull(); + Check.That(mapping.Title).Equals("test"); + + server.Stop(); + } + + [Fact] + public async Task IWireMockAdminApi_PostMappingAsync() + { + // Arrange + var server = WireMockServer.StartWithAdminInterface(); + var api = RestClient.For(server.Urls[0]); + + // Act + var model = new MappingModel + { + Request = new RequestModel { Path = "/1" }, + Response = new ResponseModel { Body = "txt", StatusCode = 200 }, + Priority = 500, + Title = "test" + }; + var result = await api.PostMappingAsync(model); + + // Assert + Check.That(result).IsNotNull(); + Check.That(result.Status).IsNotNull(); + Check.That(result.Guid).IsNotNull(); + + var mapping = server.Mappings.Single(m => m.Priority == 500); + Check.That(mapping).IsNotNull(); + Check.That(mapping.Title).Equals("test"); + + server.Stop(); + } + + [Fact] + public async Task IWireMockAdminApi_PostMappingsAsync() + { + // Arrange + var server = WireMockServer.StartWithAdminInterface(); + var api = RestClient.For(server.Urls[0]); + + // Act + var model1 = new MappingModel + { + Request = new RequestModel { Path = "/1" }, + Response = new ResponseModel { Body = "txt 1" }, + Title = "test 1" + }; + var model2 = new MappingModel + { + Request = new RequestModel { Path = "/2" }, + Response = new ResponseModel { Body = "txt 2" }, + Title = "test 2" + }; + var result = await api.PostMappingsAsync(new[] { model1, model2 }); + + // Assert + Check.That(result).IsNotNull(); + Check.That(result.Status).IsNotNull(); + Check.That(result.Guid).IsNull(); + Check.That(server.Mappings.Where(m => !m.IsAdminInterface)).HasSize(2); + + server.Stop(); + } + + [Fact] + public async Task IWireMockAdminApi_FindRequestsAsync() + { + // Arrange + var server = WireMockServer.Start(new WireMockServerSettings + { + StartAdminInterface = true, + Logger = new WireMockNullLogger() + }); + var serverUrl = "http://localhost:" + server.Ports[0]; + await new HttpClient().GetAsync(serverUrl + "/foo"); + var api = RestClient.For(serverUrl); + + // Act + var requests = await api.FindRequestsAsync(new RequestModel { Methods = new[] { "GET" } }); + + // Assert + Check.That(requests).HasSize(1); + var requestLogged = requests.First(); + Check.That(requestLogged.Request.Method).IsEqualTo("GET"); + Check.That(requestLogged.Request.Body).IsNull(); + Check.That(requestLogged.Request.Path).IsEqualTo("/foo"); + } + + [Fact] + public async Task IWireMockAdminApi_GetRequestsAsync() + { + // Arrange + var server = WireMockServer.Start(new WireMockServerSettings + { + StartAdminInterface = true, + Logger = new WireMockNullLogger() + }); + var serverUrl = "http://localhost:" + server.Ports[0]; + await new HttpClient().GetAsync(serverUrl + "/foo"); + var api = RestClient.For(serverUrl); + + // Act + var requests = await api.GetRequestsAsync(); + + // Assert + Check.That(requests).HasSize(1); + var requestLogged = requests.First(); + Check.That(requestLogged.Request.Method).IsEqualTo("GET"); + Check.That(requestLogged.Request.Body).IsNull(); + Check.That(requestLogged.Request.Path).IsEqualTo("/foo"); + } + + [Fact] + public async Task IWireMockAdminApi_GetRequestsAsync_JsonApi() + { + // Arrange + var server = WireMockServer.Start(new WireMockServerSettings + { + StartAdminInterface = true, + Logger = new WireMockNullLogger() + }); + string serverUrl = server.Urls[0]; + string data = "{\"data\":[{\"type\":\"program\",\"attributes\":{\"alias\":\"T000001\",\"title\":\"Title Group Entity\"}}]}"; + string jsonApiAcceptHeader = "application/vnd.api+json"; + string jsonApiContentType = "application/vnd.api+json"; + + var request = new HttpRequestMessage(HttpMethod.Post, serverUrl); + request.Headers.Accept.Clear(); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(jsonApiAcceptHeader)); + request.Content = new StringContent(data); + request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType); + + var response = await new HttpClient().SendAsync(request); + Check.That(response).IsNotNull(); + + var api = RestClient.For(serverUrl); + + // Act + var requests = await api.GetRequestsAsync(); + + // Assert + Check.That(requests).HasSize(1); + var requestLogged = requests.First(); + Check.That(requestLogged.Request.Method).IsEqualTo("POST"); + Check.That(requestLogged.Request.Body).IsNotNull(); + Check.That(requestLogged.Request.Body).Contains("T000001"); + } + + [Fact] + public async Task IWireMockAdminApi_GetRequestsAsync_Json() + { + // Arrange + var server = WireMockServer.Start(new WireMockServerSettings + { + StartAdminInterface = true, + Logger = new WireMockNullLogger() + }); + string serverUrl = server.Urls[0]; + string data = "{\"alias\": \"T000001\"}"; + string jsonAcceptHeader = "application/json"; + string jsonApiContentType = "application/json"; + + var request = new HttpRequestMessage(HttpMethod.Post, serverUrl); + request.Headers.Accept.Clear(); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(jsonAcceptHeader)); + request.Content = new StringContent(data); + request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType); + var response = await new HttpClient().SendAsync(request); + Check.That(response).IsNotNull(); + + var api = RestClient.For(serverUrl); + + // Act + var requests = await api.GetRequestsAsync(); + + // Assert + Check.That(requests).HasSize(1); + var requestLogged = requests.First(); + Check.That(requestLogged.Request.Method).IsEqualTo("POST"); + Check.That(requestLogged.Request.Body).IsNotNull(); + Check.That(requestLogged.Request.Body).Contains("T000001"); + } + + [Fact] + public async Task IWireMockAdminApi_PostFileAsync_Ascii() + { + // Arrange + var filesystemHandlerMock = new Mock(MockBehavior.Strict); + filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("__admin/mappings"); + filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny())).Returns(true); + filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny(), It.IsAny())); + + var server = WireMockServer.Start(new WireMockServerSettings + { + UseSSL = false, + StartAdminInterface = true, + FileSystemHandler = filesystemHandlerMock.Object + }); + + var api = RestClient.For(server.Urls[0]); + + // Act + var request = await api.PostFileAsync("filename.txt", "abc"); + + // Assert + Check.That(request.Guid).IsNull(); + Check.That(request.Status).Contains("File"); + + // Verify + filesystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Once); + filesystemHandlerMock.Verify(fs => fs.FolderExists(It.IsAny()), Times.Once); + filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is(p => p == "filename.txt"), It.IsAny()), Times.Once); + filesystemHandlerMock.VerifyNoOtherCalls(); + + server.Stop(); + } + + [Fact] + public async Task IWireMockAdminApi_PutFileAsync_Ascii() + { + // Arrange + var filesystemHandlerMock = new Mock(MockBehavior.Strict); + filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(true); + filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny(), It.IsAny())); + + var server = WireMockServer.Start(new WireMockServerSettings + { + UseSSL = false, + StartAdminInterface = true, + FileSystemHandler = filesystemHandlerMock.Object + }); + + var api = RestClient.For(server.Urls[0]); + + // Act + var request = await api.PutFileAsync("filename.txt", "abc-abc"); + + // Assert + Check.That(request.Guid).IsNull(); + Check.That(request.Status).Contains("File"); + + // Verify + filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is(p => p == "filename.txt"), It.IsAny()), Times.Once); + filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); + filesystemHandlerMock.VerifyNoOtherCalls(); + + server.Stop(); + } + + [Fact] + public void IWireMockAdminApi_PutFileAsync_NotFound() + { + // Arrange + var filesystemHandlerMock = new Mock(MockBehavior.Strict); + filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(false); + + var server = WireMockServer.Start(new WireMockServerSettings + { + UseSSL = false, + StartAdminInterface = true, + FileSystemHandler = filesystemHandlerMock.Object + }); + + var api = RestClient.For(server.Urls[0]); + + // Act and Assert + Check.ThatAsyncCode(() => api.PutFileAsync("filename.txt", "xxx")).Throws(); + + // Verify + filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); + filesystemHandlerMock.VerifyNoOtherCalls(); + + server.Stop(); + } + + [Fact] + public void IWireMockAdminApi_GetFileAsync_NotFound() + { + // Arrange + var filesystemHandlerMock = new Mock(MockBehavior.Strict); + filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(false); + filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny())).Returns(Encoding.ASCII.GetBytes("Here's a string.")); + + var server = WireMockServer.Start(new WireMockServerSettings + { + UseSSL = false, + StartAdminInterface = true, + FileSystemHandler = filesystemHandlerMock.Object + }); + + var api = RestClient.For(server.Urls[0]); + + // Act and Assert + Check.ThatAsyncCode(() => api.GetFileAsync("filename.txt")).Throws(); + + // Verify + filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); + filesystemHandlerMock.VerifyNoOtherCalls(); + + server.Stop(); + } + + [Fact] + public async Task IWireMockAdminApi_GetFileAsync_Found() + { + // Arrange + string data = "Here's a string."; + var filesystemHandlerMock = new Mock(MockBehavior.Strict); + filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(true); + filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny())).Returns(Encoding.ASCII.GetBytes(data)); + + var server = WireMockServer.Start(new WireMockServerSettings + { + UseSSL = false, + StartAdminInterface = true, + FileSystemHandler = filesystemHandlerMock.Object + }); + + var api = RestClient.For(server.Urls[0]); + + // Act + string file = await api.GetFileAsync("filename.txt"); + + // Assert + Check.That(file).Equals(data); + + // Verify + filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); + filesystemHandlerMock.Verify(fs => fs.ReadFile(It.Is(p => p == "filename.txt")), Times.Once); + filesystemHandlerMock.VerifyNoOtherCalls(); + + server.Stop(); + } + + [Fact] + public async Task IWireMockAdminApi_DeleteFileAsync_Ok() + { + // Arrange + var filesystemHandlerMock = new Mock(MockBehavior.Strict); + filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(true); + filesystemHandlerMock.Setup(fs => fs.DeleteFile(It.IsAny())); + + var server = WireMockServer.Start(new WireMockServerSettings + { + UseSSL = false, + StartAdminInterface = true, + FileSystemHandler = filesystemHandlerMock.Object + }); + + var api = RestClient.For(server.Urls[0]); + + // Act + await api.DeleteFileAsync("filename.txt"); + + // Verify + filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); + filesystemHandlerMock.Verify(fs => fs.DeleteFile(It.Is(p => p == "filename.txt")), Times.Once); + filesystemHandlerMock.VerifyNoOtherCalls(); + + server.Stop(); + } + + [Fact] + public void IWireMockAdminApi_DeleteFileAsync_NotFound() + { + // Arrange + var filesystemHandlerMock = new Mock(MockBehavior.Strict); + filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(false); + filesystemHandlerMock.Setup(fs => fs.DeleteFile(It.IsAny())); + + var server = WireMockServer.Start(new WireMockServerSettings + { + UseSSL = false, + StartAdminInterface = true, + FileSystemHandler = filesystemHandlerMock.Object + }); + + var api = RestClient.For(server.Urls[0]); + + // Act and Assert + Check.ThatAsyncCode(() => api.DeleteFileAsync("filename.txt")).Throws(); + + // Verify + filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); + filesystemHandlerMock.VerifyNoOtherCalls(); + + server.Stop(); + } + + [Fact] + public void IWireMockAdminApi_FileExistsAsync_NotFound() + { + // Arrange + var filesystemHandlerMock = new Mock(MockBehavior.Strict); + filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(false); + + var server = WireMockServer.Start(new WireMockServerSettings + { + UseSSL = false, + StartAdminInterface = true, + FileSystemHandler = filesystemHandlerMock.Object + }); + + var api = RestClient.For(server.Urls[0]); + + // Act and Assert + Check.ThatAsyncCode(() => api.FileExistsAsync("filename.txt")).Throws(); + + // Verify + filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is(p => p == "filename.txt")), Times.Once); + filesystemHandlerMock.VerifyNoOtherCalls(); + + server.Stop(); + } + } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/FluentMockServerTests.Admin.cs b/test/WireMock.Net.Tests/WireMockServer.Admin.cs similarity index 83% rename from test/WireMock.Net.Tests/FluentMockServerTests.Admin.cs rename to test/WireMock.Net.Tests/WireMockServer.Admin.cs index 038f1d6cd..a745399ec 100644 --- a/test/WireMock.Net.Tests/FluentMockServerTests.Admin.cs +++ b/test/WireMock.Net.Tests/WireMockServer.Admin.cs @@ -1,11 +1,11 @@ -using Moq; -using Newtonsoft.Json; -using NFluent; -using System; +using System; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; +using Moq; +using Newtonsoft.Json; +using NFluent; using WireMock.Handlers; using WireMock.Logging; using WireMock.RequestBuilders; @@ -16,7 +16,7 @@ namespace WireMock.Net.Tests { - public class FluentMockServerAdminTests + public class WireMockServerAdminTests { // For for AppVeyor + OpenCover private string GetCurrentFolder() @@ -29,9 +29,9 @@ private string GetCurrentFolder() } [Fact] - public void FluentMockServer_Admin_StartStop() + public void WireMockServer_Admin_StartStop() { - var server1 = FluentMockServer.Start("http://localhost:19091"); + var server1 = WireMockServer.Start("http://localhost:19091"); Check.That(server1.Urls[0]).Equals("http://localhost:19091"); @@ -39,9 +39,9 @@ public void FluentMockServer_Admin_StartStop() } [Fact] - public void FluentMockServer_Admin_ResetMappings() + public void WireMockServer_Admin_ResetMappings() { - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings"); server.ReadStaticMappings(folder); @@ -58,7 +58,7 @@ public void FluentMockServer_Admin_ResetMappings() } [Fact] - public void FluentMockServer_Admin_SaveStaticMappings() + public void WireMockServer_Admin_SaveStaticMappings() { // Assign string guid = "791a3f31-6946-aaaa-8e6f-0237c7441111"; @@ -67,7 +67,7 @@ public void FluentMockServer_Admin_SaveStaticMappings() staticMappingHandlerMock.Setup(m => m.FolderExists(It.IsAny())).Returns(true); staticMappingHandlerMock.Setup(m => m.WriteMappingFile(It.IsAny(), It.IsAny())); - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { FileSystemHandler = staticMappingHandlerMock.Object }); @@ -87,12 +87,12 @@ public void FluentMockServer_Admin_SaveStaticMappings() } [Fact] - public void FluentMockServer_Admin_ReadStaticMapping_WithNonGuidFilename() + public void WireMockServer_Admin_ReadStaticMapping_WithNonGuidFilename() { var guid = Guid.Parse("04ee4872-9efd-4770-90d3-88d445265d0d"); string title = "documentdb_root_title"; - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); string path = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "documentdb_root.json"); server.ReadStaticMappingAndAddOrUpdate(path); @@ -107,11 +107,11 @@ public void FluentMockServer_Admin_ReadStaticMapping_WithNonGuidFilename() } [Fact] - public void FluentMockServer_Admin_ReadStaticMapping_WithGuidFilename() + public void WireMockServer_Admin_ReadStaticMapping_WithGuidFilename() { string guid = "00000002-ee28-4f29-ae63-1ac9b0802d86"; - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); string path = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json"); server.ReadStaticMappingAndAddOrUpdate(path); @@ -125,9 +125,9 @@ public void FluentMockServer_Admin_ReadStaticMapping_WithGuidFilename() } [Fact] - public void FluentMockServer_Admin_ReadStaticMapping_WithArray() + public void WireMockServer_Admin_ReadStaticMapping_WithArray() { - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); string path = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "array.json"); server.ReadStaticMappingAndAddOrUpdate(path); @@ -137,7 +137,7 @@ public void FluentMockServer_Admin_ReadStaticMapping_WithArray() } [Fact] - public void FluentMockServer_Admin_ReadStaticMapping_WithResponseBodyFromFile() + public void WireMockServer_Admin_ReadStaticMapping_WithResponseBodyFromFile() { string guid = "00000002-ee28-4f29-ae63-1ac9b0802d87"; @@ -152,7 +152,7 @@ public void FluentMockServer_Admin_ReadStaticMapping_WithResponseBodyFromFile() string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented); File.WriteAllText(path, output); - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server.ReadStaticMappingAndAddOrUpdate(path); var mappings = server.Mappings.ToArray(); @@ -165,7 +165,7 @@ public void FluentMockServer_Admin_ReadStaticMapping_WithResponseBodyFromFile() } [Fact] - public void FluentMockServer_Admin_ReadStaticMappings_FolderExistsIsTrue() + public void WireMockServer_Admin_ReadStaticMappings_FolderExistsIsTrue() { // Assign var staticMappingHandlerMock = new Mock(); @@ -173,7 +173,7 @@ public void FluentMockServer_Admin_ReadStaticMappings_FolderExistsIsTrue() staticMappingHandlerMock.Setup(m => m.FolderExists(It.IsAny())).Returns(true); staticMappingHandlerMock.Setup(m => m.EnumerateFiles(It.IsAny(), It.IsAny())).Returns(new string[0]); - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { FileSystemHandler = staticMappingHandlerMock.Object }); @@ -188,14 +188,14 @@ public void FluentMockServer_Admin_ReadStaticMappings_FolderExistsIsTrue() } [Fact] - public void FluentMockServer_Admin_ReadStaticMappingAndAddOrUpdate() + public void WireMockServer_Admin_ReadStaticMappingAndAddOrUpdate() { // Assign string mapping = "{\"Request\": {\"Path\": {\"Matchers\": [{\"Name\": \"WildcardMatcher\",\"Pattern\": \"/static/mapping\"}]},\"Methods\": [\"get\"]},\"Response\": {\"BodyAsJson\": { \"body\": \"static mapping\" }}}"; var staticMappingHandlerMock = new Mock(); staticMappingHandlerMock.Setup(m => m.ReadMappingFile(It.IsAny())).Returns(mapping); - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { FileSystemHandler = staticMappingHandlerMock.Object }); @@ -208,9 +208,9 @@ public void FluentMockServer_Admin_ReadStaticMappingAndAddOrUpdate() } [Fact] - public void FluentMockServer_Admin_ReadStaticMappings() + public void WireMockServer_Admin_ReadStaticMappings() { - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings"); server.ReadStaticMappings(folder); @@ -220,16 +220,16 @@ public void FluentMockServer_Admin_ReadStaticMappings() } [Fact] - public void FluentMockServer_Admin_ReadStaticMappings_FolderDoesNotExist() + public void WireMockServer_Admin_ReadStaticMappings_FolderDoesNotExist() { // Assign var loggerMock = new Mock(); loggerMock.Setup(l => l.Info(It.IsAny(), It.IsAny())); - var settings = new FluentMockServerSettings + var settings = new WireMockServerSettings { Logger = loggerMock.Object }; - var server = FluentMockServer.Start(settings); + var server = WireMockServer.Start(settings); // Act server.ReadStaticMappings(Guid.NewGuid().ToString()); @@ -242,10 +242,10 @@ public void FluentMockServer_Admin_ReadStaticMappings_FolderDoesNotExist() } [Fact] - public void FluentMockServer_Admin_Mappings_WithGuid_Get() + public void WireMockServer_Admin_Mappings_WithGuid_Get() { Guid guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05"); - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server.Given(Request.Create().WithPath("/foo1").UsingGet()).WithGuid(guid) .RespondWith(Response.Create().WithStatusCode(201).WithBody("1")); @@ -258,10 +258,10 @@ public void FluentMockServer_Admin_Mappings_WithGuid_Get() } [Fact] - public void FluentMockServer_Admin_Mappings_WithGuidAsString_Get() + public void WireMockServer_Admin_Mappings_WithGuidAsString_Get() { string guid = "90356dba-b36c-469a-a17e-669cd84f1f05"; - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server.Given(Request.Create().WithPath("/foo100").UsingGet()).WithGuid(guid) .RespondWith(Response.Create().WithStatusCode(201).WithBody("1")); @@ -271,10 +271,10 @@ public void FluentMockServer_Admin_Mappings_WithGuidAsString_Get() } [Fact] - public void FluentMockServer_Admin_Mappings_Add_SameGuid() + public void WireMockServer_Admin_Mappings_Add_SameGuid() { var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05"); - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); var response1 = Response.Create().WithStatusCode(500); server.Given(Request.Create().UsingGet()) @@ -297,9 +297,9 @@ public void FluentMockServer_Admin_Mappings_Add_SameGuid() } [Fact] - public async Task FluentMockServer_Admin_Mappings_AtPriority() + public async Task WireMockServer_Admin_Mappings_AtPriority() { - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); // given server.Given(Request.Create().WithPath("/1").UsingGet()) @@ -321,10 +321,10 @@ public async Task FluentMockServer_Admin_Mappings_AtPriority() } [Fact] - public async Task FluentMockServer_Admin_Requests_Get() + public async Task WireMockServer_Admin_Requests_Get() { // given - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); // when await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + "/foo"); @@ -337,12 +337,12 @@ public async Task FluentMockServer_Admin_Requests_Get() } [Fact] - public async Task FluentMockServer_Admin_Logging_SetMaxRequestLogCount() + public async Task WireMockServer_Admin_Logging_SetMaxRequestLogCount() { // Assign var client = new HttpClient(); // Act - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server.SetMaxRequestLogCount(2); await client.GetAsync("http://localhost:" + server.Ports[0] + "/foo1"); @@ -360,15 +360,15 @@ public async Task FluentMockServer_Admin_Logging_SetMaxRequestLogCount() } [Fact] - public void FluentMockServer_Admin_WatchStaticMappings() + public void WireMockServer_Admin_WatchStaticMappings() { // Assign var fileMock = new Mock(); - var settings = new FluentMockServerSettings + var settings = new WireMockServerSettings { FileSystemHandler = fileMock.Object }; - var server = FluentMockServer.Start(settings); + var server = WireMockServer.Start(settings); // Act server.WatchStaticMappings(); @@ -379,7 +379,7 @@ public void FluentMockServer_Admin_WatchStaticMappings() } [Fact] - public void FluentMockServer_Admin_AddMappingsAndSaveToFile() + public void WireMockServer_Admin_AddMappingsAndSaveToFile() { // Assign string guid = "791a3f31-6946-aaaa-8e6f-0237c7442222"; @@ -388,7 +388,7 @@ public void FluentMockServer_Admin_AddMappingsAndSaveToFile() staticMappingHandlerMock.Setup(m => m.FolderExists(It.IsAny())).Returns(true); staticMappingHandlerMock.Setup(m => m.WriteMappingFile(It.IsAny(), It.IsAny())); - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { FileSystemHandler = staticMappingHandlerMock.Object }); diff --git a/test/WireMock.Net.Tests/FLuentMockServerTests.AdminFiles.cs b/test/WireMock.Net.Tests/WireMockServer.AdminFiles.cs similarity index 90% rename from test/WireMock.Net.Tests/FLuentMockServerTests.AdminFiles.cs rename to test/WireMock.Net.Tests/WireMockServer.AdminFiles.cs index 4d362d4ae..2b3eaffff 100644 --- a/test/WireMock.Net.Tests/FLuentMockServerTests.AdminFiles.cs +++ b/test/WireMock.Net.Tests/WireMockServer.AdminFiles.cs @@ -14,12 +14,12 @@ namespace WireMock.Net.Tests { - public class FluentMockServerAdminFilesTests + public class WireMockServerAdminFilesTests { private readonly HttpClient _client = new HttpClient(); [Fact] - public async Task FluentMockServer_Admin_Files_Post_Ascii() + public async Task WireMockServer_Admin_Files_Post_Ascii() { // Arrange var filesystemHandlerMock = new Mock(MockBehavior.Strict); @@ -27,7 +27,7 @@ public async Task FluentMockServer_Admin_Files_Post_Ascii() filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny())).Returns(true); filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny(), It.IsAny())); - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, @@ -53,7 +53,7 @@ public async Task FluentMockServer_Admin_Files_Post_Ascii() } [Fact] - public async Task FluentMockServer_Admin_Files_Post_MappingFolderDoesNotExistsButWillBeCreated() + public async Task WireMockServer_Admin_Files_Post_MappingFolderDoesNotExistsButWillBeCreated() { // Arrange var filesystemHandlerMock = new Mock(MockBehavior.Strict); @@ -62,7 +62,7 @@ public async Task FluentMockServer_Admin_Files_Post_MappingFolderDoesNotExistsBu filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny())).Returns(false); filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny(), It.IsAny())); - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, @@ -88,14 +88,14 @@ public async Task FluentMockServer_Admin_Files_Post_MappingFolderDoesNotExistsBu } [Fact] - public async Task FluentMockServer_Admin_Files_GetAscii() + public async Task WireMockServer_Admin_Files_GetAscii() { // Arrange var filesystemHandlerMock = new Mock(MockBehavior.Strict); filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(true); filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny())).Returns(Encoding.ASCII.GetBytes("Here's a string.")); - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, @@ -123,7 +123,7 @@ public async Task FluentMockServer_Admin_Files_GetAscii() } [Fact] - public async Task FluentMockServer_Admin_Files_GetUTF16() + public async Task WireMockServer_Admin_Files_GetUTF16() { // Arrange byte[] symbol = Encoding.UTF32.GetBytes(char.ConvertFromUtf32(0x1D161)); @@ -131,7 +131,7 @@ public async Task FluentMockServer_Admin_Files_GetUTF16() filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(true); filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny())).Returns(symbol); - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, @@ -157,13 +157,13 @@ public async Task FluentMockServer_Admin_Files_GetUTF16() } [Fact] - public async Task FluentMockServer_Admin_Files_Head() + public async Task WireMockServer_Admin_Files_Head() { // Arrange var filesystemHandlerMock = new Mock(MockBehavior.Strict); filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(true); - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, @@ -185,13 +185,13 @@ public async Task FluentMockServer_Admin_Files_Head() } [Fact] - public async Task FluentMockServer_Admin_Files_Head_FileDoesNotExistsReturns404() + public async Task WireMockServer_Admin_Files_Head_FileDoesNotExistsReturns404() { // Arrange var filesystemHandlerMock = new Mock(MockBehavior.Strict); filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny())).Returns(false); - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, diff --git a/test/WireMock.Net.Tests/FluentMockServerTests.Authentication.cs b/test/WireMock.Net.Tests/WireMockServer.Authentication.cs similarity index 77% rename from test/WireMock.Net.Tests/FluentMockServerTests.Authentication.cs rename to test/WireMock.Net.Tests/WireMockServer.Authentication.cs index 99838058d..7990cda55 100644 --- a/test/WireMock.Net.Tests/FluentMockServerTests.Authentication.cs +++ b/test/WireMock.Net.Tests/WireMockServer.Authentication.cs @@ -6,13 +6,13 @@ namespace WireMock.Net.Tests { - public class FluentMockServerAuthenticationTests + public class WireMockServerAuthenticationTests { [Fact] - public void FluentMockServer_Authentication_SetBasicAuthentication() + public void WireMockServer_Authentication_SetBasicAuthentication() { // Assign - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); // Act server.SetBasicAuthentication("x", "y"); @@ -25,10 +25,10 @@ public void FluentMockServer_Authentication_SetBasicAuthentication() } [Fact] - public void FluentMockServer_Authentication_RemoveBasicAuthentication() + public void WireMockServer_Authentication_RemoveBasicAuthentication() { // Assign - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server.SetBasicAuthentication("x", "y"); // Act diff --git a/test/WireMock.Net.Tests/FluentMockServerTests.Proxy.cs b/test/WireMock.Net.Tests/WireMockServer.Proxy.cs similarity index 83% rename from test/WireMock.Net.Tests/FluentMockServerTests.Proxy.cs rename to test/WireMock.Net.Tests/WireMockServer.Proxy.cs index 123f05a8a..9ee8a68b6 100644 --- a/test/WireMock.Net.Tests/FluentMockServerTests.Proxy.cs +++ b/test/WireMock.Net.Tests/WireMockServer.Proxy.cs @@ -1,12 +1,11 @@ -using NFluent; -using System; +using System; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; -using FluentAssertions; +using NFluent; using WireMock.Matchers.Request; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; @@ -16,13 +15,13 @@ namespace WireMock.Net.Tests { - public class FluentMockServerProxyTests + public class WireMockServerProxyTests { [Fact] - public async Task FluentMockServer_Proxy_Should_log_proxied_requests() + public async Task WireMockServer_Proxy_Should_log_proxied_requests() { // Assign - var settings = new FluentMockServerSettings + var settings = new WireMockServerSettings { ProxyAndRecordSettings = new ProxyAndRecordSettings { @@ -31,7 +30,7 @@ public async Task FluentMockServer_Proxy_Should_log_proxied_requests() SaveMappingToFile = false } }; - var server = FluentMockServer.Start(settings); + var server = WireMockServer.Start(settings); // Act var requestMessage = new HttpRequestMessage @@ -48,11 +47,11 @@ public async Task FluentMockServer_Proxy_Should_log_proxied_requests() } [Fact] - public async Task FluentMockServer_Proxy_Should_proxy_responses() + public async Task WireMockServer_Proxy_Should_proxy_responses() { // Assign string path = $"/prx_{Guid.NewGuid().ToString()}"; - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create().WithProxy("http://www.google.com")); @@ -74,16 +73,16 @@ public async Task FluentMockServer_Proxy_Should_proxy_responses() } [Fact] - public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxied_request() + public async Task WireMockServer_Proxy_Should_preserve_content_header_in_proxied_request() { // Assign string path = $"/prx_{Guid.NewGuid().ToString()}"; - var serverForProxyForwarding = FluentMockServer.Start(); + var serverForProxyForwarding = WireMockServer.Start(); serverForProxyForwarding .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create()); - var settings = new FluentMockServerSettings + var settings = new WireMockServerSettings { ProxyAndRecordSettings = new ProxyAndRecordSettings { @@ -92,7 +91,7 @@ public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxi SaveMappingToFile = false } }; - var server = FluentMockServer.Start(settings); + var server = WireMockServer.Start(settings); // Act var requestMessage = new HttpRequestMessage @@ -121,16 +120,16 @@ public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxi } [Fact] - public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_content_header_in_mapping() + public async Task WireMockServer_Proxy_Should_exclude_blacklisted_content_header_in_mapping() { // Assign string path = $"/prx_{Guid.NewGuid().ToString()}"; - var serverForProxyForwarding = FluentMockServer.Start(); + var serverForProxyForwarding = WireMockServer.Start(); serverForProxyForwarding .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create()); - var settings = new FluentMockServerSettings + var settings = new WireMockServerSettings { ProxyAndRecordSettings = new ProxyAndRecordSettings { @@ -140,7 +139,7 @@ public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_content_head BlackListedHeaders = new[] { "blacklisted" } } }; - var server = FluentMockServer.Start(settings); + var server = WireMockServer.Start(settings); var defaultMapping = server.Mappings.First(); // Act @@ -160,19 +159,19 @@ public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_content_head var matchers = ((Request)mapping.RequestMatcher).GetRequestMessageMatchers().Select(m => m.Name).ToList(); Check.That(matchers).Not.Contains("blacklisted"); Check.That(matchers).Contains("ok"); - } - + } + [Fact] - public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_cookies_in_mapping() + public async Task WireMockServer_Proxy_Should_exclude_blacklisted_cookies_in_mapping() { // Assign string path = $"/prx_{Guid.NewGuid().ToString()}"; - var serverForProxyForwarding = FluentMockServer.Start(); + var serverForProxyForwarding = WireMockServer.Start(); serverForProxyForwarding .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create()); - var settings = new FluentMockServerSettings + var settings = new WireMockServerSettings { ProxyAndRecordSettings = new ProxyAndRecordSettings { @@ -182,7 +181,7 @@ public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_cookies_in_m BlackListedCookies = new[] { "ASP.NET_SessionId" } } }; - var server = FluentMockServer.Start(settings); + var server = WireMockServer.Start(settings); var defaultMapping = server.Mappings.First(); // Act @@ -197,7 +196,7 @@ public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_cookies_in_m cookieContainer.Add(new Uri("http://localhost"), new Cookie("ASP.NET_SessionId", "exact_match")); cookieContainer.Add(new Uri("http://localhost"), new Cookie("AsP.NeT_SessIonID", "case_mismatch")); cookieContainer.Add(new Uri("http://localhost"), new Cookie("GoodCookie", "I_should_pass")); - + var handler = new HttpClientHandler { CookieContainer = cookieContainer }; await new HttpClient(handler).SendAsync(requestMessage); @@ -212,16 +211,16 @@ public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_cookies_in_m } [Fact] - public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxied_request_with_empty_content() + public async Task WireMockServer_Proxy_Should_preserve_content_header_in_proxied_request_with_empty_content() { // Assign string path = $"/prx_{Guid.NewGuid().ToString()}"; - var serverForProxyForwarding = FluentMockServer.Start(); + var serverForProxyForwarding = WireMockServer.Start(); serverForProxyForwarding .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create()); - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath("/*")) .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0])); @@ -244,18 +243,18 @@ public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxi } [Fact] - public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxied_response() + public async Task WireMockServer_Proxy_Should_preserve_content_header_in_proxied_response() { // Assign string path = $"/prx_{Guid.NewGuid().ToString()}"; - var serverForProxyForwarding = FluentMockServer.Start(); + var serverForProxyForwarding = WireMockServer.Start(); serverForProxyForwarding .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create() .WithBody("body") .WithHeader("Content-Type", "text/plain")); - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0])); @@ -275,20 +274,20 @@ public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxi } [Fact] - public async Task FluentMockServer_Proxy_Should_change_absolute_location_header_in_proxied_response() + public async Task WireMockServer_Proxy_Should_change_absolute_location_header_in_proxied_response() { // Assign string path = $"/prx_{Guid.NewGuid().ToString()}"; - var settings = new FluentMockServerSettings { AllowPartialMapping = false }; + var settings = new WireMockServerSettings { AllowPartialMapping = false }; - var serverForProxyForwarding = FluentMockServer.Start(settings); + var serverForProxyForwarding = WireMockServer.Start(settings); serverForProxyForwarding .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create() .WithStatusCode(HttpStatusCode.Redirect) .WithHeader("Location", "/testpath")); - var server = FluentMockServer.Start(settings); + var server = WireMockServer.Start(settings); server .Given(Request.Create().WithPath(path).UsingAnyMethod()) .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0])); @@ -308,16 +307,16 @@ public async Task FluentMockServer_Proxy_Should_change_absolute_location_header_ } [Fact] - public async Task FluentMockServer_Proxy_Should_preserve_cookie_header_in_proxied_request() + public async Task WireMockServer_Proxy_Should_preserve_cookie_header_in_proxied_request() { // Assign string path = $"/prx_{Guid.NewGuid().ToString()}"; - var serverForProxyForwarding = FluentMockServer.Start(); + var serverForProxyForwarding = WireMockServer.Start(); serverForProxyForwarding .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create()); - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0])); @@ -345,17 +344,17 @@ public async Task FluentMockServer_Proxy_Should_preserve_cookie_header_in_proxie /// in UTF8 and breaks if it is not treated as binary content. /// [Fact] - public async Task FluentMockServer_Proxy_Should_preserve_binary_request_content() + public async Task WireMockServer_Proxy_Should_preserve_binary_request_content() { // arrange - var jpegHeader = new byte[] {0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00}; + var jpegHeader = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00 }; var brokenJpegHeader = new byte[] {0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0xEF, 0xBF, 0xBD, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00}; bool HasCorrectHeader(byte[] bytes) => bytes.SequenceEqual(jpegHeader); bool HasBrokenHeader(byte[] bytes) => bytes.SequenceEqual(brokenJpegHeader); - - var serverForProxyForwarding = FluentMockServer.Start(); + + var serverForProxyForwarding = WireMockServer.Start(); serverForProxyForwarding .Given(Request.Create().WithBody(HasCorrectHeader)) .RespondWith(Response.Create().WithSuccess()); @@ -363,32 +362,32 @@ public async Task FluentMockServer_Proxy_Should_preserve_binary_request_content( serverForProxyForwarding .Given(Request.Create().WithBody(HasBrokenHeader)) .RespondWith(Response.Create().WithStatusCode(HttpStatusCode.InternalServerError)); - - var server = FluentMockServer.Start(); + + var server = WireMockServer.Start(); server .Given(Request.Create()) .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0])); // act var response = await new HttpClient().PostAsync(server.Urls[0], new ByteArrayContent(jpegHeader)); - + // assert Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); } [Fact] - public async Task FluentMockServer_Proxy_Should_set_BodyAsJson_in_proxied_response() + public async Task WireMockServer_Proxy_Should_set_BodyAsJson_in_proxied_response() { // Assign string path = $"/prx_{Guid.NewGuid().ToString()}"; - var serverForProxyForwarding = FluentMockServer.Start(); + var serverForProxyForwarding = WireMockServer.Start(); serverForProxyForwarding .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create() .WithBodyAsJson(new { i = 42 }) .WithHeader("Content-Type", "application/json; charset=utf-8")); - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0])); @@ -408,18 +407,18 @@ public async Task FluentMockServer_Proxy_Should_set_BodyAsJson_in_proxied_respon } [Fact] - public async Task FluentMockServer_Proxy_Should_set_Body_in_multipart_proxied_response() + public async Task WireMockServer_Proxy_Should_set_Body_in_multipart_proxied_response() { // Assign string path = $"/prx_{Guid.NewGuid().ToString()}"; - var serverForProxyForwarding = FluentMockServer.Start(); + var serverForProxyForwarding = WireMockServer.Start(); serverForProxyForwarding .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create() .WithBodyAsJson(new { i = 42 }) ); - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0])); @@ -438,16 +437,16 @@ public async Task FluentMockServer_Proxy_Should_set_Body_in_multipart_proxied_re } [Fact] - public async Task FluentMockServer_Proxy_Should_Not_overrule_AdminMappings() + public async Task WireMockServer_Proxy_Should_Not_overrule_AdminMappings() { // Assign string path = $"/prx_{Guid.NewGuid().ToString()}"; - var serverForProxyForwarding = FluentMockServer.Start(); + var serverForProxyForwarding = WireMockServer.Start(); serverForProxyForwarding .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create().WithBody("ok")); - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { StartAdminInterface = true, ReadStaticMappings = false, diff --git a/test/WireMock.Net.Tests/FluentMockServerTests.Proxy2.cs b/test/WireMock.Net.Tests/WireMockServer.Proxy2.cs similarity index 86% rename from test/WireMock.Net.Tests/FluentMockServerTests.Proxy2.cs rename to test/WireMock.Net.Tests/WireMockServer.Proxy2.cs index afae3fa30..53412b6c6 100644 --- a/test/WireMock.Net.Tests/FluentMockServerTests.Proxy2.cs +++ b/test/WireMock.Net.Tests/WireMockServer.Proxy2.cs @@ -11,18 +11,18 @@ namespace WireMock.Net.Tests { - public class FluentMockServerProxy2Tests + public class WireMockServerProxy2Tests { [Fact] - public async Task FluentMockServer_ProxyAndRecordSettings_ShouldProxy() + public async Task WireMockServer_ProxyAndRecordSettings_ShouldProxy() { // Assign - var serverAsProxy = FluentMockServer.Start(); + var serverAsProxy = WireMockServer.Start(); serverAsProxy.Given(Request.Create().UsingPost()) .RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 42 }).WithHeader("Content-Type", "application/json")); // Act - var server = FluentMockServer.Start(); + var server = WireMockServer.Start(); server.Given(Request.Create().UsingPost().WithHeader("prx", "1")) .RespondWith(Response.Create().WithProxy(serverAsProxy.Urls[0])); diff --git a/test/WireMock.Net.Tests/FluentMockServerTests.Settings.cs b/test/WireMock.Net.Tests/WireMockServer.Settings.cs similarity index 70% rename from test/WireMock.Net.Tests/FluentMockServerTests.Settings.cs rename to test/WireMock.Net.Tests/WireMockServer.Settings.cs index d04b98da2..45d57cf98 100644 --- a/test/WireMock.Net.Tests/FluentMockServerTests.Settings.cs +++ b/test/WireMock.Net.Tests/WireMockServer.Settings.cs @@ -1,6 +1,6 @@ -using System.Linq; using Moq; using NFluent; +using System.Linq; using WireMock.Logging; using WireMock.Owin; using WireMock.Server; @@ -9,21 +9,21 @@ namespace WireMock.Net.Tests { - public class FluentMockServerSettingsTests + public class WireMockServerSettingsTests { private readonly Mock _loggerMock; - public FluentMockServerSettingsTests() + public WireMockServerSettingsTests() { _loggerMock = new Mock(); _loggerMock.Setup(l => l.Info(It.IsAny(), It.IsAny())); } [Fact] - public void FluentMockServer_FluentMockServerSettings_StartAdminInterfaceTrue_BasicAuthenticationIsSet() + public void WireMockServer_WireMockServerSettings_StartAdminInterfaceTrue_BasicAuthenticationIsSet() { // Assign and Act - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { StartAdminInterface = true, AdminUsername = "u", @@ -36,10 +36,10 @@ public void FluentMockServer_FluentMockServerSettings_StartAdminInterfaceTrue_Ba } [Fact] - public void FluentMockServer_FluentMockServerSettings_StartAdminInterfaceFalse_BasicAuthenticationIsNotSet() + public void WireMockServer_WireMockServerSettings_StartAdminInterfaceFalse_BasicAuthenticationIsNotSet() { // Assign and Act - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { StartAdminInterface = false, AdminUsername = "u", @@ -52,10 +52,10 @@ public void FluentMockServer_FluentMockServerSettings_StartAdminInterfaceFalse_B } [Fact] - public void FluentMockServer_FluentMockServerSettings_PriorityFromAllAdminMappingsIsLow_When_StartAdminInterface_IsTrue() + public void WireMockServer_WireMockServerSettings_PriorityFromAllAdminMappingsIsLow_When_StartAdminInterface_IsTrue() { // Assign and Act - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { StartAdminInterface = true }); @@ -67,10 +67,10 @@ public void FluentMockServer_FluentMockServerSettings_PriorityFromAllAdminMappin } [Fact] - public void FluentMockServer_FluentMockServerSettings_ProxyAndRecordSettings_ProxyPriority_Is1000_When_StartAdminInterface_IsTrue() + public void WireMockServer_WireMockServerSettings_ProxyAndRecordSettings_ProxyPriority_Is1000_When_StartAdminInterface_IsTrue() { // Assign and Act - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { StartAdminInterface = true, ProxyAndRecordSettings = new ProxyAndRecordSettings @@ -87,10 +87,10 @@ public void FluentMockServer_FluentMockServerSettings_ProxyAndRecordSettings_Pro } [Fact] - public void FluentMockServer_FluentMockServerSettings_ProxyAndRecordSettings_ProxyPriority_Is0_When_StartAdminInterface_IsFalse() + public void WireMockServer_WireMockServerSettings_ProxyAndRecordSettings_ProxyPriority_Is0_When_StartAdminInterface_IsFalse() { // Assign and Act - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { ProxyAndRecordSettings = new ProxyAndRecordSettings { @@ -105,10 +105,10 @@ public void FluentMockServer_FluentMockServerSettings_ProxyAndRecordSettings_Pro } [Fact] - public void FluentMockServer_FluentMockServerSettings_AllowPartialMapping() + public void WireMockServer_WireMockServerSettings_AllowPartialMapping() { // Assign and Act - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { Logger = _loggerMock.Object, AllowPartialMapping = true @@ -123,10 +123,10 @@ public void FluentMockServer_FluentMockServerSettings_AllowPartialMapping() } [Fact] - public void FluentMockServer_FluentMockServerSettings_AllowBodyForAllHttpMethods() + public void WireMockServer_WireMockServerSettings_AllowBodyForAllHttpMethods() { // Assign and Act - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { Logger = _loggerMock.Object, AllowBodyForAllHttpMethods = true @@ -141,10 +141,10 @@ public void FluentMockServer_FluentMockServerSettings_AllowBodyForAllHttpMethods } [Fact] - public void FluentMockServer_FluentMockServerSettings_RequestLogExpirationDuration() + public void WireMockServer_WireMockServerSettings_RequestLogExpirationDuration() { // Assign and Act - var server = FluentMockServer.Start(new FluentMockServerSettings + var server = WireMockServer.Start(new WireMockServerSettings { Logger = _loggerMock.Object, RequestLogExpirationDuration = 1 diff --git a/test/WireMock.Net.Tests/FluentMockServerTests.cs b/test/WireMock.Net.Tests/WireMockServerTests.cs similarity index 79% rename from test/WireMock.Net.Tests/FluentMockServerTests.cs rename to test/WireMock.Net.Tests/WireMockServerTests.cs index 8d7ecf2e4..b236f71a8 100644 --- a/test/WireMock.Net.Tests/FluentMockServerTests.cs +++ b/test/WireMock.Net.Tests/WireMockServerTests.cs @@ -1,271 +1,256 @@ -using System; -using System.Diagnostics; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Threading.Tasks; -using NFluent; -using WireMock.RequestBuilders; -using WireMock.ResponseBuilders; -using WireMock.Server; -using Xunit; - -namespace WireMock.Net.Tests -{ - public class FluentMockServerTests - { - [Fact] - public async Task FluentMockServer_Should_respond_to_request_bodyAsBase64() - { - // given - var server = FluentMockServer.Start(); - - server.Given(Request.Create().WithPath("/foo").UsingGet()).RespondWith(Response.Create().WithBodyFromBase64("SGVsbG8gV29ybGQ/")); - - // when - var response = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo"); - - // then - Check.That(response).IsEqualTo("Hello World?"); - } - - [Fact] - public async Task FluentMockServer_Should_reset_requestlogs() - { - // given - var server = FluentMockServer.Start(); - - // when - await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + "/foo"); - server.ResetLogEntries(); - - // then - Check.That(server.LogEntries).IsEmpty(); - } - - [Fact] - public void FluentMockServer_Should_reset_mappings() - { - // given - string path = $"/foo_{Guid.NewGuid()}"; - var server = FluentMockServer.Start(); - - server - .Given(Request.Create() - .WithPath(path) - .UsingGet()) - .RespondWith(Response.Create() - .WithBody(@"{ msg: ""Hello world!""}")); - - // when - server.ResetMappings(); - - // then - Check.That(server.Mappings).IsEmpty(); - Check.ThatAsyncCode(() => new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path)).ThrowsAny(); - } - - [Fact] - public async Task FluentMockServer_Should_respond_a_redirect_without_body() - { - // Assign - string path = $"/foo_{Guid.NewGuid()}"; - string pathToRedirect = $"/bar_{Guid.NewGuid()}"; - - var server = FluentMockServer.Start(); - - server - .Given(Request.Create() - .WithPath(path) - .UsingGet()) - .RespondWith(Response.Create() - .WithStatusCode(307) - .WithHeader("Location", pathToRedirect)); - server - .Given(Request.Create() - .WithPath(pathToRedirect) - .UsingGet()) - .RespondWith(Response.Create() - .WithStatusCode(200) - .WithBody("REDIRECT SUCCESSFUL")); - - // Act - var response = await new HttpClient().GetStringAsync($"http://localhost:{server.Ports[0]}{path}"); - - // Assert - Check.That(response).IsEqualTo("REDIRECT SUCCESSFUL"); - } - - [Fact] - public async Task FluentMockServer_Should_delay_responses_for_a_given_route() - { - // given - var server = FluentMockServer.Start(); - - server - .Given(Request.Create() - .WithPath("/*")) - .RespondWith(Response.Create() - .WithBody(@"{ msg: ""Hello world!""}") - .WithDelay(TimeSpan.FromMilliseconds(200))); - - // when - var watch = new Stopwatch(); - watch.Start(); - await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo"); - watch.Stop(); - - // then - Check.That(watch.ElapsedMilliseconds).IsStrictlyGreaterThan(200); - } - - [Fact] - public async Task FluentMockServer_Should_delay_responses() - { - // given - var server = FluentMockServer.Start(); - server.AddGlobalProcessingDelay(TimeSpan.FromMilliseconds(200)); - server - .Given(Request.Create().WithPath("/*")) - .RespondWith(Response.Create().WithBody(@"{ msg: ""Hello world!""}")); - - // when - var watch = new Stopwatch(); - watch.Start(); - await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo"); - watch.Stop(); - - // then - Check.That(watch.ElapsedMilliseconds).IsStrictlyGreaterThan(200); - } - - //Leaving commented as this requires an actual certificate with password, along with a service that expects a client certificate - //[Fact] - //public async Task Should_proxy_responses_with_client_certificate() - //{ - // // given - // var _server = FluentMockServer.Start(); - // _server - // .Given(Request.Create().WithPath("/*")) - // .RespondWith(Response.Create().WithProxy("https://server-that-expects-a-client-certificate", @"\\yourclientcertificatecontainingprivatekey.pfx", "yourclientcertificatepassword")); - - // // when - // var result = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/someurl?someQuery=someValue"); - - // // then - // Check.That(result).Contains("google"); - //} - - [Fact] - public async Task FluentMockServer_Should_exclude_restrictedResponseHeader() - { - // Assign - string path = $"/foo_{Guid.NewGuid()}"; - var server = FluentMockServer.Start(); - - server - .Given(Request.Create().WithPath(path).UsingGet()) - .RespondWith(Response.Create().WithHeader("Transfer-Encoding", "chunked").WithHeader("test", "t")); - - // Act - var response = await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + path); - - // Assert - Check.That(response.Headers.Contains("test")).IsTrue(); - Check.That(response.Headers.Contains("Transfer-Encoding")).IsFalse(); - } - - [Theory] - [InlineData("DELETE")] -#if !NET452 - [InlineData("TRACE")] - [InlineData("GET")] -#endif - public async Task FluentMockServer_Should_exclude_body_for_methods_where_body_is_definitely_disallowed(string method) - { - // Assign - string content = "hello"; - var server = FluentMockServer.Start(); - - server - .Given(Request.Create().WithBody((byte[] bodyBytes) => bodyBytes != null)) - .AtPriority(0) - .RespondWith(Response.Create().WithStatusCode(400)); - server - .Given(Request.Create()) - .AtPriority(1) - .RespondWith(Response.Create().WithStatusCode(200)); - - // Act - var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost:" + server.Ports[0] + "/"); - request.Content = new StringContent(content); - var response = await new HttpClient().SendAsync(request); - - // Assert - Check.That(response.StatusCode).Equals(HttpStatusCode.OK); - } - - [Theory] - [InlineData("POST")] - [InlineData("PUT")] - [InlineData("OPTIONS")] - [InlineData("REPORT")] - [InlineData("SOME-UNKNOWN-METHOD")] // default behavior for unknown methods is to allow a body (see BodyParser.ShouldParseBody) - public async Task FluentMockServer_Should_not_exclude_body_for_supported_methods(string method) - { - // Assign - string content = "hello"; - var server = FluentMockServer.Start(); - - server - .Given(Request.Create().WithBody(content)) - .AtPriority(0) - .RespondWith(Response.Create().WithStatusCode(200)); - server - .Given(Request.Create()) - .AtPriority(1) - .RespondWith(Response.Create().WithStatusCode(400)); - - // Act - var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost:" + server.Ports[0] + "/"); - request.Content = new StringContent(content); - var response = await new HttpClient().SendAsync(request); - - // Assert - Check.That(response.StatusCode).Equals(HttpStatusCode.OK); - } - - [Theory] - [InlineData("application/json")] - [InlineData("application/json; charset=ascii")] - [InlineData("application/json; charset=utf-8")] - [InlineData("application/json; charset=UTF-8")] - public async Task WireMockServer_Should_AcceptPostMappingsWithContentTypeJsonAndAnyCharset(string contentType) - { - // Arrange - string message = @"{ - ""request"": { - ""method"": ""GET"", - ""url"": ""/some/thing"" - }, - ""response"": { - ""status"": 200, - ""body"": ""Hello world!"", - ""headers"": { - ""Content-Type"": ""text/plain"" - } - } - }"; - var stringContent = new StringContent(message); - stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); - var server = FluentMockServer.StartWithAdminInterface(); - - // Act - var response = await new HttpClient().PostAsync($"{server.Urls[0]}/__admin/mappings", stringContent); - - // Assert - Check.That(response.StatusCode).Equals(HttpStatusCode.Created); - Check.That(await response.Content.ReadAsStringAsync()).Contains("Mapping added"); - } - } +using System; +using System.Diagnostics; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +using NFluent; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; +using WireMock.Server; +using Xunit; + +namespace WireMock.Net.Tests +{ + public class WireMockServerTests + { + [Fact] + public async Task WireMockServer_Should_reset_requestlogs() + { + // given + var server = WireMockServer.Start(); + + // when + await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + "/foo"); + server.ResetLogEntries(); + + // then + Check.That(server.LogEntries).IsEmpty(); + } + + [Fact] + public void WireMockServer_Should_reset_mappings() + { + // given + string path = $"/foo_{Guid.NewGuid()}"; + var server = WireMockServer.Start(); + + server + .Given(Request.Create() + .WithPath(path) + .UsingGet()) + .RespondWith(Response.Create() + .WithBody(@"{ msg: ""Hello world!""}")); + + // when + server.ResetMappings(); + + // then + Check.That(server.Mappings).IsEmpty(); + Check.ThatAsyncCode(() => new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path)).ThrowsAny(); + } + + [Fact] + public async Task WireMockServer_Should_respond_a_redirect_without_body() + { + // Assign + string path = $"/foo_{Guid.NewGuid()}"; + string pathToRedirect = $"/bar_{Guid.NewGuid()}"; + + var server = WireMockServer.Start(); + + server + .Given(Request.Create() + .WithPath(path) + .UsingGet()) + .RespondWith(Response.Create() + .WithStatusCode(307) + .WithHeader("Location", pathToRedirect)); + server + .Given(Request.Create() + .WithPath(pathToRedirect) + .UsingGet()) + .RespondWith(Response.Create() + .WithStatusCode(200) + .WithBody("REDIRECT SUCCESSFUL")); + + // Act + var response = await new HttpClient().GetStringAsync($"http://localhost:{server.Ports[0]}{path}"); + + // Assert + Check.That(response).IsEqualTo("REDIRECT SUCCESSFUL"); + } + + [Fact] + public async Task WireMockServer_Should_delay_responses_for_a_given_route() + { + // given + var server = WireMockServer.Start(); + + server + .Given(Request.Create() + .WithPath("/*")) + .RespondWith(Response.Create() + .WithBody(@"{ msg: ""Hello world!""}") + .WithDelay(TimeSpan.FromMilliseconds(200))); + + // when + var watch = new Stopwatch(); + watch.Start(); + await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo"); + watch.Stop(); + + // then + Check.That(watch.ElapsedMilliseconds).IsStrictlyGreaterThan(200); + } + + [Fact] + public async Task WireMockServer_Should_delay_responses() + { + // given + var server = WireMockServer.Start(); + server.AddGlobalProcessingDelay(TimeSpan.FromMilliseconds(200)); + server + .Given(Request.Create().WithPath("/*")) + .RespondWith(Response.Create().WithBody(@"{ msg: ""Hello world!""}")); + + // when + var watch = new Stopwatch(); + watch.Start(); + await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo"); + watch.Stop(); + + // then + Check.That(watch.ElapsedMilliseconds).IsStrictlyGreaterThan(200); + } + + //Leaving commented as this requires an actual certificate with password, along with a service that expects a client certificate + //[Fact] + //public async Task Should_proxy_responses_with_client_certificate() + //{ + // // given + // var _server = WireMockServer.Start(); + // _server + // .Given(Request.Create().WithPath("/*")) + // .RespondWith(Response.Create().WithProxy("https://server-that-expects-a-client-certificate", @"\\yourclientcertificatecontainingprivatekey.pfx", "yourclientcertificatepassword")); + + // // when + // var result = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/someurl?someQuery=someValue"); + + // // then + // Check.That(result).Contains("google"); + //} + + [Fact] + public async Task WireMockServer_Should_exclude_restrictedResponseHeader() + { + // Assign + string path = $"/foo_{Guid.NewGuid()}"; + var server = WireMockServer.Start(); + + server + .Given(Request.Create().WithPath(path).UsingGet()) + .RespondWith(Response.Create().WithHeader("Transfer-Encoding", "chunked").WithHeader("test", "t")); + + // Act + var response = await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + path); + + // Assert + Check.That(response.Headers.Contains("test")).IsTrue(); + Check.That(response.Headers.Contains("Transfer-Encoding")).IsFalse(); + } + + [Theory] + [InlineData("DELETE")] +#if !NET452 + [InlineData("TRACE")] + [InlineData("GET")] +#endif + public async Task WireMockServer_Should_exclude_body_for_methods_where_body_is_definitely_disallowed(string method) + { + // Assign + string content = "hello"; + var server = WireMockServer.Start(); + + server + .Given(Request.Create().WithBody((byte[] bodyBytes) => bodyBytes != null)) + .AtPriority(0) + .RespondWith(Response.Create().WithStatusCode(400)); + server + .Given(Request.Create()) + .AtPriority(1) + .RespondWith(Response.Create().WithStatusCode(200)); + + // Act + var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost:" + server.Ports[0] + "/"); + request.Content = new StringContent(content); + var response = await new HttpClient().SendAsync(request); + + // Assert + Check.That(response.StatusCode).Equals(HttpStatusCode.OK); + } + + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("OPTIONS")] + [InlineData("REPORT")] + [InlineData("SOME-UNKNOWN-METHOD")] // default behavior for unknown methods is to allow a body (see BodyParser.ShouldParseBody) + public async Task WireMockServer_Should_not_exclude_body_for_supported_methods(string method) + { + // Assign + string content = "hello"; + var server = WireMockServer.Start(); + + server + .Given(Request.Create().WithBody(content)) + .AtPriority(0) + .RespondWith(Response.Create().WithStatusCode(200)); + server + .Given(Request.Create()) + .AtPriority(1) + .RespondWith(Response.Create().WithStatusCode(400)); + + // Act + var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost:" + server.Ports[0] + "/"); + request.Content = new StringContent(content); + var response = await new HttpClient().SendAsync(request); + + // Assert + Check.That(response.StatusCode).Equals(HttpStatusCode.OK); + } + + [Theory] + [InlineData("application/json")] + [InlineData("application/json; charset=ascii")] + [InlineData("application/json; charset=utf-8")] + [InlineData("application/json; charset=UTF-8")] + public async Task WireMockServer_Should_AcceptPostMappingsWithContentTypeJsonAndAnyCharset(string contentType) + { + // Arrange + string message = @"{ + ""request"": { + ""method"": ""GET"", + ""url"": ""/some/thing"" + }, + ""response"": { + ""status"": 200, + ""body"": ""Hello world!"", + ""headers"": { + ""Content-Type"": ""text/plain"" + } + } + }"; + var stringContent = new StringContent(message); + stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); + var server = WireMockServer.StartWithAdminInterface(); + + // Act + var response = await new HttpClient().PostAsync($"{server.Urls[0]}/__admin/mappings", stringContent); + + // Assert + Check.That(response.StatusCode).Equals(HttpStatusCode.Created); + Check.That(await response.Content.ReadAsStringAsync()).Contains("Mapping added"); + } + } } \ No newline at end of file