Compare commits

..

1 Commits

Author SHA1 Message Date
Stef Heyenrath
3e6eb256f5 wip 2020-03-02 13:25:53 +00:00
49 changed files with 356 additions and 1026 deletions

View File

@@ -1,23 +1,3 @@
# 1.2.2.0 (25 March 2020)
- [#446](https://github.com/WireMock-Net/WireMock.Net/pull/446) - When port is provided: WireMockServer still takes a random port [bug] contributed by [StefH](https://github.com/StefH)
- [#445](https://github.com/WireMock-Net/WireMock.Net/issues/445) - Port where WireMockServer listens to - v1.2x [bug]
# 1.2.1.0 (17 March 2020)
- [#442](https://github.com/WireMock-Net/WireMock.Net/pull/442) - Fix Null body in handlebars transformation [bug] contributed by [StefH](https://github.com/StefH)
# 1.2.0.0 (14 March 2020)
- [#417](https://github.com/WireMock-Net/WireMock.Net/pull/417) - Let the .NET core/standard WebHostBuilder use a random port [bug] contributed by [StefH](https://github.com/StefH)
- [#422](https://github.com/WireMock-Net/WireMock.Net/pull/422) - AllowOnlyDefinedHttpStatusCodeInResponse [bug] contributed by [StefH](https://github.com/StefH)
- [#379](https://github.com/WireMock-Net/WireMock.Net/issues/379) - Trusting the self signed certificate to enable SSL on dotnet core [bug]
- [#420](https://github.com/WireMock-Net/WireMock.Net/issues/420) - Updating to 1.1.6+ breaks tests because new AllowAnyHttpStatusCodeInResponse option defaults to false [bug]
# 1.1.10 (05 March 2020)
- [#427](https://github.com/WireMock-Net/WireMock.Net/pull/427) - Add UsingOptions, UsingConnect and UsingTrace [feature] contributed by [StefH](https://github.com/StefH)
- [#434](https://github.com/WireMock-Net/WireMock.Net/pull/434) - Option to disable JSON deserialization [feature] contributed by [sebastianmattar](https://github.com/sebastianmattar)
- [#435](https://github.com/WireMock-Net/WireMock.Net/pull/435) - Also call HandlebarsRegistrationCallback when using WithCallback(..) [feature] contributed by [StefH](https://github.com/StefH)
- [#408](https://github.com/WireMock-Net/WireMock.Net/issues/408) - Intermittent threading errors with FindLogEntries [bug]
- [#433](https://github.com/WireMock-Net/WireMock.Net/issues/433) - HandlebarsRegistrationCallback not fired [feature]
# 1.1.9.0 (25 February 2020) # 1.1.9.0 (25 February 2020)
- [#431](https://github.com/WireMock-Net/WireMock.Net/pull/431) - Fix LinqMatcher for JSON int64 [bug] contributed by [StefH](https://github.com/StefH) - [#431](https://github.com/WireMock-Net/WireMock.Net/pull/431) - Fix LinqMatcher for JSON int64 [bug] contributed by [StefH](https://github.com/StefH)
- [#425](https://github.com/WireMock-Net/WireMock.Net/issues/425) - Allow 64 bit numbers in JSON [bug] - [#425](https://github.com/WireMock-Net/WireMock.Net/issues/425) - Allow 64 bit numbers in JSON [bug]

View File

@@ -4,7 +4,7 @@
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<VersionPrefix>1.2.2</VersionPrefix> <VersionPrefix>1.1.9</VersionPrefix>
</PropertyGroup> </PropertyGroup>
<Choose> <Choose>

View File

@@ -1,3 +1,3 @@
https://github.com/StefH/GitHubReleaseNotes https://github.com/StefH/GitHubReleaseNotes
GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc --version 1.2.2.0 GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc --version 1.1.9.0

View File

@@ -65,10 +65,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.StandAlone", "
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.Console.RequestLogTest", "examples\WireMock.Net.Console.RequestLogTest\WireMock.Net.Console.RequestLogTest.csproj", "{A9D039B9-7509-4CF1-9EFD-87EB82998575}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.Console.RequestLogTest", "examples\WireMock.Net.Console.RequestLogTest\WireMock.Net.Console.RequestLogTest.csproj", "{A9D039B9-7509-4CF1-9EFD-87EB82998575}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.Client.Net472", "examples\WireMock.Net.Client.Net472\WireMock.Net.Client.Net472.csproj", "{02082E34-DEF2-47D0-AF0B-3326FAA908CE}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.Console.NETCoreApp3", "examples\WireMock.Net.Console.NETCoreApp3\WireMock.Net.Console.NETCoreApp3.csproj", "{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug - Sonar|Any CPU = Debug - Sonar|Any CPU Debug - Sonar|Any CPU = Debug - Sonar|Any CPU
@@ -307,30 +303,6 @@ Global
{A9D039B9-7509-4CF1-9EFD-87EB82998575}.Release|Any CPU.Build.0 = Release|Any CPU {A9D039B9-7509-4CF1-9EFD-87EB82998575}.Release|Any CPU.Build.0 = Release|Any CPU
{A9D039B9-7509-4CF1-9EFD-87EB82998575}.Release|x64.ActiveCfg = Release|Any CPU {A9D039B9-7509-4CF1-9EFD-87EB82998575}.Release|x64.ActiveCfg = Release|Any CPU
{A9D039B9-7509-4CF1-9EFD-87EB82998575}.Release|x64.Build.0 = Release|Any CPU {A9D039B9-7509-4CF1-9EFD-87EB82998575}.Release|x64.Build.0 = Release|Any CPU
{02082E34-DEF2-47D0-AF0B-3326FAA908CE}.Debug - Sonar|Any CPU.ActiveCfg = Debug|Any CPU
{02082E34-DEF2-47D0-AF0B-3326FAA908CE}.Debug - Sonar|Any CPU.Build.0 = Debug|Any CPU
{02082E34-DEF2-47D0-AF0B-3326FAA908CE}.Debug - Sonar|x64.ActiveCfg = Debug|Any CPU
{02082E34-DEF2-47D0-AF0B-3326FAA908CE}.Debug - Sonar|x64.Build.0 = Debug|Any CPU
{02082E34-DEF2-47D0-AF0B-3326FAA908CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{02082E34-DEF2-47D0-AF0B-3326FAA908CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{02082E34-DEF2-47D0-AF0B-3326FAA908CE}.Debug|x64.ActiveCfg = Debug|Any CPU
{02082E34-DEF2-47D0-AF0B-3326FAA908CE}.Debug|x64.Build.0 = Debug|Any CPU
{02082E34-DEF2-47D0-AF0B-3326FAA908CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{02082E34-DEF2-47D0-AF0B-3326FAA908CE}.Release|Any CPU.Build.0 = Release|Any CPU
{02082E34-DEF2-47D0-AF0B-3326FAA908CE}.Release|x64.ActiveCfg = Release|Any CPU
{02082E34-DEF2-47D0-AF0B-3326FAA908CE}.Release|x64.Build.0 = Release|Any CPU
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}.Debug - Sonar|Any CPU.ActiveCfg = Debug|Any CPU
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}.Debug - Sonar|Any CPU.Build.0 = Debug|Any CPU
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}.Debug - Sonar|x64.ActiveCfg = Debug|Any CPU
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}.Debug - Sonar|x64.Build.0 = Debug|Any CPU
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}.Debug|x64.ActiveCfg = Debug|Any CPU
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}.Debug|x64.Build.0 = Debug|Any CPU
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}.Release|Any CPU.Build.0 = Release|Any CPU
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}.Release|x64.ActiveCfg = Release|Any CPU
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@@ -355,8 +327,6 @@ Global
{B6269AAC-170A-4346-8B9A-579DED3D9A94} = {EF242EDF-7133-4277-9A0C-18744DE08707} {B6269AAC-170A-4346-8B9A-579DED3D9A94} = {EF242EDF-7133-4277-9A0C-18744DE08707}
{B6269AAC-170A-43D5-8B9A-579DED3D9A95} = {EF242EDF-7133-4277-9A0C-18744DE08707} {B6269AAC-170A-43D5-8B9A-579DED3D9A95} = {EF242EDF-7133-4277-9A0C-18744DE08707}
{A9D039B9-7509-4CF1-9EFD-87EB82998575} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A} {A9D039B9-7509-4CF1-9EFD-87EB82998575} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A}
{02082E34-DEF2-47D0-AF0B-3326FAA908CE} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A}
{C54A5D32-EFE0-407B-BA8D-7172A1000DCB} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BF428BCC-C837-433B-87D2-15C7014B73E9} SolutionGuid = {BF428BCC-C837-433B-87D2-15C7014B73E9}

View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

View File

@@ -1,35 +0,0 @@
using Newtonsoft.Json;
using RestEase;
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WireMock.Client;
namespace WireMock.Net.Client.Net472
{
class Program
{
static async Task Main(string[] args)
{
// Create an implementation of the IWireMockAdminApi and pass in the base URL for the API.
var api = RestClient.For<IWireMockAdminApi>("http://localhost:9091");
// Set BASIC Auth
var value = Convert.ToBase64String(Encoding.ASCII.GetBytes("a:b"));
api.Authorization = new AuthenticationHeaderValue("Basic", value);
var settings1 = await api.GetSettingsAsync();
Console.WriteLine($"settings1 = {JsonConvert.SerializeObject(settings1)}");
}
}
//public interface IWireMockAdminApi
//{
// /// <summary>
// /// Authentication header
// /// </summary>
// [Header("Authorization")]
// AuthenticationHeaderValue Authorization { get; set; }
//}
}

View File

@@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
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.Client.Net472")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("mStack.nl")]
[assembly: AssemblyProduct("WireMock.Net.Client.Net472")]
[assembly: AssemblyCopyright("Copyright © mStack.nl 2020")]
[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
// 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("02082e34-def2-47d0-af0b-3326faa908ce")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// 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")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -1,83 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{02082E34-DEF2-47D0-AF0B-3326FAA908CE}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>WireMock.Net.Client.Net472</RootNamespace>
<AssemblyName>WireMock.Net.Client.Net472</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>false</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>
</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="RestEase, Version=1.4.10.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\RestEase.1.4.10\lib\net45\RestEase.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="WireMock.Net.Abstractions, Version=1.2.0.0, Culture=neutral, PublicKeyToken=c8d65537854e1f03, processorArchitecture=MSIL">
<HintPath>..\..\packages\WireMock.Net.Abstractions.1.2.0\lib\net45\WireMock.Net.Abstractions.dll</HintPath>
</Reference>
<Reference Include="WireMock.Net.RestClient">
<HintPath>..\..\packages\WireMock.Net.RestClient.1.2.0\lib\net45\WireMock.Net.RestClient.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\..\packages\Brutal.Dev.StrongNameSigner.2.7.1\build\Brutal.Dev.StrongNameSigner.targets" Condition="Exists('..\..\packages\Brutal.Dev.StrongNameSigner.2.7.1\build\Brutal.Dev.StrongNameSigner.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\Brutal.Dev.StrongNameSigner.2.7.1\build\Brutal.Dev.StrongNameSigner.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Brutal.Dev.StrongNameSigner.2.7.1\build\Brutal.Dev.StrongNameSigner.targets'))" />
</Target>
</Project>

View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Brutal.Dev.StrongNameSigner" version="2.7.1" targetFramework="net472" />
<package id="Newtonsoft.Json" version="6.0.1" targetFramework="net472" />
<package id="RestEase" version="1.4.10" targetFramework="net472" />
<package id="WireMock.Net.Abstractions" version="1.2.0" targetFramework="net472" />
<package id="WireMock.Net.RestClient" version="1.2.0" targetFramework="net472" />
</packages>

View File

@@ -1,54 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<ApplicationIcon>../../WireMock.Net-Logo.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\WireMock.Net.Console.Net452.Classic\MainApp.cs" Link="MainApp.cs" />
<Compile Include="..\WireMock.Net.Console.Net452.Classic\CustomFileSystemFileHandler.cs" Link="CustomFileSystemFileHandler.cs" />
<Compile Include="..\WireMock.Net.Console.NETCoreApp\Program.cs" Link="Program.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="__admin\mappings\*.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Compile Remove="__admin\mappings\1.cs" />
</ItemGroup>
<ItemGroup>
<None Remove="__admin\mappings\array.json" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\WireMock.Net\WireMock.Net.csproj" />
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="log4net" Version="2.0.8" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>
<ItemGroup>
<None Update="log4net.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="nlog.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\791a3f31-6946-4ce7-8e6f-0237c7443275.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\791a3f31-6946-4ce7-8e6f-0237c7443275.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\MyXmlResponse.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -1,22 +0,0 @@
{
"Request": {
"Path": {
"Matchers": [
{
"Name": "WildcardMatcher",
"Pattern": "/static/mapping"
}
]
},
"Methods": [
"get"
]
},
"Response": {
"BodyAsJson": { "body": "static mapping" },
"Headers": {
"Content-Type": "application/json",
"Test-X": [ "test 1", "test 2" ]
}
}
}

View File

@@ -1,29 +0,0 @@
{
"Guid": "791a3f31-6946-4ce7-8e6f-0237c7443275",
"Title": "",
"Priority": 0,
"Request": {
"Path": "/proxy-google-test-post",
"Methods": [
"post"
],
"Body": {}
},
"Response": {
"StatusCode": 404,
"Body": "<!DOCTYPE html>\n<html lang=en>\n <meta charset=utf-8>\n <meta name=viewport content=\"initial-scale=1, minimum-scale=1, width=device-width\">\n <title>Error 404 (Not Found)!!1</title>\n <style>\n *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}\n </style>\n <a href=//www.google.com/><span id=logo aria-label=Google></span></a>\n <p><b>404.</b> <ins>Thats an error.</ins>\n <p>The requested URL <code>/proxy-google-test-post</code> was not found on this server. <ins>Thats all we know.</ins>\n",
"BodyAsBytes": "PCFET0NUWVBFIGh0bWw+CjxodG1sIGxhbmc9ZW4+CiAgPG1ldGEgY2hhcnNldD11dGYtOD4KICA8bWV0YSBuYW1lPXZpZXdwb3J0IGNvbnRlbnQ9ImluaXRpYWwtc2NhbGU9MSwgbWluaW11bS1zY2FsZT0xLCB3aWR0aD1kZXZpY2Utd2lkdGgiPgogIDx0aXRsZT5FcnJvciA0MDQgKE5vdCBGb3VuZCkhITE8L3RpdGxlPgogIDxzdHlsZT4KICAgICp7bWFyZ2luOjA7cGFkZGluZzowfWh0bWwsY29kZXtmb250OjE1cHgvMjJweCBhcmlhbCxzYW5zLXNlcmlmfWh0bWx7YmFja2dyb3VuZDojZmZmO2NvbG9yOiMyMjI7cGFkZGluZzoxNXB4fWJvZHl7bWFyZ2luOjclIGF1dG8gMDttYXgtd2lkdGg6MzkwcHg7bWluLWhlaWdodDoxODBweDtwYWRkaW5nOjMwcHggMCAxNXB4fSogPiBib2R5e2JhY2tncm91bmQ6dXJsKC8vd3d3Lmdvb2dsZS5jb20vaW1hZ2VzL2Vycm9ycy9yb2JvdC5wbmcpIDEwMCUgNXB4IG5vLXJlcGVhdDtwYWRkaW5nLXJpZ2h0OjIwNXB4fXB7bWFyZ2luOjExcHggMCAyMnB4O292ZXJmbG93OmhpZGRlbn1pbnN7Y29sb3I6Izc3Nzt0ZXh0LWRlY29yYXRpb246bm9uZX1hIGltZ3tib3JkZXI6MH1AbWVkaWEgc2NyZWVuIGFuZCAobWF4LXdpZHRoOjc3MnB4KXtib2R5e2JhY2tncm91bmQ6bm9uZTttYXJnaW4tdG9wOjA7bWF4LXdpZHRoOm5vbmU7cGFkZGluZy1yaWdodDowfX0jbG9nb3tiYWNrZ3JvdW5kOnVybCgvL3d3dy5nb29nbGUuY29tL2ltYWdlcy9icmFuZGluZy9nb29nbGVsb2dvLzF4L2dvb2dsZWxvZ29fY29sb3JfMTUweDU0ZHAucG5nKSBuby1yZXBlYXQ7bWFyZ2luLWxlZnQ6LTVweH1AbWVkaWEgb25seSBzY3JlZW4gYW5kIChtaW4tcmVzb2x1dGlvbjoxOTJkcGkpeyNsb2dve2JhY2tncm91bmQ6dXJsKC8vd3d3Lmdvb2dsZS5jb20vaW1hZ2VzL2JyYW5kaW5nL2dvb2dsZWxvZ28vMngvZ29vZ2xlbG9nb19jb2xvcl8xNTB4NTRkcC5wbmcpIG5vLXJlcGVhdCAwJSAwJS8xMDAlIDEwMCU7LW1vei1ib3JkZXItaW1hZ2U6dXJsKC8vd3d3Lmdvb2dsZS5jb20vaW1hZ2VzL2JyYW5kaW5nL2dvb2dsZWxvZ28vMngvZ29vZ2xlbG9nb19jb2xvcl8xNTB4NTRkcC5wbmcpIDB9fUBtZWRpYSBvbmx5IHNjcmVlbiBhbmQgKC13ZWJraXQtbWluLWRldmljZS1waXhlbC1yYXRpbzoyKXsjbG9nb3tiYWNrZ3JvdW5kOnVybCgvL3d3dy5nb29nbGUuY29tL2ltYWdlcy9icmFuZGluZy9nb29nbGVsb2dvLzJ4L2dvb2dsZWxvZ29fY29sb3JfMTUweDU0ZHAucG5nKSBuby1yZXBlYXQ7LXdlYmtpdC1iYWNrZ3JvdW5kLXNpemU6MTAwJSAxMDAlfX0jbG9nb3tkaXNwbGF5OmlubGluZS1ibG9jaztoZWlnaHQ6NTRweDt3aWR0aDoxNTBweH0KICA8L3N0eWxlPgogIDxhIGhyZWY9Ly93d3cuZ29vZ2xlLmNvbS8+PHNwYW4gaWQ9bG9nbyBhcmlhLWxhYmVsPUdvb2dsZT48L3NwYW4+PC9hPgogIDxwPjxiPjQwNC48L2I+IDxpbnM+VGhhdOKAmXMgYW4gZXJyb3IuPC9pbnM+CiAgPHA+VGhlIHJlcXVlc3RlZCBVUkwgPGNvZGU+L3Byb3h5LWdvb2dsZS10ZXN0LXBvc3Q8L2NvZGU+IHdhcyBub3QgZm91bmQgb24gdGhpcyBzZXJ2ZXIuICA8aW5zPlRoYXTigJlzIGFsbCB3ZSBrbm93LjwvaW5zPgo=",
"BodyEncoding": {
"CodePage": 65001,
"EncodingName": "Unicode (UTF-8)",
"WebName": "utf-8"
},
"UseTransformer": false,
"Headers": {
"Date": "Wed, 27 Oct 2017 18:57:40 GMT",
"Alt-Svc": "quic=\":443\"; ma=2592000; v=\"39,38,37,35\"",
"Referrer-Policy": "no-referrer",
"Connection": "close"
}
}
}

View File

@@ -1,19 +0,0 @@
{
"Guid": "873d495f-940e-4b86-a1f4-4f0fc7be8b8b",
"Priority": 4,
"Request": {
"Path": {},
"Methods": [
"get"
]
},
"Response": {
"StatusCode": 200,
"BodyDestination": "SameAsSource",
"Body": "NO PATH OR URL",
"UseTransformer": false,
"Headers": {
"Content-Type": "application/json"
}
}
}

View File

@@ -1,22 +0,0 @@
{
"Request": {
"Path": {
"Matchers": [
{
"Name": "WildcardMatcher",
"Pattern": "/bodyasfilexmltest",
"IgnoreCase": false
}
]
},
"Methods": [
"get"
]
},
"Response": {
"StatusCode": 200,
"Headers": {"Content-Type": "application/xml"},
"BodyAsFile": "MyXmlResponse.xml",
"UseTransformer": false
}
}

View File

@@ -1,3 +0,0 @@
<xml>
<hello>world</hello>
</xml>

View File

@@ -1,46 +0,0 @@
[
{
"Title": "1",
"Request": {
"Path": {
"Matchers": [
{
"Name": "WildcardMatcher",
"Pattern": "/mappings_static_1"
}
]
},
"Methods": [
"get"
]
},
"Response": {
"BodyAsJson": { "result": "mappings static_1" },
"Headers": {
"Content-Type": "application/json"
}
}
},
{
"Title": "2",
"Request": {
"Path": {
"Matchers": [
{
"Name": "WildcardMatcher",
"Pattern": "/mappings_static_2"
}
]
},
"Methods": [
"get"
]
},
"Response": {
"BodyAsJson": { "result": "mappings static_2" },
"Headers": {
"Content-Type": "application/json"
}
}
}
]

View File

@@ -61,6 +61,8 @@ namespace WireMock.Net.ConsoleApplication
handlebarsContext.RegisterHelper(transformer.Name, transformer.Render); handlebarsContext.RegisterHelper(transformer.Name, transformer.Render);
}, },
AllowAnyHttpStatusCodeInResponse = true
// Uncomment below if you want to use the CustomFileSystemFileHandler // Uncomment below if you want to use the CustomFileSystemFileHandler
// FileSystemHandler = new CustomFileSystemFileHandler() // FileSystemHandler = new CustomFileSystemFileHandler()
}); });
@@ -493,20 +495,6 @@ namespace WireMock.Net.ConsoleApplication
.WithBody("<xml>ok</xml>") .WithBody("<xml>ok</xml>")
); );
server
.Given(Request.Create()
.UsingPost()
.WithPath("/post_with_query")
.WithHeader("PRIVATE-TOKEN", "t")
.WithParam("name", "stef")
.WithParam("path", "p")
.WithParam("visibility", "Private")
.WithParam("parent_id", "1")
)
.RespondWith(Response.Create()
.WithBody("OK : post_with_query")
);
server.Given(Request.Create() server.Given(Request.Create()
.WithPath("/services/query/") .WithPath("/services/query/")
.WithParam("q", "SELECT Id from User where username='user@gmail.com'") .WithParam("q", "SELECT Id from User where username='user@gmail.com'")

View File

@@ -1,8 +1,8 @@
{ {
"profiles": { "profiles": {
"WireMock.Net.StandAlone.NETCoreApp": { "WireMock.Net.StandAlone.NETCoreApp": {
"commandName": "Project", "commandName": "Project",
"commandLineArgs": "--Port 9091 --WireMockLogger WireMockConsoleLogger" "commandLineArgs": "--Urls http://*:9091 --WireMockLogger WireMockConsoleLogger"
} }
} }
} }

View File

@@ -68,7 +68,7 @@ namespace WireMock.Http
return client; return client;
} }
public static async Task<ResponseMessage> SendAsync([NotNull] HttpClient client, [NotNull] RequestMessage requestMessage, string url, bool deserializeJson) public static async Task<ResponseMessage> SendAsync([NotNull] HttpClient client, [NotNull] RequestMessage requestMessage, string url)
{ {
Check.NotNull(client, nameof(client)); Check.NotNull(client, nameof(client));
Check.NotNull(requestMessage, nameof(requestMessage)); Check.NotNull(requestMessage, nameof(requestMessage));
@@ -83,7 +83,7 @@ namespace WireMock.Http
var httpResponseMessage = await client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead); var httpResponseMessage = await client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead);
// Create ResponseMessage // Create ResponseMessage
return await HttpResponseMessageHelper.CreateAsync(httpResponseMessage, requiredUri, originalUri, deserializeJson); return await HttpResponseMessageHelper.CreateAsync(httpResponseMessage, requiredUri, originalUri);
} }
} }
} }

