Update BodyParser logic (#212)

* Update BodyParser logic

* update logic for byte[]

* small update

* MyGetKey

* myget

* dotnet nuget push

* dotnet build

* Release

* .

* StringContent

* 1.0.4.18-preview-02

* Debug

* 1.0.4.18-preview-02

* disable some proxy tests

* myget

* packagesToPack

* fix

* <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>     <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>

* Release

* <VersionPrefix>1.0.4.18</VersionPrefix>

* fix

* BodyParserTests

* ResponseBodyData (#216)

* ResponseBodyData

* refactor tests

* LogEntryMapperTests
This commit is contained in:
Stef Heyenrath
2018-10-25 14:08:24 +02:00
committed by GitHub
parent d9ed1bf812
commit 1af512fc72
66 changed files with 1186 additions and 823 deletions

19
Directory.Build.props Normal file
View File

@@ -0,0 +1,19 @@
<Project>
<PropertyGroup>
<MsBuildAllProjects>$(MsBuildAllProjects);$(MsBuildThisFileFullPath)</MsBuildAllProjects>
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>1.0.4.18</VersionPrefix>
</PropertyGroup>
<Choose>
<!-- The environment variable `Prerelease` is set in the azure-pipelines.yml file. -->
<When Condition=" '$(Prerelease)' != '' ">
<PropertyGroup>
<!-- Set the version to x.x.x.x-{Prerelease}-1{Build_BuildId} (this is same buildId as defined in the azure-pipelines.yml file). -->
<VersionSuffix>$(Prerelease)-1$(BUILD_BUILDID)</VersionSuffix>
</PropertyGroup>
</When>
</Choose>
</Project>

View File

@@ -13,6 +13,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
azure-pipelines.yml = azure-pipelines.yml azure-pipelines.yml = azure-pipelines.yml
build-info.md = build-info.md build-info.md = build-info.md
CHANGELOG.md = CHANGELOG.md CHANGELOG.md = CHANGELOG.md
Directory.Build.props = Directory.Build.props
GitReleaseNotes.txt = GitReleaseNotes.txt GitReleaseNotes.txt = GitReleaseNotes.txt
README.md = README.md README.md = README.md
ReSharper_WireMock.DotSettings = ReSharper_WireMock.DotSettings ReSharper_WireMock.DotSettings = ReSharper_WireMock.DotSettings

View File

@@ -8,4 +8,7 @@
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=WWW/@EntryIndexedValue">WWW</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=WWW/@EntryIndexedValue">WWW</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=XMS/@EntryIndexedValue">XMS</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=XMS/@EntryIndexedValue">XMS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=XUA/@EntryIndexedValue">XUA</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=XUA/@EntryIndexedValue">XUA</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=funcs/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Heyenrath/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Stef/@EntryIndexedValue">True</s:Boolean>
</wpf:ResourceDictionary> </wpf:ResourceDictionary>

View File

@@ -2,17 +2,20 @@ pool:
vmImage: 'vs2017-win2016' vmImage: 'vs2017-win2016'
variables: variables:
buildConfiguration: 'Debug' Prerelease: 'ci'
buildId: "1$(Build.BuildId)" buildId: "1$(Build.BuildId)"
buildProjects: '**/src/**/*.csproj'
steps: steps:
# Print buildId # Print buildId
- script: | - script: |
echo "BuildId = $(buildId)" echo "BuildId = $(buildId)"
displayName: 'Print buildId'
# Install SonarScanner # Install SonarScanner
- script: | - script: |
dotnet tool install --global dotnet-sonarscanner dotnet tool install --global dotnet-sonarscanner
displayName: Install SonarScanner
# Begin SonarScanner # Begin SonarScanner
# See also # See also
@@ -22,17 +25,53 @@ steps:
# #
- script: | - 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" /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"
displayName: Begin SonarScanner
# Build source, tests and run tests for net452 and netcoreapp2.1 (with coverage) # Build source, tests and run tests for net452 and netcoreapp2.1 (with coverage)
- script: | - script: |
dotnet test ./test/WireMock.Net.Tests/WireMock.Net.Tests.csproj --configuration $(buildConfiguration) --framework net452 dotnet test ./test/WireMock.Net.Tests/WireMock.Net.Tests.csproj --configuration Debug --framework net452
dotnet test ./test/WireMock.Net.Tests/WireMock.Net.Tests.csproj --configuration $(buildConfiguration) --framework netcoreapp2.1 --logger trx /p:CollectCoverage=true /p:CoverletOutputFormat=opencover dotnet test ./test/WireMock.Net.Tests/WireMock.Net.Tests.csproj --configuration Debug --framework netcoreapp2.1 --logger trx /p:CollectCoverage=true /p:CoverletOutputFormat=opencover
displayName: 'Build source, tests and run tests for net452 and netcoreapp2.1 (with coverage)'
# End SonarScanner # End SonarScanner
- script: | - script: |
%USERPROFILE%\.dotnet\tools\dotnet-sonarscanner end /d:sonar.login="$(SONAR_TOKEN)" %USERPROFILE%\.dotnet\tools\dotnet-sonarscanner end /d:sonar.login="$(SONAR_TOKEN)"
displayName: End SonarScanner
- task: PublishTestResults@2 - task: PublishTestResults@2
inputs: inputs:
testRunner: VSTest testRunner: VSTest
testResultsFiles: '**/*.trx' testResultsFiles: '**/*.trx'
# Based on https://whereslou.com/2018/09/versioning-and-publishing-nuget-packages-automatically-using-azure-devops-pipelines/
- task: DotNetCoreCLI@2
displayName: Build Release
inputs:
command: 'build'
arguments: /p:Configuration=Release # https://github.com/MicrosoftDocs/vsts-docs/issues/1976
projects: $(buildProjects)
- task: DotNetCoreCLI@2
displayName: Pack
condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest')) # Do not run for PullRequests
inputs:
command: pack
configuration: 'Release'
packagesToPack: $(buildProjects)
nobuild: true
packDirectory: '$(Build.ArtifactStagingDirectory)/packages'
verbosityPack: 'normal'
- task: PublishBuildArtifacts@1
displayName: Publish Artifacts
condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest')) # Do not run for PullRequests
inputs:
PathtoPublish: '$(Build.ArtifactStagingDirectory)'
- task: DotNetCoreCLI@2
displayName: Push to MyGet
condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest')) # Do not run for PullRequests
inputs:
command: custom
custom: nuget
arguments: push $(Build.ArtifactStagingDirectory)\packages\*.nupkg --source https://www.myget.org/F/wiremock-net/api/v3/index.json --no-service-endpoint --api-key $(MyGetKey)

View File

@@ -24,7 +24,7 @@ namespace WireMock.Net.Console.Proxy.NETCoreApp2
ReadStaticMappings = false, ReadStaticMappings = false,
ProxyAndRecordSettings = new ProxyAndRecordSettings ProxyAndRecordSettings = new ProxyAndRecordSettings
{ {
Url = "https://www.google.com", Url = "http://postman-echo.com/post",
//ClientX509Certificate2ThumbprintOrSubjectName = "www.yourclientcertname.com OR yourcertificatethumbprint (only if the service you're proxying to requires it)", //ClientX509Certificate2ThumbprintOrSubjectName = "www.yourclientcertname.com OR yourcertificatethumbprint (only if the service you're proxying to requires it)",
SaveMapping = true, SaveMapping = true,
SaveMappingToFile = false, SaveMappingToFile = false,

View File

@@ -2,7 +2,6 @@
<PropertyGroup> <PropertyGroup>
<Description>Lightweight StandAlone Http Mocking Server for .Net.</Description> <Description>Lightweight StandAlone Http Mocking Server for .Net.</Description>
<AssemblyTitle>WireMock.Net.StandAlone</AssemblyTitle> <AssemblyTitle>WireMock.Net.StandAlone</AssemblyTitle>
<Version>1.0.4.18</Version>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net451;net452;net46;netstandard1.3;netstandard2.0</TargetFrameworks> <TargetFrameworks>net451;net452;net46;netstandard1.3;netstandard2.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
@@ -21,6 +20,8 @@
<IncludeSource>True</IncludeSource> <IncludeSource>True</IncludeSource>
<IncludeSymbols>True</IncludeSymbols> <IncludeSymbols>True</IncludeSymbols>
<ProjectGuid>{B6269AAC-170A-43D5-8B9A-579DED3D9A95}</ProjectGuid> <ProjectGuid>{B6269AAC-170A-43D5-8B9A-579DED3D9A95}</ProjectGuid>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">

View File

@@ -36,7 +36,7 @@ namespace WireMock.Admin.Requests
public string Url { get; set; } public string Url { get; set; }
/// <summary> /// <summary>
/// The absolete URL. /// The absolute URL.
/// </summary> /// </summary>
public string AbsoluteUrl { get; set; } public string AbsoluteUrl { get; set; }
@@ -56,7 +56,7 @@ namespace WireMock.Admin.Requests
public IDictionary<string, WireMockList<string>> Headers { get; set; } public IDictionary<string, WireMockList<string>> Headers { get; set; }
/// <summary> /// <summary>
/// Tthe Cookies. /// The Cookies.
/// </summary> /// </summary>
public IDictionary<string, string> Cookies { get; set; } public IDictionary<string, string> Cookies { get; set; }
@@ -79,5 +79,25 @@ namespace WireMock.Admin.Requests
/// The body encoding. /// The body encoding.
/// </summary> /// </summary>
public EncodingModel BodyEncoding { get; set; } public EncodingModel BodyEncoding { get; set; }
/// <summary>
/// The DetectedBodyType, valid values are:
///
/// - None
/// - String
/// - Json
/// - Bytes
/// </summary>
public string DetectedBodyType { get; set; }
/// <summary>
/// The DetectedBodyTypeFromContentType, valid values are:
///
/// - None
/// - String
/// - Json
/// - Bytes
/// </summary>
public string DetectedBodyTypeFromContentType { get; set; }
} }
} }

View File

@@ -58,5 +58,15 @@ namespace WireMock.Admin.Requests
/// Gets or sets the body. /// Gets or sets the body.
/// </summary> /// </summary>
public EncodingModel BodyEncoding { get; set; } public EncodingModel BodyEncoding { get; set; }
/// <summary>
/// The detected body type (detection based on body content).
/// </summary>
public BodyType DetectedBodyType { get; set; }
/// <summary>
/// The detected body type (detection based on Content-Type).
/// </summary>
public BodyType DetectedBodyTypeFromContentType { get; set; }
} }
} }

View File

@@ -2,16 +2,21 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Text; using JetBrains.Annotations;
using MimeKit; using MimeKit;
using Newtonsoft.Json; using Newtonsoft.Json;
using WireMock.Util;
using WireMock.Validation;
namespace WireMock.Http namespace WireMock.Http
{ {
internal static class HttpRequestMessageHelper internal static class HttpRequestMessageHelper
{ {
public static HttpRequestMessage Create(RequestMessage requestMessage, string url) internal static HttpRequestMessage Create([NotNull] RequestMessage requestMessage, [NotNull] string url)
{ {
Check.NotNull(requestMessage, nameof(requestMessage));
Check.NotNullOrEmpty(url, nameof(url));
var httpRequestMessage = new HttpRequestMessage(new HttpMethod(requestMessage.Method), url); var httpRequestMessage = new HttpRequestMessage(new HttpMethod(requestMessage.Method), url);
ContentType contentType = null; ContentType contentType = null;
@@ -21,40 +26,25 @@ namespace WireMock.Http
ContentType.TryParse(value, out contentType); ContentType.TryParse(value, out contentType);
} }
// Set Body if present switch (requestMessage.BodyData?.DetectedBodyType)
if (requestMessage.BodyAsBytes != null)
{ {
httpRequestMessage.Content = new ByteArrayContent(requestMessage.BodyAsBytes); case BodyType.Bytes:
} httpRequestMessage.Content = new ByteArrayContent(requestMessage.BodyData.BodyAsBytes);
else if (requestMessage.BodyAsJson != null) break;
{
if (contentType != null) case BodyType.Json:
{ httpRequestMessage.Content = StringContentHelper.Create(JsonConvert.SerializeObject(requestMessage.BodyData.BodyAsJson), contentType);
var encoding = requestMessage.BodyEncoding ?? Encoding.GetEncoding(contentType.Charset ?? "UTF-8"); break;
httpRequestMessage.Content = new StringContent(JsonConvert.SerializeObject(requestMessage.BodyAsJson), encoding, contentType.MimeType);
} case BodyType.String:
else httpRequestMessage.Content = StringContentHelper.Create(requestMessage.BodyData.BodyAsString, contentType);
{ break;
httpRequestMessage.Content = new StringContent(JsonConvert.SerializeObject(requestMessage.BodyAsJson), requestMessage.BodyEncoding);
}
}
else if (requestMessage.Body != null)
{
if (contentType != null)
{
var encoding = requestMessage.BodyEncoding ?? Encoding.GetEncoding(contentType.Charset ?? "UTF-8");
httpRequestMessage.Content = new StringContent(requestMessage.Body, encoding, contentType.MimeType);
}
else
{
httpRequestMessage.Content = new StringContent(requestMessage.Body, requestMessage.BodyEncoding);
}
} }
// Overwrite the host header // Overwrite the host header
httpRequestMessage.Headers.Host = new Uri(url).Authority; httpRequestMessage.Headers.Host = new Uri(url).Authority;
// Set other headers if present and if not excluded // Set other headers if present
if (requestMessage.Headers == null || requestMessage.Headers.Count == 0) if (requestMessage.Headers == null || requestMessage.Headers.Count == 0)
{ {
return httpRequestMessage; return httpRequestMessage;
@@ -63,6 +53,7 @@ namespace WireMock.Http
var excludeHeaders = new List<string> { HttpKnownHeaderNames.Host, HttpKnownHeaderNames.ContentLength }; var excludeHeaders = new List<string> { HttpKnownHeaderNames.Host, HttpKnownHeaderNames.ContentLength };
if (contentType != null) if (contentType != null)
{ {
// Content-Type should be set on the content
excludeHeaders.Add(HttpKnownHeaderNames.ContentType); excludeHeaders.Add(HttpKnownHeaderNames.ContentType);
} }

View File

@@ -24,10 +24,7 @@ namespace WireMock.Http
contentTypeHeader = headers.First(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase)).Value; contentTypeHeader = headers.First(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase)).Value;
} }
var body = await BodyParser.Parse(stream, contentTypeHeader?.FirstOrDefault()); responseMessage.BodyData = await BodyParser.Parse(stream, contentTypeHeader?.FirstOrDefault());
responseMessage.Body = body.BodyAsString;
responseMessage.BodyAsJson = body.BodyAsJson;
responseMessage.BodyAsBytes = body.BodyAsBytes;
} }
foreach (var header in headers) foreach (var header in headers)

View File

@@ -0,0 +1,38 @@
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using JetBrains.Annotations;
using MimeKit;
using WireMock.Validation;
namespace WireMock.Http
{
internal static class StringContentHelper
{
/// <summary>
/// Creates a StringContent object. Note that the Encoding is only set when it's also set on the original header.
/// </summary>
/// <param name="content">The string content (cannot be null)</param>
/// <param name="contentType">The ContentType (can be null)</param>
/// <returns>StringContent</returns>
internal static StringContent Create([NotNull] string content, [CanBeNull] ContentType contentType)
{
Check.NotNull(content, nameof(content));
if (contentType == null)
{
return new StringContent(content);
}
if (contentType.Charset == null)
{
var stringContent = new StringContent(content);
stringContent.Headers.ContentType = new MediaTypeHeaderValue(contentType.MimeType);
return stringContent;
}
var encoding = Encoding.GetEncoding(contentType.Charset);
return new StringContent(content, encoding, contentType.MimeType);
}
}
}

View File

