diff --git a/README.md b/README.md index afe118dc..252e013b 100644 --- a/README.md +++ b/README.md @@ -32,15 +32,18 @@ A C# .NET version based on [mock4net](https://github.com/alexvictoor/mock4net) w ### Frameworks The following frameworks are supported: -- net 4.5.2 and up & net 4.6 and up -- netstandard 1.3 & netstandard 2.0 +- net 4.5.1 and up (Microsoft.AspNet.WebApi.OwinSelfHost version 5.2.6) +- net 4.6.1 and up (Microsoft.AspNetCore version 2.1.2) +- netstandard 1.3 (Microsoft.AspNetCore version 1.1.7) +- netstandard 2.0 (Microsoft.AspNetCore version 2.1.2) ### Build info To build you need: -- Microsoft .NET Framework 4.5.2 Developer Pack (https://www.microsoft.com/en-us/download/details.aspx?id=42637) -- Microsoft .NET Framework 4.6 Targeting Pack (https://www.microsoft.com/en-us/download/confirmation.aspx?id=48136) -- Microsoft .NET Framework 4.6.2 Developer Pack (https://www.microsoft.com/en-us/download/confirmation.aspx?id=53321) -- .NET Core 2.0 (https://www.microsoft.com/net/core) +- Microsoft .NET Framework [4.5.1 Developer Pack](https://www.microsoft.com/en-us/download/details.aspx?id=40772) +- Microsoft .NET Framework [4.5.2 Developer Pack](https://www.microsoft.com/en-us/download/details.aspx?id=42637) +- Microsoft .NET Framework [4.6 Targeting Pack](https://www.microsoft.com/en-us/download/confirmation.aspx?id=48136) +- Microsoft .NET Framework [4.6.2 Developer Pack](https://www.microsoft.com/en-us/download/confirmation.aspx?id=53321) +- .NET Core 2.0 (https://www.microsoft.com/net/download) ## Stubbing A core feature of WireMock.Net is the ability to return canned/predefined HTTP responses for requests matching criteria, see [Wiki : Stubbing & Request Matching](https://github.com/WireMock-Net/WireMock.Net/wiki/Stubbing-and-Request-Matching). diff --git a/WireMock.Net Solution.sln b/WireMock.Net Solution.sln index 94142f9c..429b675f 100644 --- a/WireMock.Net Solution.sln +++ b/WireMock.Net Solution.sln @@ -40,8 +40,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.StandAlone.Net {B6269AAC-170A-43D5-8B9A-579DED3D9A95} = {B6269AAC-170A-43D5-8B9A-579DED3D9A95} EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.Console.NET452", "examples\WireMock.Net.ConsoleApplication\WireMock.Net.Console.NET452.csproj", "{668F689E-57B4-422E-8846-C0FF643CA268}" -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 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.Console.Proxy.Net452", "examples\WireMock.Net.Console.Proxy.Net452\WireMock.Net.Console.Proxy.Net452.csproj", "{26433A8F-BF01-4962-97EB-81BFFBB61096}" @@ -54,6 +52,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.Service", "exa EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.Console.HeadersTest", "examples\WireMock.Net.Console.HeadersTest\WireMock.Net.Console.HeadersTest.csproj", "{B70278E7-A2C6-4A3B-BBA9-1C873CA6F03C}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.Console.Net461.Classic", "examples\WireMock.Net.Console.Net461.Classic\WireMock.Net.Console.Net461.Classic.csproj", "{1261BB9B-A7D4-456C-8985-3CE560361B8E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.Console.Net452.Classic", "examples\WireMock.Net.Console.Net452.Classic\WireMock.Net.Console.Net452.Classic.csproj", "{668F689E-57B4-422E-8846-C0FF643CA268}" +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 Global @@ -94,10 +96,6 @@ Global {668F689E-57B4-422E-8846-C0FF643CA999}.Debug|Any CPU.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-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}.Release|Any CPU.ActiveCfg = Release|Any CPU - {668F689E-57B4-422E-8846-C0FF643CA268}.Release|Any CPU.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}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -122,6 +120,14 @@ Global {B70278E7-A2C6-4A3B-BBA9-1C873CA6F03C}.Debug|Any CPU.Build.0 = Debug|Any CPU {B70278E7-A2C6-4A3B-BBA9-1C873CA6F03C}.Release|Any CPU.ActiveCfg = Release|Any CPU {B70278E7-A2C6-4A3B-BBA9-1C873CA6F03C}.Release|Any CPU.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}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1261BB9B-A7D4-456C-8985-3CE560361B8E}.Release|Any CPU.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}.Release|Any CPU.ActiveCfg = Release|Any CPU + {668F689E-57B4-422E-8846-C0FF643CA268}.Release|Any CPU.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}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -139,13 +145,14 @@ Global {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} - {668F689E-57B4-422E-8846-C0FF643CA268} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {049539C1-7A66-4559-AD7A-B1C73B97CBB0} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {26433A8F-BF01-4962-97EB-81BFFBB61096} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {23A9AA3C-40FC-42AA-8A5E-05899795A1C6} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {3C279524-DB73-4DE3-BEF1-F2B2958C9F65} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {7F0B2446-0363-4720-AF46-F47F83B557DC} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {B70278E7-A2C6-4A3B-BBA9-1C873CA6F03C} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} + {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} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution diff --git a/appveyor.yml b/appveyor.yml index 80ad9a32..0401a1e8 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -35,7 +35,7 @@ build_script: # build WireMock.Net.Standalone - dotnet build .\src\WireMock.Net.Standalone\WireMock.Net.Standalone.csproj -c %CONFIGURATION% -# build WireMock.Net.Tests +# build WireMock.Net.Tests (net452 and net462) - dotnet build .\test\WireMock.Net.Tests\WireMock.Net.Tests.csproj -c %CONFIGURATION% test_script: @@ -43,7 +43,7 @@ test_script: - nuget.exe install coveralls.net -ExcludeVersion -Version 0.7.0 - pip install codecov - - cmd: '"OpenCover\tools\OpenCover.Console.exe" -target:dotnet.exe -targetargs:"test test\WireMock.Net.Tests\WireMock.Net.Tests.csproj --no-build" -output:coverage.xml -returntargetcode -register:user -filter:"+[WireMock.Net]* -[WireMock.Net.Tests*]*" -nodefaultfilters -returntargetcode -oldstyle -searchdirs:".\test\WireMock.Net.Tests\bin\%CONFIGURATION%\net452"' + - cmd: '"OpenCover\tools\OpenCover.Console.exe" -target:dotnet.exe -targetargs:"test test\WireMock.Net.Tests\WireMock.Net.Tests.csproj --no-build --framework net452" -output:coverage.xml -returntargetcode -register:user -filter:"+[WireMock.Net]* -[WireMock.Net.Tests*]*" -nodefaultfilters -returntargetcode -oldstyle -searchdirs:".\test\WireMock.Net.Tests\bin\%CONFIGURATION%\net452"' - codecov -f "coverage.xml" - coveralls.net\tools\csmacnz.Coveralls.exe --opencover -i .\coverage.xml - dotnet sonarscanner end /d:sonar.login="%SONAR_TOKEN%" diff --git a/examples/WireMock.Net.Client/WireMock.Net.Client.csproj b/examples/WireMock.Net.Client/WireMock.Net.Client.csproj index c35fb9b3..2afe44a4 100644 --- a/examples/WireMock.Net.Client/WireMock.Net.Client.csproj +++ b/examples/WireMock.Net.Client/WireMock.Net.Client.csproj @@ -8,7 +8,7 @@ - + diff --git a/examples/WireMock.Net.Console.HeadersTest/WireMock.Net.Console.HeadersTest.csproj b/examples/WireMock.Net.Console.HeadersTest/WireMock.Net.Console.HeadersTest.csproj index 7d8f16e3..a6e85cd6 100644 --- a/examples/WireMock.Net.Console.HeadersTest/WireMock.Net.Console.HeadersTest.csproj +++ b/examples/WireMock.Net.Console.HeadersTest/WireMock.Net.Console.HeadersTest.csproj @@ -9,7 +9,7 @@ - + diff --git a/examples/WireMock.Net.Console.NETCoreApp/WireMock.Net.Console.NETCoreApp.csproj b/examples/WireMock.Net.Console.NETCoreApp/WireMock.Net.Console.NETCoreApp.csproj index dc45d93a..e936ed8c 100644 --- a/examples/WireMock.Net.Console.NETCoreApp/WireMock.Net.Console.NETCoreApp.csproj +++ b/examples/WireMock.Net.Console.NETCoreApp/WireMock.Net.Console.NETCoreApp.csproj @@ -7,8 +7,8 @@ - - + + @@ -20,7 +20,7 @@ - + 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 b3569ec4..d6e2a54f 100644 --- a/examples/WireMock.Net.Console.NETCoreApp2/WireMock.Net.Console.NETCoreApp2.csproj +++ b/examples/WireMock.Net.Console.NETCoreApp2/WireMock.Net.Console.NETCoreApp2.csproj @@ -4,12 +4,11 @@ Exe netcoreapp2.1 ../../WireMock.Net-Logo.ico - WireMock.Net.Console.NETCoreApp.Program - - + + @@ -19,15 +18,10 @@ - - - - - - + diff --git a/examples/WireMock.Net.ConsoleApplication/App.config b/examples/WireMock.Net.Console.Net452.Classic/App.config similarity index 100% rename from examples/WireMock.Net.ConsoleApplication/App.config rename to examples/WireMock.Net.Console.Net452.Classic/App.config diff --git a/examples/WireMock.Net.ConsoleApplication/CustomFileSystemFileHandler.cs b/examples/WireMock.Net.Console.Net452.Classic/CustomFileSystemFileHandler.cs similarity index 100% rename from examples/WireMock.Net.ConsoleApplication/CustomFileSystemFileHandler.cs rename to examples/WireMock.Net.Console.Net452.Classic/CustomFileSystemFileHandler.cs diff --git a/examples/WireMock.Net.ConsoleApplication/MainApp.cs b/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs similarity index 96% rename from examples/WireMock.Net.ConsoleApplication/MainApp.cs rename to examples/WireMock.Net.Console.Net452.Classic/MainApp.cs index 09f12274..aad6a391 100644 --- a/examples/WireMock.Net.ConsoleApplication/MainApp.cs +++ b/examples/WireMock.Net.Console.Net452.Classic/MainApp.cs @@ -336,6 +336,20 @@ namespace WireMock.Net.ConsoleApplication .RespondWith(Response.Create() .WithBody("Test state msg 2")); + server + .Given(Request.Create().WithPath("/encoded-test/a%20b")) + .RespondWith(Response.Create() + .WithBody("EncodedTest 1 : Path={{request.path}}, Url={{request.url}}") + .WithTransformer() + ); + + server + .Given(Request.Create().WithPath("/encoded-test/a b")) + .RespondWith(Response.Create() + .WithBody("EncodedTest 2 : Path={{request.path}}, Url={{request.url}}") + .WithTransformer() + ); + System.Console.WriteLine("Press any key to stop the server"); System.Console.ReadKey(); server.Stop(); diff --git a/examples/WireMock.Net.ConsoleApplication/Program.cs b/examples/WireMock.Net.Console.Net452.Classic/Program.cs similarity index 100% rename from examples/WireMock.Net.ConsoleApplication/Program.cs rename to examples/WireMock.Net.Console.Net452.Classic/Program.cs diff --git a/examples/WireMock.Net.ConsoleApplication/Properties/AssemblyInfo.cs b/examples/WireMock.Net.Console.Net452.Classic/Properties/AssemblyInfo.cs similarity index 86% rename from examples/WireMock.Net.ConsoleApplication/Properties/AssemblyInfo.cs rename to examples/WireMock.Net.Console.Net452.Classic/Properties/AssemblyInfo.cs index e22f1147..8aee3f96 100644 --- a/examples/WireMock.Net.ConsoleApplication/Properties/AssemblyInfo.cs +++ b/examples/WireMock.Net.Console.Net452.Classic/Properties/AssemblyInfo.cs @@ -4,12 +4,12 @@ using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("WireMock.Net.ConsoleApplication")] +[assembly: AssemblyTitle("WireMock.Net.Console.Net452.Classic")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("WireMock.Net.ConsoleApplication")] -[assembly: AssemblyCopyright("Copyright © Stef Heyenrath 2017")] +[assembly: AssemblyProduct("WireMock.Net.Console.Net452.Classic")] +[assembly: AssemblyCopyright("Copyright © Stef Heyenrath 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] diff --git a/examples/WireMock.Net.ConsoleApplication/WireMock.Net.Console.NET452.csproj b/examples/WireMock.Net.Console.Net452.Classic/WireMock.Net.Console.Net452.Classic.csproj similarity index 97% rename from examples/WireMock.Net.ConsoleApplication/WireMock.Net.Console.NET452.csproj rename to examples/WireMock.Net.Console.Net452.Classic/WireMock.Net.Console.Net452.Classic.csproj index 4d689ec7..01e65204 100644 --- a/examples/WireMock.Net.ConsoleApplication/WireMock.Net.Console.NET452.csproj +++ b/examples/WireMock.Net.Console.Net452.Classic/WireMock.Net.Console.Net452.Classic.csproj @@ -43,8 +43,8 @@ ..\..\packages\Microsoft.Owin.Host.HttpListener.3.1.0\lib\net45\Microsoft.Owin.Host.HttpListener.dll - - ..\..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll ..\..\packages\SimMetrics.Net.1.0.4\lib\net45\SimMetrics.Net.dll diff --git a/examples/WireMock.Net.ConsoleApplication/__admin/mappings/11111110-a633-40e8-a244-5cb80bc0ab66.json b/examples/WireMock.Net.Console.Net452.Classic/__admin/mappings/11111110-a633-40e8-a244-5cb80bc0ab66.json similarity index 100% rename from examples/WireMock.Net.ConsoleApplication/__admin/mappings/11111110-a633-40e8-a244-5cb80bc0ab66.json rename to examples/WireMock.Net.Console.Net452.Classic/__admin/mappings/11111110-a633-40e8-a244-5cb80bc0ab66.json diff --git a/examples/WireMock.Net.ConsoleApplication/__admin/mappings/873d495f-940e-4b86-a1f4-4f0fc7be8b8b.json b/examples/WireMock.Net.Console.Net452.Classic/__admin/mappings/873d495f-940e-4b86-a1f4-4f0fc7be8b8b.json similarity index 100% rename from examples/WireMock.Net.ConsoleApplication/__admin/mappings/873d495f-940e-4b86-a1f4-4f0fc7be8b8b.json rename to examples/WireMock.Net.Console.Net452.Classic/__admin/mappings/873d495f-940e-4b86-a1f4-4f0fc7be8b8b.json diff --git a/examples/WireMock.Net.ConsoleApplication/log4net.config b/examples/WireMock.Net.Console.Net452.Classic/log4net.config similarity index 100% rename from examples/WireMock.Net.ConsoleApplication/log4net.config rename to examples/WireMock.Net.Console.Net452.Classic/log4net.config diff --git a/examples/WireMock.Net.ConsoleApplication/packages.config b/examples/WireMock.Net.Console.Net452.Classic/packages.config similarity index 80% rename from examples/WireMock.Net.ConsoleApplication/packages.config rename to examples/WireMock.Net.Console.Net452.Classic/packages.config index a1ad973f..07520191 100644 --- a/examples/WireMock.Net.ConsoleApplication/packages.config +++ b/examples/WireMock.Net.Console.Net452.Classic/packages.config @@ -2,6 +2,6 @@ - + \ No newline at end of file diff --git a/examples/WireMock.Net.Console.Net461.Classic/App.config b/examples/WireMock.Net.Console.Net461.Classic/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/examples/WireMock.Net.Console.Net461.Classic/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/test/WireMock.Net.Tests.old/Properties/AssemblyInfo.cs b/examples/WireMock.Net.Console.Net461.Classic/Properties/AssemblyInfo.cs similarity index 74% rename from test/WireMock.Net.Tests.old/Properties/AssemblyInfo.cs rename to examples/WireMock.Net.Console.Net461.Classic/Properties/AssemblyInfo.cs index e0e53361..a10ce6d3 100644 --- a/test/WireMock.Net.Tests.old/Properties/AssemblyInfo.cs +++ b/examples/WireMock.Net.Console.Net461.Classic/Properties/AssemblyInfo.cs @@ -1,34 +1,35 @@ using System.Reflection; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("WireMock.Net.Tests")] +[assembly: AssemblyTitle("WireMock.Net.Console.Net461.Classic")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("WireMock.Net.Tests")] -[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyProduct("WireMock.Net.Console.Net461.Classic")] +[assembly: AssemblyCopyright("Copyright © Stef Heyenrath 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("d8b56d28-33ce-4bef-97d4-7dd546e37f25")] +[assembly: Guid("1261bb9b-a7d4-456c-8985-3ce560361b8e")] // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -// You can specify all the values or you can default the Build and Revision Numbers +// You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] 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 new file mode 100644 index 00000000..ce4bbd85 --- /dev/null +++ b/examples/WireMock.Net.Console.Net461.Classic/WireMock.Net.Console.Net461.Classic.csproj @@ -0,0 +1,86 @@ + + + + + Debug + AnyCPU + {1261BB9B-A7D4-456C-8985-3CE560361B8E} + Exe + WireMock.Net.Console.Net461.Classic + WireMock.Net.Console.Net461.Classic + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + WireMock.Net.ConsoleApplication.Program + + + + ..\..\packages\log4net.2.0.8\lib\net45-full\log4net.dll + + + ..\..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll + + + ..\..\packages\SimMetrics.Net.1.0.4\lib\net45\SimMetrics.Net.dll + + + + + + + + + + + + + CustomFileSystemFileHandler.cs + + + MainApp.cs + + + Program.cs + + + + + + log4net.config + + + + + + + {b6269aac-170a-43d5-8b9a-579ded3d9a95} + WireMock.Net.StandAlone + + + {d3804228-91f4-4502-9595-39584e5a01ad} + WireMock.Net + + + + \ No newline at end of file diff --git a/examples/WireMock.Net.Console.Net461.Classic/packages.config b/examples/WireMock.Net.Console.Net461.Classic/packages.config new file mode 100644 index 00000000..812b5209 --- /dev/null +++ b/examples/WireMock.Net.Console.Net461.Classic/packages.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file 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 08a0483c..b13d1274 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 @@ -1,4 +1,4 @@ - + Exe @@ -7,7 +7,7 @@ - + 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 04605b1a..56fc21e4 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 @@ -71,8 +71,8 @@ ..\..\packages\Microsoft.Owin.Host.HttpListener.3.1.0\lib\net45\Microsoft.Owin.Host.HttpListener.dll - - ..\..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll diff --git a/examples/WireMock.Net.Console.Proxy.Net452/packages.config b/examples/WireMock.Net.Console.Proxy.Net452/packages.config index 524c4b7b..08416452 100644 --- a/examples/WireMock.Net.Console.Proxy.Net452/packages.config +++ b/examples/WireMock.Net.Console.Proxy.Net452/packages.config @@ -1,5 +1,5 @@  - + \ No newline at end of file diff --git a/examples/WireMock.Net.Console.Record.NETCoreApp/WireMock.Net.Console.Proxy.NETCoreApp.csproj b/examples/WireMock.Net.Console.Record.NETCoreApp/WireMock.Net.Console.Proxy.NETCoreApp.csproj index 23d023f3..aa44ab9d 100644 --- a/examples/WireMock.Net.Console.Record.NETCoreApp/WireMock.Net.Console.Proxy.NETCoreApp.csproj +++ b/examples/WireMock.Net.Console.Record.NETCoreApp/WireMock.Net.Console.Proxy.NETCoreApp.csproj @@ -8,7 +8,7 @@ - + diff --git a/examples/WireMock.Net.Service/App.config b/examples/WireMock.Net.Service/App.config index 443afce1..3b696c30 100644 --- a/examples/WireMock.Net.Service/App.config +++ b/examples/WireMock.Net.Service/App.config @@ -7,7 +7,7 @@ - + diff --git a/examples/WireMock.Net.Service/WireMock.Net.Service.csproj b/examples/WireMock.Net.Service/WireMock.Net.Service.csproj index f342b96a..ae6733dd 100644 --- a/examples/WireMock.Net.Service/WireMock.Net.Service.csproj +++ b/examples/WireMock.Net.Service/WireMock.Net.Service.csproj @@ -32,8 +32,8 @@ 4 - - ..\..\packages\Handlebars.Net.1.9.0\lib\net40\Handlebars.dll + + ..\..\packages\Handlebars.Net.1.9.5\lib\net452\Handlebars.dll ..\..\packages\Microsoft.Owin.2.0.2\lib\net45\Microsoft.Owin.dll @@ -47,8 +47,8 @@ ..\..\packages\MimeKitLite.2.0.1\lib\net45\MimeKitLite.dll - - ..\..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll ..\..\packages\Owin.1.0\lib\net40\Owin.dll diff --git a/examples/WireMock.Net.Service/packages.config b/examples/WireMock.Net.Service/packages.config index 1303aadd..a8e9d00e 100644 --- a/examples/WireMock.Net.Service/packages.config +++ b/examples/WireMock.Net.Service/packages.config @@ -1,6 +1,6 @@  - + @@ -9,7 +9,7 @@ - + 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 9cca970d..e7837990 100644 --- a/examples/WireMock.Net.StandAlone.Net452/WireMock.Net.StandAlone.Net452.csproj +++ b/examples/WireMock.Net.StandAlone.Net452/WireMock.Net.StandAlone.Net452.csproj @@ -45,14 +45,14 @@ ..\..\packages\Microsoft.Owin.Host.HttpListener.4.0.0\lib\net451\Microsoft.Owin.Host.HttpListener.dll - - ..\..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll - - ..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.4\lib\net45\System.Net.Http.Formatting.dll + + ..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.6\lib\net45\System.Net.Http.Formatting.dll diff --git a/examples/WireMock.Net.StandAlone.Net452/app.config b/examples/WireMock.Net.StandAlone.Net452/app.config index dde2c3cc..2bbe7715 100644 --- a/examples/WireMock.Net.StandAlone.Net452/app.config +++ b/examples/WireMock.Net.StandAlone.Net452/app.config @@ -4,7 +4,7 @@ - + diff --git a/examples/WireMock.Net.StandAlone.Net452/packages.config b/examples/WireMock.Net.StandAlone.Net452/packages.config index 19875868..f92a5626 100644 --- a/examples/WireMock.Net.StandAlone.Net452/packages.config +++ b/examples/WireMock.Net.StandAlone.Net452/packages.config @@ -1,7 +1,7 @@  - + - + \ No newline at end of file diff --git a/examples/WireMock.Net.WebApplication/WireMock.Net.WebApplication.NETCore2.csproj b/examples/WireMock.Net.WebApplication/WireMock.Net.WebApplication.NETCore2.csproj index c8ca0e7f..e4844cb6 100644 --- a/examples/WireMock.Net.WebApplication/WireMock.Net.WebApplication.NETCore2.csproj +++ b/examples/WireMock.Net.WebApplication/WireMock.Net.WebApplication.NETCore2.csproj @@ -11,7 +11,7 @@ - + diff --git a/examples/WireMock.Net.WebApplication/libman.json b/examples/WireMock.Net.WebApplication/libman.json new file mode 100644 index 00000000..ceee2710 --- /dev/null +++ b/examples/WireMock.Net.WebApplication/libman.json @@ -0,0 +1,5 @@ +{ + "version": "1.0", + "defaultProvider": "cdnjs", + "libraries": [] +} \ No newline at end of file diff --git a/examples/WireMock.Net.WebApplication/web.config b/examples/WireMock.Net.WebApplication/web.config index 2417b04e..37ed62c8 100644 --- a/examples/WireMock.Net.WebApplication/web.config +++ b/examples/WireMock.Net.WebApplication/web.config @@ -7,6 +7,6 @@ - + \ No newline at end of file diff --git a/src/WireMock.Net.StandAlone/WireMock.Net.StandAlone.csproj b/src/WireMock.Net.StandAlone/WireMock.Net.StandAlone.csproj index ae57d4d1..75dd8795 100644 --- a/src/WireMock.Net.StandAlone/WireMock.Net.StandAlone.csproj +++ b/src/WireMock.Net.StandAlone/WireMock.Net.StandAlone.csproj @@ -5,7 +5,7 @@ WireMock.Net.StandAlone 1.0.4.10 Stef Heyenrath - net452;net46;netstandard1.3;netstandard2.0 + net451;net452;net46;netstandard1.3;netstandard2.0 true WireMock.Net.StandAlone WireMock.Net.StandAlone @@ -30,7 +30,11 @@ - NETSTANDARD + NETSTANDARD;USE_ASPNETCORE + + + + USE_ASPNETCORE;NET46 diff --git a/src/WireMock.Net/Handlers/LocalFileSystemHandler.cs b/src/WireMock.Net/Handlers/LocalFileSystemHandler.cs index 89ee17c1..fca619ba 100644 --- a/src/WireMock.Net/Handlers/LocalFileSystemHandler.cs +++ b/src/WireMock.Net/Handlers/LocalFileSystemHandler.cs @@ -1,5 +1,7 @@ using System.Collections.Generic; using System.IO; +using JetBrains.Annotations; +using WireMock.Validation; namespace WireMock.Handlers { @@ -11,20 +13,26 @@ namespace WireMock.Handlers private static readonly string AdminMappingsFolder = Path.Combine("__admin", "mappings"); /// - public bool FolderExists(string path) + public bool FolderExists([NotNull] string path) { + Check.NotNullOrEmpty(path, nameof(path)); + return Directory.Exists(path); } /// - public void CreateFolder(string path) + public void CreateFolder([NotNull] string path) { + Check.NotNullOrEmpty(path, nameof(path)); + Directory.CreateDirectory(path); } /// - public IEnumerable EnumerateFiles(string path) + public IEnumerable EnumerateFiles([NotNull] string path) { + Check.NotNullOrEmpty(path, nameof(path)); + return Directory.EnumerateFiles(path); } @@ -35,14 +43,19 @@ namespace WireMock.Handlers } /// - public string ReadMappingFile(string path) + public string ReadMappingFile([NotNull] string path) { + Check.NotNullOrEmpty(path, nameof(path)); + return File.ReadAllText(path); } /// - public void WriteMappingFile(string path, string text) + public void WriteMappingFile([NotNull] string path, [NotNull] string text) { + Check.NotNullOrEmpty(path, nameof(path)); + Check.NotNull(text, nameof(text)); + File.WriteAllText(path, text); } } diff --git a/src/WireMock.Net/Http/PortUtil.cs b/src/WireMock.Net/Http/PortUtil.cs index 519a9902..b92e23db 100644 --- a/src/WireMock.Net/Http/PortUtil.cs +++ b/src/WireMock.Net/Http/PortUtil.cs @@ -9,7 +9,7 @@ namespace WireMock.Http /// public static class PortUtil { - private static readonly Regex UrlDetailsRegex = new Regex(@"^(?\w+)://[^/]+?(?\d+)?/", RegexOptions.Compiled); + private static readonly Regex UrlDetailsRegex = new Regex(@"^(?\w+)://[^/]+?(?\d+)/?", RegexOptions.Compiled); /// /// Finds a free TCP port. diff --git a/src/WireMock.Net/Owin/AspNetCoreSelfHost.cs b/src/WireMock.Net/Owin/AspNetCoreSelfHost.cs index 1f395f65..524600fd 100644 --- a/src/WireMock.Net/Owin/AspNetCoreSelfHost.cs +++ b/src/WireMock.Net/Owin/AspNetCoreSelfHost.cs @@ -1,4 +1,4 @@ -#if NETSTANDARD +#if USE_ASPNETCORE using System; using System.Collections.Generic; using System.Linq; @@ -107,9 +107,15 @@ namespace WireMock.Owin IsStarted = true; #if NETSTANDARD1_3 _logger.Info("WireMock.Net server using netstandard1.3"); +#elif NETSTANDARD2_0 + _logger.Info("WireMock.Net server using netstandard2.0"); +#elif NET46 + _logger.Info("WireMock.Net server using .net 4.6.1 or higher"); +#endif + +#if NETSTANDARD1_3 _host.Run(_cts.Token); #else - _logger.Info("WireMock.Net server using netstandard2.0"); _host.RunAsync(_cts.Token).Wait(); #endif } @@ -132,7 +138,7 @@ namespace WireMock.Owin #if NETSTANDARD1_3 return Task.FromResult(true); #else - return _host.WaitForShutdownAsync(); + return _host.StopAsync(); #endif } } diff --git a/src/WireMock.Net/Owin/GlobalExceptionMiddleware.cs b/src/WireMock.Net/Owin/GlobalExceptionMiddleware.cs index 0c0703dc..5b028f02 100644 --- a/src/WireMock.Net/Owin/GlobalExceptionMiddleware.cs +++ b/src/WireMock.Net/Owin/GlobalExceptionMiddleware.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; using Newtonsoft.Json; -#if !NETSTANDARD +#if !USE_ASPNETCORE using Microsoft.Owin; #else using Microsoft.AspNetCore.Http; @@ -9,7 +9,7 @@ using Microsoft.AspNetCore.Http; namespace WireMock.Owin { -#if !NETSTANDARD +#if !USE_ASPNETCORE internal class GlobalExceptionMiddleware : OwinMiddleware #else internal class GlobalExceptionMiddleware @@ -17,7 +17,7 @@ namespace WireMock.Owin { private readonly WireMockMiddlewareOptions _options; -#if !NETSTANDARD +#if !USE_ASPNETCORE public GlobalExceptionMiddleware(OwinMiddleware next, WireMockMiddlewareOptions options) : base(next) { _options = options; @@ -30,13 +30,13 @@ namespace WireMock.Owin } #endif -#if NETSTANDARD +#if USE_ASPNETCORE public RequestDelegate Next { get; } #endif private readonly OwinResponseMapper _responseMapper = new OwinResponseMapper(); -#if !NETSTANDARD +#if !USE_ASPNETCORE public override async Task Invoke(IOwinContext ctx) #else public async Task Invoke(HttpContext ctx) diff --git a/src/WireMock.Net/Owin/OwinRequestMapper.cs b/src/WireMock.Net/Owin/OwinRequestMapper.cs index 57211735..1131e739 100644 --- a/src/WireMock.Net/Owin/OwinRequestMapper.cs +++ b/src/WireMock.Net/Owin/OwinRequestMapper.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WireMock.Util; -#if !NETSTANDARD +#if !USE_ASPNETCORE using Microsoft.Owin; #else using Microsoft.AspNetCore.Http; @@ -23,14 +23,14 @@ namespace WireMock.Owin /// /// public async Task MapAsync( -#if !NETSTANDARD +#if !USE_ASPNETCORE IOwinRequest request #else HttpRequest request #endif ) { -#if !NETSTANDARD +#if !USE_ASPNETCORE var urldetails = UrlUtils.Parse(request.Uri, request.PathBase); string clientIP = request.RemoteIpAddress; #else diff --git a/src/WireMock.Net/Owin/OwinResponseMapper.cs b/src/WireMock.Net/Owin/OwinResponseMapper.cs index 7cde04f0..5d27a5b0 100644 --- a/src/WireMock.Net/Owin/OwinResponseMapper.cs +++ b/src/WireMock.Net/Owin/OwinResponseMapper.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; using Newtonsoft.Json; using WireMock.Http; using WireMock.Util; -#if !NETSTANDARD +#if !USE_ASPNETCORE using Microsoft.Owin; #else using Microsoft.AspNetCore.Http; @@ -24,7 +24,7 @@ namespace WireMock.Owin private readonly Encoding _utf8NoBom = new UTF8Encoding(false); // https://msdn.microsoft.com/en-us/library/78h415ay(v=vs.110).aspx -#if !NETSTANDARD +#if !USE_ASPNETCORE private static readonly IDictionary>> ResponseHeadersToFix = new Dictionary>>(StringComparer.OrdinalIgnoreCase) { #else private static readonly IDictionary>> ResponseHeadersToFix = new Dictionary>>(StringComparer.OrdinalIgnoreCase) { @@ -33,7 +33,7 @@ namespace WireMock.Owin }; private void SetResponseHeaders(ResponseMessage responseMessage -#if !NETSTANDARD +#if !USE_ASPNETCORE , IOwinResponse response #else , HttpResponse response @@ -49,7 +49,7 @@ namespace WireMock.Owin } else { -#if !NETSTANDARD +#if !USE_ASPNETCORE // For non-NETSTANDARD, check if this response header can be added (#148) if (!WebHeaderCollection.IsRestricted(pair.Key, true)) { @@ -69,7 +69,7 @@ namespace WireMock.Owin /// /// public async Task MapAsync(ResponseMessage responseMessage -#if !NETSTANDARD +#if !USE_ASPNETCORE , IOwinResponse response #else , HttpResponse response diff --git a/src/WireMock.Net/Owin/OwinSelfHost.cs b/src/WireMock.Net/Owin/OwinSelfHost.cs index 1234ea8d..c4f2acb9 100644 --- a/src/WireMock.Net/Owin/OwinSelfHost.cs +++ b/src/WireMock.Net/Owin/OwinSelfHost.cs @@ -1,4 +1,4 @@ -#if !NETSTANDARD +#if !USE_ASPNETCORE using JetBrains.Annotations; using Microsoft.Owin.Hosting; using Owin; @@ -65,9 +65,9 @@ namespace WireMock.Owin private void StartServers() { #if NET46 - _logger.Info("WireMock.Net server using .net 4.6.x or higher"); + _logger.Info("WireMock.Net server using .net 4.6.1 or higher"); #else - _logger.Info("WireMock.Net server using .net 4.5.x or higher"); + _logger.Info("WireMock.Net server using .net 4.5.x"); #endif var servers = new List(); diff --git a/src/WireMock.Net/Owin/WireMockMiddleware.cs b/src/WireMock.Net/Owin/WireMockMiddleware.cs index d7575c32..23aca6bc 100644 --- a/src/WireMock.Net/Owin/WireMockMiddleware.cs +++ b/src/WireMock.Net/Owin/WireMockMiddleware.cs @@ -9,7 +9,7 @@ using WireMock.Util; using Newtonsoft.Json; using WireMock.Http; using WireMock.Serialization; -#if !NETSTANDARD +#if !USE_ASPNETCORE using Microsoft.Owin; #else using Microsoft.AspNetCore.Http; @@ -17,7 +17,7 @@ using Microsoft.AspNetCore.Http; namespace WireMock.Owin { -#if !NETSTANDARD +#if !USE_ASPNETCORE internal class WireMockMiddleware : OwinMiddleware #else internal class WireMockMiddleware @@ -29,7 +29,7 @@ namespace WireMock.Owin private readonly OwinRequestMapper _requestMapper = new OwinRequestMapper(); private readonly OwinResponseMapper _responseMapper = new OwinResponseMapper(); -#if !NETSTANDARD +#if !USE_ASPNETCORE public WireMockMiddleware(OwinMiddleware next, WireMockMiddlewareOptions options) : base(next) { _options = options; @@ -41,7 +41,7 @@ namespace WireMock.Owin } #endif -#if !NETSTANDARD +#if !USE_ASPNETCORE public override async Task Invoke(IOwinContext ctx) #else public async Task Invoke(HttpContext ctx) diff --git a/src/WireMock.Net/Owin/WireMockMiddlewareOptions.cs b/src/WireMock.Net/Owin/WireMockMiddlewareOptions.cs index 2111e7e8..09beadbe 100644 --- a/src/WireMock.Net/Owin/WireMockMiddlewareOptions.cs +++ b/src/WireMock.Net/Owin/WireMockMiddlewareOptions.cs @@ -4,7 +4,7 @@ using System.Collections.ObjectModel; using WireMock.Logging; using WireMock.Matchers; using WireMock.Util; -#if !NETSTANDARD +#if !USE_ASPNETCORE using Owin; #else using Microsoft.AspNetCore.Builder; @@ -32,7 +32,7 @@ namespace WireMock.Owin public int? MaxRequestLogCount { get; set; } -#if !NETSTANDARD +#if !USE_ASPNETCORE public Action PreWireMockMiddlewareInit { get; set; } public Action PostWireMockMiddlewareInit { get; set; } diff --git a/src/WireMock.Net/Server/FluentMockServer.cs b/src/WireMock.Net/Server/FluentMockServer.cs index f7d261d4..559c1408 100644 --- a/src/WireMock.Net/Server/FluentMockServer.cs +++ b/src/WireMock.Net/Server/FluentMockServer.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; +using System.Threading.Tasks; using Newtonsoft.Json; using WireMock.Handlers; using WireMock.Http; @@ -77,7 +78,7 @@ namespace WireMock.Server /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected virtual void Dispose(bool disposing) { - if (_httpServer != null && _httpServer.IsStarted) + if (_httpServer != null) { _httpServer.StopAsync(); } @@ -194,19 +195,19 @@ namespace WireMock.Server if (settings.Urls != null) { - Urls = settings.Urls.Select(u => u.EndsWith("/") ? u : $"{u}/").ToArray(); + Urls = settings.Urls.ToArray(); } else { int port = settings.Port > 0 ? settings.Port.Value : PortUtil.FindFreeTcpPort(); - Urls = new[] { (settings.UseSSL == true ? "https" : "http") + "://localhost:" + port + "/" }; + Urls = new[] { $"{(settings.UseSSL == true ? "https" : "http")}://localhost:{port}" }; } _options.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit; _options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit; _options.Logger = _logger; -#if NETSTANDARD +#if USE_ASPNETCORE _httpServer = new AspNetCoreSelfHost(_options, Urls); #else _httpServer = new OwinSelfHost(_options, Urls); diff --git a/src/WireMock.Net/Util/UrlUtils.cs b/src/WireMock.Net/Util/UrlUtils.cs index 7ccb08f9..78b070a8 100644 --- a/src/WireMock.Net/Util/UrlUtils.cs +++ b/src/WireMock.Net/Util/UrlUtils.cs @@ -1,7 +1,7 @@ using System; using JetBrains.Annotations; using WireMock.Models; -#if !NETSTANDARD +#if !USE_ASPNETCORE using Microsoft.Owin; #else using Microsoft.AspNetCore.Http; diff --git a/src/WireMock.Net/WireMock.Net.csproj b/src/WireMock.Net/WireMock.Net.csproj index 6be2c57b..94a05c01 100644 --- a/src/WireMock.Net/WireMock.Net.csproj +++ b/src/WireMock.Net/WireMock.Net.csproj @@ -5,7 +5,7 @@ WireMock.Net 1.0.4.10 Stef Heyenrath - net452;net46;netstandard1.3;netstandard2.0 + net451;net452;net46;net461;netstandard1.3;netstandard2.0 true WireMock.Net WireMock.Net @@ -24,13 +24,17 @@ {D3804228-91F4-4502-9595-39584E5A01AD} - + $(MSBuildProjectDirectory)=/ true - - NETSTANDARD + + NETSTANDARD;USE_ASPNETCORE + + + + USE_ASPNETCORE;NET46 @@ -41,15 +45,23 @@ All - - + + + + + + + + + + @@ -57,6 +69,7 @@ + @@ -66,7 +79,14 @@ + + + + + + + @@ -75,7 +95,8 @@ - + + diff --git a/test/WireMock.Net.Tests.old/FluentMockServerTests.cs b/test/WireMock.Net.Tests.old/FluentMockServerTests.cs deleted file mode 100644 index 6c6c1a90..00000000 --- a/test/WireMock.Net.Tests.old/FluentMockServerTests.cs +++ /dev/null @@ -1,291 +0,0 @@ -using System; -using System.Diagnostics; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; -using NFluent; -using NUnit.Framework; -using WireMock.Matchers; -using WireMock.RequestBuilders; -using WireMock.ResponseBuilders; -using WireMock.Server; - -namespace WireMock.Net.Tests -{ - [TestFixture] - [Timeout(5000)] - public class FluentMockServerTests - { - private FluentMockServer _server; - - [Test] - public void FluentMockServer_Admin_Mappings_Get() - { - var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05"); - _server = FluentMockServer.Start(); - - _server.Given(Request.Create().WithPath("/foo1").UsingGet()) - .WithGuid(guid) - .RespondWith(Response.Create().WithStatusCode(201).WithBody("1")); - - _server.Given(Request.Create().WithPath("/foo2").UsingGet()) - .RespondWith(Response.Create().WithStatusCode(202).WithBody("2")); - - var mappings = _server.Mappings.ToArray(); - Check.That(mappings).HasSize(2); - - Check.That(mappings.First().RequestMatcher).IsNotNull(); - Check.That(mappings.First().Provider).IsNotNull(); - Check.That(mappings.First().Guid).Equals(guid); - - Check.That(mappings[1].Guid).Not.Equals(guid); - } - - [Test] - public void FluentMockServer_Admin_Mappings_Add_SameGuid() - { - var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05"); - _server = FluentMockServer.Start(); - - _server.Given(Request.Create().WithPath("/1").UsingGet()) - .WithGuid(guid) - .RespondWith(Response.Create().WithStatusCode(500)); - - var mappings = _server.Mappings.ToArray(); - Check.That(mappings).HasSize(1); - Check.That(mappings.First().Guid).Equals(guid); - - _server.Given(Request.Create().WithPath("/2").UsingGet()) - .WithGuid(guid) - .RespondWith(Response.Create().WithStatusCode(500)); - - Check.That(mappings).HasSize(1); - Check.That(mappings.First().Guid).Equals(guid); - } - - [Test] - public async Task FluentMockServer_Admin_Mappings_AtPriority() - { - _server = FluentMockServer.Start(); - - // given - _server.Given(Request.Create().WithPath("/1").UsingGet()) - .AtPriority(2) - .RespondWith(Response.Create().WithStatusCode(200)); - - _server.Given(Request.Create().WithPath("/1").UsingGet()) - .AtPriority(1) - .RespondWith(Response.Create().WithStatusCode(400)); - - var mappings = _server.Mappings.ToArray(); - Check.That(mappings).HasSize(2); - Check.That(mappings[0].Priority).Equals(2); - Check.That(mappings[1].Priority).Equals(1); - - // when - var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/1"); - - // then - Check.That((int)response.StatusCode).IsEqualTo(400); - } - - [Test] - public async Task FluentMockServer_Admin_Requests_Get() - { - // given - _server = FluentMockServer.Start(); - - // when - await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo"); - - // then - Check.That(_server.LogEntries).HasSize(1); - var requestLogged = _server.LogEntries.First(); - Check.That(requestLogged.RequestMessage.Method).IsEqualTo("get"); - Check.That(requestLogged.RequestMessage.BodyAsBytes).IsNull(); - } - - [Test] - public async Task Should_respond_to_request() - { - // given - _server = FluentMockServer.Start(); - - _server - .Given(Request.Create() - .WithPath("/foo") - .UsingGet()) - .RespondWith(Response.Create() - .WithStatusCode(200) - .WithBody(@"{ msg: ""Hello world!""}")); - - // when - var response = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo"); - - // then - Check.That(response).IsEqualTo(@"{ msg: ""Hello world!""}"); - } - - [Test] - public async Task Should_respond_to_request_bodyAsBase64() - { - // given - _server = FluentMockServer.Start(); - - _server.Given(Request.Create().WithPath("/foo").UsingGet()).RespondWith(Response.Create().WithBodyAsBase64("SGVsbG8gV29ybGQ/")); - - // when - var response = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo"); - - // then - Check.That(response).IsEqualTo("Hello World?"); - } - - [Test] - public async Task Should_respond_404_for_unexpected_request() - { - // given - _server = FluentMockServer.Start(); - - // when - var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo"); - - // then - Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - Check.That((int)response.StatusCode).IsEqualTo(404); - } - - [Test] - public async Task Should_find_a_request_satisfying_a_request_spec() - { - // given - _server = FluentMockServer.Start(); - - // when - await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo"); - await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/bar"); - - // then - var result = _server.FindLogEntries(Request.Create().WithPath(new RegexMatcher("^/b.*"))).ToList(); - Check.That(result).HasSize(1); - - var requestLogged = result.First(); - Check.That(requestLogged.RequestMessage.Path).IsEqualTo("/bar"); - Check.That(requestLogged.RequestMessage.Url).IsEqualTo("http://localhost:" + _server.Ports[0] + "/bar"); - } - - [Test] - public async Task Should_reset_requestlogs() - { - // given - _server = FluentMockServer.Start(); - - // when - await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo"); - _server.ResetLogEntries(); - - // then - Check.That(_server.LogEntries).IsEmpty(); - } - - [Test] - public void Should_reset_mappings() - { - // given - _server = FluentMockServer.Start(); - - _server - .Given(Request.Create() - .WithPath("/foo") - .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] + "/foo")) - .ThrowsAny(); - } - - [Test] - public async Task Should_respond_a_redirect_without_body() - { - // given - _server = FluentMockServer.Start(); - - _server - .Given(Request.Create() - .WithPath("/foo") - .UsingGet()) - .RespondWith(Response.Create() - .WithStatusCode(307) - .WithHeader("Location", "/bar")); - _server - .Given(Request.Create() - .WithPath("/bar") - .UsingGet()) - .RespondWith(Response.Create() - .WithStatusCode(200) - .WithBody("REDIRECT SUCCESSFUL")); - - // when - var response = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo"); - - // then - Check.That(response).IsEqualTo("REDIRECT SUCCESSFUL"); - } - - [Test] - public async Task Should_delay_responses_for_a_given_route() - { - // given - _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).IsGreaterThan(200); - } - - [Test] - public async Task Should_delay_responses() - { - // given - _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).IsGreaterThan(200); - } - - [TearDown] - public void ShutdownServer() - { - _server.Stop(); - } - } -} \ No newline at end of file diff --git a/test/WireMock.Net.Tests.old/Http/TinyHttpServerTests.cs b/test/WireMock.Net.Tests.old/Http/TinyHttpServerTests.cs deleted file mode 100644 index 099dac0d..00000000 --- a/test/WireMock.Net.Tests.old/Http/TinyHttpServerTests.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using System.Net.Http; -using NFluent; -using NUnit.Framework; -using WireMock.Http; - -[module: - SuppressMessage("StyleCop.CSharp.DocumentationRules", - "SA1600:ElementsMustBeDocumented", - Justification = "Reviewed. Suppression is OK here, as it's a tests class.")] -[module: - SuppressMessage("StyleCop.CSharp.DocumentationRules", - "SA1633:FileMustHaveHeader", - Justification = "Reviewed. Suppression is OK here, as unknown copyright and company.")] - -namespace WireMock.Net.Tests.Http -{ - [TestFixture] - public class TinyHttpServerTests - { - [Test] - public void Should_call_handler_on_request() - { - // given - var port = PortUtil.FindFreeTcpPort(); - bool called = false; - var urlPrefix = "http://localhost:" + port + "/"; - var server = new TinyHttpServer(ctx => called = true, urlPrefix); - server.Start(); - - // when - var httpClient = new HttpClient(); - httpClient.GetAsync(urlPrefix).Wait(3000); - - // then - Check.That(called).IsTrue(); - } - } -} diff --git a/test/WireMock.Net.Tests.old/HttpListenerRequestMapperTests.cs b/test/WireMock.Net.Tests.old/HttpListenerRequestMapperTests.cs deleted file mode 100644 index 24d8a1b1..00000000 --- a/test/WireMock.Net.Tests.old/HttpListenerRequestMapperTests.cs +++ /dev/null @@ -1,147 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; -using NFluent; -using NUnit.Framework; -using WireMock.Http; - -namespace WireMock.Net.Tests -{ - [TestFixture] - public class HttpListenerRequestMapperTests - { - private MapperServer _server; - - [SetUp] - public void StartListenerServer() - { - _server = MapperServer.Start(); - } - - [Test] - public async Task Should_map_uri_from_listener_request() - { - // given - var client = new HttpClient(); - - // when - await client.GetAsync(MapperServer.UrlPrefix + "toto"); - - // then - Check.That(MapperServer.LastRequestMessage).IsNotNull(); - Check.That(MapperServer.LastRequestMessage.Path).IsEqualTo("/toto"); - } - - [Test] - public async Task Should_map_verb_from_listener_request() - { - // given - var client = new HttpClient(); - - // when - await client.PutAsync(MapperServer.UrlPrefix, new StringContent("Hello!")); - - // then - Check.That(MapperServer.LastRequestMessage).IsNotNull(); - Check.That(MapperServer.LastRequestMessage.Method).IsEqualTo("put"); - } - - [Test] - public async Task Should_map_body_from_listener_request() - { - // given - var client = new HttpClient(); - - // when - await client.PutAsync(MapperServer.UrlPrefix, new StringContent("Hello!")); - - // then - Check.That(MapperServer.LastRequestMessage).IsNotNull(); - Check.That(MapperServer.LastRequestMessage.Body).IsEqualTo("Hello!"); - } - - [Test] - public async Task Should_map_headers_from_listener_request() - { - // given - var client = new HttpClient(); - client.DefaultRequestHeaders.Add("X-Alex", "1706"); - - // when - await client.GetAsync(MapperServer.UrlPrefix); - - // then - Check.That(MapperServer.LastRequestMessage).IsNotNull(); - Check.That(MapperServer.LastRequestMessage.Headers).Not.IsNullOrEmpty(); - Check.That(MapperServer.LastRequestMessage.Headers.Contains(new KeyValuePair("X-Alex", "1706"))).IsTrue(); - } - - [Test] - public async Task Should_map_params_from_listener_request() - { - // given - var client = new HttpClient(); - - // when - await client.GetAsync(MapperServer.UrlPrefix + "index.html?id=toto"); - - // then - Check.That(MapperServer.LastRequestMessage).IsNotNull(); - Check.That(MapperServer.LastRequestMessage.Path).EndsWith("/index.html"); - Check.That(MapperServer.LastRequestMessage.GetParameter("id")).HasSize(1); - } - - [TearDown] - public void StopListenerServer() - { - _server.Stop(); - } - - private class MapperServer : TinyHttpServer - { - private static volatile RequestMessage _lastRequestMessage; - - private MapperServer(Action httpHandler, string urlPrefix) : base(httpHandler, urlPrefix) - { - } - - public static RequestMessage LastRequestMessage - { - get - { - return _lastRequestMessage; - } - - private set - { - _lastRequestMessage = value; - } - } - - public static string UrlPrefix { get; private set; } - - public new static MapperServer Start() - { - int port = PortUtil.FindFreeTcpPort(); - UrlPrefix = "http://localhost:" + port + "/"; - var server = new MapperServer( - context => - { - LastRequestMessage = new HttpListenerRequestMapper().Map(context.Request); - context.Response.Close(); - }, UrlPrefix); - ((TinyHttpServer)server).Start(); - - return server; - } - - public new void Stop() - { - base.Stop(); - LastRequestMessage = null; - } - } - } -} diff --git a/test/WireMock.Net.Tests.old/HttpListenerResponseMapperTests.cs b/test/WireMock.Net.Tests.old/HttpListenerResponseMapperTests.cs deleted file mode 100644 index 132e644e..00000000 --- a/test/WireMock.Net.Tests.old/HttpListenerResponseMapperTests.cs +++ /dev/null @@ -1,133 +0,0 @@ -using System.Net; -using System.Net.Http; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using NFluent; -using NUnit.Framework; -using WireMock.Http; - -namespace WireMock.Net.Tests -{ - [TestFixture] - public class HttpListenerResponseMapperTests - { - private TinyHttpServer _server; - private Task _responseMsgTask; - - [Test] - public void Should_map_status_code_from_original_response() - { - // given - var response = new ResponseMessage { StatusCode = 404 }; - var httpListenerResponse = CreateHttpListenerResponse(); - - // when - new HttpListenerResponseMapper().Map(response, httpListenerResponse); - - // then - Check.That(httpListenerResponse.StatusCode).IsEqualTo(404); - } - - [Test] - public void Should_map_headers_from_original_response() - { - // given - var response = new ResponseMessage(); - response.AddHeader("cache-control", "no-cache"); - var httpListenerResponse = CreateHttpListenerResponse(); - - // when - new HttpListenerResponseMapper().Map(response, httpListenerResponse); - - // then - Check.That(httpListenerResponse.Headers).HasSize(1); - Check.That(httpListenerResponse.Headers.Keys).Contains("cache-control"); - Check.That(httpListenerResponse.Headers.Get("cache-control")).Contains("no-cache"); - } - - [Test] - public void Should_map_body_from_original_response() - { - // given - var response = new ResponseMessage - { - Body = "Hello !!!" - }; - - var httpListenerResponse = CreateHttpListenerResponse(); - - // when - new HttpListenerResponseMapper().Map(response, httpListenerResponse); - - // then - var responseMessage = ToResponseMessage(httpListenerResponse); - Check.That(responseMessage).IsNotNull(); - - var contentTask = responseMessage.Content.ReadAsStringAsync(); - Check.That(contentTask.Result).IsEqualTo("Hello !!!"); - } - - [Test] - public void Should_map_encoded_body_from_original_response() - { - // given - var response = new ResponseMessage - { - Body = "Hello !!!", - BodyEncoding = Encoding.ASCII - }; - - var httpListenerResponse = CreateHttpListenerResponse(); - - // when - new HttpListenerResponseMapper().Map(response, httpListenerResponse); - - // then - Check.That(httpListenerResponse.ContentEncoding).Equals(Encoding.ASCII); - - var responseMessage = ToResponseMessage(httpListenerResponse); - Check.That(responseMessage).IsNotNull(); - - var contentTask = responseMessage.Content.ReadAsStringAsync(); - Check.That(contentTask.Result).IsEqualTo("Hello !!!"); - } - - [TearDown] - public void StopServer() - { - _server?.Stop(); - } - - /// - /// Dirty HACK to get HttpListenerResponse instances - /// - /// - /// The . - /// - public HttpListenerResponse CreateHttpListenerResponse() - { - var port = PortUtil.FindFreeTcpPort(); - var urlPrefix = "http://localhost:" + port + "/"; - var responseReady = new AutoResetEvent(false); - HttpListenerResponse response = null; - _server = new TinyHttpServer( - context => - { - response = context.Response; - responseReady.Set(); - }, urlPrefix); - _server.Start(); - _responseMsgTask = new HttpClient().GetAsync(urlPrefix); - responseReady.WaitOne(); - return response; - } - - public HttpResponseMessage ToResponseMessage(HttpListenerResponse listenerResponse) - { - listenerResponse.Close(); - _responseMsgTask.Wait(); - return _responseMsgTask.Result; - } - } -} diff --git a/test/WireMock.Net.Tests.old/RequestMessageTests.cs b/test/WireMock.Net.Tests.old/RequestMessageTests.cs deleted file mode 100644 index 26b61236..00000000 --- a/test/WireMock.Net.Tests.old/RequestMessageTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Text; -using NFluent; -using NUnit.Framework; - -namespace WireMock.Net.Tests -{ - [TestFixture] - public class RequestMessageTests - { - [Test] - public void Should_handle_empty_query() - { - // given - var request = new RequestMessage(new Uri("http://localhost/foo"), "POST"); - - // then - Check.That(request.GetParameter("not_there")).IsNull(); - } - - [Test] - public void Should_parse_query_params() - { - // given - string bodyAsString = "whatever"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost?foo=bar&multi=1&multi=2"), "POST", body, bodyAsString, Encoding.UTF8); - - // then - Check.That(request.GetParameter("foo")).Contains("bar"); - Check.That(request.GetParameter("multi")).Contains("1"); - Check.That(request.GetParameter("multi")).Contains("2"); - } - } -} diff --git a/test/WireMock.Net.Tests.old/RequestTests.cs b/test/WireMock.Net.Tests.old/RequestTests.cs deleted file mode 100644 index 033a6a9d..00000000 --- a/test/WireMock.Net.Tests.old/RequestTests.cs +++ /dev/null @@ -1,550 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using NFluent; -using NUnit.Framework; -using WireMock.RequestBuilders; -using WireMock.Matchers; -using WireMock.Matchers.Request; - -namespace WireMock.Net.Tests -{ - [TestFixture] - public class RequestTests - { - [Test] - public void Should_specify_requests_matching_given_path() - { - // given - var spec = Request.Create().WithPath("/foo"); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo"), "blabla"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_paths() - { - var requestBuilder = Request.Create().WithPath("/x1", "/x2"); - - var request1 = new RequestMessage(new Uri("http://localhost/x1"), "blabla"); - var request2 = new RequestMessage(new Uri("http://localhost/x2"), "blabla"); - - var requestMatchResult = new RequestMatchResult(); - Check.That(requestBuilder.GetMatchingScore(request1, requestMatchResult)).IsEqualTo(1.0); - Check.That(requestBuilder.GetMatchingScore(request2, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_pathFuncs() - { - // given - var spec = Request.Create().WithPath(url => url.EndsWith("/foo")); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo"), "blabla"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_path_prefix() - { - // given - var spec = Request.Create().WithPath(new RegexMatcher("^/foo")); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo/bar"), "blabla"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_exclude_requests_not_matching_given_path() - { - // given - var spec = Request.Create().WithPath("/foo"); - - // when - var request = new RequestMessage(new Uri("http://localhost/bar"), "blabla"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_url() - { - // given - var spec = Request.Create().WithUrl("*/foo"); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo"), "blabla"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_path_and_method_put() - { - // given - var spec = Request.Create().WithPath("/foo").UsingPut(); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_path_and_method_post() - { - // given - var spec = Request.Create().WithPath("/foo").UsingPost(); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo"), "POST"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_path_and_method_get() - { - // given - var spec = Request.Create().WithPath("/foo").UsingGet(); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo"), "GET"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_path_and_method_delete() - { - // given - var spec = Request.Create().WithPath("/foo").UsingDelete(); - - // when - string bodyAsString = "whatever"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "Delete", body, bodyAsString, Encoding.UTF8); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_path_and_method_head() - { - // given - var spec = Request.Create().WithPath("/foo").UsingHead(); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo"), "HEAD"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_exclude_requests_matching_given_path_but_not_http_method() - { - // given - var spec = Request.Create().WithPath("/foo").UsingPut(); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo"), "HEAD"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0); - } - - [Test] - public void Should_exclude_requests_matching_given_http_method_but_not_url() - { - // given - var spec = Request.Create().WithPath("/bar").UsingPut(); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_path_and_headers() - { - // given - var spec = Request.Create().WithPath("/foo").UsingAnyVerb().WithHeader("X-toto", "tata"); - - // when - string bodyAsString = "whatever"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8, new Dictionary { { "X-toto", "tata" } }); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_exclude_requests_not_matching_given_headers() - { - // given - var spec = Request.Create().UsingAnyVerb().WithHeader("X-toto", "tatata"); - - // when - string bodyAsString = "whatever"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8, new Dictionary { { "X-toto", "tata" } }); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0); - } - - [Test] - public void Should_exclude_requests_not_matching_given_headers_ignorecase() - { - // given - var spec = Request.Create().UsingAnyVerb().WithHeader("X-toto", "abc", false); - - // when - string bodyAsString = "whatever"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8, new Dictionary { { "X-toto", "ABC" } }); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_header_prefix() - { - // given - var spec = Request.Create().UsingAnyVerb().WithHeader("X-toto", "tata*"); - - // when - string bodyAsString = "whatever"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8, new Dictionary { { "X-toto", "TaTa" } }); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_cookies() - { - // given - var spec = Request.Create().UsingAnyVerb().WithCookie("session", "a*"); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", null, null, null, null, new Dictionary { { "session", "abc" } }); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_body() - { - // given - var spec = Request.Create().UsingAnyVerb().WithBody("Hello world!"); - - // when - string bodyAsString = "Hello world!"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_body_using_ExactMatcher_true() - { - // given - var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new ExactMatcher("cat")); - - // when - string bodyAsString = "cat"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_body_using_ExactMatcher_multiplePatterns() - { - // given - var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new ExactMatcher("cat", "dog")); - - // when - string bodyAsString = "cat"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsEqualTo(0.5); - } - - [Test] - public void Should_specify_requests_matching_given_body_using_ExactMatcher_false() - { - // given - var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new ExactMatcher("cat")); - - // when - string bodyAsString = "caR"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsLessThan(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_body_using_SimMetricsMatcher1() - { - // given - var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new SimMetricsMatcher("The cat walks in the street.")); - - // when - string bodyAsString = "The car drives in the street."; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsLessThan(1.0).And.IsGreaterThan(0.5); - } - - [Test] - public void Should_specify_requests_matching_given_body_using_SimMetricsMatcher2() - { - // given - var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new SimMetricsMatcher("The cat walks in the street.")); - - // when - string bodyAsString = "Hello"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsLessThan(0.1).And.IsGreaterThan(0.05); - } - - [Test] - public void Should_specify_requests_matching_given_body_using_WildcardMatcher() - { - // given - var spec = Request.Create().WithPath("/foo").UsingAnyVerb().WithBody(new WildcardMatcher("H*o*")); - - // when - string bodyAsString = "Hello world!"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8, new Dictionary { { "X-toto", "tatata" } }); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_body_using_RegexMatcher() - { - // given - var spec = Request.Create().UsingAnyVerb().WithBody(new RegexMatcher("H.*o")); - - // when - string bodyAsString = "Hello world!"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_body_using_XPathMatcher_true() - { - // given - var spec = Request.Create().UsingAnyVerb().WithBody(new XPathMatcher("/todo-list[count(todo-item) = 3]")); - - // when - string xmlBodyAsString = @" - - abc - def - xyz - "; - byte[] body = Encoding.UTF8.GetBytes(xmlBodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, xmlBodyAsString, Encoding.UTF8); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_body_using_XPathMatcher_false() - { - // given - var spec = Request.Create().UsingAnyVerb().WithBody(new XPathMatcher("/todo-list[count(todo-item) = 99]")); - - // when - string xmlBodyAsString = @" - - abc - def - xyz - "; - byte[] body = Encoding.UTF8.GetBytes(xmlBodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, xmlBodyAsString, Encoding.UTF8); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_body_using_JsonPathMatcher_true() - { - // given - var spec = Request.Create().UsingAnyVerb().WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]")); - - // when - string bodyAsString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_body_using_JsonPathMatcher_false() - { - // given - var spec = Request.Create().UsingAnyVerb().WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]")); - - // when - string bodyAsString = "{ \"things\": { \"name\": \"Wiremock\" } }"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0); - } - - [Test] - public void Should_exclude_requests_not_matching_given_body() - { - // given - var spec = Request.Create().UsingAnyVerb().WithBody(" Hello world! "); - - // when - string bodyAsString = "xxx"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8, new Dictionary { { "X-toto", "tatata" } }); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_param() - { - // given - var spec = Request.Create().WithParam("bar", "1", "2"); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo?bar=1&bar=2"), "PUT"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_paramNoValue() - { - // given - var spec = Request.Create().WithParam("bar"); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo?bar"), "PUT"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_specify_requests_matching_given_param_func() - { - // given - var spec = Request.Create().UsingAnyVerb().WithParam(p => p.ContainsKey("bar")); - - // when - var request = new RequestMessage(new Uri("http://localhost/foo?bar=1&bar=2"), "PUT"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); - } - - [Test] - public void Should_exclude_requests_not_matching_given_params() - { - // given - var spec = Request.Create().WithParam("bar", "1"); - - // when - var request = new RequestMessage(new Uri("http://localhost/test=7"), "PUT"); - - // then - var requestMatchResult = new RequestMatchResult(); - Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0); - } - } -} \ No newline at end of file diff --git a/test/WireMock.Net.Tests.old/ResponseTests.cs b/test/WireMock.Net.Tests.old/ResponseTests.cs deleted file mode 100644 index a0b7bd44..00000000 --- a/test/WireMock.Net.Tests.old/ResponseTests.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using NFluent; -using NUnit.Framework; -using WireMock.ResponseBuilders; - -namespace WireMock.Net.Tests -{ - [TestFixture] - public class ResponseTests - { - [Test] - public async Task Response_ProvideResponse_Handlebars_UrlPathVerb() - { - // given - string bodyAsString = "abc"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8); - - var response = Response.Create() - .WithBody("test {{request.url}} {{request.path}} {{request.method}}") - .WithTransformer(); - - // act - var responseMessage = await response.ProvideResponse(request); - - // then - Check.That(responseMessage.Body).Equals("test http://localhost/foo /foo post"); - } - - [Test] - public async Task Response_ProvideResponse_Handlebars_Query() - { - // given - string bodyAsString = "abc"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo?a=1&a=2&b=5"), "POST", body, bodyAsString, Encoding.UTF8); - - var response = Response.Create() - .WithBody("test keya={{request.query.a}} idx={{request.query.a.[0]}} idx={{request.query.a.[1]}} keyb={{request.query.b}}") - .WithTransformer(); - - // act - var responseMessage = await response.ProvideResponse(request); - - // then - Check.That(responseMessage.Body).Equals("test keya=1 idx=1 idx=2 keyb=5"); - } - - [Test] - public async Task Response_ProvideResponse_Handlebars_Headers() - { - // given - string bodyAsString = "abc"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8, new Dictionary { { "Content-Type", "text/plain" } }); - - var response = Response.Create().WithHeader("x", "{{request.headers.Content-Type}}").WithBody("test").WithTransformer(); - - // act - var responseMessage = await response.ProvideResponse(request); - - // then - Check.That(responseMessage.Body).Equals("test"); - Check.That(responseMessage.Headers).Contains(new KeyValuePair("x", "text/plain")); - } - - [Test] - public async Task Response_ProvideResponse_Encoding_Body() - { - // given - string bodyAsString = "abc"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8); - - var response = Response.Create().WithBody("test", Encoding.ASCII); - - // act - var responseMessage = await response.ProvideResponse(request); - - // then - Check.That(responseMessage.Body).Equals("test"); - Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII); - } - - [Test] - public async Task Response_ProvideResponse_Encoding_JsonBody() - { - // given - string bodyAsString = "abc"; - byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8); - - var response = Response.Create().WithBodyAsJson(new { value = "test" }, Encoding.ASCII); - - // act - var responseMessage = await response.ProvideResponse(request); - - // then - Check.That(responseMessage.Body).Equals("{\"value\":\"test\"}"); - Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII); - } - } -} \ No newline at end of file diff --git a/test/WireMock.Net.Tests.old/WildcardMatcherTest.cs b/test/WireMock.Net.Tests.old/WildcardMatcherTest.cs deleted file mode 100644 index 4d8ccc7d..00000000 --- a/test/WireMock.Net.Tests.old/WildcardMatcherTest.cs +++ /dev/null @@ -1,59 +0,0 @@ -using NUnit.Framework; -using WireMock.Matchers; - -namespace WireMock.Net.Tests -{ - [TestFixture] - public class WildcardMatcherTest - { - [Test] - public void WildcardMatcher_patterns_positive() - { - var tests = new[] - { - new { p = "*", i = "" }, - new { p = "?", i = " " }, - new { p = "*", i = "a" }, - new { p = "*", i = "ab" }, - new { p = "?", i = "a" }, - new { p = "*?", i = "abc" }, - new { p = "?*", i = "abc" }, - new { p = "abc", i = "abc" }, - new { p = "abc*", i = "abc" }, - new { p = "abc*", i = "abcd" }, - new { p = "*abc*", i = "abc" }, - new { p = "*a*bc*", i = "abc" }, - new { p = "*a*b?", i = "aXXXbc" } - }; - foreach (var test in tests) - { - var matcher = new WildcardMatcher(test.p); - Assert.AreEqual(1.0, matcher.IsMatch(test.i), "p = " + test.p + ", i = " + test.i); - } - } - - [Test] - public void WildcardMatcher_patterns_negative() - { - var tests = new[] - { - new { p = "*a", i = ""}, - new { p = "a*", i = ""}, - new { p = "?", i = ""}, - new { p = "*b*", i = "a"}, - new { p = "b*a", i = "ab"}, - new { p = "??", i = "a"}, - new { p = "*?", i = ""}, - new { p = "??*", i = "a"}, - new { p = "*abc", i = "abX"}, - new { p = "*abc*", i = "Xbc"}, - new { p = "*a*bc*", i = "ac"} - }; - foreach (var test in tests) - { - var matcher = new WildcardMatcher(test.p); - Assert.AreEqual(0.0, matcher.IsMatch(test.i), "p = " + test.p + ", i = " + test.i); - } - } - } -} \ No newline at end of file diff --git a/test/WireMock.Net.Tests.old/WireMock.Net.Tests.csproj b/test/WireMock.Net.Tests.old/WireMock.Net.Tests.csproj deleted file mode 100644 index 24f3de77..00000000 --- a/test/WireMock.Net.Tests.old/WireMock.Net.Tests.csproj +++ /dev/null @@ -1,90 +0,0 @@ - - - - - Debug - AnyCPU - {D8B56D28-33CE-4BEF-97D4-7DD546E37F25} - Library - Properties - WireMock.Net.Tests - WireMock.Net.Tests - v4.5.2 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\packages\Castle.Core.3.3.3\lib\net45\Castle.Core.dll - True - - - ..\..\packages\Moq.4.5.30\lib\net45\Moq.dll - True - - - ..\..\packages\NFluent.1.3.1.0\lib\net40\NFluent.dll - True - - - ..\..\packages\NUnit.3.6.0\lib\net45\nunit.framework.dll - True - - - ..\..\packages\SimMetrics.Net.1.0.1.0\lib\net45\SimMetrics.Net.dll - True - - - - - - - - - - - ..\..\src\WireMock.Net\bin\$(Configuration)\net45\WireMock.Net.dll - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/WireMock.Net.Tests.old/packages.config b/test/WireMock.Net.Tests.old/packages.config deleted file mode 100644 index bf055c2f..00000000 --- a/test/WireMock.Net.Tests.old/packages.config +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/test/WireMock.Net.Tests/ClientTests.cs b/test/WireMock.Net.Tests/ClientTests.cs index cd6b830f..91295be3 100644 --- a/test/WireMock.Net.Tests/ClientTests.cs +++ b/test/WireMock.Net.Tests/ClientTests.cs @@ -9,8 +9,21 @@ using Xunit; namespace WireMock.Net.Tests { + // TODO : move these to FluentMockServerAdminRestClientTests public class ClientTests { + [Fact] + public async Task Client_IFluentMockServerAdmin_SettingsGet() + { + // Assign + 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 Client_IFluentMockServerAdmin_PostMappingAsync() { diff --git a/test/WireMock.Net.Tests/FluentMockServerAdminRestClientTests.cs b/test/WireMock.Net.Tests/FluentMockServerAdminRestClientTests.cs index 71d6be87..cb4dd967 100644 --- a/test/WireMock.Net.Tests/FluentMockServerAdminRestClientTests.cs +++ b/test/WireMock.Net.Tests/FluentMockServerAdminRestClientTests.cs @@ -13,21 +13,14 @@ using Xunit; namespace WireMock.Net.Tests { - public class FluentMockServerAdminRestClientTests : IDisposable + public class FluentMockServerAdminRestClientTests { - public void Dispose() - { - _server?.Stop(); - } - - private FluentMockServer _server; - [Fact] public async Task IFluentMockServerAdmin_FindRequestsAsync() { // given - _server = FluentMockServer.Start(new FluentMockServerSettings { StartAdminInterface = true, Logger = new WireMockNullLogger() }); - var serverUrl = "http://localhost:" + _server.Ports[0]; + 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); @@ -46,8 +39,8 @@ namespace WireMock.Net.Tests public async Task IFluentMockServerAdmin_GetRequestsAsync() { // given - _server = FluentMockServer.Start(new FluentMockServerSettings { StartAdminInterface = true, Logger = new WireMockNullLogger() }); - var serverUrl = "http://localhost:" + _server.Ports[0]; + 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); diff --git a/test/WireMock.Net.Tests/FluentMockServerTests.Admin.cs b/test/WireMock.Net.Tests/FluentMockServerTests.Admin.cs new file mode 100644 index 00000000..0ff582d1 --- /dev/null +++ b/test/WireMock.Net.Tests/FluentMockServerTests.Admin.cs @@ -0,0 +1,314 @@ +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.RequestBuilders; +using WireMock.ResponseBuilders; +using WireMock.Server; +using WireMock.Settings; +using Xunit; + +namespace WireMock.Net.Tests +{ + public class FluentMockServerAdminTests + { + // For for AppVeyor + OpenCover + private string GetCurrentFolder() + { + string current = Directory.GetCurrentDirectory(); + //if (!current.EndsWith("WireMock.Net.Tests")) + // return Path.Combine(current, "test", "WireMock.Net.Tests"); + + return current; + } + + [Fact] + public void FluentMockServer_Admin_StartStop() + { + var server1 = FluentMockServer.Start("http://localhost:9091"); + + Check.That(server1.Urls[0]).Equals("http://localhost:9091"); + + server1.Stop(); + + var server2 = FluentMockServer.Start("http://localhost:9091/"); + + Check.That(server2.Urls[0]).Equals("http://localhost:9091/"); + + server2.Stop(); + } + + [Fact] + public void FluentMockServer_Admin_SaveStaticMappings() + { + // Assign + string guid = "791a3f31-6946-aaaa-8e6f-0237c7441111"; + var staticMappingHandlerMock = new Mock(); + staticMappingHandlerMock.Setup(m => m.GetMappingFolder()).Returns("folder"); + staticMappingHandlerMock.Setup(m => m.FolderExists(It.IsAny())).Returns(true); + staticMappingHandlerMock.Setup(m => m.WriteMappingFile(It.IsAny(), It.IsAny())); + + var _server = FluentMockServer.Start(new FluentMockServerSettings + { + FileSystemHandler = staticMappingHandlerMock.Object + }); + + _server + .Given(Request.Create().WithPath($"/foo_{Guid.NewGuid()}")) + .WithGuid(guid) + .RespondWith(Response.Create().WithBody("save test")); + + // Act + _server.SaveStaticMappings(); + + // Assert and Verify + staticMappingHandlerMock.Verify(m => m.GetMappingFolder(), Times.Once); + staticMappingHandlerMock.Verify(m => m.FolderExists("folder"), Times.Once); + staticMappingHandlerMock.Verify(m => m.WriteMappingFile(Path.Combine("folder", guid + ".json"), It.IsAny()), Times.Once); + } + + [Fact] + public void FluentMockServer_Admin_ReadStaticMapping_WithNonGuidFilename() + { + var guid = Guid.Parse("04ee4872-9efd-4770-90d3-88d445265d0d"); + string title = "documentdb_root_title"; + + var _server = FluentMockServer.Start(); + + string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "documentdb_root.json"); + _server.ReadStaticMappingAndAddOrUpdate(folder); + + var mappings = _server.Mappings.ToArray(); + Check.That(mappings).HasSize(1); + + Check.That(mappings.First().RequestMatcher).IsNotNull(); + Check.That(mappings.First().Provider).IsNotNull(); + Check.That(mappings.First().Guid).Equals(guid); + Check.That(mappings.First().Title).Equals(title); + } + + [Fact] + public void FluentMockServer_Admin_ReadStaticMapping_WithGuidFilename() + { + string guid = "00000002-ee28-4f29-ae63-1ac9b0802d86"; + + var _server = FluentMockServer.Start(); + string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json"); + _server.ReadStaticMappingAndAddOrUpdate(folder); + + var mappings = _server.Mappings.ToArray(); + Check.That(mappings).HasSize(1); + + Check.That(mappings.First().RequestMatcher).IsNotNull(); + Check.That(mappings.First().Provider).IsNotNull(); + Check.That(mappings.First().Guid).Equals(Guid.Parse(guid)); + Check.That(mappings.First().Title).IsNullOrEmpty(); + } + + [Fact] + public void FluentMockServer_Admin_ReadStaticMapping_WithResponseBodyFromFile() + { + string guid = "00000002-ee28-4f29-ae63-1ac9b0802d87"; + + string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json"); + string json = File.ReadAllText(folder); + + string responseBodyFilePath = Path.Combine(GetCurrentFolder(), "responsebody.json"); + + dynamic jsonObj = JsonConvert.DeserializeObject(json); + jsonObj["Response"]["BodyAsFile"] = responseBodyFilePath; + + string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented); + File.WriteAllText(folder, output); + + var _server = FluentMockServer.Start(); + _server.ReadStaticMappingAndAddOrUpdate(folder); + + var mappings = _server.Mappings.ToArray(); + Check.That(mappings).HasSize(1); + + Check.That(mappings.First().RequestMatcher).IsNotNull(); + Check.That(mappings.First().Provider).IsNotNull(); + Check.That(mappings.First().Guid).Equals(Guid.Parse(guid)); + Check.That(mappings.First().Title).IsNullOrEmpty(); + } + + [Fact] + public void FluentMockServer_Admin_ReadStaticMappings_FolderExistsIsTrue() + { + // Assign + var staticMappingHandlerMock = new Mock(); + staticMappingHandlerMock.Setup(m => m.GetMappingFolder()).Returns("folder"); + staticMappingHandlerMock.Setup(m => m.FolderExists(It.IsAny())).Returns(true); + staticMappingHandlerMock.Setup(m => m.EnumerateFiles(It.IsAny())).Returns(new string[0]); + + var _server = FluentMockServer.Start(new FluentMockServerSettings + { + FileSystemHandler = staticMappingHandlerMock.Object + }); + + // Act + _server.ReadStaticMappings(); + + // Assert and Verify + staticMappingHandlerMock.Verify(m => m.GetMappingFolder(), Times.Once); + staticMappingHandlerMock.Verify(m => m.FolderExists("folder"), Times.Once); + staticMappingHandlerMock.Verify(m => m.EnumerateFiles("folder"), Times.Once); + } + + [Fact] + public void FluentMockServer_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 + { + FileSystemHandler = _staticMappingHandlerMock.Object + }); + + // Act + _server.ReadStaticMappingAndAddOrUpdate(@"c:\test.json"); + + // Assert and Verify + _staticMappingHandlerMock.Verify(m => m.ReadMappingFile(@"c:\test.json"), Times.Once); + } + + [Fact] + public void FluentMockServer_Admin_ReadStaticMappings() + { + var _server = FluentMockServer.Start(); + + string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings"); + _server.ReadStaticMappings(folder); + + var mappings = _server.Mappings.ToArray(); + Check.That(mappings).HasSize(3); + } + + [Fact] + public void FluentMockServer_Admin_Mappings_WithGuid_Get() + { + Guid guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05"); + var _server = FluentMockServer.Start(); + + _server.Given(Request.Create().WithPath("/foo1").UsingGet()).WithGuid(guid) + .RespondWith(Response.Create().WithStatusCode(201).WithBody("1")); + + _server.Given(Request.Create().WithPath("/foo2").UsingGet()) + .RespondWith(Response.Create().WithStatusCode(202).WithBody("2")); + + var mappings = _server.Mappings.ToArray(); + Check.That(mappings).HasSize(2); + } + + [Fact] + public void FluentMockServer_Admin_Mappings_WithGuidAsString_Get() + { + string guid = "90356dba-b36c-469a-a17e-669cd84f1f05"; + var _server = FluentMockServer.Start(); + + _server.Given(Request.Create().WithPath("/foo100").UsingGet()).WithGuid(guid) + .RespondWith(Response.Create().WithStatusCode(201).WithBody("1")); + + var mappings = _server.Mappings.ToArray(); + Check.That(mappings).HasSize(1); + } + + [Fact] + public void FluentMockServer_Admin_Mappings_Add_SameGuid() + { + var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05"); + var _server = FluentMockServer.Start(); + + var response1 = Response.Create().WithStatusCode(500); + _server.Given(Request.Create().UsingGet()) + .WithGuid(guid) + .RespondWith(response1); + + var mappings1 = _server.Mappings.ToArray(); + Check.That(mappings1).HasSize(1); + Check.That(mappings1.First().Guid).Equals(guid); + + var response2 = Response.Create().WithStatusCode(400); + _server.Given(Request.Create().WithPath("/2").UsingGet()) + .WithGuid(guid) + .RespondWith(response2); + + var mappings2 = _server.Mappings.ToArray(); + Check.That(mappings2).HasSize(1); + Check.That(mappings2.First().Guid).Equals(guid); + Check.That(mappings2.First().Provider).Equals(response2); + } + + [Fact] + public async Task FluentMockServer_Admin_Mappings_AtPriority() + { + var _server = FluentMockServer.Start(); + + // given + _server.Given(Request.Create().WithPath("/1").UsingGet()) + .AtPriority(2) + .RespondWith(Response.Create().WithStatusCode(200)); + + _server.Given(Request.Create().WithPath("/1").UsingGet()) + .AtPriority(1) + .RespondWith(Response.Create().WithStatusCode(400)); + + var mappings = _server.Mappings.ToArray(); + Check.That(mappings).HasSize(2); + + // when + var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/1"); + + // then + Check.That((int)response.StatusCode).IsEqualTo(400); + } + + [Fact] + public async Task FluentMockServer_Admin_Requests_Get() + { + // given + var _server = FluentMockServer.Start(); + + // when + await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo"); + + // then + Check.That(_server.LogEntries).HasSize(1); + var requestLogged = _server.LogEntries.First(); + Check.That(requestLogged.RequestMessage.Method).IsEqualTo("get"); + Check.That(requestLogged.RequestMessage.BodyAsBytes).IsNull(); + } + + [Fact] + public async Task FluentMockServer_Admin_Logging_SetMaxRequestLogCount() + { + // Assign + var client = new HttpClient(); + // Act + var _server = FluentMockServer.Start(); + _server.SetMaxRequestLogCount(2); + + await client.GetAsync("http://localhost:" + _server.Ports[0] + "/foo1"); + await client.GetAsync("http://localhost:" + _server.Ports[0] + "/foo2"); + await client.GetAsync("http://localhost:" + _server.Ports[0] + "/foo3"); + + // Assert + Check.That(_server.LogEntries).HasSize(2); + + var requestLoggedA = _server.LogEntries.First(); + Check.That(requestLoggedA.RequestMessage.Path).EndsWith("/foo2"); + + var requestLoggedB = _server.LogEntries.Last(); + Check.That(requestLoggedB.RequestMessage.Path).EndsWith("/foo3"); + } + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/FluentMockServerTests.Proxy.cs b/test/WireMock.Net.Tests/FluentMockServerTests.Proxy.cs index a3a8b019..b01e1f9e 100644 --- a/test/WireMock.Net.Tests/FluentMockServerTests.Proxy.cs +++ b/test/WireMock.Net.Tests/FluentMockServerTests.Proxy.cs @@ -1,10 +1,10 @@ -using System; +using NFluent; +using System; using System.Linq; 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; @@ -13,52 +13,60 @@ using Xunit; namespace WireMock.Net.Tests { - public partial class FluentMockServerTests + public class FluentMockServerProxyTests { - private FluentMockServer _serverForProxyForwarding; - +#if NET452 [Fact] public async Task FluentMockServer_Proxy_Should_proxy_responses() { - // given - _server = FluentMockServer.Start(); - _server - .Given(Request.Create().WithPath("/*")) + // Assign + string path = $"/prx_{Guid.NewGuid().ToString()}"; + var server = FluentMockServer.Start(); + server + .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create().WithProxy("http://www.google.com")); - // when - var result = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/search?q=test"); + // Act + var requestMessage = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri($"{server.Urls[0]}{path}") + }; + var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false }; + var response = await new HttpClient(httpClientHandler).SendAsync(requestMessage); + string content = await response.Content.ReadAsStringAsync(); - // then - Check.That(_server.Mappings).HasSize(1); - Check.That(result).Contains("google"); + // Assert + Check.That(server.Mappings).HasSize(1); + Check.That(content).Contains("google"); } [Fact] public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxied_request() { - // given - _serverForProxyForwarding = FluentMockServer.Start(); - _serverForProxyForwarding - .Given(Request.Create().WithPath("/*")) + // Assign + string path = $"/prx_{Guid.NewGuid().ToString()}"; + var serverForProxyForwarding = FluentMockServer.Start(); + serverForProxyForwarding + .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create()); var settings = new FluentMockServerSettings { ProxyAndRecordSettings = new ProxyAndRecordSettings { - Url = _serverForProxyForwarding.Urls[0], + Url = serverForProxyForwarding.Urls[0], SaveMapping = true, SaveMappingToFile = false } }; - _server = FluentMockServer.Start(settings); + var server = FluentMockServer.Start(settings); // when var requestMessage = new HttpRequestMessage { Method = HttpMethod.Post, - RequestUri = new Uri(_server.Urls[0]), + RequestUri = new Uri($"{server.Urls[0]}{path}"), Content = new StringContent("stringContent") }; requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); @@ -66,14 +74,14 @@ namespace WireMock.Net.Tests await new HttpClient().SendAsync(requestMessage); // then - var receivedRequest = _serverForProxyForwarding.LogEntries.First().RequestMessage; + var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage; Check.That(receivedRequest.Body).IsEqualTo("stringContent"); Check.That(receivedRequest.Headers).ContainsKey("Content-Type"); Check.That(receivedRequest.Headers["Content-Type"].First()).Contains("text/plain"); Check.That(receivedRequest.Headers).ContainsKey("bbb"); // check that new proxied mapping is added - Check.That(_server.Mappings).HasSize(2); + Check.That(server.Mappings).HasSize(2); //var newMapping = _server.Mappings.First(m => m.Guid != guid); //var matcher = ((Request)newMapping.RequestMatcher).GetRequestMessageMatchers().FirstOrDefault(m => m.Name == "bbb"); @@ -84,31 +92,29 @@ namespace WireMock.Net.Tests public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_content_header_in_mapping() { // given - _serverForProxyForwarding = FluentMockServer.Start(); - _serverForProxyForwarding - .Given(Request.Create().WithPath("/*")) + string path = $"/prx_{Guid.NewGuid().ToString()}"; + var serverForProxyForwarding = FluentMockServer.Start(); + serverForProxyForwarding + .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create()); var settings = new FluentMockServerSettings { ProxyAndRecordSettings = new ProxyAndRecordSettings { - Url = _serverForProxyForwarding.Urls[0], + Url = serverForProxyForwarding.Urls[0], SaveMapping = true, SaveMappingToFile = false, BlackListedHeaders = new[] { "blacklisted" } } }; - _server = FluentMockServer.Start(settings); - //_server - // .Given(Request.Create().WithPath("/*")) - // .RespondWith(Response.Create()); + var server = FluentMockServer.Start(settings); // when var requestMessage = new HttpRequestMessage { Method = HttpMethod.Post, - RequestUri = new Uri(_server.Urls[0]), + RequestUri = new Uri($"{server.Urls[0]}{path}"), Content = new StringContent("stringContent") }; requestMessage.Headers.Add("blacklisted", "test"); @@ -116,7 +122,7 @@ namespace WireMock.Net.Tests await new HttpClient().SendAsync(requestMessage); // then - var receivedRequest = _serverForProxyForwarding.LogEntries.First().RequestMessage; + var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage; Check.That(receivedRequest.Headers).Not.ContainsKey("bbb"); Check.That(receivedRequest.Headers).ContainsKey("ok"); @@ -128,29 +134,30 @@ namespace WireMock.Net.Tests [Fact] public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxied_request_with_empty_content() { - // given - _serverForProxyForwarding = FluentMockServer.Start(); - _serverForProxyForwarding - .Given(Request.Create().WithPath("/*")) + // Assign + string path = $"/prx_{Guid.NewGuid().ToString()}"; + var serverForProxyForwarding = FluentMockServer.Start(); + serverForProxyForwarding + .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create()); - _server = FluentMockServer.Start(); - _server + var server = FluentMockServer.Start(); + server .Given(Request.Create().WithPath("/*")) - .RespondWith(Response.Create().WithProxy(_serverForProxyForwarding.Urls[0])); + .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0])); - // when + // Act var requestMessage = new HttpRequestMessage { Method = HttpMethod.Post, - RequestUri = new Uri(_server.Urls[0]), + RequestUri = new Uri($"{server.Urls[0]}{path}"), Content = new StringContent("") }; requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); await new HttpClient().SendAsync(requestMessage); - // then - var receivedRequest = _serverForProxyForwarding.LogEntries.First().RequestMessage; + // Assert + var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage; Check.That(receivedRequest.Body).IsEqualTo(""); Check.That(receivedRequest.Headers).ContainsKey("Content-Type"); Check.That(receivedRequest.Headers["Content-Type"].First()).Contains("text/plain"); @@ -159,28 +166,29 @@ namespace WireMock.Net.Tests [Fact] public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxied_response() { - // given - _serverForProxyForwarding = FluentMockServer.Start(); - _serverForProxyForwarding - .Given(Request.Create().WithPath("/*")) + // Assign + string path = $"/prx_{Guid.NewGuid().ToString()}"; + var serverForProxyForwarding = FluentMockServer.Start(); + serverForProxyForwarding + .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create() .WithBody("body") .WithHeader("Content-Type", "text/plain")); - _server = FluentMockServer.Start(); - _server - .Given(Request.Create().WithPath("/*")) - .RespondWith(Response.Create().WithProxy(_serverForProxyForwarding.Urls[0])); + var server = FluentMockServer.Start(); + server + .Given(Request.Create().WithPath(path)) + .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0])); - // when + // Act var requestMessage = new HttpRequestMessage { Method = HttpMethod.Get, - RequestUri = new Uri(_server.Urls[0]) + RequestUri = new Uri($"{server.Urls[0]}{path}") }; var response = await new HttpClient().SendAsync(requestMessage); - // then + // Assert Check.That(await response.Content.ReadAsStringAsync()).IsEqualTo("body"); Check.That(response.Content.Headers.Contains("Content-Type")).IsTrue(); Check.That(response.Content.Headers.GetValues("Content-Type")).ContainsExactly("text/plain"); @@ -190,49 +198,52 @@ namespace WireMock.Net.Tests public async Task FluentMockServer_Proxy_Should_change_absolute_location_header_in_proxied_response() { // Assign + string path = $"/prx_{Guid.NewGuid().ToString()}"; var settings = new FluentMockServerSettings { AllowPartialMapping = false }; - _serverForProxyForwarding = FluentMockServer.Start(settings); - _serverForProxyForwarding - .Given(Request.Create().WithPath("/*")) + + var serverForProxyForwarding = FluentMockServer.Start(settings); + serverForProxyForwarding + .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create() .WithStatusCode(HttpStatusCode.Redirect) - .WithHeader("Location", _serverForProxyForwarding.Urls[0] + "testpath")); + .WithHeader("Location", "/testpath")); - _server = FluentMockServer.Start(settings); - _server - .Given(Request.Create().WithPath("/prx")) - .RespondWith(Response.Create().WithProxy(_serverForProxyForwarding.Urls[0])); + var server = FluentMockServer.Start(settings); + server + .Given(Request.Create().WithPath(path).UsingAnyMethod()) + .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0])); // Act var requestMessage = new HttpRequestMessage { Method = HttpMethod.Get, - RequestUri = new Uri(_server.Urls[0] + "/prx") + RequestUri = new Uri($"{server.Urls[0]}{path}") }; var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false }; var response = await new HttpClient(httpClientHandler).SendAsync(requestMessage); // Assert Check.That(response.Headers.Contains("Location")).IsTrue(); - Check.That(response.Headers.GetValues("Location")).ContainsExactly(_server.Urls[0] + "testpath"); + Check.That(response.Headers.GetValues("Location")).ContainsExactly("/testpath"); } [Fact] public async Task FluentMockServer_Proxy_Should_preserve_cookie_header_in_proxied_request() { - // given - _serverForProxyForwarding = FluentMockServer.Start(); - _serverForProxyForwarding - .Given(Request.Create().WithPath("/*")) + // Assign + string path = $"/prx_{Guid.NewGuid().ToString()}"; + var serverForProxyForwarding = FluentMockServer.Start(); + serverForProxyForwarding + .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create()); - _server = FluentMockServer.Start(); - _server - .Given(Request.Create().WithPath("/*")) - .RespondWith(Response.Create().WithProxy(_serverForProxyForwarding.Urls[0])); + var server = FluentMockServer.Start(); + server + .Given(Request.Create().WithPath(path)) + .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0])); - // when - var requestUri = new Uri(_server.Urls[0]); + // Act + var requestUri = new Uri($"{server.Urls[0]}{path}"); var requestMessage = new HttpRequestMessage { Method = HttpMethod.Get, @@ -243,7 +254,7 @@ namespace WireMock.Net.Tests await new HttpClient(clientHandler).SendAsync(requestMessage); // then - var receivedRequest = _serverForProxyForwarding.LogEntries.First().RequestMessage; + var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage; Check.That(receivedRequest.Cookies).IsNotNull(); Check.That(receivedRequest.Cookies).ContainsPair("name", "value"); } @@ -252,23 +263,24 @@ namespace WireMock.Net.Tests public async Task FluentMockServer_Proxy_Should_set_BodyAsJson_in_proxied_response() { // Assign - _serverForProxyForwarding = FluentMockServer.Start(); - _serverForProxyForwarding - .Given(Request.Create().WithPath("/*")) + string path = $"/prx_{Guid.NewGuid().ToString()}"; + var serverForProxyForwarding = FluentMockServer.Start(); + serverForProxyForwarding + .Given(Request.Create().WithPath(path)) .RespondWith(Response.Create() .WithBodyAsJson(new { i = 42 }) .WithHeader("Content-Type", "application/json; charset=utf-8")); - _server = FluentMockServer.Start(); - _server - .Given(Request.Create().WithPath("/*")) - .RespondWith(Response.Create().WithProxy(_serverForProxyForwarding.Urls[0])); + var server = FluentMockServer.Start(); + server + .Given(Request.Create().WithPath(path)) + .RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0])); // Act var requestMessage = new HttpRequestMessage { Method = HttpMethod.Get, - RequestUri = new Uri(_server.Urls[0]) + RequestUri = new Uri($"{server.Urls[0]}{path}") }; var response = await new HttpClient().SendAsync(requestMessage); @@ -277,5 +289,7 @@ namespace WireMock.Net.Tests Check.That(content).IsEqualTo("{\"i\":42}"); Check.That(response.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/json; charset=utf-8"); } + +#endif } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/FluentMockServerTests.cs b/test/WireMock.Net.Tests/FluentMockServerTests.cs index c3065795..596bef47 100644 --- a/test/WireMock.Net.Tests/FluentMockServerTests.cs +++ b/test/WireMock.Net.Tests/FluentMockServerTests.cs @@ -1,303 +1,30 @@ -using System; +using NFluent; +using System; using System.Collections.Generic; using System.Diagnostics; -using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; -using Moq; -using NFluent; using WireMock.Matchers; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; using WireMock.Server; using Xunit; -using Newtonsoft.Json; -using WireMock.Handlers; -using WireMock.Logging; -using WireMock.Settings; -using WireMock.Admin.Mappings; namespace WireMock.Net.Tests { - public partial class FluentMockServerTests : IDisposable + public class FluentMockServerTests { - private FluentMockServer _server; private static string jsonRequestMessage = @"{ ""message"" : ""Hello server"" }"; - // For for AppVeyor + OpenCover - private string GetCurrentFolder() - { - string current = Directory.GetCurrentDirectory(); - //if (!current.EndsWith("WireMock.Net.Tests")) - // return Path.Combine(current, "test", "WireMock.Net.Tests"); - - return current; - } - - [Fact] - public void FluentMockServer_StartStop() - { - var server1 = FluentMockServer.Start("http://localhost:9091/"); - server1.Stop(); - - var server2 = FluentMockServer.Start("http://localhost:9091/"); - server2.Stop(); - } - - [Fact] - public void FluentMockServer_SaveStaticMappings() - { - // Assign - string guid = "791a3f31-6946-aaaa-8e6f-0237c7441111"; - var _staticMappingHandlerMock = new Mock(); - _staticMappingHandlerMock.Setup(m => m.GetMappingFolder()).Returns("folder"); - _staticMappingHandlerMock.Setup(m => m.FolderExists(It.IsAny())).Returns(true); - _staticMappingHandlerMock.Setup(m => m.WriteMappingFile(It.IsAny(), It.IsAny())); - - _server = FluentMockServer.Start(new FluentMockServerSettings - { - FileSystemHandler = _staticMappingHandlerMock.Object - }); - - _server - .Given(Request.Create().WithPath($"/foo_{Guid.NewGuid()}")) - .WithGuid(guid) - .RespondWith(Response.Create().WithBody("save test")); - - // Act - _server.SaveStaticMappings(); - - // Assert and Verify - _staticMappingHandlerMock.Verify(m => m.GetMappingFolder(), Times.Once); - _staticMappingHandlerMock.Verify(m => m.FolderExists("folder"), Times.Once); - _staticMappingHandlerMock.Verify(m => m.WriteMappingFile(Path.Combine("folder", guid + ".json"), It.IsAny()), Times.Once); - } - - [Fact] - public void FluentMockServer_ReadStaticMapping_WithNonGuidFilename() - { - var guid = Guid.Parse("04ee4872-9efd-4770-90d3-88d445265d0d"); - string title = "documentdb_root_title"; - - _server = FluentMockServer.Start(); - - string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "documentdb_root.json"); - _server.ReadStaticMappingAndAddOrUpdate(folder); - - var mappings = _server.Mappings.ToArray(); - Check.That(mappings).HasSize(1); - - Check.That(mappings.First().RequestMatcher).IsNotNull(); - Check.That(mappings.First().Provider).IsNotNull(); - Check.That(mappings.First().Guid).Equals(guid); - Check.That(mappings.First().Title).Equals(title); - } - - [Fact] - public void FluentMockServer_ReadStaticMapping_WithGuidFilename() - { - string guid = "00000002-ee28-4f29-ae63-1ac9b0802d86"; - - _server = FluentMockServer.Start(); - string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json"); - _server.ReadStaticMappingAndAddOrUpdate(folder); - - var mappings = _server.Mappings.ToArray(); - Check.That(mappings).HasSize(1); - - Check.That(mappings.First().RequestMatcher).IsNotNull(); - Check.That(mappings.First().Provider).IsNotNull(); - Check.That(mappings.First().Guid).Equals(Guid.Parse(guid)); - Check.That(mappings.First().Title).IsNullOrEmpty(); - } - - [Fact] - public void FluentMockServer_ReadStaticMapping_WithResponseBodyFromFile() - { - string guid = "00000002-ee28-4f29-ae63-1ac9b0802d87"; - - string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json"); - string json = File.ReadAllText(folder); - - string responseBodyFilePath = Path.Combine(GetCurrentFolder(), "responsebody.json"); - - dynamic jsonObj = JsonConvert.DeserializeObject(json); - jsonObj["Response"]["BodyAsFile"] = responseBodyFilePath; - - string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented); - File.WriteAllText(folder, output); - - _server = FluentMockServer.Start(); - _server.ReadStaticMappingAndAddOrUpdate(folder); - - var mappings = _server.Mappings.ToArray(); - Check.That(mappings).HasSize(1); - - Check.That(mappings.First().RequestMatcher).IsNotNull(); - Check.That(mappings.First().Provider).IsNotNull(); - Check.That(mappings.First().Guid).Equals(Guid.Parse(guid)); - Check.That(mappings.First().Title).IsNullOrEmpty(); - } - - [Fact] - public void FluentMockServer_ReadStaticMappings_FolderExistsIsTrue() - { - // Assign - var _staticMappingHandlerMock = new Mock(); - _staticMappingHandlerMock.Setup(m => m.GetMappingFolder()).Returns("folder"); - _staticMappingHandlerMock.Setup(m => m.FolderExists(It.IsAny())).Returns(true); - _staticMappingHandlerMock.Setup(m => m.EnumerateFiles(It.IsAny())).Returns(new string[0]); - - _server = FluentMockServer.Start(new FluentMockServerSettings - { - FileSystemHandler = _staticMappingHandlerMock.Object - }); - - // Act - _server.ReadStaticMappings(); - - // Assert and Verify - _staticMappingHandlerMock.Verify(m => m.GetMappingFolder(), Times.Once); - _staticMappingHandlerMock.Verify(m => m.FolderExists("folder"), Times.Once); - _staticMappingHandlerMock.Verify(m => m.EnumerateFiles("folder"), Times.Once); - } - - [Fact] - public void FluentMockServer_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); - - _server = FluentMockServer.Start(new FluentMockServerSettings - { - FileSystemHandler = _staticMappingHandlerMock.Object - }); - - // Act - _server.ReadStaticMappingAndAddOrUpdate(@"c:\test.json"); - - // Assert and Verify - _staticMappingHandlerMock.Verify(m => m.ReadMappingFile(@"c:\test.json"), Times.Once); - } - - [Fact] - public void FluentMockServer_ReadStaticMappings() - { - _server = FluentMockServer.Start(); - - string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings"); - _server.ReadStaticMappings(folder); - - var mappings = _server.Mappings.ToArray(); - Check.That(mappings).HasSize(3); - } - - [Fact] - public void FluentMockServer_Admin_Mappings_WithGuid_Get() - { - Guid guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05"); - _server = FluentMockServer.Start(); - - _server.Given(Request.Create().WithPath("/foo1").UsingGet()).WithGuid(guid) - .RespondWith(Response.Create().WithStatusCode(201).WithBody("1")); - - _server.Given(Request.Create().WithPath("/foo2").UsingGet()) - .RespondWith(Response.Create().WithStatusCode(202).WithBody("2")); - - var mappings = _server.Mappings.ToArray(); - Check.That(mappings).HasSize(2); - } - - [Fact] - public void FluentMockServer_Admin_Mappings_WithGuidAsString_Get() - { - string guid = "90356dba-b36c-469a-a17e-669cd84f1f05"; - _server = FluentMockServer.Start(); - - _server.Given(Request.Create().WithPath("/foo100").UsingGet()).WithGuid(guid) - .RespondWith(Response.Create().WithStatusCode(201).WithBody("1")); - - var mappings = _server.Mappings.ToArray(); - Check.That(mappings).HasSize(1); - } - - [Fact] - public void FluentMockServer_Admin_Mappings_Add_SameGuid() - { - var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05"); - _server = FluentMockServer.Start(); - - var response1 = Response.Create().WithStatusCode(500); - _server.Given(Request.Create().UsingGet()) - .WithGuid(guid) - .RespondWith(response1); - - var mappings1 = _server.Mappings.ToArray(); - Check.That(mappings1).HasSize(1); - Check.That(mappings1.First().Guid).Equals(guid); - - var response2 = Response.Create().WithStatusCode(400); - _server.Given(Request.Create().WithPath("/2").UsingGet()) - .WithGuid(guid) - .RespondWith(response2); - - var mappings2 = _server.Mappings.ToArray(); - Check.That(mappings2).HasSize(1); - Check.That(mappings2.First().Guid).Equals(guid); - Check.That(mappings2.First().Provider).Equals(response2); - } - - [Fact] - public async Task FluentMockServer_Admin_Mappings_AtPriority() - { - _server = FluentMockServer.Start(); - - // given - _server.Given(Request.Create().WithPath("/1").UsingGet()) - .AtPriority(2) - .RespondWith(Response.Create().WithStatusCode(200)); - - _server.Given(Request.Create().WithPath("/1").UsingGet()) - .AtPriority(1) - .RespondWith(Response.Create().WithStatusCode(400)); - - var mappings = _server.Mappings.ToArray(); - Check.That(mappings).HasSize(2); - - // when - var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/1"); - - // then - Check.That((int)response.StatusCode).IsEqualTo(400); - } - - [Fact] - public async Task FluentMockServer_Admin_Requests_Get() - { - // given - _server = FluentMockServer.Start(); - - // when - await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo"); - - // then - Check.That(_server.LogEntries).HasSize(1); - var requestLogged = _server.LogEntries.First(); - Check.That(requestLogged.RequestMessage.Method).IsEqualTo("get"); - Check.That(requestLogged.RequestMessage.BodyAsBytes).IsNull(); - } - [Fact] public async Task FluentMockServer_Should_respond_to_request_methodPatch() { // given string path = $"/foo_{Guid.NewGuid()}"; - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); _server.Given(Request.Create().WithPath(path).UsingMethod("patch")) .RespondWith(Response.Create().WithBody("hello patch")); @@ -325,7 +52,7 @@ namespace WireMock.Net.Tests public async Task FluentMockServer_Should_respond_to_request_bodyAsString() { // given - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); _server .Given(Request.Create() @@ -346,7 +73,7 @@ namespace WireMock.Net.Tests public async Task FluentMockServer_Should_respond_to_request_BodyAsJson() { // Assign - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); _server .Given(Request.Create().UsingAnyMethod()) @@ -363,7 +90,7 @@ namespace WireMock.Net.Tests public async Task FluentMockServer_Should_respond_to_request_BodyAsJson_Indented() { // Assign - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); _server .Given(Request.Create().UsingAnyMethod()) @@ -380,7 +107,7 @@ namespace WireMock.Net.Tests public async Task FluentMockServer_Should_respond_to_request_bodyAsCallback() { // given - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); _server .Given(Request.Create() @@ -401,7 +128,7 @@ namespace WireMock.Net.Tests public async Task FluentMockServer_Should_respond_to_request_bodyAsBase64() { // given - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); _server.Given(Request.Create().WithPath("/foo").UsingGet()).RespondWith(Response.Create().WithBodyFromBase64("SGVsbG8gV29ybGQ/")); @@ -417,7 +144,7 @@ namespace WireMock.Net.Tests { // given string path = $"/foo_{Guid.NewGuid()}"; - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); _server.Given(Request.Create().WithPath(path).UsingGet()).RespondWith(Response.Create().WithBody(new byte[] { 48, 49 })); @@ -446,7 +173,7 @@ namespace WireMock.Net.Tests new object[] { new JsonPathMatcher("$..[?(@.message == 'Hello server')]"), "text/plain" } }; - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); foreach (var item in validMatchersForHelloServerJsonMessage) { @@ -473,7 +200,7 @@ namespace WireMock.Net.Tests { // given string path = $"/foo{Guid.NewGuid()}"; - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); // when var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + path); @@ -488,7 +215,7 @@ namespace WireMock.Net.Tests { // Assign string path = $"/bar_{Guid.NewGuid()}"; - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); // when await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo"); @@ -507,7 +234,7 @@ namespace WireMock.Net.Tests public async Task FluentMockServer_Should_reset_requestlogs() { // given - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); // when await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo"); @@ -522,7 +249,7 @@ namespace WireMock.Net.Tests { // given string path = $"/foo_{Guid.NewGuid()}"; - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); _server .Given(Request.Create() @@ -547,7 +274,7 @@ namespace WireMock.Net.Tests string path = $"/foo_{Guid.NewGuid()}"; string pathToRedirect = $"/bar_{Guid.NewGuid()}"; - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); _server .Given(Request.Create() @@ -575,7 +302,7 @@ namespace WireMock.Net.Tests public async Task FluentMockServer_Should_delay_responses_for_a_given_route() { // given - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); _server .Given(Request.Create() @@ -598,7 +325,7 @@ namespace WireMock.Net.Tests public async Task FluentMockServer_Should_delay_responses() { // given - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); _server.AddGlobalProcessingDelay(TimeSpan.FromMilliseconds(200)); _server .Given(Request.Create().WithPath("/*")) @@ -619,7 +346,7 @@ namespace WireMock.Net.Tests //public async Task Should_proxy_responses_with_client_certificate() //{ // // given - // _server = FluentMockServer.Start(); + // var _server = FluentMockServer.Start(); // _server // .Given(Request.Create().WithPath("/*")) // .RespondWith(Response.Create().WithProxy("https://server-that-expects-a-client-certificate", @"\\yourclientcertificatecontainingprivatekey.pfx", "yourclientcertificatepassword")); @@ -631,34 +358,11 @@ namespace WireMock.Net.Tests // Check.That(result).Contains("google"); //} - [Fact] - public async Task FluentMockServer_Logging_SetMaxRequestLogCount() - { - // Assign - var client = new HttpClient(); - // Act - _server = FluentMockServer.Start(); - _server.SetMaxRequestLogCount(2); - - await client.GetAsync("http://localhost:" + _server.Ports[0] + "/foo1"); - await client.GetAsync("http://localhost:" + _server.Ports[0] + "/foo2"); - await client.GetAsync("http://localhost:" + _server.Ports[0] + "/foo3"); - - // Assert - Check.That(_server.LogEntries).HasSize(2); - - var requestLoggedA = _server.LogEntries.First(); - Check.That(requestLoggedA.RequestMessage.Path).EndsWith("/foo2"); - - var requestLoggedB = _server.LogEntries.Last(); - Check.That(requestLoggedB.RequestMessage.Path).EndsWith("/foo3"); - } - [Fact] public async Task FluentMockServer_Should_respond_to_request_callback() { // Assign - _server = FluentMockServer.Start(); + var _server = FluentMockServer.Start(); _server .Given(Request.Create().WithPath("/foo").UsingGet()) @@ -671,27 +375,25 @@ namespace WireMock.Net.Tests Check.That(response).IsEqualTo("/fooBar"); } +#if !NET452 [Fact] - public async Task FluentMockServer_Should_exclude_restrictedResponseHeader_for_IOwinResponse() + public async Task FluentMockServer_Should_not_exclude_restrictedResponseHeader_for_ASPNETCORE() { - _server = FluentMockServer.Start(); + // Assign + string path = $"/foo_{Guid.NewGuid()}"; + var _server = FluentMockServer.Start(); _server - .Given(Request.Create().WithPath("/foo").UsingGet()) - .RespondWith(Response.Create().WithHeader("Keep-Alive", "").WithHeader("test", "")); + .Given(Request.Create().WithPath(path).UsingGet()) + .RespondWith(Response.Create().WithHeader("Keep-Alive", "k").WithHeader("test", "t")); // Act - var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo"); + 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("Keep-Alive")).IsFalse(); - } - - public void Dispose() - { - _server?.Stop(); - _serverForProxyForwarding?.Stop(); + Check.That(response.Headers.Contains("Keep-Alive")).IsTrue(); } +#endif } -} +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Handlers/LocalFileSystemHandlerTests.cs b/test/WireMock.Net.Tests/Handlers/LocalFileSystemHandlerTests.cs new file mode 100644 index 00000000..4c572031 --- /dev/null +++ b/test/WireMock.Net.Tests/Handlers/LocalFileSystemHandlerTests.cs @@ -0,0 +1,37 @@ +using System; +using System.IO; +using NFluent; +using WireMock.Handlers; +using Xunit; + +namespace WireMock.Net.Tests.Handlers +{ + public class LocalFileSystemHandlerTests + { + private LocalFileSystemHandler sut = new LocalFileSystemHandler(); + + [Fact] + public void LocalFileSystemHandler_GetMappingFolder() + { + // Act + string result = sut.GetMappingFolder(); + + // Assert + Check.That(result).EndsWith(Path.Combine("__admin", "mappings")); + } + + [Fact] + public void LocalFileSystemHandler_CreateFolder_Throws() + { + // Act + Check.ThatCode(() => sut.CreateFolder(null)).Throws(); + } + + [Fact] + public void LocalFileSystemHandler_WriteMappingFile_Throws() + { + // Act + Check.ThatCode(() => sut.WriteMappingFile(null, null)).Throws(); + } + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/ObservableLogEntriesTest.cs b/test/WireMock.Net.Tests/ObservableLogEntriesTest.cs index ca5c875e..b4396344 100644 --- a/test/WireMock.Net.Tests/ObservableLogEntriesTest.cs +++ b/test/WireMock.Net.Tests/ObservableLogEntriesTest.cs @@ -13,28 +13,27 @@ using Xunit; namespace WireMock.Net.Tests { - public class ObservableLogEntriesTest : IDisposable + public class ObservableLogEntriesTest { - private FluentMockServer _server; - [Fact] public async void FluentMockServer_LogEntriesChanged() { // Assign - _server = FluentMockServer.Start(); + string path = $"/log_{Guid.NewGuid()}"; + var server = FluentMockServer.Start(); - _server + server .Given(Request.Create() - .WithPath("/foo") + .WithPath(path) .UsingGet()) .RespondWith(Response.Create() .WithBody(@"{ msg: ""Hello world!""}")); int count = 0; - _server.LogEntriesChanged += (sender, args) => count++; + server.LogEntriesChanged += (sender, args) => count++; // Act - await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo"); + await new HttpClient().GetAsync($"http://localhost:{server.Ports[0]}{path}"); // Assert Check.That(count).Equals(1); @@ -46,18 +45,18 @@ namespace WireMock.Net.Tests int expectedCount = 10; // Assign - _server = FluentMockServer.Start(); + string path = $"/log_p_{Guid.NewGuid()}"; + var server = FluentMockServer.Start(); - _server + server .Given(Request.Create() - .WithPath("/foo") + .WithPath(path) .UsingGet()) .RespondWith(Response.Create() - .WithDelay(6) .WithSuccess()); int count = 0; - _server.LogEntriesChanged += (sender, args) => count++; + server.LogEntriesChanged += (sender, args) => count++; var http = new HttpClient(); @@ -65,8 +64,8 @@ namespace WireMock.Net.Tests var listOfTasks = new List>(); for (var i = 0; i < expectedCount; i++) { - Thread.Sleep(100); - listOfTasks.Add(http.GetAsync($"{_server.Urls[0]}/foo")); + Thread.Sleep(10); + listOfTasks.Add(http.GetAsync($"{server.Urls[0]}{path}")); } var responses = await Task.WhenAll(listOfTasks); var countResponsesWithStatusNotOk = responses.Count(r => r.StatusCode != HttpStatusCode.OK); @@ -75,10 +74,5 @@ namespace WireMock.Net.Tests Check.That(countResponsesWithStatusNotOk).Equals(0); Check.That(count).Equals(expectedCount); } - - public void Dispose() - { - _server?.Dispose(); - } } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/RequestWithPathTests.cs b/test/WireMock.Net.Tests/RequestWithPathTests.cs index 3f9d5b5d..52607a0f 100644 --- a/test/WireMock.Net.Tests/RequestWithPathTests.cs +++ b/test/WireMock.Net.Tests/RequestWithPathTests.cs @@ -14,6 +14,36 @@ namespace WireMock.Net.Tests { private const string ClientIp = "::1"; + // [Fact] : TODO : this test fails??? + public void Request_WithPath_EncodedSpaces() + { + // Assign + var spec = Request.Create().WithPath("/path/a%20b").UsingAnyMethod(); + + // when + var body = new BodyData(); + var request = new RequestMessage(new UrlDetails("http://localhost/path/a%20b"), "GET", ClientIp, body); + + // then + var requestMatchResult = new RequestMatchResult(); + Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); + } + + [Fact] + public void Request_WithPath_Spaces() + { + // Assign + var spec = Request.Create().WithPath("/path/a b").UsingAnyMethod(); + + // when + var body = new BodyData(); + var request = new RequestMessage(new UrlDetails("http://localhost/path/a b"), "GET", ClientIp, body); + + // then + var requestMatchResult = new RequestMatchResult(); + Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0); + } + [Fact] public void Request_WithPath_WithHeader_Match() { diff --git a/test/WireMock.Net.Tests/ResponseBuilderTests/ResponseWithHandlebarsTests.cs b/test/WireMock.Net.Tests/ResponseBuilderTests/ResponseWithHandlebarsTests.cs index e2772051..c8aa60bd 100644 --- a/test/WireMock.Net.Tests/ResponseBuilderTests/ResponseWithHandlebarsTests.cs +++ b/test/WireMock.Net.Tests/ResponseBuilderTests/ResponseWithHandlebarsTests.cs @@ -2,7 +2,11 @@ using System.Collections.Generic; using System.Text; using System.Threading.Tasks; +#if NET452 using Microsoft.Owin; +#else +using Microsoft.AspNetCore.Http; +#endif using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NFluent; @@ -18,7 +22,7 @@ namespace WireMock.Net.Tests.ResponseBuilderTests private const string ClientIp = "::1"; [Fact] - public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson() + public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsObject() { // Assign string jsonString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }"; @@ -27,17 +31,17 @@ namespace WireMock.Net.Tests.ResponseBuilderTests BodyAsJson = JsonConvert.DeserializeObject(jsonString), Encoding = Encoding.UTF8 }; - var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, bodyData); + var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData); var response = Response.Create() - .WithBodyAsJson(new { x = "test {{request.url}}" }) + .WithBodyAsJson(new { x = "test {{request.path}}" }) .WithTransformer(); // Act var responseMessage = await response.ProvideResponseAsync(request); // Assert - Check.That(JsonConvert.SerializeObject(responseMessage.BodyAsJson)).Equals("{\"x\":\"test http://localhost/foo\"}"); + Check.That(JsonConvert.SerializeObject(responseMessage.BodyAsJson)).Equals("{\"x\":\"test /foo_object\"}"); } [Fact] diff --git a/test/WireMock.Net.Tests/StatefulBehaviorTests.cs b/test/WireMock.Net.Tests/StatefulBehaviorTests.cs index 3d47ec8e..1c50838c 100644 --- a/test/WireMock.Net.Tests/StatefulBehaviorTests.cs +++ b/test/WireMock.Net.Tests/StatefulBehaviorTests.cs @@ -31,8 +31,6 @@ namespace WireMock.Net.Tests // then Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - - server.Dispose(); } [Fact] @@ -61,8 +59,6 @@ namespace WireMock.Net.Tests // then Check.That(responseNoState).Equals("No state msg"); Check.That(responseWithState).Equals("Test state msg"); - - server.Dispose(); } [Fact] @@ -117,8 +113,6 @@ namespace WireMock.Net.Tests Check.That(server.Scenarios["To do list"].NextState).IsNull(); Check.That(server.Scenarios["To do list"].Started).IsTrue(); Check.That(server.Scenarios["To do list"].Finished).IsTrue(); - - server.Dispose(); } [Fact] @@ -164,8 +158,6 @@ namespace WireMock.Net.Tests var responseWithState2 = await new HttpClient().GetStringAsync(url + "/foo2X"); Check.That(responseWithState2).Equals("Test state msg 2"); - - server.Dispose(); } } } \ No newline at end of file diff --git a/test/WireMock.Net.Tests/Util/UrlUtilsTests.cs b/test/WireMock.Net.Tests/Util/UrlUtilsTests.cs index c6245d09..e4ec478b 100644 --- a/test/WireMock.Net.Tests/Util/UrlUtilsTests.cs +++ b/test/WireMock.Net.Tests/Util/UrlUtilsTests.cs @@ -1,5 +1,9 @@ using System; +#if NET452 using Microsoft.Owin; +#else +using Microsoft.AspNetCore.Http; +#endif using NFluent; 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 9be94fe3..ba2238a0 100644 --- a/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj +++ b/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj @@ -2,7 +2,7 @@ Stef Heyenrath - net452 + net452;netcoreapp2.1 full WireMock.Net.Tests WireMock.Net.Tests @@ -16,19 +16,23 @@ - - + - - + + - + + + + + +