View File

@@ -1,18 +0,0 @@
namespace WireMock.Http
{
/// <summary>
/// https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
/// </summary>
internal static class HttpRequestMethods
{
public const string CONNECT = "CONNECT";
public const string DELETE = "DELETE";
public const string GET = "GET";
public const string HEAD = "HEAD";
public const string OPTIONS = "OPTIONS";
public const string PATCH = "PATCH";
public const string POST = "POST";
public const string PUT = "PUT";
public const string TRACE = "TRACE";
}
}

View File

@@ -9,7 +9,7 @@ namespace WireMock.Http
{ {
internal static class HttpResponseMessageHelper internal static class HttpResponseMessageHelper
{ {
public static async Task<ResponseMessage> CreateAsync(HttpResponseMessage httpResponseMessage, Uri requiredUri, Uri originalUri, bool deserializeJson) public static async Task<ResponseMessage> CreateAsync(HttpResponseMessage httpResponseMessage, Uri requiredUri, Uri originalUri)
{ {
var responseMessage = new ResponseMessage { StatusCode = (int)httpResponseMessage.StatusCode }; var responseMessage = new ResponseMessage { StatusCode = (int)httpResponseMessage.StatusCode };
@@ -24,7 +24,7 @@ namespace WireMock.Http
contentTypeHeader = headers.First(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase)).Value; contentTypeHeader = headers.First(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase)).Value;
} }
responseMessage.BodyData = await BodyParser.Parse(stream, contentTypeHeader?.FirstOrDefault(), deserializeJson); responseMessage.BodyData = await BodyParser.Parse(stream, contentTypeHeader?.FirstOrDefault());
} }
foreach (var header in headers) foreach (var header in headers)