@@ -24,15 +24,12 @@ namespace WireMock
public int Priority { get; } public int Priority { get; }
/// <inheritdoc cref="IMapping.Scenario" /> /// <inheritdoc cref="IMapping.Scenario" />
[CanBeNull]
public string Scenario { get; } public string Scenario { get; }
/// <inheritdoc cref="IMapping.ExecutionConditionState" /> /// <inheritdoc cref="IMapping.ExecutionConditionState" />
[CanBeNull]
public string ExecutionConditionState { get; } public string ExecutionConditionState { get; }
/// <inheritdoc cref="IMapping.NextState" /> /// <inheritdoc cref="IMapping.NextState" />
[CanBeNull]
public string NextState { get; } public string NextState { get; }
/// <inheritdoc cref="IMapping.RequestMatcher" /> /// <inheritdoc cref="IMapping.RequestMatcher" />
@@ -79,7 +76,7 @@ namespace WireMock
} }
/// <inheritdoc cref="IMapping.GetRequestMatchResult" /> /// <inheritdoc cref="IMapping.GetRequestMatchResult" />
public RequestMatchResult GetRequestMatchResult(RequestMessage requestMessage, [CanBeNull] string nextState) public RequestMatchResult GetRequestMatchResult(RequestMessage requestMessage, string nextState)
{ {
var result = new RequestMatchResult(); var result = new RequestMatchResult();

View File

@@ -7,7 +7,7 @@
public interface IValueMatcher: IObjectMatcher public interface IValueMatcher: IObjectMatcher
{ {
/// <summary> /// <summary>
/// Gets the value (can be a string or an obejct). /// Gets the value (can be a string or an object).
/// </summary> /// </summary>
/// <returns>Value</returns> /// <returns>Value</returns>
object Value { get; } object Value { get; }

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
namespace WireMock.Matchers namespace WireMock.Matchers
@@ -11,7 +12,7 @@ namespace WireMock.Matchers
/// <summary> /// <summary>
/// The tolerance /// The tolerance
/// </summary> /// </summary>
public const double Tolerance = 0.0001; public const double Tolerance = 0.000001;
/// <summary> /// <summary>
/// The default mismatch score /// The default mismatch score
@@ -28,6 +29,16 @@ namespace WireMock.Matchers
/// </summary> /// </summary>
public const double AlmostPerfect = 0.99; public const double AlmostPerfect = 0.99;
/// <summary>
/// Is the value a perfect match?
/// </summary>
/// <param name="value">The value.</param>
/// <returns>true/false</returns>
public static bool IsPerfect(double value)
{
return Math.Abs(value - Perfect) < Tolerance;
}
/// <summary> /// <summary>
/// Convert a bool to the score. /// Convert a bool to the score.
/// </summary> /// </summary>
@@ -39,7 +50,7 @@ namespace WireMock.Matchers
} }
/// <summary> /// <summary>
/// Calculates the score from multiple funcs. /// Calculates the score from multiple values.
/// </summary> /// </summary>
/// <param name="values">The values.</param> /// <param name="values">The values.</param>
/// <returns>average score</returns> /// <returns>average score</returns>
@@ -49,7 +60,7 @@ namespace WireMock.Matchers
} }
/// <summary> /// <summary>
/// Calculates the score from multiple funcs. /// Calculates the score from multiple values.
/// </summary> /// </summary>
/// <param name="values">The values.</param> /// <param name="values">The values.</param>
/// <returns>average score</returns> /// <returns>average score</returns>

View File

@@ -1,5 +1,6 @@
using System; using System;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Util;
using WireMock.Validation; using WireMock.Validation;
namespace WireMock.Matchers.Request namespace WireMock.Matchers.Request
@@ -93,6 +94,7 @@ namespace WireMock.Matchers.Request
public RequestMessageBodyMatcher([NotNull] IMatcher matcher) public RequestMessageBodyMatcher([NotNull] IMatcher matcher)
{ {
Check.NotNull(matcher, nameof(matcher)); Check.NotNull(matcher, nameof(matcher));
Matcher = matcher; Matcher = matcher;
} }
@@ -109,47 +111,41 @@ namespace WireMock.Matchers.Request
if (Matcher is IObjectMatcher objectMatcher) if (Matcher is IObjectMatcher objectMatcher)
{ {
// If the body is a JSON object, try to match. // If the body is a JSON object, try to match.
if (requestMessage.BodyAsJson != null) if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json)
{ {
return objectMatcher.IsMatch(requestMessage.BodyAsJson); return objectMatcher.IsMatch(requestMessage.BodyData.BodyAsJson);
} }
// If the body is a byte array, try to match. // If the body is a byte array, try to match.
if (requestMessage.BodyAsBytes != null) if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Bytes)
{ {
return objectMatcher.IsMatch(requestMessage.BodyAsBytes); return objectMatcher.IsMatch(requestMessage.BodyData.BodyAsBytes);
} }
} }
// Check if the matcher is a IStringMatcher // Check if the matcher is a IStringMatcher
if (Matcher is IStringMatcher stringMatcher) if (Matcher is IStringMatcher stringMatcher)
{ {
// If the body is a JSON object, try to use Body (string) to match. // If the body is a Json or a String, use the BodyAsString to match on.
if (requestMessage.BodyAsJson != null && requestMessage.Body != null) if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json || requestMessage?.BodyData?.DetectedBodyType == BodyType.String)
{ {
return stringMatcher.IsMatch(requestMessage.Body); return stringMatcher.IsMatch(requestMessage.BodyData.BodyAsString);
}
// If the string body is defined, try to match.
if (requestMessage.Body != null)
{
return stringMatcher.IsMatch(requestMessage.Body);
} }
} }
if (Func != null) if (Func != null)
{ {
return MatchScores.ToScore(requestMessage.Body != null && Func(requestMessage.Body)); return MatchScores.ToScore(requestMessage?.BodyData?.DetectedBodyType == BodyType.String && Func(requestMessage.BodyData.BodyAsString));
}
if (DataFunc != null)
{
return MatchScores.ToScore(requestMessage.BodyAsBytes != null && DataFunc(requestMessage.BodyAsBytes));
} }
if (JsonFunc != null) if (JsonFunc != null)
{ {
return MatchScores.ToScore(requestMessage.BodyAsJson != null && JsonFunc(requestMessage.BodyAsJson)); return MatchScores.ToScore(requestMessage?.BodyData?.DetectedBodyType == BodyType.Json && JsonFunc(requestMessage.BodyData.BodyAsJson));
}
if (DataFunc != null)
{
return MatchScores.ToScore(requestMessage?.BodyData?.DetectedBodyType == BodyType.Bytes && DataFunc(requestMessage.BodyData.BodyAsBytes));
} }
return MatchScores.Mismatch; return MatchScores.Mismatch;

View File

@@ -47,7 +47,7 @@ namespace WireMock.Owin.Mappers
} }
BodyData body = null; BodyData body = null;
if (request.Body != null && ShouldParseBody(method)) if (request.Body != null && BodyParser.ShouldParseBody(method))
{ {
body = await BodyParser.Parse(request.Body, request.ContentType); body = await BodyParser.Parse(request.Body, request.ContentType);
} }
@@ -69,21 +69,5 @@ namespace WireMock.Owin.Mappers
#endif #endif
return (urldetails, clientIP); return (urldetails, clientIP);
} }
private bool ShouldParseBody(string method)
{
/*
HEAD - No defined body semantics.
GET - No defined body semantics.
PUT - Body supported.
POST - Body supported.
DELETE - No defined body semantics.
TRACE - Body not supported.
OPTIONS - Body supported but no semantics on usage (maybe in the future).
CONNECT - No defined body semantics
PATCH - Body supported.
*/
return new[] { "PUT", "POST", "OPTIONS", "PATCH" }.Contains(method.ToUpper());
}
} }
} }

View File

@@ -45,23 +45,25 @@ namespace WireMock.Owin.Mappers
response.StatusCode = responseMessage.StatusCode; response.StatusCode = responseMessage.StatusCode;
byte[] bytes = null; byte[] bytes = null;
if (responseMessage.BodyAsBytes != null) switch (responseMessage.BodyData?.DetectedBodyType)
{ {
bytes = responseMessage.BodyAsBytes; case BodyType.String:
} bytes = (responseMessage.BodyData.Encoding ?? _utf8NoBom).GetBytes(responseMessage.BodyData.BodyAsString);
else if (responseMessage.BodyAsFile != null) break;
{
bytes = File.ReadAllBytes(responseMessage.BodyAsFile); case BodyType.Json:
} Formatting formatting = responseMessage.BodyData.BodyAsJsonIndented == true ? Formatting.Indented : Formatting.None;
else if (responseMessage.BodyAsJson != null) string jsonBody = JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson, new JsonSerializerSettings { Formatting = formatting, NullValueHandling = NullValueHandling.Ignore });
{ bytes = (responseMessage.BodyData.Encoding ?? _utf8NoBom).GetBytes(jsonBody);
Formatting formatting = responseMessage.BodyAsJsonIndented == true ? Formatting.Indented : Formatting.None; break;
string jsonBody = JsonConvert.SerializeObject(responseMessage.BodyAsJson, new JsonSerializerSettings { Formatting = formatting, NullValueHandling = NullValueHandling.Ignore });
bytes = (responseMessage.BodyEncoding ?? _utf8NoBom).GetBytes(jsonBody); case BodyType.Bytes:
} bytes = responseMessage.BodyData.BodyAsBytes;
else if (responseMessage.Body != null) break;
{
bytes = (responseMessage.BodyEncoding ?? _utf8NoBom).GetBytes(responseMessage.Body); case BodyType.File:
bytes = File.ReadAllBytes(responseMessage.BodyData.BodyAsFile);
break;
} }
SetResponseHeaders(responseMessage, response); SetResponseHeaders(responseMessage, response);

View File

@@ -94,7 +94,7 @@ namespace WireMock.Owin
IsStarted = true; IsStarted = true;
// WaitHandle is signaled when the token is cancelled, // WaitHandle is signaled when the token is cancelled,
// which will be more efficent than Thread.Sleep in while loop // which will be more efficient than Thread.Sleep in while loop
_cts.Token.WaitHandle.WaitOne(); _cts.Token.WaitHandle.WaitOne();
} }
catch (Exception e) catch (Exception e)

View File

@@ -26,7 +26,7 @@ namespace WireMock.Owin
public ConcurrentDictionary<string, ScenarioState> Scenarios { get; } = new ConcurrentDictionary<string, ScenarioState>(); public ConcurrentDictionary<string, ScenarioState> Scenarios { get; } = new ConcurrentDictionary<string, ScenarioState>();
public ObservableCollection<LogEntry> LogEntries { get; } = new ConcurentObservableCollection<LogEntry>(); public ObservableCollection<LogEntry> LogEntries { get; } = new ConcurrentObservableCollection<LogEntry>();
public int? RequestLogExpirationDuration { get; set; } public int? RequestLogExpirationDuration { get; set; }

View File

@@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using System.Net; using System.Net;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Models; using WireMock.Models;
@@ -81,19 +80,34 @@ namespace WireMock
public string RawQuery { get; } public string RawQuery { get; }
/// <summary> /// <summary>
/// The original body as string, this is defined when Body or BodyAsJson are not null. /// The body.
/// </summary>
public BodyData BodyData { get; }
/// <summary>
/// The original body as string. Convenience getter for Handlebars.
/// </summary> /// </summary>
public string Body { get; } public string Body { get; }
/// <summary> /// <summary>
/// The body (as JSON object). /// The body (as JSON object). Convenience getter for Handlebars.
/// </summary> /// </summary>
public object BodyAsJson { get; set; } public object BodyAsJson { get; }
/// <summary> /// <summary>
/// The body (as bytearray). /// The body (as bytearray). Convenience getter for Handlebars.
/// </summary> /// </summary>
public byte[] BodyAsBytes { get; set; } public byte[] BodyAsBytes { get; }
/// <summary>
/// The detected body type. Convenience getter for Handlebars.
/// </summary>
public string DetectedBodyType { get; }
/// <summary>
/// The detected body type from the Content-Type header. Convenience getter for Handlebars.
/// </summary>
public string DetectedBodyTypeFromContentType { get; }
/// <summary> /// <summary>
/// Gets the Host /// Gets the Host
@@ -115,21 +129,16 @@ namespace WireMock
/// </summary> /// </summary>
public string Origin { get; } public string Origin { get; }
/// <summary>
/// The body encoding.
/// </summary>
public Encoding BodyEncoding { get; }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="RequestMessage"/> class. /// Initializes a new instance of the <see cref="RequestMessage"/> class.
/// </summary> /// </summary>
/// <param name="urlDetails">The original url details.</param> /// <param name="urlDetails">The original url details.</param>
/// <param name="method">The HTTP method.</param> /// <param name="method">The HTTP method.</param>
/// <param name="clientIP">The client IP Address.</param> /// <param name="clientIP">The client IP Address.</param>
/// <param name="body">The body.</param> /// <param name="bodyData">The BodyData.</param>
/// <param name="headers">The headers.</param> /// <param name="headers">The headers.</param>
/// <param name="cookies">The cookies.</param> /// <param name="cookies">The cookies.</param>
public RequestMessage([NotNull] UrlDetails urlDetails, [NotNull] string method, [NotNull] string clientIP, [CanBeNull] BodyData body = null, [CanBeNull] IDictionary<string, string[]> headers = null, [CanBeNull] IDictionary<string, string> cookies = null) public RequestMessage([NotNull] UrlDetails urlDetails, [NotNull] string method, [NotNull] string clientIP, [CanBeNull] BodyData bodyData = null, [CanBeNull] IDictionary<string, string[]> headers = null, [CanBeNull] IDictionary<string, string> cookies = null)
{ {
Check.NotNull(urlDetails, nameof(urlDetails)); Check.NotNull(urlDetails, nameof(urlDetails));
Check.NotNull(method, nameof(method)); Check.NotNull(method, nameof(method));
@@ -150,10 +159,14 @@ namespace WireMock
Method = method; Method = method;
ClientIP = clientIP; ClientIP = clientIP;
Body = body?.BodyAsString; BodyData = bodyData;
BodyEncoding = body?.Encoding;
BodyAsJson = body?.BodyAsJson; // Convenience getters for e.g. Handlebars
BodyAsBytes = body?.BodyAsBytes; Body = BodyData?.BodyAsString;
BodyAsJson = BodyData?.BodyAsJson;
BodyAsBytes = BodyData?.BodyAsBytes;
DetectedBodyType = BodyData?.DetectedBodyType.ToString();
DetectedBodyTypeFromContentType = BodyData?.DetectedBodyTypeFromContentType.ToString();
Headers = headers?.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value)); Headers = headers?.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value));
Cookies = cookies; Cookies = cookies;

View File

@@ -56,17 +56,17 @@ namespace WireMock.ResponseBuilders
/// <summary> /// <summary>
/// WithBody : Create a string response based on a Base64 string (which will be decoded to a normal string). /// WithBody : Create a string response based on a Base64 string (which will be decoded to a normal string).
/// </summary> /// </summary>
/// <param name="bodyAsbase64">The body.</param> /// <param name="bodyAsBase64">The body.</param>
/// <param name="encoding">The Encoding.</param> /// <param name="encoding">The Encoding.</param>
/// <returns>A <see cref="IResponseBuilder"/>.</returns> /// <returns>A <see cref="IResponseBuilder"/>.</returns>
[Obsolete("Should not be used, will be removed in future.")] [Obsolete("Should not be used, will be removed in future.")]
IResponseBuilder WithBodyFromBase64([NotNull] string bodyAsbase64, [CanBeNull] Encoding encoding = null); IResponseBuilder WithBodyFromBase64([NotNull] string bodyAsBase64, [CanBeNull] Encoding encoding = null);
/// <summary> /// <summary>
/// WithBodyFromFile : Create a ... response based on a File. /// WithBodyFromFile : Create a ... response based on a File.
/// </summary> /// </summary>
/// <param name="filename">The filename.</param> /// <param name="filename">The filename.</param>
/// <param name="cache">Defines if this file is cached in memory or retrieved from disk everytime the response is created.</param> /// <param name="cache">Defines if this file is cached in memory or retrieved from disk every time the response is created.</param>
/// <returns>A <see cref="IResponseBuilder"/>.</returns> /// <returns>A <see cref="IResponseBuilder"/>.</returns>
IResponseBuilder WithBodyFromFile([NotNull] string filename, bool cache = true); IResponseBuilder WithBodyFromFile([NotNull] string filename, bool cache = true);
} }

View File

