This commit is contained in:
Stef Heyenrath
2019-10-22 18:53:30 +00:00
committed by GitHub
parent 9d2963632e
commit 3250604b5a
16 changed files with 250 additions and 175 deletions

View File

@@ -56,6 +56,7 @@ namespace WireMock.Net.StandAlone
MaxRequestLogCount = parser.GetIntValue("MaxRequestLogCount"), MaxRequestLogCount = parser.GetIntValue("MaxRequestLogCount"),
RequestLogExpirationDuration = parser.GetIntValue("RequestLogExpirationDuration"), RequestLogExpirationDuration = parser.GetIntValue("RequestLogExpirationDuration"),
AllowCSharpCodeMatcher = parser.GetBoolValue("AllowCSharpCodeMatcher"), AllowCSharpCodeMatcher = parser.GetBoolValue("AllowCSharpCodeMatcher"),
AllowBodyForAllHttpMethods = parser.GetBoolValue("AllowBodyForAllHttpMethods")
}; };
if (logger != null) if (logger != null)

View File

@@ -24,5 +24,10 @@
/// Gets or sets the MaxRequestLog count. /// Gets or sets the MaxRequestLog count.
/// </summary> /// </summary>
public int? MaxRequestLogCount { get; set; } public int? MaxRequestLogCount { get; set; }
/// <summary>
/// Gets or sets wether to allow a body for all HTTP methods.
/// </summary>
public bool? AllowBodyForAllHttpMethods { get; set; }
} }
} }

View File

@@ -20,7 +20,7 @@ namespace WireMock.Owin
IStringMatcher AuthorizationMatcher { get; set; } IStringMatcher AuthorizationMatcher { get; set; }
bool AllowPartialMapping { get; set; } bool? AllowPartialMapping { get; set; }
ConcurrentDictionary<Guid, IMapping> Mappings { get; } ConcurrentDictionary<Guid, IMapping> Mappings { get; }
@@ -37,5 +37,7 @@ namespace WireMock.Owin
Action<IAppBuilder> PostWireMockMiddlewareInit { get; set; } Action<IAppBuilder> PostWireMockMiddlewareInit { get; set; }
IFileSystemHandler FileSystemHandler { get; set; } IFileSystemHandler FileSystemHandler { get; set; }
bool? AllowBodyForAllHttpMethods { get; set; }
} }
} }

View File

@@ -16,7 +16,8 @@ namespace WireMock.Owin.Mappers
/// MapAsync IRequest to RequestMessage /// MapAsync IRequest to RequestMessage
/// </summary> /// </summary>
/// <param name="request">The OwinRequest/HttpRequest</param> /// <param name="request">The OwinRequest/HttpRequest</param>
/// <param name="options">The WireMockMiddlewareOptions</param>
/// <returns>RequestMessage</returns> /// <returns>RequestMessage</returns>
Task<RequestMessage> MapAsync(IRequest request); Task<RequestMessage> MapAsync(IRequest request, IWireMockMiddlewareOptions options);
} }
} }

View File