View File

@@ -1,178 +1,170 @@
#if USE_ASPNETCORE #if USE_ASPNETCORE
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using WireMock.HttpsCertificate; using WireMock.HttpsCertificate;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Owin.Mappers; using WireMock.Owin.Mappers;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation; using WireMock.Validation;
namespace WireMock.Owin namespace WireMock.Owin
{ {
internal class AspNetCoreSelfHost : IOwinSelfHost internal class AspNetCoreSelfHost : IOwinSelfHost
{ {
private readonly CancellationTokenSource _cts = new CancellationTokenSource(); private readonly CancellationTokenSource _cts = new CancellationTokenSource();
private readonly IWireMockMiddlewareOptions _options; private readonly IWireMockMiddlewareOptions _options;
private readonly IWireMockLogger _logger; private readonly string[] _urls;
private readonly HostUrlOptions _urlOptions; private readonly IWireMockLogger _logger;
private Exception _runningException;
private Exception _runningException;
private IWebHost _host; private IWebHost _host;
public bool IsStarted { get; private set; } public bool IsStarted { get; private set; }
public List<string> Urls { get; } = new List<string>(); public List<string> Urls { get; } = new List<string>();
public List<int> Ports { get; } = new List<int>(); public List<int> Ports { get; } = new List<int>();
public Exception RunningException => _runningException; public Exception RunningException => _runningException;
public AspNetCoreSelfHost([NotNull] IWireMockMiddlewareOptions options, [NotNull] HostUrlOptions urlOptions) public AspNetCoreSelfHost([NotNull] IWireMockMiddlewareOptions options, [NotNull] params string[] uriPrefixes)
{ {
Check.NotNull(options, nameof(options)); Check.NotNull(options, nameof(options));
Check.NotNull(urlOptions, nameof(urlOptions)); Check.NotNullOrEmpty(uriPrefixes, nameof(uriPrefixes));
_logger = options.Logger ?? new WireMockConsoleLogger(); _logger = options.Logger ?? new WireMockConsoleLogger();
_options = options; foreach (string uriPrefix in uriPrefixes)
_urlOptions = urlOptions; {
} Urls.Add(uriPrefix);
public Task StartAsync() PortUtils.TryExtract(uriPrefix, out string protocol, out string host, out int port);
{ Ports.Add(port);
var builder = new WebHostBuilder(); }
// Workaround for https://github.com/WireMock-Net/WireMock.Net/issues/292 _options = options;
// On some platforms, AppContext.BaseDirectory is null, which causes WebHostBuilder to fail if ContentRoot is not _urls = uriPrefixes;
// specified (even though we don't actually use that base path mechanism, since we have our own way of configuring }
// a filesystem handler).
if (string.IsNullOrEmpty(AppContext.BaseDirectory)) public Task StartAsync()
{ {
builder.UseContentRoot(System.IO.Directory.GetCurrentDirectory()); var builder = new WebHostBuilder();
}
// Workaround for https://github.com/WireMock-Net/WireMock.Net/issues/292
_host = builder // On some platforms, AppContext.BaseDirectory is null, which causes WebHostBuilder to fail if ContentRoot is not
.ConfigureServices(services => // specified (even though we don't actually use that base path mechanism, since we have our own way of configuring
{ // a filesystem handler).
services.AddSingleton(_options); if (string.IsNullOrEmpty(AppContext.BaseDirectory))
services.AddSingleton<IMappingMatcher, MappingMatcher>(); {
services.AddSingleton<IOwinRequestMapper, OwinRequestMapper>(); builder.UseContentRoot(System.IO.Directory.GetCurrentDirectory());
services.AddSingleton<IOwinResponseMapper, OwinResponseMapper>(); }
})
.Configure(appBuilder => _host = builder
{ .ConfigureServices(services =>
appBuilder.UseMiddleware<GlobalExceptionMiddleware>(); {
services.AddSingleton(_options);
_options.PreWireMockMiddlewareInit?.Invoke(appBuilder); services.AddSingleton<IMappingMatcher, MappingMatcher>();
services.AddSingleton<IOwinRequestMapper, OwinRequestMapper>();
appBuilder.UseMiddleware<WireMockMiddleware>(); services.AddSingleton<IOwinResponseMapper, OwinResponseMapper>();
})
_options.PostWireMockMiddlewareInit?.Invoke(appBuilder); .Configure(appBuilder =>
}) {
.UseKestrel(options => appBuilder.UseMiddleware<GlobalExceptionMiddleware>();
{
var urlDetails = _urlOptions.GetDetails(); _options.PreWireMockMiddlewareInit?.Invoke(appBuilder);
#if NETSTANDARD1_3 appBuilder.UseMiddleware<WireMockMiddleware>();
var urls = urlDetails.Select(u => u.Url); _options.PostWireMockMiddlewareInit?.Invoke(appBuilder);
if (urls.Any(u => u.StartsWith("https://", StringComparison.OrdinalIgnoreCase))) })
{ .UseKestrel(options =>
options.UseHttps(PublicCertificateHelper.GetX509Certificate2()); {
} #if NETSTANDARD1_3
#else if (_urls.Any(u => u.StartsWith("https://", StringComparison.OrdinalIgnoreCase)))
foreach (var detail in urlDetails) {
{ options.UseHttps(PublicCertificateHelper.GetX509Certificate2());
if (detail.Url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) }
{ #else
options.Listen(System.Net.IPAddress.Any, detail.Port, listenOptions => // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?tabs=aspnetcore2x
{ foreach (string url in _urls.Where(u => u.StartsWith("http://", StringComparison.OrdinalIgnoreCase)))
listenOptions.UseHttps(); // PublicCertificateHelper.GetX509Certificate2() {
}); PortUtils.TryExtract(url, out string protocol, out string host, out int port);
} options.Listen(System.Net.IPAddress.Any, port);
else }
{
options.Listen(System.Net.IPAddress.Any, detail.Port); foreach (string url in _urls.Where(u => u.StartsWith("https://", StringComparison.OrdinalIgnoreCase)))
} {
} PortUtils.TryExtract(url, out string protocol, out string host, out int port);
#endif options.Listen(System.Net.IPAddress.Any, port, listenOptions =>
}) {
listenOptions.UseHttps(); // PublicCertificateHelper.GetX509Certificate2()
#if NETSTANDARD1_3 });
.UseUrls(_urlOptions.GetDetails().Select(u => u.Url).ToArray()) }
#endif #endif
.Build(); })
#if NETSTANDARD1_3
return RunHost(_cts.Token); .UseUrls(_urls)
} #endif
.Build();
private Task RunHost(CancellationToken token)
{ return RunHost(_cts.Token);
try }
{
var appLifetime = (IApplicationLifetime)_host.Services.GetService(typeof(IApplicationLifetime)); private Task RunHost(CancellationToken token)
appLifetime.ApplicationStarted.Register(() => {
{ try
var addresses = _host.ServerFeatures {
.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>() var appLifetime = (IApplicationLifetime)_host.Services.GetService(typeof(IApplicationLifetime));
.Addresses; appLifetime.ApplicationStarted.Register(() =>
{
foreach (string address in addresses) IsStarted = true;
{ });
Urls.Add(address.Replace("0.0.0.0", "localhost"));
#if NETSTANDARD1_3
PortUtils.TryExtract(address, out string protocol, out string host, out int port); _logger.Info("WireMock.Net server using netstandard1.3");
Ports.Add(port); #elif NETSTANDARD2_0
} _logger.Info("WireMock.Net server using netstandard2.0");
#elif NET46
IsStarted = true; _logger.Info("WireMock.Net server using .net 4.6.1 or higher");
}); #endif
#if NETSTANDARD1_3
#if NETSTANDARD1_3 return Task.Run(() =>
_logger.Info("WireMock.Net server using netstandard1.3"); {
#elif NETSTANDARD2_0 _host.Run(token);
_logger.Info("WireMock.Net server using netstandard2.0"); });
#elif NET46 #else
_logger.Info("WireMock.Net server using .net 4.6.1 or higher"); return _host.RunAsync(token);
#endif #endif
#if NETSTANDARD1_3 }
return Task.Run(() => catch (Exception e)
{ {
_host.Run(token); _runningException = e;
}); _logger.Error(e.ToString());
#else
return _host.RunAsync(token); IsStarted = false;
#endif
} return Task.CompletedTask;
catch (Exception e) }
{ }
_runningException = e;
_logger.Error(e.ToString()); public Task StopAsync()
{
IsStarted = false; _cts.Cancel();
return Task.CompletedTask; IsStarted = false;
} #if NETSTANDARD1_3
} return Task.FromResult(true);
#else
public Task StopAsync() return _host.StopAsync();
{ #endif
_cts.Cancel(); }
}
IsStarted = false; }
#if NETSTANDARD1_3
return Task.FromResult(true);
#else
return _host.StopAsync();
#endif
}
}
}
#endif #endif

View File

@@ -1,43 +0,0 @@
using System.Collections.Generic;
using WireMock.Util;
namespace WireMock.Owin
{
internal class HostUrlOptions
{
public ICollection<string> Urls { get; set; }
public int? Port { get; set; }
public bool UseSSL { get; set; }
public ICollection<(string Url, int Port)> GetDetails()
{
var list = new List<(string Url, int Port)>();
if (Urls == null)
{
int port = Port ?? FindFreeTcpPort();
list.Add(($"{(UseSSL ? "https" : "http")}://localhost:{port}", port));
}
else
{
foreach (string url in Urls)
{
PortUtils.TryExtract(url, out string protocol, out string host, out int port);
list.Add((url, port));
}
}
return list;
}
private int FindFreeTcpPort()
{
#if USE_ASPNETCORE || NETSTANDARD2_0
return 0;
#else
return PortUtils.FindFreeTcpPort();
#endif
}
}
}

View File

@@ -40,8 +40,6 @@ namespace WireMock.Owin
bool? AllowBodyForAllHttpMethods { get; set; } bool? AllowBodyForAllHttpMethods { get; set; }
bool? AllowOnlyDefinedHttpStatusCodeInResponse { get; set; } bool? AllowAnyHttpStatusCodeInResponse { get; set; }
bool? DisableJsonBodyParsing { get; set; }
} }
} }