@@ -178,9 +178,12 @@ namespace WireMock.ResponseBuilders
return WithCallbackInternal(false, req => new ResponseMessage return WithCallbackInternal(false, req => new ResponseMessage
{ {
Body = bodyFactory(req), BodyData = new BodyData
BodyDestination = destination, {
BodyEncoding = encoding ?? Encoding.UTF8 DetectedBodyType = BodyType.String,
BodyAsString = bodyFactory(req),
Encoding = encoding ?? Encoding.UTF8
}
}); });
} }
@@ -190,19 +193,20 @@ namespace WireMock.ResponseBuilders
Check.NotNull(body, nameof(body)); Check.NotNull(body, nameof(body));
ResponseMessage.BodyDestination = destination; ResponseMessage.BodyDestination = destination;
ResponseMessage.BodyData = new BodyData();
switch (destination) switch (destination)
{ {
case BodyDestinationFormat.String: case BodyDestinationFormat.String:
var enc = encoding ?? Encoding.UTF8; var enc = encoding ?? Encoding.UTF8;
ResponseMessage.BodyAsBytes = null; ResponseMessage.BodyData.DetectedBodyType = BodyType.String;
ResponseMessage.Body = enc.GetString(body); ResponseMessage.BodyData.BodyAsString = enc.GetString(body);
ResponseMessage.BodyEncoding = enc; ResponseMessage.BodyData.Encoding = enc;
break; break;
default: default:
ResponseMessage.BodyAsBytes = body; ResponseMessage.BodyData.DetectedBodyType = BodyType.Bytes;
ResponseMessage.BodyEncoding = null; ResponseMessage.BodyData.BodyAsBytes = body;
break; break;
} }
@@ -214,20 +218,20 @@ namespace WireMock.ResponseBuilders
{ {
Check.NotNull(filename, nameof(filename)); Check.NotNull(filename, nameof(filename));
ResponseMessage.BodyEncoding = null; ResponseMessage.BodyData = new BodyData
ResponseMessage.BodyAsFileIsCached = cache; {
BodyAsFileIsCached = cache
};
if (cache) if (cache)
{ {
ResponseMessage.Body = null; ResponseMessage.BodyData.DetectedBodyType = BodyType.Bytes;
ResponseMessage.BodyAsBytes = File.ReadAllBytes(filename); ResponseMessage.BodyData.BodyAsBytes = File.ReadAllBytes(filename);
ResponseMessage.BodyAsFile = null;
} }
else else
{ {
ResponseMessage.Body = null; ResponseMessage.BodyData.DetectedBodyType = BodyType.File;
ResponseMessage.BodyAsBytes = null; ResponseMessage.BodyData.BodyAsFile = filename;
ResponseMessage.BodyAsFile = filename;
} }
return this; return this;
@@ -241,26 +245,27 @@ namespace WireMock.ResponseBuilders
encoding = encoding ?? Encoding.UTF8; encoding = encoding ?? Encoding.UTF8;
ResponseMessage.BodyDestination = destination; ResponseMessage.BodyDestination = destination;
ResponseMessage.BodyEncoding = encoding;
ResponseMessage.BodyData = new BodyData
{
Encoding = encoding
};
switch (destination) switch (destination)
{ {
case BodyDestinationFormat.Bytes: case BodyDestinationFormat.Bytes:
ResponseMessage.Body = null; ResponseMessage.BodyData.DetectedBodyType = BodyType.Bytes;
ResponseMessage.BodyAsJson = null; ResponseMessage.BodyData.BodyAsBytes= encoding.GetBytes(body);
ResponseMessage.BodyAsBytes = encoding.GetBytes(body);
break; break;
case BodyDestinationFormat.Json: case BodyDestinationFormat.Json:
ResponseMessage.Body = null; ResponseMessage.BodyData.DetectedBodyType = BodyType.Json;
ResponseMessage.BodyAsJson = JsonConvert.DeserializeObject(body); ResponseMessage.BodyData.BodyAsJson = JsonConvert.DeserializeObject(body);
ResponseMessage.BodyAsBytes = null;
break; break;
default: default:
ResponseMessage.Body = body; ResponseMessage.BodyData.DetectedBodyType = BodyType.String;
ResponseMessage.BodyAsJson = null; ResponseMessage.BodyData.BodyAsString = body;
ResponseMessage.BodyAsBytes = null;
break; break;
} }
@@ -273,10 +278,14 @@ namespace WireMock.ResponseBuilders
Check.NotNull(body, nameof(body)); Check.NotNull(body, nameof(body));
ResponseMessage.BodyDestination = null; ResponseMessage.BodyDestination = null;
ResponseMessage.BodyAsJson = body; ResponseMessage.BodyData = new BodyData
ResponseMessage.BodyEncoding = encoding; {
ResponseMessage.BodyAsJsonIndented = indented; Encoding = encoding,
DetectedBodyType = BodyType.Json,
BodyAsJson = body,
BodyAsJsonIndented = indented
};
return this; return this;
} }
@@ -287,15 +296,18 @@ namespace WireMock.ResponseBuilders
} }
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromBase64"/> /// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromBase64"/>
public IResponseBuilder WithBodyFromBase64(string bodyAsbase64, Encoding encoding = null) public IResponseBuilder WithBodyFromBase64(string bodyAsBase64, Encoding encoding = null)
{ {
Check.NotNull(bodyAsbase64, nameof(bodyAsbase64)); Check.NotNull(bodyAsBase64, nameof(bodyAsBase64));
encoding = encoding ?? Encoding.UTF8; encoding = encoding ?? Encoding.UTF8;
ResponseMessage.BodyDestination = null; ResponseMessage.BodyData = new BodyData
ResponseMessage.Body = encoding.GetString(Convert.FromBase64String(bodyAsbase64)); {
ResponseMessage.BodyEncoding = encoding; Encoding = encoding,
DetectedBodyType = BodyType.String,
BodyAsString = encoding.GetString(Convert.FromBase64String(bodyAsBase64))
};
return this; return this;
} }

View File

@@ -1,6 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using WireMock.Util; using WireMock.Util;
using WireMock.Validation; using WireMock.Validation;
@@ -32,39 +31,9 @@ namespace WireMock
public string BodyDestination { get; set; } public string BodyDestination { get; set; }
/// <summary> /// <summary>
/// Gets or sets the body as a string. /// The Body.
/// </summary> /// </summary>
public string Body { get; set; } public BodyData BodyData { get; set; }
/// <summary>
/// Gets or sets the body as a json object.
/// </summary>
public object BodyAsJson { get; set; }
/// <summary>
/// Gets or sets a value indicating whether child objects to be indented according to the Newtonsoft.Json.JsonTextWriter.Indentation and Newtonsoft.Json.JsonTextWriter.IndentChar settings.
/// </summary>
public bool? BodyAsJsonIndented { get; set; }
/// <summary>
/// Gets or sets the body as bytes.
/// </summary>
public byte[] BodyAsBytes { get; set; }
/// <summary>
/// Gets or sets the body as a file.
/// </summary>
public string BodyAsFile { get; set; }
/// <summary>
/// Is the body as file cached?
/// </summary>
public bool? BodyAsFileIsCached { get; set; }
/// <summary>
/// Gets or sets the body encoding.
/// </summary>
public Encoding BodyEncoding { get; set; } = new UTF8Encoding(false);
/// <summary> /// <summary>
/// Adds the header. /// Adds the header.

View File

@@ -16,10 +16,18 @@ namespace WireMock
var response = new ResponseMessage var response = new ResponseMessage
{ {
StatusCode = statusCode, StatusCode = statusCode,
Headers = ContentTypeJsonHeaders, Headers = ContentTypeJsonHeaders
BodyAsJson = message != null ? new StatusModel { Status = message, Guid = guid } : null
}; };
if (message != null)
{
response.BodyData = new BodyData
{
DetectedBodyType = BodyType.Json,
BodyAsJson = new StatusModel { Status = message, Guid = guid }
};
}
return response; return response;
} }
} }

View File

@@ -2,6 +2,7 @@
using WireMock.Admin.Mappings; using WireMock.Admin.Mappings;
using WireMock.Admin.Requests; using WireMock.Admin.Requests;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Util;
namespace WireMock.Serialization namespace WireMock.Serialization
{ {
@@ -9,51 +10,102 @@ namespace WireMock.Serialization
{ {
public static LogEntryModel Map(LogEntry logEntry) public static LogEntryModel Map(LogEntry logEntry)
{ {
var logRequestModel = new LogRequestModel
{
DateTime = logEntry.RequestMessage.DateTime,
ClientIP = logEntry.RequestMessage.ClientIP,
Path = logEntry.RequestMessage.Path,
AbsolutePath = logEntry.RequestMessage.AbsolutePath,
Url = logEntry.RequestMessage.Url,
AbsoluteUrl = logEntry.RequestMessage.AbsoluteUrl,
Query = logEntry.RequestMessage.Query,
Method = logEntry.RequestMessage.Method,
Headers = logEntry.RequestMessage.Headers,
Cookies = logEntry.RequestMessage.Cookies
};
if (logEntry.RequestMessage.BodyData != null)
{
logRequestModel.DetectedBodyType = logEntry.RequestMessage.BodyData.DetectedBodyType.ToString();
logRequestModel.DetectedBodyTypeFromContentType = logEntry.RequestMessage.BodyData.DetectedBodyTypeFromContentType.ToString();
switch (logEntry.RequestMessage.BodyData.DetectedBodyType)
{
case BodyType.String:
logRequestModel.Body = logEntry.RequestMessage.BodyData.BodyAsString;
break;
case BodyType.Json:
logRequestModel.Body = logEntry.RequestMessage.BodyData.BodyAsString; // In case of Json, do also save the Body as string (backwards compatible)
logRequestModel.BodyAsJson = logEntry.RequestMessage.BodyData.BodyAsJson;
break;
case BodyType.Bytes:
logRequestModel.BodyAsBytes = logEntry.RequestMessage.BodyData.BodyAsBytes;
break;
}
logRequestModel.BodyEncoding = logEntry.RequestMessage.BodyData.Encoding != null
? new EncodingModel
{
EncodingName = logEntry.RequestMessage.BodyData.Encoding.EncodingName,
CodePage = logEntry.RequestMessage.BodyData.Encoding.CodePage,
WebName = logEntry.RequestMessage.BodyData.Encoding.WebName
}
: null;
}
var logResponseModel = new LogResponseModel
{
StatusCode = logEntry.ResponseMessage.StatusCode,
Headers = logEntry.ResponseMessage.Headers
};
if (logEntry.ResponseMessage.BodyData != null)
{
logResponseModel.BodyOriginal = logEntry.ResponseMessage.BodyOriginal;
logResponseModel.BodyDestination = logEntry.ResponseMessage.BodyDestination;
logResponseModel.DetectedBodyType = logEntry.ResponseMessage.BodyData.DetectedBodyType;
logResponseModel.DetectedBodyTypeFromContentType = logEntry.ResponseMessage.BodyData.DetectedBodyTypeFromContentType;
switch (logEntry.ResponseMessage.BodyData.DetectedBodyType)
{
case BodyType.String:
logResponseModel.Body = logEntry.ResponseMessage.BodyData.BodyAsString;
break;
case BodyType.Json:
logResponseModel.BodyAsJson = logEntry.ResponseMessage.BodyData.BodyAsJson;
break;
case BodyType.Bytes:
logResponseModel.BodyAsBytes = logEntry.ResponseMessage.BodyData.BodyAsBytes;
break;
case BodyType.File:
logResponseModel.BodyAsFile = logEntry.ResponseMessage.BodyData.BodyAsFile;
logResponseModel.BodyAsFileIsCached = logEntry.ResponseMessage.BodyData.BodyAsFileIsCached;
break;
}
logResponseModel.BodyEncoding = logEntry.ResponseMessage.BodyData.Encoding != null
? new EncodingModel
{
EncodingName = logEntry.ResponseMessage.BodyData.Encoding.EncodingName,
CodePage = logEntry.ResponseMessage.BodyData.Encoding.CodePage,
WebName = logEntry.ResponseMessage.BodyData.Encoding.WebName
}
: null;
}
return new LogEntryModel return new LogEntryModel
{ {
Guid = logEntry.Guid, Guid = logEntry.Guid,
Request = new LogRequestModel
{
DateTime = logEntry.RequestMessage.DateTime,
ClientIP = logEntry.RequestMessage.ClientIP,
Path = logEntry.RequestMessage.Path,
AbsolutePath = logEntry.RequestMessage.AbsolutePath,
Url = logEntry.RequestMessage.Url,
AbsoluteUrl = logEntry.RequestMessage.AbsoluteUrl,
Query = logEntry.RequestMessage.Query,
Method = logEntry.RequestMessage.Method,
Body = logEntry.RequestMessage.Body,
BodyAsJson = logEntry.RequestMessage.BodyAsJson,
BodyAsBytes = logEntry.RequestMessage.BodyAsBytes,
Headers = logEntry.RequestMessage.Headers,
Cookies = logEntry.RequestMessage.Cookies,
BodyEncoding = logEntry.RequestMessage.BodyEncoding != null ? new EncodingModel
{
EncodingName = logEntry.RequestMessage.BodyEncoding.EncodingName,
CodePage = logEntry.RequestMessage.BodyEncoding.CodePage,
WebName = logEntry.RequestMessage.BodyEncoding.WebName
} : null
},
Response = new LogResponseModel
{
StatusCode = logEntry.ResponseMessage.StatusCode,
BodyDestination = logEntry.ResponseMessage.BodyDestination,
Body = logEntry.ResponseMessage.Body,
BodyAsJson = logEntry.ResponseMessage.BodyAsJson,
BodyAsBytes = logEntry.ResponseMessage.BodyAsBytes,
BodyOriginal = logEntry.ResponseMessage.BodyOriginal,
BodyAsFile = logEntry.ResponseMessage.BodyAsFile,
BodyAsFileIsCached = logEntry.ResponseMessage.BodyAsFileIsCached,
Headers = logEntry.ResponseMessage.Headers,
BodyEncoding = logEntry.ResponseMessage.BodyEncoding != null ? new EncodingModel
{
EncodingName = logEntry.ResponseMessage.BodyEncoding.EncodingName,
CodePage = logEntry.ResponseMessage.BodyEncoding.CodePage,
WebName = logEntry.ResponseMessage.BodyEncoding.WebName
} : null
},
MappingGuid = logEntry.MappingGuid, MappingGuid = logEntry.MappingGuid,
MappingTitle = logEntry.MappingTitle, MappingTitle = logEntry.MappingTitle,
Request = logRequestModel,
Response = logResponseModel,
RequestMatchResult = logEntry.RequestMatchResult != null ? new LogRequestMatchModel RequestMatchResult = logEntry.RequestMatchResult != null ? new LogRequestMatchModel
{ {
TotalScore = logEntry.RequestMatchResult.TotalScore, TotalScore = logEntry.RequestMatchResult.TotalScore,

View File

@@ -100,22 +100,40 @@ namespace WireMock.Serialization
mappingModel.Response.BodyDestination = response.ResponseMessage.BodyDestination; mappingModel.Response.BodyDestination = response.ResponseMessage.BodyDestination;
mappingModel.Response.StatusCode = response.ResponseMessage.StatusCode; mappingModel.Response.StatusCode = response.ResponseMessage.StatusCode;
mappingModel.Response.Headers = Map(response.ResponseMessage.Headers); mappingModel.Response.Headers = Map(response.ResponseMessage.Headers);
mappingModel.Response.BodyAsJson = response.ResponseMessage.BodyAsJson;
mappingModel.Response.BodyAsJsonIndented = response.ResponseMessage.BodyAsJsonIndented;
mappingModel.Response.Body = response.ResponseMessage.Body;
mappingModel.Response.BodyAsBytes = response.ResponseMessage.BodyAsBytes;
mappingModel.Response.BodyAsFile = response.ResponseMessage.BodyAsFile;
mappingModel.Response.BodyAsFileIsCached = response.ResponseMessage.BodyAsFileIsCached;
mappingModel.Response.UseTransformer = response.UseTransformer; mappingModel.Response.UseTransformer = response.UseTransformer;
if (response.ResponseMessage.BodyEncoding != null && response.ResponseMessage.BodyEncoding.WebName != "utf-8") if (response.ResponseMessage.BodyData != null)
{ {
mappingModel.Response.BodyEncoding = new EncodingModel switch (response.ResponseMessage.BodyData?.DetectedBodyType)
{ {
EncodingName = response.ResponseMessage.BodyEncoding.EncodingName, case BodyType.String:
CodePage = response.ResponseMessage.BodyEncoding.CodePage, mappingModel.Response.Body = response.ResponseMessage.BodyData.BodyAsString;
WebName = response.ResponseMessage.BodyEncoding.WebName break;
};
case BodyType.Json:
mappingModel.Response.BodyAsJson = response.ResponseMessage.BodyData.BodyAsJson;
mappingModel.Response.BodyAsJsonIndented = response.ResponseMessage.BodyData.BodyAsJsonIndented;
break;
case BodyType.Bytes:
mappingModel.Response.BodyAsBytes = response.ResponseMessage.BodyData.BodyAsBytes;
break;
case BodyType.File:
mappingModel.Response.BodyAsFile = response.ResponseMessage.BodyData.BodyAsFile;
mappingModel.Response.BodyAsFileIsCached = response.ResponseMessage.BodyData.BodyAsFileIsCached;
break;
}
if (response.ResponseMessage.BodyData.Encoding != null && response.ResponseMessage.BodyData.Encoding.WebName != "utf-8")
{
mappingModel.Response.BodyEncoding = new EncodingModel
{
EncodingName = response.ResponseMessage.BodyData.Encoding.EncodingName,
CodePage = response.ResponseMessage.BodyData.Encoding.CodePage,
WebName = response.ResponseMessage.BodyData.Encoding.WebName
};
}
} }
} }

View File

@@ -274,13 +274,13 @@ namespace WireMock.Server
} }
}); });
if (requestMessage.BodyAsJson != null) if (requestMessage.BodyData?.DetectedBodyType == BodyType.Json)
{ {
request.WithBody(new JsonMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyAsJson)); request.WithBody(new JsonMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsJson));
} }
else if (requestMessage.Body != null) else if (requestMessage.BodyData?.DetectedBodyType == BodyType.String)
{ {
request.WithBody(new ExactMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.Body)); request.WithBody(new ExactMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsString));
} }
var response = Response.Create(responseMessage); var response = Response.Create(responseMessage);
@@ -764,9 +764,13 @@ namespace WireMock.Server
{ {
return new ResponseMessage return new ResponseMessage
{ {
Body = JsonConvert.SerializeObject(result, keepNullValues ? _settingsIncludeNullValues : _settings), BodyData = new BodyData
{
DetectedBodyType = BodyType.String,
BodyAsString = JsonConvert.SerializeObject(result, keepNullValues ? _settingsIncludeNullValues : _settings)
},
StatusCode = 200, StatusCode = 200,
Headers = new Dictionary<string, WireMockList<string>> { { HttpKnownHeaderNames.ContentType, new WireMockList<string>("application/json") } } Headers = new Dictionary<string, WireMockList<string>> { { HttpKnownHeaderNames.ContentType, new WireMockList<string>(ContentTypeJson) } }
}; };
} }
@@ -777,9 +781,17 @@ namespace WireMock.Server
private T DeserializeObject<T>(RequestMessage requestMessage) private T DeserializeObject<T>(RequestMessage requestMessage)
{ {
return requestMessage.Body != null ? if (requestMessage?.BodyData?.DetectedBodyType == BodyType.String)
JsonConvert.DeserializeObject<T>(requestMessage.Body) : {
((JObject)requestMessage.BodyAsJson).ToObject<T>(); return JsonConvert.DeserializeObject<T>(requestMessage.BodyData.BodyAsString);
}
if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json)
{
return ((JObject)requestMessage.BodyData.BodyAsJson).ToObject<T>();
}
return default(T);
} }
} }
} }