@@ -20,7 +20,7 @@ namespace WireMock.Owin.Mappers
internal class OwinRequestMapper : IOwinRequestMapper internal class OwinRequestMapper : IOwinRequestMapper
{ {
/// <inheritdoc cref="IOwinRequestMapper.MapAsync"/> /// <inheritdoc cref="IOwinRequestMapper.MapAsync"/>
public async Task<RequestMessage> MapAsync(IRequest request) public async Task<RequestMessage> MapAsync(IRequest request, IWireMockMiddlewareOptions options)
{ {
(UrlDetails urldetails, string clientIP) = ParseRequest(request); (UrlDetails urldetails, string clientIP) = ParseRequest(request);
@@ -47,7 +47,7 @@ namespace WireMock.Owin.Mappers
} }
BodyData body = null; BodyData body = null;
if (request.Body != null && BodyParser.ShouldParseBody(method)) if (request.Body != null && BodyParser.ShouldParseBody(method, options.AllowBodyForAllHttpMethods == true))
{ {
body = await BodyParser.Parse(request.Body, request.ContentType); body = await BodyParser.Parse(request.Body, request.ContentType);
} }

View File

@@ -37,7 +37,7 @@ namespace WireMock.Owin
} }
} }
if (_options.AllowPartialMapping) if (_options.AllowPartialMapping == true)
{ {
var partialMappings = mappings var partialMappings = mappings
.Where(pm => (pm.Mapping.IsAdminInterface && pm.RequestMatchResult.IsPerfectMatch) || !pm.Mapping.IsAdminInterface) .Where(pm => (pm.Mapping.IsAdminInterface && pm.RequestMatchResult.IsPerfectMatch) || !pm.Mapping.IsAdminInterface)

View File

@@ -69,7 +69,7 @@ namespace WireMock.Owin
private async Task InvokeInternal(IContext ctx) private async Task InvokeInternal(IContext ctx)
{ {
var request = await _requestMapper.MapAsync(ctx.Request); var request = await _requestMapper.MapAsync(ctx.Request, _options);
bool logRequest = false; bool logRequest = false;
ResponseMessage response = null; ResponseMessage response = null;

View File

@@ -21,7 +21,7 @@ namespace WireMock.Owin
public IStringMatcher AuthorizationMatcher { get; set; } public IStringMatcher AuthorizationMatcher { get; set; }
public bool AllowPartialMapping { get; set; } public bool? AllowPartialMapping { get; set; }
public ConcurrentDictionary<Guid, IMapping> Mappings { get; } = new ConcurrentDictionary<Guid, IMapping>(); public ConcurrentDictionary<Guid, IMapping> Mappings { get; } = new ConcurrentDictionary<Guid, IMapping>();
@@ -39,5 +39,8 @@ namespace WireMock.Owin
/// <inheritdoc cref="IWireMockMiddlewareOptions.FileSystemHandler"/> /// <inheritdoc cref="IWireMockMiddlewareOptions.FileSystemHandler"/>
public IFileSystemHandler FileSystemHandler { get; set; } public IFileSystemHandler FileSystemHandler { get; set; }
/// <inheritdoc cref="IWireMockMiddlewareOptions.AllowBodyForAllHttpMethods"/>
public bool? AllowBodyForAllHttpMethods { get; set; }
} }
} }

View File

@@ -339,7 +339,8 @@ namespace WireMock.Server
AllowPartialMapping = _options.AllowPartialMapping, AllowPartialMapping = _options.AllowPartialMapping,
MaxRequestLogCount = _options.MaxRequestLogCount, MaxRequestLogCount = _options.MaxRequestLogCount,
RequestLogExpirationDuration = _options.RequestLogExpirationDuration, RequestLogExpirationDuration = _options.RequestLogExpirationDuration,
GlobalProcessingDelay = (int?)_options.RequestProcessingDelay?.TotalMilliseconds GlobalProcessingDelay = (int?)_options.RequestProcessingDelay?.TotalMilliseconds,
AllowBodyForAllHttpMethods = _options.AllowBodyForAllHttpMethods
}; };
return ToJson(model); return ToJson(model);
@@ -361,6 +362,11 @@ namespace WireMock.Server
_options.RequestProcessingDelay = TimeSpan.FromMilliseconds(settings.GlobalProcessingDelay.Value); _options.RequestProcessingDelay = TimeSpan.FromMilliseconds(settings.GlobalProcessingDelay.Value);
} }
if (settings.AllowBodyForAllHttpMethods != null)
{
_options.AllowBodyForAllHttpMethods = settings.AllowBodyForAllHttpMethods.Value;
}
return ResponseMessageBuilder.Create("Settings updated"); return ResponseMessageBuilder.Create("Settings updated");
} }
#endregion Settings #endregion Settings

View File