View File

@@ -49,7 +49,7 @@ namespace WireMock.Owin.Mappers
BodyData body = null; BodyData body = null;
if (request.Body != null && BodyParser.ShouldParseBody(method, options.AllowBodyForAllHttpMethods == true)) if (request.Body != null && BodyParser.ShouldParseBody(method, options.AllowBodyForAllHttpMethods == true))
{ {
body = await BodyParser.Parse(request.Body, request.ContentType, !options.DisableJsonBodyParsing.GetValueOrDefault(false)); body = await BodyParser.Parse(request.Body, request.ContentType);
} }
return new RequestMessage(urldetails, method, clientIP, body, headers, cookies) { DateTime = DateTime.UtcNow }; return new RequestMessage(urldetails, method, clientIP, body, headers, cookies) { DateTime = DateTime.UtcNow };

View File

@@ -104,12 +104,12 @@ namespace WireMock.Owin.Mappers
private int MapStatusCode(int code) private int MapStatusCode(int code)
{ {
if (_options.AllowOnlyDefinedHttpStatusCodeInResponse == true && !Enum.IsDefined(typeof(HttpStatusCode), code)) if (_options.AllowAnyHttpStatusCodeInResponse == true || Enum.IsDefined(typeof(HttpStatusCode), code))
{ {
return (int)HttpStatusCode.OK; return code;
} }
return code; return (int)HttpStatusCode.OK;
} }
private bool IsFault(ResponseMessage responseMessage) private bool IsFault(ResponseMessage responseMessage)

View File