View File

@@ -5,7 +5,6 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using WireMock.Handlers; using WireMock.Handlers;
using WireMock.Logging; using WireMock.Logging;

View File

@@ -50,14 +50,12 @@ namespace WireMock.Transformers
string ParseAsString(object arg) string ParseAsString(object arg)
{ {
if (arg is string) if (arg is string argAsString)
{ {
return (string) arg; return argAsString;
}
else
{
throw new NotSupportedException($"The value '{arg}' with type '{arg?.GetType()}' cannot be used in Handlebars Regex.");
} }
throw new NotSupportedException($"The value '{arg}' with type '{arg?.GetType()}' cannot be used in Handlebars Regex.");
} }
return (ParseAsString(arguments[0]), ParseAsString(arguments[1]), arguments.Length == 3 ? arguments[2] : null); return (ParseAsString(arguments[0]), ParseAsString(arguments[1]), arguments.Length == 3 ? arguments[2] : null);

View File

@@ -17,12 +17,12 @@ namespace WireMock.Transformers
public static ResponseMessage Transform(RequestMessage requestMessage, ResponseMessage original) public static ResponseMessage Transform(RequestMessage requestMessage, ResponseMessage original)
{ {
bool bodyIsJson = original.BodyAsJson != null; bool bodyIsJson = original.BodyData.DetectedBodyType == BodyType.Json;
var responseMessage = new ResponseMessage { StatusCode = original.StatusCode }; var responseMessage = new ResponseMessage { StatusCode = original.StatusCode };
if (!bodyIsJson) if (!bodyIsJson)
{ {
responseMessage.BodyOriginal = original.Body; responseMessage.BodyOriginal = original.BodyData.BodyAsString;
} }
var template = new { request = requestMessage }; var template = new { request = requestMessage };
@@ -57,7 +57,7 @@ namespace WireMock.Transformers
private static void TransformBodyAsJson(object template, ResponseMessage original, ResponseMessage responseMessage) private static void TransformBodyAsJson(object template, ResponseMessage original, ResponseMessage responseMessage)
{ {
JToken jToken; JToken jToken;
switch (original.BodyAsJson) switch (original.BodyData.BodyAsJson)
{ {
case JObject bodyAsJObject: case JObject bodyAsJObject:
jToken = bodyAsJObject; jToken = bodyAsJObject;
@@ -68,13 +68,18 @@ namespace WireMock.Transformers
break; break;
default: default:
jToken = JObject.FromObject(original.BodyAsJson); jToken = JObject.FromObject(original.BodyData.BodyAsJson);
break; break;
} }
WalkNode(jToken, template); WalkNode(jToken, template);
responseMessage.BodyAsJson = jToken; responseMessage.BodyData = new BodyData
{
DetectedBodyType = original.BodyData.DetectedBodyType,
DetectedBodyTypeFromContentType = original.BodyData.DetectedBodyTypeFromContentType,
BodyAsJson = jToken
};
} }
private static void WalkNode(JToken node, object template) private static void WalkNode(JToken node, object template)
@@ -127,9 +132,14 @@ namespace WireMock.Transformers
private static void TransformBodyAsString(object template, ResponseMessage original, ResponseMessage responseMessage) private static void TransformBodyAsString(object template, ResponseMessage original, ResponseMessage responseMessage)
{ {
var templateBody = Handlebars.Compile(original.Body); var templateBody = Handlebars.Compile(original.BodyData.BodyAsString);
responseMessage.Body = templateBody(template); responseMessage.BodyData = new BodyData
{
DetectedBodyType = original.BodyData.DetectedBodyType,
DetectedBodyTypeFromContentType = original.BodyData.DetectedBodyTypeFromContentType,
BodyAsString = templateBody(template)
};
} }
} }
} }

View File

@@ -26,5 +26,30 @@ namespace WireMock.Util
/// The body (as bytearray). /// The body (as bytearray).
/// </summary> /// </summary>
public byte[] BodyAsBytes { get; set; } public byte[] BodyAsBytes { get; set; }
/// <summary>
/// Gets or sets a value indicating whether child objects to be indented according to the Newtonsoft.Json.JsonTextWriter.Indentation and Newtonsoft.Json.JsonTextWriter.IndentChar settings.
/// </summary>
public bool? BodyAsJsonIndented { get; set; }
/// <summary>
/// Gets or sets the body as a file.
/// </summary>
public string BodyAsFile { get; set; }
/// <summary>
/// Is the body as file cached?
/// </summary>
public bool? BodyAsFileIsCached { get; set; }
/// <summary>
/// The detected body type (detection based on body content).
/// </summary>
public BodyType DetectedBodyType { get; set; }
/// <summary>
/// The detected body type (detection based on Content-Type).
/// </summary>
public BodyType DetectedBodyTypeFromContentType { get; set; }
} }
} }

View File

@@ -4,36 +4,112 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
using MimeKit;
using Newtonsoft.Json; using Newtonsoft.Json;
using WireMock.Matchers;
using WireMock.Validation;
namespace WireMock.Util namespace WireMock.Util
{ {
internal static class BodyParser internal static class BodyParser
{ {
private static readonly string[] JsonContentTypes = private static readonly Encoding DefaultEncoding = Encoding.UTF8;
{
"application/json", /*
"application/vnd.api+json" HEAD - No defined body semantics.
GET - No defined body semantics.
PUT - Body supported.
POST - Body supported.
DELETE - No defined body semantics.
TRACE - Body not supported.
OPTIONS - Body supported but no semantics on usage (maybe in the future).
CONNECT - No defined body semantics
PATCH - Body supported.
*/
private static readonly string[] AllowedBodyParseMethods = { "PUT", "POST", "OPTIONS", "PATCH" };
private static readonly IStringMatcher[] JsonContentTypesMatchers = {
new WildcardMatcher("application/json", true),
new WildcardMatcher("application/vnd.*+json", true)
}; };
private static readonly string[] TextContentTypes = private static readonly IStringMatcher[] TextContentTypeMatchers =
{ {
"text/", new WildcardMatcher("text/*", true),
"application/javascript", "application/typescript", new RegexMatcher("^application\\/(java|type)script$", true),
"application/xml", "application/xhtml+xml", new WildcardMatcher("application/*xml", true),
"application/x-www-form-urlencoded" new WildcardMatcher("application/x-www-form-urlencoded", true)
}; };
private static async Task<Tuple<string, Encoding>> ReadStringAsync(Stream stream) public static bool ParseBodyAsIsValid([CanBeNull] string parseBodyAs)
{ {
using (var streamReader = new StreamReader(stream)) return Enum.TryParse(parseBodyAs, out BodyType _);
{
string content = await streamReader.ReadToEndAsync();
return new Tuple<string, Encoding>(content, streamReader.CurrentEncoding);
}
} }
public static bool ShouldParseBody([CanBeNull] string method)
{
return AllowedBodyParseMethods.Contains(method, StringComparer.OrdinalIgnoreCase);
}
public static BodyType DetectBodyTypeFromContentType([CanBeNull] string contentTypeValue)
{
if (string.IsNullOrEmpty(contentTypeValue) || !ContentType.TryParse(contentTypeValue, out ContentType contentType))
{
return BodyType.Bytes;
}
if (TextContentTypeMatchers.Any(matcher => MatchScores.IsPerfect(matcher.IsMatch(contentType.MimeType))))
{
return BodyType.String;
}
if (JsonContentTypesMatchers.Any(matcher => MatchScores.IsPerfect(matcher.IsMatch(contentType.MimeType))))
{
return BodyType.Json;
}
return BodyType.Bytes;
}
public static async Task<BodyData> Parse([NotNull] Stream stream, [CanBeNull] string contentType)
{
Check.NotNull(stream, nameof(stream));
var data = new BodyData
{
BodyAsBytes = await ReadBytesAsync(stream),
DetectedBodyType = BodyType.Bytes,
DetectedBodyTypeFromContentType = DetectBodyTypeFromContentType(contentType)
};
// Try to get the body as String
try
{
data.BodyAsString = DefaultEncoding.GetString(data.BodyAsBytes);
data.Encoding = DefaultEncoding;
data.DetectedBodyType = BodyType.String;
// If string is not null or empty, try to get as Json
if (!string.IsNullOrEmpty(data.BodyAsString))
{
try
{
data.BodyAsJson = JsonConvert.DeserializeObject(data.BodyAsString, new JsonSerializerSettings { Formatting = Formatting.Indented });
data.DetectedBodyType = BodyType.Json;
}
catch
{
// JsonConvert failed, just ignore.
}
}
}
catch
{
// Reading as string failed, just ignore
}
return data;
}
private static async Task<byte[]> ReadBytesAsync(Stream stream) private static async Task<byte[]> ReadBytesAsync(Stream stream)
{ {
using (var memoryStream = new MemoryStream()) using (var memoryStream = new MemoryStream())
@@ -42,47 +118,5 @@ namespace WireMock.Util
return memoryStream.ToArray(); return memoryStream.ToArray();
} }
} }
public static async Task<BodyData> Parse([NotNull] Stream stream, [CanBeNull] string contentTypeHeaderValue)
{
var data = new BodyData();
if (contentTypeHeaderValue != null && TextContentTypes.Any(text => contentTypeHeaderValue.StartsWith(text, StringComparison.OrdinalIgnoreCase)))
{
try
{
var stringData = await ReadStringAsync(stream);
data.BodyAsString = stringData.Item1;
data.Encoding = stringData.Item2;
}
catch
{
// Reading as string failed, just get the ByteArray.
data.BodyAsBytes = await ReadBytesAsync(stream);
}
}
else if (contentTypeHeaderValue != null && JsonContentTypes.Any(json => contentTypeHeaderValue.StartsWith(json, StringComparison.OrdinalIgnoreCase)))
{
var stringData = await ReadStringAsync(stream);
data.BodyAsString = stringData.Item1;
data.Encoding = stringData.Item2;
try
{
data.BodyAsJson = JsonConvert.DeserializeObject(stringData.Item1, new JsonSerializerSettings { Formatting = Formatting.Indented });
}
catch
{
// JsonConvert failed, just set the Body as string.
data.BodyAsString = stringData.Item1;
}
}
else
{
data.BodyAsBytes = await ReadBytesAsync(stream);
}
return data;
}
} }
} }

View File

@@ -0,0 +1,33 @@
namespace WireMock.Util
{
/// <summary>
/// The BodyType
/// </summary>
public enum BodyType
{
/// <summary>
/// No body present
/// </summary>
None,
/// <summary>
/// Body is a String
/// </summary>
String,
/// <summary>
/// Body is a Json object
/// </summary>
Json,
/// <summary>
/// Body is a Byte array
/// </summary>
Bytes,
/// <summary>
/// Body is a File
/// </summary>
File
}
}

View File

