mirror of
https://github.com/wiremock/WireMock.Net.git
synced 2026-01-15 16:13:30 +01:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
368f0e13ac | ||
|
|
120a808104 | ||
|
|
b5795713b1 | ||
|
|
a8c17ce311 | ||
|
|
7678e8fb70 | ||
|
|
8ae0abb023 | ||
|
|
b3c2af0c22 | ||
|
|
2dd30b4f14 | ||
|
|
45d8c0cc27 | ||
|
|
178f2cf02f | ||
|
|
1b326a54d6 | ||
|
|
8bafd6a1ba |
25
CHANGELOG.md
25
CHANGELOG.md
@@ -1,3 +1,27 @@
|
||||
# 1.0.43.0 (26 December 2019)
|
||||
- [#385](https://github.com/WireMock-Net/WireMock.Net/pull/385) - StatusCode as string [feature] contributed by [StefH](https://github.com/StefH)
|
||||
- [#380](https://github.com/WireMock-Net/WireMock.Net/issues/380) - StatusCode is defined as integer (string is not possible) [bug]
|
||||
- [#382](https://github.com/WireMock-Net/WireMock.Net/issues/382) - Return same request body [feature]
|
||||
|
||||
# 1.0.42.0 (15 December 2019)
|
||||
- [#391](https://github.com/WireMock-Net/WireMock.Net/pull/391) - Correctly support DateTime pattern as string in ExactMatcher [bug] contributed by [StefH](https://github.com/StefH)
|
||||
- [#383](https://github.com/WireMock-Net/WireMock.Net/issues/383) - ExactMatcher does not accept ISO8601 DateTime? [bug]
|
||||
|
||||
# 1.0.41.0 (14 December 2019)
|
||||
- [#392](https://github.com/WireMock-Net/WireMock.Net/pull/392) - Fix array in JsonMatcher [bug] contributed by [StefH](https://github.com/StefH)
|
||||
- [#390](https://github.com/WireMock-Net/WireMock.Net/issues/390) - JsonMatcher does not match a body containing an array of strings [bug]
|
||||
|
||||
# 1.0.40.0 (09 December 2019)
|
||||
- [#389](https://github.com/WireMock-Net/WireMock.Net/pull/389) - Fix QueryStringParser [bug] contributed by [StefH](https://github.com/StefH)
|
||||
- [#387](https://github.com/WireMock-Net/WireMock.Net/issues/387) - Query string parameter value which contains %26 does not work with ExactMatcher [bug]
|
||||
|
||||
# 1.0.39.0 (07 December 2019)
|
||||
- [#370](https://github.com/WireMock-Net/WireMock.Net/pull/370) - Add WebProxySettings (use when proxying requests) [feature] contributed by [StefH](https://github.com/StefH)
|
||||
- [#388](https://github.com/WireMock-Net/WireMock.Net/pull/388) - Transform body as file [bug] contributed by [StefH](https://github.com/StefH)
|
||||
- [#369](https://github.com/WireMock-Net/WireMock.Net/issues/369) - Question: Is there a way to provide a corporate proxy configuration? [feature]
|
||||
- [#375](https://github.com/WireMock-Net/WireMock.Net/issues/375) - Proxying does not follow redirects : make this configurable [feature]
|
||||
- [#386](https://github.com/WireMock-Net/WireMock.Net/issues/386) - Is transforming contents of XML file supported.? [bug]
|
||||
|
||||
# 1.0.38.0 (30 November 2019)
|
||||
- [#376](https://github.com/WireMock-Net/WireMock.Net/pull/376) - Support int values for states and scenario naming [feature] contributed by [thewholuver94](https://github.com/thewholuver94)
|
||||
- [#378](https://github.com/WireMock-Net/WireMock.Net/pull/378) - Set handlebars dependency for .net 4.5.1 to fixed value [bug] contributed by [StefH](https://github.com/StefH)
|
||||
@@ -142,6 +166,7 @@
|
||||
# 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 [bug]
|
||||
|
||||
# 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)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<VersionPrefix>1.0.38</VersionPrefix>
|
||||
<VersionPrefix>1.0.43</VersionPrefix>
|
||||
</PropertyGroup>
|
||||
|
||||
<Choose>
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
https://github.com/StefH/GitHubReleaseNotes
|
||||
|
||||
GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc --version 1.0.38.0
|
||||
GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc --version 1.0.43.0
|
||||
@@ -79,6 +79,7 @@ steps:
|
||||
inputs:
|
||||
PathtoPublish: '$(Build.ArtifactStagingDirectory)'
|
||||
|
||||
# https://github.com/NuGet/Home/issues/8148
|
||||
- task: DotNetCoreCLI@2
|
||||
displayName: Push to MyGet
|
||||
condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest')) # Do not run for PullRequests
|
||||
|
||||
@@ -1 +1 @@
|
||||
C# Hello
|
||||
// C# Hello
|
||||
@@ -105,6 +105,24 @@ namespace WireMock.Net.ConsoleApplication
|
||||
.WithProxy(new ProxyAndRecordSettings { Url = "http://postman-echo.com/get" })
|
||||
);
|
||||
|
||||
server
|
||||
.Given(Request.Create()
|
||||
.UsingGet()
|
||||
.WithHeader("postmanecho", "get2")
|
||||
)
|
||||
.RespondWith(Response.Create()
|
||||
.WithProxy(new ProxyAndRecordSettings
|
||||
{
|
||||
Url = "http://postman-echo.com/get",
|
||||
WebProxySettings = new WebProxySettings
|
||||
{
|
||||
Address = "http://company",
|
||||
UserName = "test",
|
||||
Password = "pwd"
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
server
|
||||
.Given(Request.Create()
|
||||
.UsingGet()
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using System;
|
||||
using JetBrains.Annotations;
|
||||
using System.Linq;
|
||||
using JetBrains.Annotations;
|
||||
using WireMock.Logging;
|
||||
using WireMock.Server;
|
||||
using WireMock.Settings;
|
||||
@@ -87,8 +86,20 @@ namespace WireMock.Net.StandAlone
|
||||
SaveMappingForStatusCodePattern = parser.GetStringValue("SaveMappingForStatusCodePattern"),
|
||||
ClientX509Certificate2ThumbprintOrSubjectName = parser.GetStringValue("ClientX509Certificate2ThumbprintOrSubjectName"),
|
||||
BlackListedHeaders = parser.GetValues("BlackListedHeaders"),
|
||||
BlackListedCookies = parser.GetValues("BlackListedCookies")
|
||||
BlackListedCookies = parser.GetValues("BlackListedCookies"),
|
||||
AllowAutoRedirect = parser.GetBoolValue("AllowAutoRedirect")
|
||||
};
|
||||
|
||||
string proxyAddress = parser.GetStringValue("WebProxyAddress");
|
||||
if (!string.IsNullOrEmpty(proxyAddress))
|
||||
{
|
||||
settings.ProxyAndRecordSettings.WebProxySettings = new WebProxySettings
|
||||
{
|
||||
Address = proxyAddress,
|
||||
UserName = parser.GetStringValue("WebProxyUserName"),
|
||||
Password = parser.GetStringValue("WebProxyPassword")
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
<Description>Lightweight StandAlone Http Mocking Server for .Net.</Description>
|
||||
<AssemblyTitle>WireMock.Net.StandAlone</AssemblyTitle>
|
||||
<Authors>Stef Heyenrath</Authors>
|
||||
<TargetFrameworks>net451;net452;net46;netstandard1.3;netstandard2.0</TargetFrameworks>
|
||||
<!--<TargetFrameworks>net451;net452;net46;netstandard1.3;netstandard2.0</TargetFrameworks>-->
|
||||
<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0</TargetFrameworks>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<AssemblyName>WireMock.Net.StandAlone</AssemblyName>
|
||||
<PackageId>WireMock.Net.StandAlone</PackageId>
|
||||
|
||||
@@ -10,7 +10,7 @@ namespace WireMock.Admin.Mappings
|
||||
/// <summary>
|
||||
/// Gets or sets the HTTP status.
|
||||
/// </summary>
|
||||
public int? StatusCode { get; set; }
|
||||
public object StatusCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the body destination (SameAsSource, String or Bytes).
|
||||
@@ -62,6 +62,11 @@ namespace WireMock.Admin.Mappings
|
||||
/// </summary>
|
||||
public bool? UseTransformer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Use the Handlerbars transformer for the content from the referenced BodyAsFile.
|
||||
/// </summary>
|
||||
public bool? UseTransformerForBodyAsFile { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the headers.
|
||||
/// </summary>
|
||||
@@ -91,5 +96,10 @@ namespace WireMock.Admin.Mappings
|
||||
/// Gets or sets the fault.
|
||||
/// </summary>
|
||||
public FaultModel Fault { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the WebProxy settings.
|
||||
/// </summary>
|
||||
public WebProxyModel WebProxy { get; set; }
|
||||
}
|
||||
}
|
||||
23
src/WireMock.Net/Admin/Mappings/WebProxyModel.cs
Normal file
23
src/WireMock.Net/Admin/Mappings/WebProxyModel.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
namespace WireMock.Admin.Mappings
|
||||
{
|
||||
/// <summary>
|
||||
/// WebProxy settings
|
||||
/// </summary>
|
||||
public class WebProxyModel
|
||||
{
|
||||
/// <summary>
|
||||
/// A string instance that contains the address of the proxy server.
|
||||
/// </summary>
|
||||
public string Address { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The user name associated with the credentials.
|
||||
/// </summary>
|
||||
public string UserName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The password for the user name associated with the credentials.
|
||||
/// </summary>
|
||||
public string Password { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
using WireMock.Admin.Mappings;
|
||||
using WireMock.ResponseBuilders;
|
||||
using WireMock.Util;
|
||||
|
||||
namespace WireMock.Admin.Requests
|
||||
@@ -13,7 +12,7 @@ namespace WireMock.Admin.Requests
|
||||
/// <summary>
|
||||
/// Gets or sets the status code.
|
||||
/// </summary>
|
||||
public int StatusCode { get; set; } = 200;
|
||||
public object StatusCode { get; set; } = 200;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the headers.
|
||||
|
||||
28
src/WireMock.Net/Compatibility/WebProxy.cs
Normal file
28
src/WireMock.Net/Compatibility/WebProxy.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
#if NETSTANDARD1_3
|
||||
using System;
|
||||
using System.Net;
|
||||
|
||||
namespace System.Net
|
||||
{
|
||||
internal class WebProxy : IWebProxy
|
||||
{
|
||||
private readonly string _proxy;
|
||||
public ICredentials Credentials { get; set; }
|
||||
|
||||
public WebProxy(string proxy)
|
||||
{
|
||||
_proxy = proxy;
|
||||
}
|
||||
|
||||
public Uri GetProxy(Uri destination)
|
||||
{
|
||||
return new Uri(_proxy);
|
||||
}
|
||||
|
||||
public bool IsBypassed(Uri host)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,16 +1,17 @@
|
||||
using System;
|
||||
using JetBrains.Annotations;
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using JetBrains.Annotations;
|
||||
using WireMock.HttpsCertificate;
|
||||
using WireMock.Settings;
|
||||
using WireMock.Validation;
|
||||
|
||||
namespace WireMock.Http
|
||||
{
|
||||
internal static class HttpClientHelper
|
||||
{
|
||||
public static HttpClient CreateHttpClient(string clientX509Certificate2ThumbprintOrSubjectName = null)
|
||||
public static HttpClient CreateHttpClient(IProxyAndRecordSettings settings)
|
||||
{
|
||||
#if NETSTANDARD
|
||||
var handler = new HttpClientHandler
|
||||
@@ -36,20 +37,30 @@ namespace WireMock.Http
|
||||
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
|
||||
#endif
|
||||
|
||||
if (!string.IsNullOrEmpty(clientX509Certificate2ThumbprintOrSubjectName))
|
||||
if (!string.IsNullOrEmpty(settings.ClientX509Certificate2ThumbprintOrSubjectName))
|
||||
{
|
||||
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
|
||||
|
||||
var x509Certificate2 = ClientCertificateHelper.GetCertificate(clientX509Certificate2ThumbprintOrSubjectName);
|
||||
var x509Certificate2 = ClientCertificateHelper.GetCertificate(settings.ClientX509Certificate2ThumbprintOrSubjectName);
|
||||
handler.ClientCertificates.Add(x509Certificate2);
|
||||
}
|
||||
|
||||
// For proxy we shouldn't follow auto redirects
|
||||
handler.AllowAutoRedirect = false;
|
||||
handler.AllowAutoRedirect = settings.AllowAutoRedirect == true;
|
||||
|
||||
// If UseCookies enabled, httpClient ignores Cookie header
|
||||
handler.UseCookies = false;
|
||||
|
||||
if (settings.WebProxySettings != null)
|
||||
{
|
||||
handler.UseProxy = true;
|
||||
|
||||
handler.Proxy = new WebProxy(settings.WebProxySettings.Address);
|
||||
if (settings.WebProxySettings.UserName != null && settings.WebProxySettings.Password != null)
|
||||
{
|
||||
handler.Proxy.Credentials = new NetworkCredential(settings.WebProxySettings.UserName, settings.WebProxySettings.Password);
|
||||
}
|
||||
}
|
||||
|
||||
var client = new HttpClient(handler);
|
||||
#if NET452 || NET46
|
||||
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using JetBrains.Annotations;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Collections;
|
||||
using System.Linq;
|
||||
using WireMock.Util;
|
||||
using WireMock.Validation;
|
||||
@@ -85,7 +86,7 @@ namespace WireMock.Matchers
|
||||
// Check if JToken or object
|
||||
JToken jtokenInput = input is JToken tokenInput ? tokenInput : JObject.FromObject(input);
|
||||
|
||||
// Check if JToken or string or object
|
||||
// Check if JToken, string, IEnumerable or object
|
||||
JToken jtokenValue;
|
||||
switch (Value)
|
||||
{
|
||||
@@ -97,6 +98,10 @@ namespace WireMock.Matchers
|
||||
jtokenValue = JsonUtils.Parse(stringValue);
|
||||
break;
|
||||
|
||||
case IEnumerable enumerableValue:
|
||||
jtokenValue = JArray.FromObject(enumerableValue);
|
||||
break;
|
||||
|
||||
default:
|
||||
jtokenValue = JObject.FromObject(Value);
|
||||
break;
|
||||
|
||||
@@ -79,7 +79,17 @@ namespace WireMock.Owin.Mappers
|
||||
break;
|
||||
}
|
||||
|
||||
response.StatusCode = responseMessage.StatusCode;
|
||||
switch (responseMessage.StatusCode)
|
||||
{
|
||||
case int statusCodeAsInteger:
|
||||
response.StatusCode = statusCodeAsInteger;
|
||||
break;
|
||||
|
||||
case string statusCodeAsString:
|
||||
response.StatusCode = int.Parse(statusCodeAsString);
|
||||
break;
|
||||
}
|
||||
|
||||
SetResponseHeaders(responseMessage, response);
|
||||
|
||||
if (bytes != null)
|
||||
|
||||
@@ -170,7 +170,7 @@ namespace WireMock
|
||||
|
||||
Headers = headers?.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value));
|
||||
Cookies = cookies;
|
||||
RawQuery = WebUtility.UrlDecode(urlDetails.Url.Query);
|
||||
RawQuery = urlDetails.Url.Query;
|
||||
Query = QueryStringParser.Parse(RawQuery);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,13 @@ namespace WireMock.ResponseBuilders
|
||||
/// <returns>The <see cref="IResponseBuilder"/>.</returns>
|
||||
IResponseBuilder WithStatusCode(int code);
|
||||
|
||||
/// <summary>
|
||||
/// The with status code.
|
||||
/// </summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns>The <see cref="IResponseBuilder"/>.</returns>
|
||||
IResponseBuilder WithStatusCode(string code);
|
||||
|
||||
/// <summary>
|
||||
/// The with status code.
|
||||
/// </summary>
|
||||
|
||||
@@ -11,6 +11,6 @@
|
||||
/// <returns>
|
||||
/// The <see cref="IResponseBuilder"/>.
|
||||
/// </returns>
|
||||
IResponseBuilder WithTransformer();
|
||||
IResponseBuilder WithTransformer(bool transformContentFromBodyAsFile = false);
|
||||
}
|
||||
}
|
||||
48
src/WireMock.Net/ResponseBuilders/Response.WithProxy.cs
Normal file
48
src/WireMock.Net/ResponseBuilders/Response.WithProxy.cs
Normal file
@@ -0,0 +1,48 @@
|
||||
using System.Net.Http;
|
||||
using WireMock.Http;
|
||||
using WireMock.Settings;
|
||||
using WireMock.Validation;
|
||||
|
||||
namespace WireMock.ResponseBuilders
|
||||
{
|
||||
public partial class Response
|
||||
{
|
||||
private HttpClient _httpClientForProxy;
|
||||
|
||||
/// <summary>
|
||||
/// The Proxy URL to use.
|
||||
/// </summary>
|
||||
public string ProxyUrl { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The WebProxy settings.
|
||||
/// </summary>
|
||||
public IWebProxySettings WebProxySettings { get; private set; }
|
||||
|
||||
/// <inheritdoc cref="IProxyResponseBuilder.WithProxy(string, string)"/>
|
||||
public IResponseBuilder WithProxy(string proxyUrl, string clientX509Certificate2ThumbprintOrSubjectName = null)
|
||||
{
|
||||
Check.NotNullOrEmpty(proxyUrl, nameof(proxyUrl));
|
||||
|
||||
var settings = new ProxyAndRecordSettings
|
||||
{
|
||||
Url = proxyUrl,
|
||||
ClientX509Certificate2ThumbprintOrSubjectName = clientX509Certificate2ThumbprintOrSubjectName
|
||||
};
|
||||
|
||||
return WithProxy(settings);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IProxyResponseBuilder.WithProxy(IProxyAndRecordSettings)"/>
|
||||
public IResponseBuilder WithProxy(IProxyAndRecordSettings settings)
|
||||
{
|
||||
Check.NotNull(settings, nameof(settings));
|
||||
|
||||
ProxyUrl = settings.Url;
|
||||
WebProxySettings = settings.WebProxySettings;
|
||||
|
||||
_httpClientForProxy = HttpClientHelper.CreateHttpClient(settings);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,6 @@ namespace WireMock.ResponseBuilders
|
||||
/// </summary>
|
||||
public partial class Response : IResponseBuilder
|
||||
{
|
||||
private HttpClient _httpClientForProxy;
|
||||
|
||||
/// <summary>
|
||||
/// The delay
|
||||
/// </summary>
|
||||
@@ -34,14 +32,9 @@ namespace WireMock.ResponseBuilders
|
||||
public bool UseTransformer { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The Proxy URL to use.
|
||||
/// Gets a value indicating whether to use the Handlerbars transformer for the content from the referenced BodyAsFile.
|
||||
/// </summary>
|
||||
public string ProxyUrl { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The client X509Certificate2 Thumbprint or SubjectName to use.
|
||||
/// </summary>
|
||||
public string ClientX509Certificate2ThumbprintOrSubjectName { get; private set; }
|
||||
public bool UseTransformerForBodyAsFile { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the response message.
|
||||
@@ -94,11 +87,7 @@ namespace WireMock.ResponseBuilders
|
||||
ResponseMessage = responseMessage;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The with status code.
|
||||
/// </summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns>A <see cref="IResponseBuilder"/>.</returns>\
|
||||
/// <inheritdoc cref="IStatusCodeResponseBuilder.WithStatusCode(int)"/>
|
||||
[PublicAPI]
|
||||
public IResponseBuilder WithStatusCode(int code)
|
||||
{
|
||||
@@ -106,11 +95,15 @@ namespace WireMock.ResponseBuilders
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The with status code.
|
||||
/// </summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns>A <see cref="IResponseBuilder"/>.</returns>
|
||||
/// <inheritdoc cref="IStatusCodeResponseBuilder.WithStatusCode(string)"/>
|
||||
[PublicAPI]
|
||||
public IResponseBuilder WithStatusCode(string code)
|
||||
{
|
||||
ResponseMessage.StatusCode = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IStatusCodeResponseBuilder.WithStatusCode(HttpStatusCode)"/>
|
||||
[PublicAPI]
|
||||
public IResponseBuilder WithStatusCode(HttpStatusCode code)
|
||||
{
|
||||
@@ -259,7 +252,7 @@ namespace WireMock.ResponseBuilders
|
||||
|
||||
case BodyDestinationFormat.Json:
|
||||
ResponseMessage.BodyData.DetectedBodyType = BodyType.Json;
|
||||
ResponseMessage.BodyData.BodyAsJson = JsonConvert.DeserializeObject(body);
|
||||
ResponseMessage.BodyData.BodyAsJson = JsonUtils.DeserializeObject(body);
|
||||
break;
|
||||
|
||||
default:
|
||||
@@ -311,10 +304,11 @@ namespace WireMock.ResponseBuilders
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="ITransformResponseBuilder.WithTransformer"/>
|
||||
public IResponseBuilder WithTransformer()
|
||||
/// <inheritdoc cref="ITransformResponseBuilder.WithTransformer(bool)"/>
|
||||
public IResponseBuilder WithTransformer(bool transformContentFromBodyAsFile = false)
|
||||
{
|
||||
UseTransformer = true;
|
||||
UseTransformerForBodyAsFile = transformContentFromBodyAsFile;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -333,25 +327,6 @@ namespace WireMock.ResponseBuilders
|
||||
return WithDelay(TimeSpan.FromMilliseconds(milliseconds));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IProxyResponseBuilder.WithProxy(string, string)"/>
|
||||
public IResponseBuilder WithProxy(string proxyUrl, string clientX509Certificate2ThumbprintOrSubjectName = null)
|
||||
{
|
||||
Check.NotNullOrEmpty(proxyUrl, nameof(proxyUrl));
|
||||
|
||||
ProxyUrl = proxyUrl;
|
||||
ClientX509Certificate2ThumbprintOrSubjectName = clientX509Certificate2ThumbprintOrSubjectName;
|
||||
_httpClientForProxy = HttpClientHelper.CreateHttpClient(clientX509Certificate2ThumbprintOrSubjectName);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IProxyResponseBuilder.WithProxy(IProxyAndRecordSettings)"/>
|
||||
public IResponseBuilder WithProxy(IProxyAndRecordSettings settings)
|
||||
{
|
||||
Check.NotNull(settings, nameof(settings));
|
||||
|
||||
return WithProxy(settings.Url, settings.ClientX509Certificate2ThumbprintOrSubjectName);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="ICallbackResponseBuilder.WithCallback"/>
|
||||
public IResponseBuilder WithCallback(Func<RequestMessage, ResponseMessage> callbackHandler)
|
||||
{
|
||||
@@ -414,7 +389,7 @@ namespace WireMock.ResponseBuilders
|
||||
{
|
||||
var factory = new HandlebarsContextFactory(settings.FileSystemHandler, settings.HandlebarsRegistrationCallback);
|
||||
var responseMessageTransformer = new ResponseMessageTransformer(factory);
|
||||
return responseMessageTransformer.Transform(requestMessage, ResponseMessage);
|
||||
return responseMessageTransformer.Transform(requestMessage, ResponseMessage, UseTransformerForBodyAsFile);
|
||||
}
|
||||
|
||||
if (!UseTransformer && ResponseMessage.BodyData?.BodyAsFileIsCached == true)
|
||||
|
||||
@@ -19,7 +19,7 @@ namespace WireMock
|
||||
/// <summary>
|
||||
/// Gets or sets the status code.
|
||||
/// </summary>
|
||||
public int StatusCode { get; set; } = 200;
|
||||
public object StatusCode { get; set; } = 200;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the body.
|
||||
|
||||
@@ -4,6 +4,7 @@ using WireMock.Admin.Mappings;
|
||||
using WireMock.Matchers.Request;
|
||||
using WireMock.RequestBuilders;
|
||||
using WireMock.ResponseBuilders;
|
||||
using WireMock.Settings;
|
||||
using WireMock.Util;
|
||||
using WireMock.Validation;
|
||||
|
||||
@@ -112,19 +113,26 @@ namespace WireMock.Serialization
|
||||
mappingModel.Response.BodyAsFile = null;
|
||||
mappingModel.Response.BodyAsFileIsCached = null;
|
||||
mappingModel.Response.UseTransformer = null;
|
||||
mappingModel.Response.UseTransformerForBodyAsFile = null;
|
||||
mappingModel.Response.BodyEncoding = null;
|
||||
mappingModel.Response.ProxyUrl = response.ProxyUrl;
|
||||
mappingModel.Response.Fault = null;
|
||||
mappingModel.Response.WebProxy = MapWebProxy(response.WebProxySettings);
|
||||
}
|
||||
else
|
||||
{
|
||||
mappingModel.Response.WebProxy = null;
|
||||
mappingModel.Response.BodyDestination = response.ResponseMessage.BodyDestination;
|
||||
mappingModel.Response.StatusCode = response.ResponseMessage.StatusCode;
|
||||
mappingModel.Response.Headers = Map(response.ResponseMessage.Headers);
|
||||
mappingModel.Response.Headers = MapHeaders(response.ResponseMessage.Headers);
|
||||
if (response.UseTransformer)
|
||||
{
|
||||
mappingModel.Response.UseTransformer = response.UseTransformer;
|
||||
}
|
||||
if (response.UseTransformerForBodyAsFile)
|
||||
{
|
||||
mappingModel.Response.UseTransformerForBodyAsFile = response.UseTransformerForBodyAsFile;
|
||||
}
|
||||
|
||||
if (response.ResponseMessage.BodyData != null)
|
||||
{
|
||||
@@ -176,14 +184,25 @@ namespace WireMock.Serialization
|
||||
return mappingModel;
|
||||
}
|
||||
|
||||
private static IDictionary<string, object> Map(IDictionary<string, WireMockList<string>> dictionary)
|
||||
private static WebProxyModel MapWebProxy(IWebProxySettings settings)
|
||||
{
|
||||
return settings != null ? new WebProxyModel
|
||||
{
|
||||
Address = settings.Address,
|
||||
UserName = settings.UserName,
|
||||
Password = settings.Password
|
||||
} : null;
|
||||
}
|
||||
|
||||
private static IDictionary<string, object> MapHeaders(IDictionary<string, WireMockList<string>> dictionary)
|
||||
{
|
||||
var newDictionary = new Dictionary<string, object>();
|
||||
|
||||
if (dictionary == null || dictionary.Count == 0)
|
||||
{
|
||||
return null;
|
||||
return newDictionary;
|
||||
}
|
||||
|
||||
var newDictionary = new Dictionary<string, object>();
|
||||
foreach (var entry in dictionary)
|
||||
{
|
||||
object value = entry.Value.Count == 1 ? (object)entry.Value.ToString() : entry.Value;
|
||||
|
||||
@@ -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;
|
||||
@@ -179,8 +179,10 @@ namespace WireMock.Server
|
||||
|
||||
_settings.Logger.Info($"Watching folder '{folder}'{includeSubdirectoriesText} for new, updated and deleted MappingFiles.");
|
||||
|
||||
var watcher = new EnhancedFileSystemWatcher(folder, "*.json", EnhancedFileSystemWatcherTimeoutMs);
|
||||
watcher.IncludeSubdirectories = includeSubdirectories;
|
||||
var watcher = new EnhancedFileSystemWatcher(folder, "*.json", EnhancedFileSystemWatcherTimeoutMs)
|
||||
{
|
||||
IncludeSubdirectories = includeSubdirectories
|
||||
};
|
||||
|
||||
watcher.Created += (sender, args) =>
|
||||
{
|
||||
@@ -229,7 +231,7 @@ namespace WireMock.Server
|
||||
|
||||
if (FileHelper.TryReadMappingFileWithRetryAndDelay(_settings.FileSystemHandler, path, out string value))
|
||||
{
|
||||
var mappingModels = DeserializeObjectToArray<MappingModel>(JsonConvert.DeserializeObject(value));
|
||||
var mappingModels = DeserializeObjectToArray<MappingModel>(JsonUtils.DeserializeObject(value));
|
||||
foreach (var mappingModel in mappingModels)
|
||||
{
|
||||
if (mappingModels.Length == 1 && Guid.TryParse(filenameWithoutExtension, out Guid guidFromFilename))
|
||||
@@ -254,7 +256,7 @@ namespace WireMock.Server
|
||||
|
||||
private void InitProxyAndRecord(IFluentMockServerSettings settings)
|
||||
{
|
||||
_httpClientForProxy = HttpClientHelper.CreateHttpClient(settings.ProxyAndRecordSettings.ClientX509Certificate2ThumbprintOrSubjectName);
|
||||
_httpClientForProxy = HttpClientHelper.CreateHttpClient(settings.ProxyAndRecordSettings);
|
||||
|
||||
var respondProvider = Given(Request.Create().WithPath("/*").UsingAnyMethod());
|
||||
if (settings.StartAdminInterface == true)
|
||||
@@ -785,22 +787,35 @@ namespace WireMock.Server
|
||||
|
||||
if (responseModel.UseTransformer == true)
|
||||
{
|
||||
responseBuilder = responseBuilder.WithTransformer();
|
||||
responseBuilder = responseBuilder.WithTransformer(responseModel.UseTransformerForBodyAsFile == true);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(responseModel.ProxyUrl))
|
||||
{
|
||||
if (string.IsNullOrEmpty(responseModel.X509Certificate2ThumbprintOrSubjectName))
|
||||
var proxyAndRecordSettings = new ProxyAndRecordSettings
|
||||
{
|
||||
return responseBuilder.WithProxy(responseModel.ProxyUrl);
|
||||
}
|
||||
Url = responseModel.ProxyUrl,
|
||||
ClientX509Certificate2ThumbprintOrSubjectName = responseModel.X509Certificate2ThumbprintOrSubjectName,
|
||||
WebProxySettings = responseModel.WebProxy != null ? new WebProxySettings
|
||||
{
|
||||
Address = responseModel.WebProxy.Address,
|
||||
UserName = responseModel.WebProxy.UserName,
|
||||
Password = responseModel.WebProxy.Password
|
||||
} : null
|
||||
};
|
||||
|
||||
return responseBuilder.WithProxy(responseModel.ProxyUrl, responseModel.X509Certificate2ThumbprintOrSubjectName);
|
||||
return responseBuilder.WithProxy(proxyAndRecordSettings);
|
||||
}
|
||||
|
||||
if (responseModel.StatusCode.HasValue)
|
||||
switch (responseModel.StatusCode)
|
||||
{
|
||||
responseBuilder = responseBuilder.WithStatusCode(responseModel.StatusCode.Value);
|
||||
case int statusCodeAsInteger:
|
||||
responseBuilder = responseBuilder.WithStatusCode(statusCodeAsInteger);
|
||||
break;
|
||||
|
||||
case string statusCodeAsString:
|
||||
responseBuilder = responseBuilder.WithStatusCode(statusCodeAsString);
|
||||
break;
|
||||
}
|
||||
|
||||
if (responseModel.Headers != null)
|
||||
@@ -875,7 +890,7 @@ namespace WireMock.Server
|
||||
{
|
||||
if (requestMessage?.BodyData?.DetectedBodyType == BodyType.String)
|
||||
{
|
||||
return JsonConvert.DeserializeObject<T>(requestMessage.BodyData.BodyAsString);
|
||||
return JsonUtils.DeserializeObject<T>(requestMessage.BodyData.BodyAsString);
|
||||
}
|
||||
|
||||
if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json)
|
||||
|
||||
@@ -44,5 +44,15 @@ namespace WireMock.Settings
|
||||
/// Defines a list of cookies which will excluded from the saved mappings.
|
||||
/// </summary>
|
||||
string[] BlackListedCookies { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Defines the WebProxySettings.
|
||||
/// </summary>
|
||||
IWebProxySettings WebProxySettings { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Proxy requests should follow redirection (30x).
|
||||
/// </summary>
|
||||
bool? AllowAutoRedirect { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
20
src/WireMock.Net/Settings/IWebProxySettings.cs
Normal file
20
src/WireMock.Net/Settings/IWebProxySettings.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
namespace WireMock.Settings
|
||||
{
|
||||
public interface IWebProxySettings
|
||||
{
|
||||
/// <summary>
|
||||
/// A string instance that contains the address of the proxy server.
|
||||
/// </summary>
|
||||
string Address { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The user name associated with the credentials.
|
||||
/// </summary>
|
||||
string UserName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The password for the user name associated with the credentials.
|
||||
/// </summary>
|
||||
string Password { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -34,5 +34,13 @@ namespace WireMock.Settings
|
||||
/// <inheritdoc cref="IProxyAndRecordSettings.BlackListedCookies"/>
|
||||
[PublicAPI]
|
||||
public string[] BlackListedCookies { get; set; }
|
||||
|
||||
/// <inheritdoc cref="IProxyAndRecordSettings.WebProxySettings"/>
|
||||
[PublicAPI]
|
||||
public IWebProxySettings WebProxySettings { get; set; }
|
||||
|
||||
/// <inheritdoc cref="IProxyAndRecordSettings.AllowAutoRedirect"/>
|
||||
[PublicAPI]
|
||||
public bool? AllowAutoRedirect { get; set; }
|
||||
}
|
||||
}
|
||||
19
src/WireMock.Net/Settings/WebProxySettings.cs
Normal file
19
src/WireMock.Net/Settings/WebProxySettings.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using JetBrains.Annotations;
|
||||
|
||||
namespace WireMock.Settings
|
||||
{
|
||||
public class WebProxySettings : IWebProxySettings
|
||||
{
|
||||
/// <inheritdoc cref="IWebProxySettings.Address"/>
|
||||
[PublicAPI]
|
||||
public string Address { get; set; }
|
||||
|
||||
/// <inheritdoc cref="IWebProxySettings.UserName"/>
|
||||
[PublicAPI]
|
||||
public string UserName { get; set; }
|
||||
|
||||
/// <inheritdoc cref="IWebProxySettings.Password"/>
|
||||
[PublicAPI]
|
||||
public string Password { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Linq;
|
||||
using WireMock.Util;
|
||||
using WireMock.Validation;
|
||||
@@ -14,7 +15,7 @@ namespace WireMock.Transformers
|
||||
{
|
||||
handlebarsContext.RegisterHelper("JsonPath.SelectToken", (writer, context, arguments) =>
|
||||
{
|
||||
(JObject valueToProcess, string jsonPath) = ParseArguments(arguments);
|
||||
(JToken valueToProcess, string jsonPath) = ParseArguments(arguments);
|
||||
|
||||
try
|
||||
{
|
||||
@@ -29,7 +30,7 @@ namespace WireMock.Transformers
|
||||
|
||||
handlebarsContext.RegisterHelper("JsonPath.SelectTokens", (writer, options, context, arguments) =>
|
||||
{
|
||||
(JObject valueToProcess, string jsonPath) = ParseArguments(arguments);
|
||||
(JToken valueToProcess, string jsonPath) = ParseArguments(arguments);
|
||||
|
||||
try
|
||||
{
|
||||
@@ -46,22 +47,26 @@ namespace WireMock.Transformers
|
||||
});
|
||||
}
|
||||
|
||||
private static (JObject valueToProcess, string jsonpath) ParseArguments(object[] arguments)
|
||||
private static (JToken valueToProcess, string jsonpath) ParseArguments(object[] arguments)
|
||||
{
|
||||
Check.Condition(arguments, args => args.Length == 2, nameof(arguments));
|
||||
Check.NotNull(arguments[0], "arguments[0]");
|
||||
Check.NotNullOrEmpty(arguments[1] as string, "arguments[1]");
|
||||
|
||||
JObject valueToProcess;
|
||||
JToken valueToProcess;
|
||||
|
||||
switch (arguments[0])
|
||||
{
|
||||
case string jsonAsString:
|
||||
valueToProcess = JsonUtils.Parse(jsonAsString);
|
||||
case JToken tokenValue:
|
||||
valueToProcess = tokenValue;
|
||||
break;
|
||||
|
||||
case JObject jsonAsJObject:
|
||||
valueToProcess = jsonAsJObject;
|
||||
case string stringValue:
|
||||
valueToProcess = JsonUtils.Parse(stringValue);
|
||||
break;
|
||||
|
||||
case IEnumerable enumerableValue:
|
||||
valueToProcess = JArray.FromObject(enumerableValue);
|
||||
break;
|
||||
|
||||
default:
|
||||
|
||||
11
src/WireMock.Net/Transformers/HandlebarsContext.cs
Normal file
11
src/WireMock.Net/Transformers/HandlebarsContext.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
using HandlebarsDotNet;
|
||||
using WireMock.Handlers;
|
||||
|
||||
namespace WireMock.Transformers
|
||||
{
|
||||
internal class HandlebarsContext : IHandlebarsContext
|
||||
{
|
||||
public IHandlebars Handlebars { get; set; }
|
||||
public IFileSystemHandler FileSystemHandler { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -20,15 +20,19 @@ namespace WireMock.Transformers
|
||||
_action = action;
|
||||
}
|
||||
|
||||
public IHandlebars Create()
|
||||
public IHandlebarsContext Create()
|
||||
{
|
||||
var handlebarsContext = Handlebars.Create(HandlebarsConfiguration);
|
||||
var handlebars = Handlebars.Create(HandlebarsConfiguration);
|
||||
|
||||
HandlebarsHelpers.Register(handlebarsContext, _fileSystemHandler);
|
||||
HandlebarsHelpers.Register(handlebars, _fileSystemHandler);
|
||||
|
||||
_action?.Invoke(handlebarsContext, _fileSystemHandler);
|
||||
_action?.Invoke(handlebars, _fileSystemHandler);
|
||||
|
||||
return handlebarsContext;
|
||||
return new HandlebarsContext
|
||||
{
|
||||
Handlebars = handlebars,
|
||||
FileSystemHandler = _fileSystemHandler
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
12
src/WireMock.Net/Transformers/IHandlebarsContext.cs
Normal file
12
src/WireMock.Net/Transformers/IHandlebarsContext.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using HandlebarsDotNet;
|
||||
using WireMock.Handlers;
|
||||
|
||||
namespace WireMock.Transformers
|
||||
{
|
||||
interface IHandlebarsContext
|
||||
{
|
||||
IHandlebars Handlebars { get; set; }
|
||||
|
||||
IFileSystemHandler FileSystemHandler { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,6 @@ namespace WireMock.Transformers
|
||||
{
|
||||
interface IHandlebarsContextFactory
|
||||
{
|
||||
IHandlebars Create();
|
||||
IHandlebarsContext Create();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,27 +21,27 @@ namespace WireMock.Transformers
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
public ResponseMessage Transform(RequestMessage requestMessage, ResponseMessage original)
|
||||
public ResponseMessage Transform(RequestMessage requestMessage, ResponseMessage original, bool useTransformerForBodyAsFile)
|
||||
{
|
||||
var handlebarsContext = _factory.Create();
|
||||
|
||||
var responseMessage = new ResponseMessage { StatusCode = original.StatusCode };
|
||||
var responseMessage = new ResponseMessage();
|
||||
|
||||
var template = new { request = requestMessage };
|
||||
|
||||
switch (original.BodyData.DetectedBodyType)
|
||||
{
|
||||
case BodyType.Json:
|
||||
TransformBodyAsJson(handlebarsContext, template, original, responseMessage);
|
||||
TransformBodyAsJson(handlebarsContext.Handlebars, template, original, responseMessage);
|
||||
break;
|
||||
|
||||
case BodyType.File:
|
||||
TransformBodyAsFile(handlebarsContext, template, original, responseMessage);
|
||||
TransformBodyAsFile(handlebarsContext, template, original, responseMessage, useTransformerForBodyAsFile);
|
||||
break;
|
||||
|
||||
case BodyType.String:
|
||||
responseMessage.BodyOriginal = original.BodyData.BodyAsString;
|
||||
TransformBodyAsString(handlebarsContext, template, original, responseMessage);
|
||||
TransformBodyAsString(handlebarsContext.Handlebars, template, original, responseMessage);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -52,9 +52,9 @@ namespace WireMock.Transformers
|
||||
var newHeaders = new Dictionary<string, WireMockList<string>>();
|
||||
foreach (var header in original.Headers)
|
||||
{
|
||||
var templateHeaderKey = handlebarsContext.Compile(header.Key);
|
||||
var templateHeaderKey = handlebarsContext.Handlebars.Compile(header.Key);
|
||||
var templateHeaderValues = header.Value
|
||||
.Select(handlebarsContext.Compile)
|
||||
.Select(handlebarsContext.Handlebars.Compile)
|
||||
.Select(func => func(template))
|
||||
.ToArray();
|
||||
|
||||
@@ -63,6 +63,18 @@ namespace WireMock.Transformers
|
||||
|
||||
responseMessage.Headers = newHeaders;
|
||||
|
||||
switch (original.StatusCode)
|
||||
{
|
||||
case int statusCodeAsInteger:
|
||||
responseMessage.StatusCode = statusCodeAsInteger;
|
||||
break;
|
||||
|
||||
case string statusCodeAsString:
|
||||
var templateForStatusCode = handlebarsContext.Handlebars.Compile(statusCodeAsString);
|
||||
responseMessage.StatusCode = templateForStatusCode(template);
|
||||
break;
|
||||
}
|
||||
|
||||
return responseMessage;
|
||||
}
|
||||
|
||||
@@ -73,19 +85,24 @@ namespace WireMock.Transformers
|
||||
{
|
||||
case JObject bodyAsJObject:
|
||||
jToken = bodyAsJObject.DeepClone();
|
||||
WalkNode(handlebarsContext, jToken, template);
|
||||
break;
|
||||
|
||||
case Array bodyAsArray:
|
||||
jToken = JArray.FromObject(bodyAsArray);
|
||||
WalkNode(handlebarsContext, jToken, template);
|
||||
break;
|
||||
|
||||
case string bodyAsString:
|
||||
jToken = ReplaceSingleNode(handlebarsContext, bodyAsString, template);
|
||||
break;
|
||||
|
||||
default:
|
||||
jToken = JObject.FromObject(original.BodyData.BodyAsJson);
|
||||
WalkNode(handlebarsContext, jToken, template);
|
||||
break;
|
||||
}
|
||||
|
||||
WalkNode(handlebarsContext, jToken, template);
|
||||
|
||||
responseMessage.BodyData = new BodyData
|
||||
{
|
||||
DetectedBodyType = original.BodyData.DetectedBodyType,
|
||||
@@ -94,6 +111,24 @@ namespace WireMock.Transformers
|
||||
};
|
||||
}
|
||||
|
||||
private static JToken ReplaceSingleNode(IHandlebars handlebarsContext, string stringValue, object context)
|
||||
{
|
||||
var templateForStringValue = handlebarsContext.Compile(stringValue);
|
||||
string transformedString = templateForStringValue(context);
|
||||
if (!string.Equals(stringValue, transformedString))
|
||||
{
|
||||
const string property = "_";
|
||||
JObject dummy = JObject.Parse($"{{ \"{property}\": null }}");
|
||||
JToken node = dummy[property];
|
||||
|
||||
ReplaceNodeValue(node, transformedString);
|
||||
|
||||
return dummy[property];
|
||||
}
|
||||
|
||||
return stringValue;
|
||||
}
|
||||
|
||||
private static void WalkNode(IHandlebars handlebarsContext, JToken node, object context)
|
||||
{
|
||||
if (node.Type == JTokenType.Object)
|
||||
@@ -165,16 +200,33 @@ namespace WireMock.Transformers
|
||||
};
|
||||
}
|
||||
|
||||
private static void TransformBodyAsFile(IHandlebars handlebarsContext, object template, ResponseMessage original, ResponseMessage responseMessage)
|
||||
private void TransformBodyAsFile(IHandlebarsContext handlebarsContext, object template, ResponseMessage original, ResponseMessage responseMessage, bool useTransformerForBodyAsFile)
|
||||
{
|
||||
var templateBodyAsFile = handlebarsContext.Compile(original.BodyData.BodyAsFile);
|
||||
var templateBodyAsFile = handlebarsContext.Handlebars.Compile(original.BodyData.BodyAsFile);
|
||||
string transformedBodyAsFilename = templateBodyAsFile(template);
|
||||
|
||||
responseMessage.BodyData = new BodyData
|
||||
if (!useTransformerForBodyAsFile)
|
||||
{
|
||||
DetectedBodyType = original.BodyData.DetectedBodyType,
|
||||
DetectedBodyTypeFromContentType = original.BodyData.DetectedBodyTypeFromContentType,
|
||||
BodyAsFile = templateBodyAsFile(template)
|
||||
};
|
||||
responseMessage.BodyData = new BodyData
|
||||
{
|
||||
DetectedBodyType = original.BodyData.DetectedBodyType,
|
||||
DetectedBodyTypeFromContentType = original.BodyData.DetectedBodyTypeFromContentType,
|
||||
BodyAsFile = transformedBodyAsFilename
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
string text = handlebarsContext.FileSystemHandler.ReadResponseBodyAsString(transformedBodyAsFilename);
|
||||
var templateBodyAsString = handlebarsContext.Handlebars.Compile(text);
|
||||
|
||||
responseMessage.BodyData = new BodyData
|
||||
{
|
||||
DetectedBodyType = BodyType.String,
|
||||
DetectedBodyTypeFromContentType = original.BodyData.DetectedBodyTypeFromContentType,
|
||||
BodyAsString = templateBodyAsString(template),
|
||||
BodyAsFile = transformedBodyAsFilename
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,8 +57,6 @@ namespace WireMock.Util
|
||||
new WildcardMatcher("application/x-www-form-urlencoded", true)
|
||||
};
|
||||
|
||||
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings { DateParseHandling = DateParseHandling.None };
|
||||
|
||||
public static bool ShouldParseBody([CanBeNull] string httpMethod, bool allowBodyForAllHttpMethods)
|
||||
{
|
||||
if (string.IsNullOrEmpty(httpMethod))
|
||||
@@ -147,7 +145,7 @@ namespace WireMock.Util
|
||||
{
|
||||
try
|
||||
{
|
||||
data.BodyAsJson = JsonConvert.DeserializeObject(data.BodyAsString, JsonSerializerSettings);
|
||||
data.BodyAsJson = JsonUtils.DeserializeObject(data.BodyAsString);
|
||||
data.DetectedBodyType = BodyType.Json;
|
||||
}
|
||||
catch
|
||||
|
||||
@@ -10,6 +10,26 @@ namespace WireMock.Util
|
||||
/// </summary>
|
||||
internal static class HttpStatusRangeParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines whether the specified pattern is match.
|
||||
/// </summary>
|
||||
/// <param name="pattern">The pattern. (Can be null, in that case it's allowed.)</param>
|
||||
/// <param name="httpStatusCode">The value.</param>
|
||||
/// <exception cref="ArgumentException"><paramref name="pattern"/> is invalid.</exception>
|
||||
public static bool IsMatch(string pattern, object httpStatusCode)
|
||||
{
|
||||
switch (httpStatusCode)
|
||||
{
|
||||
case int statusCodeAsInteger:
|
||||
return IsMatch(pattern, statusCodeAsInteger);
|
||||
|
||||
case string statusCodeAsString:
|
||||
return IsMatch(pattern, int.Parse(statusCodeAsString));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the specified pattern is match.
|
||||
/// </summary>
|
||||
|
||||
@@ -19,10 +19,32 @@ namespace WireMock.Util
|
||||
/// Using : DateParseHandling = DateParseHandling.None
|
||||
/// </summary>
|
||||
/// <param name="json">A System.String that contains JSON.</param>
|
||||
/// <returns>A Newtonsoft.Json.Linq.JObject populated from the string that contains JSON.</returns>
|
||||
public static JObject Parse(string json)
|
||||
/// <returns>A Newtonsoft.Json.Linq.JToken populated from the string that contains JSON.</returns>
|
||||
public static JToken Parse(string json)
|
||||
{
|
||||
return JsonConvert.DeserializeObject<JObject>(json, JsonSerializerSettings);
|
||||
return JsonConvert.DeserializeObject<JToken>(json, JsonSerializerSettings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the JSON to a .NET object.
|
||||
/// Using : DateParseHandling = DateParseHandling.None
|
||||
/// </summary>
|
||||
/// <param name="json">A System.String that contains JSON.</param>
|
||||
/// <returns>The deserialized object from the JSON string.</returns>
|
||||
public static object DeserializeObject(string json)
|
||||
{
|
||||
return JsonConvert.DeserializeObject(json, JsonSerializerSettings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the JSON to the specified .NET type.
|
||||
/// Using : DateParseHandling = DateParseHandling.None
|
||||
/// </summary>
|
||||
/// <param name="json">A System.String that contains JSON.</param>
|
||||
/// <returns>The deserialized object from the JSON string.</returns>
|
||||
public static T DeserializeObject<T>(string json)
|
||||
{
|
||||
return JsonConvert.DeserializeObject<T>(json, JsonSerializerSettings);
|
||||
}
|
||||
|
||||
public static T ParseJTokenToObject<T>(object value)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
|
||||
namespace WireMock.Util
|
||||
{
|
||||
@@ -30,7 +31,7 @@ namespace WireMock.Util
|
||||
.Split(new[] { '&', ';' }, StringSplitOptions.RemoveEmptyEntries) // Support "?key=value;key=anotherValue" and "?key=value&key=anotherValue"
|
||||
.Select(parameter => parameter.Split(new[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries))
|
||||
.GroupBy(parts => parts[0], JoinParts)
|
||||
.ToDictionary(grouping => grouping.Key, grouping => new WireMockList<string>(grouping.SelectMany(x => x)));
|
||||
.ToDictionary(grouping => grouping.Key, grouping => new WireMockList<string>(grouping.SelectMany(x => x).Select(WebUtility.UrlDecode)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
<AssemblyTitle>WireMock.Net</AssemblyTitle>
|
||||
<Authors>Stef Heyenrath</Authors>
|
||||
<!--<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0;netcoreapp2.1</TargetFrameworks>-->
|
||||
<!--<TargetFrameworks>net451;net452;net46;netstandard1.3;netstandard2.0</TargetFrameworks>-->
|
||||
<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0</TargetFrameworks>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<AssemblyName>WireMock.Net</AssemblyName>
|
||||
|
||||
@@ -75,6 +75,24 @@ namespace WireMock.Net.Tests.Matchers
|
||||
Check.That(match).IsEqualTo(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JsonMatcher_IsMatch_JArray()
|
||||
{
|
||||
// Assign
|
||||
var matcher = new JsonMatcher(new[] { "x", "y" });
|
||||
|
||||
// Act
|
||||
var jArray = new JArray
|
||||
{
|
||||
"x",
|
||||
"y"
|
||||
};
|
||||
double match = matcher.IsMatch(jArray);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(1.0, match);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JsonMatcher_IsMatch_JObject()
|
||||
{
|
||||
@@ -139,6 +157,24 @@ namespace WireMock.Net.Tests.Matchers
|
||||
Assert.Equal(1.0, match);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JsonMatcher_IsMatch_JArrayAsString()
|
||||
{
|
||||
// Assign
|
||||
var matcher = new JsonMatcher("[ \"x\", \"y\" ]");
|
||||
|
||||
// Act
|
||||
var jArray = new JArray
|
||||
{
|
||||
"x",
|
||||
"y"
|
||||
};
|
||||
double match = matcher.IsMatch(jArray);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(1.0, match);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JsonMatcher_IsMatch_JObjectAsString()
|
||||
{
|
||||
|
||||
@@ -78,7 +78,7 @@ namespace WireMock.Net.Tests.Owin
|
||||
// Assert and Verify
|
||||
_optionsMock.Verify(o => o.Logger.Warn(It.IsAny<string>(), It.IsAny<object[]>()), Times.Once);
|
||||
|
||||
Expression<Func<ResponseMessage, bool>> match = r => r.StatusCode == 404 && ((StatusModel)r.BodyData.BodyAsJson).Status == "No matching mapping found";
|
||||
Expression<Func<ResponseMessage, bool>> match = r => (int) r.StatusCode == 404 && ((StatusModel)r.BodyData.BodyAsJson).Status == "No matching mapping found";
|
||||
_responseMapperMock.Verify(m => m.MapAsync(It.Is(match), It.IsAny<IResponse>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ namespace WireMock.Net.Tests.Owin
|
||||
// Assert and Verify
|
||||
_optionsMock.Verify(o => o.Logger.Error(It.IsAny<string>(), It.IsAny<object[]>()), Times.Once);
|
||||
|
||||
Expression<Func<ResponseMessage, bool>> match = r => r.StatusCode == 401;
|
||||
Expression<Func<ResponseMessage, bool>> match = r => (int) r.StatusCode == 401;
|
||||
_responseMapperMock.Verify(m => m.MapAsync(It.Is(match), It.IsAny<IResponse>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ namespace WireMock.Net.Tests.Owin
|
||||
// Assert and Verify
|
||||
_optionsMock.Verify(o => o.Logger.Error(It.IsAny<string>(), It.IsAny<object[]>()), Times.Once);
|
||||
|
||||
Expression<Func<ResponseMessage, bool>> match = r => r.StatusCode == 401;
|
||||
Expression<Func<ResponseMessage, bool>> match = r => (int) r.StatusCode == 401;
|
||||
_responseMapperMock.Verify(m => m.MapAsync(It.Is(match), It.IsAny<IResponse>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,21 +13,6 @@ namespace WireMock.Net.Tests
|
||||
{
|
||||
private const string ClientIp = "::1";
|
||||
|
||||
// [Fact] : TODO : this test fails???
|
||||
public void Request_WithPath_EncodedSpaces()
|
||||
{
|
||||
// Assign
|
||||
var spec = Request.Create().WithPath("/path/a%20b").UsingAnyMethod();
|
||||
|
||||
// when
|
||||
var body = new BodyData();
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost/path/a%20b"), "GET", ClientIp, body);
|
||||
|
||||
// then
|
||||
var requestMatchResult = new RequestMatchResult();
|
||||
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Request_WithPath_Spaces()
|
||||
{
|
||||
|
||||
@@ -8,7 +8,7 @@ using Xunit;
|
||||
|
||||
namespace WireMock.Net.Tests.ResponseBuilders
|
||||
{
|
||||
public class ResponseWithWithFaultTests
|
||||
public class ResponseWithFaultTests
|
||||
{
|
||||
private readonly Mock<IFluentMockServerSettings> _settingsMock = new Mock<IFluentMockServerSettings>();
|
||||
private const string ClientIp = "::1";
|
||||
@@ -5,6 +5,7 @@ using System.Threading.Tasks;
|
||||
using Moq;
|
||||
using Newtonsoft.Json;
|
||||
using NFluent;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Models;
|
||||
using WireMock.ResponseBuilders;
|
||||
using WireMock.Settings;
|
||||
@@ -23,30 +24,6 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
||||
private readonly Mock<IFluentMockServerSettings> _settingsMock = new Mock<IFluentMockServerSettings>();
|
||||
private const string ClientIp = "::1";
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsObject()
|
||||
{
|
||||
// Assign
|
||||
string jsonString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }";
|
||||
var bodyData = new BodyData
|
||||
{
|
||||
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
|
||||
DetectedBodyType = BodyType.Json,
|
||||
Encoding = Encoding.UTF8
|
||||
};
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
|
||||
|
||||
var response = Response.Create()
|
||||
.WithBodyAsJson(new { x = "test {{request.path}}" })
|
||||
.WithTransformer();
|
||||
|
||||
// Act
|
||||
var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object);
|
||||
|
||||
// Assert
|
||||
Check.That(JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson)).Equals("{\"x\":\"test /foo_object\"}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponse_Handlebars_UrlPathVerb()
|
||||
{
|
||||
@@ -194,6 +171,30 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
||||
Check.That(responseMessage.BodyData.BodyAsString).Equals("test http://localhost:1234 1234 http localhost");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsObject()
|
||||
{
|
||||
// Assign
|
||||
string jsonString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }";
|
||||
var bodyData = new BodyData
|
||||
{
|
||||
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
|
||||
DetectedBodyType = BodyType.Json,
|
||||
Encoding = Encoding.UTF8
|
||||
};
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
|
||||
|
||||
var response = Response.Create()
|
||||
.WithBodyAsJson(new { x = "test {{request.path}}" })
|
||||
.WithTransformer();
|
||||
|
||||
// Act
|
||||
var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object);
|
||||
|
||||
// Assert
|
||||
Check.That(JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson)).Equals("{\"x\":\"test /foo_object\"}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsArray()
|
||||
{
|
||||
@@ -226,7 +227,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
||||
|
||||
var response = Response.Create()
|
||||
.WithTransformer()
|
||||
.WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\test.xml"); // why use a \\ here ?
|
||||
.WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\\test.xml");
|
||||
|
||||
// Act
|
||||
var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object);
|
||||
@@ -235,6 +236,30 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
||||
Check.That(responseMessage.BodyData.BodyAsFile).Equals(@"c:\1\test.xml");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponse_Handlebars_WithBodyAsFile_And_TransformContentFromBodyAsFile()
|
||||
{
|
||||
// Assign
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("<xml MyUniqueNumber=\"{{request.query.MyUniqueNumber}}\"></xml>");
|
||||
|
||||
_settingsMock.SetupGet(s => s.FileSystemHandler).Returns(filesystemHandlerMock.Object);
|
||||
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost/foo?MyUniqueNumber=1"), "GET", ClientIp);
|
||||
|
||||
var response = Response.Create()
|
||||
.WithTransformer(true)
|
||||
.WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\\test.xml");
|
||||
|
||||
// Act
|
||||
var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object);
|
||||
|
||||
// Assert
|
||||
Check.That(responseMessage.BodyData.BodyAsFile).Equals(@"c:\1\test.xml");
|
||||
Check.That(responseMessage.BodyData.DetectedBodyType).Equals(BodyType.String);
|
||||
Check.That(responseMessage.BodyData.BodyAsString).Equals("<xml MyUniqueNumber=\"1\"></xml>");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponse_Handlebars_WithBodyAsFile_JsonPath()
|
||||
{
|
||||
@@ -261,5 +286,53 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
||||
// Assert
|
||||
Check.That(responseMessage.BodyData.BodyAsFile).Equals(@"c:\1\test.json");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsNormalString()
|
||||
{
|
||||
// Assign
|
||||
string jsonString = "{ \"name\": \"WireMock\" }";
|
||||
var bodyData = new BodyData
|
||||
{
|
||||
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
|
||||
DetectedBodyType = BodyType.Json,
|
||||
Encoding = Encoding.UTF8
|
||||
};
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
|
||||
|
||||
var response = Response.Create()
|
||||
.WithBodyAsJson("test")
|
||||
.WithTransformer();
|
||||
|
||||
// Act
|
||||
var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object);
|
||||
|
||||
// Assert
|
||||
Check.That(JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson)).Equals("\"test\"");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsHandlebarsString()
|
||||
{
|
||||
// Assign
|
||||
string jsonString = "{ \"name\": \"WireMock\" }";
|
||||
var bodyData = new BodyData
|
||||
{
|
||||
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
|
||||
DetectedBodyType = BodyType.Json,
|
||||
Encoding = Encoding.UTF8
|
||||
};
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
|
||||
|
||||
var response = Response.Create()
|
||||
.WithBodyAsJson("{{{request.bodyAsJson}}}")
|
||||
.WithTransformer();
|
||||
|
||||
// Act
|
||||
var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object);
|
||||
|
||||
// Assert
|
||||
Check.That(JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson)).Equals("{\"name\":\"WireMock\"}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
using NFluent;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using WireMock.Models;
|
||||
using WireMock.RequestBuilders;
|
||||
@@ -45,6 +46,28 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
||||
Check.That(responseMessage.Headers["Content-Type"].ToString()).IsEqualTo("application/json");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Response_WithProxy_WebProxySettings()
|
||||
{
|
||||
// Assign
|
||||
var settings = new ProxyAndRecordSettings
|
||||
{
|
||||
Url = "http://test.nl",
|
||||
WebProxySettings = new WebProxySettings
|
||||
{
|
||||
Address = "http://company",
|
||||
UserName = "x",
|
||||
Password = "y"
|
||||
}
|
||||
};
|
||||
var response = Response.Create().WithProxy(settings);
|
||||
|
||||
// Act
|
||||
var request = new RequestMessage(new UrlDetails($"{_server.Urls[0]}/{_guid}"), "GET", "::1");
|
||||
|
||||
Check.ThatAsyncCode(() => response.ProvideResponseAsync(request, _settingsMock.Object)).Throws<HttpRequestException>();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_server?.Dispose();
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
using FluentAssertions;
|
||||
using Moq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using WireMock.Models;
|
||||
using WireMock.ResponseBuilders;
|
||||
using WireMock.Settings;
|
||||
using Xunit;
|
||||
|
||||
namespace WireMock.Net.Tests.ResponseBuilders
|
||||
{
|
||||
public class ResponseWithStatusCodeTests
|
||||
{
|
||||
private readonly Mock<IFluentMockServerSettings> _settingsMock = new Mock<IFluentMockServerSettings>();
|
||||
private const string ClientIp = "::1";
|
||||
|
||||
[Theory]
|
||||
[InlineData("201", "201")]
|
||||
[InlineData(201, 201)]
|
||||
[InlineData(HttpStatusCode.Created, 201)]
|
||||
public async Task Response_ProvideResponse_WithStatusCode(object statusCode, object expectedStatusCode)
|
||||
{
|
||||
// Arrange
|
||||
var request = new RequestMessage(new UrlDetails("http://localhost/fault"), "GET", ClientIp);
|
||||
|
||||
// Act
|
||||
var response = Response.Create();
|
||||
switch (statusCode)
|
||||
{
|
||||
case string statusCodeAsString:
|
||||
response = response.WithStatusCode(statusCodeAsString);
|
||||
break;
|
||||
|
||||
case int statusCodeAInteger:
|
||||
response = response.WithStatusCode(statusCodeAInteger);
|
||||
break;
|
||||
|
||||
case HttpStatusCode statusCodeAsEnum:
|
||||
response = response.WithStatusCode(statusCodeAsEnum);
|
||||
break;
|
||||
}
|
||||
|
||||
var responseMessage = await response.ProvideResponseAsync(request, _settingsMock.Object);
|
||||
|
||||
// Assert
|
||||
responseMessage.StatusCode.Should().Be(expectedStatusCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,34 @@ namespace WireMock.Net.Tests.Util
|
||||
result["key"].Should().Equal(new WireMockList<string>(new[] { "1", "2", "3" }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_With1ParamContainingEscapedAnd()
|
||||
{
|
||||
// Assign
|
||||
string query = "?winkel=C%26A";
|
||||
|
||||
// Act
|
||||
var result = QueryStringParser.Parse(query);
|
||||
|
||||
// Assert
|
||||
result.Count.Should().Be(1);
|
||||
result["winkel"].Should().Equal(new WireMockList<string>(new[] { "C&A" }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_With1ParamContainingParentheses()
|
||||
{
|
||||
// Assign
|
||||
string query = "?Transaction=(123)";
|
||||
|
||||
// Act
|
||||
var result = QueryStringParser.Parse(query);
|
||||
|
||||
// Assert
|
||||
result.Count.Should().Be(1);
|
||||
result["Transaction"].Should().Equal(new WireMockList<string>(new[] { "(123)" }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WithMultipleParamWithSameKey()
|
||||
{
|
||||
@@ -227,12 +255,12 @@ namespace WireMock.Net.Tests.Util
|
||||
|
||||
// Assert
|
||||
result.Count.Should().Be(6);
|
||||
result["q"].Should().Equal(new WireMockList<string>("energy+edge"));
|
||||
result["q"].Should().Equal(new WireMockList<string>("energy edge"));
|
||||
result["rls"].Should().Equal(new WireMockList<string>("com.microsoft:en-au"));
|
||||
result["ie"].Should().Equal(new WireMockList<string>("UTF-8"));
|
||||
result["oe"].Should().Equal(new WireMockList<string>("UTF-8"));
|
||||
result["startIndex"].Should().Equal(new WireMockList<string>());
|
||||
result["startPage"].Should().Equal(new WireMockList<string>("1%22"));
|
||||
result["startPage"].Should().Equal(new WireMockList<string>("1\""));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<Authors>Stef Heyenrath</Authors>
|
||||
<TargetFrameworks>net452;netcoreapp2.1</TargetFrameworks>
|
||||
<!--<TargetFramework>netcoreapp2.1</TargetFramework>-->
|
||||
<DebugType>full</DebugType>
|
||||
<AssemblyName>WireMock.Net.Tests</AssemblyName>
|
||||
<PackageId>WireMock.Net.Tests</PackageId>
|
||||
@@ -42,7 +43,7 @@
|
||||
<PackageReference Include="System.Threading" Version="4.3.0" />
|
||||
<PackageReference Include="RestEase" Version="1.4.7" />
|
||||
<PackageReference Include="RandomDataGenerator.Net" Version="1.0.10" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
|
||||
<PackageReference Include="Moq" Version="4.10.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
|
||||
<PackageReference Include="NFluent" Version="2.5.0" />
|
||||
|
||||
Reference in New Issue
Block a user