Skip to content
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

[Middleware] Move to GenericHost #23626

Merged
merged 20 commits into from
Jul 8, 2020
Merged
399 changes: 245 additions & 154 deletions src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace CorsMiddlewareWebSite
{
Expand All @@ -19,15 +21,19 @@ public void Configure(IApplicationBuilder app)
app.UseCors(policy => policy.WithOrigins("http://example.com"));
app.UseMiddleware<EchoMiddleware>();
}
public static void Main(string[] args)
public static Task Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseIISIntegration()
.UseStartup<Startup>()
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel()
.UseIISIntegration()
.UseStartup<Startup>();
})
.Build();

host.Run();
return host.RunAsync();
}
}
}
}
16 changes: 10 additions & 6 deletions src/Middleware/ConcurrencyLimiter/sample/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public void ConfigureServices(IServiceCollection services)
{
services.AddStackPolicy(options =>
{
options.MaxConcurrentRequests = 2;
options.MaxConcurrentRequests = 2;
options.RequestQueueLimit = 25;
});
}
Expand All @@ -33,13 +33,17 @@ public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
});
}

public static void Main(string[] args)
public static Task Main(string[] args)
{
new WebHostBuilder()
.UseKestrel()
.UseStartup<Startup>()
return new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel()
.UseStartup<Startup>();
})
.Build()
.Run();
.RunAsync();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Xunit;

Expand All @@ -27,15 +28,26 @@ public class DatabaseErrorPageMiddlewareTest
[Fact]
public async Task Successful_requests_pass_thru()
{
var builder = new WebHostBuilder().Configure(app => app
.UseDatabaseErrorPage()
.UseMiddleware<SuccessMiddleware>());
var server = new TestServer(builder);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app => app
.UseDatabaseErrorPage()
.UseMiddleware<SuccessMiddleware>());
}).Build();

await host.StartAsync();

var server = host.GetTestServer();

HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/");

Assert.Equal("Request Handled", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);

await host.StopAsync();
}

class SuccessMiddleware
Expand All @@ -53,15 +65,26 @@ public virtual async Task Invoke(HttpContext context)
[Fact]
public async Task Non_database_exceptions_pass_thru()
{
var builder = new WebHostBuilder().Configure(app => app
.UseDatabaseErrorPage()
.UseMiddleware<ExceptionMiddleware>());
var server = new TestServer(builder);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app => app
.UseDatabaseErrorPage()
.UseMiddleware<ExceptionMiddleware>());
}).Build();

await host.StartAsync();

var server = host.GetTestServer();

var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () =>
await server.CreateClient().GetAsync("http://localhost/"));

Assert.Equal("Exception requested from TestMiddleware", ex.Message);

await host.StopAsync();
}