@@ -8,26 +8,26 @@ namespace WireMock.Util
/// </summary> /// </summary>
/// <typeparam name="T">The type of elements in the collection.</typeparam> /// <typeparam name="T">The type of elements in the collection.</typeparam>
/// <inheritdoc cref="ObservableCollection{T}" /> /// <inheritdoc cref="ObservableCollection{T}" />
public class ConcurentObservableCollection<T> : ObservableCollection<T> public class ConcurrentObservableCollection<T> : ObservableCollection<T>
{ {
private readonly object _lockObject = new object(); private readonly object _lockObject = new object();
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="T:WireMock.Util.ConcurentObservableCollection`1" /> class. /// Initializes a new instance of the <see cref="T:WireMock.Util.ConcurrentObservableCollection`1" /> class.
/// </summary> /// </summary>
public ConcurentObservableCollection() { } public ConcurrentObservableCollection() { }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ConcurentObservableCollection{T}"/> class that contains elements copied from the specified list. /// Initializes a new instance of the <see cref="ConcurrentObservableCollection{T}"/> class that contains elements copied from the specified list.
/// </summary> /// </summary>
/// <param name="list">The list from which the elements are copied.</param> /// <param name="list">The list from which the elements are copied.</param>
public ConcurentObservableCollection(List<T> list) : base(list) { } public ConcurrentObservableCollection(List<T> list) : base(list) { }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ConcurentObservableCollection{T}"/> class that contains elements copied from the specified collection. /// Initializes a new instance of the <see cref="ConcurrentObservableCollection{T}"/> class that contains elements copied from the specified collection.
/// </summary> /// </summary>
/// <param name="collection">The collection from which the elements are copied.</param> /// <param name="collection">The collection from which the elements are copied.</param>
public ConcurentObservableCollection(IEnumerable<T> collection) : base(collection) { } public ConcurrentObservableCollection(IEnumerable<T> collection) : base(collection) { }
/// <inheritdoc cref="ObservableCollection{T}.ClearItems"/> /// <inheritdoc cref="ObservableCollection{T}.ClearItems"/>
protected override void ClearItems() protected override void ClearItems()

View File

@@ -11,16 +11,16 @@ namespace WireMock.Util
private const int NumberOfRetries = 3; private const int NumberOfRetries = 3;
private const int DelayOnRetry = 500; private const int DelayOnRetry = 500;
public static string ReadAllTextWithRetryAndDelay([NotNull] IFileSystemHandler filehandler, [NotNull] string path) public static string ReadAllTextWithRetryAndDelay([NotNull] IFileSystemHandler handler, [NotNull] string path)
{ {
Check.NotNull(filehandler, nameof(filehandler)); Check.NotNull(handler, nameof(handler));
Check.NotNullOrEmpty(path, nameof(path)); Check.NotNullOrEmpty(path, nameof(path));
for (int i = 1; i <= NumberOfRetries; ++i) for (int i = 1; i <= NumberOfRetries; ++i)
{ {
try try
{ {
return filehandler.ReadMappingFile(path); return handler.ReadMappingFile(path);
} }
catch catch
{ {

View File

@@ -92,7 +92,7 @@ namespace WireMock.Util
private static void ProcessItem(JToken node, string path, string propertyName, List<string> lines) private static void ProcessItem(JToken node, string path, string propertyName, List<string> lines)
{ {
string castText = string.Empty; string castText;
switch (node.Type) switch (node.Type)
{ {
case JTokenType.Boolean: case JTokenType.Boolean:
@@ -132,8 +132,7 @@ namespace WireMock.Util
break; break;
default: default:
throw new NotSupportedException( throw new NotSupportedException($"JTokenType '{node.Type}' cannot be converted to a Dynamic Linq cast operator.");
$"JTokenType '{node.Type}' cannot be converted to a Dynamic Linq cast operator.");
} }
if (!string.IsNullOrEmpty(propertyName)) if (!string.IsNullOrEmpty(propertyName))

View File

@@ -1,6 +1,7 @@
using System; using System;
using JetBrains.Annotations; using JetBrains.Annotations;
using WireMock.Models; using WireMock.Models;
using WireMock.Validation;
#if !USE_ASPNETCORE #if !USE_ASPNETCORE
using Microsoft.Owin; using Microsoft.Owin;
#else #else
@@ -13,6 +14,8 @@ namespace WireMock.Util
{ {
public static UrlDetails Parse([NotNull] Uri uri, PathString pathBase) public static UrlDetails Parse([NotNull] Uri uri, PathString pathBase)
{ {
Check.NotNull(uri, nameof(uri));
if (!pathBase.HasValue) if (!pathBase.HasValue)
{ {
return new UrlDetails(uri, uri); return new UrlDetails(uri, uri);
@@ -26,7 +29,7 @@ namespace WireMock.Util
private static string RemoveFirst(string text, string search) private static string RemoveFirst(string text, string search)
{ {
int pos = text.IndexOf(search); int pos = text.IndexOf(search, StringComparison.Ordinal);
if (pos < 0) if (pos < 0)
{ {
return text; return text;

View File

@@ -2,7 +2,6 @@
<PropertyGroup> <PropertyGroup>
<Description>Lightweight Http Mocking Server for .Net, inspired by WireMock from the Java landscape.</Description> <Description>Lightweight Http Mocking Server for .Net, inspired by WireMock from the Java landscape.</Description>
<AssemblyTitle>WireMock.Net</AssemblyTitle> <AssemblyTitle>WireMock.Net</AssemblyTitle>
<Version>1.0.4.18</Version>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0</TargetFrameworks> <TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
@@ -21,6 +20,8 @@
<IncludeSource>True</IncludeSource> <IncludeSource>True</IncludeSource>
<IncludeSymbols>True</IncludeSymbols> <IncludeSymbols>True</IncludeSymbols>
<ProjectGuid>{D3804228-91F4-4502-9595-39584E5A01AD}</ProjectGuid> <ProjectGuid>{D3804228-91F4-4502-9595-39584E5A01AD}</ProjectGuid>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'"> <PropertyGroup Condition="'$(Configuration)' == 'Release'">
@@ -47,57 +48,66 @@
</PackageReference> </PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" /> <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="SimMetrics.Net" Version="1.0.4" /> <PackageReference Include="SimMetrics.Net" Version="1.0.4" />
<PackageReference Include="System.Net.Http" Version="4.3.3" />
<PackageReference Include="RestEase" Version="1.4.4" /> <PackageReference Include="RestEase" Version="1.4.4" />
<PackageReference Include="MimeKitLite" Version="2.0.1" /> <PackageReference Include="MimeKitLite" Version="2.0.1" />
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.8.18" /> <PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.8.18" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net451' "> <ItemGroup Condition=" '$(TargetFramework)' == 'net451' ">
<PackageReference Include="Handlebars.Net" Version="1.9.0" /> <!-- Required for WebRequestHandler -->
<PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.6" />
<PackageReference Include="XPath2" Version="1.0.5.1" />
<Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Net.Http.WebRequest" />
<PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.6" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="Handlebars.Net" Version="1.9.0" />
<PackageReference Include="XPath2" Version="1.0.5.1" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net452' "> <ItemGroup Condition=" '$(TargetFramework)' == 'net452' ">
<PackageReference Include="Handlebars.Net" Version="1.9.5" /> <!-- Required for WebRequestHandler -->
<PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.6" />
<PackageReference Include="XPath2" Version="1.0.5.1" />
<Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Net.Http.WebRequest" />
<PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.6" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="XPath2" Version="1.0.5.1" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net46' "> <ItemGroup Condition=" '$(TargetFramework)' == 'net46' ">
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.6" /> <PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.6" />
<PackageReference Include="Microsoft.Owin" Version="4.0.0" /> <PackageReference Include="Microsoft.Owin" Version="4.0.0" />
<PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="4.0.0" /> <PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="4.0.0" />
<PackageReference Include="Microsoft.Owin.Hosting" Version="4.0.0" /> <PackageReference Include="Microsoft.Owin.Hosting" Version="4.0.0" />
<PackageReference Include="System.Net.Http" Version="4.3.3" /> <PackageReference Include="System.Net.Http" Version="4.3.3" />
<PackageReference Include="XPath2" Version="1.0.5.1" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="XPath2" Version="1.0.5.1" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net461' "> <ItemGroup Condition=" '$(TargetFramework)' == 'net461' ">
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.2" /> <PackageReference Include="Microsoft.AspNetCore" Version="2.1.2" />
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="XPath2" Version="1.0.5.1" /> <PackageReference Include="XPath2" Version="1.0.5.1" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' "> <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' ">
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.7" /> <PackageReference Include="Microsoft.AspNetCore" Version="1.1.7" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Https" Version="1.1.3" /> <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Https" Version="1.1.3" />
<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" /> <PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />
<PackageReference Include="System.Xml.XPath.XmlDocument" Version="4.3.0" /> <PackageReference Include="System.Xml.XPath.XmlDocument" Version="4.3.0" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' "> <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.2" /> <PackageReference Include="Microsoft.AspNetCore" Version="2.1.2" />
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="XPath2" Version="1.0.5.1" /> <PackageReference Include="XPath2" Version="1.0.5.1" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -319,7 +319,7 @@ namespace WireMock.Net.Tests
Check.That(server.LogEntries).HasSize(1); Check.That(server.LogEntries).HasSize(1);
var requestLogged = server.LogEntries.First(); var requestLogged = server.LogEntries.First();
Check.That(requestLogged.RequestMessage.Method).IsEqualTo("GET"); Check.That(requestLogged.RequestMessage.Method).IsEqualTo("GET");
Check.That(requestLogged.RequestMessage.BodyAsBytes).IsNull(); Check.That(requestLogged.RequestMessage.BodyData).IsNull();
} }
[Fact] [Fact]

View File

@@ -4,6 +4,7 @@ using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
@@ -67,7 +68,7 @@ namespace WireMock.Net.Tests
{ {
Method = HttpMethod.Post, Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}{path}"), RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent("stringContent") Content = new StringContent("stringContent", Encoding.ASCII)
}; };
requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
requestMessage.Content.Headers.Add("bbb", "test"); requestMessage.Content.Headers.Add("bbb", "test");
@@ -75,7 +76,7 @@ namespace WireMock.Net.Tests
// then // then
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage; var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
Check.That(receivedRequest.Body).IsEqualTo("stringContent"); Check.That(receivedRequest.BodyData.BodyAsString).IsEqualTo("stringContent");
Check.That(receivedRequest.Headers).ContainsKey("Content-Type"); Check.That(receivedRequest.Headers).ContainsKey("Content-Type");
Check.That(receivedRequest.Headers["Content-Type"].First()).Contains("text/plain"); Check.That(receivedRequest.Headers["Content-Type"].First()).Contains("text/plain");
Check.That(receivedRequest.Headers).ContainsKey("bbb"); Check.That(receivedRequest.Headers).ContainsKey("bbb");
@@ -158,7 +159,7 @@ namespace WireMock.Net.Tests
// Assert // Assert
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage; var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
Check.That(receivedRequest.Body).IsEqualTo(""); Check.That(receivedRequest.BodyData.BodyAsString).IsEqualTo("");
Check.That(receivedRequest.Headers).ContainsKey("Content-Type"); Check.That(receivedRequest.Headers).ContainsKey("Content-Type");
Check.That(receivedRequest.Headers["Content-Type"].First()).Contains("text/plain"); Check.That(receivedRequest.Headers["Content-Type"].First()).Contains("text/plain");
} }

View File

@@ -1,115 +1,46 @@
using NFluent; using NFluent;
using System; using System;
using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Server; using WireMock.Server;
using WireMock.Settings;
using Xunit; using Xunit;
using Xunit.Abstractions;
namespace WireMock.Net.Tests namespace WireMock.Net.Tests
{ {
public class FluentMockServerProxy2Tests : IDisposable public class FluentMockServerProxy2Tests
{ {
private readonly ITestOutputHelper _output;
private readonly CancellationTokenSource _cts;
private Guid _guid;
private string _url;
public FluentMockServerProxy2Tests(ITestOutputHelper output)
{
_output = output;
_cts = new CancellationTokenSource();
}
//private Task Run()
//{
// return Task.Run(() =>
// {
// _guid = Guid.NewGuid();
// var targetServer = FluentMockServer.Start();
// targetServer.Given(Request.Create().UsingPost().WithPath($"/{_guid}"))
// .RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 42 }).WithHeader("Content-Type", "application/json"));
// _url = targetServer.Urls[0];
// //while (!_cts.IsCancellationRequested)
// //{
// // Thread.Sleep(100);
// //}
// }, _cts.Token);
//}
private void X()
{
_guid = Guid.NewGuid();
var targetServer = FluentMockServer.Start();
targetServer.Given(Request.Create().UsingPost().WithPath($"/{_guid}"))
.RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 42 }).WithHeader("Content-Type", "application/json"));
_url = targetServer.Urls[0];
// Thread.Sleep(TimeSpan.FromSeconds(3));
_output.WriteLine(targetServer.Urls[0]);
//while (!_cts.IsCancellationRequested)
//{
// Thread.Sleep(100);
//}
}
[Fact] [Fact]
public void FluentMockServer_ProxyAndRecordSettings_ShouldProxyContentTypeHeader() public async Task FluentMockServer_ProxyAndRecordSettings_ShouldProxy()
{ {
// Assign // Assign
_output.WriteLine("This is output fr"); var server = FluentMockServer.Start();
//var t = new Thread(X);
//t.Start();
X();
_output.WriteLine("started");
Thread.Sleep(TimeSpan.FromSeconds(4)); server.Given(Request.Create().UsingPost().WithHeader("prx", "1"))
.RespondWith(Response.Create().WithProxy(server.Urls[0]));
_output.WriteLine("sleep 4 done"); server.Given(Request.Create().UsingPost())
.RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 42 }).WithHeader("Content-Type", "application/json"));
var server = FluentMockServer.Start(
new FluentMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = _url
}
}
);
_output.WriteLine("started 2");
_output.WriteLine(server.Urls[0]);
// Act // Act
var response = new HttpClient().PostAsync(new Uri($"{server.Urls[0]}/{_guid}"), new StringContent("{ \"x\": 1 }", Encoding.UTF8, "application/json")).Result; var request = new HttpRequestMessage
//string content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); {
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}/TST"),
Content = new StringContent("test")
};
request.Headers.Add("prx", "1");
//// Assert // Assert
//Check.That(content).IsEqualTo("{\"p\":42}"); var response = await new HttpClient().SendAsync(request);
//Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.Created); string content = await response.Content.ReadAsStringAsync();
//Check.That(response.Content.Headers.GetValues("Content-Type").First()).IsEqualTo("application/json");
}
public void Dispose() Check.That(content).IsEqualTo("{\"p\":42}");
{ Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.Created);
_cts.Cancel(); Check.That(response.Content.Headers.GetValues("Content-Type").First()).IsEqualTo("application/json");
} }
} }
} }

View File

@@ -17,11 +17,7 @@ namespace WireMock.Net.Tests.Http
{ {
// Assign // Assign
var headers = new Dictionary<string, string[]> { { "x", new[] { "value-1" } } }; var headers = new Dictionary<string, string[]> { { "x", new[] { "value-1" } } };
var body = new BodyData var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, null, headers);
{
BodyAsString = "<xml>hello</xml>"
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers);
// Act // Act
var message = HttpRequestMessageHelper.Create(request, "http://url"); var message = HttpRequestMessageHelper.Create(request, "http://url");
@@ -36,7 +32,8 @@ namespace WireMock.Net.Tests.Http
// Assign // Assign
var body = new BodyData var body = new BodyData
{ {
BodyAsBytes = Encoding.UTF8.GetBytes("hi") BodyAsBytes = Encoding.UTF8.GetBytes("hi"),
DetectedBodyType = BodyType.Bytes
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body);
@@ -53,7 +50,8 @@ namespace WireMock.Net.Tests.Http
// Assign // Assign
var body = new BodyData var body = new BodyData
{ {
BodyAsJson = new { x = 42 } BodyAsJson = new { x = 42 },
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body);
@@ -71,7 +69,28 @@ namespace WireMock.Net.Tests.Http
var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/json" } } }; var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/json" } } };
var body = new BodyData var body = new BodyData
{ {
BodyAsJson = new { x = 42 } BodyAsJson = new { x = 42 },
DetectedBodyType = BodyType.Json
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body, headers);
// Act
var message = HttpRequestMessageHelper.Create(request, "http://url");
// Assert
Check.That(await message.Content.ReadAsStringAsync()).Equals("{\"x\":42}");
Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/json");
}
[Fact]
public async void HttpRequestMessageHelper_Create_Json_With_ContentType_ApplicationJson_UTF8()
{
// Assign
var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/json; charset=utf-8" } } };
var body = new BodyData
{
BodyAsJson = new { x = 42 },
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body, headers); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp, body, headers);
@@ -90,7 +109,8 @@ namespace WireMock.Net.Tests.Http
var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/xml" } } }; var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/xml" } } };
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "<xml>hello</xml>" BodyAsString = "<xml>hello</xml>",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers);
@@ -98,7 +118,7 @@ namespace WireMock.Net.Tests.Http
var message = HttpRequestMessageHelper.Create(request, "http://url"); var message = HttpRequestMessageHelper.Create(request, "http://url");
// Assert // Assert
Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/xml; charset=utf-8"); Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/xml");
} }
[Fact] [Fact]
@@ -108,7 +128,8 @@ namespace WireMock.Net.Tests.Http
var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/xml; charset=UTF-8" } } }; var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/xml; charset=UTF-8" } } };
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "<xml>hello</xml>" BodyAsString = "<xml>hello</xml>",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers);
@@ -126,7 +147,8 @@ namespace WireMock.Net.Tests.Http
var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/xml; charset=Ascii" } } }; var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/xml; charset=Ascii" } } };
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "<xml>hello</xml>" BodyAsString = "<xml>hello</xml>",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, headers);

View File

@@ -1,97 +0,0 @@
using System;
using NFluent;
using WireMock.Admin.Mappings;
using WireMock.Matchers;
using WireMock.Serialization;
using Xunit;
namespace WireMock.Net.Tests
{
public class MatcherMapperTests
{
[Fact]
public void MatcherMapper_Map_MatcherModel_Null()
{
// Act
var result = MatcherMapper.Map((MatcherModel)null);
// Assert
Check.That(result).IsNull();
}
[Fact]
public void MatcherMapper_Map_MatcherModel_Exception()
{
// Assign
var model = new MatcherModel { Name = "test" };
// Act and Assert
Check.ThatCode(() => MatcherMapper.Map(model)).Throws<NotSupportedException>();
}
[Fact]
public void MatcherMapper_Map_MatcherModel_LinqMatcher_Pattern()
{
// Assign
var model = new MatcherModel
{
Name = "LinqMatcher",
Pattern = "p"
};
// Act
var matcher = MatcherMapper.Map(model) as LinqMatcher;
// Assert
Check.That(matcher).IsNotNull();
Check.That(matcher.MatchBehaviour).IsEqualTo(MatchBehaviour.AcceptOnMatch);
Check.That(matcher.GetPatterns()).ContainsExactly("p");
}
[Fact]
public void MatcherMapper_Map_MatcherModel_LinqMatcher_Patterns()
{
// Assign
var model = new MatcherModel
{
Name = "LinqMatcher",
Patterns = new[] { "p1", "p2" }
};
// Act
var matcher = MatcherMapper.Map(model) as LinqMatcher;
// Assert
Check.That(matcher).IsNotNull();
Check.That(matcher.MatchBehaviour).IsEqualTo(MatchBehaviour.AcceptOnMatch);
Check.That(matcher.GetPatterns()).Contains(new[] { "p1", "p2" });
}
[Fact]
public void MatcherMapper_Map_IMatcher_Null()
{
// Act
var result = MatcherMapper.Map((IMatcher)null);
// Assert
Check.That(result).IsNull();
}
[Fact]
public void MatcherMapper_Map_IMatcher_LinqMatcher_Pattern()
{
// Assign
var matcher = new LinqMatcher(MatchBehaviour.AcceptOnMatch, "p");
// Act
var result = MatcherMapper.Map(matcher);
// Assert
Check.That(result).IsNotNull();
Check.That(result.Name).IsEqualTo("LinqMatcher");
Check.That(result.IgnoreCase).IsNull();
Check.That(result.Pattern).IsEqualTo("p");
Check.That(result.Patterns).IsNull();
}
}
}

View File