@@ -1,11 +1,11 @@
using JetBrains.Annotations;
using Newtonsoft.Json;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using JetBrains.Annotations;
using Newtonsoft.Json;
using WireMock.Admin.Mappings; using WireMock.Admin.Mappings;
using WireMock.Exceptions; using WireMock.Exceptions;
using WireMock.Handlers; using WireMock.Handlers;
@@ -257,6 +257,12 @@ namespace WireMock.Server
} }
} }
if (settings.AllowBodyForAllHttpMethods == true)
{
_options.AllowBodyForAllHttpMethods = _settings.AllowBodyForAllHttpMethods;
_settings.Logger.Info("AllowBodyForAllHttpMethods is set to {0}", _settings.AllowBodyForAllHttpMethods == true);
}
if (settings.AllowPartialMapping == true) if (settings.AllowPartialMapping == true)
{ {
AllowPartialMapping(); AllowPartialMapping();

View File

@@ -94,5 +94,9 @@ namespace WireMock.Settings
/// <inheritdoc cref="IFluentMockServerSettings.AllowCSharpCodeMatcher"/> /// <inheritdoc cref="IFluentMockServerSettings.AllowCSharpCodeMatcher"/>
[PublicAPI] [PublicAPI]
public bool? AllowCSharpCodeMatcher { get; set; } public bool? AllowCSharpCodeMatcher { get; set; }
/// <inheritdoc cref="IFluentMockServerSettings.AllowBodyForAllHttpMethods"/>
[PublicAPI]
public bool? AllowBodyForAllHttpMethods { get; set; }
} }
} }

View File

@@ -124,6 +124,13 @@ namespace WireMock.Settings
/// <summary> /// <summary>
/// Allow the usage of CSharpCodeMatcher (default is not allowed). /// Allow the usage of CSharpCodeMatcher (default is not allowed).
/// </summary> /// </summary>
[PublicAPI]
bool? AllowCSharpCodeMatcher { get; set; } bool? AllowCSharpCodeMatcher { get; set; }
/// <summary>
/// Allow a Body for all HTTP Methods. (default set to false).
/// </summary>
[PublicAPI]
bool? AllowBodyForAllHttpMethods { get; set; }
} }
} }

View File

