Skip to content

RDF test migration for some response test cases. #48611

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 8 commits into from
Jun 9, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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 @@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Linq;
using Microsoft.AspNetCore.Analyzers.RouteEmbeddedLanguage.Infrastructure;
using Microsoft.AspNetCore.App.Analyzers.Infrastructure;
using Microsoft.AspNetCore.Http.RequestDelegateGenerator.StaticRouteHandlerModel.Emitters;
Expand Down Expand Up @@ -91,11 +90,12 @@ private bool GetIsIResult()
// from an IResult. Typically, this would be done via an
// IEndpointMetadataProvider so we don't need to set a
// Content-Type here.
if (method.ReturnsVoid || IsIResult)
if (method.ReturnsVoid || IsIResult || HasNoResponse)
{
return null;
}
return method.ReturnType.SpecialType is SpecialType.System_String ? "text/plain" : "application/json";

return ResponseType!.SpecialType is SpecialType.System_String ? "text/plain; charset=utf-8" : "application/json";
}

public override bool Equals(object obj)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,6 @@ public static void EmitRequestHandler(this Endpoint endpoint, CodeWriter codeWri
{
return;
}
if (!endpoint.Response.HasNoResponse && endpoint.Response is { ContentType: { } contentType })
{
codeWriter.WriteLine($@"httpContext.Response.ContentType ??= ""{contentType}"";");
}
if (!endpoint.Response.HasNoResponse)
{
codeWriter.Write("var result = ");
Expand All @@ -89,6 +85,9 @@ public static void EmitRequestHandler(this Endpoint endpoint, CodeWriter codeWri
codeWriter.Write("await ");
}
codeWriter.WriteLine($"handler({endpoint.EmitArgumentList()});");

endpoint.Response.EmitHttpResponseContentType(codeWriter);

if (!endpoint.Response.HasNoResponse)
{
codeWriter.WriteLine(endpoint.Response.EmitResponseWritingCall(endpoint.IsAwaitable));
Expand All @@ -97,9 +96,31 @@ public static void EmitRequestHandler(this Endpoint endpoint, CodeWriter codeWri
{
codeWriter.WriteLine("return Task.CompletedTask;");
}

codeWriter.EndBlock(); // End handler method block
}

private static void EmitHttpResponseContentType(this EndpointResponse endpointResponse, CodeWriter codeWriter)
{
if (!endpointResponse.HasNoResponse
&& endpointResponse.ResponseType is { } responseType
&& (responseType.SpecialType == SpecialType.System_Object || responseType.SpecialType == SpecialType.System_String))
{
codeWriter.WriteLine("if (result is string)");
codeWriter.StartBlock();
codeWriter.WriteLine($@"httpContext.Response.ContentType ??= ""text/plain; charset=utf-8"";");
codeWriter.EndBlock();
codeWriter.WriteLine("else");
codeWriter.StartBlock();
codeWriter.WriteLine($@"httpContext.Response.ContentType ??= ""application/json"";");
codeWriter.EndBlock();
}
else
{
codeWriter.WriteLine($@"httpContext.Response.ContentType ??= ""text/plain"";");
}
}

private static string EmitResponseWritingCall(this EndpointResponse endpointResponse, bool isAwaitable)
{
var returnOrAwait = isAwaitable ? "await" : "return";
Expand Down
165 changes: 93 additions & 72 deletions src/Http/Http.Extensions/test/RequestDelegateFactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1188,64 +1188,109 @@ public async Task RequestDelegatePopulatesParametersFromServiceWithAndWithoutAtt
Assert.Same(myOriginalService, httpContext.Items["service"]);
}

public static IEnumerable<object[]> ChildResult
[Fact]
public async Task RequestDelegatePopulatesHttpContextParameterWithoutAttribute()
{
get
HttpContext? httpContextArgument = null;

void TestAction(HttpContext httpContext)
{
TodoChild originalTodo = new()
{
Name = "Write even more tests!",
Child = "With type hierarchies!",
};
httpContextArgument = httpContext;
}

Todo TestAction() => originalTodo;
var httpContext = CreateHttpContext();

Task<Todo> TaskTestAction() => Task.FromResult<Todo>(originalTodo);
async Task<Todo> TaskTestActionAwaited()
{
await Task.Yield();
return originalTodo;
}
var factoryResult = RequestDelegateFactory.Create(TestAction);
var requestDelegate = factoryResult.RequestDelegate;

ValueTask<Todo> ValueTaskTestAction() => ValueTask.FromResult<Todo>(originalTodo);
async ValueTask<Todo> ValueTaskTestActionAwaited()
{
await Task.Yield();
return originalTodo;
}
await requestDelegate(httpContext);

return new List<object[]>
{
new object[] { (Func<Todo>)TestAction },
new object[] { (Func<Task<Todo>>)TaskTestAction},
new object[] { (Func<Task<Todo>>)TaskTestActionAwaited},
new object[] { (Func<ValueTask<Todo>>)ValueTaskTestAction},
new object[] { (Func<ValueTask<Todo>>)ValueTaskTestActionAwaited},
};
Assert.Same(httpContext, httpContextArgument);
}

[Fact]
public async Task RequestDelegatePassHttpContextRequestAbortedAsCancellationToken()
{
CancellationToken? cancellationTokenArgument = null;

void TestAction(CancellationToken cancellationToken)
{
cancellationTokenArgument = cancellationToken;
}

using var cts = new CancellationTokenSource();
var httpContext = CreateHttpContext();
// Reset back to default HttpRequestLifetimeFeature that implements a setter for RequestAborted.
httpContext.Features.Set<IHttpRequestLifetimeFeature>(new HttpRequestLifetimeFeature());
httpContext.RequestAborted = cts.Token;

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

await requestDelegate(httpContext);

Assert.Equal(httpContext.RequestAborted, cancellationTokenArgument);
}

[Theory]
[MemberData(nameof(ChildResult))]
public async Task RequestDelegateWritesMembersFromChildTypesToJsonResponseBody(Delegate @delegate)
[Fact]
public async Task RequestDelegatePassHttpContextUserAsClaimsPrincipal()
{
ClaimsPrincipal? userArgument = null;

void TestAction(ClaimsPrincipal user)
{
userArgument = user;
}

var httpContext = CreateHttpContext();
var responseBodyStream = new MemoryStream();
httpContext.Response.Body = responseBodyStream;
httpContext.User = new ClaimsPrincipal();

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

await requestDelegate(httpContext);

var deserializedResponseBody = JsonSerializer.Deserialize<TodoChild>(responseBodyStream.ToArray(), new JsonSerializerOptions
Assert.Equal(httpContext.User, userArgument);
}

[Fact]
public async Task RequestDelegatePassHttpContextRequestAsHttpRequest()
{
HttpRequest? httpRequestArgument = null;

void TestAction(HttpRequest httpRequest)
{
PropertyNameCaseInsensitive = true
});
httpRequestArgument = httpRequest;
}

Assert.NotNull(deserializedResponseBody);
Assert.Equal("Write even more tests!", deserializedResponseBody!.Name);
Assert.Equal("With type hierarchies!", deserializedResponseBody!.Child);
var httpContext = CreateHttpContext();

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

await requestDelegate(httpContext);

Assert.Equal(httpContext.Request, httpRequestArgument);
}

[Fact]
public async Task RequestDelegatePassesHttpContextRresponseAsHttpResponse()
{
HttpResponse? httpResponseArgument = null;

void TestAction(HttpResponse httpResponse)
{
httpResponseArgument = httpResponse;
}

var httpContext = CreateHttpContext();

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

await requestDelegate(httpContext);

Assert.Equal(httpContext.Response, httpResponseArgument);
}

public static IEnumerable<object[]> PolymorphicResult
Expand Down Expand Up @@ -1285,6 +1330,9 @@ async ValueTask<JsonTodo> ValueTaskTestActionAwaited()
}
}