@@ -96,7 +96,7 @@ namespace WireMock.Net.Tests.Owin.Mappers
var responseMessage = new ResponseMessage var responseMessage = new ResponseMessage
{ {
Headers = new Dictionary<string, WireMockList<string>>(), Headers = new Dictionary<string, WireMockList<string>>(),
Body = body BodyData = new BodyData { DetectedBodyType = BodyType.String, BodyAsString = body }
}; };
// Act // Act
@@ -114,7 +114,7 @@ namespace WireMock.Net.Tests.Owin.Mappers
var responseMessage = new ResponseMessage var responseMessage = new ResponseMessage
{ {
Headers = new Dictionary<string, WireMockList<string>>(), Headers = new Dictionary<string, WireMockList<string>>(),
BodyAsBytes = bytes BodyData = new BodyData { DetectedBodyType = BodyType.Bytes, BodyAsBytes = bytes }
}; };
// Act // Act
@@ -128,11 +128,11 @@ namespace WireMock.Net.Tests.Owin.Mappers
public async void OwinResponseMapper_MapAsync_BodyAsJson() public async void OwinResponseMapper_MapAsync_BodyAsJson()
{ {
// Assign // Assign
var json = new { t = "x", i = (string)null };
var responseMessage = new ResponseMessage var responseMessage = new ResponseMessage
{ {
Headers = new Dictionary<string, WireMockList<string>>(), Headers = new Dictionary<string, WireMockList<string>>(),
BodyAsJson = new { t = "x", i = (string)null }, BodyData = new BodyData { DetectedBodyType = BodyType.Json, BodyAsJson = json, BodyAsJsonIndented = false }
BodyAsJsonIndented = false
}; };
// Act // Act

View File

@@ -21,7 +21,7 @@ namespace WireMock.Net.Tests.Owin
_optionsMock = new Mock<IWireMockMiddlewareOptions>(); _optionsMock = new Mock<IWireMockMiddlewareOptions>();
_optionsMock.SetupAllProperties(); _optionsMock.SetupAllProperties();
_optionsMock.Setup(o => o.Mappings).Returns(new ConcurrentDictionary<Guid, IMapping>()); _optionsMock.Setup(o => o.Mappings).Returns(new ConcurrentDictionary<Guid, IMapping>());
_optionsMock.Setup(o => o.LogEntries).Returns(new ConcurentObservableCollection<LogEntry>()); _optionsMock.Setup(o => o.LogEntries).Returns(new ConcurrentObservableCollection<LogEntry>());
_optionsMock.Setup(o => o.Scenarios).Returns(new ConcurrentDictionary<string, ScenarioState>()); _optionsMock.Setup(o => o.Scenarios).Returns(new ConcurrentDictionary<string, ScenarioState>());
_sut = new MappingMatcher(_optionsMock.Object); _sut = new MappingMatcher(_optionsMock.Object);

View File

@@ -44,7 +44,7 @@ namespace WireMock.Net.Tests.Owin
_optionsMock = new Mock<IWireMockMiddlewareOptions>(); _optionsMock = new Mock<IWireMockMiddlewareOptions>();
_optionsMock.SetupAllProperties(); _optionsMock.SetupAllProperties();
_optionsMock.Setup(o => o.Mappings).Returns(new ConcurrentDictionary<Guid, IMapping>()); _optionsMock.Setup(o => o.Mappings).Returns(new ConcurrentDictionary<Guid, IMapping>());
_optionsMock.Setup(o => o.LogEntries).Returns(new ConcurentObservableCollection<LogEntry>()); _optionsMock.Setup(o => o.LogEntries).Returns(new ConcurrentObservableCollection<LogEntry>());
_optionsMock.Setup(o => o.Scenarios).Returns(new ConcurrentDictionary<string, ScenarioState>()); _optionsMock.Setup(o => o.Scenarios).Returns(new ConcurrentDictionary<string, ScenarioState>());
_optionsMock.Setup(o => o.Logger.Warn(It.IsAny<string>(), It.IsAny<object[]>())); _optionsMock.Setup(o => o.Logger.Warn(It.IsAny<string>(), It.IsAny<object[]>()));
_optionsMock.Setup(o => o.Logger.Error(It.IsAny<string>(), It.IsAny<object[]>())); _optionsMock.Setup(o => o.Logger.Error(It.IsAny<string>(), It.IsAny<object[]>()));
@@ -79,7 +79,7 @@ namespace WireMock.Net.Tests.Owin
// Assert and Verify // Assert and Verify
_optionsMock.Verify(o => o.Logger.Warn(It.IsAny<string>(), It.IsAny<object[]>()), Times.Once); _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.BodyAsJson).Status == "No matching mapping found"; Expression<Func<ResponseMessage, bool>> match = r => 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); _responseMapperMock.Verify(m => m.MapAsync(It.Is(match), It.IsAny<IResponse>()), Times.Once);
} }

View File

@@ -73,7 +73,7 @@ namespace WireMock.Net.Tests.RequestBuilders
public void RequestBuilder_WithHeader_FuncIDictionary() public void RequestBuilder_WithHeader_FuncIDictionary()
{ {
// Act // Act
var requestBuilder = (Request)Request.Create().WithHeader((IDictionary<string, string[]> x) => true); var requestBuilder = (Request)Request.Create().WithHeader(x => true);
// Assert // Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers"); var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");

View File

@@ -0,0 +1,60 @@
using System.Collections.Generic;
using NFluent;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.RequestBuilders;
using Xunit;
namespace WireMock.Net.Tests.RequestBuilders
{
public class RequestBuilderWithUrlTests
{
[Fact]
public void RequestBuilder_WithUrl_Strings()
{
// Act
var requestBuilder = (Request)Request.Create().WithUrl("http://a", "http://b");
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher));
}
[Fact]
public void RequestBuilder_WithUrl_MatchBehaviour_Strings()
{
// Act
var requestBuilder = (Request)Request.Create().WithUrl(MatchBehaviour.AcceptOnMatch, "http://a", "http://b");
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher));
}
[Fact]
public void RequestBuilder_WithUrl_Funcs()
{
// Act
var requestBuilder = (Request) Request.Create().WithUrl(url => true, url => false);
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher));
}
[Fact]
public void RequestBuilder_WithUrl_IStringMatchers()
{
// Act
var requestBuilder = (Request) Request.Create().WithUrl(new ExactMatcher("http://a"), new ExactMatcher("http://b"));
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher));
}
}
}

View File

@@ -1,28 +0,0 @@
using System.Collections.Generic;
using NFluent;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.RequestBuilders;
using Xunit;
namespace WireMock.Net.Tests
{
public class RequestCookieTests
{
private const string ClientIp = "::1";
[Fact]
public void Request_WithCookie_OK()
{
// given
var spec = Request.Create().UsingAnyMethod().WithCookie("session", "a*");
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, null, null, new Dictionary<string, string> { { "session", "abc" } });
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
}
}

View File

@@ -16,7 +16,8 @@ namespace WireMock.Net.Tests.RequestMatchers
// Assign // Assign
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "b" BodyAsString = "b",
DetectedBodyType = BodyType.String
}; };
var stringMatcherMock = new Mock<IStringMatcher>(); var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d); stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
@@ -43,7 +44,8 @@ namespace WireMock.Net.Tests.RequestMatchers
// Assign // Assign
var body = new BodyData var body = new BodyData
{ {
BodyAsBytes = new byte[] { 1 } BodyAsBytes = new byte[] { 1 },
DetectedBodyType = BodyType.Bytes
}; };
var stringMatcherMock = new Mock<IStringMatcher>(); var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d); stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
@@ -70,7 +72,8 @@ namespace WireMock.Net.Tests.RequestMatchers
// Assign // Assign
var body = new BodyData var body = new BodyData
{ {
BodyAsJson = new { value = 42 } BodyAsJson = new { value = 42 },
DetectedBodyType = BodyType.Json
}; };
var stringMatcherMock = new Mock<IStringMatcher>(); var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d); stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
@@ -84,10 +87,10 @@ namespace WireMock.Net.Tests.RequestMatchers
double score = matcher.GetMatchingScore(requestMessage, result); double score = matcher.GetMatchingScore(requestMessage, result);
// Assert // Assert
Check.That(score).IsEqualTo(0.0d); Check.That(score).IsEqualTo(0.5d);
// Verify // Verify
stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Never); stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Once);
} }
[Fact] [Fact]
@@ -97,7 +100,8 @@ namespace WireMock.Net.Tests.RequestMatchers
var body = new BodyData var body = new BodyData
{ {
BodyAsJson = new { value = 42 }, BodyAsJson = new { value = 42 },
BodyAsString = "orig" BodyAsString = "orig",
DetectedBodyType = BodyType.Json
}; };
var stringMatcherMock = new Mock<IStringMatcher>(); var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d); stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
@@ -123,7 +127,8 @@ namespace WireMock.Net.Tests.RequestMatchers
// Assign // Assign
var body = new BodyData var body = new BodyData
{ {
BodyAsJson = 42 BodyAsJson = 42,
DetectedBodyType = BodyType.Json
}; };
var objectMatcherMock = new Mock<IObjectMatcher>(); var objectMatcherMock = new Mock<IObjectMatcher>();
objectMatcherMock.Setup(m => m.IsMatch(It.IsAny<object>())).Returns(0.5d); objectMatcherMock.Setup(m => m.IsMatch(It.IsAny<object>())).Returns(0.5d);
@@ -149,7 +154,8 @@ namespace WireMock.Net.Tests.RequestMatchers
// Assign // Assign
var body = new BodyData var body = new BodyData
{ {
BodyAsBytes = new byte[] { 1 } BodyAsBytes = new byte[] { 1 },
DetectedBodyType = BodyType.Bytes
}; };
var objectMatcherMock = new Mock<IObjectMatcher>(); var objectMatcherMock = new Mock<IObjectMatcher>();
objectMatcherMock.Setup(m => m.IsMatch(It.IsAny<object>())).Returns(0.5d); objectMatcherMock.Setup(m => m.IsMatch(It.IsAny<object>())).Returns(0.5d);

View File

@@ -35,7 +35,8 @@ namespace WireMock.Net.Tests
// when // when
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "whatever" BodyAsString = "whatever",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, new Dictionary<string, string[]> { { "X-toto", new[] { "tata" } } }); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, new Dictionary<string, string[]> { { "X-toto", new[] { "tata" } } });
@@ -53,7 +54,8 @@ namespace WireMock.Net.Tests
// when // when
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "whatever" BodyAsString = "whatever",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, new Dictionary<string, string[]> { { "X-toto", new[] { "ABC" } } }); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, new Dictionary<string, string[]> { { "X-toto", new[] { "ABC" } } });
@@ -71,7 +73,8 @@ namespace WireMock.Net.Tests
// when // when
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "whatever" BodyAsString = "whatever",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, new Dictionary<string, string[]> { { "X-toto", new[] { "TaTa" } } }); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, new Dictionary<string, string[]> { { "X-toto", new[] { "TaTa" } } });
@@ -89,7 +92,8 @@ namespace WireMock.Net.Tests
// when // when
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "Hello world!" BodyAsString = "Hello world!",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body);
@@ -107,7 +111,8 @@ namespace WireMock.Net.Tests
// when // when
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "xxx" BodyAsString = "xxx",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, new Dictionary<string, string[]> { { "X-toto", new[] { "tata" } } }); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, new Dictionary<string, string[]> { { "X-toto", new[] { "tata" } } });

View File

@@ -24,7 +24,8 @@ namespace WireMock.Net.Tests
// Act // Act
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "b" BodyAsString = "b",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
@@ -42,7 +43,8 @@ namespace WireMock.Net.Tests
// Act // Act
var body = new BodyData var body = new BodyData
{ {
BodyAsJson = 123 BodyAsJson = 123,
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
@@ -60,7 +62,8 @@ namespace WireMock.Net.Tests
// Act // Act
var body = new BodyData var body = new BodyData
{ {
BodyAsBytes = new byte[0] BodyAsBytes = new byte[0],
DetectedBodyType = BodyType.Bytes
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
@@ -78,7 +81,8 @@ namespace WireMock.Net.Tests
// when // when
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "cat" BodyAsString = "cat",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
@@ -96,7 +100,8 @@ namespace WireMock.Net.Tests
// when // when
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "Hello world!" BodyAsString = "Hello world!",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body);
@@ -119,7 +124,8 @@ namespace WireMock.Net.Tests
<todo-item id='a1'>abc</todo-item> <todo-item id='a1'>abc</todo-item>
<todo-item id='a2'>def</todo-item> <todo-item id='a2'>def</todo-item>
<todo-item id='a3'>xyz</todo-item> <todo-item id='a3'>xyz</todo-item>
</todo-list>" </todo-list>",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body);
@@ -142,7 +148,8 @@ namespace WireMock.Net.Tests
<todo-item id='a1'>abc</todo-item> <todo-item id='a1'>abc</todo-item>
<todo-item id='a2'>def</todo-item> <todo-item id='a2'>def</todo-item>
<todo-item id='a3'>xyz</todo-item> <todo-item id='a3'>xyz</todo-item>
</todo-list>" </todo-list>",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body);
@@ -160,7 +167,8 @@ namespace WireMock.Net.Tests
// when // when
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }" BodyAsString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body);
@@ -178,7 +186,8 @@ namespace WireMock.Net.Tests
// when // when
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "{ \"things\": { \"name\": \"Wiremock\" } }" BodyAsString = "{ \"things\": { \"name\": \"Wiremock\" } }",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body);
@@ -199,7 +208,8 @@ namespace WireMock.Net.Tests
{ {
BodyAsJson = JsonConvert.DeserializeObject(jsonString), BodyAsJson = JsonConvert.DeserializeObject(jsonString),
BodyAsString = jsonString, BodyAsString = jsonString,
Encoding = Encoding.UTF8 Encoding = Encoding.UTF8,
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, bodyData); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, bodyData);
@@ -221,7 +231,8 @@ namespace WireMock.Net.Tests
{ {
BodyAsJson = JsonConvert.DeserializeObject(jsonString), BodyAsJson = JsonConvert.DeserializeObject(jsonString),
BodyAsString = jsonString, BodyAsString = jsonString,
Encoding = Encoding.UTF8 Encoding = Encoding.UTF8,
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, bodyData); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, bodyData);
@@ -243,7 +254,8 @@ namespace WireMock.Net.Tests
{ {
BodyAsJson = JsonConvert.DeserializeObject(jsonString), BodyAsJson = JsonConvert.DeserializeObject(jsonString),
BodyAsString = jsonString, BodyAsString = jsonString,
Encoding = Encoding.UTF8 Encoding = Encoding.UTF8,
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, bodyData); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, bodyData);
@@ -263,7 +275,8 @@ namespace WireMock.Net.Tests
var bodyData = new BodyData var bodyData = new BodyData
{ {
BodyAsJson = DateTime.MinValue BodyAsJson = DateTime.MinValue,
DetectedBodyType = BodyType.Json
}; };
// Act // Act
@@ -283,7 +296,8 @@ namespace WireMock.Net.Tests
var bodyData = new BodyData var bodyData = new BodyData
{ {
BodyAsBytes = new byte[] { 123 } BodyAsBytes = new byte[] { 123 },
DetectedBodyType = BodyType.Bytes
}; };
// Act // Act

View File