@@ -8,6 +8,7 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Owin.Mappers; using WireMock.Owin.Mappers;
using WireMock.Util;
using WireMock.Validation; using WireMock.Validation;
namespace WireMock.Owin namespace WireMock.Owin
@@ -17,22 +18,24 @@ namespace WireMock.Owin
private readonly IWireMockMiddlewareOptions _options; private readonly IWireMockMiddlewareOptions _options;
private readonly CancellationTokenSource _cts = new CancellationTokenSource(); private readonly CancellationTokenSource _cts = new CancellationTokenSource();
private readonly IWireMockLogger _logger; private readonly IWireMockLogger _logger;
private Exception _runningException; private Exception _runningException;
public OwinSelfHost([NotNull] IWireMockMiddlewareOptions options, [NotNull] HostUrlOptions urlOptions) public OwinSelfHost([NotNull] IWireMockMiddlewareOptions options, [NotNull] params string[] uriPrefixes)
{ {
Check.NotNull(options, nameof(options)); Check.NotNull(options, nameof(options));
Check.NotNull(urlOptions, nameof(urlOptions)); Check.NotNullOrEmpty(uriPrefixes, nameof(uriPrefixes));
_options = options;
_logger = options.Logger ?? new WireMockConsoleLogger(); _logger = options.Logger ?? new WireMockConsoleLogger();
foreach (var detail in urlOptions.GetDetails()) foreach (string uriPrefix in uriPrefixes)
{ {
Urls.Add(detail.Url); Urls.Add(uriPrefix);
Ports.Add(detail.Port);
PortUtils.TryExtract(uriPrefix, out string protocol, out string host, out int port);
Ports.Add(port);
} }
_options = options;
} }
public bool IsStarted { get; private set; } public bool IsStarted { get; private set; }

View File

@@ -43,10 +43,7 @@ namespace WireMock.Owin
/// <inheritdoc cref="IWireMockMiddlewareOptions.AllowBodyForAllHttpMethods"/> /// <inheritdoc cref="IWireMockMiddlewareOptions.AllowBodyForAllHttpMethods"/>
public bool? AllowBodyForAllHttpMethods { get; set; } public bool? AllowBodyForAllHttpMethods { get; set; }
/// <inheritdoc cref="IWireMockMiddlewareOptions.AllowOnlyDefinedHttpStatusCodeInResponse"/> /// <inheritdoc cref="IWireMockMiddlewareOptions.AllowAnyHttpStatusCodeInResponse"/>
public bool? AllowOnlyDefinedHttpStatusCodeInResponse { get; set; } public bool? AllowAnyHttpStatusCodeInResponse { get; set; }
/// <inheritdoc cref="IWireMockMiddlewareOptions.DisableResponseBodyParsing"/>
public bool? DisableJsonBodyParsing { get; set; }
} }
} }

View File

@@ -9,13 +9,6 @@ namespace WireMock.RequestBuilders
/// </summary> /// </summary>
public interface IMethodRequestBuilder : IHeadersRequestBuilder public interface IMethodRequestBuilder : IHeadersRequestBuilder
{ {
/// <summary>
/// UsingConnect: add HTTP Method matching on `CONNECT` and matchBehaviour (optional).
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder UsingConnect(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary> /// <summary>
/// UsingDelete: add HTTP Method matching on `DELETE` and matchBehaviour (optional). /// UsingDelete: add HTTP Method matching on `DELETE` and matchBehaviour (optional).
/// </summary> /// </summary>
@@ -31,7 +24,7 @@ namespace WireMock.RequestBuilders
IRequestBuilder UsingGet(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); IRequestBuilder UsingGet(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary> /// <summary>
/// UsingHead: Add HTTP Method matching on `HEAD` and matchBehaviour (optional). /// Add HTTP Method matching on `HEAD` and matchBehaviour (optional).
/// </summary> /// </summary>
/// <param name="matchBehaviour">The match behaviour.</param> /// <param name="matchBehaviour">The match behaviour.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
@@ -51,13 +44,6 @@ namespace WireMock.RequestBuilders
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder UsingPatch(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); IRequestBuilder UsingPatch(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary>
/// UsingPut: add HTTP Method matching on `OPTIONS` and matchBehaviour (optional).
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder UsingOptions(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary> /// <summary>
/// UsingPut: add HTTP Method matching on `PUT` and matchBehaviour (optional). /// UsingPut: add HTTP Method matching on `PUT` and matchBehaviour (optional).
/// </summary> /// </summary>
@@ -65,13 +51,6 @@ namespace WireMock.RequestBuilders
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder UsingPut(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); IRequestBuilder UsingPut(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary>
/// UsingTrace: add HTTP Method matching on `TRACE` and matchBehaviour (optional).
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder UsingTrace(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary> /// <summary>
/// UsingAnyMethod: add HTTP Method matching on any method. /// UsingAnyMethod: add HTTP Method matching on any method.
/// </summary> /// </summary>

View File

@@ -1,113 +0,0 @@
using System.Linq;
using WireMock.Http;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.Validation;
namespace WireMock.RequestBuilders
{
public partial class Request
{
/// <inheritdoc cref="IMethodRequestBuilder.UsingConnect(MatchBehaviour)"/>
public IRequestBuilder UsingConnect(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, HttpRequestMethods.CONNECT));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingDelete(MatchBehaviour)"/>
public IRequestBuilder UsingDelete(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, HttpRequestMethods.DELETE));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingGet(MatchBehaviour)"/>
public IRequestBuilder UsingGet(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, HttpRequestMethods.GET));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingHead(MatchBehaviour)"/>
public IRequestBuilder UsingHead(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, HttpRequestMethods.HEAD));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingOptions(MatchBehaviour)"/>
public IRequestBuilder UsingOptions(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, HttpRequestMethods.OPTIONS));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingPost(MatchBehaviour)"/>
public IRequestBuilder UsingPost(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, HttpRequestMethods.POST));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingPatch(MatchBehaviour)"/>
public IRequestBuilder UsingPatch(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, HttpRequestMethods.PATCH));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingPut(MatchBehaviour)"/>
public IRequestBuilder UsingPut(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, HttpRequestMethods.PUT));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingTrace(MatchBehaviour)"/>
public IRequestBuilder UsingTrace(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, HttpRequestMethods.TRACE));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingAnyMethod"/>
public IRequestBuilder UsingAnyMethod()
{
var matchers = _requestMatchers.Where(m => m is RequestMessageMethodMatcher).ToList();
foreach (var matcher in matchers)
{
_requestMatchers.Remove(matcher);
}
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingAnyVerb"/>
public IRequestBuilder UsingAnyVerb()
{
return UsingAnyMethod();
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingMethod(string[])"/>
public IRequestBuilder UsingMethod(params string[] methods)
{
return UsingMethod(MatchBehaviour.AcceptOnMatch, methods);
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingVerb(string[])"/>
public IRequestBuilder UsingVerb(params string[] verbs)
{
return UsingMethod(verbs);
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingMethod(MatchBehaviour, string[])"/>
public IRequestBuilder UsingMethod(MatchBehaviour matchBehaviour, params string[] methods)
{
Check.NotNullOrEmpty(methods, nameof(methods));
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, methods));
return this;
}
}
}

View File

@@ -151,5 +151,86 @@ namespace WireMock.RequestBuilders
_requestMatchers.Add(new RequestMessageUrlMatcher(funcs)); _requestMatchers.Add(new RequestMessageUrlMatcher(funcs));
return this; return this;
} }
/// <inheritdoc cref="IMethodRequestBuilder.UsingDelete(MatchBehaviour)"/>
public IRequestBuilder UsingDelete(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, "DELETE"));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingGet(MatchBehaviour)"/>
public IRequestBuilder UsingGet(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, "GET"));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingHead(MatchBehaviour)"/>
public IRequestBuilder UsingHead(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, "HEAD"));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingPost(MatchBehaviour)"/>
public IRequestBuilder UsingPost(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, "POST"));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingPatch(MatchBehaviour)"/>
public IRequestBuilder UsingPatch(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, "PATCH"));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingPut(MatchBehaviour)"/>
public IRequestBuilder UsingPut(MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, "PUT"));
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingAnyMethod"/>
public IRequestBuilder UsingAnyMethod()
{
var matchers = _requestMatchers.Where(m => m is RequestMessageMethodMatcher).ToList();
foreach (var matcher in matchers)
{
_requestMatchers.Remove(matcher);
}
return this;
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingAnyVerb"/>
public IRequestBuilder UsingAnyVerb()
{
return UsingAnyMethod();
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingMethod(string[])"/>
public IRequestBuilder UsingMethod(params string[] methods)
{
return UsingMethod(MatchBehaviour.AcceptOnMatch, methods);
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingVerb(string[])"/>
public IRequestBuilder UsingVerb(params string[] verbs)
{
return UsingMethod(verbs);
}
/// <inheritdoc cref="IMethodRequestBuilder.UsingMethod(MatchBehaviour, string[])"/>
public IRequestBuilder UsingMethod(MatchBehaviour matchBehaviour, params string[] methods)
{
Check.NotNullOrEmpty(methods, nameof(methods));
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, methods));
return this;
}
} }
} }

View File

