Compare commits

..

17 Commits

Author SHA1 Message Date
Stef Heyenrath
bb906587ff 1.4.34 2022-01-27 12:36:35 +01:00
Stef Heyenrath
f2fab98abb MatcherMapper : Always use Pattern (#716) 2022-01-27 12:33:48 +01:00
Stef Heyenrath
288a50ccaf 1.4.33 2022-01-24 12:54:36 +01:00
Stef Heyenrath
ccd433b202 Add support for Cors (#714) 2022-01-24 12:26:19 +01:00
Stef Heyenrath
d6c36bc23b 1.4.32 2022-01-17 15:56:28 +00:00
Levan Nozadze
6b393ebc1d Added support of custom matchers in static mappings (#713)
* Added support of custom matchers in static mappings

* Fixed code style issues

* Fixed naming and code style

* added empty line

* Ignore serialization of CustomMatcherMappings property in WireMockServerSettings

* Added integration tests for CustomMatcherMappings
2022-01-17 16:04:37 +01:00
Stef Heyenrath
60bdc06d29 Small refactor on Template logic 2022-01-06 21:25:15 +01:00
Stef Heyenrath
0f1a4f32ef 1.4.31 2022-01-06 15:52:08 +01:00
Stef Heyenrath
e3a693ede7 Add example for Cors (#712)
* Cors

* Update Program.cs
2022-01-06 15:41:47 +01:00
Stef Heyenrath
b153024de3 Add ReplaceNodeOption flag (#710) 2022-01-05 17:03:29 +01:00
Stef Heyenrath
e8e28c21a1 Use NuGet "Stef.Validation" (#707)
* Use NuGet "Stef.Validation"

* nuget

* .
2021-12-30 10:44:50 +01:00
Bruno Targhetta
fd1f4968b4 Provide open api schema to dynamic examples generator so you can generate accurate data (#706)
* Provide open api schema to dynamic examples generator so you can generate accurate data using settings like max-length in case of a string

* Rename Schema Property and add a dynamic examples generator with properties from settings like max-length

* Remove blank lines

* Add virtual to all public method in WireMockOpenApiParserExampleValues and ireMockOpenApiParserDynamicExampleValues to extend and overrides examples values
2021-12-28 17:38:42 +01:00
Stef Heyenrath
eec9c486a5 1.4.30 2021-12-25 11:06:42 +01:00
Stef Heyenrath
b5ae087b95 Add .ConfigureAwait(false); to the await Task calls (#704)
Add .ConfigureAwait(false); to the await Task calls
2021-12-24 14:08:43 +01:00
Stef Heyenrath
1d1ff4a418 SaveUnmatchedRequests (#703) 2021-12-24 09:34:26 +01:00
Stef Heyenrath
3e1c3598f7 RegexExtended : fix SonarCloud issue 2021-12-14 07:57:42 +00:00
Stef Heyenrath
12b868401d fix test 2021-12-12 15:55:07 +01:00
176 changed files with 2312 additions and 1277 deletions

View File

@@ -1,3 +1,25 @@
# 1.4.34 (27 January 2022)
- [#716](https://github.com/WireMock-Net/WireMock.Net/pull/716) - MatcherMapper : Always use Pattern [bug] contributed by [StefH](https://github.com/StefH)
- [#715](https://github.com/WireMock-Net/WireMock.Net/issues/715) - Record request mapping outputs JsonMatcher with Patterns instead of Pattern [bug]
# 1.4.33 (24 January 2022)
- [#714](https://github.com/WireMock-Net/WireMock.Net/pull/714) - Add support for Cors [feature] contributed by [StefH](https://github.com/StefH)
# 1.4.32 (17 January 2022)
- [#713](https://github.com/WireMock-Net/WireMock.Net/pull/713) - Added support of custom matchers in static mappings contributed by [levanoz](https://github.com/levanoz)
# 1.4.31 (06 January 2022)
- [#706](https://github.com/WireMock-Net/WireMock.Net/pull/706) - Provide open api schema to dynamic examples generator so you can generate accurate data [feature] contributed by [brunotarghetta](https://github.com/brunotarghetta)
- [#707](https://github.com/WireMock-Net/WireMock.Net/pull/707) - Use NuGet "Stef.Validation" [feature] contributed by [StefH](https://github.com/StefH)
- [#710](https://github.com/WireMock-Net/WireMock.Net/pull/710) - Add ReplaceNodeOption flag [feature] contributed by [StefH](https://github.com/StefH)
# 1.4.30 (25 December 2021)
- [#703](https://github.com/WireMock-Net/WireMock.Net/pull/703) - SaveUnmatchedRequests [feature] contributed by [StefH](https://github.com/StefH)
- [#704](https://github.com/WireMock-Net/WireMock.Net/pull/704) - Add .ConfigureAwait(false); to the await Task calls [bug] contributed by [StefH](https://github.com/StefH)
- [#534](https://github.com/WireMock-Net/WireMock.Net/issues/534) - Mock server not answer if integrated in Xamarin UITest project [bug]
- [#567](https://github.com/WireMock-Net/WireMock.Net/issues/567) - Can't start WireMock.Net server in Xamarin.UITest project (.NET Framework 4.7.2) on MacOS [bug]
- [#685](https://github.com/WireMock-Net/WireMock.Net/issues/685) - GuidWildcardMatcher to match on GUIDs [feature]
# 1.4.29 (12 December 2021) # 1.4.29 (12 December 2021)
- [#699](https://github.com/WireMock-Net/WireMock.Net/pull/699) - GUID Pattern support in RegexMatcher contributed by [brogdogg](https://github.com/brogdogg) - [#699](https://github.com/WireMock-Net/WireMock.Net/pull/699) - GUID Pattern support in RegexMatcher contributed by [brogdogg](https://github.com/brogdogg)
- [#700](https://github.com/WireMock-Net/WireMock.Net/pull/700) - RegexExtended in settings [feature] contributed by [StefH](https://github.com/StefH) - [#700](https://github.com/WireMock-Net/WireMock.Net/pull/700) - RegexExtended in settings [feature] contributed by [StefH](https://github.com/StefH)

View File

@@ -4,7 +4,7 @@
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<VersionPrefix>1.4.29</VersionPrefix> <VersionPrefix>1.4.34</VersionPrefix>
<PackageReleaseNotes>See CHANGELOG.md</PackageReleaseNotes> <PackageReleaseNotes>See CHANGELOG.md</PackageReleaseNotes>
<PackageIcon>WireMock.Net-Logo.png</PackageIcon> <PackageIcon>WireMock.Net-Logo.png</PackageIcon>
<PackageProjectUrl>https://github.com/WireMock-Net/WireMock.Net</PackageProjectUrl> <PackageProjectUrl>https://github.com/WireMock-Net/WireMock.Net</PackageProjectUrl>

View File

@@ -1,6 +1,6 @@
rem https://github.com/StefH/GitHubReleaseNotes rem https://github.com/StefH/GitHubReleaseNotes
SET version=1.4.29 SET version=1.4.34
GitHubReleaseNotes --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc duplicate --version %version% --token %GH_TOKEN% GitHubReleaseNotes --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc duplicate --version %version% --token %GH_TOKEN%

View File

@@ -1,5 +1,5 @@
# 1.4.29 (12 December 2021) # 1.4.34 (27 January 2022)
- #699 GUID Pattern support in RegexMatcher - #716 MatcherMapper : Always use Pattern [bug]
- #700 RegexExtended in settings [feature] - #715 Record request mapping outputs JsonMatcher with Patterns instead of Pattern [bug]
The full release notes can be found here: https://github.com/WireMock-Net/WireMock.Net/blob/master/CHANGELOG.md The full release notes can be found here: https://github.com/WireMock-Net/WireMock.Net/blob/master/CHANGELOG.md

View File

@@ -1,4 +1,5 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=AD/@EntryIndexedValue">AD</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=CS/@EntryIndexedValue">CS</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=CS/@EntryIndexedValue">CS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=ID/@EntryIndexedValue">ID</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=ID/@EntryIndexedValue">ID</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=IP/@EntryIndexedValue">IP</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=IP/@EntryIndexedValue">IP</s:String>
@@ -11,11 +12,15 @@
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=XUA/@EntryIndexedValue">XUA</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=XUA/@EntryIndexedValue">XUA</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Flurl/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Flurl/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=funcs/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=funcs/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=guidb/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Heyenrath/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Heyenrath/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Jmes/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Jmes/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Raml/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Raml/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=randomizer/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=randomizer/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Scriban/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Sigil/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Stef/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Stef/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Victoor/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Webhook/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Webhook/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Webhooks/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Webhooks/@EntryIndexedValue">True</s:Boolean>
</wpf:ResourceDictionary> </wpf:ResourceDictionary>

View File

@@ -28,7 +28,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\src\WireMock.Net\WireMock.Net.csproj" /> <ProjectReference Include="..\..\src\WireMock.Net\WireMock.Net.csproj" />
<PackageReference Include="Handlebars.Net.Helpers" Version="2.*" /> <PackageReference Include="Handlebars.Net.Helpers" Version="2.*" />
<PackageReference Include="log4net" Version="2.0.12" /> <PackageReference Include="log4net" Version="2.0.13" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="5.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" /> <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup> </ItemGroup>

View File

@@ -1,22 +1,33 @@
{ {
"Request": { "Request": {
"Path": { "Path": {
"Matchers": [ "Matchers": [
{ {
"Name": "WildcardMatcher", "Name": "WildcardMatcher",
"Pattern": "/static/mapping" "Patterns": [ "/static/mapping", "/static/mapping2" ]
} }
] ]
}, },
"Body": {
"Matcher": {
"Name": "JsonMatcher",
"Pattern": {
"post1": "value 1",
"post2": "value 2"
},
"IgnoreCase": true
}
},
"Methods": [ "Methods": [
"get" "get",
"post"
] ]
}, },
"Response": { "Response": {
"BodyAsJson": { "body": "static mapping" }, "BodyAsJson": { "body": "static mapping" },
"Headers": { "Headers": {
"Content-Type": "application/json", "Content-Type": "application/json",
"Test-X": [ "test 1", "test 2" ] "Test-X": [ "test 1", "test 2" ]
} }
} }
} }

View File

@@ -25,7 +25,7 @@
<PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.*" /> <PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.*" />
<PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.*" /> <PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.*" />
<PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.*" /> <PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.*" />
<PackageReference Include="log4net" Version="2.0.10" /> <PackageReference Include="log4net" Version="2.0.13" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" /> <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup> </ItemGroup>

View File

@@ -37,7 +37,7 @@
<PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.*" /> <PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.*" />
<PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.*" /> <PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.*" />
<PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.*" /> <PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.*" />
<PackageReference Include="log4net" Version="2.0.10" /> <PackageReference Include="log4net" Version="2.0.13" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" /> <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup> </ItemGroup>

View File

@@ -34,7 +34,7 @@
<PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.*" /> <PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.*" />
<PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.*" /> <PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.*" />
<PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.*" /> <PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.*" />
<PackageReference Include="log4net" Version="2.0.12" /> <PackageReference Include="log4net" Version="2.0.13" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup> </ItemGroup>

View File

@@ -7,6 +7,7 @@ namespace WireMock.Net.ConsoleApplication
internal class CustomFileSystemFileHandler : IFileSystemHandler internal class CustomFileSystemFileHandler : IFileSystemHandler
{ {
private static readonly string AdminMappingsFolder = Path.Combine("__admin", "mappings"); private static readonly string AdminMappingsFolder = Path.Combine("__admin", "mappings");
private static readonly string UnmatchedRequestsFolder = Path.Combine("requests", "unmatched");
/// <inheritdoc cref="IFileSystemHandler.FolderExists"/> /// <inheritdoc cref="IFileSystemHandler.FolderExists"/>
public bool FolderExists(string path) public bool FolderExists(string path)
@@ -86,6 +87,21 @@ namespace WireMock.Net.ConsoleApplication
return File.ReadAllText(path); return File.ReadAllText(path);
} }
/// <inheritdoc cref="IFileSystemHandler.GetUnmatchedRequestsFolder"/>
public string GetUnmatchedRequestsFolder()
{
return Path.Combine(@"c:\temp-wiremock", UnmatchedRequestsFolder);
}
/// <inheritdoc cref="IFileSystemHandler.WriteUnmatchedRequest"/>
public void WriteUnmatchedRequest(string filename, string text)
{
var folder = GetUnmatchedRequestsFolder();
Directory.CreateDirectory(folder);
File.WriteAllText(Path.Combine(folder, filename), text);
}
/// <summary> /// <summary>
/// Adjusts the path to the MappingFolder. /// Adjusts the path to the MappingFolder.
/// </summary> /// </summary>

View File

@@ -1,19 +1,17 @@
using Newtonsoft.Json;
using HandlebarsDotNet;
using System; using System;
using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Server; using WireMock.Server;
using WireMock.Settings; using WireMock.Settings;
using WireMock.Util;
using System.Threading.Tasks;
using WireMock.Types; using WireMock.Types;
using WireMock.Util;
namespace WireMock.Net.ConsoleApplication namespace WireMock.Net.ConsoleApplication
{ {
@@ -359,7 +357,7 @@ namespace WireMock.Net.ConsoleApplication
.WithHeader("Transformed-Postman-Token", "token is {{request.headers.Postman-Token}}") .WithHeader("Transformed-Postman-Token", "token is {{request.headers.Postman-Token}}")
.WithHeader("xyz_{{request.headers.Postman-Token}}", "token is {{request.headers.Postman-Token}}") .WithHeader("xyz_{{request.headers.Postman-Token}}", "token is {{request.headers.Postman-Token}}")
.WithBody(@"{""msg"": ""Hello world CATCH-ALL on /*, {{request.path}}, add={{Math.Add request.query.start.[0] 42}} bykey={{request.query.start}}, bykey={{request.query.stop}}, byidx0={{request.query.stop.[0]}}, byidx1={{request.query.stop.[1]}}"" }") .WithBody(@"{""msg"": ""Hello world CATCH-ALL on /*, {{request.path}}, add={{Math.Add request.query.start.[0] 42}} bykey={{request.query.start}}, bykey={{request.query.stop}}, byidx0={{request.query.stop.[0]}}, byidx1={{request.query.stop.[1]}}"" }")
.WithTransformer(TransformerType.Handlebars) .WithTransformer(TransformerType.Handlebars, true, ReplaceNodeOptions.None)
.WithDelay(TimeSpan.FromMilliseconds(100)) .WithDelay(TimeSpan.FromMilliseconds(100))
); );
@@ -556,7 +554,7 @@ namespace WireMock.Net.ConsoleApplication
.Given(Request.Create().WithPath("/random200or505async").UsingGet()) .Given(Request.Create().WithPath("/random200or505async").UsingGet())
.RespondWith(Response.Create().WithCallback(async request => .RespondWith(Response.Create().WithCallback(async request =>
{ {
await Task.Delay(1); await Task.Delay(1).ConfigureAwait(false);
int code = new Random().Next(1, 2) == 1 ? 505 : 200; int code = new Random().Next(1, 2) == 1 ? 505 : 200;

View File

@@ -48,8 +48,8 @@
<Reference Include="HandlebarsDotNet.Helpers.Core, Version=2.1.1.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="HandlebarsDotNet.Helpers.Core, Version=2.1.1.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.Core.2.1.1-preview-01\lib\net452\HandlebarsDotNet.Helpers.Core.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.Core.2.1.1-preview-01\lib\net452\HandlebarsDotNet.Helpers.Core.dll</HintPath>
</Reference> </Reference>
<Reference Include="log4net, Version=2.0.12.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> <Reference Include="log4net, Version=2.0.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\..\packages\log4net.2.0.12\lib\net45\log4net.dll</HintPath> <HintPath>..\..\packages\log4net.2.0.13\lib\net45\log4net.dll</HintPath>
</Reference> </Reference>
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.Owin.Host.HttpListener, Version=3.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Reference Include="Microsoft.Owin.Host.HttpListener, Version=3.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">

View File

@@ -4,7 +4,7 @@
<package id="Handlebars.Net" version="2.0.4" targetFramework="net452" /> <package id="Handlebars.Net" version="2.0.4" targetFramework="net452" />
<package id="Handlebars.Net.Helpers" version="2.1.1-preview-01" targetFramework="net452" /> <package id="Handlebars.Net.Helpers" version="2.1.1-preview-01" targetFramework="net452" />
<package id="Handlebars.Net.Helpers.Core" version="2.1.1-preview-01" targetFramework="net452" /> <package id="Handlebars.Net.Helpers.Core" version="2.1.1-preview-01" targetFramework="net452" />
<package id="log4net" version="2.0.12" targetFramework="net452" /> <package id="log4net" version="2.0.13" targetFramework="net452" />
<package id="Microsoft.Owin.Host.HttpListener" version="3.1.0" targetFramework="net452" /> <package id="Microsoft.Owin.Host.HttpListener" version="3.1.0" targetFramework="net452" />
<package id="Newtonsoft.Json" version="11.0.2" targetFramework="net452" /> <package id="Newtonsoft.Json" version="11.0.2" targetFramework="net452" />
<package id="SimMetrics.Net" version="1.0.5" targetFramework="net452" /> <package id="SimMetrics.Net" version="1.0.5" targetFramework="net452" />

View File

@@ -47,8 +47,8 @@
<Reference Include="HandlebarsDotNet.Helpers.Core, Version=2.1.1.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL"> <Reference Include="HandlebarsDotNet.Helpers.Core, Version=2.1.1.0, Culture=neutral, PublicKeyToken=00d131fae0c250bc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.Helpers.Core.2.1.1-preview-01\lib\net452\HandlebarsDotNet.Helpers.Core.dll</HintPath> <HintPath>..\..\packages\Handlebars.Net.Helpers.Core.2.1.1-preview-01\lib\net452\HandlebarsDotNet.Helpers.Core.dll</HintPath>
</Reference> </Reference>
<Reference Include="log4net, Version=2.0.12.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> <Reference Include="log4net, Version=2.0.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\..\packages\log4net.2.0.12\lib\net45\log4net.dll</HintPath> <HintPath>..\..\packages\log4net.2.0.13\lib\net45\log4net.dll</HintPath>
</Reference> </Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL"> <Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath> <HintPath>..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>

View File

@@ -4,7 +4,7 @@
<package id="Handlebars.Net" version="2.0.4" targetFramework="net461" /> <package id="Handlebars.Net" version="2.0.4" targetFramework="net461" />
<package id="Handlebars.Net.Helpers" version="2.1.1-preview-01" targetFramework="net461" /> <package id="Handlebars.Net.Helpers" version="2.1.1-preview-01" targetFramework="net461" />
<package id="Handlebars.Net.Helpers.Core" version="2.1.1-preview-01" targetFramework="net461" /> <package id="Handlebars.Net.Helpers.Core" version="2.1.1-preview-01" targetFramework="net461" />
<package id="log4net" version="2.0.12" targetFramework="net461" /> <package id="log4net" version="2.0.13" targetFramework="net461" />
<package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="2.2.0" targetFramework="net461" /> <package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="2.2.0" targetFramework="net461" />
<package id="Newtonsoft.Json" version="11.0.2" targetFramework="net461" /> <package id="Newtonsoft.Json" version="11.0.2" targetFramework="net461" />
<package id="SimMetrics.Net" version="1.0.5" targetFramework="net461" /> <package id="SimMetrics.Net" version="1.0.5" targetFramework="net461" />

View File

@@ -57,8 +57,8 @@
<Reference Include="JmesPath.Net, Version=1.0.125.0, Culture=neutral, PublicKeyToken=b29d616b7f4faff0, processorArchitecture=MSIL"> <Reference Include="JmesPath.Net, Version=1.0.125.0, Culture=neutral, PublicKeyToken=b29d616b7f4faff0, processorArchitecture=MSIL">
<HintPath>..\..\packages\JmesPath.Net.1.0.125\lib\net45\JmesPath.Net.dll</HintPath> <HintPath>..\..\packages\JmesPath.Net.1.0.125\lib\net45\JmesPath.Net.dll</HintPath>
</Reference> </Reference>
<Reference Include="log4net, Version=2.0.12.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> <Reference Include="log4net, Version=2.0.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\..\packages\log4net.2.0.12\lib\net45\log4net.dll</HintPath> <HintPath>..\..\packages\log4net.2.0.13\lib\net45\log4net.dll</HintPath>
</Reference> </Reference>
<Reference Include="Microsoft.AspNetCore, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL"> <Reference Include="Microsoft.AspNetCore, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.dll</HintPath> <HintPath>..\..\packages\Microsoft.AspNetCore.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.dll</HintPath>

View File

@@ -6,7 +6,7 @@
<package id="Handlebars.Net.Helpers" version="2.1.1-preview-01" targetFramework="net472" /> <package id="Handlebars.Net.Helpers" version="2.1.1-preview-01" targetFramework="net472" />
<package id="Handlebars.Net.Helpers.Core" version="2.1.1-preview-01" targetFramework="net472" /> <package id="Handlebars.Net.Helpers.Core" version="2.1.1-preview-01" targetFramework="net472" />
<package id="JmesPath.Net" version="1.0.125" targetFramework="net472" /> <package id="JmesPath.Net" version="1.0.125" targetFramework="net472" />
<package id="log4net" version="2.0.12" targetFramework="net461" /> <package id="log4net" version="2.0.13" targetFramework="net472" />
<package id="Microsoft.AspNetCore" version="2.2.0" targetFramework="net472" /> <package id="Microsoft.AspNetCore" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Authentication.Abstractions" version="2.2.0" targetFramework="net472" /> <package id="Microsoft.AspNetCore.Authentication.Abstractions" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Authentication.Core" version="2.2.0" targetFramework="net472" /> <package id="Microsoft.AspNetCore.Authentication.Core" version="2.2.0" targetFramework="net472" />

View File

@@ -0,0 +1,26 @@
using System;
using Microsoft.OpenApi.Models;
using RandomDataGenerator.FieldOptions;
using RandomDataGenerator.Randomizers;
using WireMock.Net.OpenApiParser.Settings;
namespace WireMock.Net.OpenApiParser.ConsoleApp
{
public class DynamicDataGeneration : WireMockOpenApiParserDynamicExampleValues
{
public override string String
{
get
{
//Since you have your Schema, you can get if max-lenght is set. You can generate accurate examples with this settings
var maxLength = this.Schema.MaxLength ?? 9;
return RandomizerFactory.GetRandomizer(new FieldOptionsTextRegex
{
Pattern = $"[0-9A-Z]{{{maxLength}}}"
}).Generate() ?? "example-string";
}
set { }
}
}
}

View File

@@ -0,0 +1,73 @@
{
"swagger": "2.0",
"info": {
"title": "customer",
"description": "It contains basic customer actions.",
"version": "v1"
},
"host": "localhost",
"basePath": "/v1/customer/",
"schemes": [
"https"
],
"paths": {
"/": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "Correlation-Id",
"required": true,
"in": "header",
"type": "string",
"maxLength": 3
}
],
"responses": {
"200": {
"description": "",
"x-amf-mediaType": "application/json",
"schema": {
"$ref": "#/definitions/ResponseCustmer"
}
}
}
}
}
},
"definitions": {
"ResponseCustmer": {
"type": "object",
"additionalProperties": true,
"required": [
"first-name",
"last-name",
"status",
"interest"
],
"properties": {
"first-name": {
"type": "string"
},
"last-name": {
"type": "string"
},
"status": {
"type": "string",
"maxLength": 2
},
"interest": {
"type": "string",
"maxLength": 45
}
}
}
}
}

View File

@@ -1,41 +1,59 @@
using System; using System;
using System.IO; using System.IO;
using Microsoft.OpenApi.Readers;
using Newtonsoft.Json;
namespace WireMock.Net.OpenApiParser.ConsoleApp namespace WireMock.Net.OpenApiParser.ConsoleApp
{ {
class Program class Program
{ {
private const string Folder = "OpenApiFiles"; private const string Folder = "OpenApiFiles";
static void Main(string[] args) static void Main(string[] args)
{ {
var serverOpenAPIExamples = Run.RunServer(Path.Combine(Folder, "openAPIExamples.yaml"), "https://localhost:9091/"); //RunOthersOpenApiParserExample();
var serverPetstore_V2_json = Run.RunServer(Path.Combine(Folder, "Swagger_Petstore_V2.0.json"), "https://localhost:9092/");
var serverPetstore_V2_yaml = Run.RunServer(Path.Combine(Folder, "Swagger_Petstore_V2.0.yaml"), "https://localhost:9093/"); RunMockServerWithDynamicExampleGeneration();
var serverPetstore_V300_yaml = Run.RunServer(Path.Combine(Folder, "Swagger_Petstore_V3.0.0.yaml"), "https://localhost:9094/");
var serverPetstore_V302_json = Run.RunServer(Path.Combine(Folder, "Swagger_Petstore_V3.0.2.json"), "https://localhost:9095/");
Console.WriteLine("Press any key to stop the servers");
Console.ReadKey();
serverOpenAPIExamples.Stop();
serverPetstore_V2_json.Stop();
serverPetstore_V2_yaml.Stop();
serverPetstore_V300_yaml.Stop();
serverPetstore_V302_json.Stop();
//IWireMockOpenApiParser parser = new WireMockOpenApiParser();
//var petStoreModels = parser.FromStream(File.OpenRead("petstore-openapi3.json"), out OpenApiDiagnostic diagnostic1);
//string petStoreJson = JsonConvert.SerializeObject(petStoreModels, Settings);
// File.WriteAllText("../../../wiremock-petstore-openapi3.json", petStoreJson);
//Run.RunServer(petStoreModels);
//var mappingModels2 = parser.FromStream(File.OpenRead("infura.yaml"), out OpenApiDiagnostic diagnostic2);
//Console.WriteLine(JsonConvert.SerializeObject(diagnostic2, Settings));
//string json2 = JsonConvert.SerializeObject(mappingModels2, Settings);
//Console.WriteLine(json2);
} }
private static void RunMockServerWithDynamicExampleGeneration() {
//Run your mocking framework specifieing youur Example Values generator class.
var serverCustomer_V2_json = Run.RunServer(Path.Combine(Folder, "Swagger_Customer_V2.0.json"), "http://localhost:8090/", true, new DynamicDataGeneration(), Types.ExampleValueType.Value, Types.ExampleValueType.Value);
Console.WriteLine("Press any key to stop the servers");
Console.ReadKey();
serverCustomer_V2_json.Stop();
}
private static void RunOthersOpenApiParserExample()
{
var serverOpenAPIExamples = Run.RunServer(Path.Combine(Folder, "openAPIExamples.yaml"), "https://localhost:9091/");
var serverPetstore_V2_json = Run.RunServer(Path.Combine(Folder, "Swagger_Petstore_V2.0.json"), "https://localhost:9092/");
var serverPetstore_V2_yaml = Run.RunServer(Path.Combine(Folder, "Swagger_Petstore_V2.0.yaml"), "https://localhost:9093/");
var serverPetstore_V300_yaml = Run.RunServer(Path.Combine(Folder, "Swagger_Petstore_V3.0.0.yaml"), "https://localhost:9094/");
var serverPetstore_V302_json = Run.RunServer(Path.Combine(Folder, "Swagger_Petstore_V3.0.2.json"), "https://localhost:9095/");
Console.WriteLine("Press any key to stop the servers");
Console.ReadKey();
serverOpenAPIExamples.Stop();
serverPetstore_V2_json.Stop();
serverPetstore_V2_yaml.Stop();
serverPetstore_V300_yaml.Stop();
serverPetstore_V302_json.Stop();
//IWireMockOpenApiParser parser = new WireMockOpenApiParser();
//var petStoreModels = parser.FromStream(File.OpenRead("petstore-openapi3.json"), out OpenApiDiagnostic diagnostic1);
//string petStoreJson = JsonConvert.SerializeObject(petStoreModels, Settings);
// File.WriteAllText("../../../wiremock-petstore-openapi3.json", petStoreJson);
//Run.RunServer(petStoreModels);
//var mappingModels2 = parser.FromStream(File.OpenRead("infura.yaml"), out OpenApiDiagnostic diagnostic2);
//Console.WriteLine(JsonConvert.SerializeObject(diagnostic2, Settings));
//string json2 = JsonConvert.SerializeObject(mappingModels2, Settings);
//Console.WriteLine(json2);
}
} }
} }

View File

@@ -13,27 +13,30 @@ namespace WireMock.Net.OpenApiParser.ConsoleApp
{ {
public static class Run public static class Run
{ {
public static WireMockServer RunServer(string path, string url, bool dynamicExamples = true) public static WireMockServer RunServer(string path, string url, bool dynamicExamples = true, IWireMockOpenApiParserExampleValues examplesValuesGenerator = null, ExampleValueType pathPatternToUse = ExampleValueType.Wildcard, ExampleValueType headerPatternToUse = ExampleValueType.Wildcard)
{ {
var server = WireMockServer.Start(new WireMockServerSettings var server = WireMockServer.Start(new WireMockServerSettings
{ {
AllowCSharpCodeMatcher = true, AllowCSharpCodeMatcher = true,
Urls = new[] { url }, Urls = new[] { url },
StartAdminInterface = true, StartAdminInterface = true,
ReadStaticMappings = false, ReadStaticMappings = true,
WatchStaticMappings = false, WatchStaticMappings = false,
WatchStaticMappingsInSubdirectories = false, WatchStaticMappingsInSubdirectories = false,
Logger = new WireMockConsoleLogger() Logger = new WireMockConsoleLogger(),
SaveUnmatchedRequests = true
}); });
Console.WriteLine("WireMockServer listening at {0}", string.Join(",", server.Urls)); Console.WriteLine("WireMockServer listening at {0}", string.Join(",", server.Urls));
server.SetBasicAuthentication("a", "b"); //server.SetBasicAuthentication("a", "b");
var settings = new WireMockOpenApiParserSettings var settings = new WireMockOpenApiParserSettings
{ {
DynamicExamples = dynamicExamples, DynamicExamples = dynamicExamples,
PathPatternToUse = ExampleValueType.Wildcard, ExampleValues = examplesValuesGenerator,
HeaderPatternToUse = ExampleValueType.Wildcard PathPatternToUse = pathPatternToUse,
HeaderPatternToUse = headerPatternToUse,
}; };
server.WithMappingFromOpenApiFile(path, settings, out var diag); server.WithMappingFromOpenApiFile(path, settings, out var diag);

View File

@@ -36,6 +36,9 @@
<None Update="petstore.yml"> <None Update="petstore.yml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<None Update="OpenApiFiles\Swagger_Customer_V2.0.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -32,8 +32,8 @@
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="log4net, Version=2.0.12.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> <Reference Include="log4net, Version=2.0.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\..\packages\log4net.2.0.12\lib\net45\log4net.dll</HintPath> <HintPath>..\..\packages\log4net.2.0.13\lib\net45\log4net.dll</HintPath>
</Reference> </Reference>
<Reference Include="Microsoft.Owin, Version=2.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Reference Include="Microsoft.Owin, Version=2.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Owin.2.0.2\lib\net45\Microsoft.Owin.dll</HintPath> <HintPath>..\..\packages\Microsoft.Owin.2.0.2\lib\net45\Microsoft.Owin.dll</HintPath>

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="log4net" version="2.0.12" targetFramework="net452" /> <package id="log4net" version="2.0.13" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" /> <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" /> <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net452" /> <package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net452" />

View File

@@ -1,79 +1,80 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading; using System.Threading;
using log4net; using log4net;
using log4net.Config; using log4net.Config;
using log4net.Repository; using log4net.Repository;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Server; using WireMock.Server;
using WireMock.Settings; using WireMock.Settings;
using WireMock.Util; using WireMock.Util;
namespace WireMock.Net.StandAlone.NETCoreApp namespace WireMock.Net.StandAlone.NETCoreApp
{ {
static class Program static class Program
{ {
private static readonly ILoggerRepository LogRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); private static readonly ILoggerRepository LogRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
// private static readonly ILog Log = LogManager.GetLogger(typeof(Program)); // private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
private static int sleepTime = 30000; private static int sleepTime = 30000;
private static WireMockServer _server; private static WireMockServer _server;
static void Main(string[] args) static void Main(string[] args)
{ {
XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config")); XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));
if (!WireMockServerSettingsParser.TryParseArguments(args, out var settings, new WireMockLog4NetLogger())) if (!WireMockServerSettingsParser.TryParseArguments(args, out var settings, new WireMockLog4NetLogger()))
{ {
return; return;
} }
settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'"))); settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));
_server = WireMockServer.Start(settings); _server = WireMockServer.Start(settings);
_server.Given(Request.Create().WithPath("/api/sap") _server.Given(Request.Create().WithPath("/api/sap")
.UsingPost() .UsingPost()
.WithBody((IBodyData xmlData) => { .WithBody((IBodyData xmlData) =>
{
//xmlData is always null //xmlData is always null
return true; return true;
})) }))
.RespondWith(Response.Create().WithStatusCode(System.Net.HttpStatusCode.OK)); .RespondWith(Response.Create().WithStatusCode(System.Net.HttpStatusCode.OK));
_server _server
.Given(Request.Create() .Given(Request.Create()
.UsingAnyMethod()) .UsingAnyMethod())
.RespondWith(Response.Create() .RespondWith(Response.Create()
.WithTransformer() .WithTransformer()
.WithBody("{{Random Type=\"Integer\" Min=100 Max=999999}} {{DateTime.Now}} {{DateTime.Now \"yyyy-MMM\"}} {{String.Format (DateTime.Now) \"MMM-dd\"}}")); .WithBody("{{Random Type=\"Integer\" Min=100 Max=999999}} {{DateTime.Now}} {{DateTime.Now \"yyyy-MMM\"}} {{String.Format (DateTime.Now) \"MMM-dd\"}}"));
Console.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down"); Console.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down");
Console.CancelKeyPress += (s, e) => Console.CancelKeyPress += (s, e) =>
{ {
Stop("CancelKeyPress"); Stop("CancelKeyPress");
}; };
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx => System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
{ {
Stop("AssemblyLoadContext.Default.Unloading"); Stop("AssemblyLoadContext.Default.Unloading");
}; };
while (true) while (true)
{ {
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server running : {_server.IsStarted}"); Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server running : {_server.IsStarted}");
Thread.Sleep(sleepTime); Thread.Sleep(sleepTime);
} }
} }
private static void Stop(string why) private static void Stop(string why)
{ {
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server stopping because '{why}'"); Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server stopping because '{why}'");
_server.Stop(); _server.Stop();
Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server stopped"); Console.WriteLine($"{DateTime.UtcNow} WireMock.Net server stopped");
} }
} }
} }

View File

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

View File

@@ -7,7 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="log4net" Version="2.0.10" /> <PackageReference Include="log4net" Version="2.0.13" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -39,8 +39,8 @@
<StartupObject>WireMock.Net.StandAlone.Net452.Program</StartupObject> <StartupObject>WireMock.Net.StandAlone.Net452.Program</StartupObject>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="log4net, Version=2.0.12.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> <Reference Include="log4net, Version=2.0.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\..\packages\log4net.2.0.12\lib\net45\log4net.dll</HintPath> <HintPath>..\..\packages\log4net.2.0.13\lib\net45\log4net.dll</HintPath>
</Reference> </Reference>
<Reference Include="Microsoft.Owin.Host.HttpListener, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Reference Include="Microsoft.Owin.Host.HttpListener, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Owin.Host.HttpListener.4.0.0\lib\net451\Microsoft.Owin.Host.HttpListener.dll</HintPath> <HintPath>..\..\packages\Microsoft.Owin.Host.HttpListener.4.0.0\lib\net451\Microsoft.Owin.Host.HttpListener.dll</HintPath>

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="log4net" version="2.0.12" targetFramework="net452" /> <package id="log4net" version="2.0.13" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.6" targetFramework="net452" /> <package id="Microsoft.AspNet.WebApi.Client" version="5.2.6" targetFramework="net452" />
<package id="Microsoft.Owin.Host.HttpListener" version="4.0.0" targetFramework="net452" /> <package id="Microsoft.Owin.Host.HttpListener" version="4.0.0" targetFramework="net452" />
<package id="Newtonsoft.Json" version="11.0.2" targetFramework="net452" /> <package id="Newtonsoft.Json" version="11.0.2" targetFramework="net452" />

View File

@@ -1,4 +1,4 @@
using System.Collections.Generic; using System.Collections.Generic;
namespace WireMock.Admin.Mappings namespace WireMock.Admin.Mappings
{ {
@@ -64,10 +64,15 @@ namespace WireMock.Admin.Mappings
public string TransformerType { get; set; } public string TransformerType { get; set; }
/// <summary> /// <summary>
/// Use the Handlerbars transformer for the content from the referenced BodyAsFile. /// Use the Handlebars transformer for the content from the referenced BodyAsFile.
/// </summary> /// </summary>
public bool? UseTransformerForBodyAsFile { get; set; } public bool? UseTransformerForBodyAsFile { get; set; }
/// <summary>
/// The ReplaceNodeOptions to use when transforming a JSON node.
/// </summary>
public string TransformerReplaceNodeOptions { get; set; }
/// <summary> /// <summary>
/// Gets or sets the headers. /// Gets or sets the headers.
/// </summary> /// </summary>

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using WireMock.Types;
namespace WireMock.Admin.Mappings namespace WireMock.Admin.Mappings
{ {
@@ -42,5 +43,10 @@ namespace WireMock.Admin.Mappings
/// Gets the type of the transformer. /// Gets the type of the transformer.
/// </summary> /// </summary>
public string TransformerType { get; set; } public string TransformerType { get; set; }
/// <summary>
/// The ReplaceNodeOptions to use when transforming a JSON node.
/// </summary>
public string TransformerReplaceNodeOptions { get; set; }
} }
} }

View File

@@ -1,4 +1,8 @@
namespace WireMock.Admin.Settings using System.Text.RegularExpressions;
using WireMock.Handlers;
using WireMock.Types;
namespace WireMock.Admin.Settings
{ {
/// <summary> /// <summary>
/// Settings /// Settings
@@ -40,5 +44,20 @@
/// Throw an exception when the Matcher fails because of invalid input. (default set to false). /// Throw an exception when the Matcher fails because of invalid input. (default set to false).
/// </summary> /// </summary>
public bool? ThrowExceptionWhenMatcherFails { get; set; } public bool? ThrowExceptionWhenMatcherFails { get; set; }
/// <summary>
/// Use the RegexExtended instead of the default <see cref="Regex"/>. (default set to true).
/// </summary>
public bool? UseRegexExtended { get; set; }
/// <summary>
/// Save unmatched requests to a file using the <see cref="IFileSystemHandler"/>. (default set to false).
/// </summary>
public bool? SaveUnmatchedRequests { get; set; }
/// <summary>
/// Policies to use when using CORS. By default CORS is disabled. [Optional]
/// </summary>
public string CorsPolicyOptions { get; set; }
} }
} }

View File

@@ -96,5 +96,18 @@ namespace WireMock.Handlers
/// <param name="filename">The filename.</param> /// <param name="filename">The filename.</param>
/// <returns>The file content as a string.</returns> /// <returns>The file content as a string.</returns>
string ReadFileAsString([NotNull] string filename); string ReadFileAsString([NotNull] string filename);
/// <summary>
/// Gets the folder where the unmatched requests should be stored. For local file system, this would be `{CurrentFolder}/requests/unmatched`.
/// </summary>
/// <returns>The folder name.</returns>
string GetUnmatchedRequestsFolder();
/// <summary>
/// Write a unmatched request to the Unmatched RequestsFolder.
/// </summary>
/// <param name="filename">The filename.</param>
/// <param name="text">The text.</param>
void WriteUnmatchedRequest([NotNull] string filename, [NotNull] string text);
} }
} }

View File

@@ -1,13 +1,13 @@
namespace WireMock.Models namespace WireMock.Models
{ {
/// <summary> /// <summary>
/// IWebhook /// IWebhook
/// </summary> /// </summary>
public interface IWebhook public interface IWebhook
{ {
/// <summary> /// <summary>
/// Request /// Request
/// </summary> /// </summary>
IWebhookRequest Request { get; set; } IWebhookRequest Request { get; set; }
} }
} }

View File

@@ -1,42 +1,47 @@
using System.Collections.Generic; using System.Collections.Generic;
using WireMock.Types; using WireMock.Types;
using WireMock.Util; using WireMock.Util;
namespace WireMock.Models namespace WireMock.Models
{ {
/// <summary> /// <summary>
/// IWebhookRequest /// IWebhookRequest
/// </summary> /// </summary>
public interface IWebhookRequest public interface IWebhookRequest
{ {
/// <summary> /// <summary>
/// The Webhook Url. /// The Webhook Url.
/// </summary> /// </summary>
string Url { get; set; } string Url { get; set; }
/// <summary> /// <summary>
/// The method to use. /// The method to use.
/// </summary> /// </summary>
string Method { get; set; } string Method { get; set; }
/// <summary> /// <summary>
/// The Headers to send. /// The Headers to send.
/// </summary> /// </summary>
IDictionary<string, WireMockList<string>> Headers { get; } IDictionary<string, WireMockList<string>> Headers { get; }
/// <summary> /// <summary>
/// The body to send. /// The body to send.
/// </summary> /// </summary>
IBodyData BodyData { get; set; } IBodyData BodyData { get; set; }
/// <summary> /// <summary>
/// Use Transformer. /// Use Transformer.
/// </summary> /// </summary>
bool? UseTransformer { get; set; } bool? UseTransformer { get; set; }
/// <summary> /// <summary>
/// The transformer type. /// The transformer type.
/// </summary> /// </summary>
TransformerType TransformerType { get; set; } TransformerType TransformerType { get; set; }
}
/// <summary>
/// The ReplaceNodeOptions to use when transforming a JSON node.
/// </summary>
ReplaceNodeOptions TransformerReplaceNodeOptions { get; set; }
}
} }

View File

@@ -0,0 +1,36 @@
using System;
namespace WireMock.Types
{
/// <summary>
/// Policies to use when using CORS.
/// </summary>
[Flags]
public enum CorsPolicyOptions
{
/// <summary>
/// Cors is disabled
/// </summary>
None = 0,
/// <summary>
/// Ensures that the policy allows any header.
/// </summary>
AllowAnyHeader = 0b00000001,
/// <summary>
/// Ensures that the policy allows any method.
/// </summary>
AllowAnyMethod = 0b00000010,
/// <summary>
/// Ensures that the policy allows any origin.
/// </summary>
AllowAnyOrigin = 0b00000100,
/// <summary>
/// Ensures that the policy allows any header, method and origin.
/// </summary>
AllowAll = AllowAnyHeader | AllowAnyMethod | AllowAnyOrigin
}
}

View File

@@ -0,0 +1,36 @@
using System;
namespace WireMock.Types
{
/// <summary>
/// Flags to use when replace a JSON node using the Transformer.
/// </summary>
[Flags]
public enum ReplaceNodeOptions
{
/// <summary>
/// Default
/// </summary>
None = 0
///// <summary>
///// Replace boolean string value to a real boolean value. (This is used by default to maintain backward compatibility.)
///// </summary>
//Bool = 0b00000001,
///// <summary>
///// Replace integer string value to a real integer value.
///// </summary>
//Integer = 0b00000010,
///// <summary>
///// Replace long string value to a real long value.
///// </summary>
//Long = 0b00000100,
///// <summary>
///// Replace all string values to a real values.
///// </summary>
//All = Bool | Integer | Long
}
}

View File

@@ -8,7 +8,7 @@ using Newtonsoft.Json.Linq;
using WireMock.Exceptions; using WireMock.Exceptions;
using WireMock.Extensions; using WireMock.Extensions;
using WireMock.Models; using WireMock.Models;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers namespace WireMock.Matchers
{ {
@@ -53,7 +53,7 @@ namespace WireMock.Matchers
/// <param name="patterns">The patterns.</param> /// <param name="patterns">The patterns.</param>
public CSharpCodeMatcher(MatchBehaviour matchBehaviour, [NotNull] params AnyOf<string, StringPattern>[] patterns) public CSharpCodeMatcher(MatchBehaviour matchBehaviour, [NotNull] params AnyOf<string, StringPattern>[] patterns)
{ {
Check.NotNull(patterns, nameof(patterns)); Guard.NotNull(patterns, nameof(patterns));
MatchBehaviour = matchBehaviour; MatchBehaviour = matchBehaviour;
ThrowException = false; ThrowException = false;

View File

@@ -1,5 +1,6 @@
using System; using System;
using Microsoft.OpenApi.Models;
namespace WireMock.Net.OpenApiParser.Settings namespace WireMock.Net.OpenApiParser.Settings
{ {
/// <summary> /// <summary>
@@ -48,5 +49,10 @@ namespace WireMock.Net.OpenApiParser.Settings
/// An example value for a String. /// An example value for a String.
/// </summary> /// </summary>
string String { get; set; } string String { get; set; }
/// <summary>
/// OpenApi Schema to generate dynamic examples more accurate
/// </summary>
OpenApiSchema Schema { get; set; }
} }
} }

View File

@@ -1,4 +1,5 @@
using System; using System;
using Microsoft.OpenApi.Models;
using RandomDataGenerator.FieldOptions; using RandomDataGenerator.FieldOptions;
using RandomDataGenerator.Randomizers; using RandomDataGenerator.Randomizers;
@@ -10,22 +11,24 @@ namespace WireMock.Net.OpenApiParser.Settings
public class WireMockOpenApiParserDynamicExampleValues : IWireMockOpenApiParserExampleValues public class WireMockOpenApiParserDynamicExampleValues : IWireMockOpenApiParserExampleValues
{ {
/// <inheritdoc /> /// <inheritdoc />
public bool Boolean { get { return RandomizerFactory.GetRandomizer(new FieldOptionsBoolean()).Generate() ?? true; } set { } } public virtual bool Boolean { get { return RandomizerFactory.GetRandomizer(new FieldOptionsBoolean()).Generate() ?? true; } set { } }
/// <inheritdoc /> /// <inheritdoc />
public int Integer { get { return RandomizerFactory.GetRandomizer(new FieldOptionsInteger()).Generate() ?? 42; } set { } } public virtual int Integer { get { return RandomizerFactory.GetRandomizer(new FieldOptionsInteger()).Generate() ?? 42; } set { } }
/// <inheritdoc /> /// <inheritdoc />
public float Float { get { return RandomizerFactory.GetRandomizer(new FieldOptionsFloat()).Generate() ?? 4.2f; } set { } } public virtual float Float { get { return RandomizerFactory.GetRandomizer(new FieldOptionsFloat()).Generate() ?? 4.2f; } set { } }
/// <inheritdoc /> /// <inheritdoc />
public double Double { get { return RandomizerFactory.GetRandomizer(new FieldOptionsDouble()).Generate() ?? 4.2d; } set { } } public virtual double Double { get { return RandomizerFactory.GetRandomizer(new FieldOptionsDouble()).Generate() ?? 4.2d; } set { } }
/// <inheritdoc /> /// <inheritdoc />
public Func<DateTime> Date { get { return () => RandomizerFactory.GetRandomizer(new FieldOptionsDateTime()).Generate() ?? System.DateTime.UtcNow.Date; } set { } } public virtual Func<DateTime> Date { get { return () => RandomizerFactory.GetRandomizer(new FieldOptionsDateTime()).Generate() ?? System.DateTime.UtcNow.Date; } set { } }
/// <inheritdoc /> /// <inheritdoc />
public Func<DateTime> DateTime { get { return () => RandomizerFactory.GetRandomizer(new FieldOptionsDateTime()).Generate() ?? System.DateTime.UtcNow; } set { } } public virtual Func<DateTime> DateTime { get { return () => RandomizerFactory.GetRandomizer(new FieldOptionsDateTime()).Generate() ?? System.DateTime.UtcNow; } set { } }
/// <inheritdoc /> /// <inheritdoc />
public byte[] Bytes { get { return RandomizerFactory.GetRandomizer(new FieldOptionsBytes()).Generate(); } set { } } public virtual byte[] Bytes { get { return RandomizerFactory.GetRandomizer(new FieldOptionsBytes()).Generate(); } set { } }
/// <inheritdoc /> /// <inheritdoc />
public object Object { get; set; } = "example-object"; public virtual object Object { get; set; } = "example-object";
/// <inheritdoc /> /// <inheritdoc />
public string String { get { return RandomizerFactory.GetRandomizer(new FieldOptionsTextRegex { Pattern = @"^[0-9]{2}[A-Z]{5}[0-9]{2}" }).Generate() ?? "example-string"; } set { } } public virtual string String { get { return RandomizerFactory.GetRandomizer(new FieldOptionsTextRegex { Pattern = @"^[0-9]{2}[A-Z]{5}[0-9]{2}" }).Generate() ?? "example-string"; } set { } }
/// <inheritdoc />
public virtual OpenApiSchema Schema { get; set; }
} }
} }

View File

@@ -1,5 +1,6 @@
using System; using System;
using Microsoft.OpenApi.Models;
namespace WireMock.Net.OpenApiParser.Settings namespace WireMock.Net.OpenApiParser.Settings
{ {
/// <summary> /// <summary>
@@ -8,22 +9,24 @@ namespace WireMock.Net.OpenApiParser.Settings
public class WireMockOpenApiParserExampleValues : IWireMockOpenApiParserExampleValues public class WireMockOpenApiParserExampleValues : IWireMockOpenApiParserExampleValues
{ {
/// <inheritdoc /> /// <inheritdoc />
public bool Boolean { get; set; } = true; public virtual bool Boolean { get; set; } = true;
/// <inheritdoc /> /// <inheritdoc />
public int Integer { get; set; } = 42; public virtual int Integer { get; set; } = 42;
/// <inheritdoc /> /// <inheritdoc />
public float Float { get; set; } = 4.2f; public virtual float Float { get; set; } = 4.2f;
/// <inheritdoc /> /// <inheritdoc />
public double Double { get; set; } = 4.2d; public virtual double Double { get; set; } = 4.2d;
/// <inheritdoc /> /// <inheritdoc />
public Func<DateTime> Date { get; set; } = () => System.DateTime.UtcNow.Date; public virtual Func<DateTime> Date { get; set; } = () => System.DateTime.UtcNow.Date;
/// <inheritdoc /> /// <inheritdoc />
public Func<DateTime> DateTime { get; set; } = () => System.DateTime.UtcNow; public virtual Func<DateTime> DateTime { get; set; } = () => System.DateTime.UtcNow;
/// <inheritdoc /> /// <inheritdoc />
public byte[] Bytes { get; set; } = { 48, 49, 50 }; public virtual byte[] Bytes { get; set; } = { 48, 49, 50 };
/// <inheritdoc /> /// <inheritdoc />
public object Object { get; set; } = "example-object"; public virtual object Object { get; set; } = "example-object";
/// <inheritdoc /> /// <inheritdoc />
public string String { get; set; } = "example-string"; public virtual string String { get; set; } = "example-string";
/// <inheritdoc />
public virtual OpenApiSchema Schema { get; set; } = new OpenApiSchema();
} }
} }

View File

@@ -36,6 +36,8 @@ namespace WireMock.Net.OpenApiParser.Utils
var schemaExample = schema?.Example; var schemaExample = schema?.Example;
var schemaEnum = GetRandomEnumValue(schema?.Enum); var schemaEnum = GetRandomEnumValue(schema?.Enum);
_settings.ExampleValues.Schema = schema;
switch (schema?.GetSchemaType()) switch (schema?.GetSchemaType())
{ {
case SchemaType.Boolean: case SchemaType.Boolean:

View File

@@ -26,7 +26,7 @@
<PackageReference Include="JetBrains.Annotations" Version="2021.3.0" PrivateAssets="All" /> <PackageReference Include="JetBrains.Annotations" Version="2021.3.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
<PackageReference Include="RandomDataGenerator.Net" Version="1.0.13" /> <PackageReference Include="RandomDataGenerator.Net" Version="1.0.13" />
<PackageReference Include="Stef.Validation" Version="0.0.4" /> <PackageReference Include="Stef.Validation" Version="0.1.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -4,7 +4,7 @@ using JetBrains.Annotations;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Server; using WireMock.Server;
using WireMock.Settings; using WireMock.Settings;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Net.StandAlone namespace WireMock.Net.StandAlone
{ {
@@ -22,7 +22,7 @@ namespace WireMock.Net.StandAlone
[PublicAPI] [PublicAPI]
public static WireMockServer Start([NotNull] IWireMockServerSettings settings) public static WireMockServer Start([NotNull] IWireMockServerSettings settings)
{ {
Check.NotNull(settings, nameof(settings)); Guard.NotNull(settings, nameof(settings));
var server = WireMockServer.Start(settings); var server = WireMockServer.Start(settings);
@@ -40,7 +40,7 @@ namespace WireMock.Net.StandAlone
[PublicAPI] [PublicAPI]
public static WireMockServer Start([NotNull] string[] args, [CanBeNull] IWireMockLogger logger = null) public static WireMockServer Start([NotNull] string[] args, [CanBeNull] IWireMockLogger logger = null)
{ {
Check.NotNull(args, nameof(args)); Guard.NotNull(args, nameof(args));
if (WireMockServerSettingsParser.TryParseArguments(args, out var settings, logger)) if (WireMockServerSettingsParser.TryParseArguments(args, out var settings, logger))
{ {
@@ -62,7 +62,7 @@ namespace WireMock.Net.StandAlone
[PublicAPI] [PublicAPI]
public static bool TryStart([NotNull] string[] args, out WireMockServer server, [CanBeNull] IWireMockLogger logger = null) public static bool TryStart([NotNull] string[] args, out WireMockServer server, [CanBeNull] IWireMockLogger logger = null)
{ {
Check.NotNull(args, nameof(args)); Guard.NotNull(args, nameof(args));
if (WireMockServerSettingsParser.TryParseArguments(args, out var settings, logger)) if (WireMockServerSettingsParser.TryParseArguments(args, out var settings, logger))
{ {

View File

@@ -46,7 +46,7 @@ namespace WireMock.Authentication
try try
{ {
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(_stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever()); var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(_stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
var config = configManager.GetConfigurationAsync().GetAwaiter().GetResult(); var config = configManager.GetConfigurationAsync().ConfigureAwait(false).GetAwaiter().GetResult();
var validationParameters = new TokenValidationParameters var validationParameters = new TokenValidationParameters
{ {

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Handlers namespace WireMock.Handlers
{ {
@@ -11,6 +11,7 @@ namespace WireMock.Handlers
public class LocalFileSystemHandler : IFileSystemHandler public class LocalFileSystemHandler : IFileSystemHandler
{ {
private static readonly string AdminMappingsFolder = Path.Combine("__admin", "mappings"); private static readonly string AdminMappingsFolder = Path.Combine("__admin", "mappings");
private static readonly string UnmatchedRequestsFolder = Path.Combine("requests", "unmatched");
private readonly string _rootFolder; private readonly string _rootFolder;
@@ -31,56 +32,56 @@ namespace WireMock.Handlers
} }
/// <inheritdoc cref="IFileSystemHandler.FolderExists"/> /// <inheritdoc cref="IFileSystemHandler.FolderExists"/>
public bool FolderExists(string path) public virtual bool FolderExists(string path)
{ {
Check.NotNullOrEmpty(path, nameof(path)); Guard.NotNullOrEmpty(path, nameof(path));
return Directory.Exists(path); return Directory.Exists(path);
} }
/// <inheritdoc cref="IFileSystemHandler.CreateFolder"/> /// <inheritdoc cref="IFileSystemHandler.CreateFolder"/>
public void CreateFolder(string path) public virtual void CreateFolder(string path)
{ {
Check.NotNullOrEmpty(path, nameof(path)); Guard.NotNullOrEmpty(path, nameof(path));
Directory.CreateDirectory(path); Directory.CreateDirectory(path);
} }
/// <inheritdoc cref="IFileSystemHandler.EnumerateFiles"/> /// <inheritdoc cref="IFileSystemHandler.EnumerateFiles"/>
public IEnumerable<string> EnumerateFiles(string path, bool includeSubdirectories) public virtual IEnumerable<string> EnumerateFiles(string path, bool includeSubdirectories)
{ {
Check.NotNullOrEmpty(path, nameof(path)); Guard.NotNullOrEmpty(path, nameof(path));
return includeSubdirectories ? Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories) : Directory.EnumerateFiles(path); return includeSubdirectories ? Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories) : Directory.EnumerateFiles(path);
} }
/// <inheritdoc cref="IFileSystemHandler.GetMappingFolder"/> /// <inheritdoc cref="IFileSystemHandler.GetMappingFolder"/>
public string GetMappingFolder() public virtual string GetMappingFolder()
{ {
return Path.Combine(_rootFolder, AdminMappingsFolder); return Path.Combine(_rootFolder, AdminMappingsFolder);
} }
/// <inheritdoc cref="IFileSystemHandler.ReadMappingFile"/> /// <inheritdoc cref="IFileSystemHandler.ReadMappingFile"/>
public string ReadMappingFile(string path) public virtual string ReadMappingFile(string path)
{ {
Check.NotNullOrEmpty(path, nameof(path)); Guard.NotNullOrEmpty(path, nameof(path));
return File.ReadAllText(path); return File.ReadAllText(path);
} }
/// <inheritdoc cref="IFileSystemHandler.WriteMappingFile(string, string)"/> /// <inheritdoc cref="IFileSystemHandler.WriteMappingFile(string, string)"/>
public void WriteMappingFile(string path, string text) public virtual void WriteMappingFile(string path, string text)
{ {
Check.NotNullOrEmpty(path, nameof(path)); Guard.NotNullOrEmpty(path, nameof(path));
Check.NotNull(text, nameof(text)); Guard.NotNull(text, nameof(text));
File.WriteAllText(path, text); File.WriteAllText(path, text);
} }
/// <inheritdoc cref="IFileSystemHandler.ReadResponseBodyAsFile"/> /// <inheritdoc cref="IFileSystemHandler.ReadResponseBodyAsFile"/>
public byte[] ReadResponseBodyAsFile(string path) public virtual byte[] ReadResponseBodyAsFile(string path)
{ {
Check.NotNullOrEmpty(path, nameof(path)); Guard.NotNullOrEmpty(path, nameof(path));
path = PathUtils.CleanPath(path); path = PathUtils.CleanPath(path);
// If the file exists at the given path relative to the MappingsFolder, then return that. // If the file exists at the given path relative to the MappingsFolder, then return that.
// Else the path will just be as-is. // Else the path will just be as-is.
@@ -88,9 +89,9 @@ namespace WireMock.Handlers
} }
/// <inheritdoc cref="IFileSystemHandler.ReadResponseBodyAsString"/> /// <inheritdoc cref="IFileSystemHandler.ReadResponseBodyAsString"/>
public string ReadResponseBodyAsString(string path) public virtual string ReadResponseBodyAsString(string path)
{ {
Check.NotNullOrEmpty(path, nameof(path)); Guard.NotNullOrEmpty(path, nameof(path));
path = PathUtils.CleanPath(path); path = PathUtils.CleanPath(path);
// In case the path is a filename, the path will be adjusted to the MappingFolder. // In case the path is a filename, the path will be adjusted to the MappingFolder.
// Else the path will just be as-is. // Else the path will just be as-is.
@@ -98,42 +99,63 @@ namespace WireMock.Handlers
} }
/// <inheritdoc cref="IFileSystemHandler.FileExists"/> /// <inheritdoc cref="IFileSystemHandler.FileExists"/>
public bool FileExists(string filename) public virtual bool FileExists(string filename)
{ {
Check.NotNullOrEmpty(filename, nameof(filename)); Guard.NotNullOrEmpty(filename, nameof(filename));
return File.Exists(AdjustPath(filename)); return File.Exists(AdjustPathForMappingFolder(filename));
} }
/// <inheritdoc cref="IFileSystemHandler.WriteFile(string, byte[])"/> /// <inheritdoc cref="IFileSystemHandler.WriteFile(string, byte[])"/>
public void WriteFile(string filename, byte[] bytes) public virtual void WriteFile(string filename, byte[] bytes)
{ {
Check.NotNullOrEmpty(filename, nameof(filename)); Guard.NotNullOrEmpty(filename, nameof(filename));
Check.NotNull(bytes, nameof(bytes)); Guard.NotNull(bytes, nameof(bytes));
File.WriteAllBytes(AdjustPath(filename), bytes); File.WriteAllBytes(AdjustPathForMappingFolder(filename), bytes);
} }
/// <inheritdoc cref="IFileSystemHandler.DeleteFile"/> /// <inheritdoc cref="IFileSystemHandler.DeleteFile"/>
public void DeleteFile(string filename) public virtual void DeleteFile(string filename)
{ {
Check.NotNullOrEmpty(filename, nameof(filename)); Guard.NotNullOrEmpty(filename, nameof(filename));
File.Delete(AdjustPath(filename)); File.Delete(AdjustPathForMappingFolder(filename));
} }
/// <inheritdoc cref="IFileSystemHandler.ReadFile"/> /// <inheritdoc cref="IFileSystemHandler.ReadFile"/>
public byte[] ReadFile(string filename) public virtual byte[] ReadFile(string filename)
{ {
Check.NotNullOrEmpty(filename, nameof(filename)); Guard.NotNullOrEmpty(filename, nameof(filename));
return File.ReadAllBytes(AdjustPath(filename)); return File.ReadAllBytes(AdjustPathForMappingFolder(filename));
} }
/// <inheritdoc cref="IFileSystemHandler.ReadFileAsString"/> /// <inheritdoc cref="IFileSystemHandler.ReadFileAsString"/>
public string ReadFileAsString(string filename) public virtual string ReadFileAsString(string filename)
{ {
return File.ReadAllText(AdjustPath(Check.NotNullOrEmpty(filename, nameof(filename)))); return File.ReadAllText(AdjustPathForMappingFolder(Guard.NotNullOrEmpty(filename, nameof(filename))));
}
/// <inheritdoc cref="IFileSystemHandler.GetUnmatchedRequestsFolder"/>
public virtual string GetUnmatchedRequestsFolder()
{
return Path.Combine(_rootFolder, UnmatchedRequestsFolder);
}
/// <inheritdoc cref="IFileSystemHandler.WriteUnmatchedRequest"/>
public virtual void WriteUnmatchedRequest(string filename, string text)
{
Guard.NotNullOrEmpty(filename, nameof(filename));
Guard.NotNull(text, nameof(text));
var folder = GetUnmatchedRequestsFolder();
if (!FolderExists(folder))
{
CreateFolder(folder);
}
File.WriteAllText(Path.Combine(folder, filename), text);
} }
/// <summary> /// <summary>
@@ -141,7 +163,7 @@ namespace WireMock.Handlers
/// </summary> /// </summary>
/// <param name="filename">The path.</param> /// <param name="filename">The path.</param>
/// <returns>Adjusted path</returns> /// <returns>Adjusted path</returns>
private string AdjustPath(string filename) private string AdjustPathForMappingFolder(string filename)
{ {
return Path.Combine(GetMappingFolder(), filename); return Path.Combine(GetMappingFolder(), filename);
} }

View File

@@ -1,7 +1,7 @@
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Http namespace WireMock.Http
{ {
@@ -15,7 +15,7 @@ namespace WireMock.Http
/// <returns>ByteArrayContent</returns> /// <returns>ByteArrayContent</returns>
internal static ByteArrayContent Create([NotNull] byte[] content, [CanBeNull] MediaTypeHeaderValue contentType) internal static ByteArrayContent Create([NotNull] byte[] content, [CanBeNull] MediaTypeHeaderValue contentType)
{ {
Check.NotNull(content, nameof(content)); Guard.NotNull(content, nameof(content));
var byteContent = new ByteArrayContent(content); var byteContent = new ByteArrayContent(content);
if (contentType != null) if (contentType != null)

View File

@@ -6,7 +6,7 @@ using System.Net.Http.Headers;
using JetBrains.Annotations; using JetBrains.Annotations;
using Newtonsoft.Json; using Newtonsoft.Json;
using WireMock.Types; using WireMock.Types;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Http namespace WireMock.Http
{ {
@@ -14,8 +14,8 @@ namespace WireMock.Http
{ {
internal static HttpRequestMessage Create([NotNull] RequestMessage requestMessage, [NotNull] string url) internal static HttpRequestMessage Create([NotNull] RequestMessage requestMessage, [NotNull] string url)
{ {
Check.NotNull(requestMessage, nameof(requestMessage)); Guard.NotNull(requestMessage, nameof(requestMessage));
Check.NotNullOrEmpty(url, nameof(url)); Guard.NotNullOrEmpty(url, nameof(url));
var httpRequestMessage = new HttpRequestMessage(new HttpMethod(requestMessage.Method), url); var httpRequestMessage = new HttpRequestMessage(new HttpMethod(requestMessage.Method), url);

View File

@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
@@ -17,7 +17,7 @@ namespace WireMock.Http
var headers = (httpResponseMessage.Content?.Headers.Union(httpResponseMessage.Headers) ?? Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>()).ToArray(); var headers = (httpResponseMessage.Content?.Headers.Union(httpResponseMessage.Headers) ?? Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>()).ToArray();
if (httpResponseMessage.Content != null) if (httpResponseMessage.Content != null)
{ {
var stream = await httpResponseMessage.Content.ReadAsStreamAsync(); var stream = await httpResponseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false);
IEnumerable<string> contentTypeHeader = null; IEnumerable<string> contentTypeHeader = null;
if (headers.Any(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase))) if (headers.Any(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase)))
{ {
@@ -38,7 +38,7 @@ namespace WireMock.Http
ContentEncoding = contentEncodingHeader?.FirstOrDefault(), ContentEncoding = contentEncodingHeader?.FirstOrDefault(),
DecompressGZipAndDeflate = decompressGzipAndDeflate DecompressGZipAndDeflate = decompressGzipAndDeflate
}; };
responseMessage.BodyData = await BodyParser.Parse(bodyParserSettings); responseMessage.BodyData = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false);
} }
foreach (var header in headers) foreach (var header in headers)

View File

@@ -1,7 +1,7 @@
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Http namespace WireMock.Http
{ {
@@ -15,7 +15,7 @@ namespace WireMock.Http
/// <returns>StringContent</returns> /// <returns>StringContent</returns>
internal static StringContent Create([NotNull] string content, [CanBeNull] MediaTypeHeaderValue contentType) internal static StringContent Create([NotNull] string content, [CanBeNull] MediaTypeHeaderValue contentType)
{ {
Check.NotNull(content, nameof(content)); Guard.NotNull(content, nameof(content));
var stringContent = new StringContent(content); var stringContent = new StringContent(content);
stringContent.Headers.ContentType = contentType; stringContent.Headers.ContentType = contentType;

View File

@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
@@ -11,7 +11,7 @@ using WireMock.Transformers.Handlebars;
using WireMock.Transformers.Scriban; using WireMock.Transformers.Scriban;
using WireMock.Types; using WireMock.Types;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Http namespace WireMock.Http
{ {
@@ -28,10 +28,10 @@ namespace WireMock.Http
public Task<HttpResponseMessage> SendAsync([NotNull] HttpClient client, [NotNull] IWebhookRequest request, [NotNull] RequestMessage originalRequestMessage, [NotNull] ResponseMessage originalResponseMessage) public Task<HttpResponseMessage> SendAsync([NotNull] HttpClient client, [NotNull] IWebhookRequest request, [NotNull] RequestMessage originalRequestMessage, [NotNull] ResponseMessage originalResponseMessage)
{ {
Check.NotNull(client, nameof(client)); Guard.NotNull(client, nameof(client));
Check.NotNull(request, nameof(request)); Guard.NotNull(request, nameof(request));
Check.NotNull(originalRequestMessage, nameof(originalRequestMessage)); Guard.NotNull(originalRequestMessage, nameof(originalRequestMessage));
Check.NotNull(originalResponseMessage, nameof(originalResponseMessage)); Guard.NotNull(originalResponseMessage, nameof(originalResponseMessage));
IBodyData bodyData; IBodyData bodyData;
IDictionary<string, WireMockList<string>> headers; IDictionary<string, WireMockList<string>> headers;
@@ -55,7 +55,7 @@ namespace WireMock.Http
throw new NotImplementedException($"TransformerType '{request.TransformerType}' is not supported."); throw new NotImplementedException($"TransformerType '{request.TransformerType}' is not supported.");
} }
(bodyData, headers) = responseMessageTransformer.Transform(originalRequestMessage, originalResponseMessage, request.BodyData, request.Headers); (bodyData, headers) = responseMessageTransformer.Transform(originalRequestMessage, originalResponseMessage, request.BodyData, request.Headers, request.TransformerReplaceNodeOptions);
} }
else else
{ {

View File

@@ -108,9 +108,9 @@ namespace WireMock
} }
/// <inheritdoc cref="IMapping.ProvideResponseAsync" /> /// <inheritdoc cref="IMapping.ProvideResponseAsync" />
public async Task<(ResponseMessage Message, IMapping Mapping)> ProvideResponseAsync(RequestMessage requestMessage) public Task<(ResponseMessage Message, IMapping Mapping)> ProvideResponseAsync(RequestMessage requestMessage)
{ {
return await Provider.ProvideResponseAsync(requestMessage, Settings); return Provider.ProvideResponseAsync(requestMessage, Settings);
} }
/// <inheritdoc cref="IMapping.GetRequestMatchResult" /> /// <inheritdoc cref="IMapping.GetRequestMatchResult" />

View File

@@ -3,7 +3,7 @@ using AnyOfTypes;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Extensions; using WireMock.Extensions;
using WireMock.Models; using WireMock.Models;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers namespace WireMock.Matchers
{ {
@@ -37,7 +37,7 @@ namespace WireMock.Matchers
/// <param name="values">The values.</param> /// <param name="values">The values.</param>
public ExactMatcher(MatchBehaviour matchBehaviour, bool throwException = false, [NotNull] params AnyOf<string, StringPattern>[] values) public ExactMatcher(MatchBehaviour matchBehaviour, bool throwException = false, [NotNull] params AnyOf<string, StringPattern>[] values)
{ {
Check.NotNull(values, nameof(values)); Guard.NotNull(values, nameof(values));
MatchBehaviour = matchBehaviour; MatchBehaviour = matchBehaviour;
ThrowException = throwException; ThrowException = throwException;

View File

@@ -1,6 +1,6 @@
using JetBrains.Annotations; using JetBrains.Annotations;
using System.Linq; using System.Linq;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers namespace WireMock.Matchers
{ {
@@ -41,7 +41,7 @@ namespace WireMock.Matchers
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
public ExactObjectMatcher(MatchBehaviour matchBehaviour, [NotNull] object value) public ExactObjectMatcher(MatchBehaviour matchBehaviour, [NotNull] object value)
{ {
Check.NotNull(value, nameof(value)); Guard.NotNull(value, nameof(value));
ValueAsObject = value; ValueAsObject = value;
MatchBehaviour = matchBehaviour; MatchBehaviour = matchBehaviour;
@@ -63,7 +63,7 @@ namespace WireMock.Matchers
/// <param name="value">The value.</param> /// <param name="value">The value.</param>
public ExactObjectMatcher(MatchBehaviour matchBehaviour, [NotNull] byte[] value, bool throwException = false) public ExactObjectMatcher(MatchBehaviour matchBehaviour, [NotNull] byte[] value, bool throwException = false)
{ {
Check.NotNull(value, nameof(value)); Guard.NotNull(value, nameof(value));
MatchBehaviour = matchBehaviour; MatchBehaviour = matchBehaviour;
ThrowException = throwException; ThrowException = throwException;

View File

@@ -5,7 +5,7 @@ using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using WireMock.Extensions; using WireMock.Extensions;
using WireMock.Models; using WireMock.Models;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers namespace WireMock.Matchers
{ {
@@ -48,7 +48,7 @@ namespace WireMock.Matchers
/// <param name="patterns">The patterns.</param> /// <param name="patterns">The patterns.</param>
public JsonPathMatcher(MatchBehaviour matchBehaviour, bool throwException = false, [NotNull] params AnyOf<string, StringPattern>[] patterns) public JsonPathMatcher(MatchBehaviour matchBehaviour, bool throwException = false, [NotNull] params AnyOf<string, StringPattern>[] patterns)
{ {
Check.NotNull(patterns, nameof(patterns)); Guard.NotNull(patterns, nameof(patterns));
MatchBehaviour = matchBehaviour; MatchBehaviour = matchBehaviour;
ThrowException = throwException; ThrowException = throwException;
@@ -63,8 +63,8 @@ namespace WireMock.Matchers
{ {
try try
{ {
var jtoken = JToken.Parse(input); var jToken = JToken.Parse(input);
match = IsMatch(jtoken); match = IsMatch(jToken);
} }
catch (JsonException) catch (JsonException)
{ {
@@ -89,8 +89,8 @@ namespace WireMock.Matchers
try try
{ {
// Check if JToken or object // Check if JToken or object
JToken jtoken = input is JToken token ? token : JObject.FromObject(input); JToken jToken = input is JToken token ? token : JObject.FromObject(input);
match = IsMatch(jtoken); match = IsMatch(jToken);
} }
catch (JsonException) catch (JsonException)
{ {
@@ -113,9 +113,9 @@ namespace WireMock.Matchers
/// <inheritdoc cref="IMatcher.Name"/> /// <inheritdoc cref="IMatcher.Name"/>
public string Name => "JsonPathMatcher"; public string Name => "JsonPathMatcher";
private double IsMatch(JToken jtoken) private double IsMatch(JToken jToken)
{ {
return MatchScores.ToScore(_patterns.Select(pattern => jtoken.SelectToken(pattern.GetPattern()) != null)); return MatchScores.ToScore(_patterns.Select(pattern => jToken.SelectToken(pattern.GetPattern()) != null));
} }
} }
} }

View File

@@ -5,7 +5,7 @@ using Newtonsoft.Json;
using System.Linq; using System.Linq;
using WireMock.Extensions; using WireMock.Extensions;
using WireMock.Models; using WireMock.Models;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers namespace WireMock.Matchers
{ {
@@ -55,7 +55,7 @@ namespace WireMock.Matchers
/// <param name="patterns">The patterns.</param> /// <param name="patterns">The patterns.</param>
public JmesPathMatcher(MatchBehaviour matchBehaviour, bool throwException = false, [NotNull] params AnyOf<string, StringPattern>[] patterns) public JmesPathMatcher(MatchBehaviour matchBehaviour, bool throwException = false, [NotNull] params AnyOf<string, StringPattern>[] patterns)
{ {
Check.NotNull(patterns, nameof(patterns)); Guard.NotNull(patterns, nameof(patterns));
MatchBehaviour = matchBehaviour; MatchBehaviour = matchBehaviour;
ThrowException = throwException; ThrowException = throwException;

View File

@@ -5,7 +5,7 @@ using JetBrains.Annotations;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers namespace WireMock.Matchers
{ {
@@ -61,7 +61,7 @@ namespace WireMock.Matchers
/// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param> /// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param>
public JsonMatcher(MatchBehaviour matchBehaviour, [NotNull] object value, bool ignoreCase = false, bool throwException = false) public JsonMatcher(MatchBehaviour matchBehaviour, [NotNull] object value, bool ignoreCase = false, bool throwException = false)
{ {
Check.NotNull(value, nameof(value)); Guard.NotNull(value, nameof(value));
MatchBehaviour = matchBehaviour; MatchBehaviour = matchBehaviour;
IgnoreCase = ignoreCase; IgnoreCase = ignoreCase;

View File

@@ -6,7 +6,7 @@ using Newtonsoft.Json.Linq;
using WireMock.Extensions; using WireMock.Extensions;
using WireMock.Models; using WireMock.Models;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers namespace WireMock.Matchers
{ {
@@ -57,7 +57,7 @@ namespace WireMock.Matchers
/// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param> /// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param>
public LinqMatcher(MatchBehaviour matchBehaviour, bool throwException = false, [NotNull] params AnyOf<string, StringPattern>[] patterns) public LinqMatcher(MatchBehaviour matchBehaviour, bool throwException = false, [NotNull] params AnyOf<string, StringPattern>[] patterns)
{ {
Check.NotNull(patterns, nameof(patterns)); Guard.NotNull(patterns, nameof(patterns));
MatchBehaviour = matchBehaviour; MatchBehaviour = matchBehaviour;
ThrowException = throwException; ThrowException = throwException;

View File

@@ -6,7 +6,7 @@ using JetBrains.Annotations;
using WireMock.Extensions; using WireMock.Extensions;
using WireMock.Models; using WireMock.Models;
using WireMock.RegularExpressions; using WireMock.RegularExpressions;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers namespace WireMock.Matchers
{ {
@@ -61,7 +61,7 @@ namespace WireMock.Matchers
/// <param name="useRegexExtended">Use RegexExtended (default = true).</param> /// <param name="useRegexExtended">Use RegexExtended (default = true).</param>
public RegexMatcher(MatchBehaviour matchBehaviour, [NotNull, RegexPattern] AnyOf<string, StringPattern>[] patterns, bool ignoreCase = false, bool throwException = false, bool useRegexExtended = true) public RegexMatcher(MatchBehaviour matchBehaviour, [NotNull, RegexPattern] AnyOf<string, StringPattern>[] patterns, bool ignoreCase = false, bool throwException = false, bool useRegexExtended = true)
{ {
Check.NotNull(patterns, nameof(patterns)); Guard.NotNull(patterns, nameof(patterns));
_patterns = patterns; _patterns = patterns;
IgnoreCase = ignoreCase; IgnoreCase = ignoreCase;

View File

@@ -3,7 +3,7 @@ using System;
using System.Linq; using System.Linq;
using WireMock.Types; using WireMock.Types;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers.Request namespace WireMock.Matchers.Request
{ {
@@ -70,7 +70,7 @@ namespace WireMock.Matchers.Request
/// <param name="func">The function.</param> /// <param name="func">The function.</param>
public RequestMessageBodyMatcher([NotNull] Func<string, bool> func) public RequestMessageBodyMatcher([NotNull] Func<string, bool> func)
{ {
Check.NotNull(func, nameof(func)); Guard.NotNull(func, nameof(func));
Func = func; Func = func;
} }
@@ -80,7 +80,7 @@ namespace WireMock.Matchers.Request
/// <param name="func">The function.</param> /// <param name="func">The function.</param>
public RequestMessageBodyMatcher([NotNull] Func<byte[], bool> func) public RequestMessageBodyMatcher([NotNull] Func<byte[], bool> func)
{ {
Check.NotNull(func, nameof(func)); Guard.NotNull(func, nameof(func));
DataFunc = func; DataFunc = func;
} }
@@ -90,7 +90,7 @@ namespace WireMock.Matchers.Request
/// <param name="func">The function.</param> /// <param name="func">The function.</param>
public RequestMessageBodyMatcher([NotNull] Func<object, bool> func) public RequestMessageBodyMatcher([NotNull] Func<object, bool> func)
{ {
Check.NotNull(func, nameof(func)); Guard.NotNull(func, nameof(func));
JsonFunc = func; JsonFunc = func;
} }
@@ -100,7 +100,7 @@ namespace WireMock.Matchers.Request
/// <param name="func">The function.</param> /// <param name="func">The function.</param>
public RequestMessageBodyMatcher([NotNull] Func<IBodyData, bool> func) public RequestMessageBodyMatcher([NotNull] Func<IBodyData, bool> func)
{ {
Check.NotNull(func, nameof(func)); Guard.NotNull(func, nameof(func));
BodyDataFunc = func; BodyDataFunc = func;
} }
@@ -110,7 +110,7 @@ namespace WireMock.Matchers.Request
/// <param name="matchers">The matchers.</param> /// <param name="matchers">The matchers.</param>
public RequestMessageBodyMatcher([NotNull] params IMatcher[] matchers) public RequestMessageBodyMatcher([NotNull] params IMatcher[] matchers)
{ {
Check.NotNull(matchers, nameof(matchers)); Guard.NotNull(matchers, nameof(matchers));
Matchers = matchers; Matchers = matchers;
} }

View File

@@ -2,7 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers.Request namespace WireMock.Matchers.Request
{ {
@@ -36,7 +36,7 @@ namespace WireMock.Matchers.Request
/// <param name="matchers">The matchers.</param> /// <param name="matchers">The matchers.</param>
public RequestMessageClientIPMatcher([NotNull] params IStringMatcher[] matchers) public RequestMessageClientIPMatcher([NotNull] params IStringMatcher[] matchers)
{ {
Check.NotNull(matchers, nameof(matchers)); Guard.NotNull(matchers, nameof(matchers));
Matchers = matchers; Matchers = matchers;
} }
@@ -46,7 +46,7 @@ namespace WireMock.Matchers.Request
/// <param name="funcs">The clientIP functions.</param> /// <param name="funcs">The clientIP functions.</param>
public RequestMessageClientIPMatcher([NotNull] params Func<string, bool>[] funcs) public RequestMessageClientIPMatcher([NotNull] params Func<string, bool>[] funcs)
{ {
Check.NotNull(funcs, nameof(funcs)); Guard.NotNull(funcs, nameof(funcs));
Funcs = funcs; Funcs = funcs;
} }

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers.Request namespace WireMock.Matchers.Request
{ {
@@ -27,7 +27,7 @@ namespace WireMock.Matchers.Request
/// <param name="type">The CompositeMatcherType type (Defaults to 'And')</param> /// <param name="type">The CompositeMatcherType type (Defaults to 'And')</param>
protected RequestMessageCompositeMatcher([NotNull] IEnumerable<IRequestMatcher> requestMatchers, CompositeMatcherType type = CompositeMatcherType.And) protected RequestMessageCompositeMatcher([NotNull] IEnumerable<IRequestMatcher> requestMatchers, CompositeMatcherType type = CompositeMatcherType.And)
{ {
Check.NotNull(requestMatchers, nameof(requestMatchers)); Guard.NotNull(requestMatchers, nameof(requestMatchers));
_type = type; _type = type;
RequestMatchers = requestMatchers; RequestMatchers = requestMatchers;

View File

@@ -2,7 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers.Request namespace WireMock.Matchers.Request
{ {
@@ -39,8 +39,8 @@ namespace WireMock.Matchers.Request
/// <param name="matchBehaviour">The match behaviour.</param> /// <param name="matchBehaviour">The match behaviour.</param>
public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, [NotNull] string pattern, bool ignoreCase) public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, [NotNull] string pattern, bool ignoreCase)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNull(pattern, nameof(pattern)); Guard.NotNull(pattern, nameof(pattern));
_matchBehaviour = matchBehaviour; _matchBehaviour = matchBehaviour;
_ignoreCase = ignoreCase; _ignoreCase = ignoreCase;
@@ -58,7 +58,7 @@ namespace WireMock.Matchers.Request
public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, bool ignoreCase, [NotNull] params string[] patterns) : public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, bool ignoreCase, [NotNull] params string[] patterns) :
this(matchBehaviour, name, ignoreCase, patterns.Select(pattern => new WildcardMatcher(matchBehaviour, pattern, ignoreCase)).Cast<IStringMatcher>().ToArray()) this(matchBehaviour, name, ignoreCase, patterns.Select(pattern => new WildcardMatcher(matchBehaviour, pattern, ignoreCase)).Cast<IStringMatcher>().ToArray())
{ {
Check.NotNull(patterns, nameof(patterns)); Guard.NotNull(patterns, nameof(patterns));
} }
/// <summary> /// <summary>
@@ -70,8 +70,8 @@ namespace WireMock.Matchers.Request
/// <param name="ignoreCase">Ignore the case from the pattern.</param> /// <param name="ignoreCase">Ignore the case from the pattern.</param>
public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, bool ignoreCase, [NotNull] params IStringMatcher[] matchers) public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, bool ignoreCase, [NotNull] params IStringMatcher[] matchers)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNull(matchers, nameof(matchers)); Guard.NotNull(matchers, nameof(matchers));
_matchBehaviour = matchBehaviour; _matchBehaviour = matchBehaviour;
Name = name; Name = name;
@@ -85,7 +85,7 @@ namespace WireMock.Matchers.Request
/// <param name="funcs">The funcs.</param> /// <param name="funcs">The funcs.</param>
public RequestMessageCookieMatcher([NotNull] params Func<IDictionary<string, string>, bool>[] funcs) public RequestMessageCookieMatcher([NotNull] params Func<IDictionary<string, string>, bool>[] funcs)
{ {
Check.NotNull(funcs, nameof(funcs)); Guard.NotNull(funcs, nameof(funcs));
Funcs = funcs; Funcs = funcs;
} }

View File

@@ -3,7 +3,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using WireMock.Types; using WireMock.Types;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers.Request namespace WireMock.Matchers.Request
{ {
@@ -40,8 +40,8 @@ namespace WireMock.Matchers.Request
/// <param name="matchBehaviour">The match behaviour.</param> /// <param name="matchBehaviour">The match behaviour.</param>
public RequestMessageHeaderMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, [NotNull] string pattern, bool ignoreCase) public RequestMessageHeaderMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, [NotNull] string pattern, bool ignoreCase)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNull(pattern, nameof(pattern)); Guard.NotNull(pattern, nameof(pattern));
_matchBehaviour = matchBehaviour; _matchBehaviour = matchBehaviour;
_ignoreCase = ignoreCase; _ignoreCase = ignoreCase;
@@ -59,7 +59,7 @@ namespace WireMock.Matchers.Request
public RequestMessageHeaderMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, bool ignoreCase, [NotNull] params string[] patterns) : public RequestMessageHeaderMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, bool ignoreCase, [NotNull] params string[] patterns) :
this(matchBehaviour, name, ignoreCase, patterns.Select(pattern => new WildcardMatcher(matchBehaviour, pattern, ignoreCase)).Cast<IStringMatcher>().ToArray()) this(matchBehaviour, name, ignoreCase, patterns.Select(pattern => new WildcardMatcher(matchBehaviour, pattern, ignoreCase)).Cast<IStringMatcher>().ToArray())
{ {
Check.NotNull(patterns, nameof(patterns)); Guard.NotNull(patterns, nameof(patterns));
} }
/// <summary> /// <summary>
@@ -71,8 +71,8 @@ namespace WireMock.Matchers.Request
/// <param name="ignoreCase">Ignore the case from the pattern.</param> /// <param name="ignoreCase">Ignore the case from the pattern.</param>
public RequestMessageHeaderMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, bool ignoreCase, [NotNull] params IStringMatcher[] matchers) public RequestMessageHeaderMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, bool ignoreCase, [NotNull] params IStringMatcher[] matchers)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNull(matchers, nameof(matchers)); Guard.NotNull(matchers, nameof(matchers));
_matchBehaviour = matchBehaviour; _matchBehaviour = matchBehaviour;
Name = name; Name = name;
@@ -86,7 +86,7 @@ namespace WireMock.Matchers.Request
/// <param name="funcs">The funcs.</param> /// <param name="funcs">The funcs.</param>
public RequestMessageHeaderMatcher([NotNull] params Func<IDictionary<string, string[]>, bool>[] funcs) public RequestMessageHeaderMatcher([NotNull] params Func<IDictionary<string, string[]>, bool>[] funcs)
{ {
Check.NotNull(funcs, nameof(funcs)); Guard.NotNull(funcs, nameof(funcs));
Funcs = funcs; Funcs = funcs;
} }

View File

@@ -1,7 +1,7 @@
using System; using System;
using System.Linq; using System.Linq;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers.Request namespace WireMock.Matchers.Request
{ {
@@ -24,7 +24,7 @@ namespace WireMock.Matchers.Request
/// <param name="methods">The methods.</param> /// <param name="methods">The methods.</param>
public RequestMessageMethodMatcher(MatchBehaviour matchBehaviour, [NotNull] params string[] methods) public RequestMessageMethodMatcher(MatchBehaviour matchBehaviour, [NotNull] params string[] methods)
{ {
Check.NotNull(methods, nameof(methods)); Guard.NotNull(methods, nameof(methods));
_matchBehaviour = matchBehaviour; _matchBehaviour = matchBehaviour;
Methods = methods; Methods = methods;

View File

@@ -3,7 +3,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using WireMock.Types; using WireMock.Types;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers.Request namespace WireMock.Matchers.Request
{ {
@@ -64,7 +64,7 @@ namespace WireMock.Matchers.Request
/// <param name="matchers">The matchers.</param> /// <param name="matchers">The matchers.</param>
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, bool ignoreCase, [CanBeNull] IStringMatcher[] matchers) public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, bool ignoreCase, [CanBeNull] IStringMatcher[] matchers)
{ {
Check.NotNull(key, nameof(key)); Guard.NotNull(key, nameof(key));
_matchBehaviour = matchBehaviour; _matchBehaviour = matchBehaviour;
Key = key; Key = key;
@@ -78,7 +78,7 @@ namespace WireMock.Matchers.Request
/// <param name="funcs">The funcs.</param> /// <param name="funcs">The funcs.</param>
public RequestMessageParamMatcher([NotNull] params Func<IDictionary<string, WireMockList<string>>, bool>[] funcs) public RequestMessageParamMatcher([NotNull] params Func<IDictionary<string, WireMockList<string>>, bool>[] funcs)
{ {
Check.NotNull(funcs, nameof(funcs)); Guard.NotNull(funcs, nameof(funcs));
Funcs = funcs; Funcs = funcs;
} }

View File

@@ -2,7 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers.Request namespace WireMock.Matchers.Request
{ {
@@ -36,7 +36,7 @@ namespace WireMock.Matchers.Request
/// <param name="matchers">The matchers.</param> /// <param name="matchers">The matchers.</param>
public RequestMessagePathMatcher([NotNull] params IStringMatcher[] matchers) public RequestMessagePathMatcher([NotNull] params IStringMatcher[] matchers)
{ {
Check.NotNull(matchers, nameof(matchers)); Guard.NotNull(matchers, nameof(matchers));
Matchers = matchers; Matchers = matchers;
} }
@@ -47,7 +47,7 @@ namespace WireMock.Matchers.Request
/// <param name="funcs">The path functions.</param> /// <param name="funcs">The path functions.</param>
public RequestMessagePathMatcher([NotNull] params Func<string, bool>[] funcs) public RequestMessagePathMatcher([NotNull] params Func<string, bool>[] funcs)
{ {
Check.NotNull(funcs, nameof(funcs)); Guard.NotNull(funcs, nameof(funcs));
Funcs = funcs; Funcs = funcs;
} }

View File

@@ -2,7 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers.Request namespace WireMock.Matchers.Request
{ {
@@ -36,7 +36,7 @@ namespace WireMock.Matchers.Request
/// <param name="matchers">The matchers.</param> /// <param name="matchers">The matchers.</param>
public RequestMessageUrlMatcher([NotNull] params IStringMatcher[] matchers) public RequestMessageUrlMatcher([NotNull] params IStringMatcher[] matchers)
{ {
Check.NotNull(matchers, nameof(matchers)); Guard.NotNull(matchers, nameof(matchers));
Matchers = matchers; Matchers = matchers;
} }
@@ -46,7 +46,7 @@ namespace WireMock.Matchers.Request
/// <param name="funcs">The url functions.</param> /// <param name="funcs">The url functions.</param>
public RequestMessageUrlMatcher([NotNull] params Func<string, bool>[] funcs) public RequestMessageUrlMatcher([NotNull] params Func<string, bool>[] funcs)
{ {
Check.NotNull(funcs, nameof(funcs)); Guard.NotNull(funcs, nameof(funcs));
Funcs = funcs; Funcs = funcs;
} }

View File

@@ -6,7 +6,7 @@ using SimMetrics.Net.API;
using SimMetrics.Net.Metric; using SimMetrics.Net.Metric;
using WireMock.Extensions; using WireMock.Extensions;
using WireMock.Models; using WireMock.Models;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Matchers namespace WireMock.Matchers
{ {
@@ -71,7 +71,7 @@ namespace WireMock.Matchers
/// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param> /// <param name="throwException">Throw an exception when the internal matching fails because of invalid input.</param>
public SimMetricsMatcher(MatchBehaviour matchBehaviour, [NotNull] AnyOf<string, StringPattern>[] patterns, SimMetricType simMetricType = SimMetricType.Levenstein, bool throwException = false) public SimMetricsMatcher(MatchBehaviour matchBehaviour, [NotNull] AnyOf<string, StringPattern>[] patterns, SimMetricType simMetricType = SimMetricType.Levenstein, bool throwException = false)
{ {
Check.NotNull(patterns, nameof(patterns)); Guard.NotNull(patterns, nameof(patterns));
MatchBehaviour = matchBehaviour; MatchBehaviour = matchBehaviour;
ThrowException = throwException; ThrowException = throwException;
@@ -83,9 +83,9 @@ namespace WireMock.Matchers
/// <inheritdoc cref="IStringMatcher.IsMatch"/> /// <inheritdoc cref="IStringMatcher.IsMatch"/>
public double IsMatch(string input) public double IsMatch(string input)
{ {
IStringMetric stringmetricType = GetStringMetricType(); IStringMetric stringMetricType = GetStringMetricType();
return MatchBehaviourHelper.Convert(MatchBehaviour, MatchScores.ToScore(_patterns.Select(p => stringmetricType.GetSimilarity(p.GetPattern(), input)))); return MatchBehaviourHelper.Convert(MatchBehaviour, MatchScores.ToScore(_patterns.Select(p => stringMetricType.GetSimilarity(p.GetPattern(), input))));
} }
private IStringMetric GetStringMetricType() private IStringMetric GetStringMetricType()

View File

@@ -5,7 +5,7 @@ using AnyOfTypes;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Extensions; using WireMock.Extensions;
using WireMock.Models; using WireMock.Models;
using WireMock.Validation; using Stef.Validation;
#if !NETSTANDARD1_3 #if !NETSTANDARD1_3
using Wmhelp.XPath2; using Wmhelp.XPath2;
#endif #endif
@@ -42,7 +42,7 @@ namespace WireMock.Matchers
/// <param name="patterns">The patterns.</param> /// <param name="patterns">The patterns.</param>
public XPathMatcher(MatchBehaviour matchBehaviour, bool throwException = false, [NotNull] params AnyOf<string, StringPattern>[] patterns) public XPathMatcher(MatchBehaviour matchBehaviour, bool throwException = false, [NotNull] params AnyOf<string, StringPattern>[] patterns)
{ {
Check.NotNull(patterns, nameof(patterns)); Guard.NotNull(patterns, nameof(patterns));
MatchBehaviour = matchBehaviour; MatchBehaviour = matchBehaviour;
ThrowException = throwException; ThrowException = throwException;

View File

@@ -1,5 +1,5 @@
using System; using System;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Models namespace WireMock.Models
{ {
@@ -41,8 +41,8 @@ namespace WireMock.Models
/// <param name="url">The URL (relative).</param> /// <param name="url">The URL (relative).</param>
public UrlDetails(Uri absoluteUrl, Uri url) public UrlDetails(Uri absoluteUrl, Uri url)
{ {
Check.NotNull(absoluteUrl, nameof(absoluteUrl)); Guard.NotNull(absoluteUrl, nameof(absoluteUrl));
Check.NotNull(url, nameof(url)); Guard.NotNull(url, nameof(url));
AbsoluteUrl = absoluteUrl; AbsoluteUrl = absoluteUrl;
Url = url; Url = url;

View File

@@ -1,4 +1,4 @@
using System.Collections.Generic; using System.Collections.Generic;
using WireMock.Types; using WireMock.Types;
using WireMock.Util; using WireMock.Util;
@@ -26,5 +26,8 @@ namespace WireMock.Models
/// <inheritdoc cref="IWebhookRequest.TransformerType"/> /// <inheritdoc cref="IWebhookRequest.TransformerType"/>
public TransformerType TransformerType { get; set; } public TransformerType TransformerType { get; set; }
/// <inheritdoc cref="IWebhookRequest.TransformerReplaceNodeOptions"/>
public ReplaceNodeOptions TransformerReplaceNodeOptions { get; set; }
} }
} }

View File

@@ -0,0 +1,48 @@
#if NETCOREAPP3_1_OR_GREATER
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using WireMock.Types;
namespace WireMock.Owin
{
internal partial class AspNetCoreSelfHost
{
public void AddCors(IServiceCollection services)
{
if (_wireMockMiddlewareOptions.CorsPolicyOptions > CorsPolicyOptions.None)
{
/* https://stackoverflow.com/questions/31942037/how-to-enable-cors-in-asp-net-core */
/* Enable Cors */
services.AddCors(corsOptions => corsOptions
.AddPolicy(CorsPolicyName,
corsPolicyBuilder =>
{
if (_wireMockMiddlewareOptions.CorsPolicyOptions.Value.HasFlag(CorsPolicyOptions.AllowAnyHeader))
{
corsPolicyBuilder.AllowAnyHeader();
}
if (_wireMockMiddlewareOptions.CorsPolicyOptions.Value.HasFlag(CorsPolicyOptions.AllowAnyMethod))
{
corsPolicyBuilder.AllowAnyMethod();
}
if (_wireMockMiddlewareOptions.CorsPolicyOptions.Value.HasFlag(CorsPolicyOptions.AllowAnyOrigin))
{
corsPolicyBuilder.AllowAnyOrigin();
}
}));
}
}
public void UseCors(IApplicationBuilder appBuilder)
{
if (_wireMockMiddlewareOptions.CorsPolicyOptions > CorsPolicyOptions.None)
{
/* Use Cors */
appBuilder.UseCors(CorsPolicyName);
}
}
}
}
#endif

View File

@@ -1,10 +1,11 @@
#if USE_ASPNETCORE && !NETSTANDARD1_3 #if USE_ASPNETCORE && !NETSTANDARD1_3
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using WireMock.HttpsCertificate; using WireMock.HttpsCertificate;
using WireMock.Types;
namespace WireMock.Owin namespace WireMock.Owin
{ {

View File

@@ -1,6 +1,7 @@
#if USE_ASPNETCORE #if USE_ASPNETCORE
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -8,15 +9,17 @@ 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 Stef.Validation;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Owin.Mappers; using WireMock.Owin.Mappers;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation;
namespace WireMock.Owin namespace WireMock.Owin
{ {
internal partial class AspNetCoreSelfHost : IOwinSelfHost internal partial class AspNetCoreSelfHost : IOwinSelfHost
{ {
private const string CorsPolicyName = "WireMock.Net - Policy";
private readonly CancellationTokenSource _cts = new CancellationTokenSource(); private readonly CancellationTokenSource _cts = new CancellationTokenSource();
private readonly IWireMockMiddlewareOptions _wireMockMiddlewareOptions; private readonly IWireMockMiddlewareOptions _wireMockMiddlewareOptions;
private readonly IWireMockLogger _logger; private readonly IWireMockLogger _logger;
@@ -35,8 +38,8 @@ namespace WireMock.Owin
public AspNetCoreSelfHost([NotNull] IWireMockMiddlewareOptions wireMockMiddlewareOptions, [NotNull] HostUrlOptions urlOptions) public AspNetCoreSelfHost([NotNull] IWireMockMiddlewareOptions wireMockMiddlewareOptions, [NotNull] HostUrlOptions urlOptions)
{ {
Check.NotNull(wireMockMiddlewareOptions, nameof(wireMockMiddlewareOptions)); Guard.NotNull(wireMockMiddlewareOptions, nameof(wireMockMiddlewareOptions));
Check.NotNull(urlOptions, nameof(urlOptions)); Guard.NotNull(urlOptions, nameof(urlOptions));
_logger = wireMockMiddlewareOptions.Logger ?? new WireMockConsoleLogger(); _logger = wireMockMiddlewareOptions.Logger ?? new WireMockConsoleLogger();
@@ -54,7 +57,7 @@ namespace WireMock.Owin
// a filesystem handler). // a filesystem handler).
if (string.IsNullOrEmpty(AppContext.BaseDirectory)) if (string.IsNullOrEmpty(AppContext.BaseDirectory))
{ {
builder.UseContentRoot(System.IO.Directory.GetCurrentDirectory()); builder.UseContentRoot(Directory.GetCurrentDirectory());
} }
_host = builder _host = builder
@@ -67,12 +70,18 @@ namespace WireMock.Owin
services.AddSingleton<IOwinRequestMapper, OwinRequestMapper>(); services.AddSingleton<IOwinRequestMapper, OwinRequestMapper>();
services.AddSingleton<IOwinResponseMapper, OwinResponseMapper>(); services.AddSingleton<IOwinResponseMapper, OwinResponseMapper>();
#if NETCOREAPP3_1_OR_GREATER
AddCors(services);
#endif
_wireMockMiddlewareOptions.AdditionalServiceRegistration?.Invoke(services); _wireMockMiddlewareOptions.AdditionalServiceRegistration?.Invoke(services);
}) })
.Configure(appBuilder => .Configure(appBuilder =>
{ {
appBuilder.UseMiddleware<GlobalExceptionMiddleware>(); appBuilder.UseMiddleware<GlobalExceptionMiddleware>();
#if NETCOREAPP3_1_OR_GREATER
UseCors(appBuilder);
#endif
_wireMockMiddlewareOptions.PreWireMockMiddlewareInit?.Invoke(appBuilder); _wireMockMiddlewareOptions.PreWireMockMiddlewareInit?.Invoke(appBuilder);
appBuilder.UseMiddleware<WireMockMiddleware>(); appBuilder.UseMiddleware<WireMockMiddleware>();

View File

@@ -1,4 +1,4 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
#if !USE_ASPNETCORE #if !USE_ASPNETCORE
@@ -12,7 +12,7 @@ using IContext = Microsoft.AspNetCore.Http.HttpContext;
using Next = Microsoft.AspNetCore.Http.RequestDelegate; using Next = Microsoft.AspNetCore.Http.RequestDelegate;
#endif #endif
using WireMock.Owin.Mappers; using WireMock.Owin.Mappers;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Owin namespace WireMock.Owin
{ {
@@ -24,8 +24,8 @@ namespace WireMock.Owin
#if !USE_ASPNETCORE #if !USE_ASPNETCORE
public GlobalExceptionMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinResponseMapper responseMapper) : base(next) public GlobalExceptionMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinResponseMapper responseMapper) : base(next)
{ {
Check.NotNull(options, nameof(options)); Guard.NotNull(options, nameof(options));
Check.NotNull(responseMapper, nameof(responseMapper)); Guard.NotNull(responseMapper, nameof(responseMapper));
_options = options; _options = options;
_responseMapper = responseMapper; _responseMapper = responseMapper;
@@ -33,8 +33,8 @@ namespace WireMock.Owin
#else #else
public GlobalExceptionMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinResponseMapper responseMapper) public GlobalExceptionMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinResponseMapper responseMapper)
{ {
Check.NotNull(options, nameof(options)); Guard.NotNull(options, nameof(options));
Check.NotNull(responseMapper, nameof(responseMapper)); Guard.NotNull(responseMapper, nameof(responseMapper));
Next = next; Next = next;
_options = options; _options = options;
@@ -52,19 +52,22 @@ namespace WireMock.Owin
public Task Invoke(IContext ctx) public Task Invoke(IContext ctx)
#endif #endif
{ {
return InvokeInternal(ctx); return InvokeInternalAsync(ctx);
} }
private async Task InvokeInternal(IContext ctx) private async Task InvokeInternalAsync(IContext ctx)
{ {
try try
{ {
await Next?.Invoke(ctx); if (Next != null)
{
await Next.Invoke(ctx).ConfigureAwait(false);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
_options.Logger.Error("HttpStatusCode set to 500 {0}", ex); _options.Logger.Error("HttpStatusCode set to 500 {0}", ex);
await _responseMapper.MapAsync(ResponseMessageBuilder.Create(JsonConvert.SerializeObject(ex), 500), ctx.Response); await _responseMapper.MapAsync(ResponseMessageBuilder.Create(JsonConvert.SerializeObject(ex), 500), ctx.Response).ConfigureAwait(false);
} }
} }
} }

View File

@@ -4,6 +4,8 @@ using WireMock.Handlers;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Util; using WireMock.Util;
using JetBrains.Annotations;
using WireMock.Types;
#if !USE_ASPNETCORE #if !USE_ASPNETCORE
using Owin; using Owin;
#else #else
@@ -39,6 +41,8 @@ namespace WireMock.Owin
#if USE_ASPNETCORE #if USE_ASPNETCORE
Action<IServiceCollection> AdditionalServiceRegistration { get; set; } Action<IServiceCollection> AdditionalServiceRegistration { get; set; }
CorsPolicyOptions? CorsPolicyOptions { get; set; }
#endif #endif
IFileSystemHandler FileSystemHandler { get; set; } IFileSystemHandler FileSystemHandler { get; set; }
@@ -64,5 +68,7 @@ namespace WireMock.Owin
string X509CertificatePassword { get; set; } string X509CertificatePassword { get; set; }
bool CustomCertificateDefined { get; } bool CustomCertificateDefined { get; }
bool? SaveUnmatchedRequests { get; set; }
} }
} }

View File

@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -23,7 +23,7 @@ namespace WireMock.Owin.Mappers
/// <inheritdoc cref="IOwinRequestMapper.MapAsync"/> /// <inheritdoc cref="IOwinRequestMapper.MapAsync"/>
public async Task<RequestMessage> MapAsync(IRequest request, IWireMockMiddlewareOptions options) public async Task<RequestMessage> MapAsync(IRequest request, IWireMockMiddlewareOptions options)
{ {
(UrlDetails urldetails, string clientIP) = ParseRequest(request); var (urlDetails, clientIP) = ParseRequest(request);
string method = request.Method; string method = request.Method;
@@ -65,25 +65,25 @@ namespace WireMock.Owin.Mappers
DecompressGZipAndDeflate = !options.DisableRequestBodyDecompressing.GetValueOrDefault(false) DecompressGZipAndDeflate = !options.DisableRequestBodyDecompressing.GetValueOrDefault(false)
}; };
body = await BodyParser.Parse(bodyParserSettings); body = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false);
} }
return new RequestMessage(urldetails, method, clientIP, body, headers, cookies) { DateTime = DateTime.UtcNow }; return new RequestMessage(urlDetails, method, clientIP, body, headers, cookies) { DateTime = DateTime.UtcNow };
} }
private (UrlDetails UrlDetails, string ClientIP) ParseRequest(IRequest request) private static (UrlDetails UrlDetails, string ClientIP) ParseRequest(IRequest request)
{ {
#if !USE_ASPNETCORE #if !USE_ASPNETCORE
var urldetails = UrlUtils.Parse(request.Uri, request.PathBase); var urlDetails = UrlUtils.Parse(request.Uri, request.PathBase);
string clientIP = request.RemoteIpAddress; string clientIP = request.RemoteIpAddress;
#else #else
var urldetails = UrlUtils.Parse(new Uri(request.GetEncodedUrl()), request.PathBase); var urlDetails = UrlUtils.Parse(new Uri(request.GetEncodedUrl()), request.PathBase);
var connection = request.HttpContext.Connection; var connection = request.HttpContext.Connection;
string clientIP = connection.RemoteIpAddress.IsIPv4MappedToIPv6 string clientIP = connection.RemoteIpAddress.IsIPv4MappedToIPv6
? connection.RemoteIpAddress.MapToIPv4().ToString() ? connection.RemoteIpAddress.MapToIPv4().ToString()
: connection.RemoteIpAddress.ToString(); : connection.RemoteIpAddress.ToString();
#endif #endif
return (urldetails, clientIP); return (urlDetails, clientIP);
} }
} }
} }

View File

@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
@@ -12,7 +12,7 @@ using RandomDataGenerator.Randomizers;
using WireMock.Http; using WireMock.Http;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Types; using WireMock.Types;
using WireMock.Validation; using Stef.Validation;
#if !USE_ASPNETCORE #if !USE_ASPNETCORE
using IResponse = Microsoft.Owin.IOwinResponse; using IResponse = Microsoft.Owin.IOwinResponse;
#else #else
@@ -47,7 +47,7 @@ namespace WireMock.Owin.Mappers
/// <param name="options">The IWireMockMiddlewareOptions.</param> /// <param name="options">The IWireMockMiddlewareOptions.</param>
public OwinResponseMapper(IWireMockMiddlewareOptions options) public OwinResponseMapper(IWireMockMiddlewareOptions options)
{ {
Check.NotNull(options, nameof(options)); Guard.NotNull(options, nameof(options));
_options = options; _options = options;
} }
@@ -103,7 +103,7 @@ namespace WireMock.Owin.Mappers
if (bytes != null) if (bytes != null)
{ {
await response.Body.WriteAsync(bytes, 0, bytes.Length); await response.Body.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
} }
} }

View File

@@ -2,7 +2,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using WireMock.Extensions; using WireMock.Extensions;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Owin namespace WireMock.Owin
{ {
@@ -12,7 +12,7 @@ namespace WireMock.Owin
public MappingMatcher(IWireMockMiddlewareOptions options) public MappingMatcher(IWireMockMiddlewareOptions options)
{ {
Check.NotNull(options, nameof(options)); Guard.NotNull(options, nameof(options));
_options = options; _options = options;
} }

View File

@@ -8,7 +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.Validation; using Stef.Validation;
namespace WireMock.Owin namespace WireMock.Owin
{ {
@@ -22,8 +22,8 @@ namespace WireMock.Owin
public OwinSelfHost([NotNull] IWireMockMiddlewareOptions options, [NotNull] HostUrlOptions urlOptions) public OwinSelfHost([NotNull] IWireMockMiddlewareOptions options, [NotNull] HostUrlOptions urlOptions)
{ {
Check.NotNull(options, nameof(options)); Guard.NotNull(options, nameof(options));
Check.NotNull(urlOptions, nameof(urlOptions)); Guard.NotNull(urlOptions, nameof(urlOptions));
_options = options; _options = options;
_logger = options.Logger ?? new WireMockConsoleLogger(); _logger = options.Logger ?? new WireMockConsoleLogger();
@@ -46,10 +46,7 @@ namespace WireMock.Owin
[PublicAPI] [PublicAPI]
public Task StartAsync() public Task StartAsync()
{ {
return Task.Run(() => return Task.Run(StartServers, _cts.Token);
{
StartServers();
}, _cts.Token);
} }
[PublicAPI] [PublicAPI]

View File

@@ -1,13 +1,13 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using WireMock.Logging;
using System.Linq; using System.Linq;
using Stef.Validation;
using WireMock.Logging;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Http; using WireMock.Http;
using WireMock.Owin.Mappers; using WireMock.Owin.Mappers;
using WireMock.Serialization; using WireMock.Serialization;
using WireMock.Types; using WireMock.Types;
using WireMock.Validation;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Settings; using WireMock.Settings;
#if !USE_ASPNETCORE #if !USE_ASPNETCORE
@@ -35,28 +35,18 @@ namespace WireMock.Owin
#if !USE_ASPNETCORE #if !USE_ASPNETCORE
public WireMockMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinRequestMapper requestMapper, IOwinResponseMapper responseMapper, IMappingMatcher mappingMatcher) : base(next) public WireMockMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinRequestMapper requestMapper, IOwinResponseMapper responseMapper, IMappingMatcher mappingMatcher) : base(next)
{ {
Check.NotNull(options, nameof(options)); _options = Guard.NotNull(options, nameof(options));
Check.NotNull(requestMapper, nameof(requestMapper)); _requestMapper = Guard.NotNull(requestMapper, nameof(requestMapper));
Check.NotNull(responseMapper, nameof(responseMapper)); _responseMapper = Guard.NotNull(responseMapper, nameof(responseMapper));
Check.NotNull(mappingMatcher, nameof(mappingMatcher)); _mappingMatcher = Guard.NotNull(mappingMatcher, nameof(mappingMatcher));
_options = options;
_requestMapper = requestMapper;
_responseMapper = responseMapper;
_mappingMatcher = mappingMatcher;
} }
#else #else
public WireMockMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinRequestMapper requestMapper, IOwinResponseMapper responseMapper, IMappingMatcher mappingMatcher) public WireMockMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinRequestMapper requestMapper, IOwinResponseMapper responseMapper, IMappingMatcher mappingMatcher)
{ {
Check.NotNull(options, nameof(options)); _options = Guard.NotNull(options, nameof(options));
Check.NotNull(requestMapper, nameof(requestMapper)); _requestMapper = Guard.NotNull(requestMapper, nameof(requestMapper));
Check.NotNull(responseMapper, nameof(responseMapper)); _responseMapper = Guard.NotNull(responseMapper, nameof(responseMapper));
Check.NotNull(mappingMatcher, nameof(mappingMatcher)); _mappingMatcher = Guard.NotNull(mappingMatcher, nameof(mappingMatcher));
_options = options;
_requestMapper = requestMapper;
_responseMapper = responseMapper;
_mappingMatcher = mappingMatcher;
} }
#endif #endif
@@ -70,20 +60,18 @@ namespace WireMock.Owin
{ {
lock (_lock) lock (_lock)
{ {
return InvokeInternal(ctx); return InvokeInternalAsync(ctx);
} }
} }
else
{ return InvokeInternalAsync(ctx);
return InvokeInternal(ctx);
}
} }
private async Task InvokeInternal(IContext ctx) private async Task InvokeInternalAsync(IContext ctx)
{ {
var request = await _requestMapper.MapAsync(ctx.Request, _options); var request = await _requestMapper.MapAsync(ctx.Request, _options).ConfigureAwait(false);
bool logRequest = false; var logRequest = false;
ResponseMessage response = null; ResponseMessage response = null;
(MappingMatcherResult Match, MappingMatcherResult Partial) result = (null, null); (MappingMatcherResult Match, MappingMatcherResult Partial) result = (null, null);
try try
@@ -126,22 +114,22 @@ namespace WireMock.Owin
if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero) if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero)
{ {
await Task.Delay(_options.RequestProcessingDelay.Value); await Task.Delay(_options.RequestProcessingDelay.Value).ConfigureAwait(false);
} }
var (theResponse, theOptionalNewMapping) = await targetMapping.ProvideResponseAsync(request); var (theResponse, theOptionalNewMapping) = await targetMapping.ProvideResponseAsync(request).ConfigureAwait(false);
response = theResponse; response = theResponse;
var responseBuilder = targetMapping.Provider as Response; var responseBuilder = targetMapping.Provider as Response;
if (!targetMapping.IsAdminInterface && theOptionalNewMapping != null) if (!targetMapping.IsAdminInterface && theOptionalNewMapping != null)
{ {
if (responseBuilder?.ProxyAndRecordSettings?.SaveMapping == true || targetMapping?.Settings?.ProxyAndRecordSettings?.SaveMapping == true) if (responseBuilder?.ProxyAndRecordSettings?.SaveMapping == true || targetMapping.Settings?.ProxyAndRecordSettings?.SaveMapping == true)
{ {
_options.Mappings.TryAdd(theOptionalNewMapping.Guid, theOptionalNewMapping); _options.Mappings.TryAdd(theOptionalNewMapping.Guid, theOptionalNewMapping);
} }
if (responseBuilder?.ProxyAndRecordSettings?.SaveMappingToFile == true || targetMapping?.Settings?.ProxyAndRecordSettings?.SaveMappingToFile == true) if (responseBuilder?.ProxyAndRecordSettings?.SaveMappingToFile == true || targetMapping.Settings?.ProxyAndRecordSettings?.SaveMappingToFile == true)
{ {
var matcherMapper = new MatcherMapper(targetMapping.Settings); var matcherMapper = new MatcherMapper(targetMapping.Settings);
var mappingConverter = new MappingConverter(matcherMapper); var mappingConverter = new MappingConverter(matcherMapper);
@@ -185,10 +173,23 @@ namespace WireMock.Owin
LogRequest(log, logRequest); LogRequest(log, logRequest);
await _responseMapper.MapAsync(response, ctx.Response); try
{
if (_options.SaveUnmatchedRequests == true && result.Match?.RequestMatchResult.IsPerfectMatch != true)
{
var filename = $"{log.Guid}.LogEntry.json";
_options.FileSystemHandler?.WriteUnmatchedRequest(filename, Util.JsonUtils.Serialize(log));
}
}
catch
{
// Empty catch
}
await _responseMapper.MapAsync(response, ctx.Response).ConfigureAwait(false);
} }
await CompletedTask; await CompletedTask.ConfigureAwait(false);
} }
private async Task SendToWebhooksAsync(IMapping mapping, RequestMessage request, ResponseMessage response) private async Task SendToWebhooksAsync(IMapping mapping, RequestMessage request, ResponseMessage response)

View File

@@ -1,8 +1,9 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using WireMock.Handlers; using WireMock.Handlers;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Types;
using WireMock.Util; using WireMock.Util;
#if !USE_ASPNETCORE #if !USE_ASPNETCORE
using Owin; using Owin;
@@ -39,6 +40,8 @@ namespace WireMock.Owin
#if USE_ASPNETCORE #if USE_ASPNETCORE
public Action<IServiceCollection> AdditionalServiceRegistration { get; set; } public Action<IServiceCollection> AdditionalServiceRegistration { get; set; }
public CorsPolicyOptions? CorsPolicyOptions { get; set; }
#endif #endif
/// <inheritdoc cref="IWireMockMiddlewareOptions.FileSystemHandler"/> /// <inheritdoc cref="IWireMockMiddlewareOptions.FileSystemHandler"/>
@@ -78,5 +81,8 @@ namespace WireMock.Owin
public bool CustomCertificateDefined => public bool CustomCertificateDefined =>
!string.IsNullOrEmpty(X509StoreName) && !string.IsNullOrEmpty(X509StoreLocation) || !string.IsNullOrEmpty(X509StoreName) && !string.IsNullOrEmpty(X509StoreLocation) ||
!string.IsNullOrEmpty(X509CertificateFilePath) && !string.IsNullOrEmpty(X509CertificatePassword); !string.IsNullOrEmpty(X509CertificateFilePath) && !string.IsNullOrEmpty(X509CertificatePassword);
/// <inheritdoc cref="IWireMockMiddlewareOptions.SaveUnmatchedRequests"/>
public bool? SaveUnmatchedRequests { get; set; }
} }
} }

View File

@@ -11,7 +11,7 @@ using WireMock.ResponseBuilders;
using WireMock.Settings; using WireMock.Settings;
using WireMock.Types; using WireMock.Types;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.Proxy namespace WireMock.Proxy
{ {
@@ -21,7 +21,7 @@ namespace WireMock.Proxy
public ProxyHelper([NotNull] IWireMockServerSettings settings) public ProxyHelper([NotNull] IWireMockServerSettings settings)
{ {
_settings = Check.NotNull(settings, nameof(settings)); _settings = Guard.NotNull(settings, nameof(settings));
} }
public async Task<(ResponseMessage Message, IMapping Mapping)> SendAsync( public async Task<(ResponseMessage Message, IMapping Mapping)> SendAsync(
@@ -30,9 +30,9 @@ namespace WireMock.Proxy
[NotNull] RequestMessage requestMessage, [NotNull] RequestMessage requestMessage,
[NotNull] string url) [NotNull] string url)
{ {
Check.NotNull(client, nameof(client)); Guard.NotNull(client, nameof(client));
Check.NotNull(requestMessage, nameof(requestMessage)); Guard.NotNull(requestMessage, nameof(requestMessage));
Check.NotNull(url, nameof(url)); Guard.NotNull(url, nameof(url));
var originalUri = new Uri(requestMessage.Url); var originalUri = new Uri(requestMessage.Url);
var requiredUri = new Uri(url); var requiredUri = new Uri(url);
@@ -41,13 +41,13 @@ namespace WireMock.Proxy
var httpRequestMessage = HttpRequestMessageHelper.Create(requestMessage, url); var httpRequestMessage = HttpRequestMessageHelper.Create(requestMessage, url);
// Call the URL // Call the URL
var httpResponseMessage = await client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead); var httpResponseMessage = await client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);
// Create ResponseMessage // Create ResponseMessage
bool deserializeJson = !_settings.DisableJsonBodyParsing.GetValueOrDefault(false); bool deserializeJson = !_settings.DisableJsonBodyParsing.GetValueOrDefault(false);
bool decompressGzipAndDeflate = !_settings.DisableRequestBodyDecompressing.GetValueOrDefault(false); bool decompressGzipAndDeflate = !_settings.DisableRequestBodyDecompressing.GetValueOrDefault(false);
var responseMessage = await HttpResponseMessageHelper.CreateAsync(httpResponseMessage, requiredUri, originalUri, deserializeJson, decompressGzipAndDeflate); var responseMessage = await HttpResponseMessageHelper.CreateAsync(httpResponseMessage, requiredUri, originalUri, deserializeJson, decompressGzipAndDeflate).ConfigureAwait(false);
IMapping mapping = null; IMapping mapping = null;
if (HttpStatusRangeParser.IsMatch(proxyAndRecordSettings.SaveMappingForStatusCodePattern, responseMessage.StatusCode) && if (HttpStatusRangeParser.IsMatch(proxyAndRecordSettings.SaveMappingForStatusCodePattern, responseMessage.StatusCode) &&

View File

@@ -1,14 +1,17 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.RegularExpressions namespace WireMock.RegularExpressions
{ {
/// <summary> /// <summary>
/// Extension to the <see cref="Regex"/> object, adding support for GUID tokens for matching on. /// Extension to the <see cref="Regex"/> object, adding support for GUID tokens for matching on.
/// </summary> /// </summary>
public class RegexExtended : Regex #if !NETSTANDARD1_3
[Serializable]
#endif
internal class RegexExtended : Regex
{ {
/// <inheritdoc cref="Regex"/> /// <inheritdoc cref="Regex"/>
public RegexExtended(string pattern) : this(pattern, RegexOptions.None) public RegexExtended(string pattern) : this(pattern, RegexOptions.None)
@@ -16,17 +19,24 @@ namespace WireMock.RegularExpressions
} }
/// <inheritdoc cref="Regex"/> /// <inheritdoc cref="Regex"/>
public RegexExtended(string pattern, RegexOptions options) public RegexExtended(string pattern, RegexOptions options) :
: this(pattern, options, Regex.InfiniteMatchTimeout) this(pattern, options, Regex.InfiniteMatchTimeout)
{ {
} }
/// <inheritdoc cref="Regex"/> /// <inheritdoc cref="Regex"/>
public RegexExtended(string pattern, RegexOptions options, TimeSpan matchTimeout) public RegexExtended(string pattern, RegexOptions options, TimeSpan matchTimeout) :
: base(ReplaceGuidPattern(pattern), options, matchTimeout) base(ReplaceGuidPattern(pattern), options, matchTimeout)
{ {
} }
#if !NETSTANDARD1_3
/// <inheritdoc cref="Regex"/>
protected RegexExtended(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) :
base(info, context)
{
}
#endif
// Dictionary of various Guid tokens with a corresponding regular expression pattern to use instead. // Dictionary of various Guid tokens with a corresponding regular expression pattern to use instead.
private static readonly Dictionary<string, string> GuidTokenPatterns = new Dictionary<string, string> private static readonly Dictionary<string, string> GuidTokenPatterns = new Dictionary<string, string>
{ {
@@ -67,7 +77,7 @@ namespace WireMock.RegularExpressions
/// <param name="pattern">Pattern to replace token for.</param> /// <param name="pattern">Pattern to replace token for.</param>
private static string ReplaceGuidPattern(string pattern) private static string ReplaceGuidPattern(string pattern)
{ {
Check.NotNull(pattern, nameof(pattern)); Guard.NotNull(pattern, nameof(pattern));
foreach (var tokenPattern in GuidTokenPatterns) foreach (var tokenPattern in GuidTokenPatterns)
{ {

View File

@@ -1,80 +1,80 @@
using JetBrains.Annotations; using JetBrains.Annotations;
using System; using System;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.Util; using WireMock.Util;
namespace WireMock.RequestBuilders namespace WireMock.RequestBuilders
{ {
/// <summary> /// <summary>
/// The BodyRequestBuilder interface. /// The BodyRequestBuilder interface.
/// </summary> /// </summary>
public interface IBodyRequestBuilder : IRequestMatcher public interface IBodyRequestBuilder : IRequestMatcher
{ {
/// <summary> /// <summary>
/// WithBody: IMatcher /// WithBody: IMatcher
/// </summary> /// </summary>
/// <param name="matcher">The matcher.</param> /// <param name="matcher">The matcher.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithBody([NotNull] IMatcher matcher); IRequestBuilder WithBody([NotNull] IMatcher matcher);
/// <summary> /// <summary>
/// WithBody: IMatcher[] /// WithBody: IMatcher[]
/// </summary> /// </summary>
/// <param name="matchers">The matchers.</param> /// <param name="matchers">The matchers.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithBody([NotNull] IMatcher[] matchers); IRequestBuilder WithBody([NotNull] IMatcher[] matchers);
/// <summary> /// <summary>
/// WithBody: Body as string /// WithBody: Body as string
/// </summary> /// </summary>
/// <param name="body">The body.</param> /// <param name="body">The body.</param>
/// <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>
IRequestBuilder WithBody(string body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); IRequestBuilder WithBody(string body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary> /// <summary>
/// WithBody: Body as byte[] /// WithBody: Body as byte[]
/// </summary> /// </summary>
/// <param name="body">The body.</param> /// <param name="body">The body.</param>
/// <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>
IRequestBuilder WithBody(byte[] body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); IRequestBuilder WithBody(byte[] body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary> /// <summary>
/// WithBody: Body as object /// WithBody: Body as object
/// </summary> /// </summary>
/// <param name="body">The body.</param> /// <param name="body">The body.</param>
/// <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>
IRequestBuilder WithBody(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch); IRequestBuilder WithBody(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary> /// <summary>
/// WithBody: func (string) /// WithBody: func (string)
/// </summary> /// </summary>
/// <param name="func">The function.</param> /// <param name="func">The function.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithBody([NotNull] Func<string, bool> func); IRequestBuilder WithBody([NotNull] Func<string, bool> func);
/// <summary> /// <summary>
/// WithBody: func (byte[]) /// WithBody: func (byte[])
/// </summary> /// </summary>
/// <param name="func">The function.</param> /// <param name="func">The function.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithBody([NotNull] Func<byte[], bool> func); IRequestBuilder WithBody([NotNull] Func<byte[], bool> func);
/// <summary> /// <summary>
/// WithBody: func (json object) /// WithBody: func (json object)
/// </summary> /// </summary>
/// <param name="func">The function.</param> /// <param name="func">The function.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithBody([NotNull] Func<object, bool> func); IRequestBuilder WithBody([NotNull] Func<object, bool> func);
/// <summary> /// <summary>
/// WithBody: func (BodyData object) /// WithBody: func (BodyData object)
/// </summary> /// </summary>
/// <param name="func">The function.</param> /// <param name="func">The function.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns> /// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithBody([NotNull] Func<IBodyData, bool> func); IRequestBuilder WithBody([NotNull] Func<IBodyData, bool> func);
} }
} }

View File

@@ -4,7 +4,7 @@ using System.Linq;
using WireMock.Http; using WireMock.Http;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.RequestBuilders namespace WireMock.RequestBuilders
{ {
@@ -106,7 +106,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IMethodRequestBuilder.UsingMethod(MatchBehaviour, string[])"/> /// <inheritdoc cref="IMethodRequestBuilder.UsingMethod(MatchBehaviour, string[])"/>
public IRequestBuilder UsingMethod(MatchBehaviour matchBehaviour, params string[] methods) public IRequestBuilder UsingMethod(MatchBehaviour matchBehaviour, params string[] methods)
{ {
Check.NotNullOrEmpty(methods, nameof(methods)); Guard.NotNullOrEmpty(methods, nameof(methods));
_requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, methods)); _requestMatchers.Add(new RequestMessageMethodMatcher(matchBehaviour, methods));
return this; return this;

View File

@@ -4,7 +4,7 @@ using System;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.RequestBuilders namespace WireMock.RequestBuilders
{ {
@@ -40,7 +40,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IBodyRequestBuilder.WithBody(IMatcher[])"/> /// <inheritdoc cref="IBodyRequestBuilder.WithBody(IMatcher[])"/>
public IRequestBuilder WithBody(IMatcher[] matchers) public IRequestBuilder WithBody(IMatcher[] matchers)
{ {
Check.NotNull(matchers, nameof(matchers)); Guard.NotNull(matchers, nameof(matchers));
_requestMatchers.Add(new RequestMessageBodyMatcher(matchers)); _requestMatchers.Add(new RequestMessageBodyMatcher(matchers));
return this; return this;
@@ -49,7 +49,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IBodyRequestBuilder.WithBody(Func{string, bool})"/> /// <inheritdoc cref="IBodyRequestBuilder.WithBody(Func{string, bool})"/>
public IRequestBuilder WithBody(Func<string, bool> func) public IRequestBuilder WithBody(Func<string, bool> func)
{ {
Check.NotNull(func, nameof(func)); Guard.NotNull(func, nameof(func));
_requestMatchers.Add(new RequestMessageBodyMatcher(func)); _requestMatchers.Add(new RequestMessageBodyMatcher(func));
return this; return this;
@@ -58,7 +58,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IBodyRequestBuilder.WithBody(Func{byte[], bool})"/> /// <inheritdoc cref="IBodyRequestBuilder.WithBody(Func{byte[], bool})"/>
public IRequestBuilder WithBody(Func<byte[], bool> func) public IRequestBuilder WithBody(Func<byte[], bool> func)
{ {
Check.NotNull(func, nameof(func)); Guard.NotNull(func, nameof(func));
_requestMatchers.Add(new RequestMessageBodyMatcher(func)); _requestMatchers.Add(new RequestMessageBodyMatcher(func));
return this; return this;
@@ -67,7 +67,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IBodyRequestBuilder.WithBody(Func{object, bool})"/> /// <inheritdoc cref="IBodyRequestBuilder.WithBody(Func{object, bool})"/>
public IRequestBuilder WithBody(Func<object, bool> func) public IRequestBuilder WithBody(Func<object, bool> func)
{ {
Check.NotNull(func, nameof(func)); Guard.NotNull(func, nameof(func));
_requestMatchers.Add(new RequestMessageBodyMatcher(func)); _requestMatchers.Add(new RequestMessageBodyMatcher(func));
return this; return this;
@@ -76,7 +76,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IBodyRequestBuilder.WithBody(Func{IBodyData, bool})"/> /// <inheritdoc cref="IBodyRequestBuilder.WithBody(Func{IBodyData, bool})"/>
public IRequestBuilder WithBody(Func<IBodyData, bool> func) public IRequestBuilder WithBody(Func<IBodyData, bool> func)
{ {
Check.NotNull(func, nameof(func)); Guard.NotNull(func, nameof(func));
_requestMatchers.Add(new RequestMessageBodyMatcher(func)); _requestMatchers.Add(new RequestMessageBodyMatcher(func));
return this; return this;

View File

@@ -2,7 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.RequestBuilders namespace WireMock.RequestBuilders
{ {
@@ -17,8 +17,8 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="ICookiesRequestBuilder.WithCookie(string, string, bool, MatchBehaviour)"/> /// <inheritdoc cref="ICookiesRequestBuilder.WithCookie(string, string, bool, MatchBehaviour)"/>
public IRequestBuilder WithCookie(string name, string pattern, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch) public IRequestBuilder WithCookie(string name, string pattern, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNull(pattern, nameof(pattern)); Guard.NotNull(pattern, nameof(pattern));
_requestMatchers.Add(new RequestMessageCookieMatcher(matchBehaviour, name, pattern, ignoreCase)); _requestMatchers.Add(new RequestMessageCookieMatcher(matchBehaviour, name, pattern, ignoreCase));
return this; return this;
@@ -33,8 +33,8 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="ICookiesRequestBuilder.WithCookie(string, string[], bool, MatchBehaviour)"/> /// <inheritdoc cref="ICookiesRequestBuilder.WithCookie(string, string[], bool, MatchBehaviour)"/>
public IRequestBuilder WithCookie(string name, string[] patterns, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch) public IRequestBuilder WithCookie(string name, string[] patterns, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNull(patterns, nameof(patterns)); Guard.NotNull(patterns, nameof(patterns));
_requestMatchers.Add(new RequestMessageCookieMatcher(matchBehaviour, name, ignoreCase, patterns)); _requestMatchers.Add(new RequestMessageCookieMatcher(matchBehaviour, name, ignoreCase, patterns));
return this; return this;
@@ -43,8 +43,8 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="ICookiesRequestBuilder.WithCookie(string, IStringMatcher[])"/> /// <inheritdoc cref="ICookiesRequestBuilder.WithCookie(string, IStringMatcher[])"/>
public IRequestBuilder WithCookie(string name, params IStringMatcher[] matchers) public IRequestBuilder WithCookie(string name, params IStringMatcher[] matchers)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNullOrEmpty(matchers, nameof(matchers)); Guard.NotNullOrEmpty(matchers, nameof(matchers));
_requestMatchers.Add(new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, name, false, matchers)); _requestMatchers.Add(new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, name, false, matchers));
return this; return this;
@@ -53,8 +53,8 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="ICookiesRequestBuilder.WithCookie(string, bool, IStringMatcher[])"/> /// <inheritdoc cref="ICookiesRequestBuilder.WithCookie(string, bool, IStringMatcher[])"/>
public IRequestBuilder WithCookie(string name, bool ignoreCase, params IStringMatcher[] matchers) public IRequestBuilder WithCookie(string name, bool ignoreCase, params IStringMatcher[] matchers)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNullOrEmpty(matchers, nameof(matchers)); Guard.NotNullOrEmpty(matchers, nameof(matchers));
_requestMatchers.Add(new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, name, ignoreCase, matchers)); _requestMatchers.Add(new RequestMessageCookieMatcher(MatchBehaviour.AcceptOnMatch, name, ignoreCase, matchers));
return this; return this;
@@ -63,8 +63,8 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="ICookiesRequestBuilder.WithCookie(string, IStringMatcher[])"/> /// <inheritdoc cref="ICookiesRequestBuilder.WithCookie(string, IStringMatcher[])"/>
public IRequestBuilder WithCookie(string name, bool ignoreCase, MatchBehaviour matchBehaviour, params IStringMatcher[] matchers) public IRequestBuilder WithCookie(string name, bool ignoreCase, MatchBehaviour matchBehaviour, params IStringMatcher[] matchers)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNullOrEmpty(matchers, nameof(matchers)); Guard.NotNullOrEmpty(matchers, nameof(matchers));
_requestMatchers.Add(new RequestMessageCookieMatcher(matchBehaviour, name, ignoreCase, matchers)); _requestMatchers.Add(new RequestMessageCookieMatcher(matchBehaviour, name, ignoreCase, matchers));
return this; return this;
@@ -73,7 +73,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="ICookiesRequestBuilder.WithCookie(Func{IDictionary{string, string}, bool}[])"/> /// <inheritdoc cref="ICookiesRequestBuilder.WithCookie(Func{IDictionary{string, string}, bool}[])"/>
public IRequestBuilder WithCookie(params Func<IDictionary<string, string>, bool>[] funcs) public IRequestBuilder WithCookie(params Func<IDictionary<string, string>, bool>[] funcs)
{ {
Check.NotNullOrEmpty(funcs, nameof(funcs)); Guard.NotNullOrEmpty(funcs, nameof(funcs));
_requestMatchers.Add(new RequestMessageCookieMatcher(funcs)); _requestMatchers.Add(new RequestMessageCookieMatcher(funcs));
return this; return this;

View File

@@ -4,7 +4,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.RequestBuilders namespace WireMock.RequestBuilders
{ {
@@ -19,8 +19,8 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IHeadersRequestBuilder.WithHeader(string, string, bool, MatchBehaviour)"/> /// <inheritdoc cref="IHeadersRequestBuilder.WithHeader(string, string, bool, MatchBehaviour)"/>
public IRequestBuilder WithHeader(string name, string pattern, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch) public IRequestBuilder WithHeader(string name, string pattern, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNull(pattern, nameof(pattern)); Guard.NotNull(pattern, nameof(pattern));
_requestMatchers.Add(new RequestMessageHeaderMatcher(matchBehaviour, name, pattern, ignoreCase)); _requestMatchers.Add(new RequestMessageHeaderMatcher(matchBehaviour, name, pattern, ignoreCase));
return this; return this;
@@ -35,8 +35,8 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IHeadersRequestBuilder.WithHeader(string, string[], bool, MatchBehaviour)"/> /// <inheritdoc cref="IHeadersRequestBuilder.WithHeader(string, string[], bool, MatchBehaviour)"/>
public IRequestBuilder WithHeader(string name, string[] patterns, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch) public IRequestBuilder WithHeader(string name, string[] patterns, bool ignoreCase = true, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNull(patterns, nameof(patterns)); Guard.NotNull(patterns, nameof(patterns));
_requestMatchers.Add(new RequestMessageHeaderMatcher(matchBehaviour, name, ignoreCase, patterns)); _requestMatchers.Add(new RequestMessageHeaderMatcher(matchBehaviour, name, ignoreCase, patterns));
return this; return this;
@@ -45,8 +45,8 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IHeadersRequestBuilder.WithHeader(string, IStringMatcher[])"/> /// <inheritdoc cref="IHeadersRequestBuilder.WithHeader(string, IStringMatcher[])"/>
public IRequestBuilder WithHeader(string name, params IStringMatcher[] matchers) public IRequestBuilder WithHeader(string name, params IStringMatcher[] matchers)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNullOrEmpty(matchers, nameof(matchers)); Guard.NotNullOrEmpty(matchers, nameof(matchers));
_requestMatchers.Add(new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, name, false, matchers)); _requestMatchers.Add(new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, name, false, matchers));
return this; return this;
@@ -55,8 +55,8 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IHeadersRequestBuilder.WithHeader(string, bool, IStringMatcher[])"/> /// <inheritdoc cref="IHeadersRequestBuilder.WithHeader(string, bool, IStringMatcher[])"/>
public IRequestBuilder WithHeader(string name, bool ignoreCase, params IStringMatcher[] matchers) public IRequestBuilder WithHeader(string name, bool ignoreCase, params IStringMatcher[] matchers)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNullOrEmpty(matchers, nameof(matchers)); Guard.NotNullOrEmpty(matchers, nameof(matchers));
_requestMatchers.Add(new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, name, ignoreCase, matchers)); _requestMatchers.Add(new RequestMessageHeaderMatcher(MatchBehaviour.AcceptOnMatch, name, ignoreCase, matchers));
return this; return this;
@@ -65,8 +65,8 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IHeadersRequestBuilder.WithHeader(string, IStringMatcher[])"/> /// <inheritdoc cref="IHeadersRequestBuilder.WithHeader(string, IStringMatcher[])"/>
public IRequestBuilder WithHeader(string name, bool ignoreCase, MatchBehaviour matchBehaviour, params IStringMatcher[] matchers) public IRequestBuilder WithHeader(string name, bool ignoreCase, MatchBehaviour matchBehaviour, params IStringMatcher[] matchers)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
Check.NotNullOrEmpty(matchers, nameof(matchers)); Guard.NotNullOrEmpty(matchers, nameof(matchers));
_requestMatchers.Add(new RequestMessageHeaderMatcher(matchBehaviour, name, ignoreCase, matchers)); _requestMatchers.Add(new RequestMessageHeaderMatcher(matchBehaviour, name, ignoreCase, matchers));
return this; return this;
@@ -75,7 +75,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IHeadersRequestBuilder.WithHeader(Func{IDictionary{string, string[]}, bool}[])"/> /// <inheritdoc cref="IHeadersRequestBuilder.WithHeader(Func{IDictionary{string, string[]}, bool}[])"/>
public IRequestBuilder WithHeader(params Func<IDictionary<string, string[]>, bool>[] funcs) public IRequestBuilder WithHeader(params Func<IDictionary<string, string[]>, bool>[] funcs)
{ {
Check.NotNullOrEmpty(funcs, nameof(funcs)); Guard.NotNullOrEmpty(funcs, nameof(funcs));
_requestMatchers.Add(new RequestMessageHeaderMatcher(funcs)); _requestMatchers.Add(new RequestMessageHeaderMatcher(funcs));
return this; return this;

View File

@@ -5,7 +5,7 @@ using System.Collections.Generic;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.Types; using WireMock.Types;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.RequestBuilders namespace WireMock.RequestBuilders
{ {
@@ -20,7 +20,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, bool, MatchBehaviour)"/> /// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, bool, MatchBehaviour)"/>
public IRequestBuilder WithParam(string key, bool ignoreCase, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch) public IRequestBuilder WithParam(string key, bool ignoreCase, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{ {
Check.NotNull(key, nameof(key)); Guard.NotNull(key, nameof(key));
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase)); _requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase));
return this; return this;
@@ -59,7 +59,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, bool, string[])"/> /// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, bool, string[])"/>
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, bool ignoreCase = false, params string[] values) public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, bool ignoreCase = false, params string[] values)
{ {
Check.NotNull(key, nameof(key)); Guard.NotNull(key, nameof(key));
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase, values)); _requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase, values));
return this; return this;
@@ -74,7 +74,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, bool, IStringMatcher[])"/> /// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, bool, IStringMatcher[])"/>
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, bool ignoreCase, params IStringMatcher[] matchers) public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, bool ignoreCase, params IStringMatcher[] matchers)
{ {
Check.NotNull(key, nameof(key)); Guard.NotNull(key, nameof(key));
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase, matchers)); _requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase, matchers));
return this; return this;
@@ -83,7 +83,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(Func{IDictionary{string, WireMockList{string}}, bool}[])"/> /// <inheritdoc cref="IParamsRequestBuilder.WithParam(Func{IDictionary{string, WireMockList{string}}, bool}[])"/>
public IRequestBuilder WithParam(params Func<IDictionary<string, WireMockList<string>>, bool>[] funcs) public IRequestBuilder WithParam(params Func<IDictionary<string, WireMockList<string>>, bool>[] funcs)
{ {
Check.NotNullOrEmpty(funcs, nameof(funcs)); Guard.NotNullOrEmpty(funcs, nameof(funcs));
_requestMatchers.Add(new RequestMessageParamMatcher(funcs)); _requestMatchers.Add(new RequestMessageParamMatcher(funcs));
return this; return this;

View File

@@ -6,7 +6,7 @@ using System.Collections.ObjectModel;
using System.Linq; using System.Linq;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.RequestBuilders namespace WireMock.RequestBuilders
{ {
@@ -68,7 +68,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IClientIPRequestBuilder.WithClientIP(IStringMatcher[])"/> /// <inheritdoc cref="IClientIPRequestBuilder.WithClientIP(IStringMatcher[])"/>
public IRequestBuilder WithClientIP(params IStringMatcher[] matchers) public IRequestBuilder WithClientIP(params IStringMatcher[] matchers)
{ {
Check.NotNullOrEmpty(matchers, nameof(matchers)); Guard.NotNullOrEmpty(matchers, nameof(matchers));
_requestMatchers.Add(new RequestMessageClientIPMatcher(matchers)); _requestMatchers.Add(new RequestMessageClientIPMatcher(matchers));
return this; return this;
@@ -83,7 +83,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IClientIPRequestBuilder.WithClientIP(string[])"/> /// <inheritdoc cref="IClientIPRequestBuilder.WithClientIP(string[])"/>
public IRequestBuilder WithClientIP(MatchBehaviour matchBehaviour, params string[] clientIPs) public IRequestBuilder WithClientIP(MatchBehaviour matchBehaviour, params string[] clientIPs)
{ {
Check.NotNullOrEmpty(clientIPs, nameof(clientIPs)); Guard.NotNullOrEmpty(clientIPs, nameof(clientIPs));
_requestMatchers.Add(new RequestMessageClientIPMatcher(matchBehaviour, clientIPs)); _requestMatchers.Add(new RequestMessageClientIPMatcher(matchBehaviour, clientIPs));
return this; return this;
@@ -92,7 +92,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IClientIPRequestBuilder.WithClientIP(Func{string, bool}[])"/> /// <inheritdoc cref="IClientIPRequestBuilder.WithClientIP(Func{string, bool}[])"/>
public IRequestBuilder WithClientIP(params Func<string, bool>[] funcs) public IRequestBuilder WithClientIP(params Func<string, bool>[] funcs)
{ {
Check.NotNullOrEmpty(funcs, nameof(funcs)); Guard.NotNullOrEmpty(funcs, nameof(funcs));
_requestMatchers.Add(new RequestMessageClientIPMatcher(funcs)); _requestMatchers.Add(new RequestMessageClientIPMatcher(funcs));
return this; return this;
@@ -101,7 +101,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IUrlAndPathRequestBuilder.WithPath(IStringMatcher[])"/> /// <inheritdoc cref="IUrlAndPathRequestBuilder.WithPath(IStringMatcher[])"/>
public IRequestBuilder WithPath(params IStringMatcher[] matchers) public IRequestBuilder WithPath(params IStringMatcher[] matchers)
{ {
Check.NotNullOrEmpty(matchers, nameof(matchers)); Guard.NotNullOrEmpty(matchers, nameof(matchers));
_requestMatchers.Add(new RequestMessagePathMatcher(matchers)); _requestMatchers.Add(new RequestMessagePathMatcher(matchers));
return this; return this;
@@ -116,7 +116,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IUrlAndPathRequestBuilder.WithPath(MatchBehaviour, string[])"/> /// <inheritdoc cref="IUrlAndPathRequestBuilder.WithPath(MatchBehaviour, string[])"/>
public IRequestBuilder WithPath(MatchBehaviour matchBehaviour, params string[] paths) public IRequestBuilder WithPath(MatchBehaviour matchBehaviour, params string[] paths)
{ {
Check.NotNullOrEmpty(paths, nameof(paths)); Guard.NotNullOrEmpty(paths, nameof(paths));
_requestMatchers.Add(new RequestMessagePathMatcher(matchBehaviour, paths)); _requestMatchers.Add(new RequestMessagePathMatcher(matchBehaviour, paths));
return this; return this;
@@ -125,7 +125,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IUrlAndPathRequestBuilder.WithPath(Func{string, bool}[])"/> /// <inheritdoc cref="IUrlAndPathRequestBuilder.WithPath(Func{string, bool}[])"/>
public IRequestBuilder WithPath(params Func<string, bool>[] funcs) public IRequestBuilder WithPath(params Func<string, bool>[] funcs)
{ {
Check.NotNullOrEmpty(funcs, nameof(funcs)); Guard.NotNullOrEmpty(funcs, nameof(funcs));
_requestMatchers.Add(new RequestMessagePathMatcher(funcs)); _requestMatchers.Add(new RequestMessagePathMatcher(funcs));
return this; return this;
@@ -134,7 +134,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IUrlAndPathRequestBuilder.WithUrl(IStringMatcher[])"/> /// <inheritdoc cref="IUrlAndPathRequestBuilder.WithUrl(IStringMatcher[])"/>
public IRequestBuilder WithUrl(params IStringMatcher[] matchers) public IRequestBuilder WithUrl(params IStringMatcher[] matchers)
{ {
Check.NotNullOrEmpty(matchers, nameof(matchers)); Guard.NotNullOrEmpty(matchers, nameof(matchers));
_requestMatchers.Add(new RequestMessageUrlMatcher(matchers)); _requestMatchers.Add(new RequestMessageUrlMatcher(matchers));
return this; return this;
@@ -149,7 +149,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IUrlAndPathRequestBuilder.WithUrl(MatchBehaviour, string[])"/> /// <inheritdoc cref="IUrlAndPathRequestBuilder.WithUrl(MatchBehaviour, string[])"/>
public IRequestBuilder WithUrl(MatchBehaviour matchBehaviour, params string[] urls) public IRequestBuilder WithUrl(MatchBehaviour matchBehaviour, params string[] urls)
{ {
Check.NotNullOrEmpty(urls, nameof(urls)); Guard.NotNullOrEmpty(urls, nameof(urls));
_requestMatchers.Add(new RequestMessageUrlMatcher(matchBehaviour, urls)); _requestMatchers.Add(new RequestMessageUrlMatcher(matchBehaviour, urls));
return this; return this;
@@ -158,7 +158,7 @@ namespace WireMock.RequestBuilders
/// <inheritdoc cref="IUrlAndPathRequestBuilder.WithUrl(Func{string, bool}[])"/> /// <inheritdoc cref="IUrlAndPathRequestBuilder.WithUrl(Func{string, bool}[])"/>
public IRequestBuilder WithUrl(params Func<string, bool>[] funcs) public IRequestBuilder WithUrl(params Func<string, bool>[] funcs)
{ {
Check.NotNullOrEmpty(funcs, nameof(funcs)); Guard.NotNullOrEmpty(funcs, nameof(funcs));
_requestMatchers.Add(new RequestMessageUrlMatcher(funcs)); _requestMatchers.Add(new RequestMessageUrlMatcher(funcs));
return this; return this;

View File

@@ -8,7 +8,7 @@ using System.Net;
using WireMock.Models; using WireMock.Models;
using WireMock.Types; using WireMock.Types;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation; using Stef.Validation;
namespace WireMock namespace WireMock
{ {
@@ -103,9 +103,9 @@ namespace WireMock
/// <param name="cookies">The cookies.</param> /// <param name="cookies">The cookies.</param>
public RequestMessage([NotNull] UrlDetails urlDetails, [NotNull] string method, [NotNull] string clientIP, [CanBeNull] IBodyData bodyData = null, [CanBeNull] IDictionary<string, string[]> headers = null, [CanBeNull] IDictionary<string, string> cookies = null) public RequestMessage([NotNull] UrlDetails urlDetails, [NotNull] string method, [NotNull] string clientIP, [CanBeNull] IBodyData bodyData = null, [CanBeNull] IDictionary<string, string[]> headers = null, [CanBeNull] IDictionary<string, string> cookies = null)
{ {
Check.NotNull(urlDetails, nameof(urlDetails)); Guard.NotNull(urlDetails, nameof(urlDetails));
Check.NotNull(method, nameof(method)); Guard.NotNull(method, nameof(method));
Check.NotNull(clientIP, nameof(clientIP)); Guard.NotNull(clientIP, nameof(clientIP));
AbsoluteUrl = urlDetails.AbsoluteUrl.ToString(); AbsoluteUrl = urlDetails.AbsoluteUrl.ToString();
Url = urlDetails.Url.ToString(); Url = urlDetails.Url.ToString();

View File

@@ -1,4 +1,4 @@
using WireMock.Types; using WireMock.Types;
namespace WireMock.ResponseBuilders namespace WireMock.ResponseBuilders
{ {
@@ -13,7 +13,15 @@ namespace WireMock.ResponseBuilders
/// <returns> /// <returns>
/// The <see cref="IResponseBuilder"/>. /// The <see cref="IResponseBuilder"/>.
/// </returns> /// </returns>
IResponseBuilder WithTransformer(bool transformContentFromBodyAsFile = false); IResponseBuilder WithTransformer(bool transformContentFromBodyAsFile);
/// <summary>
/// Use the Handlebars.Net ResponseMessage transformer.
/// </summary>
/// <returns>
/// The <see cref="IResponseBuilder"/>.
/// </returns>
IResponseBuilder WithTransformer(ReplaceNodeOptions options);
/// <summary> /// <summary>
/// Use a specific ResponseMessage transformer. /// Use a specific ResponseMessage transformer.
@@ -21,6 +29,6 @@ namespace WireMock.ResponseBuilders
/// <returns> /// <returns>
/// The <see cref="IResponseBuilder"/>. /// The <see cref="IResponseBuilder"/>.
/// </returns> /// </returns>
IResponseBuilder WithTransformer(TransformerType transformerType, bool transformContentFromBodyAsFile = false); IResponseBuilder WithTransformer(TransformerType transformerType = TransformerType.Handlebars, bool transformContentFromBodyAsFile = false, ReplaceNodeOptions options = ReplaceNodeOptions.None);
} }
} }

View File

@@ -1,6 +1,6 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.ResponseBuilders namespace WireMock.ResponseBuilders
{ {
@@ -24,7 +24,7 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="ICallbackResponseBuilder.WithCallback(Func{RequestMessage, ResponseMessage})"/> /// <inheritdoc cref="ICallbackResponseBuilder.WithCallback(Func{RequestMessage, ResponseMessage})"/>
public IResponseBuilder WithCallback(Func<RequestMessage, ResponseMessage> callbackHandler) public IResponseBuilder WithCallback(Func<RequestMessage, ResponseMessage> callbackHandler)
{ {
Check.NotNull(callbackHandler, nameof(callbackHandler)); Guard.NotNull(callbackHandler, nameof(callbackHandler));
return WithCallbackInternal(true, callbackHandler); return WithCallbackInternal(true, callbackHandler);
} }
@@ -32,14 +32,14 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="ICallbackResponseBuilder.WithCallback(Func{RequestMessage, Task{ResponseMessage}})"/> /// <inheritdoc cref="ICallbackResponseBuilder.WithCallback(Func{RequestMessage, Task{ResponseMessage}})"/>
public IResponseBuilder WithCallback(Func<RequestMessage, Task<ResponseMessage>> callbackHandler) public IResponseBuilder WithCallback(Func<RequestMessage, Task<ResponseMessage>> callbackHandler)
{ {
Check.NotNull(callbackHandler, nameof(callbackHandler)); Guard.NotNull(callbackHandler, nameof(callbackHandler));
return WithCallbackInternal(true, callbackHandler); return WithCallbackInternal(true, callbackHandler);
} }
private IResponseBuilder WithCallbackInternal(bool withCallbackUsed, Func<RequestMessage, ResponseMessage> callbackHandler) private IResponseBuilder WithCallbackInternal(bool withCallbackUsed, Func<RequestMessage, ResponseMessage> callbackHandler)
{ {
Check.NotNull(callbackHandler, nameof(callbackHandler)); Guard.NotNull(callbackHandler, nameof(callbackHandler));
WithCallbackUsed = withCallbackUsed; WithCallbackUsed = withCallbackUsed;
Callback = callbackHandler; Callback = callbackHandler;
@@ -49,7 +49,7 @@ namespace WireMock.ResponseBuilders
private IResponseBuilder WithCallbackInternal(bool withCallbackUsed, Func<RequestMessage, Task<ResponseMessage>> callbackHandler) private IResponseBuilder WithCallbackInternal(bool withCallbackUsed, Func<RequestMessage, Task<ResponseMessage>> callbackHandler)
{ {
Check.NotNull(callbackHandler, nameof(callbackHandler)); Guard.NotNull(callbackHandler, nameof(callbackHandler));
WithCallbackUsed = withCallbackUsed; WithCallbackUsed = withCallbackUsed;
CallbackAsync = callbackHandler; CallbackAsync = callbackHandler;

View File

@@ -1,7 +1,7 @@
using System.Net.Http; using System.Net.Http;
using WireMock.Http; using WireMock.Http;
using WireMock.Settings; using WireMock.Settings;
using WireMock.Validation; using Stef.Validation;
namespace WireMock.ResponseBuilders namespace WireMock.ResponseBuilders
{ {
@@ -17,7 +17,7 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IProxyResponseBuilder.WithProxy(string, string)"/> /// <inheritdoc cref="IProxyResponseBuilder.WithProxy(string, string)"/>
public IResponseBuilder WithProxy(string proxyUrl, string clientX509Certificate2ThumbprintOrSubjectName = null) public IResponseBuilder WithProxy(string proxyUrl, string clientX509Certificate2ThumbprintOrSubjectName = null)
{ {
Check.NotNullOrEmpty(proxyUrl, nameof(proxyUrl)); Guard.NotNullOrEmpty(proxyUrl, nameof(proxyUrl));
var settings = new ProxyAndRecordSettings var settings = new ProxyAndRecordSettings
{ {
@@ -31,7 +31,7 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IProxyResponseBuilder.WithProxy(IProxyAndRecordSettings)"/> /// <inheritdoc cref="IProxyResponseBuilder.WithProxy(IProxyAndRecordSettings)"/>
public IResponseBuilder WithProxy(IProxyAndRecordSettings settings) public IResponseBuilder WithProxy(IProxyAndRecordSettings settings)
{ {
Check.NotNull(settings, nameof(settings)); Guard.NotNull(settings, nameof(settings));
ProxyAndRecordSettings = settings; ProxyAndRecordSettings = settings;

View File

@@ -8,6 +8,7 @@ using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
using Stef.Validation;
using WireMock.Proxy; using WireMock.Proxy;
using WireMock.ResponseProviders; using WireMock.ResponseProviders;
using WireMock.Settings; using WireMock.Settings;
@@ -16,7 +17,6 @@ using WireMock.Transformers.Handlebars;
using WireMock.Transformers.Scriban; using WireMock.Transformers.Scriban;
using WireMock.Types; using WireMock.Types;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation;
namespace WireMock.ResponseBuilders namespace WireMock.ResponseBuilders
{ {
@@ -54,10 +54,7 @@ namespace WireMock.ResponseBuilders
return _delay; return _delay;
} }
private set private set => _delay = value;
{
_delay = value;
}
} }
/// <summary> /// <summary>
@@ -71,10 +68,15 @@ namespace WireMock.ResponseBuilders
public TransformerType TransformerType { get; private set; } public TransformerType TransformerType { get; private set; }
/// <summary> /// <summary>
/// Gets a value indicating whether to use the Handlerbars transformer for the content from the referenced BodyAsFile. /// Gets a value indicating whether to use the Handlebars transformer for the content from the referenced BodyAsFile.
/// </summary> /// </summary>
public bool UseTransformerForBodyAsFile { get; private set; } public bool UseTransformerForBodyAsFile { get; private set; }
/// <summary>
/// Gets the ReplaceNodeOptions to use when transforming a JSON node.
/// </summary>
public ReplaceNodeOptions TransformerReplaceNodeOptions { get; private set; }
/// <summary> /// <summary>
/// Gets the response message. /// Gets the response message.
/// </summary> /// </summary>
@@ -100,7 +102,7 @@ namespace WireMock.ResponseBuilders
[PublicAPI] [PublicAPI]
public static IResponseBuilder Create([NotNull] Func<ResponseMessage> func) public static IResponseBuilder Create([NotNull] Func<ResponseMessage> func)
{ {
Check.NotNull(func, nameof(func)); Guard.NotNull(func, nameof(func));
return new Response(func()); return new Response(func());
} }
@@ -162,7 +164,7 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IHeadersResponseBuilder.WithHeader(string, string[])"/> /// <inheritdoc cref="IHeadersResponseBuilder.WithHeader(string, string[])"/>
public IResponseBuilder WithHeader(string name, params string[] values) public IResponseBuilder WithHeader(string name, params string[] values)
{ {
Check.NotNull(name, nameof(name)); Guard.NotNull(name, nameof(name));
ResponseMessage.AddHeader(name, values); ResponseMessage.AddHeader(name, values);
return this; return this;
@@ -171,7 +173,7 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string})"/> /// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string})"/>
public IResponseBuilder WithHeaders(IDictionary<string, string> headers) public IResponseBuilder WithHeaders(IDictionary<string, string> headers)
{ {
Check.NotNull(headers, nameof(headers)); Guard.NotNull(headers, nameof(headers));
ResponseMessage.Headers = headers.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value)); ResponseMessage.Headers = headers.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value));
return this; return this;
@@ -180,7 +182,7 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string[]})"/> /// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string[]})"/>
public IResponseBuilder WithHeaders(IDictionary<string, string[]> headers) public IResponseBuilder WithHeaders(IDictionary<string, string[]> headers)
{ {
Check.NotNull(headers, nameof(headers)); Guard.NotNull(headers, nameof(headers));
ResponseMessage.Headers = headers.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value)); ResponseMessage.Headers = headers.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value));
return this; return this;
@@ -196,7 +198,7 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IBodyResponseBuilder.WithBody(Func{RequestMessage, string}, string, Encoding)"/> /// <inheritdoc cref="IBodyResponseBuilder.WithBody(Func{RequestMessage, string}, string, Encoding)"/>
public IResponseBuilder WithBody(Func<RequestMessage, string> bodyFactory, string destination = BodyDestinationFormat.SameAsSource, Encoding encoding = null) public IResponseBuilder WithBody(Func<RequestMessage, string> bodyFactory, string destination = BodyDestinationFormat.SameAsSource, Encoding encoding = null)
{ {
Check.NotNull(bodyFactory, nameof(bodyFactory)); Guard.NotNull(bodyFactory, nameof(bodyFactory));
return WithCallbackInternal(true, req => new ResponseMessage return WithCallbackInternal(true, req => new ResponseMessage
{ {
@@ -212,14 +214,14 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IBodyResponseBuilder.WithBody(Func{RequestMessage, Task{string}}, string, Encoding)"/> /// <inheritdoc cref="IBodyResponseBuilder.WithBody(Func{RequestMessage, Task{string}}, string, Encoding)"/>
public IResponseBuilder WithBody(Func<RequestMessage, Task<string>> bodyFactory, string destination = BodyDestinationFormat.SameAsSource, Encoding encoding = null) public IResponseBuilder WithBody(Func<RequestMessage, Task<string>> bodyFactory, string destination = BodyDestinationFormat.SameAsSource, Encoding encoding = null)
{ {
Check.NotNull(bodyFactory, nameof(bodyFactory)); Guard.NotNull(bodyFactory, nameof(bodyFactory));
return WithCallbackInternal(true, async req => new ResponseMessage return WithCallbackInternal(true, async req => new ResponseMessage
{ {
BodyData = new BodyData BodyData = new BodyData
{ {
DetectedBodyType = BodyType.String, DetectedBodyType = BodyType.String,
BodyAsString = await bodyFactory(req), BodyAsString = await bodyFactory(req).ConfigureAwait(false),
Encoding = encoding ?? Encoding.UTF8 Encoding = encoding ?? Encoding.UTF8
} }
}); });
@@ -228,7 +230,7 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IBodyResponseBuilder.WithBody(byte[], string, Encoding)"/> /// <inheritdoc cref="IBodyResponseBuilder.WithBody(byte[], string, Encoding)"/>
public IResponseBuilder WithBody(byte[] body, string destination = BodyDestinationFormat.SameAsSource, Encoding encoding = null) public IResponseBuilder WithBody(byte[] body, string destination = BodyDestinationFormat.SameAsSource, Encoding encoding = null)
{ {
Check.NotNull(body, nameof(body)); Guard.NotNull(body, nameof(body));
ResponseMessage.BodyDestination = destination; ResponseMessage.BodyDestination = destination;
ResponseMessage.BodyData = new BodyData(); ResponseMessage.BodyData = new BodyData();
@@ -254,7 +256,7 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromFile"/> /// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromFile"/>
public IResponseBuilder WithBodyFromFile(string filename, bool cache = true) public IResponseBuilder WithBodyFromFile(string filename, bool cache = true)
{ {
Check.NotNull(filename, nameof(filename)); Guard.NotNull(filename, nameof(filename));
ResponseMessage.BodyData = new BodyData ResponseMessage.BodyData = new BodyData
{ {
@@ -277,7 +279,7 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IBodyResponseBuilder.WithBody(string, string, Encoding)"/> /// <inheritdoc cref="IBodyResponseBuilder.WithBody(string, string, Encoding)"/>
public IResponseBuilder WithBody(string body, string destination = BodyDestinationFormat.SameAsSource, Encoding encoding = null) public IResponseBuilder WithBody(string body, string destination = BodyDestinationFormat.SameAsSource, Encoding encoding = null)
{ {
Check.NotNull(body, nameof(body)); Guard.NotNull(body, nameof(body));
encoding = encoding ?? Encoding.UTF8; encoding = encoding ?? Encoding.UTF8;
@@ -312,7 +314,7 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson(object, Encoding, bool?)"/> /// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson(object, Encoding, bool?)"/>
public IResponseBuilder WithBodyAsJson(object body, Encoding encoding = null, bool? indented = null) public IResponseBuilder WithBodyAsJson(object body, Encoding encoding = null, bool? indented = null)
{ {
Check.NotNull(body, nameof(body)); Guard.NotNull(body, nameof(body));
ResponseMessage.BodyDestination = null; ResponseMessage.BodyDestination = null;
ResponseMessage.BodyData = new BodyData ResponseMessage.BodyData = new BodyData
@@ -333,27 +335,33 @@ namespace WireMock.ResponseBuilders
} }
/// <inheritdoc cref="ITransformResponseBuilder.WithTransformer(bool)"/> /// <inheritdoc cref="ITransformResponseBuilder.WithTransformer(bool)"/>
public IResponseBuilder WithTransformer(bool transformContentFromBodyAsFile = false) public IResponseBuilder WithTransformer(bool transformContentFromBodyAsFile)
{ {
UseTransformer = true; return WithTransformer(TransformerType.Handlebars, transformContentFromBodyAsFile);
TransformerType = TransformerType.Handlebars;
UseTransformerForBodyAsFile = transformContentFromBodyAsFile;
return this;
} }
/// <inheritdoc cref="ITransformResponseBuilder.WithTransformer(TransformerType, bool)"/> /// <inheritdoc cref="ITransformResponseBuilder.WithTransformer(ReplaceNodeOptions)"/>
public IResponseBuilder WithTransformer(TransformerType transformerType, bool transformContentFromBodyAsFile = false) public IResponseBuilder WithTransformer(ReplaceNodeOptions options)
{
return WithTransformer(TransformerType.Handlebars, false, options);
}
#pragma warning disable CS1574
/// <inheritdoc cref="ITransformResponseBuilder.WithTransformer(TransformerType, bool, ReplaceNodeOptions)"/>
#pragma warning restore CS1574
public IResponseBuilder WithTransformer(TransformerType transformerType, bool transformContentFromBodyAsFile = false, ReplaceNodeOptions options = ReplaceNodeOptions.None)
{ {
UseTransformer = true; UseTransformer = true;
TransformerType = transformerType; TransformerType = transformerType;
UseTransformerForBodyAsFile = transformContentFromBodyAsFile; UseTransformerForBodyAsFile = transformContentFromBodyAsFile;
TransformerReplaceNodeOptions = options;
return this; return this;
} }
/// <inheritdoc cref="IDelayResponseBuilder.WithDelay(TimeSpan)"/> /// <inheritdoc cref="IDelayResponseBuilder.WithDelay(TimeSpan)"/>
public IResponseBuilder WithDelay(TimeSpan delay) public IResponseBuilder WithDelay(TimeSpan delay)
{ {
Check.Condition(delay, d => d > TimeSpan.Zero, nameof(delay)); Guard.Condition(delay, d => d > TimeSpan.Zero, nameof(delay));
Delay = delay; Delay = delay;
return this; return this;
@@ -368,8 +376,8 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IDelayResponseBuilder.WithRandomDelay(int, int)"/> /// <inheritdoc cref="IDelayResponseBuilder.WithRandomDelay(int, int)"/>
public IResponseBuilder WithRandomDelay(int minimumMilliseconds = 0, int maximumMilliseconds = 60_000) public IResponseBuilder WithRandomDelay(int minimumMilliseconds = 0, int maximumMilliseconds = 60_000)
{ {
Check.Condition(minimumMilliseconds, min => min >= 0, nameof(minimumMilliseconds)); Guard.Condition(minimumMilliseconds, min => min >= 0, nameof(minimumMilliseconds));
Check.Condition(maximumMilliseconds, max => max > minimumMilliseconds, nameof(maximumMilliseconds)); Guard.Condition(maximumMilliseconds, max => max > minimumMilliseconds, nameof(maximumMilliseconds));
MinimumDelayMilliseconds = minimumMilliseconds; MinimumDelayMilliseconds = minimumMilliseconds;
MaximumDelayMilliseconds = maximumMilliseconds; MaximumDelayMilliseconds = maximumMilliseconds;
@@ -380,12 +388,12 @@ namespace WireMock.ResponseBuilders
/// <inheritdoc cref="IResponseProvider.ProvideResponseAsync(RequestMessage, IWireMockServerSettings)"/> /// <inheritdoc cref="IResponseProvider.ProvideResponseAsync(RequestMessage, IWireMockServerSettings)"/>
public async Task<(ResponseMessage Message, IMapping Mapping)> ProvideResponseAsync(RequestMessage requestMessage, IWireMockServerSettings settings) public async Task<(ResponseMessage Message, IMapping Mapping)> ProvideResponseAsync(RequestMessage requestMessage, IWireMockServerSettings settings)
{ {
Check.NotNull(requestMessage, nameof(requestMessage)); Guard.NotNull(requestMessage, nameof(requestMessage));
Check.NotNull(settings, nameof(settings)); Guard.NotNull(settings, nameof(settings));
if (Delay != null) if (Delay != null)
{ {
await Task.Delay(Delay.Value); await Task.Delay(Delay.Value).ConfigureAwait(false);
} }
if (ProxyAndRecordSettings != null && _httpClientForProxy != null) if (ProxyAndRecordSettings != null && _httpClientForProxy != null)
@@ -409,7 +417,7 @@ namespace WireMock.ResponseBuilders
_httpClientForProxy, _httpClientForProxy,
requestMessage, requestMessage,
requestMessage.ProxyUrl requestMessage.ProxyUrl
); ).ConfigureAwait(false);
} }
ResponseMessage responseMessage; ResponseMessage responseMessage;
@@ -425,7 +433,7 @@ namespace WireMock.ResponseBuilders
} }
else else
{ {
responseMessage = await CallbackAsync(requestMessage); responseMessage = await CallbackAsync(requestMessage).ConfigureAwait(false);
} }
// Copy StatusCode from ResponseMessage (if defined) // Copy StatusCode from ResponseMessage (if defined)
@@ -461,7 +469,7 @@ namespace WireMock.ResponseBuilders
throw new NotImplementedException($"TransformerType '{TransformerType}' is not supported."); throw new NotImplementedException($"TransformerType '{TransformerType}' is not supported.");
} }
return (responseMessageTransformer.Transform(requestMessage, responseMessage, UseTransformerForBodyAsFile), null); return (responseMessageTransformer.Transform(requestMessage, responseMessage, UseTransformerForBodyAsFile, TransformerReplaceNodeOptions), null);
} }
if (!UseTransformer && ResponseMessage.BodyData?.BodyAsFileIsCached == true) if (!UseTransformer && ResponseMessage.BodyData?.BodyAsFileIsCached == true)

View File

@@ -5,7 +5,7 @@ using System.Linq;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Types; using WireMock.Types;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation; using Stef.Validation;
namespace WireMock namespace WireMock
{ {
@@ -44,7 +44,7 @@ namespace WireMock
/// <inheritdoc cref="IResponseMessage.AddHeader(string, string[])" /> /// <inheritdoc cref="IResponseMessage.AddHeader(string, string[])" />
public void AddHeader(string name, params string[] values) public void AddHeader(string name, params string[] values)
{ {
Check.NotNullOrEmpty(values, nameof(values)); Guard.NotNullOrEmpty(values, nameof(values));
var newHeaderValues = Headers.TryGetValue(name, out WireMockList<string> existingValues) var newHeaderValues = Headers.TryGetValue(name, out WireMockList<string> existingValues)
? values.Union(existingValues).ToArray() ? values.Union(existingValues).ToArray()

View File

@@ -1,4 +1,4 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using WireMock.Settings; using WireMock.Settings;
@@ -15,7 +15,7 @@ namespace WireMock.ResponseProviders
public async Task<(ResponseMessage Message, IMapping Mapping)> ProvideResponseAsync(RequestMessage requestMessage, IWireMockServerSettings settings) public async Task<(ResponseMessage Message, IMapping Mapping)> ProvideResponseAsync(RequestMessage requestMessage, IWireMockServerSettings settings)
{ {
return (await _responseMessageFunc(requestMessage), null); return (await _responseMessageFunc(requestMessage).ConfigureAwait(false), null);
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show More