@@ -1,56 +0,0 @@
using NFluent;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.RequestBuilders;
using Xunit;
namespace WireMock.Net.Tests
{
public class RequestWithUrlTests
{
private const string ClientIp = "::1";
[Fact]
public void Request_WithUrl()
{
// given
var spec = Request.Create().WithUrl("*/foo");
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "blabla", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Request_WithUrl_WildcardMatcher()
{
// given
var spec = Request.Create().WithUrl(new WildcardMatcher("*/foo"));
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "blabla", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Request_WithUrl_Func()
{
// given
var spec = Request.Create().WithUrl(url => url.Contains("foo"));
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "blabla", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
}
}

View File

@@ -18,6 +18,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
// given // given
var body = new BodyData var body = new BodyData
{ {
DetectedBodyType = BodyType.String,
BodyAsString = "abc" BodyAsString = "abc"
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
@@ -28,9 +29,9 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// then // then
Check.That(responseMessage.Body).Equals("01"); Check.That(responseMessage.BodyData.BodyAsString).Equals("01");
Check.That(responseMessage.BodyAsBytes).IsNull(); Check.That(responseMessage.BodyData.BodyAsBytes).IsNull();
Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII); Check.That(responseMessage.BodyData.Encoding).Equals(Encoding.ASCII);
} }
[Fact] [Fact]
@@ -39,6 +40,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
// given // given
var body = new BodyData var body = new BodyData
{ {
DetectedBodyType = BodyType.String,
BodyAsString = "abc" BodyAsString = "abc"
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
@@ -49,9 +51,9 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// then // then
Check.That(responseMessage.BodyAsBytes).ContainsExactly(new byte[] { 48, 49 }); Check.That(responseMessage.BodyData.BodyAsBytes).ContainsExactly(new byte[] { 48, 49 });
Check.That(responseMessage.Body).IsNull(); Check.That(responseMessage.BodyData.BodyAsString).IsNull();
Check.That(responseMessage.BodyEncoding).IsNull(); Check.That(responseMessage.BodyData.Encoding).IsNull();
} }
[Fact] [Fact]
@@ -60,6 +62,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
// given // given
var body = new BodyData var body = new BodyData
{ {
DetectedBodyType = BodyType.String,
BodyAsString = "abc" BodyAsString = "abc"
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
@@ -70,8 +73,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// then // then
Check.That(responseMessage.Body).Equals("test"); Check.That(responseMessage.BodyData.BodyAsString).Equals("test");
Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII); Check.That(responseMessage.BodyData.Encoding).Equals(Encoding.ASCII);
} }
[Fact] [Fact]
@@ -80,6 +83,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
// given // given
var body = new BodyData var body = new BodyData
{ {
DetectedBodyType = BodyType.String,
BodyAsString = "abc" BodyAsString = "abc"
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
@@ -91,9 +95,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// then // then
Check.That(responseMessage.BodyAsJson).IsNotNull(); Check.That(responseMessage.BodyData.BodyAsJson).Equals(x);
Check.That(responseMessage.BodyAsJson).Equals(x); Check.That(responseMessage.BodyData.Encoding).Equals(Encoding.ASCII);
Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII);
} }
[Fact] [Fact]
@@ -102,6 +105,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
// given // given
var body = new BodyData var body = new BodyData
{ {
DetectedBodyType = BodyType.String,
BodyAsString = "abc" BodyAsString = "abc"
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body);
@@ -113,9 +117,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// then // then
Check.That(responseMessage.BodyAsJson).IsNotNull(); Check.That(responseMessage.BodyData.BodyAsJson).Equals(x);
Check.That(responseMessage.BodyAsJson).Equals(x); Check.That(responseMessage.BodyData.BodyAsJsonIndented).IsEqualTo(true);
Check.That(responseMessage.BodyAsJsonIndented).IsEqualTo(true);
} }
[Fact] [Fact]
@@ -130,10 +133,10 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.BodyAsBytes).IsNull(); Check.That(responseMessage.BodyData.BodyAsBytes).IsNull();
Check.That(responseMessage.BodyAsJson).IsNull(); Check.That(responseMessage.BodyData.BodyAsJson).IsNull();
Check.That(responseMessage.Body).Equals("r"); Check.That(responseMessage.BodyData.BodyAsString).Equals("r");
Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII); Check.That(responseMessage.BodyData.Encoding).Equals(Encoding.ASCII);
} }
[Fact] [Fact]
@@ -148,10 +151,10 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).IsNull(); Check.That(responseMessage.BodyData.BodyAsString).IsNull();
Check.That(responseMessage.BodyAsJson).IsNull(); Check.That(responseMessage.BodyData.BodyAsJson).IsNull();
Check.That(responseMessage.BodyAsBytes).IsNotNull(); Check.That(responseMessage.BodyData.BodyAsBytes).IsNotNull();
Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII); Check.That(responseMessage.BodyData.Encoding).Equals(Encoding.ASCII);
} }
[Fact] [Fact]
@@ -166,10 +169,10 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).IsNull(); Check.That(responseMessage.BodyData.BodyAsString).IsNull();
Check.That(responseMessage.BodyAsBytes).IsNull(); Check.That(responseMessage.BodyData.BodyAsBytes).IsNull();
Check.That(((dynamic)responseMessage.BodyAsJson).value).Equals(42); Check.That(((dynamic)responseMessage.BodyData.BodyAsJson).value).Equals(42);
Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII); Check.That(responseMessage.BodyData.Encoding).Equals(Encoding.ASCII);
} }
[Fact] [Fact]
@@ -188,10 +191,10 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).IsEqualTo("path: /test"); Check.That(responseMessage.BodyData.BodyAsString).IsEqualTo("path: /test");
Check.That(responseMessage.BodyAsBytes).IsNull(); Check.That(responseMessage.BodyData.BodyAsBytes).IsNull();
Check.That(responseMessage.BodyAsJson).IsNull(); Check.That(responseMessage.BodyData.BodyAsJson).IsNull();
Check.That(responseMessage.BodyEncoding.CodePage).Equals(Encoding.UTF8.CodePage); Check.That(responseMessage.BodyData.Encoding.CodePage).Equals(Encoding.UTF8.CodePage);
Check.That(responseMessage.StatusCode).IsEqualTo(500); Check.That(responseMessage.StatusCode).IsEqualTo(500);
Check.That(responseMessage.Headers["H1"].ToString()).IsEqualTo("X1"); Check.That(responseMessage.Headers["H1"].ToString()).IsEqualTo("X1");
Check.That(responseMessage.Headers["H2"].ToString()).IsEqualTo("X2"); Check.That(responseMessage.Headers["H2"].ToString()).IsEqualTo("X2");

View File

@@ -2,6 +2,7 @@
using NFluent; using NFluent;
using WireMock.Models; using WireMock.Models;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Util;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.ResponseBuilders namespace WireMock.Net.Tests.ResponseBuilders
@@ -13,13 +14,13 @@ namespace WireMock.Net.Tests.ResponseBuilders
{ {
// Assign // Assign
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1"); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
var response = Response.Create().WithCallback(req => new ResponseMessage { Body = req.Path + "Bar", StatusCode = 302 }); var response = Response.Create().WithCallback(req => new ResponseMessage { BodyData = new BodyData { DetectedBodyType = BodyType.String, BodyAsString = req.Path + "Bar" }, StatusCode = 302 });
// Act // Act
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).IsEqualTo("/fooBar"); Check.That(responseMessage.BodyData.BodyAsString).IsEqualTo("/fooBar");
Check.That(responseMessage.StatusCode).IsEqualTo(302); Check.That(responseMessage.StatusCode).IsEqualTo(302);
} }
} }

View File

@@ -48,7 +48,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
] ]
} }
] ]
}" }",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -62,7 +63,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
JObject j = JObject.FromObject(responseMessage.BodyAsJson); JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["x"]).IsNotNull(); Check.That(j["x"]).IsNotNull();
Check.That(j["x"]["Name"].ToString()).Equals("Acme Co"); Check.That(j["x"]["Name"].ToString()).Equals("Acme Co");
} }
@@ -71,7 +72,11 @@ namespace WireMock.Net.Tests.ResponseBuilders
public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Number_ResponseBodyAsJson() public async Task Response_ProvideResponse_Handlebars_JsonPath_SelectToken_Number_ResponseBodyAsJson()
{ {
// Assign // Assign
var body = new BodyData { BodyAsString = "{ \"Price\": 99 }" }; var body = new BodyData
{
BodyAsString = "{ \"Price\": 99 }",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -84,7 +89,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
JObject j = JObject.FromObject(responseMessage.BodyAsJson); JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["x"].Value<long>()).Equals(99); Check.That(j["x"].Value<long>()).Equals(99);
} }
@@ -123,7 +128,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
] ]
} }
] ]
}" }",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -137,7 +143,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).Equals($"{{{Environment.NewLine} \"Name\": \"Acme Co\",{Environment.NewLine} \"Products\": [{Environment.NewLine} {{{Environment.NewLine} \"Name\": \"Anvil\",{Environment.NewLine} \"Price\": 50{Environment.NewLine} }}{Environment.NewLine} ]{Environment.NewLine}}}"); Check.That(responseMessage.BodyData.BodyAsString).Equals($"{{{Environment.NewLine} \"Name\": \"Acme Co\",{Environment.NewLine} \"Products\": [{Environment.NewLine} {{{Environment.NewLine} \"Name\": \"Anvil\",{Environment.NewLine} \"Price\": 50{Environment.NewLine} }}{Environment.NewLine} ]{Environment.NewLine}}}");
} }
[Fact] [Fact]
@@ -175,7 +181,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
] ]
} }
] ]
}") }"),
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -189,7 +196,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).Equals($"{{{Environment.NewLine} \"Name\": \"Acme Co\",{Environment.NewLine} \"Products\": [{Environment.NewLine} {{{Environment.NewLine} \"Name\": \"Anvil\",{Environment.NewLine} \"Price\": 50{Environment.NewLine} }}{Environment.NewLine} ]{Environment.NewLine}}}"); Check.That(responseMessage.BodyData.BodyAsString).Equals($"{{{Environment.NewLine} \"Name\": \"Acme Co\",{Environment.NewLine} \"Products\": [{Environment.NewLine} {{{Environment.NewLine} \"Name\": \"Anvil\",{Environment.NewLine} \"Price\": 50{Environment.NewLine} }}{Environment.NewLine} ]{Environment.NewLine}}}");
} }
[Fact] [Fact]
@@ -227,7 +234,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
] ]
} }
] ]
}" }",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -241,7 +249,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).Equals("%0:Anvil%%1:Elbow Grease%"); Check.That(responseMessage.BodyData.BodyAsString).Equals("%0:Anvil%%1:Elbow Grease%");
} }
[Fact] [Fact]
@@ -279,7 +287,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
] ]
} }
] ]
}") }"),
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -293,7 +302,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).Equals("%0:Anvil%%1:Elbow Grease%"); Check.That(responseMessage.BodyData.BodyAsString).Equals("%0:Anvil%%1:Elbow Grease%");
} }
[Fact] [Fact]
@@ -307,7 +316,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
'Lambton Quay', 'Lambton Quay',
'Willis Street' 'Willis Street'
] ]
}") }"),
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);

View File

@@ -28,7 +28,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
JObject j = JObject.FromObject(responseMessage.BodyAsJson); JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["x"]).IsNotNull(); Check.That(j["x"]).IsNotNull();
Check.That(j["x"].ToString()).Equals("/pathtest"); Check.That(j["x"].ToString()).Equals("/pathtest");
} }
@@ -43,7 +43,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
{ {
{ "Id", new JValue(9) }, { "Id", new JValue(9) },
{ "Name", new JValue("Test") } { "Name", new JValue("Test") }
} },
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
@@ -57,7 +58,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
JObject j = JObject.FromObject(responseMessage.BodyAsJson); JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["x"]).IsNotNull(); Check.That(j["x"]).IsNotNull();
Check.That(j["x"].ToString()).Equals("Test_123"); Check.That(j["x"].ToString()).Equals("Test_123");
} }
@@ -72,7 +73,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
{ {
{ "Id", new JValue(9) }, { "Id", new JValue(9) },
{ "Name", new JValue("Test") } { "Name", new JValue("Test") }
} },
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
@@ -86,7 +88,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
JObject j = JObject.FromObject(responseMessage.BodyAsJson); JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["x"]).IsNotNull(); Check.That(j["x"]).IsNotNull();
Check.That(j["x"].ToString()).Equals("{ N = Test_123, I = 9 }"); Check.That(j["x"].ToString()).Equals("{ N = Test_123, I = 9 }");
} }
@@ -101,7 +103,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
{ {
{ "Id", new JValue(9) }, { "Id", new JValue(9) },
{ "Name", new JValue("Test") } { "Name", new JValue("Test") }
} },
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
@@ -115,7 +118,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
JObject j = JObject.FromObject(responseMessage.BodyAsJson); JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["x"]).IsNotNull(); Check.That(j["x"]).IsNotNull();
Check.That(j["x"].ToString()).Equals("{ N = Test_123, I = 9 }"); Check.That(j["x"].ToString()).Equals("{ N = Test_123, I = 9 }");
} }
@@ -124,7 +127,11 @@ namespace WireMock.Net.Tests.ResponseBuilders
public void Response_ProvideResponse_Handlebars_Linq_Throws_NotSupportedException() public void Response_ProvideResponse_Handlebars_Linq_Throws_NotSupportedException()
{ {
// Assign // Assign
var body = new BodyData { BodyAsJson = new { x = "x" }}; var body = new BodyData
{
BodyAsJson = new { x = "x" },
DetectedBodyType = BodyType.Json
};
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
@@ -178,7 +185,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
{ {
{ "Id", new JValue(9) }, { "Id", new JValue(9) },
{ "Name", new JValue("Test") } { "Name", new JValue("Test") }
} },
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
@@ -191,7 +199,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
JObject j = JObject.FromObject(responseMessage.BodyAsJson); JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["x"].ToString()).IsEmpty(); Check.That(j["x"].ToString()).IsEmpty();
} }
@@ -205,7 +213,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
{ {
{ "Id", new JValue(9) }, { "Id", new JValue(9) },
{ "Name", new JValue("Test") } { "Name", new JValue("Test") }
} },
DetectedBodyType = BodyType.Json
}; };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", "::1", body);
@@ -218,7 +227,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
JObject j = JObject.FromObject(responseMessage.BodyAsJson); JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["x"].ToString()).IsEmpty(); Check.That(j["x"].ToString()).IsEmpty();
} }
} }

View File

@@ -15,7 +15,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
public async void Response_ProvideResponse_Handlebars_RegexMatch() public async void Response_ProvideResponse_Handlebars_RegexMatch()
{ {
// Assign // Assign
var body = new BodyData { BodyAsString = "abc" }; var body = new BodyData { BodyAsString = "abc", DetectedBodyType = BodyType.String };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -27,14 +27,14 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// assert // assert
Check.That(responseMessage.Body).Equals("abc"); Check.That(responseMessage.BodyData.BodyAsString).Equals("abc");
} }
[Fact] [Fact]
public async void Response_ProvideResponse_Handlebars_RegexMatch_NoMatch() public async void Response_ProvideResponse_Handlebars_RegexMatch_NoMatch()
{ {
// Assign // Assign
var body = new BodyData { BodyAsString = "abc" }; var body = new BodyData { BodyAsString = "abc", DetectedBodyType = BodyType.String };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -46,14 +46,14 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// assert // assert
Check.That(responseMessage.Body).Equals(""); Check.That(responseMessage.BodyData.BodyAsString).Equals("");
} }
[Fact] [Fact]
public async void Response_ProvideResponse_Handlebars_RegexMatch_NoMatch_WithDefaultValue() public async void Response_ProvideResponse_Handlebars_RegexMatch_NoMatch_WithDefaultValue()
{ {
// Assign // Assign
var body = new BodyData { BodyAsString = "abc" }; var body = new BodyData { BodyAsString = "abc", DetectedBodyType = BodyType.String };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -65,14 +65,14 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// assert // assert
Check.That(responseMessage.Body).Equals("d"); Check.That(responseMessage.BodyData.BodyAsString).Equals("d");
} }
[Fact] [Fact]
public async void Response_ProvideResponse_Handlebars_RegexMatch2() public async void Response_ProvideResponse_Handlebars_RegexMatch2()
{ {
// Assign // Assign
var body = new BodyData { BodyAsString = "https://localhost:5000/" }; var body = new BodyData { BodyAsString = "https://localhost:5000/", DetectedBodyType = BodyType.String };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -84,14 +84,14 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// assert // assert
Check.That(responseMessage.Body).Equals("5000-https"); Check.That(responseMessage.BodyData.BodyAsString).Equals("5000-https");
} }
[Fact] [Fact]
public async void Response_ProvideResponse_Handlebars_RegexMatch2_NoMatch() public async void Response_ProvideResponse_Handlebars_RegexMatch2_NoMatch()
{ {
// Assign // Assign
var body = new BodyData { BodyAsString = "{{\\test" }; var body = new BodyData { BodyAsString = "{{\\test", DetectedBodyType = BodyType.String };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -103,14 +103,14 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// assert // assert
Check.That(responseMessage.Body).Equals(""); Check.That(responseMessage.BodyData.BodyAsString).Equals("");
} }
[Fact] [Fact]
public async void Response_ProvideResponse_Handlebars_RegexMatch2_NoMatch_WithDefaultValue() public async void Response_ProvideResponse_Handlebars_RegexMatch2_NoMatch_WithDefaultValue()
{ {
// Assign // Assign
var body = new BodyData { BodyAsString = "{{\\test" }; var body = new BodyData { BodyAsString = "{{\\test", DetectedBodyType = BodyType.String };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -122,14 +122,14 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// assert // assert
Check.That(responseMessage.Body).Equals("x"); Check.That(responseMessage.BodyData.BodyAsString).Equals("x");
} }
[Fact] [Fact]
public void Response_ProvideResponse_Handlebars_RegexMatch2_Throws() public void Response_ProvideResponse_Handlebars_RegexMatch2_Throws()
{ {
// Assign // Assign
var body = new BodyData { BodyAsString = "{{\\test" }; var body = new BodyData { BodyAsString = "{{\\test", DetectedBodyType = BodyType.String };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);

View File

@@ -28,6 +28,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var bodyData = new BodyData var bodyData = new BodyData
{ {
BodyAsJson = JsonConvert.DeserializeObject(jsonString), BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8 Encoding = Encoding.UTF8
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData); var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
@@ -40,7 +41,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(JsonConvert.SerializeObject(responseMessage.BodyAsJson)).Equals("{\"x\":\"test /foo_object\"}"); Check.That(JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson)).Equals("{\"x\":\"test /foo_object\"}");
} }
[Fact] [Fact]
@@ -49,7 +50,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
// Assign // Assign
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "whatever" BodyAsString = "whatever",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POSt", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POSt", ClientIp, body);
@@ -61,7 +63,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).Equals("test http://localhost/foo /foo POSt"); Check.That(responseMessage.BodyData.BodyAsString).Equals("test http://localhost/foo /foo POSt");
} }
[Fact] [Fact]
@@ -79,7 +81,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).Equals("http://localhost/a/b http://localhost/wiremock/a/b /a/b /wiremock/a/b"); Check.That(responseMessage.BodyData.BodyAsString).Equals("http://localhost/a/b http://localhost/wiremock/a/b /a/b /wiremock/a/b");
} }
[Fact] [Fact]
@@ -97,7 +99,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).Equals("a wiremock"); Check.That(responseMessage.BodyData.BodyAsString).Equals("a wiremock");
} }
[Fact] [Fact]
@@ -106,7 +108,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
// Assign // Assign
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "abc" BodyAsString = "abc",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=1&a=2&b=5"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=1&a=2&b=5"), "POST", ClientIp, body);
@@ -118,7 +121,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).Equals("test keya=1 idx=1 idx=2 keyb=5"); Check.That(responseMessage.BodyData.BodyAsString).Equals("test keya=1 idx=1 idx=2 keyb=5");
} }
[Fact] [Fact]
@@ -127,7 +130,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
// Assign // Assign
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "abc" BodyAsString = "abc",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body, new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } }); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body, new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } });
@@ -137,7 +141,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).Equals("test"); Check.That(responseMessage.BodyData.BodyAsString).Equals("test");
Check.That(responseMessage.Headers).ContainsKey("x"); Check.That(responseMessage.Headers).ContainsKey("x");
Check.That(responseMessage.Headers["x"]).ContainsExactly("text/plain"); Check.That(responseMessage.Headers["x"]).ContainsExactly("text/plain");
} }
@@ -148,7 +152,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
// Assign // Assign
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "abc" BodyAsString = "abc",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body, new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } }); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body, new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } });
@@ -158,7 +163,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).Equals("test"); Check.That(responseMessage.BodyData.BodyAsString).Equals("test");
Check.That(responseMessage.Headers).ContainsKey("x"); Check.That(responseMessage.Headers).ContainsKey("x");
Check.That(responseMessage.Headers["x"]).Contains("text/plain"); Check.That(responseMessage.Headers["x"]).Contains("text/plain");
Check.That(responseMessage.Headers["x"]).Contains("http://localhost/foo"); Check.That(responseMessage.Headers["x"]).Contains("http://localhost/foo");
@@ -170,7 +175,8 @@ namespace WireMock.Net.Tests.ResponseBuilders
// Assign // Assign
var body = new BodyData var body = new BodyData
{ {
BodyAsString = "abc" BodyAsString = "abc",
DetectedBodyType = BodyType.String
}; };
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body); var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
@@ -182,7 +188,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).Equals("test http://localhost:1234 1234 http localhost"); Check.That(responseMessage.BodyData.BodyAsString).Equals("test http://localhost:1234 1234 http localhost");
} }
[Fact] [Fact]
@@ -193,6 +199,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var bodyData = new BodyData var bodyData = new BodyData
{ {
BodyAsJson = JsonConvert.DeserializeObject(jsonString), BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8 Encoding = Encoding.UTF8
}; };
var request = new RequestMessage(new UrlDetails("http://localhost/foo_array"), "POST", ClientIp, bodyData); var request = new RequestMessage(new UrlDetails("http://localhost/foo_array"), "POST", ClientIp, bodyData);
@@ -205,7 +212,7 @@ namespace WireMock.Net.Tests.ResponseBuilders
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(JsonConvert.SerializeObject(responseMessage.BodyAsJson)).Equals("[\"first\",\"/foo_array\",\"test 1\",\"test 2\",\"last\"]"); Check.That(JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson)).Equals("[\"first\",\"/foo_array\",\"test 1\",\"test 2\",\"last\"]");
} }
} }
} }