@@ -1,5 +1,4 @@
using System.Net; using System.Net;
using WireMock.Settings;
namespace WireMock.ResponseBuilders namespace WireMock.ResponseBuilders
{ {
@@ -10,7 +9,6 @@ namespace WireMock.ResponseBuilders
{ {
/// <summary> /// <summary>
/// The with status code. /// The with status code.
/// By default all status codes are allowed, to change this behaviour, see <inheritdoc cref="IWireMockServerSettings.AllowOnlyDefinedHttpStatusCodeInResponse"/>.
/// </summary> /// </summary>
/// <param name="code">The code.</param> /// <param name="code">The code.</param>
/// <returns>The <see cref="IResponseBuilder"/>.</returns> /// <returns>The <see cref="IResponseBuilder"/>.</returns>
@@ -18,7 +16,6 @@ namespace WireMock.ResponseBuilders
/// <summary> /// <summary>
/// The with status code. /// The with status code.
/// By default all status codes are allowed, to change this behaviour, see <inheritdoc cref="IWireMockServerSettings.AllowOnlyDefinedHttpStatusCodeInResponse"/>.
/// </summary> /// </summary>
/// <param name="code">The code.</param> /// <param name="code">The code.</param>
/// <returns>The <see cref="IResponseBuilder"/>.</returns> /// <returns>The <see cref="IResponseBuilder"/>.</returns>
@@ -26,7 +23,6 @@ namespace WireMock.ResponseBuilders
/// <summary> /// <summary>
/// The with status code. /// The with status code.
/// By default all status codes are allowed, to change this behaviour, see <inheritdoc cref="IWireMockServerSettings.AllowOnlyDefinedHttpStatusCodeInResponse"/>.
/// </summary> /// </summary>
/// <param name="code">The code.</param> /// <param name="code">The code.</param>
/// <returns>The <see cref="IResponseBuilder"/>.</returns> /// <returns>The <see cref="IResponseBuilder"/>.</returns>

View File

@@ -345,7 +345,7 @@ namespace WireMock.ResponseBuilders
var proxyUri = new Uri(ProxyUrl); var proxyUri = new Uri(ProxyUrl);
var proxyUriWithRequestPathAndQuery = new Uri(proxyUri, requestUri.PathAndQuery); var proxyUriWithRequestPathAndQuery = new Uri(proxyUri, requestUri.PathAndQuery);
return await HttpClientHelper.SendAsync(_httpClientForProxy, requestMessage, proxyUriWithRequestPathAndQuery.AbsoluteUri, !settings.DisableJsonBodyParsing.GetValueOrDefault(false)); return await HttpClientHelper.SendAsync(_httpClientForProxy, requestMessage, proxyUriWithRequestPathAndQuery.AbsoluteUri);
} }
ResponseMessage responseMessage; ResponseMessage responseMessage;

View File

@@ -275,7 +275,7 @@ namespace WireMock.Server
var proxyUri = new Uri(settings.ProxyAndRecordSettings.Url); var proxyUri = new Uri(settings.ProxyAndRecordSettings.Url);
var proxyUriWithRequestPathAndQuery = new Uri(proxyUri, requestUri.PathAndQuery); var proxyUriWithRequestPathAndQuery = new Uri(proxyUri, requestUri.PathAndQuery);
var responseMessage = await HttpClientHelper.SendAsync(_httpClientForProxy, requestMessage, proxyUriWithRequestPathAndQuery.AbsoluteUri, !settings.DisableJsonBodyParsing.GetValueOrDefault(false)); var responseMessage = await HttpClientHelper.SendAsync(_httpClientForProxy, requestMessage, proxyUriWithRequestPathAndQuery.AbsoluteUri);
if (HttpStatusRangeParser.IsMatch(settings.ProxyAndRecordSettings.SaveMappingForStatusCodePattern, responseMessage.StatusCode) && if (HttpStatusRangeParser.IsMatch(settings.ProxyAndRecordSettings.SaveMappingForStatusCodePattern, responseMessage.StatusCode) &&
(settings.ProxyAndRecordSettings.SaveMapping || settings.ProxyAndRecordSettings.SaveMappingToFile)) (settings.ProxyAndRecordSettings.SaveMapping || settings.ProxyAndRecordSettings.SaveMappingToFile))

View File

@@ -202,37 +202,31 @@ namespace WireMock.Server
_settings.Logger.Info("WireMock.Net by Stef Heyenrath (https://github.com/WireMock-Net/WireMock.Net)"); _settings.Logger.Info("WireMock.Net by Stef Heyenrath (https://github.com/WireMock-Net/WireMock.Net)");
_settings.Logger.Debug("WireMock.Net server settings {0}", JsonConvert.SerializeObject(settings, Formatting.Indented)); _settings.Logger.Debug("WireMock.Net server settings {0}", JsonConvert.SerializeObject(settings, Formatting.Indented));
HostUrlOptions urlOptions;
if (settings.Urls != null) if (settings.Urls != null)
{ {
urlOptions = new HostUrlOptions Urls = settings.Urls.ToArray();
{
Urls = settings.Urls
};
} }
else else
{ {
urlOptions = new HostUrlOptions int port = settings.Port > 0 ? settings.Port.Value : PortUtils.FindFreeTcpPort();
{ Urls = new[] { $"{(settings.UseSSL == true ? "https" : "http")}://localhost:{port}" };
UseSSL = settings.UseSSL == true,
Port = settings.Port
};
} }
_options.FileSystemHandler = _settings.FileSystemHandler; _options.FileSystemHandler = _settings.FileSystemHandler;
_options.PreWireMockMiddlewareInit = _settings.PreWireMockMiddlewareInit; _options.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit;
_options.PostWireMockMiddlewareInit = _settings.PostWireMockMiddlewareInit; _options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit;
_options.Logger = _settings.Logger; _options.Logger = _settings.Logger;
_options.DisableJsonBodyParsing = _settings.DisableJsonBodyParsing;
_matcherMapper = new MatcherMapper(_settings); _matcherMapper = new MatcherMapper(_settings);
_mappingConverter = new MappingConverter(_matcherMapper); _mappingConverter = new MappingConverter(_matcherMapper);
#if USE_ASPNETCORE #if USE_ASPNETCORE
_httpServer = new AspNetCoreSelfHost(_options, urlOptions); _httpServer = new AspNetCoreSelfHost(_options, Urls);
#else #else
_httpServer = new OwinSelfHost(_options, urlOptions); _httpServer = new OwinSelfHost(_options, Urls);
#endif #endif
Ports = _httpServer.Ports;
var startTask = _httpServer.StartAsync(); var startTask = _httpServer.StartAsync();
using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout)) using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout))
@@ -259,9 +253,6 @@ namespace WireMock.Server
ctsStartTimeout.Token.WaitHandle.WaitOne(ServerStartDelayInMs); ctsStartTimeout.Token.WaitHandle.WaitOne(ServerStartDelayInMs);
} }
Urls = _httpServer.Urls.ToArray();
Ports = _httpServer.Ports;
} }
if (settings.AllowBodyForAllHttpMethods == true) if (settings.AllowBodyForAllHttpMethods == true)
@@ -270,10 +261,10 @@ namespace WireMock.Server
_settings.Logger.Info("AllowBodyForAllHttpMethods is set to True"); _settings.Logger.Info("AllowBodyForAllHttpMethods is set to True");
} }
if (settings.AllowOnlyDefinedHttpStatusCodeInResponse == true) if (settings.AllowAnyHttpStatusCodeInResponse == true)
{ {
_options.AllowOnlyDefinedHttpStatusCodeInResponse = _settings.AllowOnlyDefinedHttpStatusCodeInResponse; _options.AllowAnyHttpStatusCodeInResponse = _settings.AllowAnyHttpStatusCodeInResponse;
_settings.Logger.Info("AllowOnlyDefinedHttpStatusCodeInResponse is set to True"); _settings.Logger.Info("AllowAnyHttpStatusCodeInResponse is set to True");
} }
if (settings.AllowPartialMapping == true) if (settings.AllowPartialMapping == true)

View File

@@ -139,17 +139,9 @@ namespace WireMock.Settings
bool? AllowBodyForAllHttpMethods { get; set; } bool? AllowBodyForAllHttpMethods { get; set; }
/// <summary> /// <summary>
/// Allow only a HttpStatus Code in the response which is defined. (default set to false). /// Allow any HttpStatusCode in the response. Also null, 0, empty or invalid. (default set to false).
/// - false : also null, 0, empty or invalid HttpStatus codes are allowed.
/// - true : only codes defined in <see cref="System.Net.HttpStatusCode"/> are allowed.
/// </summary> /// </summary>
/// [PublicAPI] /// [PublicAPI]
bool? AllowOnlyDefinedHttpStatusCodeInResponse { get; set; } bool? AllowAnyHttpStatusCodeInResponse { get; set; }
/// <summary>
/// Set to true to disable Json deserialization when processing requests. (default set to false).
/// </summary>
[PublicAPI]
bool? DisableJsonBodyParsing { get; set; }
} }
} }

View File

@@ -102,11 +102,7 @@ namespace WireMock.Settings
[PublicAPI] [PublicAPI]
public bool? AllowBodyForAllHttpMethods { get; set; } public bool? AllowBodyForAllHttpMethods { get; set; }
/// <inheritdoc cref="IWireMockServerSettings.AllowOnlyDefinedHttpStatusCodeInResponse"/> /// <inheritdoc cref="IWireMockServerSettings.AllowAnyHttpStatusCodeInResponse"/>
public bool? AllowOnlyDefinedHttpStatusCodeInResponse { get; set; } public bool? AllowAnyHttpStatusCodeInResponse { get; set; }
/// <inheritdoc cref="IWireMockServerSettings.DisableJsonBodyParsing"/>
[PublicAPI]
public bool? DisableJsonBodyParsing { get; set; }
} }
} }

View File

