mirror of
https://github.com/wiremock/WireMock.Net.git
synced 2026-01-12 13:30:32 +01:00
Compare commits
13 Commits
CommandLin
...
1.0.8.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
658f74ac61 | ||
|
|
1392119f9d | ||
|
|
62550b61e8 | ||
|
|
d736745aff | ||
|
|
34abd05d19 | ||
|
|
f9ab43bf58 | ||
|
|
62823688a3 | ||
|
|
33f40c0e84 | ||
|
|
98097a033e | ||
|
|
d654ef97dc | ||
|
|
4be1483a5f | ||
|
|
cd200a10a4 | ||
|
|
dc36da45ec |
35
CHANGELOG.md
35
CHANGELOG.md
@@ -1,8 +1,39 @@
|
||||
# 1.0.4.21 (09 November 2018)
|
||||
# 1.0.8.0 (12 March 2019)
|
||||
- [#254](https://github.com/WireMock-Net/WireMock.Net/pull/254) - RequestMessageParamMatcher supports Ignore Case for the key [feature] contributed by [StefH](https://github.com/StefH)
|
||||
- [#251](https://github.com/WireMock-Net/WireMock.Net/issues/251) - Problem with Request Match WithBody [question]
|
||||
- [#253](https://github.com/WireMock-Net/WireMock.Net/issues/253) - Request Path and query parameter keys are case-sensitive
|
||||
|
||||
# 1.0.7.0 (19 January 2019)
|
||||
- [#244](https://github.com/WireMock-Net/WireMock.Net/pull/244) - Fix BodyAsFile to also allow relative paths [feature] contributed by [StefH](https://github.com/StefH)
|
||||
- [#240](https://github.com/WireMock-Net/WireMock.Net/issues/240) - How to submit mappings for multiple request, responses [feature]
|
||||
- [#243](https://github.com/WireMock-Net/WireMock.Net/issues/243) - Not able to read response from file [question]
|
||||
|
||||
# 1.0.6.1 (10 January 2019)
|
||||
- [#247](https://github.com/WireMock-Net/WireMock.Net/pull/247) - Issue 225 improve logging in example for wire mock as windows service contributed by [paulssn](https://github.com/paulssn)
|
||||
- [#249](https://github.com/WireMock-Net/WireMock.Net/pull/249) - Fixed "Content-Type multipart/form-data" [bug] contributed by [StefH](https://github.com/StefH)
|
||||
- [#225](https://github.com/WireMock-Net/WireMock.Net/issues/225) - Feature: Improve logging in example for WireMock as Windows Service [feature]
|
||||
- [#238](https://github.com/WireMock-Net/WireMock.Net/issues/238) - Localhost and free port problem [question]
|
||||
- [#245](https://github.com/WireMock-Net/WireMock.Net/issues/245) - Not able to match XML request body using XPathMatcher pattern [question]
|
||||
- [#248](https://github.com/WireMock-Net/WireMock.Net/issues/248) - Content-Type multipart/form-data is not seen as byte[] anymore
|
||||
|
||||
# 1.0.6 (15 December 2018)
|
||||
- [#242](https://github.com/WireMock-Net/WireMock.Net/pull/242) - Post multiple Mappings [feature] contributed by [StefH](https://github.com/StefH)
|
||||
- [#237](https://github.com/WireMock-Net/WireMock.Net/issues/237) - Port not released [question]
|
||||
- [#239](https://github.com/WireMock-Net/WireMock.Net/issues/239) - Not able to hit the mock server if AllowPartialMapping is not set to true [question]
|
||||
|
||||
# 1.0.5 (07 December 2018)
|
||||
- [#236](https://github.com/WireMock-Net/WireMock.Net/pull/236) - Add Random Regex (using Fare) [feature] contributed by [StefH](https://github.com/StefH)
|
||||
|
||||
# 1.0.4.21 (30 November 2018)
|
||||
- [#221](https://github.com/WireMock-Net/WireMock.Net/pull/221) - Update dependencies [feature] contributed by [StefH](https://github.com/StefH)
|
||||
- [#229](https://github.com/WireMock-Net/WireMock.Net/pull/229) - Fix proxy tests [test] contributed by [StefH](https://github.com/StefH)
|
||||
- [#230](https://github.com/WireMock-Net/WireMock.Net/pull/230) - Add HandleBars Random functionality (#219) [feature] contributed by [StefH](https://github.com/StefH)
|
||||
- [#231](https://github.com/WireMock-Net/WireMock.Net/pull/231) - Use RandomDataGenerator.Net 1.0.3.0 contributed by [StefH](https://github.com/StefH)
|
||||
- [#232](https://github.com/WireMock-Net/WireMock.Net/pull/232) - Add SonarLint checks [feature] contributed by [StefH](https://github.com/StefH)
|
||||
- [#233](https://github.com/WireMock-Net/WireMock.Net/pull/233) - RandomDataGenerator.Net 1.0.4 [feature] contributed by [StefH](https://github.com/StefH)
|
||||
- [#235](https://github.com/WireMock-Net/WireMock.Net/pull/235) - Check aggregate exception during startup [bug] contributed by [StefH](https://github.com/StefH)
|
||||
- [#219](https://github.com/WireMock-Net/WireMock.Net/issues/219) - Feature: random value helper [feature]
|
||||
- [#234](https://github.com/WireMock-Net/WireMock.Net/issues/234) - Timeout Exception on VSTS Test Platform (Azure DevOps), with private build agent
|
||||
|
||||
# 1.0.4.20 (07 November 2018)
|
||||
- [#222](https://github.com/WireMock-Net/WireMock.Net/pull/222) - Codecov contributed by [StefH](https://github.com/StefH)
|
||||
@@ -158,7 +189,7 @@
|
||||
- [#124](https://github.com/WireMock-Net/WireMock.Net/issues/124) - Issue: Unable to get host to listen on ips other than 127.0.0.1 using StandAloneApp
|
||||
|
||||
# 1.0.3.15 (05 April 2018)
|
||||
- [#117](https://github.com/WireMock-Net/WireMock.Net/pull/117) - Respect start timeout setting and expose exception from server startup contributed by [msft-eliang](https://github.com/msft-eliang)
|
||||
- [#117](https://github.com/WireMock-Net/WireMock.Net/pull/117) - Respect start timeout setting and expose exception from server startup contributed by [evanlwj](https://github.com/evanlwj)
|
||||
|
||||
# 1.0.3.14 (01 April 2018)
|
||||
- [#111](https://github.com/WireMock-Net/WireMock.Net/issues/111) - Question: Adding wiki documentation on how to use WireMock.Net.WebApplication project
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<VersionPrefix>1.0.4.20</VersionPrefix>
|
||||
<VersionPrefix>1.0.8</VersionPrefix>
|
||||
</PropertyGroup>
|
||||
|
||||
<Choose>
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
https://github.com/StefH/GitHubReleaseNotes
|
||||
|
||||
GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --version 1.0.4.21
|
||||
GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --version 1.0.8.0
|
||||
@@ -5,10 +5,10 @@ A C# .NET version based on [mock4net](https://github.com/alexvictoor/mock4net) w
|
||||
* HTTP response stubbing, matchable on URL/Path, headers, cookies and body content patterns
|
||||
* Runs in unit tests, as a standalone process, as windows service, as Azure or IIS or as docker
|
||||
* Configurable via a fluent DotNet API, JSON files and JSON over HTTP
|
||||
* Record/playback of stubs
|
||||
* Record/playback of stubs (proxying)
|
||||
* Per-request conditional proxying
|
||||
* Stateful behaviour simulation
|
||||
* Configurable response delays
|
||||
* Response transformation
|
||||
|
||||
## Info
|
||||
| | |
|
||||
|
||||
@@ -24,7 +24,7 @@ steps:
|
||||
# - https://github.com/Microsoft/vsts-tasks/issues/8291
|
||||
#
|
||||
- script: |
|
||||
%USERPROFILE%\.dotnet\tools\dotnet-sonarscanner begin /k:"wiremock" /d:sonar.organization="stefh-github" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.login="$(SONAR_TOKEN)" /v:"$(buildId)" /d:sonar.cs.opencover.reportsPaths="**\coverage.opencover.xml"
|
||||
%USERPROFILE%\.dotnet\tools\dotnet-sonarscanner begin /k:"wiremock" /o:"stefh-github" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.login="$(SONAR_TOKEN)" /v:"$(buildId)" /d:sonar.cs.opencover.reportsPaths="**\coverage.opencover.xml"
|
||||
displayName: Begin SonarScanner
|
||||
|
||||
# Build source, tests and run tests for net452 and netcoreapp2.1 (with coverage)
|
||||
|
||||
@@ -18,6 +18,10 @@
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="__admin\mappings\array.json" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\WireMock.Net\WireMock.Net.csproj" />
|
||||
<PackageReference Include="log4net" Version="2.0.8" />
|
||||
@@ -37,6 +41,9 @@
|
||||
<None Update="__admin\mappings\791a3f31-6946-4ce7-8e6f-0237c7443275.json">
|
||||
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="__admin\mappings\MyXmlResponse.xml">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"Request": {
|
||||
"Path": {
|
||||
"Matchers": [
|
||||
{
|
||||
"Name": "WildcardMatcher",
|
||||
"Pattern": "/bodyasfilexmltest",
|
||||
"IgnoreCase": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"Methods": [
|
||||
"get"
|
||||
]
|
||||
},
|
||||
"Response": {
|
||||
"StatusCode": 200,
|
||||
"Headers": {"Content-Type": "application/xml"},
|
||||
"BodyAsFile": "MyXmlResponse.xml",
|
||||
"UseTransformer": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
<xml>
|
||||
<hello>world</hello>
|
||||
</xml>
|
||||
@@ -0,0 +1,46 @@
|
||||
[
|
||||
{
|
||||
"Title": "1",
|
||||
"Request": {
|
||||
"Path": {
|
||||
"Matchers": [
|
||||
{
|
||||
"Name": "WildcardMatcher",
|
||||
"Pattern": "/mappings_static_1"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Methods": [
|
||||
"get"
|
||||
]
|
||||
},
|
||||
"Response": {
|
||||
"BodyAsJson": { "result": "mappings static_1" },
|
||||
"Headers": {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Title": "2",
|
||||
"Request": {
|
||||
"Path": {
|
||||
"Matchers": [
|
||||
{
|
||||
"Name": "WildcardMatcher",
|
||||
"Pattern": "/mappings_static_2"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Methods": [
|
||||
"get"
|
||||
]
|
||||
},
|
||||
"Response": {
|
||||
"BodyAsJson": { "result": "mappings static_2" },
|
||||
"Headers": {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -43,5 +43,11 @@ namespace WireMock.Net.ConsoleApplication
|
||||
{
|
||||
File.WriteAllText(path, text);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.ReadResponseBodyAsFile"/>
|
||||
public byte[] ReadResponseBodyAsFile(string path)
|
||||
{
|
||||
return File.ReadAllBytes(Path.GetFileName(path) == path ? Path.Combine(GetMappingFolder(), path) : path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
using System;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using Newtonsoft.Json;
|
||||
using WireMock.Logging;
|
||||
using WireMock.Matchers;
|
||||
using WireMock.RequestBuilders;
|
||||
@@ -39,7 +39,7 @@ namespace WireMock.Net.ConsoleApplication
|
||||
|
||||
server.SetBasicAuthentication("a", "b");
|
||||
|
||||
server.AllowPartialMapping();
|
||||
// server.AllowPartialMapping();
|
||||
|
||||
server
|
||||
.Given(Request.Create().WithPath(p => p.Contains("x")).UsingGet())
|
||||
@@ -388,11 +388,10 @@ namespace WireMock.Net.ConsoleApplication
|
||||
.WithStatusCode(500)
|
||||
.WithBody(requestMessage =>
|
||||
{
|
||||
string returnStr = JsonConvert.SerializeObject(new
|
||||
return JsonConvert.SerializeObject(new
|
||||
{
|
||||
Message = "Test error"
|
||||
});
|
||||
return returnStr;
|
||||
})
|
||||
);
|
||||
|
||||
@@ -402,26 +401,43 @@ namespace WireMock.Net.ConsoleApplication
|
||||
.WithHeader("Content-Type", "application/json")
|
||||
.WithBodyAsJson(new
|
||||
{
|
||||
Xeger1 = "{{Xeger \"\\w{4}\\d{5}\"}}",
|
||||
Xeger2 = "{{Xeger \"\\d{5}\"}}",
|
||||
TextRegexPostcode = "{{Random Type=\"TextRegex\" Pattern=\"[1-9][0-9]{3}[A-Z]{2}\"}}",
|
||||
Text = "{{Random Type=\"Text\" Min=8 Max=20}}",
|
||||
TextLipsum = "{{Random Type=\"TextLipsum\"}}",
|
||||
IBAN = "{{Random Type=\"IBAN\" CountryCode=\"NL\"}}",
|
||||
TimeSpan1 = "{{Random Type=\"TimeSpan\" Format=\"c\" IncludeMilliseconds=false}}",
|
||||
TimeSpan2 = "{{Random Type=\"TimeSpan\"}}",
|
||||
DateTime1 = "{{Random Type=\"DateTime\"}}",
|
||||
DateTimeNow = DateTime.Now,
|
||||
DateTimeToString = DateTime.Now.ToString("s", CultureInfo.InvariantCulture),
|
||||
DateTimeNowToString = DateTime.Now.ToString("s", CultureInfo.InvariantCulture),
|
||||
Guid1 = "{{Random Type=\"Guid\" Uppercase=false}}",
|
||||
Guid2 = "{{Random Type=\"Guid\"}}",
|
||||
Integer1 = "{{Random Type=\"Integer\" Min=1000 Max=9999}}",
|
||||
Integer2 = "{{#Random Type=\"Integer\" Min=10000000 Max=99999999}}{{this}}{{/Random}}",
|
||||
Double1 = "{{Random Type=\"Double\" Min=10 Max=99}}",
|
||||
Double2 = "{{Random Type=\"Double\" Min=100 Max=999}}",
|
||||
Boolean = "{{Random Type=\"Boolean\"}}",
|
||||
Integer = "{{Random Type=\"Integer\" Min=1000 Max=9999}}",
|
||||
Long = "{{#Random Type=\"Long\" Min=10000000 Max=99999999}}{{this}}{{/Random}}",
|
||||
Double = "{{Random Type=\"Double\" Min=10 Max=99}}",
|
||||
Float = "{{Random Type=\"Float\" Min=100 Max=999}}",
|
||||
IP4Address = "{{Random Type=\"IPv4Address\" Min=\"10.2.3.4\"}}",
|
||||
IP6Address = "{{Random Type=\"IPv6Address\"}}",
|
||||
MACAddress = "{{Random Type=\"MACAddress\" Separator=\"-\"}}"
|
||||
MACAddress = "{{Random Type=\"MACAddress\" Separator=\"-\"}}",
|
||||
StringListValue = "{{Random Type=\"StringList\" Values=[\"a\", \"b\", \"c\"]}}"
|
||||
})
|
||||
.WithTransformer()
|
||||
);
|
||||
|
||||
server
|
||||
.Given(Request.Create()
|
||||
.UsingPost()
|
||||
.WithPath("/xpathsoap")
|
||||
.WithBody(new XPathMatcher("//*[local-name() = 'getMyData']"))
|
||||
)
|
||||
.RespondWith(Response.Create()
|
||||
.WithHeader("Content-Type", "application/xml")
|
||||
.WithBody("<xml>ok</xml>")
|
||||
);
|
||||
|
||||
System.Console.WriteLine("Press any key to stop the server");
|
||||
System.Console.ReadKey();
|
||||
server.Stop();
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using log4net.Config;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.ServiceProcess;
|
||||
using WireMock.Logging;
|
||||
using WireMock.Net.Service;
|
||||
using WireMock.Net.StandAlone;
|
||||
using WireMock.Server;
|
||||
using WireMock.Settings;
|
||||
@@ -21,7 +23,7 @@ namespace Wiremock.Net.Service
|
||||
|
||||
protected override void OnStart(string[] args)
|
||||
{
|
||||
Start(new WireMockNullLogger());
|
||||
Start();
|
||||
}
|
||||
|
||||
protected override void OnStop()
|
||||
@@ -35,6 +37,11 @@ namespace Wiremock.Net.Service
|
||||
|
||||
static void Main(string[] args)
|
||||
{
|
||||
//Setting the current directory explicitly is required if the application is running as Windows Service,
|
||||
//as the current directory of a Windows Service is %WinDir%\System32 per default.
|
||||
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
|
||||
XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net.config"));
|
||||
|
||||
// running as service
|
||||
if (!Environment.UserInteractive)
|
||||
{
|
||||
@@ -46,7 +53,7 @@ namespace Wiremock.Net.Service
|
||||
else
|
||||
{
|
||||
// running as console app
|
||||
Start(new WireMockConsoleLogger());
|
||||
Start();
|
||||
|
||||
Console.WriteLine("Press any key to stop...");
|
||||
Console.ReadKey(true);
|
||||
@@ -55,14 +62,14 @@ namespace Wiremock.Net.Service
|
||||
}
|
||||
}
|
||||
|
||||
private static void Start(IWireMockLogger logger)
|
||||
private static void Start()
|
||||
{
|
||||
_server = StandAloneApp.Start(new FluentMockServerSettings
|
||||
{
|
||||
Urls = new[] { "http://*:9091/" },
|
||||
StartAdminInterface = true,
|
||||
ReadStaticMappings = true,
|
||||
Logger = logger
|
||||
Logger = new WireMockLog4NetLogger()
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,9 @@
|
||||
<Reference Include="Handlebars, Version=1.9.5.0, Culture=neutral, PublicKeyToken=22225d0bf33cd661, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Handlebars.Net.1.9.5\lib\net452\Handlebars.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\log4net.2.0.8\lib\net45-full\log4net.dll</HintPath>
|
||||
</Reference>
|
||||
<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>
|
||||
</Reference>
|
||||
@@ -96,9 +99,13 @@
|
||||
</Compile>
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="WireMockLog4NetLogger.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
<None Include="log4net.config">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="Service-Start.bat">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
|
||||
39
examples/WireMock.Net.Service/WireMockLog4NetLogger.cs
Normal file
39
examples/WireMock.Net.Service/WireMockLog4NetLogger.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using log4net;
|
||||
using Newtonsoft.Json;
|
||||
using Wiremock.Net.Service;
|
||||
using WireMock.Admin.Requests;
|
||||
using WireMock.Logging;
|
||||
|
||||
namespace WireMock.Net.Service
|
||||
{
|
||||
internal class WireMockLog4NetLogger : IWireMockLogger
|
||||
{
|
||||
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
|
||||
|
||||
public void Debug(string formatString, params object[] args)
|
||||
{
|
||||
Log.DebugFormat(formatString, args);
|
||||
}
|
||||
|
||||
public void Info(string formatString, params object[] args)
|
||||
{
|
||||
Log.InfoFormat(formatString, args);
|
||||
}
|
||||
|
||||
public void Warn(string formatString, params object[] args)
|
||||
{
|
||||
Log.WarnFormat(formatString, args);
|
||||
}
|
||||
|
||||
public void Error(string formatString, params object[] args)
|
||||
{
|
||||
Log.ErrorFormat(formatString, args);
|
||||
}
|
||||
|
||||
public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest)
|
||||
{
|
||||
string message = JsonConvert.SerializeObject(logEntryModel, Formatting.Indented);
|
||||
Log.DebugFormat("Admin[{0}] {1}", isAdminRequest, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
38
examples/WireMock.Net.Service/log4net.config
Normal file
38
examples/WireMock.Net.Service/log4net.config
Normal file
@@ -0,0 +1,38 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<configSections>
|
||||
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
|
||||
</configSections>
|
||||
<appSettings>
|
||||
<add key="log4net.Internal.Debug" value="true"/>
|
||||
</appSettings>
|
||||
<log4net>
|
||||
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
|
||||
<layout type="log4net.Layout.PatternLayout">
|
||||
<conversionPattern value="%date [%thread] %-5level %logger{1} - %message%newline" />
|
||||
</layout>
|
||||
</appender>
|
||||
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
|
||||
<file value="log.txt" />
|
||||
<appendToFile value="true" />
|
||||
<rollingStyle value="Size" />
|
||||
<maxSizeRollBackups value="10" />
|
||||
<maximumFileSize value="10000KB" />
|
||||
<staticLogFileName value="true" />
|
||||
<layout type="log4net.Layout.PatternLayout">
|
||||
<conversionPattern value="%date [%thread] %-5level %logger{1} - %message%newline" />
|
||||
</layout>
|
||||
</appender>
|
||||
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
|
||||
<layout type="log4net.Layout.PatternLayout">
|
||||
<conversionPattern value="%date [%thread] %-5level %logger{1} - %message%newline" />
|
||||
</layout>
|
||||
</appender>
|
||||
<root>
|
||||
<level value="DEBUG" />
|
||||
<appender-ref ref="ConsoleAppender" />
|
||||
<appender-ref ref="RollingLogFileAppender" />
|
||||
<!--<appender-ref ref="EventLogAppender" /> --> <!-- comment in if needed -->
|
||||
</root>
|
||||
</log4net>
|
||||
</configuration>
|
||||
@@ -1,6 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Handlebars.Net" version="1.9.5" targetFramework="net452" />
|
||||
<package id="log4net" version="2.0.8" 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.Owin" version="5.2.3" targetFramework="net452" />
|
||||
|
||||
@@ -10,6 +10,11 @@
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Defines if the key should be matched using case-ignore.
|
||||
/// </summary>
|
||||
public bool? IgnoreCase { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the matchers.
|
||||
/// </summary>
|
||||
|
||||
@@ -58,6 +58,14 @@ namespace WireMock.Client
|
||||
[Header("Content-Type", "application/json")]
|
||||
Task<StatusModel> PostMappingAsync([Body] MappingModel mapping);
|
||||
|
||||
/// <summary>
|
||||
/// Add new mappings.
|
||||
/// </summary>
|
||||
/// <param name="mappings">MappingModels</param>
|
||||
[Post("__admin/mappings")]
|
||||
[Header("Content-Type", "application/json")]
|
||||
Task<StatusModel> PostMappingsAsync([Body] IList<MappingModel> mappings);
|
||||
|
||||
/// <summary>
|
||||
/// Delete all mappings.
|
||||
/// </summary>
|
||||
|
||||
35
src/WireMock.Net/Exceptions/WireMockException.cs
Normal file
35
src/WireMock.Net/Exceptions/WireMockException.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
|
||||
namespace WireMock.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// WireMockException
|
||||
/// </summary>
|
||||
/// <seealso cref="Exception" />
|
||||
public class WireMockException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WireMockException"/> class.
|
||||
/// </summary>
|
||||
public WireMockException()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WireMockException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">The message that describes the error.</param>
|
||||
public WireMockException(string message) : base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WireMockException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">The message.</param>
|
||||
/// <param name="inner">The inner.</param>
|
||||
public WireMockException(string message, Exception inner) : base(message, inner)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ namespace WireMock.Handlers
|
||||
/// <summary>
|
||||
/// Gets the folder where the static mappings are located. For local file system, this would be `{CurrentFolder}/__admin/mappings`.
|
||||
/// </summary>
|
||||
/// <returns>The foldername.</returns>
|
||||
/// <returns>The folder name.</returns>
|
||||
string GetMappingFolder();
|
||||
|
||||
/// <summary>
|
||||
@@ -37,6 +37,7 @@ namespace WireMock.Handlers
|
||||
/// Read a static mapping file as text.
|
||||
/// </summary>
|
||||
/// <param name="path">The path (folder + filename with .json extension).</param>
|
||||
/// <returns>The file content as text.</returns>
|
||||
string ReadMappingFile(string path);
|
||||
|
||||
/// <summary>
|
||||
@@ -45,5 +46,12 @@ namespace WireMock.Handlers
|
||||
/// <param name="path">The path (folder + filename with .json extension).</param>
|
||||
/// <param name="text">The text.</param>
|
||||
void WriteMappingFile(string path, string text);
|
||||
|
||||
/// <summary>
|
||||
/// Read a response body file as text.
|
||||
/// </summary>
|
||||
/// <param name="path">The path or filename from the file to read.</param>
|
||||
/// <returns>The file content as bytes.</returns>
|
||||
byte[] ReadResponseBodyAsFile(string path);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using JetBrains.Annotations;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using JetBrains.Annotations;
|
||||
using WireMock.Validation;
|
||||
|
||||
namespace WireMock.Handlers
|
||||
@@ -58,5 +58,15 @@ namespace WireMock.Handlers
|
||||
|
||||
File.WriteAllText(path, text);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.ReadResponseBodyAsFile"/>
|
||||
public byte[] ReadResponseBodyAsFile(string path)
|
||||
{
|
||||
Check.NotNullOrEmpty(path, nameof(path));
|
||||
|
||||
// In case the path is a filename, the path will be adjusted to the MappingFolder.
|
||||
// Else the path will just be as-is.
|
||||
return File.ReadAllBytes(Path.GetFileName(path) == path ? Path.Combine(GetMappingFolder(), path) : path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,11 @@ namespace WireMock.Matchers.Request
|
||||
/// </summary>
|
||||
public string Key { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Defines if the key should be matched using case-ignore.
|
||||
/// </summary>
|
||||
public bool? IgnoreCase { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The matchers.
|
||||
/// </summary>
|
||||
@@ -34,7 +39,8 @@ namespace WireMock.Matchers.Request
|
||||
/// </summary>
|
||||
/// <param name="matchBehaviour">The match behaviour.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key) : this(matchBehaviour, key, (IStringMatcher[])null)
|
||||
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
|
||||
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, bool ignoreCase) : this(matchBehaviour, key, ignoreCase, (IStringMatcher[])null)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -43,8 +49,9 @@ namespace WireMock.Matchers.Request
|
||||
/// </summary>
|
||||
/// <param name="matchBehaviour">The match behaviour.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
|
||||
/// <param name="values">The values.</param>
|
||||
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, [CanBeNull] string[] values) : this(matchBehaviour, key, values?.Select(value => new ExactMatcher(matchBehaviour, value)).Cast<IStringMatcher>().ToArray())
|
||||
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, bool ignoreCase, [CanBeNull] string[] values) : this(matchBehaviour, key, ignoreCase, values?.Select(value => new ExactMatcher(matchBehaviour, value)).Cast<IStringMatcher>().ToArray())
|
||||
{
|
||||
}
|
||||
|
||||
@@ -53,13 +60,15 @@ namespace WireMock.Matchers.Request
|
||||
/// </summary>
|
||||
/// <param name="matchBehaviour">The match behaviour.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
|
||||
/// <param name="matchers">The matchers.</param>
|
||||
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, [CanBeNull] IStringMatcher[] matchers)
|
||||
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, bool ignoreCase, [CanBeNull] IStringMatcher[] matchers)
|
||||
{
|
||||
Check.NotNull(key, nameof(key));
|
||||
|
||||
_matchBehaviour = matchBehaviour;
|
||||
Key = key;
|
||||
IgnoreCase = ignoreCase;
|
||||
Matchers = matchers;
|
||||
}
|
||||
|
||||
@@ -88,7 +97,7 @@ namespace WireMock.Matchers.Request
|
||||
return MatchScores.ToScore(requestMessage.Query != null && Funcs.Any(f => f(requestMessage.Query)));
|
||||
}
|
||||
|
||||
WireMockList<string> valuesPresentInRequestMessage = requestMessage.GetParameter(Key);
|
||||
WireMockList<string> valuesPresentInRequestMessage = requestMessage.GetParameter(Key, IgnoreCase ?? false);
|
||||
if (valuesPresentInRequestMessage == null)
|
||||
{
|
||||
// Key is not present at all, just return Mismatch
|
||||
|
||||
@@ -8,6 +8,7 @@ using JetBrains.Annotations;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.HttpsCertificate;
|
||||
using WireMock.Logging;
|
||||
using WireMock.Owin.Mappers;
|
||||
@@ -58,7 +59,8 @@ namespace WireMock.Owin
|
||||
_host = new WebHostBuilder()
|
||||
.ConfigureServices(services =>
|
||||
{
|
||||
services.AddSingleton<IWireMockMiddlewareOptions>(_options);
|
||||
services.AddSingleton(_options.FileSystemHandler);
|
||||
services.AddSingleton(_options);
|
||||
services.AddSingleton<IMappingMatcher, MappingMatcher>();
|
||||
services.AddSingleton<IOwinRequestMapper, OwinRequestMapper>();
|
||||
services.AddSingleton<IOwinResponseMapper, OwinResponseMapper>();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.ObjectModel;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Logging;
|
||||
using WireMock.Matchers;
|
||||
#if !USE_ASPNETCORE
|
||||
@@ -34,5 +35,7 @@ namespace WireMock.Owin
|
||||
Action<IAppBuilder> PreWireMockMiddlewareInit { get; set; }
|
||||
|
||||
Action<IAppBuilder> PostWireMockMiddlewareInit { get; set; }
|
||||
|
||||
IFileSystemHandler FileSystemHandler { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Http;
|
||||
using WireMock.Util;
|
||||
using WireMock.Validation;
|
||||
#if !USE_ASPNETCORE
|
||||
using IResponse = Microsoft.Owin.IOwinResponse;
|
||||
#else
|
||||
@@ -21,6 +22,7 @@ namespace WireMock.Owin.Mappers
|
||||
/// </summary>
|
||||
public class OwinResponseMapper : IOwinResponseMapper
|
||||
{
|
||||
private readonly IFileSystemHandler _fileSystemHandler;
|
||||
private readonly Encoding _utf8NoBom = new UTF8Encoding(false);
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/78h415ay(v=vs.110).aspx
|
||||
@@ -32,6 +34,17 @@ namespace WireMock.Owin.Mappers
|
||||
{ HttpKnownHeaderNames.ContentType, (r, v) => r.ContentType = v.FirstOrDefault() }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="fileSystemHandler">The IFileSystemHandler.</param>
|
||||
public OwinResponseMapper(IFileSystemHandler fileSystemHandler)
|
||||
{
|
||||
Check.NotNull(fileSystemHandler, nameof(fileSystemHandler));
|
||||
|
||||
_fileSystemHandler = fileSystemHandler;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IOwinResponseMapper.MapAsync"/>
|
||||
public async Task MapAsync(ResponseMessage responseMessage, IResponse response)
|
||||
{
|
||||
@@ -60,7 +73,7 @@ namespace WireMock.Owin.Mappers
|
||||
break;
|
||||
|
||||
case BodyType.File:
|
||||
bytes = File.ReadAllBytes(responseMessage.BodyData.BodyAsFile);
|
||||
bytes = _fileSystemHandler.ReadResponseBodyAsFile(responseMessage.BodyData.BodyAsFile);
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Logging;
|
||||
using WireMock.Owin.Mappers;
|
||||
using WireMock.Util;
|
||||
@@ -75,7 +76,7 @@ namespace WireMock.Owin
|
||||
try
|
||||
{
|
||||
var requestMapper = new OwinRequestMapper();
|
||||
var responseMapper = new OwinResponseMapper();
|
||||
var responseMapper = new OwinResponseMapper(_options.FileSystemHandler);
|
||||
var matcher = new MappingMatcher(_options);
|
||||
|
||||
Action<IAppBuilder> startup = app =>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.ObjectModel;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Logging;
|
||||
using WireMock.Matchers;
|
||||
using WireMock.Util;
|
||||
@@ -35,5 +36,8 @@ namespace WireMock.Owin
|
||||
public Action<IAppBuilder> PreWireMockMiddlewareInit { get; set; }
|
||||
|
||||
public Action<IAppBuilder> PostWireMockMiddlewareInit { get; set; }
|
||||
|
||||
/// <inheritdoc cref="IWireMockMiddlewareOptions.FileSystemHandler"/>
|
||||
public IFileSystemHandler FileSystemHandler { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using System;
|
||||
using JetBrains.Annotations;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using JetBrains.Annotations;
|
||||
using WireMock.Matchers;
|
||||
using WireMock.Util;
|
||||
|
||||
@@ -19,6 +19,15 @@ namespace WireMock.RequestBuilders
|
||||
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
|
||||
IRequestBuilder WithParam([NotNull] string key, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
|
||||
|
||||
/// <summary>
|
||||
/// WithParam: matching on key only.
|
||||
/// </summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
|
||||
/// <param name="matchBehaviour">The match behaviour (optional).</param>
|
||||
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
|
||||
IRequestBuilder WithParam([NotNull] string key, bool ignoreCase, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
|
||||
|
||||
/// <summary>
|
||||
/// WithParam: matching on key and values.
|
||||
/// </summary>
|
||||
@@ -27,6 +36,15 @@ namespace WireMock.RequestBuilders
|
||||
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
|
||||
IRequestBuilder WithParam([NotNull] string key, [CanBeNull] params string[] values);
|
||||
|
||||
/// <summary>
|
||||
/// WithParam: matching on key and values.
|
||||
/// </summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
|
||||
/// <param name="values">The values.</param>
|
||||
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
|
||||
IRequestBuilder WithParam([NotNull] string key, bool ignoreCase, [CanBeNull] params string[] values);
|
||||
|
||||
/// <summary>
|
||||
/// WithParam: matching on key and matchers.
|
||||
/// </summary>
|
||||
@@ -35,6 +53,15 @@ namespace WireMock.RequestBuilders
|
||||
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
|
||||
IRequestBuilder WithParam([NotNull] string key, [CanBeNull] params IStringMatcher[] matchers);
|
||||
|
||||
/// <summary>
|
||||
/// WithParam: matching on key and matchers.
|
||||
/// </summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
|
||||
/// <param name="matchers">The matchers.</param>
|
||||
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
|
||||
IRequestBuilder WithParam([NotNull] string key, bool ignoreCase, [CanBeNull] params IStringMatcher[] matchers);
|
||||
|
||||
/// <summary>
|
||||
/// WithParam: matching on key, values and matchBehaviour.
|
||||
/// </summary>
|
||||
@@ -44,6 +71,16 @@ namespace WireMock.RequestBuilders
|
||||
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
|
||||
IRequestBuilder WithParam([NotNull] string key, MatchBehaviour matchBehaviour, [CanBeNull] params string[] values);
|
||||
|
||||
/// <summary>
|
||||
/// WithParam: matching on key, values and matchBehaviour.
|
||||
/// </summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
|
||||
/// <param name="values">The values.</param>
|
||||
/// <param name="matchBehaviour">The match behaviour.</param>
|
||||
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
|
||||
IRequestBuilder WithParam([NotNull] string key, MatchBehaviour matchBehaviour, bool ignoreCase = false, [CanBeNull] params string[] values);
|
||||
|
||||
/// <summary>
|
||||
/// WithParam: matching on key, matchers and matchBehaviour.
|
||||
/// </summary>
|
||||
@@ -53,6 +90,16 @@ namespace WireMock.RequestBuilders
|
||||
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
|
||||
IRequestBuilder WithParam([NotNull] string key, MatchBehaviour matchBehaviour, [CanBeNull] params IStringMatcher[] matchers);
|
||||
|
||||
/// <summary>
|
||||
/// WithParam: matching on key, matchers and matchBehaviour.
|
||||
/// </summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
|
||||
/// <param name="matchers">The matchers.</param>
|
||||
/// <param name="matchBehaviour">The match behaviour.</param>
|
||||
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
|
||||
IRequestBuilder WithParam([NotNull] string key, MatchBehaviour matchBehaviour, bool ignoreCase = false, [CanBeNull] params IStringMatcher[] matchers);
|
||||
|
||||
/// <summary>
|
||||
/// WithParam: matching on functions.
|
||||
/// </summary>
|
||||
|
||||
89
src/WireMock.Net/RequestBuilders/Request.Params.cs
Normal file
89
src/WireMock.Net/RequestBuilders/Request.Params.cs
Normal file
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using WireMock.Matchers;
|
||||
using WireMock.Matchers.Request;
|
||||
using WireMock.Util;
|
||||
using WireMock.Validation;
|
||||
|
||||
namespace WireMock.RequestBuilders
|
||||
{
|
||||
public partial class Request
|
||||
{
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour)"/>
|
||||
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
|
||||
{
|
||||
return WithParam(key, false, matchBehaviour);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, bool, MatchBehaviour)"/>
|
||||
public IRequestBuilder WithParam(string key, bool ignoreCase, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
|
||||
{
|
||||
Check.NotNull(key, nameof(key));
|
||||
|
||||
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase));
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, string[])"/>
|
||||
public IRequestBuilder WithParam(string key, params string[] values)
|
||||
{
|
||||
return WithParam(key, MatchBehaviour.AcceptOnMatch, false, values);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, bool, string[])"/>
|
||||
public IRequestBuilder WithParam(string key, bool ignoreCase, params string[] values)
|
||||
{
|
||||
return WithParam(key, MatchBehaviour.AcceptOnMatch, ignoreCase, values);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, IStringMatcher[])"/>
|
||||
public IRequestBuilder WithParam(string key, params IStringMatcher[] matchers)
|
||||
{
|
||||
return WithParam(key, MatchBehaviour.AcceptOnMatch, false, matchers);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, bool, IStringMatcher[])"/>
|
||||
public IRequestBuilder WithParam(string key, bool ignoreCase, params IStringMatcher[] matchers)
|
||||
{
|
||||
return WithParam(key, MatchBehaviour.AcceptOnMatch, ignoreCase, matchers);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, string[])"/>
|
||||
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, params string[] values)
|
||||
{
|
||||
return WithParam(key, matchBehaviour, false, values);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, bool, string[])"/>
|
||||
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, bool ignoreCase = false, params string[] values)
|
||||
{
|
||||
Check.NotNull(key, nameof(key));
|
||||
|
||||
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase, values));
|
||||
return this;
|
||||
}
|
||||
|
||||
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, params IStringMatcher[] matchers)
|
||||
{
|
||||
return WithParam(key, matchBehaviour, false, matchers);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, bool, IStringMatcher[])"/>
|
||||
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, bool ignoreCase, params IStringMatcher[] matchers)
|
||||
{
|
||||
Check.NotNull(key, nameof(key));
|
||||
|
||||
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase, matchers));
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(Func{IDictionary{string, WireMockList{T}}, bool}[])"/>
|
||||
public IRequestBuilder WithParam(params Func<IDictionary<string, WireMockList<string>>, bool>[] funcs)
|
||||
{
|
||||
Check.NotNullOrEmpty(funcs, nameof(funcs));
|
||||
|
||||
_requestMatchers.Add(new RequestMessageParamMatcher(funcs));
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ namespace WireMock.RequestBuilders
|
||||
/// <summary>
|
||||
/// The requests.
|
||||
/// </summary>
|
||||
public class Request : RequestMessageCompositeMatcher, IRequestBuilder
|
||||
public partial class Request : RequestMessageCompositeMatcher, IRequestBuilder
|
||||
{
|
||||
private readonly IList<IRequestMatcher> _requestMatchers;
|
||||
|
||||
@@ -291,54 +291,6 @@ namespace WireMock.RequestBuilders
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour)"/>
|
||||
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
|
||||
{
|
||||
Check.NotNull(key, nameof(key));
|
||||
|
||||
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key));
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, string[])"/>
|
||||
public IRequestBuilder WithParam(string key, params string[] values)
|
||||
{
|
||||
return WithParam(key, MatchBehaviour.AcceptOnMatch, values);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, IStringMatcher[])"/>
|
||||
public IRequestBuilder WithParam(string key, params IStringMatcher[] matchers)
|
||||
{
|
||||
return WithParam(key, MatchBehaviour.AcceptOnMatch, matchers);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, string[])"/>
|
||||
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, params string[] values)
|
||||
{
|
||||
Check.NotNull(key, nameof(key));
|
||||
|
||||
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, values));
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, IStringMatcher[])"/>
|
||||
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, params IStringMatcher[] matchers)
|
||||
{
|
||||
Check.NotNull(key, nameof(key));
|
||||
|
||||
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, matchers));
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(Func{IDictionary{string, WireMockList{string}}, bool}[])"/>
|
||||
public IRequestBuilder WithParam(params Func<IDictionary<string, WireMockList<string>>, bool>[] funcs)
|
||||
{
|
||||
Check.NotNullOrEmpty(funcs, nameof(funcs));
|
||||
|
||||
_requestMatchers.Add(new RequestMessageParamMatcher(funcs));
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IHeadersAndCookiesRequestBuilder.WithHeader(string, string, MatchBehaviour)"/>
|
||||
public IRequestBuilder WithHeader(string name, string pattern, MatchBehaviour matchBehaviour)
|
||||
{
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
using System;
|
||||
using JetBrains.Annotations;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using JetBrains.Annotations;
|
||||
using WireMock.Models;
|
||||
using WireMock.Util;
|
||||
using WireMock.Validation;
|
||||
@@ -211,15 +211,18 @@ namespace WireMock
|
||||
/// Get a query parameter.
|
||||
/// </summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
|
||||
/// <returns>The query parameter.</returns>
|
||||
public WireMockList<string> GetParameter(string key)
|
||||
public WireMockList<string> GetParameter(string key, bool ignoreCase = false)
|
||||
{
|
||||
if (Query == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return Query.ContainsKey(key) ? Query[key] : null;
|
||||
var query = !ignoreCase ? Query : new Dictionary<string, WireMockList<string>>(Query, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
return query.ContainsKey(key) ? query[key] : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
using JetBrains.Annotations;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using JetBrains.Annotations;
|
||||
using Newtonsoft.Json;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Http;
|
||||
using WireMock.Settings;
|
||||
using WireMock.Transformers;
|
||||
@@ -21,6 +21,7 @@ namespace WireMock.ResponseBuilders
|
||||
/// </summary>
|
||||
public class Response : IResponseBuilder
|
||||
{
|
||||
private readonly IFileSystemHandler _fileSystemHandler = new LocalFileSystemHandler();
|
||||
private HttpClient _httpClientForProxy;
|
||||
|
||||
/// <summary>
|
||||
@@ -226,7 +227,7 @@ namespace WireMock.ResponseBuilders
|
||||
if (cache)
|
||||
{
|
||||
ResponseMessage.BodyData.DetectedBodyType = BodyType.Bytes;
|
||||
ResponseMessage.BodyData.BodyAsBytes = File.ReadAllBytes(filename);
|
||||
ResponseMessage.BodyData.BodyAsBytes = _fileSystemHandler.ReadResponseBodyAsFile(filename);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -255,7 +256,7 @@ namespace WireMock.ResponseBuilders
|
||||
{
|
||||
case BodyDestinationFormat.Bytes:
|
||||
ResponseMessage.BodyData.DetectedBodyType = BodyType.Bytes;
|
||||
ResponseMessage.BodyData.BodyAsBytes= encoding.GetBytes(body);
|
||||
ResponseMessage.BodyData.BodyAsBytes = encoding.GetBytes(body);
|
||||
break;
|
||||
|
||||
case BodyDestinationFormat.Json:
|
||||
@@ -285,7 +286,7 @@ namespace WireMock.ResponseBuilders
|
||||
BodyAsJson = body,
|
||||
BodyAsJsonIndented = indented
|
||||
};
|
||||
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,7 @@ namespace WireMock.Serialization
|
||||
Params = paramsMatchers != null && paramsMatchers.Any() ? paramsMatchers.Select(pm => new ParamModel
|
||||
{
|
||||
Name = pm.Key,
|
||||
IgnoreCase = pm.IgnoreCase,
|
||||
Matchers = MatcherMapper.Map(pm.Matchers)
|
||||
}).ToList() : null,
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
using JetBrains.Annotations;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
@@ -5,9 +8,6 @@ using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using JetBrains.Annotations;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using WireMock.Admin.Mappings;
|
||||
using WireMock.Admin.Scenarios;
|
||||
using WireMock.Admin.Settings;
|
||||
@@ -206,14 +206,17 @@ namespace WireMock.Server
|
||||
|
||||
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(path);
|
||||
|
||||
MappingModel mappingModel = JsonConvert.DeserializeObject<MappingModel>(_fileSystemHandler.ReadMappingFile(path));
|
||||
if (Guid.TryParse(filenameWithoutExtension, out Guid guidFromFilename))
|
||||
var mappingModels = DeserializeObjectToArray<MappingModel>(JsonConvert.DeserializeObject(_fileSystemHandler.ReadMappingFile(path)));
|
||||
foreach (var mappingModel in mappingModels)
|
||||
{
|
||||
DeserializeAndAddOrUpdateMapping(mappingModel, guidFromFilename, path);
|
||||
}
|
||||
else
|
||||
{
|
||||
DeserializeAndAddOrUpdateMapping(mappingModel, null, path);
|
||||
if (mappingModels.Length == 1 && Guid.TryParse(filenameWithoutExtension, out Guid guidFromFilename))
|
||||
{
|
||||
DeserializeAndAddOrUpdateMapping(mappingModel, guidFromFilename, path);
|
||||
}
|
||||
else
|
||||
{
|
||||
DeserializeAndAddOrUpdateMapping(mappingModel, null, path);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
@@ -262,7 +265,7 @@ namespace WireMock.Server
|
||||
request.WithPath(requestMessage.Path);
|
||||
request.UsingMethod(requestMessage.Method);
|
||||
|
||||
requestMessage.Query.Loop((key, value) => request.WithParam(key, value.ToArray()));
|
||||
requestMessage.Query.Loop((key, value) => request.WithParam(key, false, value.ToArray()));
|
||||
requestMessage.Cookies.Loop((key, value) => request.WithCookie(key, value));
|
||||
|
||||
var allBlackListedHeaders = new List<string>(blacklistedHeaders) { "Cookie" };
|
||||
@@ -412,11 +415,21 @@ namespace WireMock.Server
|
||||
|
||||
private ResponseMessage MappingsPost(RequestMessage requestMessage)
|
||||
{
|
||||
Guid? guid;
|
||||
try
|
||||
{
|
||||
var mappingModel = DeserializeObject<MappingModel>(requestMessage);
|
||||
guid = DeserializeAndAddOrUpdateMapping(mappingModel);
|
||||
var mappingModels = DeserializeRequestMessageToArray<MappingModel>(requestMessage);
|
||||
if (mappingModels.Length == 1)
|
||||
{
|
||||
Guid? guid = DeserializeAndAddOrUpdateMapping(mappingModels[0]);
|
||||
return ResponseMessageBuilder.Create("Mapping added", 201, guid);
|
||||
}
|
||||
|
||||
foreach (var mappingModel in mappingModels)
|
||||
{
|
||||
DeserializeAndAddOrUpdateMapping(mappingModel);
|
||||
}
|
||||
|
||||
return ResponseMessageBuilder.Create("Mappings added", 201);
|
||||
}
|
||||
catch (ArgumentException a)
|
||||
{
|
||||
@@ -428,8 +441,6 @@ namespace WireMock.Server
|
||||
_logger.Error("HttpStatusCode set to 500 {0}", e);
|
||||
return ResponseMessageBuilder.Create(e.ToString(), 500);
|
||||
}
|
||||
|
||||
return ResponseMessageBuilder.Create("Mapping added", 201, guid);
|
||||
}
|
||||
|
||||
private Guid? DeserializeAndAddOrUpdateMapping(MappingModel mappingModel, Guid? guid = null, string path = null)
|
||||
@@ -674,7 +685,8 @@ namespace WireMock.Server
|
||||
{
|
||||
foreach (var paramModel in requestModel.Params.Where(c => c.Matchers != null))
|
||||
{
|
||||
requestBuilder = requestBuilder.WithParam(paramModel.Name, paramModel.Matchers.Select(MatcherMapper.Map).Cast<IStringMatcher>().ToArray());
|
||||
bool ignoreCase = paramModel?.IgnoreCase ?? false;
|
||||
requestBuilder = requestBuilder.WithParam(paramModel.Name, ignoreCase, paramModel.Matchers.Select(MatcherMapper.Map).Cast<IStringMatcher>().ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -793,5 +805,28 @@ namespace WireMock.Server
|
||||
|
||||
return default(T);
|
||||
}
|
||||
|
||||
private T[] DeserializeRequestMessageToArray<T>(RequestMessage requestMessage)
|
||||
{
|
||||
if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json)
|
||||
{
|
||||
var bodyAsJson = requestMessage.BodyData.BodyAsJson;
|
||||
|
||||
return DeserializeObjectToArray<T>(bodyAsJson);
|
||||
}
|
||||
|
||||
return default(T[]);
|
||||
}
|
||||
|
||||
private T[] DeserializeObjectToArray<T>(object value)
|
||||
{
|
||||
if (value is JArray jArray)
|
||||
{
|
||||
return jArray.ToObject<T[]>();
|
||||
}
|
||||
|
||||
var singleResult = ((JObject)value).ToObject<T>();
|
||||
return new[] { singleResult };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using Newtonsoft.Json;
|
||||
using WireMock.Exceptions;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Logging;
|
||||
using WireMock.Matchers;
|
||||
@@ -202,6 +203,7 @@ namespace WireMock.Server
|
||||
Urls = new[] { $"{(settings.UseSSL == true ? "https" : "http")}://localhost:{port}" };
|
||||
}
|
||||
|
||||
_options.FileSystemHandler = settings.FileSystemHandler;
|
||||
_options.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit;
|
||||
_options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit;
|
||||
_options.Logger = _logger;
|
||||
@@ -213,21 +215,27 @@ namespace WireMock.Server
|
||||
#endif
|
||||
Ports = _httpServer.Ports;
|
||||
|
||||
_httpServer.StartAsync();
|
||||
var startTask = _httpServer.StartAsync();
|
||||
|
||||
using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout))
|
||||
{
|
||||
while (!_httpServer.IsStarted)
|
||||
{
|
||||
// Throw out exception if service start fails
|
||||
// Throw exception if service start fails
|
||||
if (_httpServer.RunningException != null)
|
||||
{
|
||||
throw new Exception($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException);
|
||||
throw new WireMockException($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException);
|
||||
}
|
||||
|
||||
// Respect start timeout setting by throwing TimeoutException
|
||||
if (ctsStartTimeout.IsCancellationRequested)
|
||||
{
|
||||
// In case of an aggregate exception, throw the exception.
|
||||
if (startTask.Exception != null)
|
||||
{
|
||||
throw new WireMockException($"Service start failed with error: {startTask.Exception.Message}", startTask.Exception);
|
||||
}
|
||||
|
||||
// Else throw TimeoutException
|
||||
throw new TimeoutException($"Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}");
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ namespace WireMock.Transformers
|
||||
HandleBarsLinq.Register(handlebarsContext);
|
||||
|
||||
HandleBarsRandom.Register(handlebarsContext);
|
||||
|
||||
HandleBarsXeger.Register(handlebarsContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
39
src/WireMock.Net/Transformers/HandleBarsXeger.cs
Normal file
39
src/WireMock.Net/Transformers/HandleBarsXeger.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using Fare;
|
||||
using HandlebarsDotNet;
|
||||
using WireMock.Validation;
|
||||
|
||||
namespace WireMock.Transformers
|
||||
{
|
||||
internal static class HandleBarsXeger
|
||||
{
|
||||
public static void Register(IHandlebars handlebarsContext)
|
||||
{
|
||||
handlebarsContext.RegisterHelper("Xeger", (writer, context, arguments) =>
|
||||
{
|
||||
string value = ParseArgumentAndGenerate(arguments);
|
||||
writer.Write(value);
|
||||
});
|
||||
|
||||
handlebarsContext.RegisterHelper("Xeger", (writer, options, context, arguments) =>
|
||||
{
|
||||
string value = ParseArgumentAndGenerate(arguments);
|
||||
options.Template(writer, value);
|
||||
});
|
||||
}
|
||||
|
||||
private static string ParseArgumentAndGenerate(object[] arguments)
|
||||
{
|
||||
Check.Condition(arguments, args => args.Length == 1, nameof(arguments));
|
||||
Check.NotNull(arguments[0], "arguments[0]");
|
||||
|
||||
switch (arguments[0])
|
||||
{
|
||||
case string pattern:
|
||||
return new Xeger(pattern).Generate();
|
||||
}
|
||||
|
||||
throw new NotSupportedException($"The value '{arguments[0]}' with type '{arguments[0]?.GetType()}' cannot be used in Handlebars Xeger.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,23 +120,34 @@ namespace WireMock.Transformers
|
||||
string transformedString = templateForStringValue(template);
|
||||
if (!string.Equals(stringValue, transformedString))
|
||||
{
|
||||
JToken value;
|
||||
try
|
||||
{
|
||||
// Try to convert this string into a real JsonObject
|
||||
value = JToken.Parse(transformedString);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Ignore JsonException and just convert to JToken
|
||||
value = transformedString;
|
||||
}
|
||||
|
||||
node.Replace(value);
|
||||
ReplaceNodeValue(node, transformedString);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ReplaceNodeValue(JToken node, string stringValue)
|
||||
{
|
||||
if (bool.TryParse(stringValue, out bool valueAsBoolean))
|
||||
{
|
||||
node.Replace(valueAsBoolean);
|
||||
return;
|
||||
}
|
||||
|
||||
JToken value;
|
||||
try
|
||||
{
|
||||
// Try to convert this string into a JsonObject
|
||||
value = JToken.Parse(stringValue);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Ignore JsonException and just keep string value and convert to JToken
|
||||
value = stringValue;
|
||||
}
|
||||
|
||||
node.Replace(value);
|
||||
}
|
||||
|
||||
private static void TransformBodyAsString(object template, ResponseMessage original, ResponseMessage responseMessage)
|
||||
{
|
||||
var templateBody = HandlebarsContext.Compile(original.BodyData.BodyAsString);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
using System;
|
||||
using JetBrains.Annotations;
|
||||
using MimeKit;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using JetBrains.Annotations;
|
||||
using MimeKit;
|
||||
using Newtonsoft.Json;
|
||||
using WireMock.Matchers;
|
||||
using WireMock.Validation;
|
||||
|
||||
@@ -28,6 +28,10 @@ namespace WireMock.Util
|
||||
*/
|
||||
private static readonly string[] AllowedBodyParseMethods = { "PUT", "POST", "OPTIONS", "PATCH" };
|
||||
|
||||
private static readonly IStringMatcher[] MultipartContentTypesMatchers = {
|
||||
new WildcardMatcher("multipart/*", true)
|
||||
};
|
||||
|
||||
private static readonly IStringMatcher[] JsonContentTypesMatchers = {
|
||||
new WildcardMatcher("application/json", true),
|
||||
new WildcardMatcher("application/vnd.*+json", true)
|
||||
@@ -68,6 +72,11 @@ namespace WireMock.Util
|
||||
return BodyType.Json;
|
||||
}
|
||||
|
||||
if (MultipartContentTypesMatchers.Any(matcher => MatchScores.IsPerfect(matcher.IsMatch(contentType.MimeType))))
|
||||
{
|
||||
return BodyType.MultiPart;
|
||||
}
|
||||
|
||||
return BodyType.Bytes;
|
||||
}
|
||||
|
||||
@@ -82,6 +91,12 @@ namespace WireMock.Util
|
||||
DetectedBodyTypeFromContentType = DetectBodyTypeFromContentType(contentType)
|
||||
};
|
||||
|
||||
// In case of MultiPart: never try to read as String but keep as-is
|
||||
if (data.DetectedBodyTypeFromContentType == BodyType.MultiPart)
|
||||
{
|
||||
return data;
|
||||
}
|
||||
|
||||
// Try to get the body as String
|
||||
try
|
||||
{
|
||||
|
||||
@@ -28,6 +28,11 @@
|
||||
/// <summary>
|
||||
/// Body is a File
|
||||
/// </summary>
|
||||
File
|
||||
File,
|
||||
|
||||
/// <summary>
|
||||
/// Body is a MultiPart
|
||||
/// </summary>
|
||||
MultiPart
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.9" />
|
||||
<PackageReference Include="RandomDataGenerator.Net" Version="1.0.4" />
|
||||
<PackageReference Include="RandomDataGenerator.Net" Version="1.0.7" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition=" '$(TargetFramework)' == 'net451' ">
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
using System.Linq;
|
||||
using NFluent;
|
||||
using RestEase;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
using NFluent;
|
||||
using RestEase;
|
||||
using WireMock.Admin.Mappings;
|
||||
using WireMock.Admin.Settings;
|
||||
using WireMock.Client;
|
||||
@@ -19,7 +19,7 @@ namespace WireMock.Net.Tests
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_GetSettingsAsync()
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
var server = FluentMockServer.StartWithAdminInterface();
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
@@ -31,7 +31,7 @@ namespace WireMock.Net.Tests
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_PostSettingsAsync()
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
var server = FluentMockServer.StartWithAdminInterface();
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
@@ -44,7 +44,7 @@ namespace WireMock.Net.Tests
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_PutSettingsAsync()
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
var server = FluentMockServer.StartWithAdminInterface();
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
@@ -57,22 +57,15 @@ namespace WireMock.Net.Tests
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_PostMappingAsync()
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
var server = FluentMockServer.StartWithAdminInterface();
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
// Act
|
||||
var model = new MappingModel
|
||||
{
|
||||
Request = new RequestModel
|
||||
{
|
||||
Path = "/1"
|
||||
},
|
||||
Response = new ResponseModel
|
||||
{
|
||||
Body = "txt",
|
||||
StatusCode = 200
|
||||
},
|
||||
Request = new RequestModel { Path = "/1" },
|
||||
Response = new ResponseModel { Body = "txt", StatusCode = 200 },
|
||||
Priority = 500,
|
||||
Title = "test"
|
||||
};
|
||||
@@ -90,10 +83,41 @@ namespace WireMock.Net.Tests
|
||||
server.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_PostMappingsAsync()
|
||||
{
|
||||
// Arrange
|
||||
var server = FluentMockServer.StartWithAdminInterface();
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
// Act
|
||||
var model1 = new MappingModel
|
||||
{
|
||||
Request = new RequestModel { Path = "/1" },
|
||||
Response = new ResponseModel { Body = "txt 1" },
|
||||
Title = "test 1"
|
||||
};
|
||||
var model2 = new MappingModel
|
||||
{
|
||||
Request = new RequestModel { Path = "/2" },
|
||||
Response = new ResponseModel { Body = "txt 2" },
|
||||
Title = "test 2"
|
||||
};
|
||||
var result = await api.PostMappingsAsync(new[] { model1, model2 });
|
||||
|
||||
// Assert
|
||||
Check.That(result).IsNotNull();
|
||||
Check.That(result.Status).IsNotNull();
|
||||
Check.That(result.Guid).IsNull();
|
||||
Check.That(server.Mappings.Where(m => !m.IsAdminInterface)).HasSize(2);
|
||||
|
||||
server.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_FindRequestsAsync()
|
||||
{
|
||||
// given
|
||||
// Arrange
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
StartAdminInterface = true,
|
||||
@@ -103,10 +127,10 @@ namespace WireMock.Net.Tests
|
||||
await new HttpClient().GetAsync(serverUrl + "/foo");
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
|
||||
|
||||
// when
|
||||
// Act
|
||||
var requests = await api.FindRequestsAsync(new RequestModel { Methods = new[] { "GET" } });
|
||||
|
||||
// then
|
||||
// Assert
|
||||
Check.That(requests).HasSize(1);
|
||||
var requestLogged = requests.First();
|
||||
Check.That(requestLogged.Request.Method).IsEqualTo("GET");
|
||||
@@ -117,7 +141,7 @@ namespace WireMock.Net.Tests
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_GetRequestsAsync()
|
||||
{
|
||||
// given
|
||||
// Arrange
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
StartAdminInterface = true,
|
||||
@@ -127,10 +151,10 @@ namespace WireMock.Net.Tests
|
||||
await new HttpClient().GetAsync(serverUrl + "/foo");
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
|
||||
|
||||
// when
|
||||
// Act
|
||||
var requests = await api.GetRequestsAsync();
|
||||
|
||||
// then
|
||||
// Assert
|
||||
Check.That(requests).HasSize(1);
|
||||
var requestLogged = requests.First();
|
||||
Check.That(requestLogged.Request.Method).IsEqualTo("GET");
|
||||
@@ -141,7 +165,7 @@ namespace WireMock.Net.Tests
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_GetRequestsAsync_JsonApi()
|
||||
{
|
||||
// given
|
||||
// Arrange
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
StartAdminInterface = true,
|
||||
@@ -159,13 +183,14 @@ namespace WireMock.Net.Tests
|
||||
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType);
|
||||
|
||||
var response = await new HttpClient().SendAsync(request);
|
||||
Check.That(response).IsNotNull();
|
||||
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
|
||||
|
||||
// when
|
||||
// Act
|
||||
var requests = await api.GetRequestsAsync();
|
||||
|
||||
// then
|
||||
// Assert
|
||||
Check.That(requests).HasSize(1);
|
||||
var requestLogged = requests.First();
|
||||
Check.That(requestLogged.Request.Method).IsEqualTo("POST");
|
||||
@@ -176,7 +201,7 @@ namespace WireMock.Net.Tests
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_GetRequestsAsync_Json()
|
||||
{
|
||||
// given
|
||||
// Arrange
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
StartAdminInterface = true,
|
||||
@@ -193,13 +218,14 @@ namespace WireMock.Net.Tests
|
||||
request.Content = new StringContent(data);
|
||||
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType);
|
||||
var response = await new HttpClient().SendAsync(request);
|
||||
Check.That(response).IsNotNull();
|
||||
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
|
||||
|
||||
// when
|
||||
// Act
|
||||
var requests = await api.GetRequestsAsync();
|
||||
|
||||
// then
|
||||
// Assert
|
||||
Check.That(requests).HasSize(1);
|
||||
var requestLogged = requests.First();
|
||||
Check.That(requestLogged.Request.Method).IsEqualTo("POST");
|
||||
|
||||
@@ -46,7 +46,7 @@ namespace WireMock.Net.Tests
|
||||
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings");
|
||||
server.ReadStaticMappings(folder);
|
||||
|
||||
Check.That(server.Mappings).HasSize(3);
|
||||
Check.That(server.Mappings).HasSize(5);
|
||||
|
||||
// Act
|
||||
server.ResetMappings();
|
||||
@@ -92,8 +92,8 @@ namespace WireMock.Net.Tests
|
||||
|
||||
var server = FluentMockServer.Start();
|
||||
|
||||
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "documentdb_root.json");
|
||||
server.ReadStaticMappingAndAddOrUpdate(folder);
|
||||
string path = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "documentdb_root.json");
|
||||
server.ReadStaticMappingAndAddOrUpdate(path);
|
||||
|
||||
var mappings = server.Mappings.ToArray();
|
||||
Check.That(mappings).HasSize(1);
|
||||
@@ -110,8 +110,8 @@ namespace WireMock.Net.Tests
|
||||
string guid = "00000002-ee28-4f29-ae63-1ac9b0802d86";
|
||||
|
||||
var server = FluentMockServer.Start();
|
||||
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json");
|
||||
server.ReadStaticMappingAndAddOrUpdate(folder);
|
||||
string path = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json");
|
||||
server.ReadStaticMappingAndAddOrUpdate(path);
|
||||
|
||||
var mappings = server.Mappings.ToArray();
|
||||
Check.That(mappings).HasSize(1);
|
||||
@@ -122,13 +122,25 @@ namespace WireMock.Net.Tests
|
||||
Check.That(mappings.First().Title).IsNullOrEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FluentMockServer_Admin_ReadStaticMapping_WithArray()
|
||||
{
|
||||
var server = FluentMockServer.Start();
|
||||
|
||||
string path = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "array.json");
|
||||
server.ReadStaticMappingAndAddOrUpdate(path);
|
||||
|
||||
var mappings = server.Mappings.ToArray();
|
||||
Check.That(mappings).HasSize(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FluentMockServer_Admin_ReadStaticMapping_WithResponseBodyFromFile()
|
||||
{
|
||||
string guid = "00000002-ee28-4f29-ae63-1ac9b0802d87";
|
||||
|
||||
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json");
|
||||
string json = File.ReadAllText(folder);
|
||||
string path = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json");
|
||||
string json = File.ReadAllText(path);
|
||||
|
||||
string responseBodyFilePath = Path.Combine(GetCurrentFolder(), "responsebody.json");
|
||||
|
||||
@@ -136,10 +148,10 @@ namespace WireMock.Net.Tests
|
||||
jsonObj["Response"]["BodyAsFile"] = responseBodyFilePath;
|
||||
|
||||
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
|
||||
File.WriteAllText(folder, output);
|
||||
File.WriteAllText(path, output);
|
||||
|
||||
var server = FluentMockServer.Start();
|
||||
server.ReadStaticMappingAndAddOrUpdate(folder);
|
||||
server.ReadStaticMappingAndAddOrUpdate(path);
|
||||
|
||||
var mappings = server.Mappings.ToArray();
|
||||
Check.That(mappings).HasSize(1);
|
||||
@@ -202,7 +214,7 @@ namespace WireMock.Net.Tests
|
||||
server.ReadStaticMappings(folder);
|
||||
|
||||
var mappings = server.Mappings.ToArray();
|
||||
Check.That(mappings).HasSize(3);
|
||||
Check.That(mappings).HasSize(5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -33,5 +33,12 @@ namespace WireMock.Net.Tests.Handlers
|
||||
// Act
|
||||
Check.ThatCode(() => _sut.WriteMappingFile(null, null)).Throws<ArgumentNullException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LocalFileSystemHandler_ReadResponseBodyAsFile_Throws()
|
||||
{
|
||||
// Act
|
||||
Check.ThatCode(() => _sut.ReadResponseBodyAsFile(null)).Throws<ArgumentNullException>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using Xunit;
|
||||
using Moq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Threading;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Owin.Mappers;
|
||||
using WireMock.Util;
|
||||
#if NET452
|
||||
@@ -26,6 +27,7 @@ namespace WireMock.Net.Tests.Owin.Mappers
|
||||
private readonly Mock<IResponse> _responseMock;
|
||||
private readonly Mock<Stream> _stream;
|
||||
private readonly Mock<IHeaderDictionary> _headers;
|
||||
private readonly Mock<IFileSystemHandler> _fileSystemHandlerMock;
|
||||
|
||||
public OwinResponseMapperTests()
|
||||
{
|
||||
@@ -46,20 +48,23 @@ namespace WireMock.Net.Tests.Owin.Mappers
|
||||
_responseMock.SetupGet(r => r.Body).Returns(_stream.Object);
|
||||
_responseMock.SetupGet(r => r.Headers).Returns(_headers.Object);
|
||||
|
||||
_sut = new OwinResponseMapper();
|
||||
_fileSystemHandlerMock = new Mock<IFileSystemHandler>();
|
||||
_fileSystemHandlerMock.SetupAllProperties();
|
||||
|
||||
_sut = new OwinResponseMapper(_fileSystemHandlerMock.Object);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async void OwinResponseMapper_MapAsync_Null()
|
||||
public async Task OwinResponseMapper_MapAsync_Null()
|
||||
{
|
||||
// Act
|
||||
await _sut.MapAsync(null, _responseMock.Object);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async void OwinResponseMapper_MapAsync_StatusCode()
|
||||
public async Task OwinResponseMapper_MapAsync_StatusCode()
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
var responseMessage = new ResponseMessage
|
||||
{
|
||||
StatusCode = 302
|
||||
@@ -73,9 +78,9 @@ namespace WireMock.Net.Tests.Owin.Mappers
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async void OwinResponseMapper_MapAsync_NoBody()
|
||||
public async Task OwinResponseMapper_MapAsync_NoBody()
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
var responseMessage = new ResponseMessage
|
||||
{
|
||||
Headers = new Dictionary<string, WireMockList<string>>()
|
||||
@@ -89,9 +94,9 @@ namespace WireMock.Net.Tests.Owin.Mappers
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async void OwinResponseMapper_MapAsync_Body()
|
||||
public async Task OwinResponseMapper_MapAsync_Body()
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
string body = "abc";
|
||||
var responseMessage = new ResponseMessage
|
||||
{
|
||||
@@ -107,9 +112,9 @@ namespace WireMock.Net.Tests.Owin.Mappers
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async void OwinResponseMapper_MapAsync_BodyAsBytes()
|
||||
public async Task OwinResponseMapper_MapAsync_BodyAsBytes()
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
var bytes = new byte[] { 48, 49 };
|
||||
var responseMessage = new ResponseMessage
|
||||
{
|
||||
@@ -125,9 +130,9 @@ namespace WireMock.Net.Tests.Owin.Mappers
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async void OwinResponseMapper_MapAsync_BodyAsJson()
|
||||
public async Task OwinResponseMapper_MapAsync_BodyAsJson()
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
var json = new { t = "x", i = (string)null };
|
||||
var responseMessage = new ResponseMessage
|
||||
{
|
||||
@@ -143,9 +148,9 @@ namespace WireMock.Net.Tests.Owin.Mappers
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async void OwinResponseMapper_MapAsync_SetResponseHeaders()
|
||||
public async Task OwinResponseMapper_MapAsync_SetResponseHeaders()
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
var responseMessage = new ResponseMessage
|
||||
{
|
||||
Headers = new Dictionary<string, WireMockList<string>> { { "h", new WireMockList<string>("x", "y") } }
|
||||
|
||||
@@ -8,12 +8,27 @@ namespace WireMock.Net.Tests.RequestMatchers
|
||||
{
|
||||
public class RequestMessageParamMatcherTests
|
||||
{
|
||||
[Fact]
|
||||
public void RequestMessageParamMatcher_GetMatchingScore_IgnoreCaseKeyWithValuesPresentInUrl_MatchExactOnStringValues()
|
||||
{
|
||||
// Assign
|
||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1"), "GET", "127.0.0.1");
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "KeY", true, new[] { "test1" });
|
||||
|
||||
// Act
|
||||
var result = new RequestMatchResult();
|
||||
double score = matcher.GetMatchingScore(requestMessage, result);
|
||||
|
||||
// Assert
|
||||
Check.That(score).IsEqualTo(1.0d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequestMessageParamMatcher_GetMatchingScore_KeyWithValuesPresentInUrl_MatchExactOnStringValues()
|
||||
{
|
||||
// Assign
|
||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2"), "GET", "127.0.0.1");
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", new[] { "test1", "test2" });
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" });
|
||||
|
||||
// Act
|
||||
var result = new RequestMatchResult();
|
||||
@@ -28,7 +43,7 @@ namespace WireMock.Net.Tests.RequestMatchers
|
||||
{
|
||||
// Assign
|
||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2"), "GET", "127.0.0.1");
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", new IStringMatcher[] { new ExactMatcher("test1"), new ExactMatcher("test2") });
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new IStringMatcher[] { new ExactMatcher("test1"), new ExactMatcher("test2") });
|
||||
|
||||
// Act
|
||||
var result = new RequestMatchResult();
|
||||
@@ -43,7 +58,7 @@ namespace WireMock.Net.Tests.RequestMatchers
|
||||
{
|
||||
// Assign
|
||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test0,test2"), "GET", "127.0.0.1");
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", new[] { "test1", "test2" });
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" });
|
||||
|
||||
// Act
|
||||
var result = new RequestMatchResult();
|
||||
@@ -58,7 +73,7 @@ namespace WireMock.Net.Tests.RequestMatchers
|
||||
{
|
||||
// Assign
|
||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key"), "GET", "127.0.0.1");
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", new[] { "test1", "test2" });
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" });
|
||||
|
||||
// Act
|
||||
var result = new RequestMatchResult();
|
||||
@@ -73,7 +88,7 @@ namespace WireMock.Net.Tests.RequestMatchers
|
||||
{
|
||||
// Assign
|
||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key"), "GET", "127.0.0.1");
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key");
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false);
|
||||
|
||||
// Act
|
||||
var result = new RequestMatchResult();
|
||||
@@ -88,7 +103,7 @@ namespace WireMock.Net.Tests.RequestMatchers
|
||||
{
|
||||
// Assign
|
||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key"), "GET", "127.0.0.1");
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", new string[] { });
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new string[] { });
|
||||
|
||||
// Act
|
||||
var result = new RequestMatchResult();
|
||||
@@ -103,7 +118,7 @@ namespace WireMock.Net.Tests.RequestMatchers
|
||||
{
|
||||
// Assign
|
||||
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=frank@contoso.com"), "GET", "127.0.0.1");
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key");
|
||||
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false);
|
||||
|
||||
// Act
|
||||
var result = new RequestMatchResult();
|
||||
|
||||
@@ -39,6 +39,16 @@ namespace WireMock.Net.Tests
|
||||
Check.That(request.GetParameter("foo")).ContainsExactly("bar");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequestMessage_ParseQuery_SingleKey_SingleValue_WithIgnoreCase()
|
||||
{
|
||||
// Assign
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost?foo=bar"), "POST", ClientIp);
|
||||
|
||||
// Assert
|
||||
Check.That(request.GetParameter("FoO", true)).ContainsExactly("bar");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequestMessage_ParseQuery_MultipleKeys_MultipleValues()
|
||||
{
|
||||
|
||||
@@ -34,9 +34,30 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
||||
|
||||
// Assert
|
||||
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
|
||||
Check.That(j["Text"]).IsNotNull();
|
||||
Check.That(j["Text"].Value<string>()).IsNotEmpty();
|
||||
Check.That(j["Integer"].Value<int>()).IsEqualTo(1000);
|
||||
Check.That(j["Long"].Value<int>()).IsStrictlyGreaterThan(77777777).And.IsStrictlyLessThan(99999999);
|
||||
Check.That(j["Long"].Value<long>()).IsStrictlyGreaterThan(77777777).And.IsStrictlyLessThan(99999999);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponseAsync_Handlebars_Random1_Boolean()
|
||||
{
|
||||
// Assign
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||
|
||||
var response = Response.Create()
|
||||
.WithBodyAsJson(new
|
||||
{
|
||||
Value = "{{Random Type=\"Boolean\"}}"
|
||||
})
|
||||
.WithTransformer();
|
||||
|
||||
// Act
|
||||
var responseMessage = await response.ProvideResponseAsync(request);
|
||||
|
||||
// Assert
|
||||
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
|
||||
Check.That(j["Value"].Type).IsEqualTo(JTokenType.Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using NFluent;
|
||||
using WireMock.Models;
|
||||
using WireMock.ResponseBuilders;
|
||||
using Xunit;
|
||||
|
||||
namespace WireMock.Net.Tests.ResponseBuilders
|
||||
{
|
||||
public class ResponseWithHandlebarsXegerTests
|
||||
{
|
||||
private const string ClientIp = "::1";
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponseAsync_Handlebars_Xeger1()
|
||||
{
|
||||
// Assign
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||
|
||||
var response = Response.Create()
|
||||
.WithBodyAsJson(new
|
||||
{
|
||||
Number = "{{Xeger \"[1-9]{1}\\d{3}\"}}",
|
||||
Postcode = "{{Xeger \"[1-9][0-9]{3}[A-Z]{2}\"}}"
|
||||
})
|
||||
.WithTransformer();
|
||||
|
||||
// Act
|
||||
var responseMessage = await response.ProvideResponseAsync(request);
|
||||
|
||||
// Assert
|
||||
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
|
||||
Check.That(j["Number"].Value<int>()).IsStrictlyGreaterThan(1000).And.IsStrictlyLessThan(9999);
|
||||
Check.That(j["Postcode"].Value<string>()).IsNotEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponseAsync_Handlebars_Xeger2()
|
||||
{
|
||||
// Assign
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
|
||||
|
||||
var response = Response.Create()
|
||||
.WithBodyAsJson(new
|
||||
{
|
||||
Number = "{{#Xeger \"[1-9]{1}\\d{3}\"}}{{this}}{{/Xeger}}",
|
||||
Postcode = "{{#Xeger \"[1-9][0-9]{3}[A-Z]{2}\"}}{{this}}{{/Xeger}}"
|
||||
})
|
||||
.WithTransformer();
|
||||
|
||||
// Act
|
||||
var responseMessage = await response.ProvideResponseAsync(request);
|
||||
|
||||
// Assert
|
||||
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
|
||||
Check.That(j["Number"].Value<int>()).IsStrictlyGreaterThan(1000).And.IsStrictlyLessThan(9999);
|
||||
Check.That(j["Postcode"].Value<string>()).IsNotEmpty();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
using System.IO;
|
||||
using NFluent;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using NFluent;
|
||||
using WireMock.Util;
|
||||
using Xunit;
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace WireMock.Net.Tests.Util
|
||||
[InlineData("application/vnd.test+json", "{ \"x\": 1 }", BodyType.Json, BodyType.Json)]
|
||||
public async Task BodyParser_Parse_ContentTypeJson(string contentType, string bodyAsJson, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType)
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsJson));
|
||||
|
||||
// Act
|
||||
@@ -36,7 +36,7 @@ namespace WireMock.Net.Tests.Util
|
||||
[InlineData("something", "hello", BodyType.String, BodyType.Bytes)]
|
||||
public async Task BodyParser_Parse_ContentTypeString(string contentType, string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType)
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString));
|
||||
|
||||
// Act
|
||||
@@ -50,11 +50,49 @@ namespace WireMock.Net.Tests.Util
|
||||
Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BodyParser_Parse_ContentTypeMultipart()
|
||||
{
|
||||
// Arrange
|
||||
string contentType = "multipart/form-data";
|
||||
string body = @"
|
||||
|
||||
-----------------------------9051914041544843365972754266
|
||||
Content-Disposition: form-data; name=""text""
|
||||
|
||||
text default
|
||||
-----------------------------9051914041544843365972754266
|
||||
Content-Disposition: form-data; name=""file1""; filename=""a.txt""
|
||||
Content-Type: text/plain
|
||||
|
||||
Content of a txt
|
||||
|
||||
-----------------------------9051914041544843365972754266
|
||||
Content-Disposition: form-data; name=""file2""; filename=""a.html""
|
||||
Content-Type: text/html
|
||||
|
||||
<!DOCTYPE html><title>Content of a.html.</title>
|
||||
|
||||
-----------------------------9051914041544843365972754266--";
|
||||
|
||||
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(body));
|
||||
|
||||
// Act
|
||||
var result = await BodyParser.Parse(memoryStream, contentType);
|
||||
|
||||
// Assert
|
||||
Check.That(result.DetectedBodyType).IsEqualTo(BodyType.Bytes);
|
||||
Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart);
|
||||
Check.That(result.BodyAsBytes).IsNotNull();
|
||||
Check.That(result.BodyAsJson).IsNull();
|
||||
Check.That(result.BodyAsString).IsNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, "hello", BodyType.String, BodyType.Bytes)]
|
||||
public async Task BodyParser_Parse_ContentTypeIsNull(string contentType, string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType)
|
||||
{
|
||||
// Assign
|
||||
// Arrange
|
||||
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString));
|
||||
|
||||
// Act
|
||||
|
||||
@@ -62,9 +62,15 @@
|
||||
<None Update="__admin\mappings\00000002-ee28-4f29-ae63-1ac9b0802d87.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="__admin\mappings\array.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="__admin\mappings\documentdb_root.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="__admin\mappings\MyXmlResponse.xml">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -16,9 +16,9 @@
|
||||
},
|
||||
"Response": {
|
||||
"StatusCode": 200,
|
||||
"BodyAsFile": "responsebody.json",
|
||||
"BodyAsFile": "MyXmlResponse.xml",
|
||||
"Headers": {
|
||||
"Content-Type": "application/json"
|
||||
"Content-Type": "application/xml"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
<xml>
|
||||
<hello>world</hello>
|
||||
</xml>
|
||||
46
test/WireMock.Net.Tests/__admin/mappings/array.json
Normal file
46
test/WireMock.Net.Tests/__admin/mappings/array.json
Normal file
@@ -0,0 +1,46 @@
|
||||
[
|
||||
{
|
||||
"Title": "1",
|
||||
"Request": {
|
||||
"Path": {
|
||||
"Matchers": [
|
||||
{
|
||||
"Name": "WildcardMatcher",
|
||||
"Pattern": "/mappings_static_1"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Methods": [
|
||||
"get"
|
||||
]
|
||||
},
|
||||
"Response": {
|
||||
"BodyAsJson": { "result": "mappings static_1" },
|
||||
"Headers": {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Title": "2",
|
||||
"Request": {
|
||||
"Path": {
|
||||
"Matchers": [
|
||||
{
|
||||
"Name": "WildcardMatcher",
|
||||
"Pattern": "/mappings_static_2"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Methods": [
|
||||
"get"
|
||||
]
|
||||
},
|
||||
"Response": {
|
||||
"BodyAsJson": { "result": "mappings static_2" },
|
||||
"Headers": {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
Reference in New Issue
Block a user