View File

@@ -12,6 +12,39 @@ namespace WireMock.Net.Tests.ResponseBuilders
{ {
private const string ClientIp = "::1"; private const string ClientIp = "::1";
[Theory]
[InlineData("Content-Length", "1024")]
[InlineData("Transfer-Encoding", "identity")]
[InlineData("Location", "http://test")]
public async Task Response_ProvideResponse_WithHeader_SingleValue(string headerName, string headerValue)
{
// Assign
var requestMock = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp);
IResponseBuilder builder = Response.Create().WithHeader(headerName, headerValue);
// Act
var response = await builder.ProvideResponseAsync(requestMock);
// Assert
Check.That(response.Headers[headerName].ToString()).Equals(headerValue);
}
[Theory]
[InlineData("Test", new[] { "one" })]
[InlineData("Test", new[] { "a", "b" })]
public async Task Response_ProvideResponse_WithHeader_MultipleValues(string headerName, string[] headerValues)
{
// Assign
var requestMock = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp);
IResponseBuilder builder = Response.Create().WithHeader(headerName, headerValues);
// Act
var response = await builder.ProvideResponseAsync(requestMock);
// Assert
Check.That(response.Headers[headerName].ToArray()).Equals(headerValues);
}
[Fact] [Fact]
public async Task Response_ProvideResponse_WithHeaders_SingleValue() public async Task Response_ProvideResponse_WithHeaders_SingleValue()
{ {

View File

@@ -30,14 +30,14 @@ namespace WireMock.Net.Tests.ResponseBuilders
{ {
// Assign // Assign
var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/xml" } } }; var headers = new Dictionary<string, string[]> { { "Content-Type", new[] { "application/xml" } } };
var request = new RequestMessage(new UrlDetails($"{_server.Urls[0]}/{_guid}"), "POST", "::1", new BodyData { BodyAsJson = new { a = 1 } }, headers); var request = new RequestMessage(new UrlDetails($"{_server.Urls[0]}/{_guid}"), "POST", "::1", new BodyData { DetectedBodyType = BodyType.Json, BodyAsJson = new { a = 1 } }, headers);
var response = Response.Create().WithProxy(_server.Urls[0]); var response = Response.Create().WithProxy(_server.Urls[0]);
// Act // Act
var responseMessage = await response.ProvideResponseAsync(request); var responseMessage = await response.ProvideResponseAsync(request);
// Assert // Assert
Check.That(responseMessage.Body).IsEqualTo("{\"p\":42}"); Check.That(responseMessage.BodyData.BodyAsString).IsEqualTo("{\"p\":42}");
Check.That(responseMessage.StatusCode).IsEqualTo(201); Check.That(responseMessage.StatusCode).IsEqualTo(201);
Check.That(responseMessage.Headers["Content-Type"].ToString()).IsEqualTo("application/json"); Check.That(responseMessage.Headers["Content-Type"].ToString()).IsEqualTo("application/json");
} }

View File

@@ -1,29 +0,0 @@
using NFluent;
using WireMock.Models;
using WireMock.ResponseBuilders;
using Xunit;
namespace WireMock.Net.Tests
{
public class ResponseTests
{
private const string ClientIp = "::1";
[Theory]
[InlineData("Content-Length", "1024")]
[InlineData("Transfer-Encoding", "identity")]
[InlineData("Location", "http://test")]
public async void Response_Create_WithHeader(string headerName, string headerValue)
{
// Assign
var requestMock = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp);
IResponseBuilder builder = Response.Create().WithHeader(headerName, headerValue);
// Act
var response = await builder.ProvideResponseAsync(requestMock);
// Assert
Check.That(response.Headers[headerName].ToString()).Equals(headerValue);
}
}
}

View File

@@ -0,0 +1,92 @@
using NFluent;
using WireMock.Logging;
using WireMock.Models;
using WireMock.Serialization;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.Serialization
{
public class LogEntryMapperTests
{
[Fact]
public void LogEntryMapper_Map_LogEntry_Check_BodyTypeBytes()
{
// Assign
var logEntry = new LogEntry
{
RequestMessage = new RequestMessage(
new UrlDetails("http://localhost"),
"post",
"::1",
new BodyData
{
DetectedBodyType = BodyType.Bytes,
BodyAsBytes = new byte[] { 0 }
}
),
ResponseMessage = new ResponseMessage
{
BodyData = new BodyData
{
DetectedBodyType = BodyType.Bytes,
BodyAsBytes = new byte[] { 0 }
}
}
};
// Act
var result = LogEntryMapper.Map(logEntry);
// Assert
Check.That(result.Request.DetectedBodyType).IsEqualTo("Bytes");
Check.That(result.Request.DetectedBodyTypeFromContentType).IsEqualTo("None");
Check.That(result.Request.BodyAsBytes).ContainsExactly(new byte[] { 0 });
Check.That(result.Request.Body).IsNull();
Check.That(result.Request.BodyAsJson).IsNull();
Check.That(result.Response.DetectedBodyType).IsEqualTo(BodyType.Bytes);
Check.That(result.Response.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.None);
Check.That(result.Response.BodyAsBytes).ContainsExactly(new byte[] { 0 });
Check.That(result.Response.Body).IsNull();
Check.That(result.Response.BodyAsJson).IsNull();
Check.That(result.Response.BodyAsFile).IsNull();
}
[Fact]
public void LogEntryMapper_Map_LogEntry_Check_ResponseBodyTypeFile()
{
// Assign
var logEntry = new LogEntry
{
RequestMessage = new RequestMessage(new UrlDetails("http://localhost"), "get", "::1"
),
ResponseMessage = new ResponseMessage
{
BodyData = new BodyData
{
DetectedBodyType = BodyType.File,
BodyAsFile = "test"
}
}
};
// Act
var result = LogEntryMapper.Map(logEntry);
// Assert
Check.That(result.Request.DetectedBodyType).IsNull();
Check.That(result.Request.DetectedBodyTypeFromContentType).IsNull();
Check.That(result.Request.BodyAsBytes).IsNull();
Check.That(result.Request.Body).IsNull();
Check.That(result.Request.BodyAsJson).IsNull();
Check.That(result.Response.DetectedBodyType).IsEqualTo(BodyType.File);
Check.That(result.Response.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.None);
Check.That(result.Request.BodyAsBytes).IsNull();
Check.That(result.Response.Body).IsNull();
Check.That(result.Response.BodyAsJson).IsNull();
Check.That(result.Response.BodyAsFile).IsEqualTo("test");
}
}
}

View File

@@ -1,5 +1,7 @@
using Moq; using System;
using Moq;
using NFluent; using NFluent;
using WireMock.Admin.Mappings;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Serialization; using WireMock.Serialization;
using Xunit; using Xunit;
@@ -36,7 +38,7 @@ namespace WireMock.Net.Tests.Serialization
var matcherMock2 = new Mock<IStringMatcher>(); var matcherMock2 = new Mock<IStringMatcher>();
// Act // Act
var models = MatcherMapper.Map(new [] { matcherMock1.Object, matcherMock2.Object }); var models = MatcherMapper.Map(new[] { matcherMock1.Object, matcherMock2.Object });
// Assert // Assert
Check.That(models).HasSize(2); Check.That(models).HasSize(2);
@@ -73,5 +75,61 @@ namespace WireMock.Net.Tests.Serialization
// Assert // Assert
Check.That(model.IgnoreCase).Equals(true); Check.That(model.IgnoreCase).Equals(true);
} }
[Fact]
public void MatcherMapper_Map_MatcherModel_Null()
{
// Act
var result = MatcherMapper.Map((MatcherModel)null);
// Assert
Check.That(result).IsNull();
}
[Fact]
public void MatcherMapper_Map_MatcherModel_Exception()
{
// Assign
var model = new MatcherModel { Name = "test" };
// Act and Assert
Check.ThatCode(() => MatcherMapper.Map(model)).Throws<NotSupportedException>();
}
[Fact]
public void MatcherMapper_Map_MatcherModel_LinqMatcher_Pattern()
{
// Assign
var model = new MatcherModel
{
Name = "LinqMatcher",
Pattern = "p"
};
// Act
var matcher = (LinqMatcher)MatcherMapper.Map(model);
// Assert
Check.That(matcher.MatchBehaviour).IsEqualTo(MatchBehaviour.AcceptOnMatch);
Check.That(matcher.GetPatterns()).ContainsExactly("p");
}
[Fact]
public void MatcherMapper_Map_MatcherModel_LinqMatcher_Patterns()
{
// Assign
var model = new MatcherModel
{
Name = "LinqMatcher",
Patterns = new[] { "p1", "p2" }
};
// Act
var matcher = (LinqMatcher)MatcherMapper.Map(model);
// Assert
Check.That(matcher.MatchBehaviour).IsEqualTo(MatchBehaviour.AcceptOnMatch);
Check.That(matcher.GetPatterns()).ContainsExactly("p1", "p2");
}
} }
} }

View File

@@ -9,49 +9,63 @@ namespace WireMock.Net.Tests.Util
{ {
public class BodyParserTests public class BodyParserTests
{ {
[Fact] [Theory]
public async Task BodyParser_Parse_ApplicationJson() [InlineData("application/json", "{ \"x\": 1 }", BodyType.Json, BodyType.Json)]
[InlineData("application/json; charset=utf-8", "{ \"x\": 1 }", BodyType.Json, BodyType.Json)]
[InlineData("application/json; odata.metadata=minimal", "{ \"x\": 1 }", BodyType.Json, BodyType.Json)]
[InlineData("application/vnd.api+json", "{ \"x\": 1 }", BodyType.Json, BodyType.Json)]
[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 // Assign
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes("{ \"x\": 1 }")); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsJson));
// Act // Act
var body = await BodyParser.Parse(memoryStream, "application/json"); var body = await BodyParser.Parse(memoryStream, contentType);
// Assert // Assert
Check.That(body.BodyAsBytes).IsNull(); Check.That(body.BodyAsBytes).IsNotNull();
Check.That(body.BodyAsJson).IsNotNull(); Check.That(body.BodyAsJson).IsNotNull();
Check.That(body.BodyAsString).Equals("{ \"x\": 1 }"); Check.That(body.BodyAsString).Equals(bodyAsJson);
Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType);
} }
[Fact] // http://jsonapi.org/ [Theory]
public async Task BodyParser_Parse_ApplicationJsonApi() [InlineData("application/xml", "<xml>hello</xml>", BodyType.String, BodyType.String)]
[InlineData("something", "hello", BodyType.String, BodyType.Bytes)]
public async Task BodyParser_Parse_ContentTypeString(string contentType, string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType)
{ {
// Assign // Assign
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes("{ \"x\": 1 }")); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString));
// Act // Act
var body = await BodyParser.Parse(memoryStream, "application/vnd.api+json"); var body = await BodyParser.Parse(memoryStream, contentType);
// Assert // Assert
Check.That(body.BodyAsBytes).IsNull(); Check.That(body.BodyAsBytes).IsNotNull();
Check.That(body.BodyAsJson).IsNotNull();
Check.That(body.BodyAsString).Equals("{ \"x\": 1 }");
}
[Fact]
public async Task BodyParser_Parse_ApplicationXml()
{
// Assign
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes("<xml>hello</xml>"));
// Act
var body = await BodyParser.Parse(memoryStream, "application/xml; charset=UTF-8");
// Assert
Check.That(body.BodyAsBytes).IsNull();
Check.That(body.BodyAsJson).IsNull(); Check.That(body.BodyAsJson).IsNull();
Check.That(body.BodyAsString).Equals("<xml>hello</xml>"); Check.That(body.BodyAsString).Equals(bodyAsString);
Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType);
}
[Theory]
[InlineData(null, "hello", BodyType.String, BodyType.Bytes)]
public async Task BodyParser_Parse_ContentTypeIsNull(string contentType, string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType)
{
// Assign
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString));
// Act
var body = await BodyParser.Parse(memoryStream, contentType);
// Assert
Check.That(body.BodyAsBytes).IsNotNull();
Check.That(body.BodyAsJson).IsNull();
Check.That(body.BodyAsString).Equals(bodyAsString);
Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType);
} }
} }
} }

View File

@@ -14,6 +14,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Remove="FluentMockServerTests.Proxy.cs" />
<Compile Remove="FluentMockServerTests.Proxy2.cs" /> <Compile Remove="FluentMockServerTests.Proxy2.cs" />
</ItemGroup> </ItemGroup>
@@ -27,17 +28,19 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="System.Threading" Version="4.3.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.8.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.8.0" />
<PackageReference Include="MimeKitLite" Version="2.0.1" />
<PackageReference Include="Moq" Version="4.8.3" /> <PackageReference Include="Moq" Version="4.8.3" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" /> <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="NFluent" Version="2.2.0" /> <PackageReference Include="NFluent" Version="2.2.0" />
<PackageReference Include="OpenCover" Version="4.6.519" /> <PackageReference Include="OpenCover" Version="4.6.519" />
<PackageReference Include="ReportGenerator" Version="3.1.2" /> <PackageReference Include="ReportGenerator" Version="3.1.2" />
<PackageReference Include="SimMetrics.Net" Version="1.0.4" /> <PackageReference Include="SimMetrics.Net" Version="1.0.4" />
<PackageReference Include="System.Threading" Version="4.3.0" /> <PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.8.18" />
<PackageReference Include="xunit" Version="2.4.0" /> <PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.8.18" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net452'"> <ItemGroup Condition="'$(TargetFramework)' == 'net452'">