@@ -35,8 +35,7 @@ namespace WireMock.Settings
RequestLogExpirationDuration = parser.GetIntValue("RequestLogExpirationDuration"), RequestLogExpirationDuration = parser.GetIntValue("RequestLogExpirationDuration"),
AllowCSharpCodeMatcher = parser.GetBoolValue("AllowCSharpCodeMatcher"), AllowCSharpCodeMatcher = parser.GetBoolValue("AllowCSharpCodeMatcher"),
AllowBodyForAllHttpMethods = parser.GetBoolValue("AllowBodyForAllHttpMethods"), AllowBodyForAllHttpMethods = parser.GetBoolValue("AllowBodyForAllHttpMethods"),
AllowOnlyDefinedHttpStatusCodeInResponse = parser.GetBoolValue("AllowOnlyDefinedHttpStatusCodeInResponse"), AllowAnyHttpStatusCodeInResponse = parser.GetBoolValue("AllowAnyHttpStatusCodeInResponse")
DisableJsonBodyParsing = parser.GetBoolValue("DisableJsonBodyParsing")
}; };
if (logger != null) if (logger != null)

View File

@@ -30,7 +30,7 @@ namespace WireMock.Transformers
var template = new { request = requestMessage }; var template = new { request = requestMessage };
switch (original.BodyData?.DetectedBodyType) switch (original.BodyData.DetectedBodyType)
{ {
case BodyType.Json: case BodyType.Json:
TransformBodyAsJson(handlebarsContext.Handlebars, template, original, responseMessage); TransformBodyAsJson(handlebarsContext.Handlebars, template, original, responseMessage);

View File

@@ -6,7 +6,6 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
using Newtonsoft.Json; using Newtonsoft.Json;
using WireMock.Http;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Types; using WireMock.Types;
using WireMock.Validation; using WireMock.Validation;
@@ -31,15 +30,15 @@ namespace WireMock.Util
*/ */
private static readonly IDictionary<string, bool> BodyAllowedForMethods = new Dictionary<string, bool> private static readonly IDictionary<string, bool> BodyAllowedForMethods = new Dictionary<string, bool>
{ {
{ HttpRequestMethods.HEAD, false }, { "HEAD", false },
{ HttpRequestMethods.GET, false }, { "GET", false },
{ HttpRequestMethods.PUT, true }, { "PUT", true },
{ HttpRequestMethods.POST, true }, { "POST", true },
{ HttpRequestMethods.DELETE, true }, { "DELETE", true },
{ HttpRequestMethods.TRACE, false }, { "TRACE", false },
{ HttpRequestMethods.OPTIONS, true }, { "OPTIONS", true },
{ HttpRequestMethods.CONNECT, false }, { "CONNECT", false },
{ HttpRequestMethods.PATCH, true } { "PATCH", true }
}; };
private static readonly IStringMatcher[] MultipartContentTypesMatchers = { private static readonly IStringMatcher[] MultipartContentTypesMatchers = {
@@ -108,7 +107,7 @@ namespace WireMock.Util
return BodyType.Bytes; return BodyType.Bytes;
} }
public static async Task<BodyData> Parse([NotNull] Stream stream, [CanBeNull] string contentType = null, bool deserializeJson = true) public static async Task<BodyData> Parse([NotNull] Stream stream, [CanBeNull] string contentType)
{ {
Check.NotNull(stream, nameof(stream)); Check.NotNull(stream, nameof(stream));
@@ -128,6 +127,8 @@ namespace WireMock.Util
data.BodyAsString = encoding.GetString(data.BodyAsBytes); data.BodyAsString = encoding.GetString(data.BodyAsBytes);
data.Encoding = encoding; data.Encoding = encoding;
data.DetectedBodyType = BodyType.String; data.DetectedBodyType = BodyType.String;
return data;
} }
return data; return data;
@@ -141,7 +142,7 @@ namespace WireMock.Util
data.DetectedBodyType = BodyType.String; data.DetectedBodyType = BodyType.String;
// If string is not null or empty, try to deserialize the string to a JObject // If string is not null or empty, try to deserialize the string to a JObject
if (deserializeJson && !string.IsNullOrEmpty(data.BodyAsString)) if (!string.IsNullOrEmpty(data.BodyAsString))
{ {
try try
{ {

View File

@@ -96,7 +96,7 @@ namespace WireMock.Net.Tests
var listOfTasks = new List<Task<HttpResponseMessage>>(); var listOfTasks = new List<Task<HttpResponseMessage>>();
for (var i = 0; i < expectedCount; i++) for (var i = 0; i < expectedCount; i++)
{ {
Thread.Sleep(50); Thread.Sleep(10);
listOfTasks.Add(http.GetAsync($"{server.Urls[0]}{path}")); listOfTasks.Add(http.GetAsync($"{server.Urls[0]}{path}"));
} }
var responses = await Task.WhenAll(listOfTasks); var responses = await Task.WhenAll(listOfTasks);

View File

@@ -69,33 +69,14 @@ namespace WireMock.Net.Tests.Owin.Mappers
await _sut.MapAsync(null, _responseMock.Object); await _sut.MapAsync(null, _responseMock.Object);
} }
[Theory]
[InlineData(300, 300)]
[InlineData(500, 500)]
public async Task OwinResponseMapper_MapAsync_Valid_StatusCode(object code, int expected)
{
// Arrange
var responseMessage = new ResponseMessage
{
StatusCode = code
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object);
// Assert
_responseMock.VerifySet(r => r.StatusCode = expected, Times.Once);
}
[Theory] [Theory]
[InlineData(0, 200)] [InlineData(0, 200)]
[InlineData(-1, 200)] [InlineData(-1, 200)]
[InlineData(10000, 200)] [InlineData(10000, 200)]
[InlineData(300, 300)] [InlineData(300, 300)]
public async Task OwinResponseMapper_MapAsync_Invalid_StatusCode_When_AllowOnlyDefinedHttpStatusCodeInResponseSet_Is_True(object code, int expected) public async Task OwinResponseMapper_MapAsync_StatusCode(object code, int expected)
{ {
// Arrange // Arrange
_optionsMock.SetupGet(o => o.AllowOnlyDefinedHttpStatusCodeInResponse).Returns(true);
var responseMessage = new ResponseMessage var responseMessage = new ResponseMessage
{ {
StatusCode = code StatusCode = code
@@ -109,24 +90,7 @@ namespace WireMock.Net.Tests.Owin.Mappers
} }
[Fact] [Fact]
public async Task OwinResponseMapper_MapAsync_Null_StatusCode_When_AllowOnlyDefinedHttpStatusCodeInResponseSet_Is_True() public async Task OwinResponseMapper_MapAsync_StatusCodeNull()
{
// Arrange
_optionsMock.SetupGet(o => o.AllowOnlyDefinedHttpStatusCodeInResponse).Returns(true);
var responseMessage = new ResponseMessage
{
StatusCode = null
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object);
// Assert
_responseMock.VerifyNoOtherCalls();
}
[Fact]
public async Task OwinResponseMapper_MapAsync_StatusCode_Is_Null()
{ {
// Arrange // Arrange
var responseMessage = new ResponseMessage var responseMessage = new ResponseMessage
@@ -146,9 +110,10 @@ namespace WireMock.Net.Tests.Owin.Mappers
[InlineData(-1, -1)] [InlineData(-1, -1)]
[InlineData(10000, 10000)] [InlineData(10000, 10000)]
[InlineData(300, 300)] [InlineData(300, 300)]
public async Task OwinResponseMapper_MapAsync_StatusCode_Is_NotInEnumRange(object code, int expected) public async Task OwinResponseMapper_MapAsync_StatusCode_WithAllowAll(object code, int expected)
{ {
// Arrange // Arrange
_optionsMock.SetupGet(o => o.AllowAnyHttpStatusCodeInResponse).Returns(true);
var responseMessage = new ResponseMessage var responseMessage = new ResponseMessage
{ {
StatusCode = code StatusCode = code
@@ -161,6 +126,23 @@ namespace WireMock.Net.Tests.Owin.Mappers
_responseMock.VerifySet(r => r.StatusCode = expected, Times.Once); _responseMock.VerifySet(r => r.StatusCode = expected, Times.Once);
} }
[Fact]
public async Task OwinResponseMapper_MapAsync_StatusCode_WithAllowAll_Null()
{
// Arrange
_optionsMock.SetupGet(o => o.AllowAnyHttpStatusCodeInResponse).Returns(true);
var responseMessage = new ResponseMessage
{
StatusCode = null
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object);
// Assert
_responseMock.VerifyNoOtherCalls();
}
[Fact] [Fact]
public async Task OwinResponseMapper_MapAsync_NoBody() public async Task OwinResponseMapper_MapAsync_NoBody()
{ {

View File

@@ -8,54 +8,18 @@ namespace WireMock.Net.Tests.RequestBuilders
{ {
public class RequestBuilderUsingMethodTests public class RequestBuilderUsingMethodTests
{ {
[Fact]
public void RequestBuilder_UsingConnect()
{
// Act
var requestBuilder = (Request)Request.Create().UsingConnect();
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count).IsEqualTo(1);
Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("CONNECT");
}
[Fact]
public void RequestBuilder_UsingOptions()
{
// Act
var requestBuilder = (Request)Request.Create().UsingOptions();
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count).IsEqualTo(1);
Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("OPTIONS");
}
[Fact] [Fact]
public void RequestBuilder_UsingPatch() public void RequestBuilder_UsingPatch()
{ {
// Act // Act
var requestBuilder = (Request)Request.Create().UsingPatch(); var requestBuilder = (Request)Request.Create().UsingPatch();
// Assert // Assert 1
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers"); var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count).IsEqualTo(1); Check.That(matchers.Count).IsEqualTo(1);
Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("PATCH"); Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("PATCH");
} }
[Fact]
public void RequestBuilder_UsingTrace()
{
// Act
var requestBuilder = (Request)Request.Create().UsingTrace();
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count).IsEqualTo(1);
Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("TRACE");
}
[Fact] [Fact]
public void RequestBuilder_UsingAnyMethod_ClearsAllOtherMatches() public void RequestBuilder_UsingAnyMethod_ClearsAllOtherMatches()
{ {

View File

@@ -243,9 +243,9 @@ namespace WireMock.Net.Tests.RequestMatchers
// assign // assign
BodyData bodyData; BodyData bodyData;
if (body is byte[] b) if (body is byte[] b)
bodyData = await BodyParser.Parse(new MemoryStream(b), null, true); bodyData = await BodyParser.Parse(new MemoryStream(b), null);
else if (body is string s) else if (body is string s)
bodyData = await BodyParser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(s)), null, true); bodyData = await BodyParser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(s)), null);
else else
throw new Exception(); throw new Exception();

View File

@@ -2,7 +2,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using FluentAssertions;
using Moq; using Moq;
using Newtonsoft.Json; using Newtonsoft.Json;
using NFluent; using NFluent;
@@ -25,23 +24,6 @@ namespace WireMock.Net.Tests.ResponseBuilders
{ {
private readonly WireMockServerSettings _settings = new WireMockServerSettings(); private readonly WireMockServerSettings _settings = new WireMockServerSettings();
private const string ClientIp = "::1"; private const string ClientIp = "::1";
[Fact]
public async Task Response_ProvideResponse_Handlebars_WithNullBody_ShouldNotThrowException()
{
// Assign
var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
var request = new RequestMessage(urlDetails, "GET", ClientIp);
var response = Response.Create()
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request, _settings);
// Assert
responseMessage.BodyData.Should().BeNull();
}
[Fact] [Fact]
public async Task Response_ProvideResponse_Handlebars_UrlPathVerb() public async Task Response_ProvideResponse_Handlebars_UrlPathVerb()
@@ -65,14 +47,12 @@ namespace WireMock.Net.Tests.ResponseBuilders
Check.That(responseMessage.BodyData.BodyAsString).Equals("test http://localhost/foo /foo POSt"); Check.That(responseMessage.BodyData.BodyAsString).Equals("test http://localhost/foo /foo POSt");
} }
[Theory] [Fact]
[InlineData("Get")] public async Task Response_ProvideResponse_Handlebars_UrlPath()
[InlineData("Post")]
public async Task Response_ProvideResponse_Handlebars_UrlPath(string httpMethod)
{ {
// Assign // Assign
var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock")); var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
var request = new RequestMessage(urlDetails, httpMethod, ClientIp); var request = new RequestMessage(urlDetails, "POST", ClientIp);
var response = Response.Create() var response = Response.Create()
.WithBody("{{request.url}} {{request.absoluteurl}} {{request.path}} {{request.absolutepath}}") .WithBody("{{request.url}} {{request.absoluteurl}} {{request.path}} {{request.absolutepath}}")

View File

@@ -22,7 +22,7 @@ namespace WireMock.Net.Tests.Util
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsJson)); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsJson));
// Act // Act
var body = await BodyParser.Parse(memoryStream, contentType, true); var body = await BodyParser.Parse(memoryStream, contentType);
// Assert // Assert
Check.That(body.BodyAsBytes).IsNotNull(); Check.That(body.BodyAsBytes).IsNotNull();
@@ -41,7 +41,7 @@ namespace WireMock.Net.Tests.Util
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString)); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString));
// Act // Act
var body = await BodyParser.Parse(memoryStream, contentType, true); var body = await BodyParser.Parse(memoryStream, contentType);
// Assert // Assert
Check.That(body.BodyAsBytes).IsNotNull(); Check.That(body.BodyAsBytes).IsNotNull();
@@ -61,23 +61,7 @@ namespace WireMock.Net.Tests.Util
var memoryStream = new MemoryStream(content); var memoryStream = new MemoryStream(content);
// act // act
var body = await BodyParser.Parse(memoryStream, null, true); var body = await BodyParser.Parse(memoryStream, null);
// assert
Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
}
[Theory]
[InlineData(new byte[] { 34, 97, 34 }, BodyType.String)]
[InlineData(new byte[] { 97 }, BodyType.String)]
[InlineData(new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }, BodyType.Bytes)]
public async Task BodyParser_Parse_DetectedBodyTypeNoJsonParsing(byte[] content, BodyType detectedBodyType)
{
// arrange
var memoryStream = new MemoryStream(content);
// act
var body = await BodyParser.Parse(memoryStream, null, false);
// assert // assert
Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
@@ -111,7 +95,7 @@ Content-Type: text/html
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(body)); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(body));
// Act // Act
var result = await BodyParser.Parse(memoryStream, contentType, true); var result = await BodyParser.Parse(memoryStream, contentType);
// Assert // Assert
Check.That(result.DetectedBodyType).IsEqualTo(BodyType.String); Check.That(result.DetectedBodyType).IsEqualTo(BodyType.String);
@@ -131,7 +115,7 @@ Content-Type: text/html
var memoryStream = new MemoryStream(Encoding.UTF32.GetBytes(body)); var memoryStream = new MemoryStream(Encoding.UTF32.GetBytes(body));
// Act // Act
var result = await BodyParser.Parse(memoryStream, contentType, true); var result = await BodyParser.Parse(memoryStream, contentType);
// Assert // Assert
Check.That(result.DetectedBodyType).IsEqualTo(BodyType.Bytes); Check.That(result.DetectedBodyType).IsEqualTo(BodyType.Bytes);
@@ -149,7 +133,7 @@ Content-Type: text/html
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString)); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString));
// Act // Act
var body = await BodyParser.Parse(memoryStream, contentType, true); var body = await BodyParser.Parse(memoryStream, contentType);
// Assert // Assert
Check.That(body.BodyAsBytes).IsNotNull(); Check.That(body.BodyAsBytes).IsNotNull();

