Skip to content

Migrate some tests and fix fallback for empty optional bodies #47377

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ internal static class RequestDelegateGeneratorSources
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
}

return (false, default);
return (allowEmpty, default);
}
""";

Expand Down
273 changes: 0 additions & 273 deletions src/Http/Http.Extensions/test/RequestDelegateFactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1497,249 +1497,6 @@ public async Task RequestDelegatePopulatesFromBodyParameter(Delegate action)
Assert.Equal(originalTodo.Name, ((ITodo)deserializedRequestBody!).Name);
}

public static object[][] ImplicitRawFromBodyActions
{
get
{
void TestStream(HttpContext httpContext, Stream stream)
{
var ms = new MemoryStream();
stream.CopyTo(ms);
httpContext.Items.Add("body", ms.ToArray());
}

async Task TestPipeReader(HttpContext httpContext, PipeReader reader)
{
var ms = new MemoryStream();
await reader.CopyToAsync(ms);
httpContext.Items.Add("body", ms.ToArray());
}

return new[]
{
new object[] { (Action<HttpContext, Stream>)TestStream },
new object[] { (Func<HttpContext, PipeReader, Task>)TestPipeReader }
};
}
}

public static object[][] ExplicitRawFromBodyActions
{
get
{
void TestStream(HttpContext httpContext, [FromBody] Stream stream)
{
var ms = new MemoryStream();
stream.CopyTo(ms);
httpContext.Items.Add("body", ms.ToArray());
}

async Task TestPipeReader(HttpContext httpContext, [FromBody] PipeReader reader)
{
var ms = new MemoryStream();
await reader.CopyToAsync(ms);
httpContext.Items.Add("body", ms.ToArray());
}

return new[]
{
new object[] { (Action<HttpContext, Stream>)TestStream },
new object[] { (Func<HttpContext, PipeReader, Task>)TestPipeReader }
};
}
}

[Theory]
[MemberData(nameof(ImplicitRawFromBodyActions))]
public async Task RequestDelegatePopulatesFromImplicitRawBodyParameter(Delegate action)
{
var httpContext = CreateHttpContext();

var requestBodyBytes = JsonSerializer.SerializeToUtf8Bytes(new
{
Name = "Write more tests!"
});

var stream = new MemoryStream(requestBodyBytes);
httpContext.Request.Body = stream;

httpContext.Request.Headers["Content-Length"] = stream.Length.ToString(CultureInfo.InvariantCulture);
httpContext.Features.Set<IHttpRequestBodyDetectionFeature>(new RequestBodyDetectionFeature(true));

var mock = new Mock<IServiceProvider>();
httpContext.RequestServices = mock.Object;

var factoryResult = RequestDelegateFactory.Create(action);

var requestDelegate = factoryResult.RequestDelegate;

await requestDelegate(httpContext);

Assert.Same(httpContext.Request.Body, stream);

// Assert that we can read the body from both the pipe reader and Stream after executing
httpContext.Request.Body.Position = 0;
byte[] data = new byte[requestBodyBytes.Length];
int read = await httpContext.Request.Body.ReadAsync(data.AsMemory());
Assert.Equal(read, data.Length);
Assert.Equal(requestBodyBytes, data);

httpContext.Request.Body.Position = 0;
var result = await httpContext.Request.BodyReader.ReadAsync();
Assert.Equal(requestBodyBytes.Length, result.Buffer.Length);
Assert.Equal(requestBodyBytes, result.Buffer.ToArray());
httpContext.Request.BodyReader.AdvanceTo(result.Buffer.End);

var rawRequestBody = httpContext.Items["body"];
Assert.NotNull(rawRequestBody);
Assert.Equal(requestBodyBytes, (byte[])rawRequestBody!);
}

[Theory]
[MemberData(nameof(ExplicitRawFromBodyActions))]
public async Task RequestDelegatePopulatesFromExplicitRawBodyParameter(Delegate action)
{
var httpContext = CreateHttpContext();

var requestBodyBytes = JsonSerializer.SerializeToUtf8Bytes(new
{
Name = "Write more tests!"
});

var stream = new MemoryStream(requestBodyBytes);
httpContext.Request.Body = stream;

httpContext.Request.Headers["Content-Length"] = stream.Length.ToString(CultureInfo.InvariantCulture);
httpContext.Features.Set<IHttpRequestBodyDetectionFeature>(new RequestBodyDetectionFeature(true));

var mock = new Mock<IServiceProvider>();
httpContext.RequestServices = mock.Object;

var factoryResult = RequestDelegateFactory.Create(action);

var requestDelegate = factoryResult.RequestDelegate;

await requestDelegate(httpContext);

Assert.Same(httpContext.Request.Body, stream);

// Assert that we can read the body from both the pipe reader and Stream after executing
httpContext.Request.Body.Position = 0;
byte[] data = new byte[requestBodyBytes.Length];
int read = await httpContext.Request.Body.ReadAsync(data.AsMemory());
Assert.Equal(read, data.Length);
Assert.Equal(requestBodyBytes, data);

httpContext.Request.Body.Position = 0;
var result = await httpContext.Request.BodyReader.ReadAsync();
Assert.Equal(requestBodyBytes.Length, result.Buffer.Length);
Assert.Equal(requestBodyBytes, result.Buffer.ToArray());
httpContext.Request.BodyReader.AdvanceTo(result.Buffer.End);

var rawRequestBody = httpContext.Items["body"];
Assert.NotNull(rawRequestBody);
Assert.Equal(requestBodyBytes, (byte[])rawRequestBody!);
}

[Theory]
[MemberData(nameof(ImplicitRawFromBodyActions))]
public async Task RequestDelegatePopulatesFromImplicitRawBodyParameterPipeReader(Delegate action)
{
var httpContext = CreateHttpContext();

var requestBodyBytes = JsonSerializer.SerializeToUtf8Bytes(new
{
Name = "Write more tests!"
});

var pipeReader = PipeReader.Create(new MemoryStream(requestBodyBytes));
var stream = pipeReader.AsStream();
httpContext.Features.Set<IRequestBodyPipeFeature>(new PipeRequestBodyFeature(pipeReader));
httpContext.Request.Body = stream;

httpContext.Request.Headers["Content-Length"] = requestBodyBytes.Length.ToString(CultureInfo.InvariantCulture);
httpContext.Features.Set<IHttpRequestBodyDetectionFeature>(new RequestBodyDetectionFeature(true));

var mock = new Mock<IServiceProvider>();
httpContext.RequestServices = mock.Object;

var factoryResult = RequestDelegateFactory.Create(action);

var requestDelegate = factoryResult.RequestDelegate;

await requestDelegate(httpContext);

Assert.Same(httpContext.Request.Body, stream);
Assert.Same(httpContext.Request.BodyReader, pipeReader);

// Assert that we can read the body from both the pipe reader and Stream after executing and verify that they are empty (the pipe reader isn't seekable here)
int read = await httpContext.Request.Body.ReadAsync(new byte[requestBodyBytes.Length].AsMemory());
Assert.Equal(0, read);

var result = await httpContext.Request.BodyReader.ReadAsync();
Assert.Equal(0, result.Buffer.Length);
Assert.True(result.IsCompleted);
httpContext.Request.BodyReader.AdvanceTo(result.Buffer.End);

var rawRequestBody = httpContext.Items["body"];
Assert.NotNull(rawRequestBody);
Assert.Equal(requestBodyBytes, (byte[])rawRequestBody!);
}

[Theory]
[MemberData(nameof(ExplicitRawFromBodyActions))]
public async Task RequestDelegatePopulatesFromExplicitRawBodyParameterPipeReader(Delegate action)
{
var httpContext = CreateHttpContext();

var requestBodyBytes = JsonSerializer.SerializeToUtf8Bytes(new
{
Name = "Write more tests!"
});

var pipeReader = PipeReader.Create(new MemoryStream(requestBodyBytes));
var stream = pipeReader.AsStream();
httpContext.Features.Set<IRequestBodyPipeFeature>(new PipeRequestBodyFeature(pipeReader));
httpContext.Request.Body = stream;

httpContext.Request.Headers["Content-Length"] = requestBodyBytes.Length.ToString(CultureInfo.InvariantCulture);
httpContext.Features.Set<IHttpRequestBodyDetectionFeature>(new RequestBodyDetectionFeature(true));

var mock = new Mock<IServiceProvider>();
httpContext.RequestServices = mock.Object;

var factoryResult = RequestDelegateFactory.Create(action);

var requestDelegate = factoryResult.RequestDelegate;

await requestDelegate(httpContext);

Assert.Same(httpContext.Request.Body, stream);
Assert.Same(httpContext.Request.BodyReader, pipeReader);

// Assert that we can read the body from both the pipe reader and Stream after executing and verify that they are empty (the pipe reader isn't seekable here)
int read = await httpContext.Request.Body.ReadAsync(new byte[requestBodyBytes.Length].AsMemory());
Assert.Equal(0, read);

var result = await httpContext.Request.BodyReader.ReadAsync();
Assert.Equal(0, result.Buffer.Length);
Assert.True(result.IsCompleted);
httpContext.Request.BodyReader.AdvanceTo(result.Buffer.End);

var rawRequestBody = httpContext.Items["body"];
Assert.NotNull(rawRequestBody);
Assert.Equal(requestBodyBytes, (byte[])rawRequestBody!);
}

class PipeRequestBodyFeature : IRequestBodyPipeFeature
{
public PipeRequestBodyFeature(PipeReader pipeReader)
{
Reader = pipeReader;
}
public PipeReader Reader { get; set; }
}

[Theory]
[MemberData(nameof(ExplicitFromBodyActions))]
public async Task RequestDelegateRejectsEmptyBodyGivenExplicitFromBodyParameter(Delegate action)
Expand Down Expand Up @@ -1778,31 +1535,6 @@ public async Task RequestDelegateRejectsEmptyBodyGivenImplicitFromBodyParameter(
Assert.EndsWith("but no body was provided. Did you mean to use a Service instead?", ex.Message);
}

[Fact]
public async Task RequestDelegateAllowsEmptyBodyStructGivenCorrectyConfiguredFromBodyParameter()
{
var structToBeZeroed = new BodyStruct
{
Id = 42
};

void TestAction([FromBody(AllowEmpty = true)] BodyStruct bodyStruct)
{
structToBeZeroed = bodyStruct;
}

var httpContext = CreateHttpContext();
httpContext.Request.Headers["Content-Type"] = "application/json";
httpContext.Request.Headers["Content-Length"] = "0";

var factoryResult = RequestDelegateFactory.Create(TestAction);
var requestDelegate = factoryResult.RequestDelegate;

await requestDelegate(httpContext);

Assert.Equal(default, structToBeZeroed);
}

[Fact]
public void RequestDelegateFactoryThrowsForByRefReturnTypes()
{
Expand Down Expand Up @@ -7131,11 +6863,6 @@ public override void Write(Utf8JsonWriter writer, ITodo value, JsonSerializerOpt
}
}

private struct BodyStruct
{
public int Id { get; set; }
}

private class FromRouteAttribute : Attribute, IFromRouteMetadata
{
public string? Name { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ namespace Microsoft.AspNetCore.Http.Generated
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
}

return (false, default);
return (allowEmpty, default);
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ namespace Microsoft.AspNetCore.Http.Generated
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
}

return (false, default);
return (allowEmpty, default);
}
private static Func<HttpContext, bool, ValueTask<(bool, T?)>> ResolveJsonBodyOrService<T>(IServiceProviderIsService? serviceProviderIsService = null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ namespace Microsoft.AspNetCore.Http.Generated
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
}

return (false, default);
return (allowEmpty, default);
}
private static Func<HttpContext, bool, ValueTask<(bool, T?)>> ResolveJsonBodyOrService<T>(IServiceProviderIsService? serviceProviderIsService = null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ namespace Microsoft.AspNetCore.Http.Generated
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
}

return (false, default);
return (allowEmpty, default);
}
private static Func<HttpContext, bool, ValueTask<(bool, T?)>> ResolveJsonBodyOrService<T>(IServiceProviderIsService? serviceProviderIsService = null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using System.IO.Pipelines;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
Expand Down Expand Up @@ -433,4 +434,13 @@ public RequestBodyDetectionFeature(bool canHaveBody)

public bool CanHaveBody { get; }
}

internal sealed class PipeRequestBodyFeature : IRequestBodyPipeFeature
{
public PipeRequestBodyFeature(PipeReader pipeReader)
{
Reader = pipeReader;
}
public PipeReader Reader { get; set; }
}
}
Loading