// NOTE: This test needs to be retained here because it tests a specific capability to create a delegate
// from the request delegate factory without passing in an instance of a service provider which
// is not something we can get at with the shared compiler/runtime test harness.
[Theory]
[MemberData(nameof(PolymorphicResult))]
public async Task RequestDelegateWritesMembersFromChildTypesToJsonResponseBody_WithJsonPolymorphicOptions(Delegate @delegate)
Expand Down Expand Up @@ -1312,33 +1360,11 @@ public async Task RequestDelegateWritesMembersFromChildTypesToJsonResponseBody_W
Assert.Equal("With type hierarchies!", deserializedResponseBody!.Child);
}

[Theory]
[MemberData(nameof(PolymorphicResult))]
public async Task RequestDelegateWritesMembersFromChildTypesToJsonResponseBody_WithJsonPolymorphicOptionsAndConfiguredJsonOptions(Delegate @delegate)
{
var httpContext = CreateHttpContext();
httpContext.RequestServices = new ServiceCollection()
.AddSingleton(LoggerFactory)
.AddSingleton(Options.Create(new JsonOptions()))
.BuildServiceProvider();
var responseBodyStream = new MemoryStream();
httpContext.Response.Body = responseBodyStream;

var factoryResult = RequestDelegateFactory.Create(@delegate, new RequestDelegateFactoryOptions { ServiceProvider = httpContext.RequestServices });
var requestDelegate = factoryResult.RequestDelegate;

await requestDelegate(httpContext);

var deserializedResponseBody = JsonSerializer.Deserialize<JsonTodoChild>(responseBodyStream.ToArray(), new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});

Assert.NotNull(deserializedResponseBody);
Assert.Equal("Write even more tests!", deserializedResponseBody!.Name);
Assert.Equal("With type hierarchies!", deserializedResponseBody!.Child);
}

// NOTE: This test needs to be retained here because it tests a specific capability to create a delegate
// from the request delegate factory without passing in an instance of a service provider which
// is not something we can get at with the shared compiler/runtime test harness. There is a variant
// of this test that has been added to the shared test harness to make sure that we do write the
// type discriminator.
[Theory]
[MemberData(nameof(PolymorphicResult))]
public async Task RequestDelegateWritesJsonTypeDiscriminatorToJsonResponseBody_WithJsonPolymorphicOptions(Delegate @delegate)
Expand Down Expand Up @@ -3419,11 +3445,6 @@ private class Todo : ITodo
public bool IsComplete { get; set; }
}

private class TodoChild : Todo
{
public string? Child { get; set; }
}

private class JsonTodoChild : JsonTodo
{
public string? Child { get; set; }
Expand Down
Loading