View File

@@ -2,8 +2,8 @@
<PropertyGroup> <PropertyGroup>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<!--<TargetFrameworks>net452;netcoreapp2.1</TargetFrameworks>--> <TargetFrameworks>net452;netcoreapp2.1</TargetFrameworks>
<TargetFramework>netcoreapp2.1</TargetFramework> <!--<TargetFramework>netcoreapp2.1</TargetFramework>-->
<DebugType>full</DebugType> <DebugType>full</DebugType>
<AssemblyName>WireMock.Net.Tests</AssemblyName> <AssemblyName>WireMock.Net.Tests</AssemblyName>
<PackageId>WireMock.Net.Tests</PackageId> <PackageId>WireMock.Net.Tests</PackageId>
@@ -19,10 +19,6 @@
<AssemblyOriginatorKeyFile>../../src/WireMock.Net/WireMock.Net.snk</AssemblyOriginatorKeyFile> <AssemblyOriginatorKeyFile>../../src/WireMock.Net/WireMock.Net.snk</AssemblyOriginatorKeyFile>
<!--<DelaySign>true</DelaySign>--> <!--<DelaySign>true</DelaySign>-->
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign> <PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<!--https://developercommunity.visualstudio.com/content/problem/26347/unit-tests-fail-with-fileloadexception-newtonsoftj-1.html-->
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'"> <PropertyGroup Condition="'$(Configuration)' == 'Release'">
@@ -62,7 +58,6 @@
<ItemGroup Condition="'$(TargetFramework)' == 'net452'"> <ItemGroup Condition="'$(TargetFramework)' == 'net452'">
<PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="3.1.0" /> <PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="3.1.0" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net462'"> <ItemGroup Condition="'$(TargetFramework)' == 'net462'">

View File

@@ -141,21 +141,21 @@ namespace WireMock.Net.Tests
} }
[Fact] [Fact]
public void WireMockServer_WireMockServerSettings_AllowOnlyDefinedHttpStatusCodeInResponse() public void WireMockServer_WireMockServerSettings_AllowAnyHttpStatusCodeInResponse()
{ {
// Assign and Act // Assign and Act
var server = WireMockServer.Start(new WireMockServerSettings var server = WireMockServer.Start(new WireMockServerSettings
{ {
Logger = _loggerMock.Object, Logger = _loggerMock.Object,
AllowOnlyDefinedHttpStatusCodeInResponse = true AllowAnyHttpStatusCodeInResponse = true
}); });
// Assert // Assert
var options = server.GetPrivateFieldValue<IWireMockMiddlewareOptions>("_options"); var options = server.GetPrivateFieldValue<IWireMockMiddlewareOptions>("_options");
Check.That(options.AllowOnlyDefinedHttpStatusCodeInResponse).Equals(true); Check.That(options.AllowAnyHttpStatusCodeInResponse).Equals(true);
// Verify // Verify
_loggerMock.Verify(l => l.Info(It.Is<string>(s => s.Contains("AllowOnlyDefinedHttpStatusCodeInResponse") && s.Contains("True")))); _loggerMock.Verify(l => l.Info(It.Is<string>(s => s.Contains("AllowAnyHttpStatusCodeInResponse") && s.Contains("True"))));
} }
[Fact] [Fact]