@@ -59,14 +59,19 @@ namespace WireMock.Util
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings { DateParseHandling = DateParseHandling.None }; private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings { DateParseHandling = DateParseHandling.None };
public static bool ShouldParseBody([CanBeNull] string method) public static bool ShouldParseBody([CanBeNull] string httpMethod, bool allowBodyForAllHttpMethods)
{ {
if (string.IsNullOrEmpty(method)) if (string.IsNullOrEmpty(httpMethod))
{ {
return false; return false;
} }
if (BodyAllowedForMethods.TryGetValue(method.ToUpper(), out bool allowed)) if (allowBodyForAllHttpMethods)
{
return true;
}
if (BodyAllowedForMethods.TryGetValue(httpMethod.ToUpper(), out bool allowed))
{ {
return allowed; return allowed;
} }

View File

@@ -116,7 +116,25 @@ namespace WireMock.Net.Tests
// Assert // Assert
var options = server.GetPrivateFieldValue<IWireMockMiddlewareOptions>("_options"); var options = server.GetPrivateFieldValue<IWireMockMiddlewareOptions>("_options");
Check.That(options.AllowPartialMapping).IsTrue(); Check.That(options.AllowPartialMapping).Equals(true);
// Verify
_loggerMock.Verify(l => l.Info(It.IsAny<string>(), It.IsAny<bool>()));
}
[Fact]
public void FluentMockServer_FluentMockServerSettings_AllowBodyForAllHttpMethods()
{
// Assign and Act
var server = FluentMockServer.Start(new FluentMockServerSettings
{
Logger = _loggerMock.Object,
AllowBodyForAllHttpMethods = true
});
// Assert
var options = server.GetPrivateFieldValue<IWireMockMiddlewareOptions>("_options");
Check.That(options.AllowBodyForAllHttpMethods).Equals(true);
// Verify // Verify
_loggerMock.Verify(l => l.Info(It.IsAny<string>(), It.IsAny<bool>())); _loggerMock.Verify(l => l.Info(It.IsAny<string>(), It.IsAny<bool>()));

View File

@@ -52,7 +52,7 @@ namespace WireMock.Net.Tests.Owin
_requestMapperMock = new Mock<IOwinRequestMapper>(); _requestMapperMock = new Mock<IOwinRequestMapper>();
_requestMapperMock.SetupAllProperties(); _requestMapperMock.SetupAllProperties();
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1"); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
_requestMapperMock.Setup(m => m.MapAsync(It.IsAny<IRequest>())).ReturnsAsync(request); _requestMapperMock.Setup(m => m.MapAsync(It.IsAny<IRequest>(), It.IsAny<IWireMockMiddlewareOptions>())).ReturnsAsync(request);
_responseMapperMock = new Mock<IOwinResponseMapper>(); _responseMapperMock = new Mock<IOwinResponseMapper>();
_responseMapperMock.SetupAllProperties(); _responseMapperMock.SetupAllProperties();
@@ -87,7 +87,7 @@ namespace WireMock.Net.Tests.Owin
{ {
// Assign // Assign
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1", null, new Dictionary<string, string[]>()); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1", null, new Dictionary<string, string[]>());
_requestMapperMock.Setup(m => m.MapAsync(It.IsAny<IRequest>())).ReturnsAsync(request); _requestMapperMock.Setup(m => m.MapAsync(It.IsAny<IRequest>(), It.IsAny<IWireMockMiddlewareOptions>())).ReturnsAsync(request);
_optionsMock.SetupGet(o => o.AuthorizationMatcher).Returns(new ExactMatcher()); _optionsMock.SetupGet(o => o.AuthorizationMatcher).Returns(new ExactMatcher());
_mappingMock.SetupGet(m => m.IsAdminInterface).Returns(true); _mappingMock.SetupGet(m => m.IsAdminInterface).Returns(true);
@@ -108,7 +108,7 @@ namespace WireMock.Net.Tests.Owin
{ {
// Assign // Assign
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1", null, new Dictionary<string, string[]> { { "h", new[] { "x" } } }); var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1", null, new Dictionary<string, string[]> { { "h", new[] { "x" } } });
_requestMapperMock.Setup(m => m.MapAsync(It.IsAny<IRequest>())).ReturnsAsync(request); _requestMapperMock.Setup(m => m.MapAsync(It.IsAny<IRequest>(), It.IsAny<IWireMockMiddlewareOptions>())).ReturnsAsync(request);
_optionsMock.SetupGet(o => o.AuthorizationMatcher).Returns(new ExactMatcher()); _optionsMock.SetupGet(o => o.AuthorizationMatcher).Returns(new ExactMatcher());
_mappingMock.SetupGet(m => m.IsAdminInterface).Returns(true); _mappingMock.SetupGet(m => m.IsAdminInterface).Returns(true);

View File

@@ -1,168 +1,185 @@
using NFluent; using NFluent;
using System.IO; using System.IO;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WireMock.Util; using WireMock.Util;
using Xunit; using Xunit;
namespace WireMock.Net.Tests.Util namespace WireMock.Net.Tests.Util
{ {
public class BodyParserTests public class BodyParserTests
{ {
[Theory] [Theory]
[InlineData("application/json", "{ \"x\": 1 }", BodyType.Json, BodyType.Json)] [InlineData("application/json", "{ \"x\": 1 }", BodyType.Json, BodyType.Json)]
[InlineData("application/json; charset=utf-8", "{ \"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/json; odata.metadata=minimal", "{ \"x\": 1 }", BodyType.Json, BodyType.Json)]
[InlineData("application/vnd.api+json", "{ \"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)] [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) public async Task BodyParser_Parse_ContentTypeJson(string contentType, string bodyAsJson, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType)
{ {
// Arrange // Arrange
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsJson)); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsJson));
// Act // Act
var body = await BodyParser.Parse(memoryStream, contentType); var body = await BodyParser.Parse(memoryStream, contentType);
// Assert // Assert
Check.That(body.BodyAsBytes).IsNotNull(); Check.That(body.BodyAsBytes).IsNotNull();
Check.That(body.BodyAsJson).IsNotNull(); Check.That(body.BodyAsJson).IsNotNull();
Check.That(body.BodyAsString).Equals(bodyAsJson); Check.That(body.BodyAsString).Equals(bodyAsJson);
Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType); Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType);
} }
[Theory] [Theory]
[InlineData("application/xml", "<xml>hello</xml>", BodyType.String, BodyType.String)] [InlineData("application/xml", "<xml>hello</xml>", BodyType.String, BodyType.String)]
[InlineData("something", "hello", BodyType.String, BodyType.Bytes)] [InlineData("something", "hello", BodyType.String, BodyType.Bytes)]
public async Task BodyParser_Parse_ContentTypeString(string contentType, string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType) public async Task BodyParser_Parse_ContentTypeString(string contentType, string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType)
{ {
// Arrange // Arrange
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString)); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString));
// Act // Act
var body = await BodyParser.Parse(memoryStream, contentType); var body = await BodyParser.Parse(memoryStream, contentType);
// Assert // Assert
Check.That(body.BodyAsBytes).IsNotNull(); Check.That(body.BodyAsBytes).IsNotNull();
Check.That(body.BodyAsJson).IsNull(); Check.That(body.BodyAsJson).IsNull();
Check.That(body.BodyAsString).Equals(bodyAsString); Check.That(body.BodyAsString).Equals(bodyAsString);
Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType); Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType);
} }
[Theory] [Theory]
[InlineData(new byte[] {34, 97, 34}, BodyType.Json)] [InlineData(new byte[] {34, 97, 34}, BodyType.Json)]
[InlineData(new byte[] {97}, BodyType.String)] [InlineData(new byte[] {97}, BodyType.String)]
[InlineData(new byte[] {0xFF, 0xD8, 0xFF, 0xE0}, BodyType.Bytes)] [InlineData(new byte[] {0xFF, 0xD8, 0xFF, 0xE0}, BodyType.Bytes)]
public async Task BodyParser_Parse_DetectedBodyType(byte[] content, BodyType detectedBodyType) public async Task BodyParser_Parse_DetectedBodyType(byte[] content, BodyType detectedBodyType)
{ {
// arrange // arrange
var memoryStream = new MemoryStream(content); var memoryStream = new MemoryStream(content);
// act // act
var body = await BodyParser.Parse(memoryStream, null); var body = await BodyParser.Parse(memoryStream, null);
// assert // assert
Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
} }
[Fact] [Fact]
public async Task BodyParser_Parse_WithUTF8EncodingAndContentTypeMultipart_DetectedBodyTypeEqualsString() public async Task BodyParser_Parse_WithUTF8EncodingAndContentTypeMultipart_DetectedBodyTypeEqualsString()
{ {
// Arrange // Arrange
string contentType = "multipart/form-data"; string contentType = "multipart/form-data";
string body = @" string body = @"
-----------------------------9051914041544843365972754266 -----------------------------9051914041544843365972754266
Content-Disposition: form-data; name=""text"" Content-Disposition: form-data; name=""text""
text default text default
-----------------------------9051914041544843365972754266 -----------------------------9051914041544843365972754266
Content-Disposition: form-data; name=""file1""; filename=""a.txt"" Content-Disposition: form-data; name=""file1""; filename=""a.txt""
Content-Type: text/plain Content-Type: text/plain
Content of a txt Content of a txt
-----------------------------9051914041544843365972754266 -----------------------------9051914041544843365972754266
Content-Disposition: form-data; name=""file2""; filename=""a.html"" Content-Disposition: form-data; name=""file2""; filename=""a.html""
Content-Type: text/html Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title> <!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--"; -----------------------------9051914041544843365972754266--";
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(body)); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(body));
// Act // Act
var result = await BodyParser.Parse(memoryStream, contentType); var result = await BodyParser.Parse(memoryStream, contentType);
// Assert // Assert
Check.That(result.DetectedBodyType).IsEqualTo(BodyType.String); Check.That(result.DetectedBodyType).IsEqualTo(BodyType.String);
Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart); Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart);
Check.That(result.BodyAsBytes).IsNotNull(); Check.That(result.BodyAsBytes).IsNotNull();
Check.That(result.BodyAsJson).IsNull(); Check.That(result.BodyAsJson).IsNull();
Check.That(result.BodyAsString).IsNotNull(); Check.That(result.BodyAsString).IsNotNull();
} }
[Fact] [Fact]
public async Task BodyParser_Parse_WithUTF16EncodingAndContentTypeMultipart_DetectedBodyTypeEqualsString() public async Task BodyParser_Parse_WithUTF16EncodingAndContentTypeMultipart_DetectedBodyTypeEqualsString()
{ {
// Arrange // Arrange
string contentType = "multipart/form-data"; string contentType = "multipart/form-data";
string body = char.ConvertFromUtf32(0x1D161); //U+1D161 = MUSICAL SYMBOL SIXTEENTH NOTE string body = char.ConvertFromUtf32(0x1D161); //U+1D161 = MUSICAL SYMBOL SIXTEENTH NOTE
var memoryStream = new MemoryStream(Encoding.UTF32.GetBytes(body)); var memoryStream = new MemoryStream(Encoding.UTF32.GetBytes(body));
// Act // Act
var result = await BodyParser.Parse(memoryStream, contentType); var result = await BodyParser.Parse(memoryStream, contentType);
// Assert // Assert
Check.That(result.DetectedBodyType).IsEqualTo(BodyType.Bytes); Check.That(result.DetectedBodyType).IsEqualTo(BodyType.Bytes);
Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart); Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart);
Check.That(result.BodyAsBytes).IsNotNull(); Check.That(result.BodyAsBytes).IsNotNull();
Check.That(result.BodyAsJson).IsNull(); Check.That(result.BodyAsJson).IsNull();
Check.That(result.BodyAsString).IsNull(); Check.That(result.BodyAsString).IsNull();
} }
[Theory] [Theory]
[InlineData(null, "hello", BodyType.String, BodyType.Bytes)] [InlineData(null, "hello", BodyType.String, BodyType.Bytes)]
public async Task BodyParser_Parse_ContentTypeIsNull(string contentType, string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType) public async Task BodyParser_Parse_ContentTypeIsNull(string contentType, string bodyAsString, BodyType detectedBodyType, BodyType detectedBodyTypeFromContentType)
{ {
// Arrange // Arrange
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString)); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(bodyAsString));
// Act // Act
var body = await BodyParser.Parse(memoryStream, contentType); var body = await BodyParser.Parse(memoryStream, contentType);
// Assert // Assert
Check.That(body.BodyAsBytes).IsNotNull(); Check.That(body.BodyAsBytes).IsNotNull();
Check.That(body.BodyAsJson).IsNull(); Check.That(body.BodyAsJson).IsNull();
Check.That(body.BodyAsString).Equals(bodyAsString); Check.That(body.BodyAsString).Equals(bodyAsString);
Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType); Check.That(body.DetectedBodyType).IsEqualTo(detectedBodyType);
Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType); Check.That(body.DetectedBodyTypeFromContentType).IsEqualTo(detectedBodyTypeFromContentType);
} }
[Theory] [Theory]
[InlineData("HEAD", false)] [InlineData("HEAD", false)]
[InlineData("GET", false)] [InlineData("GET", false)]
[InlineData("PUT", true)] [InlineData("PUT", true)]
[InlineData("POST", true)] [InlineData("POST", true)]
[InlineData("DELETE", false)] [InlineData("DELETE", false)]
[InlineData("TRACE", false)] [InlineData("TRACE", false)]
[InlineData("OPTIONS", true)] [InlineData("OPTIONS", true)]
[InlineData("CONNECT", false)] [InlineData("CONNECT", false)]
[InlineData("PATCH", true)] [InlineData("PATCH", true)]
public void BodyParser_ShouldParseBody_ExpectedResultForKnownMethods(string method, bool resultShouldBe) public void BodyParser_ShouldParseBodyForMethodAndAllowAllIsFalse_ExpectedResultForKnownMethods(string method, bool resultShouldBe)
{ {
Check.That(BodyParser.ShouldParseBody(method)).Equals(resultShouldBe); Check.That(BodyParser.ShouldParseBody(method, false)).Equals(resultShouldBe);
} }
[Theory] [Theory]
[InlineData("REPORT")] [InlineData("HEAD")]
[InlineData("SOME-UNKNOWN-METHOD")] [InlineData("GET")]
[InlineData("PUT")]
[InlineData("POST")]
[InlineData("DELETE")]
[InlineData("TRACE")]
[InlineData("OPTIONS")]
[InlineData("CONNECT")]
[InlineData("PATCH")]
[InlineData("REPORT")]
[InlineData("SOME-UNKNOWN-METHOD")]
public void BodyParser_ShouldParseBodyForMethodAndAllowAllIsTrue_ExpectedResultShouldBeTrue(string method)
{
Check.That(BodyParser.ShouldParseBody(method, true)).IsTrue();
}
[Theory]
[InlineData("REPORT")]
[InlineData("SOME-UNKNOWN-METHOD")]
public void BodyParser_ShouldParseBody_DefaultIsTrueForUnknownMethods(string method) public void BodyParser_ShouldParseBody_DefaultIsTrueForUnknownMethods(string method)
{ {
Check.That(BodyParser.ShouldParseBody(method)).IsTrue(); Check.That(BodyParser.ShouldParseBody(method, false)).IsTrue();
} }
} }
} }