class ExceptionMiddleware
Expand All @@ -82,7 +105,8 @@ public async Task Existing_database_not_using_migrations_exception_passes_thru()
{
using (var database = SqlTestStore.CreateScratch())
{
TestServer server = SetupTestServer<BloggingContext, DatabaseErrorButNoMigrationsMiddleware>(database);
using var host = await SetupServer<BloggingContext, DatabaseErrorButNoMigrationsMiddleware>(database);
using var server = host.GetTestServer();
var ex = await Assert.ThrowsAsync<DbUpdateException>(async () =>
await server.CreateClient().GetAsync("http://localhost/"));

Expand Down Expand Up @@ -114,7 +138,8 @@ public async Task Error_page_displayed_no_migrations()
{
using (var database = SqlTestStore.CreateScratch())
{
TestServer server = SetupTestServer<BloggingContext, NoMigrationsMiddleware>(database);
using var host = await SetupServer<BloggingContext, NoMigrationsMiddleware>(database);
using var server = host.GetTestServer();
HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/");

Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
Expand Down Expand Up @@ -142,13 +167,13 @@ public virtual Task Invoke(HttpContext context)
[ConditionalFact]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
public void No_exception_on_diagnostic_event_received_when_null_state()
public async Task No_exception_on_diagnostic_event_received_when_null_state()
{
using (var database = SqlTestStore.CreateScratch())
{
using (var server = SetupTestServer<BloggingContext, NoMigrationsMiddleware>(database))
using (var server = await SetupServer<BloggingContext, NoMigrationsMiddleware>(database))
{
using (var db = server.Host.Services.GetService<BloggingContext>())
using (var db = server.Services.GetService<BloggingContext>())
{
db.Blogs.Add(new Blog());

Expand All @@ -172,7 +197,8 @@ public async Task Error_page_displayed_pending_migrations()
{
using (var database = SqlTestStore.CreateScratch())
{
TestServer server = SetupTestServer<BloggingContextWithMigrations, PendingMigrationsMiddleware>(database);
using var host = await SetupServer<BloggingContextWithMigrations, PendingMigrationsMiddleware>(database);
using var server = host.GetTestServer();
HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/");

Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
Expand Down Expand Up @@ -208,7 +234,8 @@ public async Task Error_page_displayed_pending_model_changes()
{
using (var database = SqlTestStore.CreateScratch())
{
TestServer server = SetupTestServer<BloggingContextWithPendingModelChanges, PendingModelChangesMiddleware>(database);
using var host = await SetupServer<BloggingContextWithPendingModelChanges, PendingModelChangesMiddleware>(database);
using var server = host.GetTestServer();
HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/");

Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
Expand Down Expand Up @@ -245,7 +272,8 @@ public async Task Error_page_then_apply_migrations()
{
using (var database = SqlTestStore.CreateScratch())
{
TestServer server = SetupTestServer<BloggingContextWithMigrations, ApplyMigrationsMiddleware>(database);
using var host = await SetupServer<BloggingContextWithMigrations, ApplyMigrationsMiddleware>(database);
using var server = host.GetTestServer();
var client = server.CreateClient();

var expectedMigrationsEndpoint = "/ApplyDatabaseMigrations";
Expand Down Expand Up @@ -302,7 +330,11 @@ public async Task Customize_migrations_end_point()

using (var database = SqlTestStore.CreateScratch())
{
var builder = new WebHostBuilder()
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseDatabaseErrorPage(new DatabaseErrorPageOptions
Expand All @@ -317,14 +349,20 @@ public async Task Customize_migrations_end_point()
services.AddDbContext<BloggingContextWithMigrations>(
optionsBuilder => optionsBuilder.UseSqlite(database.ConnectionString));
});
var server = new TestServer(builder);
}).Build();

await host.StartAsync();

var server = host.GetTestServer();

HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/");

Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);

var content = await response.Content.ReadAsStringAsync();
Assert.Contains("req.open(\"POST\", \"" + JavaScriptEncode(migrationsEndpoint) + "\", true);", content);

await host.StopAsync();
}
}

Expand All @@ -335,16 +373,24 @@ public async Task Pass_thru_when_context_not_in_services()
{
var logProvider = new TestLoggerProvider();

var builder = new WebHostBuilder()
.Configure(app =>
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
app.UseDatabaseErrorPage();
app.UseMiddleware<ContextNotRegisteredInServicesMiddleware>();
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseDatabaseErrorPage();
app.UseMiddleware<ContextNotRegisteredInServicesMiddleware>();
#pragma warning disable CS0618 // Type or member is obsolete
app.ApplicationServices.GetService<ILoggerFactory>().AddProvider(logProvider);
app.ApplicationServices.GetService<ILoggerFactory>().AddProvider(logProvider);
#pragma warning restore CS0618 // Type or member is obsolete
});
var server = new TestServer(builder);
});
}).Build();

await host.StartAsync();

var server = host.GetTestServer();

try
{
Expand All @@ -359,6 +405,8 @@ public async Task Pass_thru_when_context_not_in_services()

Assert.Contains(logProvider.Logger.Messages.ToList(), m =>
m.StartsWith(StringsHelpers.GetResourceString("FormatDatabaseErrorPageMiddleware_ContextNotRegistered", typeof(BloggingContext))));

await host.StopAsync();
}

class ContextNotRegisteredInServicesMiddleware
Expand Down Expand Up @@ -391,7 +439,8 @@ public async Task Pass_thru_when_exception_in_logic()
{
var logProvider = new TestLoggerProvider();

var server = SetupTestServer<BloggingContextWithSnapshotThatThrows, ExceptionInLogicMiddleware>(database, logProvider);
using var host = await SetupServer<BloggingContextWithSnapshotThatThrows, ExceptionInLogicMiddleware>(database, logProvider);
using var server = host.GetTestServer();

try
{
Expand Down Expand Up @@ -430,7 +479,8 @@ public async Task Error_page_displayed_when_exception_wrapped()
{
using (var database = SqlTestStore.CreateScratch())
{
TestServer server = SetupTestServer<BloggingContext, WrappedExceptionMiddleware>(database);
using var host = await SetupServer<BloggingContext, WrappedExceptionMiddleware>(database);
using var server = host.GetTestServer();
HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/");

Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
Expand Down Expand Up @@ -461,29 +511,36 @@ public virtual Task Invoke(HttpContext context)
}
}

private static TestServer SetupTestServer<TContext, TMiddleware>(SqlTestStore database, ILoggerProvider logProvider = null)
private static async Task<IHost> SetupServer<TContext, TMiddleware>(SqlTestStore database, ILoggerProvider logProvider = null)
where TContext : DbContext
{
var builder = new WebHostBuilder()
.Configure(app =>
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
app.UseDatabaseErrorPage();
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseDatabaseErrorPage();

app.UseMiddleware<TMiddleware>();
app.UseMiddleware<TMiddleware>();

if (logProvider != null)
{
if (logProvider != null)
{
#pragma warning disable CS0618 // Type or member is obsolete
app.ApplicationServices.GetService<ILoggerFactory>().AddProvider(logProvider);
app.ApplicationServices.GetService<ILoggerFactory>().AddProvider(logProvider);
#pragma warning restore CS0618 // Type or member is obsolete
}
})
.ConfigureServices(services =>
{
services.AddDbContext<TContext>(optionsBuilder => optionsBuilder.UseSqlite(database.ConnectionString));
});
}
})
.ConfigureServices(services =>
{
services.AddDbContext<TContext>(optionsBuilder => optionsBuilder.UseSqlite(database.ConnectionString));
});
}).Build();

await host.StartAsync();

return new TestServer(builder);
return host;
}

private static UrlEncoder _urlEncoder = UrlEncoder.Default;
Expand Down
Loading