From fdb4e448b7d51485edc1015c17b630b0fdd02cae Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:02:07 -0700 Subject: [PATCH 01/20] cors --- .../test/UnitTests/CorsMiddlewareTests.cs | 399 +++++++++++------- .../CorsMiddlewareWebSite/Startup.cs | 20 +- 2 files changed, 258 insertions(+), 161 deletions(-) diff --git a/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs b/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs index 4b53a43a5be1..3e9db89da246 100644 --- a/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs +++ b/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; @@ -27,20 +28,27 @@ public class CorsMiddlewareTests public async Task CorsRequest_MatchesPolicy_OnCaseInsensitiveAccessControlRequestMethod(string accessControlRequestMethod) { // Arrange - var hostBuilder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors(builder => - builder.WithOrigins(OriginUrl) - .WithMethods("PUT")); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => services.AddCors()); + app.UseCors(builder => + builder.WithOrigins(OriginUrl) + .WithMethods("PUT")); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => services.AddCors()); + }).Build(); - using (var server = new TestServer(hostBuilder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { // Act // Actual request. @@ -54,28 +62,37 @@ public async Task CorsRequest_MatchesPolicy_OnCaseInsensitiveAccessControlReques Assert.Equal("Cross origin response", await response.Content.ReadAsStringAsync()); Assert.Equal(OriginUrl, response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault()); } + + await host.StopAsync(); } [Fact] public async Task CorsRequest_MatchPolicy_SetsResponseHeaders() { // Arrange - var hostBuilder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors(builder => - builder.WithOrigins(OriginUrl) - .WithMethods("PUT") - .WithHeaders("Header1") - .WithExposedHeaders("AllowedHeader")); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => services.AddCors()); + app.UseCors(builder => + builder.WithOrigins(OriginUrl) + .WithMethods("PUT") + .WithHeaders("Header1") + .WithExposedHeaders("AllowedHeader")); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => services.AddCors()); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(hostBuilder)) + using (var server = host.GetTestServer()) { // Act // Actual request. @@ -90,6 +107,8 @@ public async Task CorsRequest_MatchPolicy_SetsResponseHeaders() Assert.Equal(OriginUrl, response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault()); Assert.Equal("AllowedHeader", response.Headers.GetValues(CorsConstants.AccessControlExposeHeaders).FirstOrDefault()); } + + await host.StopAsync(); } [Theory] @@ -102,24 +121,31 @@ public async Task PreFlight_MatchesPolicy_OnCaseInsensitiveOptionsMethod(string policy.Origins.Add(OriginUrl); policy.Methods.Add("PUT"); - var hostBuilder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors("customPolicy"); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => - { - services.AddCors(options => + app.UseCors("customPolicy"); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => { - options.AddPolicy("customPolicy", policy); + services.AddCors(options => + { + options.AddPolicy("customPolicy", policy); + }); }); - }); + }).Build(); - using (var server = new TestServer(hostBuilder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { // Act // Preflight request. @@ -132,6 +158,8 @@ public async Task PreFlight_MatchesPolicy_OnCaseInsensitiveOptionsMethod(string Assert.Single(response.Headers); Assert.Equal(OriginUrl, response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault()); } + + await host.StopAsync(); } [Fact] @@ -144,24 +172,31 @@ public async Task PreFlight_MatchesPolicy_SetsResponseHeaders() policy.Headers.Add("Header1"); policy.ExposedHeaders.Add("AllowedHeader"); - var hostBuilder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors("customPolicy"); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => - { - services.AddCors(options => + app.UseCors("customPolicy"); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => { - options.AddPolicy("customPolicy", policy); + services.AddCors(options => + { + options.AddPolicy("customPolicy", policy); + }); }); - }); + }).Build(); - using (var server = new TestServer(hostBuilder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { // Act // Preflight request. @@ -190,6 +225,8 @@ public async Task PreFlight_MatchesPolicy_SetsResponseHeaders() Assert.Equal(new[] { OriginUrl }, kvp.Value); }); } + + await host.StopAsync(); } [Fact] @@ -202,24 +239,31 @@ public async Task PreFlight_WithCredentialsAllowed_ReflectsRequestHeaders() .AllowCredentials() .Build(); - var hostBuilder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors("customPolicy"); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => - { - services.AddCors(options => + app.UseCors("customPolicy"); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => { - options.AddPolicy("customPolicy", policy); + services.AddCors(options => + { + options.AddPolicy("customPolicy", policy); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(hostBuilder)) + using (var server = host.GetTestServer()) { // Act // Preflight request. @@ -254,28 +298,37 @@ public async Task PreFlight_WithCredentialsAllowed_ReflectsRequestHeaders() Assert.Equal(new[] { OriginUrl }, kvp.Value); }); } + + await host.StopAsync(); } [Fact] public async Task PreFlightRequest_DoesNotMatchPolicy_SetsResponseHeadersAndReturnsNoContent() { // Arrange - var hostBuilder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors(builder => - builder.WithOrigins(OriginUrl) - .WithMethods("PUT") - .WithHeaders("Header1") - .WithExposedHeaders("AllowedHeader")); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => services.AddCors()); + app.UseCors(builder => + builder.WithOrigins(OriginUrl) + .WithMethods("PUT") + .WithHeaders("Header1") + .WithExposedHeaders("AllowedHeader")); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => services.AddCors()); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(hostBuilder)) + using (var server = host.GetTestServer()) { // Act // Preflight request. @@ -288,28 +341,37 @@ public async Task PreFlightRequest_DoesNotMatchPolicy_SetsResponseHeadersAndRetu Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Empty(response.Headers); } + + await host.StartAsync(); } [Fact] public async Task CorsRequest_DoesNotMatchPolicy_DoesNotSetHeaders() { // Arrange - var hostBuilder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors(builder => - builder.WithOrigins(OriginUrl) - .WithMethods("PUT") - .WithHeaders("Header1") - .WithExposedHeaders("AllowedHeader")); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => services.AddCors()); + app.UseCors(builder => + builder.WithOrigins(OriginUrl) + .WithMethods("PUT") + .WithHeaders("Header1") + .WithExposedHeaders("AllowedHeader")); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => services.AddCors()); + }).Build(); - using (var server = new TestServer(hostBuilder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { // Act // Actual request. @@ -321,6 +383,8 @@ public async Task CorsRequest_DoesNotMatchPolicy_DoesNotSetHeaders() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Empty(response.Headers); } + + await host.StopAsync(); } [Fact] @@ -387,38 +451,45 @@ public async Task DoesNotSetHeaders_ForNoPolicy() public async Task PreFlight_MatchesDefaultPolicy_SetsResponseHeaders() { // Arrange - var hostBuilder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => - { - services.AddCors(options => - { - options.AddDefaultPolicy(policyBuilder => + app.UseCors(); + app.Run(async context => { - policyBuilder - .WithOrigins(OriginUrl) - .WithMethods("PUT") - .WithHeaders("Header1") - .WithExposedHeaders("AllowedHeader") - .Build(); + await context.Response.WriteAsync("Cross origin response"); }); - options.AddPolicy("policy2", policyBuilder => + }) + .ConfigureServices(services => + { + services.AddCors(options => { - policyBuilder - .WithOrigins("http://test.example.com") - .Build(); + options.AddDefaultPolicy(policyBuilder => + { + policyBuilder + .WithOrigins(OriginUrl) + .WithMethods("PUT") + .WithHeaders("Header1") + .WithExposedHeaders("AllowedHeader") + .Build(); + }); + options.AddPolicy("policy2", policyBuilder => + { + policyBuilder + .WithOrigins("http://test.example.com") + .Build(); + }); }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(hostBuilder)) + using (var server = host.GetTestServer()) { // Act // Preflight request. @@ -447,29 +518,38 @@ public async Task PreFlight_MatchesDefaultPolicy_SetsResponseHeaders() Assert.Equal(new[] { OriginUrl }, kvp.Value); }); } + + await host.StopAsync(); } [Fact] public async Task CorsRequest_SetsResponseHeaders() { // Arrange - var hostBuilder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors(builder => - builder.WithOrigins(OriginUrl) - .WithMethods("PUT") - .WithHeaders("Header1") - .WithExposedHeaders("AllowedHeader")); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - context.Response.Headers.Add("Test", "Should-Appear"); - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => services.AddCors()); + app.UseCors(builder => + builder.WithOrigins(OriginUrl) + .WithMethods("PUT") + .WithHeaders("Header1") + .WithExposedHeaders("AllowedHeader")); + app.Run(async context => + { + context.Response.Headers.Add("Test", "Should-Appear"); + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => services.AddCors()); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(hostBuilder)) + using (var server = host.GetTestServer()) { // Act // Actual request. @@ -499,6 +579,8 @@ public async Task CorsRequest_SetsResponseHeaders() Assert.Equal("Cross origin response", await response.Content.ReadAsStringAsync()); } + + await host.StopAsync(); } [Fact] @@ -506,39 +588,46 @@ public async Task CorsRequest_SetsResponseHeader_IfExceptionHandlerClearsRespons { // Arrange var exceptionSeen = true; - var hostBuilder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - // Simulate ExceptionHandler middleware - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - try - { - await next(); - } - catch (Exception) + // Simulate ExceptionHandler middleware + app.Use(async (context, next) => { - exceptionSeen = true; - context.Response.Clear(); - context.Response.StatusCode = 500; - } - }); + try + { + await next(); + } + catch (Exception) + { + exceptionSeen = true; + context.Response.Clear(); + context.Response.StatusCode = 500; + } + }); - app.UseCors(builder => - builder.WithOrigins(OriginUrl) - .WithMethods("PUT") - .WithHeaders("Header1") - .WithExposedHeaders("AllowedHeader")); + app.UseCors(builder => + builder.WithOrigins(OriginUrl) + .WithMethods("PUT") + .WithHeaders("Header1") + .WithExposedHeaders("AllowedHeader")); - app.Run(context => - { - context.Response.Headers.Add("Test", "Should-Not-Exist"); - throw new Exception("Runtime error"); - }); - }) - .ConfigureServices(services => services.AddCors()); + app.Run(context => + { + context.Response.Headers.Add("Test", "Should-Not-Exist"); + throw new Exception("Runtime error"); + }); + }) + .ConfigureServices(services => services.AddCors()); + }).Build(); - using (var server = new TestServer(hostBuilder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { // Act // Actual request. @@ -563,6 +652,8 @@ public async Task CorsRequest_SetsResponseHeader_IfExceptionHandlerClearsRespons Assert.Equal("AllowedHeader", Assert.Single(kvp.Value)); }); } + + await host.StopAsync(); } [Fact] diff --git a/src/Middleware/CORS/test/testassets/CorsMiddlewareWebSite/Startup.cs b/src/Middleware/CORS/test/testassets/CorsMiddlewareWebSite/Startup.cs index 3043f59bcd98..3baa298e1189 100644 --- a/src/Middleware/CORS/test/testassets/CorsMiddlewareWebSite/Startup.cs +++ b/src/Middleware/CORS/test/testassets/CorsMiddlewareWebSite/Startup.cs @@ -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 { @@ -19,15 +21,19 @@ public void Configure(IApplicationBuilder app) app.UseCors(policy => policy.WithOrigins("http://example.com")); app.UseMiddleware(); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } -} \ No newline at end of file +} From 8ecb8ea5acc7e2a2439353359f6f225a82816c6f Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:02:32 -0700 Subject: [PATCH 02/20] concurrencylimiter --- .../ConcurrencyLimiter/sample/Startup.cs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Middleware/ConcurrencyLimiter/sample/Startup.cs b/src/Middleware/ConcurrencyLimiter/sample/Startup.cs index bd4bf2ec58a8..72d38f94f619 100644 --- a/src/Middleware/ConcurrencyLimiter/sample/Startup.cs +++ b/src/Middleware/ConcurrencyLimiter/sample/Startup.cs @@ -17,7 +17,7 @@ public void ConfigureServices(IServiceCollection services) { services.AddStackPolicy(options => { - options.MaxConcurrentRequests = 2; + options.MaxConcurrentRequests = 2; options.RequestQueueLimit = 25; }); } @@ -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() + return new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseStartup(); + }) .Build() - .Run(); + .RunAsync(); } } } From 18f2ea0b28fbf3acd88c9f0b41aadb7c31f4ed2c Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:03:02 -0700 Subject: [PATCH 03/20] Diagnostics.EntityFrameworkCore --- .../DatabaseErrorPageMiddlewareTest.cs | 134 ++++++++++++------ .../MigrationsEndPointMiddlewareTest.cs | 106 +++++++++++--- 2 files changed, 176 insertions(+), 64 deletions(-) diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs index 630c34e7cf82..12bee7e91e29 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs @@ -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; @@ -27,15 +28,26 @@ public class DatabaseErrorPageMiddlewareTest [Fact] public async Task Successful_requests_pass_thru() { - var builder = new WebHostBuilder().Configure(app => app - .UseDatabaseErrorPage() - .UseMiddleware()); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => app + .UseDatabaseErrorPage() + .UseMiddleware()); + }).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 @@ -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()); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => app + .UseDatabaseErrorPage() + .UseMiddleware()); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var ex = await Assert.ThrowsAsync(async () => await server.CreateClient().GetAsync("http://localhost/")); Assert.Equal("Exception requested from TestMiddleware", ex.Message); + + await host.StopAsync(); } class ExceptionMiddleware @@ -82,7 +105,7 @@ public async Task Existing_database_not_using_migrations_exception_passes_thru() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = SetupTestServer(database); + using TestServer server = await SetupTestServer(database); var ex = await Assert.ThrowsAsync(async () => await server.CreateClient().GetAsync("http://localhost/")); @@ -114,7 +137,7 @@ public async Task Error_page_displayed_no_migrations() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = SetupTestServer(database); + using TestServer server = await SetupTestServer(database); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -142,13 +165,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(database)) + using (var server = await SetupTestServer(database)) { - using (var db = server.Host.Services.GetService()) + using (var db = server.Services.GetService()) { db.Blogs.Add(new Blog()); @@ -172,7 +195,7 @@ public async Task Error_page_displayed_pending_migrations() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = SetupTestServer(database); + using TestServer server = await SetupTestServer(database); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -208,7 +231,7 @@ public async Task Error_page_displayed_pending_model_changes() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = SetupTestServer(database); + using TestServer server = await SetupTestServer(database); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -245,7 +268,7 @@ public async Task Error_page_then_apply_migrations() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = SetupTestServer(database); + using TestServer server = await SetupTestServer(database); var client = server.CreateClient(); var expectedMigrationsEndpoint = "/ApplyDatabaseMigrations"; @@ -302,7 +325,11 @@ public async Task Customize_migrations_end_point() using (var database = SqlTestStore.CreateScratch()) { - var builder = new WebHostBuilder() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() .Configure(app => { app.UseDatabaseErrorPage(new DatabaseErrorPageOptions @@ -317,7 +344,11 @@ public async Task Customize_migrations_end_point() services.AddDbContext( 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/"); @@ -325,6 +356,8 @@ public async Task Customize_migrations_end_point() var content = await response.Content.ReadAsStringAsync(); Assert.Contains("req.open(\"POST\", \"" + JavaScriptEncode(migrationsEndpoint) + "\", true);", content); + + await host.StopAsync(); } } @@ -335,16 +368,24 @@ public async Task Pass_thru_when_context_not_in_services() { var logProvider = new TestLoggerProvider(); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseDatabaseErrorPage(); - app.UseMiddleware(); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseDatabaseErrorPage(); + app.UseMiddleware(); #pragma warning disable CS0618 // Type or member is obsolete - app.ApplicationServices.GetService().AddProvider(logProvider); + app.ApplicationServices.GetService().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 { @@ -359,6 +400,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 @@ -391,7 +434,7 @@ public async Task Pass_thru_when_exception_in_logic() { var logProvider = new TestLoggerProvider(); - var server = SetupTestServer(database, logProvider); + var server = await SetupTestServer(database, logProvider); try { @@ -430,7 +473,7 @@ public async Task Error_page_displayed_when_exception_wrapped() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = SetupTestServer(database); + TestServer server = await SetupTestServer(database); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -461,29 +504,36 @@ public virtual Task Invoke(HttpContext context) } } - private static TestServer SetupTestServer(SqlTestStore database, ILoggerProvider logProvider = null) + private static async Task SetupTestServer(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(); + app.UseMiddleware(); - if (logProvider != null) - { + if (logProvider != null) + { #pragma warning disable CS0618 // Type or member is obsolete - app.ApplicationServices.GetService().AddProvider(logProvider); + app.ApplicationServices.GetService().AddProvider(logProvider); #pragma warning restore CS0618 // Type or member is obsolete - } - }) - .ConfigureServices(services => - { - services.AddDbContext(optionsBuilder => optionsBuilder.UseSqlite(database.ConnectionString)); - }); + } + }) + .ConfigureServices(services => + { + services.AddDbContext(optionsBuilder => optionsBuilder.UseSqlite(database.ConnectionString)); + }); + }).Build(); + + await host.StartAsync(); - return new TestServer(builder); + return host.GetTestServer(); } private static UrlEncoder _urlEncoder = UrlEncoder.Default; diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs index d77826fda4a6..79ee7b96d648 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs @@ -18,6 +18,7 @@ using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.Tests @@ -27,15 +28,26 @@ public class MigrationsEndPointMiddlewareTest [Fact] public async Task Non_migration_requests_pass_thru() { - var builder = new WebHostBuilder().Configure(app => app - .UseMigrationsEndPoint() - .UseMiddleware()); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => app + .UseMigrationsEndPoint() + .UseMiddleware()); + }).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 @@ -75,7 +87,11 @@ private async Task Migration_request(bool useCustomPath) var path = useCustomPath ? new PathString("/EndPoints/ApplyMyMigrations") : MigrationsEndPointOptions.DefaultPath; - var builder = new WebHostBuilder() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() .Configure(app => { if (useCustomPath) @@ -97,7 +113,11 @@ private async Task Migration_request(bool useCustomPath) options.UseSqlite(database.ConnectionString); }); }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); using (var db = BloggingContextWithMigrations.CreateWithoutExternalServiceProvider(optionsBuilder.Options)) { @@ -122,18 +142,28 @@ private async Task Migration_request(bool useCustomPath) Assert.Equal("111111111111111_MigrationOne", appliedMigrations.ElementAt(0).MigrationId); Assert.Equal("222222222222222_MigrationTwo", appliedMigrations.ElementAt(1).MigrationId); } + + await host.StopAsync(); } } [Fact] public async Task Context_type_not_specified() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseMigrationsEndPoint(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseMigrationsEndPoint(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var formData = new FormUrlEncodedContent(new List>()); @@ -143,17 +173,27 @@ public async Task Context_type_not_specified() Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.StartsWith(StringsHelpers.GetResourceString("MigrationsEndPointMiddleware_NoContextType"), content); Assert.True(content.Length > 512); + + await host.StopAsync(); } [Fact] public async Task Invalid_context_type_specified() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseMigrationsEndPoint(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseMigrationsEndPoint(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var typeName = "You won't find this type ;)"; var formData = new FormUrlEncodedContent(new List> @@ -167,15 +207,25 @@ public async Task Invalid_context_type_specified() Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.StartsWith(StringsHelpers.GetResourceString("FormatMigrationsEndPointMiddleware_InvalidContextType", typeName), content); Assert.True(content.Length > 512); + + await host.StopAsync(); } [Fact] public async Task Context_not_registered_in_services() { - var builder = new WebHostBuilder() - .Configure(app => app.UseMigrationsEndPoint()) - .ConfigureServices(services => services.AddEntityFrameworkSqlite()); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => app.UseMigrationsEndPoint()) + .ConfigureServices(services => services.AddEntityFrameworkSqlite()); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var formData = new FormUrlEncodedContent(new List> { @@ -188,6 +238,8 @@ public async Task Context_not_registered_in_services() Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.StartsWith(StringsHelpers.GetResourceString("FormatMigrationsEndPointMiddleware_ContextNotRegistered", typeof(BloggingContext)), content); Assert.True(content.Length > 512); + + await host.StopAsync(); } [ConditionalFact] @@ -197,7 +249,11 @@ public async Task Exception_while_applying_migrations() { using (var database = SqlTestStore.CreateScratch()) { - var builder = new WebHostBuilder() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() .Configure(app => app.UseMigrationsEndPoint()) .ConfigureServices(services => { @@ -206,7 +262,11 @@ public async Task Exception_while_applying_migrations() optionsBuilder.UseSqlite(database.ConnectionString); }); }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var formData = new FormUrlEncodedContent(new List> { @@ -218,6 +278,8 @@ public async Task Exception_while_applying_migrations() Assert.StartsWith(StringsHelpers.GetResourceString("FormatMigrationsEndPointMiddleware_Exception", typeof(BloggingContextWithSnapshotThatThrows)), ex.Message); Assert.Equal("Welcome to the invalid migration!", ex.InnerException.Message); + + await host.StopAsync(); } } } From 4c13e9b10aef541ef249efefb08be41fb79f1107 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:04:28 -0700 Subject: [PATCH 04/20] Diagnostics --- .../test/FunctionalTests/TestFixture.cs | 13 +- .../DeveloperExceptionPageMiddlewareTest.cs | 205 ++++++--- .../test/UnitTests/ExceptionHandlerTest.cs | 394 +++++++++++------- .../UnitTests/StatusCodeMiddlewareTest.cs | 195 +++++---- .../DatabaseErrorPageSample/Startup.cs | 17 +- .../DeveloperExceptionPageSample/Startup.cs | 17 +- .../ExceptionHandlerSample/Startup.cs | 18 +- .../StatusCodePagesSample/Startup.cs | 20 +- .../testassets/WelcomePageSample/Startup.cs | 19 +- 9 files changed, 550 insertions(+), 348 deletions(-) diff --git a/src/Middleware/Diagnostics/test/FunctionalTests/TestFixture.cs b/src/Middleware/Diagnostics/test/FunctionalTests/TestFixture.cs index ef4666ad3143..b628c26b023e 100644 --- a/src/Middleware/Diagnostics/test/FunctionalTests/TestFixture.cs +++ b/src/Middleware/Diagnostics/test/FunctionalTests/TestFixture.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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; @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.Testing; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.Diagnostics.FunctionalTests { @@ -20,10 +21,16 @@ public TestFixture() // (DefaultRequestCulture) is consistent regardless of system configuration or personal preferences. using (new CultureReplacer()) { - var builder = new WebHostBuilder() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() .UseStartup(typeof(TStartup)); + }).Build(); - _server = new TestServer(builder); + host.Start(); + _server = host.GetTestServer(); } Client = _server.CreateClient(); diff --git a/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs b/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs index 26bda1074dc5..d630fbe4e349 100644 --- a/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs +++ b/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Diagnostics @@ -22,17 +23,25 @@ public async Task UnhandledErrorsWriteToDiagnosticWhenUsingExceptionPage() { // Arrange DiagnosticListener diagnosticListener = null; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - diagnosticListener = app.ApplicationServices.GetRequiredService(); - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - throw new Exception("Test exception"); + diagnosticListener = app.ApplicationServices.GetRequiredService(); + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var listener = new TestDiagnosticListener(); diagnosticListener.SubscribeWithAdapter(listener); @@ -44,22 +53,32 @@ public async Task UnhandledErrorsWriteToDiagnosticWhenUsingExceptionPage() Assert.NotNull(listener.DiagnosticUnhandledException?.Exception); Assert.Null(listener.DiagnosticHandledException?.HttpContext); Assert.Null(listener.DiagnosticHandledException?.Exception); + + await host.StopAsync(); } [Fact] public async Task ErrorPageWithAcceptHeaderForHtmlReturnsHtml() { // Arrange - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - throw new Exception("Test exception"); + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // Act var client = server.CreateClient(); @@ -71,22 +90,32 @@ public async Task ErrorPageWithAcceptHeaderForHtmlReturnsHtml() Assert.Equal("text/html", response.Content.Headers.ContentType.MediaType); Assert.Contains(" + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - throw new Exception("Test exception"); + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // Act var response = await server.CreateClient().GetAsync("/path"); @@ -96,88 +125,120 @@ public async Task ErrorPageWithoutAcceptHeaderForHtmlReturnsPlainText() Assert.Equal("text/plain", response.Content.Headers.ContentType.MediaType); Assert.Contains("Test exception", responseText); Assert.DoesNotContain(" - { - services.AddSingleton(); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - throw new Exception("Test exception"); + services.AddSingleton(); + }) + .Configure(app => + { + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // Act var response = await server.CreateClient().GetAsync("/path"); // Assert Assert.Equal("Test exception", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task ExceptionFilterCallingNextWorks() { // Arrange - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + }) + .Configure(app => { - throw new Exception("Test exception"); + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // Act var response = await server.CreateClient().GetAsync("/path"); // Assert Assert.Equal("Bad format exception!", await response.Content.ReadAsStringAsync()); + + await host.StartAsync(); } [Fact] public async Task ExceptionPageFiltersAreAppliedInOrder() { // Arrange - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - }) - .Configure(app => - { - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + }) + .Configure(app => { - throw new Exception("Test exception"); + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // Act var response = await server.CreateClient().GetAsync("/path"); // Assert Assert.Equal("An error occurred", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } public static TheoryData CompilationExceptionData @@ -241,17 +302,25 @@ public async Task NullInfoInCompilationException_ShouldNotThrowExceptionGenerati { // Arrange DiagnosticListener diagnosticListener = null; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - diagnosticListener = app.ApplicationServices.GetRequiredService(); - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - throw new CustomCompilationException(failures); + diagnosticListener = app.ApplicationServices.GetRequiredService(); + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new CustomCompilationException(failures); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var listener = new TestDiagnosticListener(); diagnosticListener.SubscribeWithAdapter(listener); @@ -263,6 +332,8 @@ public async Task NullInfoInCompilationException_ShouldNotThrowExceptionGenerati Assert.NotNull(listener.DiagnosticUnhandledException?.Exception); Assert.Null(listener.DiagnosticHandledException?.HttpContext); Assert.Null(listener.DiagnosticHandledException?.Exception); + + await host.StopAsync(); } public class CustomCompilationException : Exception, ICompilationException diff --git a/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs b/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs index da5c6c60d18a..0a33c78e2b1f 100644 --- a/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs +++ b/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs @@ -16,6 +16,7 @@ using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Diagnostics @@ -28,136 +29,161 @@ public class ExceptionHandlerTest [InlineData(HttpStatusCode.InternalServerError)] public async Task OnlyHandles_UnhandledExceptions(HttpStatusCode expectedStatusCode) { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseExceptionHandler("/handle-errors"); - - app.Map("/handle-errors", (innerAppBuilder) => + webHostBuilder + .UseTestServer() + .Configure(app => { - innerAppBuilder.Run(async (httpContext) => + app.UseExceptionHandler("/handle-errors"); + + app.Map("/handle-errors", (innerAppBuilder) => { - await httpContext.Response.WriteAsync("Handled error in a custom way."); + innerAppBuilder.Run(async (httpContext) => + { + await httpContext.Response.WriteAsync("Handled error in a custom way."); + }); }); + + app.Run((RequestDelegate)(async (context) => + { + context.Response.StatusCode = (int)expectedStatusCode; + context.Response.ContentType = "text/plain; charset=utf-8"; + await context.Response.WriteAsync("An error occurred while adding a product"); + })); }); + }).Build(); - app.Run((RequestDelegate)(async (context) => - { - context.Response.StatusCode = (int)expectedStatusCode; - context.Response.ContentType = "text/plain; charset=utf-8"; - await context.Response.WriteAsync("An error occurred while adding a product"); - })); - }); + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); Assert.Equal(expectedStatusCode, response.StatusCode); Assert.Equal("An error occurred while adding a product", await response.Content.ReadAsStringAsync()); } + + await host.StopAsync(); } [Fact] public async Task DoesNotHandle_UnhandledExceptions_WhenResponseAlreadyStarted() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (httpContext, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - Exception exception = null; - try - { - await next(); - } - catch (InvalidOperationException ex) + app.Use(async (httpContext, next) => { - exception = ex; - } + Exception exception = null; + try + { + await next(); + } + catch (InvalidOperationException ex) + { + exception = ex; + } + + Assert.NotNull(exception); + Assert.Equal("Something bad happened", exception.Message); + }); - Assert.NotNull(exception); - Assert.Equal("Something bad happened", exception.Message); - }); + app.UseExceptionHandler("/handle-errors"); - app.UseExceptionHandler("/handle-errors"); + app.Map("/handle-errors", (innerAppBuilder) => + { + innerAppBuilder.Run(async (httpContext) => + { + await httpContext.Response.WriteAsync("Handled error in a custom way."); + }); + }); - app.Map("/handle-errors", (innerAppBuilder) => - { - innerAppBuilder.Run(async (httpContext) => + app.Run(async (httpContext) => { - await httpContext.Response.WriteAsync("Handled error in a custom way."); + await httpContext.Response.WriteAsync("Hello"); + throw new InvalidOperationException("Something bad happened"); }); }); + }).Build(); - app.Run(async (httpContext) => - { - await httpContext.Response.WriteAsync("Hello"); - throw new InvalidOperationException("Something bad happened"); - }); - }); + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); response.EnsureSuccessStatusCode(); Assert.Equal("Hello", await response.Content.ReadAsStringAsync()); } + + await host.StopAsync(); } [Fact] public async Task ClearsResponseBuffer_BeforeRequestIsReexecuted() { var expectedResponseBody = "New response body"; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - // add response buffering - app.Use(async (httpContext, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - var response = httpContext.Response; - var originalResponseBody = response.Body; - var bufferingStream = new MemoryStream(); - response.Body = bufferingStream; - - try + // add response buffering + app.Use(async (httpContext, next) => { - await next(); + var response = httpContext.Response; + var originalResponseBody = response.Body; + var bufferingStream = new MemoryStream(); + response.Body = bufferingStream; + + try + { + await next(); + + response.Body = originalResponseBody; + bufferingStream.Seek(0, SeekOrigin.Begin); + await bufferingStream.CopyToAsync(response.Body); + } + finally + { + response.Body = originalResponseBody; + } + }); - response.Body = originalResponseBody; - bufferingStream.Seek(0, SeekOrigin.Begin); - await bufferingStream.CopyToAsync(response.Body); - } - finally + app.UseExceptionHandler("/handle-errors"); + + app.Map("/handle-errors", (innerAppBuilder) => { - response.Body = originalResponseBody; - } - }); + innerAppBuilder.Run(async (httpContext) => + { + Assert.True(httpContext.Response.Body.CanSeek); + Assert.Equal(0, httpContext.Response.Body.Position); - app.UseExceptionHandler("/handle-errors"); + await httpContext.Response.WriteAsync(expectedResponseBody); + }); + }); - app.Map("/handle-errors", (innerAppBuilder) => - { - innerAppBuilder.Run(async (httpContext) => + app.Run(async (context) => { - Assert.True(httpContext.Response.Body.CanSeek); - Assert.Equal(0, httpContext.Response.Body.Position); + // Write some content into the response before throwing exception + await context.Response.WriteAsync(new string('a', 100)); - await httpContext.Response.WriteAsync(expectedResponseBody); + throw new InvalidOperationException("Invalid input provided."); }); }); + }).Build(); - app.Run(async (context) => - { - // Write some content into the response before throwing exception - await context.Response.WriteAsync(new string('a', 100)); - - throw new InvalidOperationException("Invalid input provided."); - }); - }); + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -174,6 +200,8 @@ public async Task ClearsResponseBuffer_BeforeRequestIsReexecuted() Assert.Equal("-1", values.First()); Assert.False(response.Headers.TryGetValues("ETag", out values)); } + + await host.StopAsync(); } [Fact] @@ -181,32 +209,39 @@ public async Task ClearsCacheHeaders_SetByReexecutionPathHandlers() { var expiresTime = DateTime.UtcNow.AddDays(5).ToString("R"); var expectedResponseBody = "Handled error in a custom way."; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseExceptionHandler("/handle-errors"); - - app.Map("/handle-errors", (innerAppBuilder) => + webHostBuilder + .UseTestServer() + .Configure(app => { - innerAppBuilder.Run(async (httpContext) => + app.UseExceptionHandler("/handle-errors"); + + app.Map("/handle-errors", (innerAppBuilder) => { - httpContext.Response.Headers.Add("Cache-Control", new[] { "max-age=600" }); - httpContext.Response.Headers.Add("Pragma", new[] { "max-age=600" }); - httpContext.Response.Headers.Add( - "Expires", new[] { expiresTime }); - httpContext.Response.Headers.Add("ETag", new[] { "12345" }); + innerAppBuilder.Run(async (httpContext) => + { + httpContext.Response.Headers.Add("Cache-Control", new[] { "max-age=600" }); + httpContext.Response.Headers.Add("Pragma", new[] { "max-age=600" }); + httpContext.Response.Headers.Add( + "Expires", new[] { expiresTime }); + httpContext.Response.Headers.Add("ETag", new[] { "12345" }); + + await httpContext.Response.WriteAsync(expectedResponseBody); + }); + }); - await httpContext.Response.WriteAsync(expectedResponseBody); + app.Run((context) => + { + throw new InvalidOperationException("Invalid input provided."); }); }); + }).Build(); - app.Run((context) => - { - throw new InvalidOperationException("Invalid input provided."); - }); - }); + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -223,6 +258,8 @@ public async Task ClearsCacheHeaders_SetByReexecutionPathHandlers() Assert.Equal("-1", values.First()); Assert.False(response.Headers.TryGetValues("ETag", out values)); } + + await host.StopAsync(); } [Fact] @@ -230,31 +267,38 @@ public async Task DoesNotModifyCacheHeaders_WhenNoExceptionIsThrown() { var expiresTime = DateTime.UtcNow.AddDays(10).ToString("R"); var expectedResponseBody = "Hello world!"; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseExceptionHandler("/handle-errors"); - - app.Map("/handle-errors", (innerAppBuilder) => + webHostBuilder + .UseTestServer() + .Configure(app => { - innerAppBuilder.Run(async (httpContext) => + app.UseExceptionHandler("/handle-errors"); + + app.Map("/handle-errors", (innerAppBuilder) => { - await httpContext.Response.WriteAsync("Handled error in a custom way."); + innerAppBuilder.Run(async (httpContext) => + { + await httpContext.Response.WriteAsync("Handled error in a custom way."); + }); }); - }); - app.Run(async (httpContext) => - { - httpContext.Response.Headers.Add("Cache-Control", new[] { "max-age=3600" }); - httpContext.Response.Headers.Add("Pragma", new[] { "max-age=3600" }); - httpContext.Response.Headers.Add("Expires", new[] { expiresTime }); - httpContext.Response.Headers.Add("ETag", new[] { "abcdef" }); + app.Run(async (httpContext) => + { + httpContext.Response.Headers.Add("Cache-Control", new[] { "max-age=3600" }); + httpContext.Response.Headers.Add("Pragma", new[] { "max-age=3600" }); + httpContext.Response.Headers.Add("Expires", new[] { expiresTime }); + httpContext.Response.Headers.Add("ETag", new[] { "abcdef" }); - await httpContext.Response.WriteAsync(expectedResponseBody); + await httpContext.Response.WriteAsync(expectedResponseBody); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -274,55 +318,64 @@ public async Task DoesNotModifyCacheHeaders_WhenNoExceptionIsThrown() Assert.Single(values); Assert.Equal("abcdef", values.First()); } + + await host.StopAsync(); } [Fact] public async Task DoesNotClearCacheHeaders_WhenResponseHasAlreadyStarted() { var expiresTime = DateTime.UtcNow.AddDays(10).ToString("R"); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (httpContext, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - Exception exception = null; - try + app.Use(async (httpContext, next) => { - await next(); - } - catch (InvalidOperationException ex) - { - exception = ex; - } - - Assert.NotNull(exception); - Assert.Equal("Something bad happened", exception.Message); - }); + Exception exception = null; + try + { + await next(); + } + catch (InvalidOperationException ex) + { + exception = ex; + } + + Assert.NotNull(exception); + Assert.Equal("Something bad happened", exception.Message); + }); - app.UseExceptionHandler("/handle-errors"); + app.UseExceptionHandler("/handle-errors"); - app.Map("/handle-errors", (innerAppBuilder) => - { - innerAppBuilder.Run(async (httpContext) => + app.Map("/handle-errors", (innerAppBuilder) => { - await httpContext.Response.WriteAsync("Handled error in a custom way."); + innerAppBuilder.Run(async (httpContext) => + { + await httpContext.Response.WriteAsync("Handled error in a custom way."); + }); }); - }); - app.Run(async (httpContext) => - { - httpContext.Response.Headers.Add("Cache-Control", new[] { "max-age=3600" }); - httpContext.Response.Headers.Add("Pragma", new[] { "max-age=3600" }); - httpContext.Response.Headers.Add("Expires", new[] { expiresTime }); - httpContext.Response.Headers.Add("ETag", new[] { "abcdef" }); + app.Run(async (httpContext) => + { + httpContext.Response.Headers.Add("Cache-Control", new[] { "max-age=3600" }); + httpContext.Response.Headers.Add("Pragma", new[] { "max-age=3600" }); + httpContext.Response.Headers.Add("Expires", new[] { expiresTime }); + httpContext.Response.Headers.Add("ETag", new[] { "abcdef" }); - await httpContext.Response.WriteAsync("Hello"); + await httpContext.Response.WriteAsync("Hello"); - throw new InvalidOperationException("Something bad happened"); + throw new InvalidOperationException("Something bad happened"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -342,6 +395,8 @@ public async Task DoesNotClearCacheHeaders_WhenResponseHasAlreadyStarted() Assert.Single(values); Assert.Equal("abcdef", values.First()); } + + await host.StopAsync(); } [Fact] @@ -350,25 +405,33 @@ public async Task HandledErrorsWriteToDiagnosticWhenUsingExceptionHandler() // Arrange DiagnosticListener diagnosticListener = null; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - diagnosticListener = app.ApplicationServices.GetRequiredService(); - - app.UseExceptionHandler("/handle-errors"); - app.Map("/handle-errors", (innerAppBuilder) => + webHostBuilder + .UseTestServer() + .Configure(app => { - innerAppBuilder.Run(async (httpContext) => + diagnosticListener = app.ApplicationServices.GetRequiredService(); + + app.UseExceptionHandler("/handle-errors"); + app.Map("/handle-errors", (innerAppBuilder) => { - await httpContext.Response.WriteAsync("Handled error in a custom way."); + innerAppBuilder.Run(async (httpContext) => + { + await httpContext.Response.WriteAsync("Handled error in a custom way."); + }); + }); + app.Run(context => + { + throw new Exception("Test exception"); }); }); - app.Run(context => - { - throw new Exception("Test exception"); - }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var listener = new TestDiagnosticListener(); diagnosticListener.SubscribeWithAdapter(listener); @@ -387,6 +450,8 @@ public async Task HandledErrorsWriteToDiagnosticWhenUsingExceptionHandler() Assert.Null(listener.DiagnosticUnhandledException?.Exception); Assert.NotNull(listener.DiagnosticHandledException?.HttpContext); Assert.NotNull(listener.DiagnosticHandledException?.Exception); + + await host.StopAsync(); } [Fact] @@ -395,15 +460,20 @@ public void UsingExceptionHandler_ThrowsAnException_WhenExceptionHandlingPathNot // Arrange DiagnosticListener diagnosticListener = null; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - diagnosticListener = app.ApplicationServices.GetRequiredService(); - app.UseExceptionHandler(); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + diagnosticListener = app.ApplicationServices.GetRequiredService(); + app.UseExceptionHandler(); + }); + }).Build(); // Act - var exception = Assert.Throws(() => new TestServer(builder)); + var exception = Assert.Throws(() => host.Start()); // Assert Assert.Equal("An error occurred when configuring the exception handler middleware. " + diff --git a/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs b/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs index c2bb236c4f89..6bca5a112f2c 100644 --- a/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs +++ b/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Diagnostics @@ -21,36 +22,44 @@ public async Task Redirect_StatusPage() { var expectedStatusCode = 432; var destination = "/location"; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseStatusCodePagesWithRedirects("/errorPage?id={0}"); - - app.Map(destination, (innerAppBuilder) => + webHostBuilder + .UseTestServer() + .Configure(app => { - innerAppBuilder.Run((httpContext) => + app.UseStatusCodePagesWithRedirects("/errorPage?id={0}"); + + app.Map(destination, (innerAppBuilder) => { - httpContext.Response.StatusCode = expectedStatusCode; - return Task.FromResult(1); + innerAppBuilder.Run((httpContext) => + { + httpContext.Response.StatusCode = expectedStatusCode; + return Task.FromResult(1); + }); }); - }); - app.Map("/errorPage", (innerAppBuilder) => - { - innerAppBuilder.Run(async (httpContext) => + app.Map("/errorPage", (innerAppBuilder) => { - await httpContext.Response.WriteAsync(httpContext.Request.QueryString.Value); + innerAppBuilder.Run(async (httpContext) => + { + await httpContext.Response.WriteAsync(httpContext.Request.QueryString.Value); + }); }); - }); - app.Run((context) => - { - throw new InvalidOperationException($"Invalid input provided. {context.Request.Path}"); + app.Run((context) => + { + throw new InvalidOperationException($"Invalid input provided. {context.Request.Path}"); + }); }); - }); + }).Build(); + + await host.StartAsync(); + var expectedQueryString = $"?id={expectedStatusCode}"; var expectedUri = $"/errorPage{expectedQueryString}"; - using var server = new TestServer(builder); + using var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync(destination); Assert.Equal(HttpStatusCode.Found, response.StatusCode); @@ -60,6 +69,8 @@ public async Task Redirect_StatusPage() var content = await response.Content.ReadAsStringAsync(); Assert.Equal(expectedQueryString, content); Assert.Equal(expectedQueryString, response.RequestMessage.RequestUri.Query); + + await host.StopAsync(); } [Fact] @@ -67,53 +78,62 @@ public async Task Reexecute_CanRetrieveInformationAboutOriginalRequest() { var expectedStatusCode = 432; var destination = "/location"; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - var beforeNext = context.Request.QueryString; - await next(); - var afterNext = context.Request.QueryString; + app.Use(async (context, next) => + { + var beforeNext = context.Request.QueryString; + await next(); + var afterNext = context.Request.QueryString; - Assert.Equal(beforeNext, afterNext); - }); - app.UseStatusCodePagesWithReExecute(pathFormat: "/errorPage", queryFormat: "?id={0}"); + Assert.Equal(beforeNext, afterNext); + }); + app.UseStatusCodePagesWithReExecute(pathFormat: "/errorPage", queryFormat: "?id={0}"); - app.Map(destination, (innerAppBuilder) => - { - innerAppBuilder.Run((httpContext) => + app.Map(destination, (innerAppBuilder) => { - httpContext.Response.StatusCode = expectedStatusCode; - return Task.FromResult(1); + innerAppBuilder.Run((httpContext) => + { + httpContext.Response.StatusCode = expectedStatusCode; + return Task.FromResult(1); + }); }); - }); - app.Map("/errorPage", (innerAppBuilder) => - { - innerAppBuilder.Run(async (httpContext) => + app.Map("/errorPage", (innerAppBuilder) => { - var statusCodeReExecuteFeature = httpContext.Features.Get(); - await httpContext.Response.WriteAsync( - httpContext.Request.QueryString.Value - + ", " - + statusCodeReExecuteFeature.OriginalPath - + ", " - + statusCodeReExecuteFeature.OriginalQueryString); + innerAppBuilder.Run(async (httpContext) => + { + var statusCodeReExecuteFeature = httpContext.Features.Get(); + await httpContext.Response.WriteAsync( + httpContext.Request.QueryString.Value + + ", " + + statusCodeReExecuteFeature.OriginalPath + + ", " + + statusCodeReExecuteFeature.OriginalQueryString); + }); }); - }); - app.Run((context) => - { - throw new InvalidOperationException("Invalid input provided."); + app.Run((context) => + { + throw new InvalidOperationException("Invalid input provided."); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using var server = new TestServer(builder); + using var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync(destination + "?name=James"); var content = await response.Content.ReadAsStringAsync(); Assert.Equal($"?id={expectedStatusCode}, /location, ?name=James", content); + + await host.StopAsync(); } [Fact] @@ -121,54 +141,63 @@ public async Task Reexecute_ClearsEndpointAndRouteData() { var expectedStatusCode = 432; var destination = "/location"; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseStatusCodePagesWithReExecute(pathFormat: "/errorPage", queryFormat: "?id={0}"); - - app.Use((context, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Empty(context.Request.RouteValues); - Assert.Null(context.GetEndpoint()); - return next(); - }); + app.UseStatusCodePagesWithReExecute(pathFormat: "/errorPage", queryFormat: "?id={0}"); - app.Map(destination, (innerAppBuilder) => - { - innerAppBuilder.Run((httpContext) => + app.Use((context, next) => { - httpContext.SetEndpoint(new Endpoint((_) => Task.CompletedTask, new EndpointMetadataCollection(), "Test")); - httpContext.Request.RouteValues["John"] = "Doe"; - httpContext.Response.StatusCode = expectedStatusCode; - return Task.CompletedTask; + Assert.Empty(context.Request.RouteValues); + Assert.Null(context.GetEndpoint()); + return next(); }); - }); - app.Map("/errorPage", (innerAppBuilder) => - { - innerAppBuilder.Run(async (httpContext) => + app.Map(destination, (innerAppBuilder) => { - var statusCodeReExecuteFeature = httpContext.Features.Get(); - await httpContext.Response.WriteAsync( - httpContext.Request.QueryString.Value - + ", " - + statusCodeReExecuteFeature.OriginalPath - + ", " - + statusCodeReExecuteFeature.OriginalQueryString); + innerAppBuilder.Run((httpContext) => + { + httpContext.SetEndpoint(new Endpoint((_) => Task.CompletedTask, new EndpointMetadataCollection(), "Test")); + httpContext.Request.RouteValues["John"] = "Doe"; + httpContext.Response.StatusCode = expectedStatusCode; + return Task.CompletedTask; + }); }); - }); - app.Run((context) => - { - throw new InvalidOperationException("Invalid input provided."); + app.Map("/errorPage", (innerAppBuilder) => + { + innerAppBuilder.Run(async (httpContext) => + { + var statusCodeReExecuteFeature = httpContext.Features.Get(); + await httpContext.Response.WriteAsync( + httpContext.Request.QueryString.Value + + ", " + + statusCodeReExecuteFeature.OriginalPath + + ", " + + statusCodeReExecuteFeature.OriginalQueryString); + }); + }); + + app.Run((context) => + { + throw new InvalidOperationException("Invalid input provided."); + }); }); - }); + }).Build(); - using var server = new TestServer(builder); + await host.StartAsync(); + + using var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync(destination + "?name=James"); var content = await response.Content.ReadAsStringAsync(); Assert.Equal($"?id={expectedStatusCode}, /location, ?name=James", content); + + await host.StopAsync(); } } } diff --git a/src/Middleware/Diagnostics/test/testassets/DatabaseErrorPageSample/Startup.cs b/src/Middleware/Diagnostics/test/testassets/DatabaseErrorPageSample/Startup.cs index 42bbbdb48301..a59ce7c96acc 100644 --- a/src/Middleware/Diagnostics/test/testassets/DatabaseErrorPageSample/Startup.cs +++ b/src/Middleware/Diagnostics/test/testassets/DatabaseErrorPageSample/Startup.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace DatabaseErrorPageSample { @@ -26,15 +27,19 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } diff --git a/src/Middleware/Diagnostics/test/testassets/DeveloperExceptionPageSample/Startup.cs b/src/Middleware/Diagnostics/test/testassets/DeveloperExceptionPageSample/Startup.cs index 52d67cf9b41e..7ac337c8142e 100644 --- a/src/Middleware/Diagnostics/test/testassets/DeveloperExceptionPageSample/Startup.cs +++ b/src/Middleware/Diagnostics/test/testassets/DeveloperExceptionPageSample/Startup.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Patterns; +using Microsoft.Extensions.Hosting; namespace DeveloperExceptionPageSample { @@ -44,15 +45,19 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/Diagnostics/test/testassets/ExceptionHandlerSample/Startup.cs b/src/Middleware/Diagnostics/test/testassets/ExceptionHandlerSample/Startup.cs index cf2e57429bc2..b964486fd427 100644 --- a/src/Middleware/Diagnostics/test/testassets/ExceptionHandlerSample/Startup.cs +++ b/src/Middleware/Diagnostics/test/testassets/ExceptionHandlerSample/Startup.cs @@ -1,10 +1,12 @@ using System; using System.Text.Encodings.Web; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; +using Microsoft.Extensions.Hosting; namespace ExceptionHandlerSample { @@ -56,15 +58,19 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/Diagnostics/test/testassets/StatusCodePagesSample/Startup.cs b/src/Middleware/Diagnostics/test/testassets/StatusCodePagesSample/Startup.cs index 594cc193405f..e35269915a6a 100644 --- a/src/Middleware/Diagnostics/test/testassets/StatusCodePagesSample/Startup.cs +++ b/src/Middleware/Diagnostics/test/testassets/StatusCodePagesSample/Startup.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; +using Microsoft.Extensions.Hosting; namespace StatusCodePagesSample { @@ -37,7 +38,7 @@ public void Configure(IApplicationBuilder app) { context.Response.StatusCode = int.Parse(requestedStatusCode); - // To turn off the StatusCode feature - For example the below code turns off the StatusCode middleware + // To turn off the StatusCode feature - For example the below code turns off the StatusCode middleware // if the query contains a disableStatusCodePages=true parameter. var disableStatusCodePages = context.Request.Query["disableStatusCodePages"]; if (disableStatusCodePages == "true") @@ -102,15 +103,18 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() - .Build(); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/Diagnostics/test/testassets/WelcomePageSample/Startup.cs b/src/Middleware/Diagnostics/test/testassets/WelcomePageSample/Startup.cs index 866b10d78816..74ad6f7f5b8d 100644 --- a/src/Middleware/Diagnostics/test/testassets/WelcomePageSample/Startup.cs +++ b/src/Middleware/Diagnostics/test/testassets/WelcomePageSample/Startup.cs @@ -1,5 +1,7 @@ +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; namespace WelcomePageSample { @@ -10,15 +12,18 @@ public void Configure(IApplicationBuilder app) app.UseWelcomePage(); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() - .Build(); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } From 38b4dae47e8a75cb6b29dd5bd6c9aa6aea8d28fb Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:04:46 -0700 Subject: [PATCH 05/20] HeaderPropagation --- .../test/HeaderPropagationIntegrationTest.cs | 142 +++++++++++------- 1 file changed, 86 insertions(+), 56 deletions(-) diff --git a/src/Middleware/HeaderPropagation/test/HeaderPropagationIntegrationTest.cs b/src/Middleware/HeaderPropagation/test/HeaderPropagationIntegrationTest.cs index 251e324abcfc..6809470f582e 100644 --- a/src/Middleware/HeaderPropagation/test/HeaderPropagationIntegrationTest.cs +++ b/src/Middleware/HeaderPropagation/test/HeaderPropagationIntegrationTest.cs @@ -12,6 +12,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.HeaderPropagation.Tests @@ -24,34 +25,41 @@ public async Task HeaderPropagation_WithoutMiddleware_Throws() // Arrange Exception captured = null; - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHttpClient("test").AddHeaderPropagation(); - services.AddHeaderPropagation(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.Headers.Add("X-TraceId"); - }); - }) - .Configure(app => - { - // note: no header propagation middleware - - app.Run(async context => - { - try + services.AddHttpClient("test").AddHeaderPropagation(); + services.AddHeaderPropagation(options => { - var client = context.RequestServices.GetRequiredService().CreateClient("test"); - await client.GetAsync("http://localhost/"); // will throw - } - catch (Exception ex) + options.Headers.Add("X-TraceId"); + }); + }) + .Configure(app => + { + // note: no header propagation middleware + + app.Run(async context => { - captured = ex; - } + try + { + var client = context.RequestServices.GetRequiredService().CreateClient("test"); + await client.GetAsync("http://localhost/"); // will throw + } + catch (Exception ex) + { + captured = ex; + } + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(); @@ -67,6 +75,8 @@ public async Task HeaderPropagation_WithoutMiddleware_Throws() "by adding 'app.UseHeaderPropagation()' in the 'Configure(...)' method. Header propagation can only be used within " + "the context of an HTTP request.", captured.Message); + + await host.StopAsync(); } [Fact] @@ -96,10 +106,10 @@ public async Task HeaderInRequest_AddCorrectValue() { // Arrange var handler = new SimpleHandler(); - var builder = CreateBuilder(c => + var host = await CreateHost(c => c.Headers.Add("in", "out"), handler); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(); @@ -112,6 +122,8 @@ public async Task HeaderInRequest_AddCorrectValue() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(handler.Headers.Contains("out")); Assert.Equal(new[] { "test" }, handler.Headers.GetValues("out")); + + await host.StopAsync(); } [Fact] @@ -119,13 +131,13 @@ public async Task MultipleHeaders_HeadersInRequest_AddAllHeaders() { // Arrange var handler = new SimpleHandler(); - var builder = CreateBuilder(c => + var host = await CreateHost(c => { c.Headers.Add("first"); c.Headers.Add("second"); }, handler); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(); @@ -141,18 +153,25 @@ public async Task MultipleHeaders_HeadersInRequest_AddAllHeaders() Assert.Equal(new[] { "value" }, handler.Headers.GetValues("first")); Assert.True(handler.Headers.Contains("second")); Assert.Equal(new[] { "other" }, handler.Headers.GetValues("second")); + + await host.StopAsync(); } [Fact] - public void Builder_UseHeaderPropagation_Without_AddHeaderPropagation_Throws() + public async Task Builder_UseHeaderPropagation_Without_AddHeaderPropagation_Throws() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHeaderPropagation(); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHeaderPropagation(); + }); + }).Build(); - var exception = Assert.Throws(() => new TestServer(builder)); + var exception = await Assert.ThrowsAsync(() => host.StartAsync()); Assert.Equal( "Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddHeaderPropagation' inside the call to 'ConfigureServices(...)' in the application startup code.", exception.Message); @@ -163,11 +182,11 @@ public async Task HeaderInRequest_OverrideHeaderPerClient_AddCorrectValue() { // Arrange var handler = new SimpleHandler(); - var builder = CreateBuilder( + var host = await CreateHost( c => c.Headers.Add("in", "out"), handler, c => c.Headers.Add("out", "different")); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(); @@ -180,34 +199,45 @@ public async Task HeaderInRequest_OverrideHeaderPerClient_AddCorrectValue() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(handler.Headers.Contains("different")); Assert.Equal(new[] { "test" }, handler.Headers.GetValues("different")); + + await host.StopAsync(); } - private IWebHostBuilder CreateBuilder(Action configure, HttpMessageHandler primaryHandler, Action configureClient = null) + private async Task CreateHost(Action configure, HttpMessageHandler primaryHandler, Action configureClient = null) { - return new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHeaderPropagation(); - app.UseMiddleware(); - }) - .ConfigureServices(services => - { - services.AddHeaderPropagation(configure); - var client = services.AddHttpClient("example.com", c => c.BaseAddress = new Uri("http://example.com")) - .ConfigureHttpMessageHandlerBuilder(b => - { - b.PrimaryHandler = primaryHandler; - }); - - if (configureClient != null) + webHostBuilder + .UseTestServer() + .Configure(app => { - client.AddHeaderPropagation(configureClient); - } - else + app.UseHeaderPropagation(); + app.UseMiddleware(); + }) + .ConfigureServices(services => { - client.AddHeaderPropagation(); - } - }); + services.AddHeaderPropagation(configure); + var client = services.AddHttpClient("example.com", c => c.BaseAddress = new Uri("http://example.com")) + .ConfigureHttpMessageHandlerBuilder(b => + { + b.PrimaryHandler = primaryHandler; + }); + + if (configureClient != null) + { + client.AddHeaderPropagation(configureClient); + } + else + { + client.AddHeaderPropagation(); + } + }); + }).Build(); + + await host.StartAsync(); + + return host; } private class SimpleHandler : DelegatingHandler From b1273ea391f3291496832722cf1b7f3e6589ccd3 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:05:16 -0700 Subject: [PATCH 06/20] HealthChecks --- ...CheckEndpointRouteBuilderExtensionsTest.cs | 104 ++- .../HealthCheckMiddlewareSampleTest.cs | 63 +- .../UnitTests/HealthCheckMiddlewareTests.cs | 863 +++++++++++------- .../testassets/HealthChecksSample/Program.cs | 28 +- 4 files changed, 686 insertions(+), 372 deletions(-) diff --git a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs index 00a7da8d6462..7df7443b2acc 100644 --- a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs +++ b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs @@ -13,6 +13,7 @@ using Xunit; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.Diagnostics.HealthChecks { @@ -21,21 +22,26 @@ public class HealthCheckEndpointRouteBuilderExtensionsTest [Fact] public void ThrowFriendlyErrorWhenServicesNotRegistered() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRouting(); - app.UseEndpoints(endpoints => + webHostBuilder + .UseTestServer() + .Configure(app => { - endpoints.MapHealthChecks("/healthz"); + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapHealthChecks("/healthz"); + }); + }) + .ConfigureServices(services => + { + services.AddRouting(); }); - }) - .ConfigureServices(services => - { - services.AddRouting(); - }); + }).Build(); - var ex = Assert.Throws(() => new TestServer(builder)); + var ex = Assert.Throws(() => host.Start()); Assert.Equal( "Unable to find the required services. Please add all the required services by calling " + @@ -48,21 +54,29 @@ public void ThrowFriendlyErrorWhenServicesNotRegistered() public async Task MapHealthChecks_ReturnsOk() { // Arrange - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRouting(); - app.UseEndpoints(endpoints => + webHostBuilder + .UseTestServer() + .Configure(app => { - endpoints.MapHealthChecks("/healthz"); + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapHealthChecks("/healthz"); + }); + }) + .ConfigureServices(services => + { + services.AddRouting(); + services.AddHealthChecks(); }); - }) - .ConfigureServices(services => - { - services.AddRouting(); - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); // Act @@ -72,34 +86,44 @@ public async Task MapHealthChecks_ReturnsOk() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task MapHealthChecks_WithOptions_ReturnsOk() { // Arrange - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRouting(); - app.UseEndpoints(endpoints => + webHostBuilder + .UseTestServer() + .Configure(app => { - endpoints.MapHealthChecks("/healthz", new HealthCheckOptions + app.UseRouting(); + app.UseEndpoints(endpoints => { - ResponseWriter = async (context, report) => + endpoints.MapHealthChecks("/healthz", new HealthCheckOptions { - context.Response.ContentType = "text/plain"; - await context.Response.WriteAsync("Custom!"); - } + ResponseWriter = async (context, report) => + { + context.Response.ContentType = "text/plain"; + await context.Response.WriteAsync("Custom!"); + } + }); }); + }) + .ConfigureServices(services => + { + services.AddRouting(); + services.AddHealthChecks(); }); - }) - .ConfigureServices(services => - { - services.AddRouting(); - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); // Act @@ -109,6 +133,8 @@ public async Task MapHealthChecks_WithOptions_ReturnsOk() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Custom!", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } } } diff --git a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs index bffed9ed6631..657abce13746 100644 --- a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs +++ b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs @@ -1,10 +1,11 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Diagnostics.HealthChecks @@ -14,25 +15,41 @@ public class HealthCheckMiddlewareSampleTest [Fact] public async Task BasicStartup() { - var builder = new WebHostBuilder() - .UseStartup(); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseStartup(); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task CustomWriterStartup() { - var builder = new WebHostBuilder() - .UseStartup(); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseStartup(); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -40,36 +57,56 @@ public async Task CustomWriterStartup() Assert.Equal("application/json", response.Content.Headers.ContentType.ToString()); // Ignoring the body since it contains a bunch of statistics + + await host.StopAsync(); } [Fact] public async Task LivenessProbeStartup_Liveness() { - var builder = new WebHostBuilder() - .UseStartup(); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseStartup(); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health/live"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task LivenessProbeStartup_Readiness() { - var builder = new WebHostBuilder() - .UseStartup(); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseStartup(); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health/ready"); Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Unhealthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } } } diff --git a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs index 629f46cebe6f..d2235447243b 100644 --- a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs +++ b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs @@ -14,6 +14,7 @@ using System.Net; using System.Threading.Tasks; using Xunit; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.Diagnostics.HealthChecks { @@ -22,13 +23,18 @@ public class HealthCheckMiddlewareTests [Fact] public void ThrowFriendlyErrorWhenServicesNotRegistered() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health"); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }); + }).Build(); - var ex = Assert.Throws(() => new TestServer(builder)); + var ex = Assert.Throws(() => host.Start()); Assert.Equal( "Unable to find the required services. Please add all the required services by calling " + @@ -40,54 +46,82 @@ public void ThrowFriendlyErrorWhenServicesNotRegistered() [Fact] // Matches based on '.Map' public async Task IgnoresRequestThatDoesNotMatchPath() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/frob"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + + await host.StopAsync(); } [Fact] // Matches based on '.Map' public async Task MatchIsCaseInsensitive() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/HEALTH"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + await host.StopAsync(); } [Fact] public async Task ReturnsPlainTextStatus() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -95,21 +129,31 @@ public async Task ReturnsPlainTextStatus() Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task StatusCodeIs200IfNoChecks() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -117,24 +161,34 @@ public async Task StatusCodeIs200IfNoChecks() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task StatusCodeIs200IfAllChecksHealthy() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => - { - services.AddHealthChecks() - .AddCheck("Foo", () => HealthCheckResult.Healthy("A-ok!")) - .AddCheck("Bar", () => HealthCheckResult.Healthy("A-ok!")) - .AddCheck("Baz", () => HealthCheckResult.Healthy("A-ok!")); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks() + .AddCheck("Foo", () => HealthCheckResult.Healthy("A-ok!")) + .AddCheck("Bar", () => HealthCheckResult.Healthy("A-ok!")) + .AddCheck("Baz", () => HealthCheckResult.Healthy("A-ok!")); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -142,24 +196,34 @@ public async Task StatusCodeIs200IfAllChecksHealthy() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task StatusCodeIs200IfCheckIsDegraded() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => - { - services.AddHealthChecks() - .AddCheck("Foo", () => HealthCheckResult.Healthy("A-ok!")) - .AddCheck("Bar", () => HealthCheckResult.Degraded("Not so great.")) - .AddCheck("Baz", () => HealthCheckResult.Healthy("A-ok!")); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks() + .AddCheck("Foo", () => HealthCheckResult.Healthy("A-ok!")) + .AddCheck("Bar", () => HealthCheckResult.Degraded("Not so great.")) + .AddCheck("Baz", () => HealthCheckResult.Healthy("A-ok!")); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -167,24 +231,34 @@ public async Task StatusCodeIs200IfCheckIsDegraded() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Degraded", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task StatusCodeIs503IfCheckIsUnhealthy() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => - { - services.AddHealthChecks() - .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) - .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("Pretty bad."))) - .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks() + .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) + .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("Pretty bad."))) + .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -192,24 +266,34 @@ public async Task StatusCodeIs503IfCheckIsUnhealthy() Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Unhealthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task StatusCodeIs503IfCheckHasUnhandledException() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks() - .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) - .AddAsyncCheck("Bar", () => throw null) - .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks() + .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) + .AddAsyncCheck("Bar", () => throw null) + .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -217,6 +301,8 @@ public async Task StatusCodeIs503IfCheckHasUnhandledException() Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Unhealthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] @@ -227,27 +313,35 @@ public async Task CanUseCustomWriter() status = "Unhealthy", }); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health", new HealthCheckOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - ResponseWriter = (c, r) => + app.UseHealthChecks("/health", new HealthCheckOptions() { - var json = JsonConvert.SerializeObject(new { status = r.Status.ToString(), }); - c.Response.ContentType = "application/json"; - return c.Response.WriteAsync(json); - }, + ResponseWriter = (c, r) => + { + var json = JsonConvert.SerializeObject(new { status = r.Status.ToString(), }); + c.Response.ContentType = "application/json"; + return c.Response.WriteAsync(json); + }, + }); + }) + .ConfigureServices(services => + { + services.AddHealthChecks() + .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) + .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("Pretty bad."))) + .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); }); - }) - .ConfigureServices(services => - { - services.AddHealthChecks() - .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) - .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("Pretty bad."))) - .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -256,75 +350,105 @@ public async Task CanUseCustomWriter() var result = await response.Content.ReadAsStringAsync(); Assert.Equal(expectedJson, result); + + await host.StopAsync(); } [Fact] public async Task NoResponseWriterReturnsEmptyBody() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health", new HealthCheckOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - ResponseWriter = null, + app.UseHealthChecks("/health", new HealthCheckOptions() + { + ResponseWriter = null, + }); + }) + .ConfigureServices(services => + { + services.AddHealthChecks() + .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) + .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("Pretty bad."))) + .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); }); - }) - .ConfigureServices(services => - { - services.AddHealthChecks() - .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) - .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("Pretty bad."))) - .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task CanSetCustomStatusCodes() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health", new HealthCheckOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - ResultStatusCodes = + app.UseHealthChecks("/health", new HealthCheckOptions() { - [HealthStatus.Healthy] = 201, - } + ResultStatusCodes = + { + [HealthStatus.Healthy] = 201, + } + }); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); }); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); Assert.Equal(HttpStatusCode.Created, response.StatusCode); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task SetsCacheHeaders() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -334,24 +458,34 @@ public async Task SetsCacheHeaders() Assert.Equal("no-store, no-cache", response.Headers.CacheControl.ToString()); Assert.Equal("no-cache", response.Headers.Pragma.ToString()); Assert.Equal(new string[] { "Thu, 01 Jan 1970 00:00:00 GMT" }, response.Content.Headers.GetValues(HeaderNames.Expires)); + + await host.StopAsync(); } [Fact] public async Task CanSuppressCacheHeaders() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health", new HealthCheckOptions() + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health", new HealthCheckOptions() + { + AllowCachingResponses = true, + }); + }) + .ConfigureServices(services => { - AllowCachingResponses = true, + services.AddHealthChecks(); }); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -361,28 +495,38 @@ public async Task CanSuppressCacheHeaders() Assert.Null(response.Headers.CacheControl); Assert.Empty(response.Headers.Pragma.ToString()); Assert.False(response.Content.Headers.Contains(HeaderNames.Expires)); + + await host.StopAsync(); } [Fact] public async Task CanFilterChecks() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health", new HealthCheckOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - Predicate = (check) => check.Name == "Foo" || check.Name == "Baz", + app.UseHealthChecks("/health", new HealthCheckOptions() + { + Predicate = (check) => check.Name == "Foo" || check.Name == "Baz", + }); + }) + .ConfigureServices(services => + { + services.AddHealthChecks() + .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) + // Will get filtered out + .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("A-ok!"))) + .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); }); - }) - .ConfigureServices(services => - { - services.AddHealthChecks() - .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) - // Will get filtered out - .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("A-ok!"))) - .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -390,22 +534,31 @@ public async Task CanFilterChecks() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task CanListenWithoutPath_AcceptsRequest() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks(default); - }) - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks(default); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health"); @@ -413,43 +566,61 @@ public async Task CanListenWithoutPath_AcceptsRequest() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task CanListenWithPath_AcceptsRequestWithExtraSlash() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health/"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + + await host.StopAsync(); } [Fact] public async Task CanListenWithPath_AcceptsRequestWithCaseInsensitiveMatch() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/HEALTH"); @@ -457,50 +628,68 @@ public async Task CanListenWithPath_AcceptsRequestWithCaseInsensitiveMatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task CanListenWithPath_RejectsRequestWithExtraSegments() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health/detailed"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + + await host.StopAsync(); } // See: https://github.com/aspnet/Diagnostics/issues/511 [Fact] public async Task CanListenWithPath_MultipleMiddleware_LeastSpecificFirst() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - // Throws if used - app.UseHealthChecks("/health", new HealthCheckOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - ResponseWriter = (c, r) => throw null, + // Throws if used + app.UseHealthChecks("/health", new HealthCheckOptions() + { + ResponseWriter = (c, r) => throw null, + }); + + app.UseHealthChecks("/health/detailed"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); }); + }).Build(); - app.UseHealthChecks("/health/detailed"); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health/detailed"); @@ -508,29 +697,38 @@ public async Task CanListenWithPath_MultipleMiddleware_LeastSpecificFirst() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } // See: https://github.com/aspnet/Diagnostics/issues/511 [Fact] public async Task CanListenWithPath_MultipleMiddleware_MostSpecificFirst() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health/detailed"); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health/detailed"); - // Throws if used - app.UseHealthChecks("/health", new HealthCheckOptions() + // Throws if used + app.UseHealthChecks("/health", new HealthCheckOptions() + { + ResponseWriter = (c, r) => throw null, + }); + }) + .ConfigureServices(services => { - ResponseWriter = (c, r) => throw null, + services.AddHealthChecks(); }); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health/detailed"); @@ -538,30 +736,39 @@ public async Task CanListenWithPath_MultipleMiddleware_MostSpecificFirst() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task CanListenOnPort_AcceptsRequest_OnSpecifiedPort() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(next => async (context) => + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.Use(next => async (context) => + { + // Need to fake setting the connection info. TestServer doesn't + // do that, because it doesn't have a connection. + context.Connection.LocalPort = context.Request.Host.Port.Value; + await next(context); + }); + + app.UseHealthChecks("/health", port: 5001); + }) + .ConfigureServices(services => { - // Need to fake setting the connection info. TestServer doesn't - // do that, because it doesn't have a connection. - context.Connection.LocalPort = context.Request.Host.Port.Value; - await next(context); + services.AddHealthChecks(); }); + }).Build(); - app.UseHealthChecks("/health", port: 5001); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health"); @@ -569,30 +776,39 @@ public async Task CanListenOnPort_AcceptsRequest_OnSpecifiedPort() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task CanListenOnPortWithoutPath_AcceptsRequest_OnSpecifiedPort() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(next => async (context) => + webHostBuilder + .UseTestServer() + .Configure(app => { - // Need to fake setting the connection info. TestServer doesn't - // do that, because it doesn't have a connection. - context.Connection.LocalPort = context.Request.Host.Port.Value; - await next(context); + app.Use(next => async (context) => + { + // Need to fake setting the connection info. TestServer doesn't + // do that, because it doesn't have a connection. + context.Connection.LocalPort = context.Request.Host.Port.Value; + await next(context); + }); + + app.UseHealthChecks(default, port: 5001); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); }); + }).Build(); - app.UseHealthChecks(default, port: 5001); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health"); @@ -600,65 +816,83 @@ public async Task CanListenOnPortWithoutPath_AcceptsRequest_OnSpecifiedPort() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task CanListenOnPort_RejectsRequest_OnOtherPort() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(next => async (context) => + webHostBuilder + .UseTestServer() + .Configure(app => { - // Need to fake setting the connection info. TestServer doesn't - // do that, because it doesn't have a connection. - context.Connection.LocalPort = context.Request.Host.Port.Value; - await next(context); + app.Use(next => async (context) => + { + // Need to fake setting the connection info. TestServer doesn't + // do that, because it doesn't have a connection. + context.Connection.LocalPort = context.Request.Host.Port.Value; + await next(context); + }); + + app.UseHealthChecks("/health", port: 5001); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); }); + }).Build(); - app.UseHealthChecks("/health", port: 5001); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5000/health"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + + await host.StopAsync(); } [Fact] public async Task CanListenOnPort_MultipleMiddleware() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(next => async (context) => + webHostBuilder + .UseTestServer() + .Configure(app => { - // Need to fake setting the connection info. TestServer doesn't - // do that, because it doesn't have a connection. - context.Connection.LocalPort = context.Request.Host.Port.Value; - await next(context); - }); + app.Use(next => async (context) => + { + // Need to fake setting the connection info. TestServer doesn't + // do that, because it doesn't have a connection. + context.Connection.LocalPort = context.Request.Host.Port.Value; + await next(context); + }); + + // Throws if used + app.UseHealthChecks("/health", port: 5001, new HealthCheckOptions() + { + ResponseWriter = (c, r) => throw null, + }); - // Throws if used - app.UseHealthChecks("/health", port: 5001, new HealthCheckOptions() + app.UseHealthChecks("/health/detailed", port: 5001); + }) + .ConfigureServices(services => { - ResponseWriter = (c, r) => throw null, + services.AddHealthChecks(); }); + }).Build(); - app.UseHealthChecks("/health/detailed", port: 5001); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health/detailed"); @@ -666,36 +900,45 @@ public async Task CanListenOnPort_MultipleMiddleware() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } [Fact] public async Task CanListenOnPort_MultipleMiddleware_DifferentPorts() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(next => async (context) => + webHostBuilder + .UseTestServer() + .Configure(app => { - // Need to fake setting the connection info. TestServer doesn't - // do that, because it doesn't have a connection. - context.Connection.LocalPort = context.Request.Host.Port.Value; - await next(context); - }); + app.Use(next => async (context) => + { + // Need to fake setting the connection info. TestServer doesn't + // do that, because it doesn't have a connection. + context.Connection.LocalPort = context.Request.Host.Port.Value; + await next(context); + }); + + // Throws if used + app.UseHealthChecks("/health", port: 5002, new HealthCheckOptions() + { + ResponseWriter = (c, r) => throw null, + }); - // Throws if used - app.UseHealthChecks("/health", port: 5002, new HealthCheckOptions() + app.UseHealthChecks("/health", port: 5001); + }) + .ConfigureServices(services => { - ResponseWriter = (c, r) => throw null, + services.AddHealthChecks(); }); + }).Build(); - app.UseHealthChecks("/health", port: 5001); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health"); @@ -703,8 +946,10 @@ public async Task CanListenOnPort_MultipleMiddleware_DifferentPorts() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } - + [Fact] public void HealthCheckOptions_HasDefaultMappingWithDefaultResultStatusCodes() { @@ -714,7 +959,7 @@ public void HealthCheckOptions_HasDefaultMappingWithDefaultResultStatusCodes() Assert.Equal(StatusCodes.Status200OK, options.ResultStatusCodes[HealthStatus.Degraded]); Assert.Equal(StatusCodes.Status503ServiceUnavailable, options.ResultStatusCodes[HealthStatus.Unhealthy]); } - + [Fact] public void HealthCheckOptions_HasDefaultMappingWhenResettingResultStatusCodes() { @@ -724,8 +969,8 @@ public void HealthCheckOptions_HasDefaultMappingWhenResettingResultStatusCodes() Assert.Equal(StatusCodes.Status200OK, options.ResultStatusCodes[HealthStatus.Degraded]); Assert.Equal(StatusCodes.Status503ServiceUnavailable, options.ResultStatusCodes[HealthStatus.Unhealthy]); } - - + + [Fact] public void HealthCheckOptions_DoesNotThrowWhenProperlyConfiguringResultStatusCodes() { @@ -743,18 +988,18 @@ public void HealthCheckOptions_DoesNotThrowWhenProperlyConfiguringResultStatusCo [Fact] public void HealthCheckOptions_ThrowsWhenAHealthStatusIsMissing() { - var exception = Assert.Throws(() => + var exception = Assert.Throws(() => new HealthCheckOptions { ResultStatusCodes = new Dictionary() } ); Assert.Contains($"{nameof(HealthStatus)}.{nameof(HealthStatus.Healthy)}", exception.Message); Assert.Contains($"{nameof(HealthStatus)}.{nameof(HealthStatus.Degraded)}", exception.Message); Assert.Contains($"{nameof(HealthStatus)}.{nameof(HealthStatus.Unhealthy)}", exception.Message); } - + [Fact] public void HealthCheckOptions_ThrowsWhenAHealthStatusIsMissing_MessageDoesNotContainDefinedStatus() { - var exception = Assert.Throws(() => + var exception = Assert.Throws(() => new HealthCheckOptions { ResultStatusCodes = new Dictionary diff --git a/src/Middleware/HealthChecks/test/testassets/HealthChecksSample/Program.cs b/src/Middleware/HealthChecks/test/testassets/HealthChecksSample/Program.cs index 56e6e6478fa4..754ea5260de7 100644 --- a/src/Middleware/HealthChecks/test/testassets/HealthChecksSample/Program.cs +++ b/src/Middleware/HealthChecks/test/testassets/HealthChecksSample/Program.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.IO; +using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace HealthChecksSample @@ -25,12 +27,12 @@ static Program() }; } - public static void Main(string[] args) + public static Task Main(string[] args) { - BuildWebHost(args).Run(); + return BuildWebHost(args).RunAsync(); } - public static IWebHost BuildWebHost(string[] args) + public static IHost BuildWebHost(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) @@ -45,16 +47,20 @@ public static IWebHost BuildWebHost(string[] args) startupType = typeof(BasicStartup); } - return new WebHostBuilder() - .UseConfiguration(config) - .ConfigureLogging(builder => + return new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - builder.SetMinimumLevel(LogLevel.Trace); - builder.AddConfiguration(config); - builder.AddConsole(); + webHostBuilder + .UseConfiguration(config) + .ConfigureLogging(builder => + { + builder.SetMinimumLevel(LogLevel.Trace); + builder.AddConfiguration(config); + builder.AddConsole(); + }) + .UseKestrel() + .UseStartup(startupType); }) - .UseKestrel() - .UseStartup(startupType) .Build(); } From a9aad9d734573efa4c9d627ce79f634f5949e126 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:05:34 -0700 Subject: [PATCH 07/20] HostFiltering --- .../HostFiltering/sample/Program.cs | 40 +-- .../test/HostFilteringMiddlewareTests.cs | 261 +++++++++++------- 2 files changed, 184 insertions(+), 117 deletions(-) diff --git a/src/Middleware/HostFiltering/sample/Program.cs b/src/Middleware/HostFiltering/sample/Program.cs index 0ccc7cdb2e51..8aad652893bf 100644 --- a/src/Middleware/HostFiltering/sample/Program.cs +++ b/src/Middleware/HostFiltering/sample/Program.cs @@ -1,35 +1,41 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace HostFilteringSample { public class Program { - public static void Main(string[] args) + public static Task Main(string[] args) { - BuildWebHost(args).Run(); + return BuildWebHost(args).RunAsync(); } - public static IWebHost BuildWebHost(string[] args) + public static IHost BuildWebHost(string[] args) { - var hostBuilder = new WebHostBuilder() - .ConfigureLogging((_, factory) => + var hostBuilder = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - factory.SetMinimumLevel(LogLevel.Debug); - factory.AddConsole(); - }) - .ConfigureAppConfiguration((hostingContext, config) => - { - var env = hostingContext.HostingEnvironment; - config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) - .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); - }) - .UseKestrel() - .UseStartup(); + webHostBuilder + .ConfigureLogging((_, factory) => + { + factory.SetMinimumLevel(LogLevel.Debug); + factory.AddConsole(); + }) + .ConfigureAppConfiguration((hostingContext, config) => + { + var env = hostingContext.HostingEnvironment; + config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) + .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); + }) + .UseKestrel() + .UseStartup(); + }); return hostBuilder.Build(); } diff --git a/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs b/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs index 921202dbd361..8e6f9e2480fc 100644 --- a/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs +++ b/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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; @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; @@ -21,12 +22,22 @@ public class HostFilteringMiddlewareTests [Fact] public async Task MissingConfigThrows() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHostFiltering(); - }); - await Assert.ThrowsAsync(() => new TestServer(builder).SendAsync(_ => { })); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHostFiltering(); + }); + }).Build(); + + await host.StartAsync(); + + await Assert.ThrowsAsync(() => host.GetTestServer().SendAsync(_ => { })); + + await host.StopAsync(); } [Theory] @@ -34,32 +45,42 @@ public async Task MissingConfigThrows() [InlineData(false, 400)] public async Task AllowsMissingHost(bool allowed, int status) { - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHostFiltering(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.AllowEmptyHosts = allowed; - options.AllowedHosts.Add("Localhost"); - }); - }) - .Configure(app => - { - app.Use((ctx, next) => - { - ctx.Request.Headers.Remove(HeaderNames.Host); - return next(); - }); - app.UseHostFiltering(); - app.Run(c => + services.AddHostFiltering(options => + { + options.AllowEmptyHosts = allowed; + options.AllowedHosts.Add("Localhost"); + }); + }) + .Configure(app => { - Assert.False(c.Request.Headers.TryGetValue(HeaderNames.Host, out var host)); - return Task.CompletedTask; + app.Use((ctx, next) => + { + ctx.Request.Headers.Remove(HeaderNames.Host); + return next(); + }); + app.UseHostFiltering(); + app.Run(c => + { + Assert.False(c.Request.Headers.TryGetValue(HeaderNames.Host, out var host)); + return Task.CompletedTask; + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(status, (int)response.StatusCode); + + await host.StopAsync(); } [Theory] @@ -67,34 +88,44 @@ public async Task AllowsMissingHost(bool allowed, int status) [InlineData(false, 400)] public async Task AllowsEmptyHost(bool allowed, int status) { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddHostFiltering(options => - { - options.AllowEmptyHosts = allowed; - options.AllowedHosts.Add("Localhost"); - }); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use((ctx, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - ctx.Request.Headers[HeaderNames.Host] = ""; - return next(); - }); - app.UseHostFiltering(); - app.Run(c => + services.AddHostFiltering(options => + { + options.AllowEmptyHosts = allowed; + options.AllowedHosts.Add("Localhost"); + }); + }) + .Configure(app => { - Assert.True(c.Request.Headers.TryGetValue(HeaderNames.Host, out var host)); - Assert.True(StringValues.Equals("", host)); - return Task.CompletedTask; + app.Use((ctx, next) => + { + ctx.Request.Headers[HeaderNames.Host] = ""; + return next(); + }); + app.UseHostFiltering(); + app.Run(c => + { + Assert.True(c.Request.Headers.TryGetValue(HeaderNames.Host, out var host)); + Assert.True(StringValues.Equals("", host)); + return Task.CompletedTask; + }); + app.Run(c => Task.CompletedTask); }); - app.Run(c => Task.CompletedTask); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(status, (int)response.StatusCode); + + await host.StopAsync(); } [Theory] @@ -113,31 +144,41 @@ public async Task AllowsEmptyHost(bool allowed, int status) [InlineData("xn--c1yn36f:443", "點看")] [InlineData("[::ABC]", "[::aBc]")] [InlineData("[::1]:80", "[::1]")] - public async Task AllowsSpecifiedHost(string host, string allowedHost) + public async Task AllowsSpecifiedHost(string hosturl, string allowedHost) { - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHostFiltering(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.AllowedHosts = allowedHost.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - }); - }) - .Configure(app => - { - app.Use((ctx, next) => + services.AddHostFiltering(options => + { + options.AllowedHosts = allowedHost.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + }); + }) + .Configure(app => { - // TestHost's ClientHandler doesn't let you set the host header, only the host in the URI - // and that would over-normalize some of our test conditions like casing. - ctx.Request.Headers[HeaderNames.Host] = host; - return next(); + app.Use((ctx, next) => + { + // TestHost's ClientHandler doesn't let you set the host header, only the host in the URI + // and that would over-normalize some of our test conditions like casing. + ctx.Request.Headers[HeaderNames.Host] = hosturl; + return next(); + }); + app.UseHostFiltering(); + app.Run(c => Task.CompletedTask); }); - app.UseHostFiltering(); - app.Run(c => Task.CompletedTask); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateRequest("/").GetAsync(); Assert.Equal(200, (int)response.StatusCode); + + await host.StopAsync(); } [Theory] @@ -157,31 +198,41 @@ public async Task AllowsSpecifiedHost(string host, string allowedHost) [InlineData("點看", "點看")] [InlineData("[::1", "[::1]")] [InlineData("[::1:80", "[::1]")] - public async Task RejectsMismatchedHosts(string host, string allowedHost) + public async Task RejectsMismatchedHosts(string hosturl, string allowedHost) { - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHostFiltering(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.AllowedHosts = allowedHost.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - }); - }) - .Configure(app => - { - app.Use((ctx, next) => + services.AddHostFiltering(options => + { + options.AllowedHosts = allowedHost.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + }); + }) + .Configure(app => { - // TestHost's ClientHandler doesn't let you set the host header, only the host in the URI - // and that would reject some of our test conditions. - ctx.Request.Headers[HeaderNames.Host] = host; - return next(); + app.Use((ctx, next) => + { + // TestHost's ClientHandler doesn't let you set the host header, only the host in the URI + // and that would reject some of our test conditions. + ctx.Request.Headers[HeaderNames.Host] = hosturl; + return next(); + }); + app.UseHostFiltering(); + app.Run(c => throw new NotImplementedException("App")); }); - app.UseHostFiltering(); - app.Run(c => throw new NotImplementedException("App")); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateRequest("/").GetAsync(); Assert.Equal(400, (int)response.StatusCode); + + await host.StopAsync(); } [Fact] @@ -191,26 +242,34 @@ public async Task SupportsDynamicOptionsReload() config["AllowedHosts"] = "localhost"; var currentHost = "otherHost"; - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHostFiltering(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.AllowedHosts = new[] { config["AllowedHosts"] }; - }); - services.AddSingleton>(new ConfigurationChangeTokenSource(config)); - }) - .Configure(app => - { - app.Use((ctx, next) => + services.AddHostFiltering(options => + { + options.AllowedHosts = new[] { config["AllowedHosts"] }; + }); + services.AddSingleton>(new ConfigurationChangeTokenSource(config)); + }) + .Configure(app => { - ctx.Request.Headers[HeaderNames.Host] = currentHost; - return next(); + app.Use((ctx, next) => + { + ctx.Request.Headers[HeaderNames.Host] = currentHost; + return next(); + }); + app.UseHostFiltering(); + app.Run(c => Task.CompletedTask); }); - app.UseHostFiltering(); - app.Run(c => Task.CompletedTask); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateRequest("/").GetAsync(); Assert.Equal(400, (int)response.StatusCode); @@ -218,6 +277,8 @@ public async Task SupportsDynamicOptionsReload() response = await server.CreateRequest("/").GetAsync(); Assert.Equal(200, (int)response.StatusCode); + + await host.StopAsync(); } private class ReloadableMemorySource : IConfigurationSource From 20c925a4c78e8c68b270aa055c1563121139a287 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:05:59 -0700 Subject: [PATCH 08/20] HttpOverrides --- .../HttpOverrides/sample/Startup.cs | 18 +- .../test/CertificateForwardingTest.cs | 213 ++++-- .../test/ForwardedHeadersMiddlewareTest.cs | 721 ++++++++++++------ .../test/HttpMethodOverrideMiddlewareTest.cs | 187 +++-- 4 files changed, 749 insertions(+), 390 deletions(-) diff --git a/src/Middleware/HttpOverrides/sample/Startup.cs b/src/Middleware/HttpOverrides/sample/Startup.cs index f90cedc70218..69423d52e1c4 100644 --- a/src/Middleware/HttpOverrides/sample/Startup.cs +++ b/src/Middleware/HttpOverrides/sample/Startup.cs @@ -1,7 +1,9 @@ +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.Extensions.Hosting; namespace HttpOverridesSample { @@ -30,15 +32,19 @@ public void Configure(IApplicationBuilder app) } // Entry point for the application. - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - // .UseIIS() // This repo can no longer reference IIS because IISIntegration depends on it. - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + // .UseIIS() // This repo can no longer reference IIS because IISIntegration depends on it. + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs b/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs index 42464ccb9895..717510e7fa54 100644 --- a/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs +++ b/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; using Xunit; @@ -42,152 +43,202 @@ public void VerifySettingEmptyHeaderOptionThrows() [Fact] public async Task VerifyHeaderIsUsedIfNoCertificateAlreadySet() { - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddCertificateForwarding(options => { }); - }) - .Configure(app => - { - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - Assert.Null(context.Connection.ClientCertificate); - await next(); - }); - app.UseCertificateForwarding(); - app.Use(async (context, next) => + services.AddCertificateForwarding(options => { }); + }) + .Configure(app => { - Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); - await next(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + await next(); + }); + app.UseCertificateForwarding(); + app.Use(async (context, next) => + { + Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); + await next(); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { c.Request.Headers["X-Client-Cert"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData); }); + + await host.StopAsync(); } [Fact] public async Task VerifyHeaderOverridesCertificateEvenAlreadySet() { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddCertificateForwarding(options => { }); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - Assert.Null(context.Connection.ClientCertificate); - context.Connection.ClientCertificate = Certificates.SelfSignedNotYetValid; - await next(); - }); - app.UseCertificateForwarding(); - app.Use(async (context, next) => + services.AddCertificateForwarding(options => { }); + }) + .Configure(app => { - Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); - await next(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + context.Connection.ClientCertificate = Certificates.SelfSignedNotYetValid; + await next(); + }); + app.UseCertificateForwarding(); + app.Use(async (context, next) => + { + Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); + await next(); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { c.Request.Headers["X-Client-Cert"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData); }); + + await host.StopAsync(); } [Fact] public async Task VerifySettingTheAzureHeaderOnTheForwarderOptionsWorks() { - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddCertificateForwarding(options => options.CertificateHeader = "X-ARR-ClientCert"); - }) - .Configure(app => - { - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - Assert.Null(context.Connection.ClientCertificate); - await next(); - }); - app.UseCertificateForwarding(); - app.Use(async (context, next) => + services.AddCertificateForwarding(options => options.CertificateHeader = "X-ARR-ClientCert"); + }) + .Configure(app => { - Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); - await next(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + await next(); + }); + app.UseCertificateForwarding(); + app.Use(async (context, next) => + { + Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); + await next(); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { c.Request.Headers["X-ARR-ClientCert"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData); }); + + await host.StopAsync(); } [Fact] public async Task VerifyACustomHeaderFailsIfTheHeaderIsNotPresent() { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddCertificateForwarding(options => options.CertificateHeader = "some-random-header"); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - Assert.Null(context.Connection.ClientCertificate); - await next(); - }); - app.UseCertificateForwarding(); - app.Use(async (context, next) => + services.AddCertificateForwarding(options => options.CertificateHeader = "some-random-header"); + }) + .Configure(app => { - Assert.Null(context.Connection.ClientCertificate); - await next(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + await next(); + }); + app.UseCertificateForwarding(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + await next(); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { c.Request.Headers["not-the-right-header"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData); }); + + await host.StopAsync(); } [Fact] public async Task VerifyArrHeaderEncodedCertFailsOnBadEncoding() { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddCertificateForwarding(options => { }); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - Assert.Null(context.Connection.ClientCertificate); - await next(); - }); - app.UseCertificateForwarding(); - app.Use(async (context, next) => + services.AddCertificateForwarding(options => { }); + }) + .Configure(app => { - Assert.Null(context.Connection.ClientCertificate); - await next(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + await next(); + }); + app.UseCertificateForwarding(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + await next(); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { c.Request.Headers["X-Client-Cert"] = "OOPS" + Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData); }); + + await host.StopAsync(); } private static class Certificates diff --git a/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs b/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs index f427c5b5b404..8663d870062f 100644 --- a/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs +++ b/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Net.Http.Headers; using Xunit; @@ -19,15 +20,23 @@ public class ForwardedHeadersMiddlewareTests [Fact] public async Task XForwardedForDefaultSettingsChangeRemoteIpAndPort() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -40,22 +49,32 @@ public async Task XForwardedForDefaultSettingsChangeRemoteIpAndPort() Assert.False(context.Request.Headers.ContainsKey("X-Original-For")); // Should have been consumed and removed Assert.False(context.Request.Headers.ContainsKey("X-Forwarded-For")); + + await host.StopAsync(); } [Theory] [InlineData(1, "11.111.111.11.12345", "10.0.0.1", 99)] // Invalid public async Task XForwardedForFirstValueIsInvalid(int limit, string header, string expectedIp, int expectedPort) { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor, - ForwardLimit = limit, + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor, + ForwardLimit = limit, + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -69,6 +88,8 @@ public async Task XForwardedForFirstValueIsInvalid(int limit, string header, str Assert.False(context.Request.Headers.ContainsKey("X-Original-For")); Assert.True(context.Request.Headers.ContainsKey("X-Forwarded-For")); Assert.Equal(header, context.Request.Headers["X-Forwarded-For"]); + + await host.StopAsync(); } [Theory] @@ -92,20 +113,28 @@ public async Task XForwardedForFirstValueIsInvalid(int limit, string header, str [InlineData(3, "13.113.113.13:34567, 12.112.112.12:23456, 11.111.111.11:12345", "13.113.113.13", 34567, "", true)] public async Task XForwardedForForwardLimit(int limit, string header, string expectedIp, int expectedPort, string remainingHeader, bool requireSymmetry) { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor, - RequireHeaderSymmetry = requireSymmetry, - ForwardLimit = limit, - }; - options.KnownProxies.Clear(); - options.KnownNetworks.Clear(); - app.UseForwardedHeaders(options); - }); - var server = new TestServer(builder); + var options = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor, + RequireHeaderSymmetry = requireSymmetry, + ForwardLimit = limit, + }; + options.KnownProxies.Clear(); + options.KnownNetworks.Clear(); + app.UseForwardedHeaders(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -117,6 +146,8 @@ public async Task XForwardedForForwardLimit(int limit, string header, string exp Assert.Equal(expectedIp, context.Connection.RemoteIpAddress.ToString()); Assert.Equal(expectedPort, context.Connection.RemotePort); Assert.Equal(remainingHeader, context.Request.Headers["X-Forwarded-For"].ToString()); + + await host.StopAsync(); } [Theory] @@ -127,15 +158,23 @@ public async Task XForwardedForForwardLimit(int limit, string header, string exp [InlineData("::", false)] public async Task XForwardedForLoopback(string originalIp, bool expectForwarded) { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor, + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor, + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -158,6 +197,8 @@ public async Task XForwardedForLoopback(string originalIp, bool expectForwarded) Assert.Equal(99, context.Connection.RemotePort); Assert.False(context.Request.Headers.ContainsKey("X-Original-For")); } + + await host.StopAsync(); } [Theory] @@ -185,22 +226,30 @@ public async Task XForwardedForLoopback(string originalIp, bool expectForwarded) [InlineData(3, "13.113.113.13;34567, 12.112.112.12:23456, 11.111.111.11:12345", "10.0.0.1,11.111.111.11,12.112.112.12", "12.112.112.12", 23456, true)] // Invalid 3rd IP public async Task XForwardedForForwardKnownIps(int limit, string header, string knownIPs, string expectedIp, int expectedPort, bool requireSymmetry) { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor, - RequireHeaderSymmetry = requireSymmetry, - ForwardLimit = limit, - }; - foreach (var ip in knownIPs.Split(',').Select(text => IPAddress.Parse(text))) - { - options.KnownProxies.Add(ip); - } - app.UseForwardedHeaders(options); - }); - var server = new TestServer(builder); + var options = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor, + RequireHeaderSymmetry = requireSymmetry, + ForwardLimit = limit, + }; + foreach (var ip in knownIPs.Split(',').Select(text => IPAddress.Parse(text))) + { + options.KnownProxies.Add(ip); + } + app.UseForwardedHeaders(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -211,20 +260,30 @@ public async Task XForwardedForForwardKnownIps(int limit, string header, string Assert.Equal(expectedIp, context.Connection.RemoteIpAddress.ToString()); Assert.Equal(expectedPort, context.Connection.RemotePort); + + await host.StopAsync(); } [Fact] public async Task XForwardedForOverrideBadIpDoesntChangeRemoteIp() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -232,20 +291,30 @@ public async Task XForwardedForOverrideBadIpDoesntChangeRemoteIp() }); Assert.Null(context.Connection.RemoteIpAddress); + + await host.StopAsync(); } [Fact] public async Task XForwardedHostOverrideChangesRequestHost() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedHost + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedHost + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -253,6 +322,8 @@ public async Task XForwardedHostOverrideChangesRequestHost() }); Assert.Equal("testhost", context.Request.Host.ToString()); + + await host.StopAsync(); } public static TheoryData HostHeaderData @@ -291,31 +362,41 @@ public static TheoryData HostHeaderData [Theory] [MemberData(nameof(HostHeaderData))] - public async Task XForwardedHostAllowsValidCharacters(string host) + public async Task XForwardedHostAllowsValidCharacters(string hostHeader) { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedHost + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedHost + }); + app.Run(context => + { + Assert.Equal(hostHeader, context.Request.Host.ToString()); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - app.Run(context => - { - Assert.Equal(host, context.Request.Host.ToString()); - assertsExecuted = true; - return Task.FromResult(0); - }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); await server.SendAsync(c => { - c.Request.Headers["X-Forwarded-Host"] = host; + c.Request.Headers["X-Forwarded-Host"] = hostHeader; }); Assert.True(assertsExecuted); + + await host.StopAsync(); } public static TheoryData HostHeaderInvalidData @@ -368,31 +449,41 @@ public static TheoryData HostHeaderInvalidData [Theory] [MemberData(nameof(HostHeaderInvalidData))] - public async Task XForwardedHostFailsForInvalidCharacters(string host) + public async Task XForwardedHostFailsForInvalidCharacters(string hostHeader) { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedHost - }); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.NotEqual(host, context.Request.Host.Value); - assertsExecuted = true; - return Task.FromResult(0); + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedHost + }); + app.Run(context => + { + Assert.NotEqual(hostHeader, context.Request.Host.Value); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); await server.SendAsync(c => { - c.Request.Headers["X-Forwarded-Host"] = host; + c.Request.Headers["X-Forwarded-Host"] = hostHeader; }); Assert.True(assertsExecuted); + + await host.StopAsync(); } [Theory] @@ -411,30 +502,40 @@ await server.SendAsync(c => [InlineData("xn--c1yn36f:443", "點看")] [InlineData("[::ABC]", "[::aBc]")] [InlineData("[::1]:80", "[::1]")] - public async Task XForwardedHostAllowsSpecifiedHost(string host, string allowedHost) + public async Task XForwardedHostAllowsSpecifiedHost(string hostHeader, string allowedHost) { bool assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedHost, - AllowedHosts = allowedHost.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedHost, + AllowedHosts = allowedHost.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) + }); + app.Run(context => + { + Assert.Equal(hostHeader, context.Request.Headers[HeaderNames.Host]); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - app.Run(context => - { - Assert.Equal(host, context.Request.Headers[HeaderNames.Host]); - assertsExecuted = true; - return Task.FromResult(0); - }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.SendAsync(ctx => { - ctx.Request.Headers["X-forwarded-Host"] = host; + ctx.Request.Headers["X-forwarded-Host"] = hostHeader; }); Assert.True(assertsExecuted); + + await host.StopAsync(); } [Theory] @@ -454,58 +555,78 @@ public async Task XForwardedHostAllowsSpecifiedHost(string host, string allowedH [InlineData("點看", "點看")] [InlineData("[::1", "[::1]")] [InlineData("[::1:80", "[::1]")] - public async Task XForwardedHostFailsMismatchedHosts(string host, string allowedHost) + public async Task XForwardedHostFailsMismatchedHosts(string hostHeader, string allowedHost) { bool assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedHost, - AllowedHosts = new[] { allowedHost } - }); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.NotEqual(host, context.Request.Headers[HeaderNames.Host]); - assertsExecuted = true; - return Task.FromResult(0); + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedHost, + AllowedHosts = new[] { allowedHost } + }); + app.Run(context => + { + Assert.NotEqual(hostHeader, context.Request.Headers[HeaderNames.Host]); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.SendAsync(ctx => { - ctx.Request.Headers["X-forwarded-Host"] = host; + ctx.Request.Headers["X-forwarded-Host"] = hostHeader; }); Assert.True(assertsExecuted); + + await host.StopAsync(); } [Fact] public async Task XForwardedHostStopsAtFirstUnspecifiedHost() { bool assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedHost, - ForwardLimit = 10, - AllowedHosts = new[] { "bar.com", "*.foo.com" } + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedHost, + ForwardLimit = 10, + AllowedHosts = new[] { "bar.com", "*.foo.com" } + }); + app.Run(context => + { + Assert.Equal("bar.foo.com:432", context.Request.Headers[HeaderNames.Host]); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - app.Run(context => - { - Assert.Equal("bar.foo.com:432", context.Request.Headers[HeaderNames.Host]); - assertsExecuted = true; - return Task.FromResult(0); - }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.SendAsync(ctx => { ctx.Request.Headers["X-forwarded-Host"] = "stuff:523, bar.foo.com:432, bar.com:80"; }); Assert.True(assertsExecuted); + + await host.StopAsync(); } [Theory] @@ -518,16 +639,24 @@ public async Task XForwardedHostStopsAtFirstUnspecifiedHost() [InlineData(10, "h3, h2, h1", "h3")] public async Task XForwardedProtoOverrideChangesRequestProtocol(int limit, string header, string expected) { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedProto, - ForwardLimit = limit, + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto, + ForwardLimit = limit, + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -535,6 +664,8 @@ public async Task XForwardedProtoOverrideChangesRequestProtocol(int limit, strin }); Assert.Equal(expected, context.Request.Scheme); + + await host.StopAsync(); } public static TheoryData ProtoHeaderData @@ -559,27 +690,37 @@ public async Task XForwardedProtoAcceptsValidProtocols(string scheme) { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedProto - }); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Equal(scheme, context.Request.Scheme); - assertsExecuted = true; - return Task.FromResult(0); + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto + }); + app.Run(context => + { + Assert.Equal(scheme, context.Request.Scheme); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); await server.SendAsync(c => { c.Request.Headers["X-Forwarded-Proto"] = scheme; }); Assert.True(assertsExecuted); + + await host.StopAsync(); } public static TheoryData ProtoHeaderInvalidData @@ -608,27 +749,37 @@ public async Task XForwardedProtoRejectsInvalidProtocols(string scheme) { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedProto, + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto, + }); + app.Run(context => + { + Assert.Equal("http", context.Request.Scheme); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - app.Run(context => - { - Assert.Equal("http", context.Request.Scheme); - assertsExecuted = true; - return Task.FromResult(0); - }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); await server.SendAsync(c => { c.Request.Headers["X-Forwarded-Proto"] = scheme; }); Assert.True(assertsExecuted); + + await host.StopAsync(); } [Theory] @@ -642,17 +793,25 @@ await server.SendAsync(c => [InlineData(10, "h3, h2, h1", "::1, badip, ::1", "h1")] public async Task XForwardedProtoOverrideLimitedByXForwardedForCount(int limit, string protoHeader, string forHeader, string expected) { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, - RequireHeaderSymmetry = true, - ForwardLimit = limit, + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, + RequireHeaderSymmetry = true, + ForwardLimit = limit, + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -661,6 +820,8 @@ public async Task XForwardedProtoOverrideLimitedByXForwardedForCount(int limit, }); Assert.Equal(expected, context.Request.Scheme); + + await host.StopAsync(); } [Theory] @@ -676,17 +837,25 @@ public async Task XForwardedProtoOverrideLimitedByXForwardedForCount(int limit, [InlineData(10, "h3, h2, h1", "::1, badip, ::1", "h1")] public async Task XForwardedProtoOverrideCanBeIndependentOfXForwardedForCount(int limit, string protoHeader, string forHeader, string expected) { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, - RequireHeaderSymmetry = false, - ForwardLimit = limit, + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, + RequireHeaderSymmetry = false, + ForwardLimit = limit, + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -695,6 +864,8 @@ public async Task XForwardedProtoOverrideCanBeIndependentOfXForwardedForCount(in }); Assert.Equal(expected, context.Request.Scheme); + + await host.StopAsync(); } [Theory] @@ -712,23 +883,31 @@ public async Task XForwardedProtoOverrideCanBeIndependentOfXForwardedForCount(in [InlineData("h2, h1", "E::, D::", "F::", true, "http")] public async Task XForwardedProtoOverrideLimitedByLoopback(string protoHeader, string forHeader, string remoteIp, bool loopback, string expected) { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, - RequireHeaderSymmetry = true, - ForwardLimit = 5, - }; - if (!loopback) + webHostBuilder + .UseTestServer() + .Configure(app => { - options.KnownNetworks.Clear(); - options.KnownProxies.Clear(); - } - app.UseForwardedHeaders(options); - }); - var server = new TestServer(builder); + var options = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, + RequireHeaderSymmetry = true, + ForwardLimit = 5, + }; + if (!loopback) + { + options.KnownNetworks.Clear(); + options.KnownProxies.Clear(); + } + app.UseForwardedHeaders(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -738,6 +917,8 @@ public async Task XForwardedProtoOverrideLimitedByLoopback(string protoHeader, s }); Assert.Equal(expected, context.Request.Scheme); + + await host.StopAsync(); } [Fact] @@ -753,15 +934,23 @@ public void AllForwardsDisabledByDefault() [Fact] public async Task AllForwardsEnabledChangeRequestRemoteIpHostandProtocol() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.All + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.All + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -773,20 +962,30 @@ public async Task AllForwardsEnabledChangeRequestRemoteIpHostandProtocol() Assert.Equal("11.111.111.11", context.Connection.RemoteIpAddress.ToString()); Assert.Equal("testhost", context.Request.Host.ToString()); Assert.Equal("Protocol", context.Request.Scheme); + + await host.StopAsync(); } [Fact] public async Task AllOptionsDisabledRequestDoesntChange() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.None + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.None + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -798,20 +997,30 @@ public async Task AllOptionsDisabledRequestDoesntChange() Assert.Null(context.Connection.RemoteIpAddress); Assert.Equal("localhost", context.Request.Host.ToString()); Assert.Equal("http", context.Request.Scheme); + + await host.StopAsync(); } [Fact] public async Task PartiallyEnabledForwardsPartiallyChangesRequest() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -822,6 +1031,8 @@ public async Task PartiallyEnabledForwardsPartiallyChangesRequest() Assert.Equal("11.111.111.11", context.Connection.RemoteIpAddress.ToString()); Assert.Equal("localhost", context.Request.Host.ToString()); Assert.Equal("Protocol", context.Request.Scheme); + + await host.StopAsync(); } [Theory] @@ -852,12 +1063,20 @@ public async Task XForwardForIPv4ToIPv6Mapping(string forHeader, string knownPro options.KnownNetworks.Add(new IPNetwork(networkIp, prefixLength)); } - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseForwardedHeaders(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -865,6 +1084,8 @@ public async Task XForwardForIPv4ToIPv6Mapping(string forHeader, string knownPro }); Assert.Equal(expectedRemoteIp, context.Connection.RemoteIpAddress.ToString()); + + await host.StopAsync(); } [Theory] @@ -872,23 +1093,31 @@ public async Task XForwardForIPv4ToIPv6Mapping(string forHeader, string knownPro [InlineData(2, "httpa, httpb, httpc", "httpb", "httpa")] public async Task ForwardersWithDIOptionsRunsOnce(int limit, string header, string expectedScheme, string remainingHeader) { - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.Configure(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.ForwardedHeaders = ForwardedHeaders.XForwardedProto; - options.KnownProxies.Clear(); - options.KnownNetworks.Clear(); - options.ForwardLimit = limit; + services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedProto; + options.KnownProxies.Clear(); + options.KnownNetworks.Clear(); + options.ForwardLimit = limit; + }); + }) + .Configure(app => + { + app.UseForwardedHeaders(); + app.UseForwardedHeaders(); }); - }) - .Configure(app => - { - app.UseForwardedHeaders(); - app.UseForwardedHeaders(); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -897,6 +1126,8 @@ public async Task ForwardersWithDIOptionsRunsOnce(int limit, string header, stri Assert.Equal(expectedScheme, context.Request.Scheme); Assert.Equal(remainingHeader, context.Request.Headers["X-Forwarded-Proto"].ToString()); + + await host.StopAsync(); } [Theory] @@ -904,20 +1135,28 @@ public async Task ForwardersWithDIOptionsRunsOnce(int limit, string header, stri [InlineData(2, "httpa, httpb, httpc", "httpa", "")] public async Task ForwardersWithDirectOptionsRunsTwice(int limit, string header, string expectedScheme, string remainingHeader) { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedProto, - ForwardLimit = limit, - }; - options.KnownProxies.Clear(); - options.KnownNetworks.Clear(); - app.UseForwardedHeaders(options); - app.UseForwardedHeaders(options); - }); - var server = new TestServer(builder); + var options = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto, + ForwardLimit = limit, + }; + options.KnownProxies.Clear(); + options.KnownNetworks.Clear(); + app.UseForwardedHeaders(options); + app.UseForwardedHeaders(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -926,6 +1165,8 @@ public async Task ForwardersWithDirectOptionsRunsTwice(int limit, string header, Assert.Equal(expectedScheme, context.Request.Scheme); Assert.Equal(remainingHeader, context.Request.Headers["X-Forwarded-Proto"].ToString()); + + await host.StopAsync(); } } } diff --git a/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs b/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs index fcd47da8ba83..af8893f3ab2d 100644 --- a/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs +++ b/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs @@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.HttpOverrides @@ -17,67 +18,97 @@ public class HttpMethodOverrideMiddlewareTest public async Task XHttpMethodOverrideHeaderAvaiableChangesRequestMethod() { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpMethodOverride(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - assertsExecuted = true; - Assert.Equal("DELETE", context.Request.Method); - return Task.FromResult(0); + app.UseHttpMethodOverride(); + app.Run(context => + { + assertsExecuted = true; + Assert.Equal("DELETE", context.Request.Method); + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); req.Headers.Add("X-Http-Method-Override", "DELETE"); await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); + + await host.StopAsync(); } [Fact] public async Task XHttpMethodOverrideHeaderUnavaiableDoesntChangeRequestMethod() { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpMethodOverride(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Equal("POST",context.Request.Method); - assertsExecuted = true; - return Task.FromResult(0); + app.UseHttpMethodOverride(); + app.Run(context => + { + Assert.Equal("POST", context.Request.Method); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); + + await host.StopAsync(); } [Fact] public async Task XHttpMethodOverrideFromGetRequestDoesntChangeMethodType() { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpMethodOverride(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Equal("GET", context.Request.Method); - assertsExecuted = true; - return Task.FromResult(0); + app.UseHttpMethodOverride(); + app.Run(context => + { + Assert.Equal("GET", context.Request.Method); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, ""); await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); + + await host.StopAsync(); } @@ -85,21 +116,29 @@ public async Task XHttpMethodOverrideFromGetRequestDoesntChangeMethodType() public async Task FormFieldAvailableChangesRequestMethod() { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpMethodOverride(new HttpMethodOverrideOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - FormFieldName = "_METHOD" + app.UseHttpMethodOverride(new HttpMethodOverrideOptions() + { + FormFieldName = "_METHOD" + }); + app.Run(context => + { + Assert.Equal("DELETE", context.Request.Method); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - app.Run(context => - { - Assert.Equal("DELETE", context.Request.Method); - assertsExecuted = true; - return Task.FromResult(0); - }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); req.Content = new FormUrlEncodedContent(new Dictionary() @@ -110,27 +149,37 @@ public async Task FormFieldAvailableChangesRequestMethod() await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); + + await host.StopAsync(); } [Fact] public async Task FormFieldUnavailableDoesNotChangeRequestMethod() { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpMethodOverride(new HttpMethodOverrideOptions() - { - FormFieldName = "_METHOD" - }); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Equal("POST", context.Request.Method); - assertsExecuted = true; - return Task.FromResult(0); + app.UseHttpMethodOverride(new HttpMethodOverrideOptions() + { + FormFieldName = "_METHOD" + }); + app.Run(context => + { + Assert.Equal("POST", context.Request.Method); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); req.Content = new FormUrlEncodedContent(new Dictionary() @@ -140,27 +189,37 @@ public async Task FormFieldUnavailableDoesNotChangeRequestMethod() await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); + + await host.StopAsync(); } [Fact] public async Task FormFieldEmptyDoesNotChangeRequestMethod() { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpMethodOverride(new HttpMethodOverrideOptions() - { - FormFieldName = "_METHOD" - }); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Equal("POST", context.Request.Method); - assertsExecuted = true; - return Task.FromResult(0); + app.UseHttpMethodOverride(new HttpMethodOverrideOptions() + { + FormFieldName = "_METHOD" + }); + app.Run(context => + { + Assert.Equal("POST", context.Request.Method); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); req.Content = new FormUrlEncodedContent(new Dictionary() @@ -171,6 +230,8 @@ public async Task FormFieldEmptyDoesNotChangeRequestMethod() await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); + + await host.StopAsync(); } } } From fff8195d79864b120aeb0c8dfefc90e8f4d74938 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:06:30 -0700 Subject: [PATCH 09/20] HttpsPolicy --- src/Middleware/HttpsPolicy/sample/Startup.cs | 38 +- .../HttpsPolicy/test/HstsMiddlewareTests.cs | 308 ++++++++++------ .../HttpsPolicy/test/HttpsPolicyTests.cs | 60 ++-- .../test/HttpsRedirectionMiddlewareTests.cs | 329 +++++++++++------- 4 files changed, 451 insertions(+), 284 deletions(-) diff --git a/src/Middleware/HttpsPolicy/sample/Startup.cs b/src/Middleware/HttpsPolicy/sample/Startup.cs index 6f2f5f7eb51d..cd83e7f3df7d 100644 --- a/src/Middleware/HttpsPolicy/sample/Startup.cs +++ b/src/Middleware/HttpsPolicy/sample/Startup.cs @@ -49,30 +49,34 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment environment) } // Entry point for the application. - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel( - options => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(new IPEndPoint(IPAddress.Loopback, 5001), listenOptions => + webHostBuilder + .UseKestrel( + options => { - listenOptions.UseHttps("testCert.pfx", "testPassword"); - }); - options.Listen(new IPEndPoint(IPAddress.Loopback, 5000), listenOptions => + options.Listen(new IPEndPoint(IPAddress.Loopback, 5001), listenOptions => + { + listenOptions.UseHttps("testCert.pfx", "testPassword"); + }); + options.Listen(new IPEndPoint(IPAddress.Loopback, 5000), listenOptions => + { + }); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) // for the cert file + .ConfigureLogging(factory => { - }); + factory.SetMinimumLevel(LogLevel.Debug); + factory.AddConsole(); + }) + .UseStartup(); }) - .UseContentRoot(Directory.GetCurrentDirectory()) // for the cert file - .ConfigureLogging(factory => - { - factory.SetMinimumLevel(LogLevel.Debug); - factory.AddConsole(); - }) - .UseStartup() .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs b/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs index 0cb5f5755c96..37d44fe489d2 100644 --- a/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs +++ b/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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; @@ -12,6 +12,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Microsoft.Net.Http.Headers; @@ -24,20 +25,27 @@ public class HstsMiddlewareTests [Fact] public async Task SetOptionsWithDefault_SetsMaxAgeToCorrectValue() { - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - }) - .Configure(app => - { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); client.BaseAddress = new Uri("https://example.com:5050"); @@ -47,6 +55,8 @@ public async Task SetOptionsWithDefault_SetsMaxAgeToCorrectValue() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("max-age=2592000", response.Headers.GetValues(HeaderNames.StrictTransportSecurity).FirstOrDefault()); + + await host.StopAsync(); } [Theory] @@ -58,25 +68,33 @@ public async Task SetOptionsWithDefault_SetsMaxAgeToCorrectValue() [InlineData(50000, true, true, "max-age=50000; includeSubDomains; preload")] public async Task SetOptionsThroughConfigure_SetsHeaderCorrectly(int maxAge, bool includeSubDomains, bool preload, string expected) { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.Configure(options => { - options.Preload = preload; - options.IncludeSubDomains = includeSubDomains; - options.MaxAge = TimeSpan.FromSeconds(maxAge); - }); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - return context.Response.WriteAsync("Hello world"); + services.Configure(options => + { + options.Preload = preload; + options.IncludeSubDomains = includeSubDomains; + options.MaxAge = TimeSpan.FromSeconds(maxAge); + }); + }) + .Configure(app => + { + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); client.BaseAddress = new Uri("https://example.com:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -85,6 +103,8 @@ public async Task SetOptionsThroughConfigure_SetsHeaderCorrectly(int maxAge, boo Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expected, response.Headers.GetValues(HeaderNames.StrictTransportSecurity).FirstOrDefault()); + + await host.StopAsync(); } [Theory] @@ -96,25 +116,33 @@ public async Task SetOptionsThroughConfigure_SetsHeaderCorrectly(int maxAge, boo [InlineData(50000, true, true, "max-age=50000; includeSubDomains; preload")] public async Task SetOptionsThroughHelper_SetsHeaderCorrectly(int maxAge, bool includeSubDomains, bool preload, string expected) { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddHsts(options => { - options.Preload = preload; - options.IncludeSubDomains = includeSubDomains; - options.MaxAge = TimeSpan.FromSeconds(maxAge); - }); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - return context.Response.WriteAsync("Hello world"); + services.AddHsts(options => + { + options.Preload = preload; + options.IncludeSubDomains = includeSubDomains; + options.MaxAge = TimeSpan.FromSeconds(maxAge); + }); + }) + .Configure(app => + { + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); client.BaseAddress = new Uri("https://example.com:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -123,6 +151,8 @@ public async Task SetOptionsThroughHelper_SetsHeaderCorrectly(int maxAge, bool i Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expected, response.Headers.GetValues(HeaderNames.StrictTransportSecurity).FirstOrDefault()); + + await host.StopAsync(); } [Theory] @@ -131,29 +161,37 @@ public async Task SetOptionsThroughHelper_SetsHeaderCorrectly(int maxAge, bool i [InlineData("LOCALHOST")] [InlineData("127.0.0.1")] [InlineData("[::1]")] - public async Task DefaultExcludesCommonLocalhostDomains_DoesNotSetHstsHeader(string host) + public async Task DefaultExcludesCommonLocalhostDomains_DoesNotSetHstsHeader(string hostUrl) { var sink = new TestSink( TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddSingleton(loggerFactory); - }) - .Configure(app => + + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - return context.Response.WriteAsync("Hello world"); + services.AddSingleton(loggerFactory); + }) + .Configure(app => + { + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); - client.BaseAddress = new Uri($"https://{host}:5050"); + client.BaseAddress = new Uri($"https://{hostUrl}:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); var response = await client.SendAsync(request); @@ -166,41 +204,51 @@ public async Task DefaultExcludesCommonLocalhostDomains_DoesNotSetHstsHeader(str Assert.Single(logMessages); var message = logMessages.Single(); Assert.Equal(LogLevel.Debug, message.LogLevel); - Assert.Equal($"The host '{host}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true); + Assert.Equal($"The host '{hostUrl}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true); + + await host.StopAsync(); } [Theory] [InlineData("localhost")] [InlineData("127.0.0.1")] [InlineData("[::1]")] - public async Task AllowLocalhostDomainsIfListIsReset_SetHstsHeader(string host) + public async Task AllowLocalhostDomainsIfListIsReset_SetHstsHeader(string hostUrl) { var sink = new TestSink( TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - - services.AddHsts(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.ExcludedHosts.Clear(); - }); - }) - .Configure(app => - { - app.UseHsts(); - app.Run(context => + services.AddSingleton(loggerFactory); + + services.AddHsts(options => + { + options.ExcludedHosts.Clear(); + }); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); - client.BaseAddress = new Uri($"https://{host}:5050"); + client.BaseAddress = new Uri($"https://{hostUrl}:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); var response = await client.SendAsync(request); @@ -214,39 +262,50 @@ public async Task AllowLocalhostDomainsIfListIsReset_SetHstsHeader(string host) var message = logMessages.Single(); Assert.Equal(LogLevel.Trace, message.LogLevel); Assert.Equal("Adding HSTS header to response.", message.State.ToString()); + + await host.StopAsync(); } - + [Theory] [InlineData("example.com")] [InlineData("Example.com")] [InlineData("EXAMPLE.COM")] - public async Task AddExcludedDomains_DoesNotAddHstsHeader(string host) + public async Task AddExcludedDomains_DoesNotAddHstsHeader(string hostUrl) { var sink = new TestSink( TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - - services.AddHsts(options => { - options.ExcludedHosts.Add(host); - }); - }) - .Configure(app => - { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + + services.AddHsts(options => + { + options.ExcludedHosts.Add(hostUrl); + }); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); - client.BaseAddress = new Uri($"https://{host}:5050"); + client.BaseAddress = new Uri($"https://{hostUrl}:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); var response = await client.SendAsync(request); @@ -259,7 +318,9 @@ public async Task AddExcludedDomains_DoesNotAddHstsHeader(string host) Assert.Single(logMessages); var message = logMessages.Single(); Assert.Equal(LogLevel.Debug, message.LogLevel); - Assert.Equal($"The host '{host}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true); + Assert.Equal($"The host '{hostUrl}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true); + + await host.StopAsync(); } [Fact] @@ -270,20 +331,28 @@ public async Task WhenRequestIsInsecure_DoesNotAddHstsHeader() TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddSingleton(loggerFactory); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); client.BaseAddress = new Uri("http://example.com:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -299,6 +368,8 @@ public async Task WhenRequestIsInsecure_DoesNotAddHstsHeader() var message = logMessages.Single(); Assert.Equal(LogLevel.Debug, message.LogLevel); Assert.Equal("The request is insecure. Skipping HSTS header.", message.State.ToString()); + + await host.StopAsync(); } [Fact] @@ -309,20 +380,27 @@ public async Task WhenRequestIsSecure_AddsHstsHeader() TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddSingleton(loggerFactory); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + var server = host.GetTestServer(); var client = server.CreateClient(); client.BaseAddress = new Uri("https://example.com:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -338,6 +416,8 @@ public async Task WhenRequestIsSecure_AddsHstsHeader() var message = logMessages.Single(); Assert.Equal(LogLevel.Trace, message.LogLevel); Assert.Equal("Adding HSTS header to response.", message.State.ToString()); + + await host.StopAsync(); } } } diff --git a/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs b/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs index 2b9b3d3b4924..457042331832 100644 --- a/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs +++ b/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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; @@ -13,6 +13,7 @@ using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Net.Http.Headers; using Xunit; @@ -30,36 +31,41 @@ public class HttpsPolicyTests [InlineData(302, 5050, 2592000, true, true, "max-age=2592000; includeSubDomains; preload", "https://localhost:5050/")] public async Task SetsBothHstsAndHttpsRedirection_RedirectOnFirstRequest_HstsOnSecondRequest(int statusCode, int? tlsPort, int maxAge, bool includeSubDomains, bool preload, string expectedHstsHeader, string expectedUrl) { - - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.Configure(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.RedirectStatusCode = statusCode; - options.HttpsPort = tlsPort; - }); - services.Configure(options => + services.Configure(options => + { + options.RedirectStatusCode = statusCode; + options.HttpsPort = tlsPort; + }); + services.Configure(options => + { + options.IncludeSubDomains = includeSubDomains; + options.MaxAge = TimeSpan.FromSeconds(maxAge); + options.Preload = preload; + options.ExcludedHosts.Clear(); // allowing localhost for testing + }); + }) + .Configure(app => { - options.IncludeSubDomains = includeSubDomains; - options.MaxAge = TimeSpan.FromSeconds(maxAge); - options.Preload = preload; - options.ExcludedHosts.Clear(); // allowing localhost for testing + app.UseHttpsRedirection(); + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.UseHsts(); - app.Run(context => - { - return context.Response.WriteAsync("Hello world"); - }); - }); + }).Build(); + + await host.StartAsync(); - var featureCollection = new FeatureCollection(); - featureCollection.Set(new ServerAddressesFeature()); - var server = new TestServer(builder, featureCollection); + var server = host.GetTestServer(); + server.Features.Set(new ServerAddressesFeature()); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -75,6 +81,8 @@ public async Task SetsBothHstsAndHttpsRedirection_RedirectOnFirstRequest_HstsOnS response = await client.SendAsync(request); Assert.Equal(expectedHstsHeader, response.Headers.GetValues(HeaderNames.StrictTransportSecurity).FirstOrDefault()); + + await host.StopAsync(); } } } diff --git a/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs b/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs index ef0b0c368598..d83c1a93dce3 100644 --- a/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs +++ b/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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; @@ -8,11 +8,13 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Xunit; @@ -28,21 +30,28 @@ public async Task SetOptions_NotEnabledByDefault() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -57,6 +66,8 @@ public async Task SetOptions_NotEnabledByDefault() var message = logMessages.Single(); Assert.Equal(LogLevel.Warning, message.LogLevel); Assert.Equal("Failed to determine the https port for redirect.", message.State.ToString()); + + await host.StopAsync(); } [Theory] @@ -71,26 +82,33 @@ public async Task SetOptions_SetStatusCodeHttpsPort(int statusCode, int? httpsPo TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - services.Configure(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.RedirectStatusCode = statusCode; - options.HttpsPort = httpsPort; - }); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + services.AddSingleton(loggerFactory); + services.Configure(options => + { + options.RedirectStatusCode = statusCode; + options.HttpsPort = httpsPort; + }); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -106,6 +124,8 @@ public async Task SetOptions_SetStatusCodeHttpsPort(int statusCode, int? httpsPo var message = logMessages.Single(); Assert.Equal(LogLevel.Debug, message.LogLevel); Assert.Equal($"Redirecting to '{expected}'.", message.State.ToString()); + + await host.StopAsync(); } [Theory] @@ -120,26 +140,33 @@ public async Task SetOptionsThroughHelperMethod_SetStatusCodeAndHttpsPort(int st TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - services.AddHttpsRedirection(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.RedirectStatusCode = statusCode; - options.HttpsPort = httpsPort; - }); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + services.AddSingleton(loggerFactory); + services.AddHttpsRedirection(options => + { + options.RedirectStatusCode = statusCode; + options.HttpsPort = httpsPort; + }); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -155,6 +182,8 @@ public async Task SetOptionsThroughHelperMethod_SetStatusCodeAndHttpsPort(int st var message = logMessages.Single(); Assert.Equal(LogLevel.Debug, message.LogLevel); Assert.Equal($"Redirecting to '{expectedUrl}'.", message.State.ToString()); + + await host.StopAsync(); } [Theory] @@ -169,34 +198,39 @@ public async Task SetOptionsThroughHelperMethod_SetStatusCodeAndHttpsPort(int st public async Task SetHttpsPortEnvironmentVariableAndServerFeature_ReturnsCorrectStatusCodeOnResponse( int? optionsHttpsPort, string configHttpsPort, string serverAddressFeatureUrl, string expectedUrl) { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddHttpsRedirection(options => - { - options.HttpsPort = optionsHttpsPort; - }); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => - { - return context.Response.WriteAsync("Hello world"); - }); - }); - - builder.UseSetting("HTTPS_PORT", configHttpsPort); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddHttpsRedirection(options => + { + options.HttpsPort = optionsHttpsPort; + }); + }) + .Configure(app => + { + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); + }); - var featureCollection = new FeatureCollection(); - featureCollection.Set(new ServerAddressesFeature()); + webHostBuilder.UseSetting("HTTPS_PORT", configHttpsPort); + }).Build(); - var server = new TestServer(builder, featureCollection); + var server = host.GetTestServer(); + server.Features.Set(new ServerAddressesFeature()); if (serverAddressFeatureUrl != null) { server.Features.Get().Addresses.Add(serverAddressFeatureUrl); } + await host.StartAsync(); + var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -204,6 +238,8 @@ public async Task SetHttpsPortEnvironmentVariableAndServerFeature_ReturnsCorrect var response = await client.SendAsync(request); Assert.Equal(expectedUrl, response.Headers.Location.ToString()); + + await host.StopAsync(); } [Fact] @@ -213,25 +249,30 @@ public async Task SetServerAddressesFeature_SingleHttpsAddress_Success() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); - var featureCollection = new FeatureCollection(); - featureCollection.Set(new ServerAddressesFeature()); - var server = new TestServer(builder, featureCollection); + var server = host.GetTestServer(); + server.Features.Set(new ServerAddressesFeature()); server.Features.Get().Addresses.Add("https://localhost:5050"); + await host.StartAsync(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -250,6 +291,8 @@ public async Task SetServerAddressesFeature_SingleHttpsAddress_Success() message = logMessages.Skip(1).First(); Assert.Equal(LogLevel.Debug, message.LogLevel); Assert.Equal("Redirecting to 'https://localhost:5050/'.", message.State.ToString()); + + await host.StopAsync(); } [Fact] @@ -259,27 +302,33 @@ public async Task SetServerAddressesFeature_MultipleHttpsAddresses_LogsAndFailsT TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); - var featureCollection = new FeatureCollection(); - featureCollection.Set(new ServerAddressesFeature()); - var server = new TestServer(builder, featureCollection); + var server = host.GetTestServer(); + server.Features.Set(new ServerAddressesFeature()); server.Features.Get().Addresses.Add("https://localhost:5050"); server.Features.Get().Addresses.Add("https://localhost:5051"); + await host.StartAsync(); + var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -294,6 +343,8 @@ public async Task SetServerAddressesFeature_MultipleHttpsAddresses_LogsAndFailsT Assert.Equal(LogLevel.Warning, message.LogLevel); Assert.Equal("Cannot determine the https port from IServerAddressesFeature, multiple values were found. " + "Please set the desired port explicitly on HttpsRedirectionOptions.HttpsPort.", message.State.ToString()); + + await host.StopAsync(); } [Fact] @@ -303,27 +354,32 @@ public async Task SetServerAddressesFeature_MultipleHttpsAddressesWithSamePort_S TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); - - var featureCollection = new FeatureCollection(); - featureCollection.Set(new ServerAddressesFeature()); - var server = new TestServer(builder, featureCollection); + }).Build(); + var server = host.GetTestServer(); + server.Features.Set(new ServerAddressesFeature()); server.Features.Get().Addresses.Add("https://localhost:5050"); server.Features.Get().Addresses.Add("https://example.com:5050"); + await host.StartAsync(); + var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -342,6 +398,8 @@ public async Task SetServerAddressesFeature_MultipleHttpsAddressesWithSamePort_S message = logMessages.Skip(1).First(); Assert.Equal(LogLevel.Debug, message.LogLevel); Assert.Equal("Redirecting to 'https://localhost:5050/'.", message.State.ToString()); + + await host.StopAsync(); } [Fact] @@ -351,21 +409,28 @@ public async Task NoServerAddressFeature_DoesNotThrow_DoesNotRedirect() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddSingleton(loggerFactory); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpsRedirection(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - return context.Response.WriteAsync("Hello world"); + services.AddSingleton(loggerFactory); + }) + .Configure(app => + { + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); var response = await client.SendAsync(request); @@ -377,6 +442,8 @@ public async Task NoServerAddressFeature_DoesNotThrow_DoesNotRedirect() var message = logMessages.First(); Assert.Equal(LogLevel.Warning, message.LogLevel); Assert.Equal("Failed to determine the https port for redirect.", message.State.ToString()); + + await host.StopAsync(); } [Fact] @@ -386,23 +453,29 @@ public async Task SetNullAddressFeature_DoesNotThrow() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddSingleton(loggerFactory); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpsRedirection(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); - var featureCollection = new FeatureCollection(); - featureCollection.Set(null); - var server = new TestServer(builder, featureCollection); + var server = host.GetTestServer(); + server.Features.Set(null); + + await host.StartAsync(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -415,6 +488,8 @@ public async Task SetNullAddressFeature_DoesNotThrow() var message = logMessages.First(); Assert.Equal(LogLevel.Warning, message.LogLevel); Assert.Equal("Failed to determine the https port for redirect.", message.State.ToString()); + + await host.StopAsync(); } } } From 51c45389d09952c05c4ab3f647d8d5ad87741029 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:07:17 -0700 Subject: [PATCH 10/20] Localization --- .../RouteDataRequestCultureProviderTest.cs | 206 +++++---- src/Middleware/Localization/sample/Startup.cs | 26 +- .../FunctionalTests/LocalizationSampleTest.cs | 16 +- .../test/FunctionalTests/LocalizationTest.cs | 18 +- ...anguageHeaderRequestCultureProviderTest.cs | 185 ++++---- .../CookieRequestCultureProviderTest.cs | 290 +++++++------ .../CustomRequestCultureProviderTest.cs | 66 +-- .../QueryStringRequestCultureProviderTest.cs | 403 +++++++++++------- .../testassets/LocalizationWebsite/Program.cs | 24 +- 9 files changed, 732 insertions(+), 502 deletions(-) diff --git a/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs b/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs index 72e729285927..b3743d32efd8 100644 --- a/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs +++ b/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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.Collections.Generic; @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Localization.Routing @@ -30,50 +31,57 @@ public async Task GetCultureInfo_FromRouteData( string expectedCulture, string expectedUICulture) { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRouter(routes => + webHostBuilder + .UseTestServer() + .Configure(app => { - routes.MapMiddlewareRoute(routeTemplate, fork => + app.UseRouter(routes => { - var options = new RequestLocalizationOptions + routes.MapMiddlewareRoute(routeTemplate, fork => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }; + options.RequestCultureProviders = new[] { - new CultureInfo("ar-YE") - } - }; - options.RequestCultureProviders = new[] - { - new RouteDataRequestCultureProvider() - { - Options = options - } - }; - fork.UseRequestLocalization(options); + new RouteDataRequestCultureProvider() + { + Options = options + } + }; + fork.UseRequestLocalization(options); - fork.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - return context.Response.WriteAsync( - $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"); + fork.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + return context.Response.WriteAsync( + $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"); + }); }); }); + }) + .ConfigureServices(services => + { + services.AddRouting(); }); - }) - .ConfigureServices(services => - { - services.AddRouting(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(requestUrl); @@ -82,37 +90,46 @@ public async Task GetCultureInfo_FromRouteData( var data = await response.Content.ReadAsStringAsync(); Assert.Equal($"{expectedCulture},{expectedUICulture}", data); } + + await host.StopAsync(); } [Fact] public async Task GetDefaultCultureInfo_IfCultureKeysAreMissing() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions - { - DefaultRequestCulture = new RequestCulture("en-US") - }; - options.RequestCultureProviders = new[] + webHostBuilder + .UseTestServer() + .Configure(app => { - new RouteDataRequestCultureProvider() + var options = new RequestLocalizationOptions { - Options = options - } - }; - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; + DefaultRequestCulture = new RequestCulture("en-US") + }; + options.RequestCultureProviders = new[] + { + new RouteDataRequestCultureProvider() + { + Options = options + } + }; + app.UseRequestLocalization(options); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; - return context.Response.WriteAsync( - $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"); + return context.Response.WriteAsync( + $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page"); @@ -121,6 +138,8 @@ public async Task GetDefaultCultureInfo_IfCultureKeysAreMissing() var data = await response.Content.ReadAsStringAsync(); Assert.Equal("en-US,en-US", data); } + + await host.StopAsync(); } [Theory] @@ -135,53 +154,60 @@ public async Task GetCultureInfo_FromRouteData_WithCustomKeys( string expectedCulture, string expectedUICulture) { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRouter(routes => + webHostBuilder + .UseTestServer() + .Configure(app => { - routes.MapMiddlewareRoute(routeTemplate, fork => + app.UseRouter(routes => { - var options = new RequestLocalizationOptions + routes.MapMiddlewareRoute(routeTemplate, fork => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }; + options.RequestCultureProviders = new[] { - new CultureInfo("ar-YE") - } - }; - options.RequestCultureProviders = new[] - { - new RouteDataRequestCultureProvider() + new RouteDataRequestCultureProvider() + { + Options = options, + RouteDataStringKey = "c", + UIRouteDataStringKey = "uic" + } + }; + fork.UseRequestLocalization(options); + + fork.Run(context => { - Options = options, - RouteDataStringKey = "c", - UIRouteDataStringKey = "uic" - } - }; - fork.UseRequestLocalization(options); - - fork.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; - return context.Response.WriteAsync( - $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"); + return context.Response.WriteAsync( + $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"); + }); }); }); + }) + .ConfigureServices(services => + { + services.AddRouting(); }); - }) - .ConfigureServices(services => - { - services.AddRouting(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(requestUrl); @@ -190,6 +216,8 @@ public async Task GetCultureInfo_FromRouteData_WithCustomKeys( var data = await response.Content.ReadAsStringAsync(); Assert.Equal($"{expectedCulture},{expectedUICulture}", data); } + + await host.StopAsync(); } } } diff --git a/src/Middleware/Localization/sample/Startup.cs b/src/Middleware/Localization/sample/Startup.cs index 7b6dd5c4ec74..03fa12c13b9a 100644 --- a/src/Middleware/Localization/sample/Startup.cs +++ b/src/Middleware/Localization/sample/Startup.cs @@ -1,14 +1,16 @@ -// 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. +// 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; using System.Globalization; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Localization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; @@ -134,21 +136,25 @@ private static async System.Threading.Tasks.Task WriteCultureSelectOptions(HttpC await context.Response.WriteAsync($" "); } - public static void Main(string[] args) + public static Task Main(string[] args) { var config = new ConfigurationBuilder() .AddCommandLine(args) .Build(); - var host = new WebHostBuilder() - .ConfigureLogging(factory => factory.AddConsole()) - .UseKestrel() - .UseConfiguration(config) - .UseIISIntegration() - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .ConfigureLogging(factory => factory.AddConsole()) + .UseKestrel() + .UseConfiguration(config) + .UseIISIntegration() + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs b/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs index 0b5e64f48ad8..f514098016e2 100644 --- a/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs +++ b/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs @@ -9,6 +9,7 @@ using LocalizationSample; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Localization.FunctionalTests @@ -19,8 +20,17 @@ public class LocalizationSampleTest public async Task LocalizationSampleSmokeTest() { // Arrange - var webHostBuilder = new WebHostBuilder().UseStartup(typeof(Startup)); - var testHost = new TestServer(webHostBuilder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseStartup(typeof(Startup)); + }).Build(); + + await host.StartAsync(); + + var testHost = host.GetTestServer(); var locale = "fr-FR"; var client = testHost.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, "My/Resources"); @@ -33,6 +43,8 @@ public async Task LocalizationSampleSmokeTest() // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Contains("

Bonjour

", await response.Content.ReadAsStringAsync()); + + await host.StopAsync(); } } } diff --git a/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs b/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs index 15b00dfacfe2..8e971155188c 100644 --- a/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs +++ b/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs @@ -8,6 +8,7 @@ using LocalizationWebsite; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Localization.FunctionalTests @@ -97,8 +98,17 @@ public Task Localization_BuilderAPIs() private async Task RunTest(Type startupType, string culture, string expected) { - var webHostBuilder = new WebHostBuilder().UseStartup(startupType); - var testHost = new TestServer(webHostBuilder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseStartup(startupType); + }).Build(); + + await host.StartAsync(); + + var testHost = host.GetTestServer(); var client = testHost.CreateClient(); var request = new HttpRequestMessage(); @@ -109,6 +119,8 @@ private async Task RunTest(Type startupType, string culture, string expected) Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expected, await response.Content.ReadAsStringAsync()); - } + + await host.StopAsync(); + } } } diff --git a/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs index 49a40f0a248b..30e6bee3dba7 100644 --- a/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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.Collections.Generic; @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.Extensions.Localization @@ -17,28 +18,35 @@ public class AcceptLanguageHeaderRequestCultureProviderTest [Fact] public async Task GetFallbackLanguage_ReturnsFirstNonNullCultureFromSupportedCultureList() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA"), - new CultureInfo("en-US") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - return Task.FromResult(0); + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA"), + new CultureInfo("en-US") + } + }); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("jp,ar-SA,en-US"); @@ -46,66 +54,84 @@ public async Task GetFallbackLanguage_ReturnsFirstNonNullCultureFromSupportedCul var response = await client.GetAsync(string.Empty); Assert.Equal(3, count); } + + await host.StopAsync(); } [Fact] public async Task GetFallbackLanguage_ReturnsFromSupportedCulture_AcceptLanguageListContainsSupportedCultures() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("fr-FR"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA"), - new CultureInfo("en-US") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - return Task.FromResult(0); + DefaultRequestCulture = new RequestCulture("fr-FR"), + SupportedCultures = new List + { + new CultureInfo("ar-SA"), + new CultureInfo("en-US") + } + }); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-GB,ar-SA,en-US"); var count = client.DefaultRequestHeaders.AcceptLanguage.Count; var response = await client.GetAsync(string.Empty); } + + await host.StopAsync(); } [Fact] public async Task GetFallbackLanguage_ReturnsDefault_AcceptLanguageListDoesnotContainSupportedCultures() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("fr-FR"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA"), - new CultureInfo("af-ZA") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("fr-FR", requestCulture.Culture.Name); - return Task.FromResult(0); + DefaultRequestCulture = new RequestCulture("fr-FR"), + SupportedCultures = new List + { + new CultureInfo("ar-SA"), + new CultureInfo("af-ZA") + } + }); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("fr-FR", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-GB,ar-MA,en-US"); @@ -113,38 +139,47 @@ public async Task GetFallbackLanguage_ReturnsDefault_AcceptLanguageListDoesnotCo var response = await client.GetAsync(string.Empty); Assert.Equal(3, count); } + + await host.StopAsync(); } - + [Fact] public async Task OmitDefaultRequestCultureShouldNotThrowNullReferenceException_And_ShouldGetTheRightCulture() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-YE") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-YE") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }); + app.Run(context => { - new CultureInfo("ar-YE") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-YE", requestCulture.Culture.Name); - Assert.Equal("ar-YE", requestCulture.UICulture.Name); - return Task.FromResult(0); + Assert.Equal("ar-YE", requestCulture.Culture.Name); + Assert.Equal("ar-YE", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-GB,ar-YE,en-US"); @@ -152,6 +187,8 @@ public async Task OmitDefaultRequestCultureShouldNotThrowNullReferenceException_ var response = await client.GetAsync(string.Empty); Assert.Equal(3, count); } + + await host.StopAsync(); } } -} \ No newline at end of file +} diff --git a/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs index 2e11bb42cbc7..09ad71e05050 100644 --- a/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Microsoft.Net.Http.Headers; @@ -21,38 +22,45 @@ public class CookieRequestCultureProviderTest [Fact] public async Task GetCultureInfoFromPersistentCookie() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }; + var provider = new CookieRequestCultureProvider { - new CultureInfo("ar-SA") - } - }; - var provider = new CookieRequestCultureProvider - { - CookieName = "Preferences" - }; - options.RequestCultureProviders.Insert(0, provider); + CookieName = "Preferences" + }; + options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - return Task.FromResult(0); + app.UseRequestLocalization(options); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var culture = new CultureInfo("ar-SA"); @@ -62,88 +70,108 @@ public async Task GetCultureInfoFromPersistentCookie() var response = await client.GetAsync(string.Empty); Assert.Equal("c=ar-SA|uic=ar-SA", value); } + + await host.StopAsync(); } [Fact] public async Task GetDefaultCultureInfoIfCultureKeysAreMissingOrInvalid() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }; + var provider = new CookieRequestCultureProvider { - new CultureInfo("ar-SA") - } - }; - var provider = new CookieRequestCultureProvider - { - CookieName = "Preferences" - }; - options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("en-US", requestCulture.Culture.Name); - return Task.FromResult(0); + CookieName = "Preferences" + }; + options.RequestCultureProviders.Insert(0, provider); + app.UseRequestLocalization(options); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("en-US", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue("Preferences", "uic=ar-SA").ToString()); var response = await client.GetAsync(string.Empty); } + + await host.StopAsync(); } [Fact] public async Task GetDefaultCultureInfoIfCookieDoesNotExist() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }; + var provider = new CookieRequestCultureProvider { - new CultureInfo("ar-SA") - } - }; - var provider = new CookieRequestCultureProvider - { - CookieName = "Preferences" - }; - options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("en-US", requestCulture.Culture.Name); - return Task.FromResult(0); + CookieName = "Preferences" + }; + options.RequestCultureProviders.Insert(0, provider); + app.UseRequestLocalization(options); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("en-US", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); } + + await host.StopAsync(); } [Fact] @@ -153,35 +181,42 @@ public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedCultures( TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-YE") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-YE") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }; + var provider = new CookieRequestCultureProvider { - new CultureInfo("ar-YE") - } - }; - var provider = new CookieRequestCultureProvider + CookieName = "Preferences" + }; + options.RequestCultureProviders.Insert(0, provider); + app.UseRequestLocalization(options); + app.Run(context => Task.CompletedTask); + }) + .ConfigureServices(services => { - CookieName = "Preferences" - }; - options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => Task.CompletedTask); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - }); + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var culture = "??"; @@ -197,6 +232,8 @@ public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedCultures( var write = Assert.Single(sink.Writes); Assert.Equal(LogLevel.Debug, write.LogLevel); Assert.Equal(expectedMessage, write.State.ToString()); + + await host.StopAsync(); } [Fact] @@ -206,35 +243,42 @@ public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedUICulture TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-YE") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-YE") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }; + var provider = new CookieRequestCultureProvider { - new CultureInfo("ar-YE") - } - }; - var provider = new CookieRequestCultureProvider + CookieName = "Preferences" + }; + options.RequestCultureProviders.Insert(0, provider); + app.UseRequestLocalization(options); + app.Run(context => Task.CompletedTask); + }) + .ConfigureServices(services => { - CookieName = "Preferences" - }; - options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => Task.CompletedTask); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - }); + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var culture = "ar-YE"; @@ -249,6 +293,8 @@ public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedUICulture var write = Assert.Single(sink.Writes); Assert.Equal(LogLevel.Debug, write.LogLevel); Assert.Equal(expectedMessage, write.State.ToString()); + + await host.StopAsync(); } } -} \ No newline at end of file +} diff --git a/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs index 2cd5cf7177fb..96b40ced09de 100644 --- a/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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; @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.Extensions.Localization @@ -19,42 +20,51 @@ public class CustomRequestCultureProviderTest [Fact] public async Task CustomRequestCultureProviderThatGetsCultureInfoFromUrl() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar") + }, + SupportedUICultures = new List + { + new CultureInfo("ar") + } + }; + options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context => { - new CultureInfo("ar") - } - }; - options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context => - { - var culture = GetCultureInfoFromUrl(context, options.SupportedCultures); - var requestCulture = new ProviderCultureResult(culture); - return Task.FromResult(requestCulture); - })); - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar", requestCulture.Culture.Name); - return Task.FromResult(0); + var culture = GetCultureInfoFromUrl(context, options.SupportedCultures); + var requestCulture = new ProviderCultureResult(culture); + return Task.FromResult(requestCulture); + })); + app.UseRequestLocalization(options); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/ar/page"); } + + await host.StopAsync(); } private string GetCultureInfoFromUrl(HttpContext context, IList supportedCultures) @@ -69,4 +79,4 @@ private string GetCultureInfoFromUrl(HttpContext context, IList sup return currentCulture; } } -} \ No newline at end of file +} diff --git a/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs index 9ad34e32e213..b6568ac5fb97 100644 --- a/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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.Collections.Generic; @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.Extensions.Localization @@ -17,282 +18,354 @@ public class QueryStringRequestCultureProviderTest [Fact] public async Task GetCultureInfoFromQueryString() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }); + app.Run(context => { - new CultureInfo("ar-YE") - } + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + Assert.Equal("ar-YE", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - Assert.Equal("ar-YE", requestCulture.UICulture.Name); - return Task.FromResult(0); - }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-SA&ui-culture=ar-YE"); } + + await host.StopAsync(); } [Fact] public async Task GetDefaultCultureInfoIfCultureKeysAreMissing() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US") - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("en-US", requestCulture.Culture.Name); - Assert.Equal("en-US", requestCulture.UICulture.Name); - return Task.FromResult(0); + app.UseRequestLocalization(new RequestLocalizationOptions + { + DefaultRequestCulture = new RequestCulture("en-US") + }); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("en-US", requestCulture.Culture.Name); + Assert.Equal("en-US", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page"); } + + await host.StopAsync(); } [Fact] public async Task GetDefaultCultureInfoIfCultureIsInSupportedCultureList() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }); + app.Run(context => { - new CultureInfo("ar-SA") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("en-US", requestCulture.Culture.Name); - return Task.FromResult(0); + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("en-US", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-XY&ui-culture=ar-SA"); } + + await host.StopAsync(); } [Fact] public async Task GetDefaultCultureInfoIfUICultureIsNotInSupportedList() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }); + app.Run(context => { - new CultureInfo("ar-SA") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("en-US", requestCulture.UICulture.Name); - return Task.FromResult(0); + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("en-US", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-SA&ui-culture=ar-XY"); } + + await host.StopAsync(); } [Fact] public async Task GetSameCultureInfoIfCultureKeyIsMissing() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }); + app.Run(context => { - new CultureInfo("ar-SA") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - Assert.Equal("ar-SA", requestCulture.UICulture.Name); - return Task.FromResult(0); + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + Assert.Equal("ar-SA", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?ui-culture=ar-SA"); } + + await host.StopAsync(); } [Fact] public async Task GetSameCultureInfoIfUICultureKeyIsMissing() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }); + app.Run(context => { - new CultureInfo("ar-SA") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - Assert.Equal("ar-SA", requestCulture.UICulture.Name); - return Task.FromResult(0); + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + Assert.Equal("ar-SA", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-SA"); } + + await host.StopAsync(); } [Fact] public async Task GetCultureInfoFromQueryStringWithCustomKeys() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }; + var provider = new QueryStringRequestCultureProvider(); + provider.QueryStringKey = "c"; + provider.UIQueryStringKey = "uic"; + options.RequestCultureProviders.Insert(0, provider); + app.UseRequestLocalization(options); + app.Run(context => { - new CultureInfo("ar-YE") - } - }; - var provider = new QueryStringRequestCultureProvider(); - provider.QueryStringKey = "c"; - provider.UIQueryStringKey = "uic"; - options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - Assert.Equal("ar-YE", requestCulture.UICulture.Name); - return Task.FromResult(0); + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + Assert.Equal("ar-YE", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?c=ar-SA&uic=ar-YE"); } + + await host.StopAsync(); } [Fact] public async Task GetTheRightCultureInfoRegardlessOfCultureNameCasing() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("FR") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("FR") + }, + SupportedUICultures = new List + { + new CultureInfo("FR") + } + }; + var provider = new QueryStringRequestCultureProvider(); + + provider.QueryStringKey = "c"; + provider.UIQueryStringKey = "uic"; + options.RequestCultureProviders.Insert(0, provider); + app.UseRequestLocalization(options); + app.Run(context => { - new CultureInfo("FR") - } - }; - var provider = new QueryStringRequestCultureProvider(); - - provider.QueryStringKey = "c"; - provider.UIQueryStringKey = "uic"; - options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("fr", requestCulture.Culture.ToString()); - Assert.Equal("fr", requestCulture.UICulture.ToString()); - return Task.FromResult(0); + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("fr", requestCulture.Culture.ToString()); + Assert.Equal("fr", requestCulture.UICulture.ToString()); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?c=FR&uic=FR"); } + + await host.StopAsync(); } } -} \ No newline at end of file +} diff --git a/src/Middleware/Localization/testassets/LocalizationWebsite/Program.cs b/src/Middleware/Localization/testassets/LocalizationWebsite/Program.cs index 7975594760bd..d736d118654f 100644 --- a/src/Middleware/Localization/testassets/LocalizationWebsite/Program.cs +++ b/src/Middleware/Localization/testassets/LocalizationWebsite/Program.cs @@ -1,32 +1,38 @@ // 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.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace LocalizationWebsite { public static class Program { - public static void Main(string[] args) + public static Task Main(string[] args) { var config = new ConfigurationBuilder() .AddCommandLine(args) .Build(); - var host = new WebHostBuilder() - .ConfigureLogging((_, factory) => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - factory.AddConsole(); - factory.AddFilter("Console", level => level >= LogLevel.Warning); + webHostBuilder + .ConfigureLogging((_, factory) => + { + factory.AddConsole(); + factory.AddFilter("Console", level => level >= LogLevel.Warning); + }) + .UseKestrel() + .UseConfiguration(config) + .UseStartup("LocalizationWebsite"); }) - .UseKestrel() - .UseConfiguration(config) - .UseStartup("LocalizationWebsite") .Build(); - host.Run(); + return host.RunAsync(); } } } From fa9cba5d6dc4b7b17e2487a8e1cc6e5eae509d27 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:07:44 -0700 Subject: [PATCH 11/20] MiddlewareAnalysis --- .../MiddlewareAnalysisSample/Startup.cs | 29 ++++++++------- .../test/MiddlewareAnalysisTests.cs | 35 ++++++++++++------- 2 files changed, 40 insertions(+), 24 deletions(-) diff --git a/src/Middleware/MiddlewareAnalysis/samples/MiddlewareAnalysisSample/Startup.cs b/src/Middleware/MiddlewareAnalysis/samples/MiddlewareAnalysisSample/Startup.cs index 8f8d950a47a5..de7ff66d1c41 100644 --- a/src/Middleware/MiddlewareAnalysis/samples/MiddlewareAnalysisSample/Startup.cs +++ b/src/Middleware/MiddlewareAnalysis/samples/MiddlewareAnalysisSample/Startup.cs @@ -1,10 +1,12 @@ using System; using System.Diagnostics; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DiagnosticAdapter; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace MiddlewareAnaysisSample @@ -79,20 +81,23 @@ public void Configure(IApplicationBuilder app, ILoggerFactory factory, Diagnosti // Note there's always a default 404 middleware at the end of the pipeline. } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .ConfigureLogging((_, factory) => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - factory.AddConsole(); - factory.AddFilter("Console", level => level >= LogLevel.Debug); - }) - .UseKestrel() - .UseIISIntegration() - .UseStartup() - .Build(); - - host.Run(); + webHostBuilder + .ConfigureLogging((_, factory) => + { + factory.AddConsole(); + factory.AddFilter("Console", level => level >= LogLevel.Debug); + }) + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }).Build(); + + return host.RunAsync(); } public class TestDiagnosticListener diff --git a/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs b/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs index 64d14ad49258..9a6646d6c5e5 100644 --- a/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs +++ b/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.MiddlewareAnalysis @@ -19,23 +20,31 @@ public async Task ExceptionWrittenToDiagnostics() { DiagnosticListener diagnosticListener = null; - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - diagnosticListener = app.ApplicationServices.GetRequiredService(); - - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - throw new Exception("Test exception"); - }); - }) - .ConfigureServices(services => services.AddMiddlewareAnalysis()); - var server = new TestServer(builder); + diagnosticListener = app.ApplicationServices.GetRequiredService(); + + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); + }) + .ConfigureServices(services => services.AddMiddlewareAnalysis()); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var listener = new TestDiagnosticListener(); diagnosticListener.SubscribeWithAdapter(listener); - + await server.CreateClient().GetAsync(string.Empty); // "Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware", @@ -48,6 +57,8 @@ public async Task ExceptionWrittenToDiagnostics() // reversed "Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware" Assert.Equal(1, listener.MiddlewareFinished.Count); Assert.Equal("Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware", listener.MiddlewareFinished[0]); + + await host.StopAsync(); } } } From f683669e37cb172027e8a272c63e37b36d55e007 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:07:58 -0700 Subject: [PATCH 12/20] NodeServices --- .../samples/NodeServicesExamples/Startup.cs | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/src/Middleware/NodeServices/samples/NodeServicesExamples/Startup.cs b/src/Middleware/NodeServices/samples/NodeServicesExamples/Startup.cs index 60cb8044e15f..44e7411132f0 100644 --- a/src/Middleware/NodeServices/samples/NodeServicesExamples/Startup.cs +++ b/src/Middleware/NodeServices/samples/NodeServicesExamples/Startup.cs @@ -3,11 +3,13 @@ using System; using System.IO; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.NodeServices; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace NodeServicesExamples @@ -58,21 +60,24 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, INodeSer } #pragma warning restore 0618 - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .ConfigureLogging(factory => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - factory.AddConsole(); - factory.AddDebug(); - }) - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseKestrel() - .UseStartup() - .Build(); + webHostBuilder + .ConfigureLogging(factory => + { + factory.AddConsole(); + factory.AddDebug(); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseKestrel() + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } From 3b10782c2160986173114db3ec00ae3ce730534b Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:08:26 -0700 Subject: [PATCH 13/20] ResponseCaching --- .../samples/ResponseCachingSample/Startup.cs | 21 +- .../test/ResponseCachingTests.cs | 295 +++++++++++++++--- .../ResponseCaching/test/TestUtils.cs | 39 ++- 3 files changed, 294 insertions(+), 61 deletions(-) diff --git a/src/Middleware/ResponseCaching/samples/ResponseCachingSample/Startup.cs b/src/Middleware/ResponseCaching/samples/ResponseCachingSample/Startup.cs index 6184a36946cc..3d691a3db4f0 100644 --- a/src/Middleware/ResponseCaching/samples/ResponseCachingSample/Startup.cs +++ b/src/Middleware/ResponseCaching/samples/ResponseCachingSample/Startup.cs @@ -3,10 +3,12 @@ using System; using System.IO; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Net.Http.Headers; namespace ResponseCachingSample @@ -34,16 +36,19 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseStartup() - .Build(); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs b/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs index 522b6952c279..25040684d9c8 100644 --- a/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs +++ b/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs @@ -22,7 +22,11 @@ public async Task ServesCachedContent_IfAvailable(string method) foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.SendAsync(TestUtils.CreateRequest(method, "")); @@ -30,6 +34,8 @@ public async Task ServesCachedContent_IfAvailable(string method) await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -42,7 +48,11 @@ public async Task ServesFreshContent_IfNotAvailable(string method) foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.SendAsync(TestUtils.CreateRequest(method, "")); @@ -50,6 +60,8 @@ public async Task ServesFreshContent_IfNotAvailable(string method) await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -60,7 +72,11 @@ public async Task ServesFreshContent_Post() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.PostAsync("", new StringContent(string.Empty)); @@ -68,6 +84,8 @@ public async Task ServesFreshContent_Post() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -78,7 +96,11 @@ public async Task ServesFreshContent_Head_Get() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var subsequentResponse = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, "")); @@ -86,6 +108,8 @@ public async Task ServesFreshContent_Head_Get() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -96,7 +120,11 @@ public async Task ServesFreshContent_Get_Head() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "")); @@ -104,6 +132,7 @@ public async Task ServesFreshContent_Get_Head() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + await host.StopAsync(); } } @@ -116,7 +145,11 @@ public async Task ServesFreshContent_If_CacheControlNoCache(string method) foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); @@ -133,6 +166,8 @@ public async Task ServesFreshContent_If_CacheControlNoCache(string method) await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -145,7 +180,11 @@ public async Task ServesFreshContent_If_PragmaNoCache(string method) foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); @@ -162,6 +201,8 @@ public async Task ServesFreshContent_If_PragmaNoCache(string method) await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -174,7 +215,11 @@ public async Task ServesCachedContent_If_PathCasingDiffers(string method) foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.SendAsync(TestUtils.CreateRequest(method, "path")); @@ -182,6 +227,8 @@ public async Task ServesCachedContent_If_PathCasingDiffers(string method) await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -194,7 +241,11 @@ public async Task ServesFreshContent_If_ResponseExpired(string method) foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.SendAsync(TestUtils.CreateRequest(method, "?Expires=0")); @@ -202,6 +253,8 @@ public async Task ServesFreshContent_If_ResponseExpired(string method) await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -214,7 +267,11 @@ public async Task ServesFreshContent_If_Authorization_HeaderExists(string method foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("abc"); @@ -223,6 +280,8 @@ public async Task ServesFreshContent_If_Authorization_HeaderExists(string method await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -233,7 +292,11 @@ public async Task ServesCachedContent_IfVaryHeader_Matches() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.From = "user@example.com"; @@ -242,6 +305,8 @@ public async Task ServesCachedContent_IfVaryHeader_Matches() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -252,7 +317,11 @@ public async Task ServesFreshContent_IfVaryHeader_Mismatches() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.From = "user@example.com"; @@ -262,6 +331,8 @@ public async Task ServesFreshContent_IfVaryHeader_Mismatches() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -272,7 +343,11 @@ public async Task ServesCachedContent_IfVaryQueryKeys_Matches() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?query=value"); @@ -280,6 +355,8 @@ public async Task ServesCachedContent_IfVaryQueryKeys_Matches() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -290,7 +367,11 @@ public async Task ServesCachedContent_IfVaryQueryKeysExplicit_Matches_QueryKeyCa foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?querya=valuea&queryb=valueb"); @@ -298,6 +379,8 @@ public async Task ServesCachedContent_IfVaryQueryKeysExplicit_Matches_QueryKeyCa await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -308,7 +391,11 @@ public async Task ServesCachedContent_IfVaryQueryKeyStar_Matches_QueryKeyCaseIns foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?querya=valuea&queryb=valueb"); @@ -316,6 +403,8 @@ public async Task ServesCachedContent_IfVaryQueryKeyStar_Matches_QueryKeyCaseIns await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -326,7 +415,11 @@ public async Task ServesCachedContent_IfVaryQueryKeyExplicit_Matches_OrderInsens foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?QueryA=ValueA&QueryB=ValueB"); @@ -334,6 +427,8 @@ public async Task ServesCachedContent_IfVaryQueryKeyExplicit_Matches_OrderInsens await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -344,7 +439,11 @@ public async Task ServesCachedContent_IfVaryQueryKeyStar_Matches_OrderInsensitiv foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?QueryA=ValueA&QueryB=ValueB"); @@ -352,6 +451,8 @@ public async Task ServesCachedContent_IfVaryQueryKeyStar_Matches_OrderInsensitiv await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -362,7 +463,11 @@ public async Task ServesFreshContent_IfVaryQueryKey_Mismatches() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?query=value"); @@ -370,6 +475,8 @@ public async Task ServesFreshContent_IfVaryQueryKey_Mismatches() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -380,7 +487,11 @@ public async Task ServesFreshContent_IfVaryQueryKeyExplicit_Mismatch_QueryKeyCas foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?querya=valuea&queryb=valueb"); @@ -388,6 +499,8 @@ public async Task ServesFreshContent_IfVaryQueryKeyExplicit_Mismatch_QueryKeyCas await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -398,7 +511,11 @@ public async Task ServesFreshContent_IfVaryQueryKeyStar_Mismatch_QueryKeyValueCa foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?querya=valuea&queryb=valueb"); @@ -406,6 +523,8 @@ public async Task ServesFreshContent_IfVaryQueryKeyStar_Mismatch_QueryKeyValueCa await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -416,7 +535,11 @@ public async Task ServesFreshContent_IfRequestRequirements_NotMet() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -428,6 +551,8 @@ public async Task ServesFreshContent_IfRequestRequirements_NotMet() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -438,7 +563,11 @@ public async Task Serves504_IfOnlyIfCachedHeader_IsSpecified() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -451,6 +580,8 @@ public async Task Serves504_IfOnlyIfCachedHeader_IsSpecified() initialResponse.EnsureSuccessStatusCode(); Assert.Equal(System.Net.HttpStatusCode.GatewayTimeout, subsequentResponse.StatusCode); } + + await host.StopAsync(); } } @@ -461,7 +592,11 @@ public async Task ServesFreshContent_IfSetCookie_IsSpecified() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -469,6 +604,8 @@ public async Task ServesFreshContent_IfSetCookie_IsSpecified() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -479,7 +616,11 @@ public async Task ServesCachedContent_IfSubsequentRequestContainsNoStore() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -491,6 +632,8 @@ public async Task ServesCachedContent_IfSubsequentRequestContainsNoStore() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -501,7 +644,11 @@ public async Task ServesFreshContent_IfInitialRequestContainsNoStore() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue() @@ -513,6 +660,8 @@ public async Task ServesFreshContent_IfInitialRequestContainsNoStore() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -523,7 +672,11 @@ public async Task ServesFreshContent_IfInitialResponseContainsNoStore() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -531,6 +684,8 @@ public async Task ServesFreshContent_IfInitialResponseContainsNoStore() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -546,7 +701,11 @@ public async Task Serves304_IfIfModifiedSince_Satisfied() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?Expires=90"); @@ -557,6 +716,8 @@ public async Task Serves304_IfIfModifiedSince_Satisfied() Assert.Equal(System.Net.HttpStatusCode.NotModified, subsequentResponse.StatusCode); Assert304Headers(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -567,7 +728,11 @@ public async Task ServesCachedContent_IfIfModifiedSince_NotSatisfied() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -576,6 +741,8 @@ public async Task ServesCachedContent_IfIfModifiedSince_NotSatisfied() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -591,7 +758,11 @@ public async Task Serves304_IfIfNoneMatch_Satisfied() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?Expires=90"); @@ -602,6 +773,8 @@ public async Task Serves304_IfIfNoneMatch_Satisfied() Assert.Equal(System.Net.HttpStatusCode.NotModified, subsequentResponse.StatusCode); Assert304Headers(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -612,7 +785,11 @@ public async Task ServesCachedContent_IfIfNoneMatch_NotSatisfied() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -621,6 +798,8 @@ public async Task ServesCachedContent_IfIfNoneMatch_NotSatisfied() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -634,7 +813,11 @@ public async Task ServesCachedContent_IfBodySize_IsCacheable() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -642,6 +825,8 @@ public async Task ServesCachedContent_IfBodySize_IsCacheable() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -655,7 +840,11 @@ public async Task ServesFreshContent_IfBodySize_IsNotCacheable() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -663,6 +852,8 @@ public async Task ServesFreshContent_IfBodySize_IsNotCacheable() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -676,7 +867,11 @@ public async Task ServesFreshContent_CaseSensitivePaths_IsNotCacheable() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("/path"); @@ -684,6 +879,8 @@ public async Task ServesFreshContent_CaseSensitivePaths_IsNotCacheable() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -694,7 +891,11 @@ public async Task ServesCachedContent_WithoutReplacingCachedVaryBy_OnCacheMiss() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.From = "user@example.com"; @@ -706,6 +907,8 @@ public async Task ServesCachedContent_WithoutReplacingCachedVaryBy_OnCacheMiss() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -716,7 +919,11 @@ public async Task ServesFreshContent_IfCachedVaryByUpdated_OnCacheMiss() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.From = "user@example.com"; @@ -737,6 +944,8 @@ public async Task ServesFreshContent_IfCachedVaryByUpdated_OnCacheMiss() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -747,7 +956,11 @@ public async Task ServesCachedContent_IfCachedVaryByNotUpdated_OnCacheMiss() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.From = "user@example.com"; @@ -768,6 +981,8 @@ public async Task ServesCachedContent_IfCachedVaryByNotUpdated_OnCacheMiss() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } @@ -778,7 +993,11 @@ public async Task ServesCachedContent_IfAvailable_UsingHead_WithContentLength() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.SendAsync(TestUtils.CreateRequest("HEAD", "?contentLength=10")); @@ -786,6 +1005,8 @@ public async Task ServesCachedContent_IfAvailable_UsingHead_WithContentLength() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } + + await host.StopAsync(); } } diff --git a/src/Middleware/ResponseCaching/test/TestUtils.cs b/src/Middleware/ResponseCaching/test/TestUtils.cs index 270778f99619..1fb815ff1de7 100644 --- a/src/Middleware/ResponseCaching/test/TestUtils.cs +++ b/src/Middleware/ResponseCaching/test/TestUtils.cs @@ -12,7 +12,9 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Testing; @@ -116,7 +118,7 @@ internal static IResponseCachingKeyProvider CreateTestKeyProvider(ResponseCachin return new ResponseCachingKeyProvider(new DefaultObjectPoolProvider(), Options.Create(options)); } - internal static IEnumerable CreateBuildersWithResponseCaching( + internal static IEnumerable CreateBuildersWithResponseCaching( Action configureDelegate = null, ResponseCachingOptions options = null, Action contextAction = null) @@ -141,7 +143,7 @@ internal static IEnumerable CreateBuildersWithResponseCaching( }); } - private static IEnumerable CreateBuildersWithResponseCaching( + private static IEnumerable CreateBuildersWithResponseCaching( Action configureDelegate = null, ResponseCachingOptions options = null, IEnumerable requestDelegates = null) @@ -162,24 +164,29 @@ private static IEnumerable CreateBuildersWithResponseCaching( foreach (var requestDelegate in requestDelegates) { // Test with in memory ResponseCache - yield return new WebHostBuilder() - .ConfigureServices(services => + yield return new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCaching(responseCachingOptions => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - if (options != null) + services.AddResponseCaching(responseCachingOptions => { - responseCachingOptions.MaximumBodySize = options.MaximumBodySize; - responseCachingOptions.UseCaseSensitivePaths = options.UseCaseSensitivePaths; - responseCachingOptions.SystemClock = options.SystemClock; - } + if (options != null) + { + responseCachingOptions.MaximumBodySize = options.MaximumBodySize; + responseCachingOptions.UseCaseSensitivePaths = options.UseCaseSensitivePaths; + responseCachingOptions.SystemClock = options.SystemClock; + } + }); + }) + .Configure(app => + { + configureDelegate(app); + app.UseResponseCaching(); + app.Run(requestDelegate); }); - }) - .Configure(app => - { - configureDelegate(app); - app.UseResponseCaching(); - app.Run(requestDelegate); }); } } From 717ce1f3e6788cda7882108919ec33a01723ba53 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:08:43 -0700 Subject: [PATCH 14/20] ResponseCompression --- .../ResponseCompression/sample/Startup.cs | 24 +- .../test/ResponseCompressionMiddlewareTest.cs | 739 +++++++++++------- 2 files changed, 453 insertions(+), 310 deletions(-) diff --git a/src/Middleware/ResponseCompression/sample/Startup.cs b/src/Middleware/ResponseCompression/sample/Startup.cs index a640867559b8..5d84f952d0df 100644 --- a/src/Middleware/ResponseCompression/sample/Startup.cs +++ b/src/Middleware/ResponseCompression/sample/Startup.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.ResponseCompression; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace ResponseCompressionSample @@ -71,19 +72,22 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .ConfigureLogging(factory => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - factory.AddConsole() - .SetMinimumLevel(LogLevel.Debug); - }) - .UseStartup() - .Build(); + webHostBuilder + .UseKestrel() + .ConfigureLogging(factory => + { + factory.AddConsole() + .SetMinimumLevel(LogLevel.Debug); + }) + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs index c6ad14a66c13..44ca99b5f7d4 100644 --- a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs +++ b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs @@ -17,6 +17,7 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Microsoft.Net.Http.Headers; @@ -134,24 +135,31 @@ public async Task ContentType_WithCharset_Compress(string contentType) [Fact] public async Task GZipCompressionProvider_OptionsSetInDI_Compress() { - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.Configure(options => options.Level = CompressionLevel.NoCompression); - services.AddResponseCompression(); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.Configure(options => options.Level = CompressionLevel.NoCompression); + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - return context.Response.WriteAsync(new string('a', 100)); + app.UseResponseCompression(); + app.Run(context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + return context.Response.WriteAsync(new string('a', 100)); + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -160,6 +168,8 @@ public async Task GZipCompressionProvider_OptionsSetInDI_Compress() var response = await client.SendAsync(request); CheckResponseCompressed(response, expectedBodyLength: 133, expectedEncoding: "gzip"); + + await host.StopAsync(); } [Theory] @@ -286,23 +296,30 @@ public async Task NoIncludedMimeTypes_UseDefaults() [InlineData("text/plain2")] public async Task NoBody_NotCompressed(string contentType) { - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCompression(); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = contentType; - return Task.FromResult(0); + app.UseResponseCompression(); + app.Run(context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = contentType; + return Task.FromResult(0); + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -311,6 +328,8 @@ public async Task NoBody_NotCompressed(string contentType) var response = await client.SendAsync(request); CheckResponseNotCompressed(response, expectedBodyLength: 0, sendVaryHeader: false); + + await host.StopAsync(); } [Fact] @@ -413,30 +432,35 @@ public async Task Request_Https_CompressedIfEnabled(bool enableHttps, int expect TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - services.AddResponseCompression(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.EnableForHttps = enableHttps; - options.MimeTypes = new[] { TextPlain }; - }); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(context => + services.AddSingleton(loggerFactory); + services.AddResponseCompression(options => + { + options.EnableForHttps = enableHttps; + options.MimeTypes = new[] { TextPlain }; + }); + }) + .Configure(app => { - context.Response.ContentType = TextPlain; - return context.Response.WriteAsync(new string('a', 100)); + app.UseResponseCompression(); + app.Run(context => + { + context.Response.ContentType = TextPlain; + return context.Response.WriteAsync(new string('a', 100)); + }); }); - }); + }).Build(); - var server = new TestServer(builder) - { - BaseAddress = new Uri("https://localhost/") - }; + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("https://localhost/"); var client = server.CreateClient(); @@ -456,6 +480,8 @@ public async Task Request_Https_CompressedIfEnabled(bool enableHttps, int expect { AssertLog(logMessages.Skip(1).Single(), LogLevel.Debug, "No response compression available for HTTPS requests. See ResponseCompressionOptions.EnableForHttps."); } + + await host.StopAsync(); } [Theory] @@ -469,32 +495,37 @@ public async Task Request_Https_CompressedIfOptIn(HttpsCompressionMode mode, int TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - services.AddResponseCompression(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.EnableForHttps = false; - options.MimeTypes = new[] { TextPlain }; - }); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(context => + services.AddSingleton(loggerFactory); + services.AddResponseCompression(options => + { + options.EnableForHttps = false; + options.MimeTypes = new[] { TextPlain }; + }); + }) + .Configure(app => { - var feature = context.Features.Get(); - feature.Mode = mode; - context.Response.ContentType = TextPlain; - return context.Response.WriteAsync(new string('a', 100)); + app.UseResponseCompression(); + app.Run(context => + { + var feature = context.Features.Get(); + feature.Mode = mode; + context.Response.ContentType = TextPlain; + return context.Response.WriteAsync(new string('a', 100)); + }); }); - }); + }).Build(); - var server = new TestServer(builder) - { - BaseAddress = new Uri("https://localhost/") - }; + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("https://localhost/"); var client = server.CreateClient(); @@ -514,6 +545,8 @@ public async Task Request_Https_CompressedIfOptIn(HttpsCompressionMode mode, int { AssertLog(logMessages.Skip(1).Single(), LogLevel.Debug, "No response compression available for HTTPS requests. See ResponseCompressionOptions.EnableForHttps."); } + + await host.StopAsync(); } [Theory] @@ -527,32 +560,37 @@ public async Task Request_Https_NotCompressedIfOptOut(HttpsCompressionMode mode, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - services.AddResponseCompression(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.EnableForHttps = true; - options.MimeTypes = new[] { TextPlain }; - }); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(context => + services.AddSingleton(loggerFactory); + services.AddResponseCompression(options => + { + options.EnableForHttps = true; + options.MimeTypes = new[] { TextPlain }; + }); + }) + .Configure(app => { - var feature = context.Features.Get(); - feature.Mode = mode; - context.Response.ContentType = TextPlain; - return context.Response.WriteAsync(new string('a', 100)); + app.UseResponseCompression(); + app.Run(context => + { + var feature = context.Features.Get(); + feature.Mode = mode; + context.Response.ContentType = TextPlain; + return context.Response.WriteAsync(new string('a', 100)); + }); }); - }); + }).Build(); - var server = new TestServer(builder) - { - BaseAddress = new Uri("https://localhost/") - }; + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("https://localhost/"); var client = server.CreateClient(); @@ -572,6 +610,8 @@ public async Task Request_Https_NotCompressedIfOptOut(HttpsCompressionMode mode, { AssertCompressedWithLog(logMessages, "gzip"); } + + await host.StopAsync(); } [Theory] @@ -580,28 +620,33 @@ public async Task FlushHeaders_SendsHeaders_Compresses(string encoding, int expe { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCompression(); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - context.Response.Body.Flush(); - await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - await context.Response.WriteAsync(new string('a', 100)); + app.UseResponseCompression(); + app.Run(async context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + context.Response.Body.Flush(); + await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + await context.Response.WriteAsync(new string('a', 100)); + }); }); - }); + }).Build(); - var server = new TestServer(builder) - { - AllowSynchronousIO = true // needed for synchronous flush - }; + await host.StartAsync(); + + var server = host.GetTestServer(); + server.AllowSynchronousIO = true; // needed for synchronous flush var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -613,6 +658,8 @@ public async Task FlushHeaders_SendsHeaders_Compresses(string encoding, int expe await response.Content.LoadIntoBufferAsync(); CheckResponseCompressed(response, expectedBodyLength, encoding); + + await host.StopAsync(); } [Theory] @@ -621,25 +668,32 @@ public async Task FlushAsyncHeaders_SendsHeaders_Compresses(string encoding, int { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCompression(); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - await context.Response.Body.FlushAsync(); - await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - await context.Response.WriteAsync(new string('a', 100)); + app.UseResponseCompression(); + app.Run(async context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + await context.Response.Body.FlushAsync(); + await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + await context.Response.WriteAsync(new string('a', 100)); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -651,6 +705,8 @@ public async Task FlushAsyncHeaders_SendsHeaders_Compresses(string encoding, int await response.Content.LoadIntoBufferAsync(); CheckResponseCompressed(response, expectedBodyLength, encoding); + + await host.StopAsync(); } [Theory] @@ -659,32 +715,39 @@ public async Task FlushBody_CompressesAndFlushes(string encoding) { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseResponseCompression(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - var feature = context.Features.Get(); - if (feature != null) + services.AddResponseCompression(); + }) + .Configure(app => + { + app.UseResponseCompression(); + app.Run(async context => { - feature.AllowSynchronousIO = true; - } - - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - context.Response.Body.Write(new byte[10], 0, 10); - context.Response.Body.Flush(); - await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - context.Response.Body.Write(new byte[90], 0, 90); + var feature = context.Features.Get(); + if (feature != null) + { + feature.AllowSynchronousIO = true; + } + + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + context.Response.Body.Write(new byte[10], 0, 10); + context.Response.Body.Flush(); + await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + context.Response.Body.Write(new byte[90], 0, 90); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -703,6 +766,8 @@ public async Task FlushBody_CompressesAndFlushes(string encoding) read = await body.ReadAsync(new byte[100], 0, 100); Assert.True(read > 0); + + await host.StopAsync(); } [Theory] @@ -711,26 +776,33 @@ public async Task FlushAsyncBody_CompressesAndFlushes(string encoding) { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCompression(); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - await context.Response.WriteAsync(new string('a', 10)); - await context.Response.Body.FlushAsync(); - await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - await context.Response.WriteAsync(new string('a', 90)); + app.UseResponseCompression(); + app.Run(async context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + await context.Response.WriteAsync(new string('a', 10)); + await context.Response.Body.FlushAsync(); + await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + await context.Response.WriteAsync(new string('a', 90)); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -749,6 +821,8 @@ public async Task FlushAsyncBody_CompressesAndFlushes(string encoding) read = await body.ReadAsync(new byte[100], 0, 100); Assert.True(read > 0); + + await host.StopAsync(); } [Theory] @@ -764,36 +838,43 @@ public async Task TrickleWriteAndFlush_FlushesEachWrite(string encoding) new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously), }; - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseResponseCompression(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - context.Features.Get().DisableBuffering(); - - var feature = context.Features.Get(); - if (feature != null) - { - feature.AllowSynchronousIO = true; - } - - foreach (var signal in responseReceived) + services.AddResponseCompression(); + }) + .Configure(app => + { + app.UseResponseCompression(); + app.Run(async context => { - context.Response.Body.Write(new byte[1], 0, 1); - context.Response.Body.Flush(); - await signal.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - } + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + context.Features.Get().DisableBuffering(); + + var feature = context.Features.Get(); + if (feature != null) + { + feature.AllowSynchronousIO = true; + } + + foreach (var signal in responseReceived) + { + context.Response.Body.Write(new byte[1], 0, 1); + context.Response.Body.Flush(); + await signal.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + } + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -812,6 +893,8 @@ public async Task TrickleWriteAndFlush_FlushesEachWrite(string encoding) signal.SetResult(0); } + + await host.StopAsync(); } [Theory] @@ -827,30 +910,37 @@ public async Task TrickleWriteAndFlushAsync_FlushesEachWrite(string encoding) new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously), }; - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseResponseCompression(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - context.Features.Get().DisableBuffering(); - - foreach (var signal in responseReceived) + services.AddResponseCompression(); + }) + .Configure(app => + { + app.UseResponseCompression(); + app.Run(async context => { - await context.Response.WriteAsync("a"); - await context.Response.Body.FlushAsync(); - await signal.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - } + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + context.Features.Get().DisableBuffering(); + + foreach (var signal in responseReceived) + { + await context.Response.WriteAsync("a"); + await context.Response.Body.FlushAsync(); + await signal.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + } + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -869,6 +959,8 @@ public async Task TrickleWriteAndFlushAsync_FlushesEachWrite(string encoding) signal.SetResult(0); } + + await host.StopAsync(); } [Fact] @@ -876,32 +968,39 @@ public async Task SendFileAsync_DifferentContentType_NotBypassed() { FakeSendFileFeature fakeSendFile = null; - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCompression(); - }) - .Configure(app => - { - app.Use((context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - fakeSendFile = new FakeSendFileFeature(context.Features.Get()); - context.Features.Set(fakeSendFile); - return next(); - }); - app.UseResponseCompression(); - app.Run(context => + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = "custom/type"; - context.Response.ContentLength = 1024; - var sendFile = context.Features.Get(); - Assert.NotNull(sendFile); - return sendFile.SendFileAsync("testfile1kb.txt", 0, null, CancellationToken.None); + app.Use((context, next) => + { + fakeSendFile = new FakeSendFileFeature(context.Features.Get()); + context.Features.Set(fakeSendFile); + return next(); + }); + app.UseResponseCompression(); + app.Run(context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = "custom/type"; + context.Response.ContentLength = 1024; + var sendFile = context.Features.Get(); + Assert.NotNull(sendFile); + return sendFile.SendFileAsync("testfile1kb.txt", 0, null, CancellationToken.None); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -912,6 +1011,8 @@ public async Task SendFileAsync_DifferentContentType_NotBypassed() CheckResponseNotCompressed(response, expectedBodyLength: 1024, sendVaryHeader: false); Assert.True(fakeSendFile.SendFileInvoked); + + await host.StopAsync(); } [Fact] @@ -919,32 +1020,39 @@ public async Task SendFileAsync_FirstWrite_CompressesAndFlushes() { FakeSendFileFeature fakeSendFile = null; - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCompression(); - }) - .Configure(app => - { - app.Use((context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - fakeSendFile = new FakeSendFileFeature(context.Features.Get()); - context.Features.Set(fakeSendFile); - return next(); - }); - app.UseResponseCompression(); - app.Run(context => + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - context.Response.ContentLength = 1024; - var sendFile = context.Features.Get(); - Assert.NotNull(sendFile); - return sendFile.SendFileAsync("testfile1kb.txt", 0, null, CancellationToken.None); + app.Use((context, next) => + { + fakeSendFile = new FakeSendFileFeature(context.Features.Get()); + context.Features.Set(fakeSendFile); + return next(); + }); + app.UseResponseCompression(); + app.Run(context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + context.Response.ContentLength = 1024; + var sendFile = context.Features.Get(); + Assert.NotNull(sendFile); + return sendFile.SendFileAsync("testfile1kb.txt", 0, null, CancellationToken.None); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -955,6 +1063,8 @@ public async Task SendFileAsync_FirstWrite_CompressesAndFlushes() CheckResponseCompressed(response, expectedBodyLength: 34, expectedEncoding: "gzip"); Assert.False(fakeSendFile.SendFileInvoked); + + await host.StartAsync(); } [Fact] @@ -962,32 +1072,39 @@ public async Task SendFileAsync_AfterFirstWrite_CompressesAndFlushes() { FakeSendFileFeature fakeSendFile = null; - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use((context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - fakeSendFile = new FakeSendFileFeature(context.Features.Get()); - context.Features.Set(fakeSendFile); - return next(); - }); - app.UseResponseCompression(); - app.Run(async context => + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - var feature = context.Features.Get(); + app.Use((context, next) => + { + fakeSendFile = new FakeSendFileFeature(context.Features.Get()); + context.Features.Set(fakeSendFile); + return next(); + }); + app.UseResponseCompression(); + app.Run(async context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + var feature = context.Features.Get(); - await context.Response.WriteAsync(new string('a', 100)); - await feature.SendFileAsync("testfile1kb.txt", 0, null, CancellationToken.None); + await context.Response.WriteAsync(new string('a', 100)); + await feature.SendFileAsync("testfile1kb.txt", 0, null, CancellationToken.None); + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -998,6 +1115,8 @@ public async Task SendFileAsync_AfterFirstWrite_CompressesAndFlushes() CheckResponseCompressed(response, expectedBodyLength: 46, expectedEncoding: "gzip"); Assert.False(fakeSendFile.SendFileInvoked); + + await host.StopAsync(); } [Theory] @@ -1006,31 +1125,38 @@ public async Task Dispose_SyncWriteOrFlushNotCalled(string encoding) { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use((context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - context.Response.Body = new NoSyncWrapperStream(context.Response.Body); - return next(); - }); - app.UseResponseCompression(); - app.Run(async context => + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - await context.Response.WriteAsync(new string('a', 10)); - await context.Response.Body.FlushAsync(); - await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - await context.Response.WriteAsync(new string('a', 90)); + app.Use((context, next) => + { + context.Response.Body = new NoSyncWrapperStream(context.Response.Body); + return next(); + }); + app.UseResponseCompression(); + app.Run(async context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + await context.Response.WriteAsync(new string('a', 10)); + await context.Response.Body.FlushAsync(); + await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + await context.Response.WriteAsync(new string('a', 90)); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -1049,6 +1175,8 @@ public async Task Dispose_SyncWriteOrFlushNotCalled(string encoding) read = await body.ReadAsync(new byte[100], 0, 100); Assert.True(read > 0); + + await host.StopAsync(); } private async Task<(HttpResponseMessage, List)> InvokeMiddleware( @@ -1063,25 +1191,32 @@ public async Task Dispose_SyncWriteOrFlushNotCalled(string encoding) TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(configure ?? (_ => { })); - services.AddSingleton(loggerFactory); - }) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseResponseCompression(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = responseType; - addResponseAction?.Invoke(context.Response); - return context.Response.WriteAsync(new string('a', uncompressedBodyLength)); + services.AddResponseCompression(configure ?? (_ => { })); + services.AddSingleton(loggerFactory); + }) + .Configure(app => + { + app.UseResponseCompression(); + app.Run(context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = responseType; + addResponseAction?.Invoke(context.Response); + return context.Response.WriteAsync(new string('a', uncompressedBodyLength)); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -1090,7 +1225,11 @@ public async Task Dispose_SyncWriteOrFlushNotCalled(string encoding) request.Headers.AcceptEncoding.Add(System.Net.Http.Headers.StringWithQualityHeaderValue.Parse(requestAcceptEncodings[i])); } - return (await client.SendAsync(request), sink.Writes.ToList()); + var response = await client.SendAsync(request); + + await host.StopAsync(); + + return (response, sink.Writes.ToList()); } private void CheckResponseCompressed(HttpResponseMessage response, int expectedBodyLength, string expectedEncoding) From a4ecffc88c11efe44d46d9fe47ba01160ed3a442 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:09:06 -0700 Subject: [PATCH 15/20] Rewrite --- src/Middleware/Rewrite/sample/Startup.cs | 31 +- .../ModRewriteMiddlewareTest.cs | 411 ++++++++++----- .../test/IISUrlRewrite/MiddleWareTests.cs | 468 ++++++++++++----- .../Rewrite/test/MiddlewareTests.cs | 484 +++++++++++++----- 4 files changed, 993 insertions(+), 401 deletions(-) diff --git a/src/Middleware/Rewrite/sample/Startup.cs b/src/Middleware/Rewrite/sample/Startup.cs index 5a50edd9d805..253f0247c88c 100644 --- a/src/Middleware/Rewrite/sample/Startup.cs +++ b/src/Middleware/Rewrite/sample/Startup.cs @@ -3,11 +3,13 @@ using System.IO; using System.Net; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Rewrite; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace RewriteSample { @@ -42,23 +44,26 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel(options => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(IPAddress.Loopback, 5000); - options.Listen(IPAddress.Loopback, 5001, listenOptions => + webHostBuilder + .UseKestrel(options => { - // Configure SSL - listenOptions.UseHttps("testCert.pfx", "testPassword"); - }); - }) - .UseStartup() - .UseContentRoot(Directory.GetCurrentDirectory()) - .Build(); + options.Listen(IPAddress.Loopback, 5000); + options.Listen(IPAddress.Loopback, 5001, listenOptions => + { + // Configure SSL + listenOptions.UseHttps("testCert.pfx", "testPassword"); + }); + }) + .UseStartup() + .UseContentRoot(Directory.GetCurrentDirectory()); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs b/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs index 67deba236d44..98740759d142 100644 --- a/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs +++ b/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Rewrite.Tests.ModRewrite @@ -19,17 +20,27 @@ public class ModRewriteMiddlewareTest public async Task Invoke_RewritePathWhenMatching() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader("RewriteRule /hey/(.*) /$1 ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("/hey/hello"); Assert.Equal("/hello", response); + + await host.StopAsync(); } [Fact] @@ -37,17 +48,27 @@ public async Task Invoke_RewritePathTerminatesOnFirstSuccessOfRule() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader("RewriteRule /hey/(.*) /$1 [L]")) .AddApacheModRewrite(new StringReader("RewriteRule /hello /what")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("/hey/hello"); Assert.Equal("/hello", response); + + await host.StopAsync(); } [Fact] @@ -55,85 +76,135 @@ public async Task Invoke_RewritePathDoesNotTerminateOnFirstSuccessOfRule() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader("RewriteRule /hey/(.*) /$1")) .AddApacheModRewrite(new StringReader("RewriteRule /hello /what")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("/hey/hello"); Assert.Equal("/what", response); + + await host.StopAsync(); } [Fact] public async Task Invoke_ShouldIgnoreComments() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader("#RewriteRule ^/hey/(.*) /$1 ")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("/hey/hello"); Assert.Equal("/hey/hello", response); + + await host.StopAsync(); } [Fact] public async Task Invoke_ShouldRewriteHomepage() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteRule ^/$ /homepage.html")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("http://www.foo.org/"); Assert.Equal("/homepage.html", response); + + await host.StopAsync(); } [Fact] public async Task Invoke_ShouldIgnorePorts() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteRule ^/$ /homepage.html")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("http://www.foo.org:42/"); Assert.Equal("/homepage.html", response); + + await host.StopAsync(); } [Fact] public async Task Invoke_HandleNegatedRewriteRules() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteRule !^/$ /homepage.html")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("http://www.foo.org/"); Assert.Equal("/", response); + + await host.StopAsync(); } [Theory] @@ -142,17 +213,27 @@ public async Task Invoke_HandleNegatedRewriteRules() public async Task Invoke_BackReferencesShouldBeApplied(string url, string rule, string expected) { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(rule)); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(url); Assert.Equal(expected, response); + + await host.StopAsync(); } [Theory] @@ -165,17 +246,27 @@ public async Task Invoke_BackReferencesShouldBeApplied(string url, string rule, public async Task Invoke_ShouldHandleFlagNoCase(string url, string rule, string expected) { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(rule)); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(url); Assert.Equal(expected, response); + + await host.StopAsync(); } [Fact] @@ -183,17 +274,27 @@ public async Task Invoke_CheckFullUrlWithOnlyPath() { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader(@"RewriteRule (.+) http://www.example.com$1/")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("http://www.foo.org/blog/2016-jun"); Assert.Equal(@"/blog/2016-jun/", response); + + await host.StopAsync(); } [Fact] @@ -201,17 +302,27 @@ public async Task Invoke_CheckFullUrlWithUFlag() { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader(@"RewriteRule (.+) http://www.example.com$1/")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("http://www.foo.org/blog/2016-jun"); Assert.Equal(@"http://www.example.com/blog/2016-jun/", response); + + await host.StopAsync(); } [Fact] @@ -219,17 +330,27 @@ public async Task Invoke_CheckModFileConditions() { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader(@"RewriteRule (.+) http://www.example.com$1/")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("http://www.foo.org/blog/2016-jun"); Assert.Equal(@"http://www.example.com/blog/2016-jun/", response); + + await host.StopAsync(); } [Theory] @@ -238,18 +359,28 @@ public async Task Invoke_EnsureHttps(string input) { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader("RewriteCond %{REQUEST_URI} /foo/ \nRewriteCond %{HTTPS} !on \nRewriteRule ^(.*)$ https://www.example.com$1 [R=301,L]")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(input); Assert.Equal(response.StatusCode, (HttpStatusCode)301); Assert.Equal(@"https://www.example.com/foo/", response.Headers.Location.AbsoluteUri); + + await host.StopAsync(); } [Theory] @@ -258,18 +389,28 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRedirectLocationHasForwa { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader("RewriteRule ^(.*)$ $1 [R=301,L]")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(input); Assert.Equal(HttpStatusCode.MovedPermanently, response.StatusCode); Assert.Equal("/", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Theory] @@ -278,35 +419,56 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRewriteHasForwardSlash(s { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader("RewriteRule ^(.*)$ $1 [L]")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(input); Assert.Equal("/", response); + + await host.StopAsync(); } [Fact] public async Task Invoke_CaptureEmptyStringInRegexAssertLocationHeaderContainsPathBase() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteRule ^(.*)$ $1 [R=301,L]")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync( - context.Request.Path + - context.Request.QueryString)); - }); - var server = new TestServer(builder) { BaseAddress = new Uri("http://localhost:5000/foo") }; + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("http://localhost:5000/foo"); var response = await server.CreateClient().GetAsync(""); Assert.Equal("/foo", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] @@ -315,18 +477,29 @@ public async Task CapturedVariablesInConditionsArePreservedToRewriteRule() var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteCond %{REQUEST_URI} /home RewriteCond %{QUERY_STRING} report_id=(.+) RewriteRule (.*) http://localhost:80/home/report/%1 [R=301,L,QSD]")); - var builder = new WebHostBuilder().Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync( + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( context.Request.Path + context.Request.QueryString)); - }); + }); + }).Build(); - var server = new TestServer(builder) { BaseAddress = new Uri("http://localhost:5000/foo") }; + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("http://localhost:5000/foo"); var response = await server.CreateClient().GetAsync("/home?report_id=123"); Assert.Equal("http://localhost:80/home/report/123", response.Headers.Location.OriginalString); + + await host.StopAsync(); } } } diff --git a/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs b/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs index a11410d0acc8..94e89e76591b 100644 --- a/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs +++ b/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs @@ -15,6 +15,7 @@ using Microsoft.AspNetCore.Rewrite.UrlActions; using Microsoft.AspNetCore.Rewrite.UrlMatches; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Microsoft.Net.Http.Headers; using Xunit; @@ -33,17 +34,27 @@ public async Task Invoke_RedirectPathToPathAndQuery() ")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Response.Headers[HeaderNames.Location])); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Response.Headers[HeaderNames.Location])); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("article/10/hey"); Assert.Equal("/article.aspx?id=10&title=hey", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] @@ -57,17 +68,27 @@ public async Task Invoke_RewritePathToPathAndQuery() ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("/article/10/hey"); Assert.Equal("/article.aspx?id=10&title=hey", response); + + await host.StopAsync(); } [Fact] @@ -85,17 +106,27 @@ public async Task Invoke_RewriteBasedOnQueryStringParameters() ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("page.asp?p2=321&p1=123"); Assert.Equal("/newpage.aspx?param1=123¶m2=321", response); + + await host.StopAsync(); } [Fact] @@ -109,17 +140,27 @@ public async Task Invoke_RedirectToLowerCase() ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Response.Headers[HeaderNames.Location])); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Response.Headers[HeaderNames.Location])); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("HElLo"); Assert.Equal("/hello", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] @@ -137,16 +178,26 @@ public async Task Invoke_RedirectRemoveTrailingSlash() ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("hey/hello/"); Assert.Equal("/hey/hello", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] @@ -164,16 +215,26 @@ public async Task Invoke_RedirectAddTrailingSlash() ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("hey/hello"); Assert.Equal("/hey/hello/", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] @@ -190,16 +251,26 @@ public async Task Invoke_RedirectToHttps() ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("http://example.com")); Assert.Equal("https://example.com/", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] @@ -216,22 +287,32 @@ public async Task Invoke_RewriteToHttps() ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync( - context.Request.Scheme + - "://" + - context.Request.Host + - context.Request.Path + - context.Request.QueryString)); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Scheme + + "://" + + context.Request.Host + + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(new Uri("http://example.com")); Assert.Equal("https://example.com/", response); + + await host.StopAsync(); } [Fact] @@ -245,22 +326,32 @@ public async Task Invoke_ReverseProxyToAnotherSite() ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync( - context.Request.Scheme + - "://" + - context.Request.Host + - context.Request.Path + - context.Request.QueryString)); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Scheme + + "://" + + context.Request.Host + + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(new Uri("http://example.com/")); Assert.Equal("http://internalserver/", response); + + await host.StopAsync(); } [Fact] @@ -274,22 +365,32 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRedirectLocationHasForwa ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync( - context.Request.Scheme + - "://" + - context.Request.Host + - context.Request.Path + - context.Request.QueryString)); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Scheme + + "://" + + context.Request.Host + + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("http://example.com/")); Assert.Equal("/", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] @@ -303,19 +404,29 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRewriteLocationHasForwar ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync( - context.Request.Path + - context.Request.QueryString)); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(new Uri("http://example.com/")); Assert.Equal("/", response); + + await host.StopAsync(); } [Fact] @@ -329,19 +440,30 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertLocationHeaderContainsPa ")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync( - context.Request.Path + - context.Request.QueryString)); - }); - var server = new TestServer(builder) { BaseAddress = new Uri("http://localhost:5000/foo") }; + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("http://localhost:5000/foo"); var response = await server.CreateClient().GetAsync(""); Assert.Equal("/foo", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Theory] @@ -362,16 +484,26 @@ public async Task VerifyIsFileAndIsDirectoryParsing(string matchType) ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("hey/hello"); Assert.Equal("/hey/hello/", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] @@ -390,16 +522,26 @@ public async Task VerifyTrackAllCaptures() ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("article/23?p1=123&p2=abc"); Assert.Equal("/blogposts/article/abc?p1=123&p2=abc", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] @@ -418,16 +560,26 @@ public async Task VerifyTrackAllCapturesRuleAndConditionCapture() ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("article/23?p1=123&p2=abc"); Assert.Equal("/blog/article/23/abc?p1=123&p2=abc", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] @@ -447,16 +599,26 @@ public async Task ThrowIndexOutOfRangeExceptionWithCorrectMessage() ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var ex = await Assert.ThrowsAsync(() => server.CreateClient().GetAsync("article/23?p1=123&p2=abc")); Assert.Equal("Cannot access back reference at index 9. Only 5 back references were captured.", ex.Message); + + await host.StopAsync(); } [Fact] @@ -475,19 +637,29 @@ public async Task Invoke_GlobalRuleConditionMatchesAgainstFullUri_ParsedRule() "; var options = new RewriteOptions().AddIISUrlRewrite(new StringReader(xml)); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.GetEncodedUrl())); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.GetEncodedUrl())); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // act var response = await server.CreateClient().GetStringAsync($"http://localhost/{Guid.NewGuid()}/foo/bar"); // assert Assert.Equal("http://www.test.com/foo/bar", response); + + await host.StopAsync(); } [Theory] @@ -512,17 +684,27 @@ public async Task Invoke_ReverseProxyToAnotherSiteUsingXmlConfiguredRewriteMap(s ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.GetEncodedUrl())); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.GetEncodedUrl())); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(new Uri(requestUri)); Assert.Equal(expectedRewrittenUri, response); + + await host.StopAsync(); } [Fact] @@ -536,12 +718,20 @@ public async Task Invoke_CustomResponse() ")); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("article/10/hey"); var content = await response.Content.ReadAsStringAsync(); @@ -549,6 +739,8 @@ public async Task Invoke_CustomResponse() Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); Assert.Equal("reason", response.ReasonPhrase); Assert.Equal("description", content); + + await host.StopAsync(); } [Theory] @@ -583,19 +775,29 @@ public async Task Invoke_GlobalRuleConditionMatchesAgainstFullUri_CodedRule(stri ruleBuilder.AddUrlAction(action); var options = new RewriteOptions().Add(ruleBuilder.Build()); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.GetEncodedUrl())); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.GetEncodedUrl())); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // act var response = await server.CreateClient().GetStringAsync("http://localhost/foo/bar"); // assert Assert.Equal(expectedResult, response); + + await host.StopAsync(); } } } diff --git a/src/Middleware/Rewrite/test/MiddlewareTests.cs b/src/Middleware/Rewrite/test/MiddlewareTests.cs index e8a4a4aec893..1c1534ff06f3 100644 --- a/src/Middleware/Rewrite/test/MiddlewareTests.cs +++ b/src/Middleware/Rewrite/test/MiddlewareTests.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Rewrite.Tests.CodeRules @@ -18,76 +19,116 @@ public class MiddlewareTests public async Task CheckRewritePath() { var options = new RewriteOptions().AddRewrite("(.*)", "http://example.com/$1", skipRemainingRules: false); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync( - context.Request.Scheme + - "://" + - context.Request.Host + - context.Request.Path + - context.Request.QueryString)); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Scheme + + "://" + + context.Request.Host + + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("foo"); Assert.Equal("http://example.com/foo", response); + + await host.StopAsync(); } [Fact] public async Task CheckRedirectPath() { var options = new RewriteOptions().AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("foo"); Assert.Equal("http://example.com/foo", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] public async Task RewriteRulesCanComeFromConfigureOptions() { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.Configure(options => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently); - }); - }) - .Configure(app => - { - app.UseRewriter(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.Configure(options => + { + options.AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently); + }); + }) + .Configure(app => + { + app.UseRewriter(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("foo"); Assert.Equal("http://example.com/foo", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] public async Task CheckRedirectPathWithQueryString() { var options = new RewriteOptions().AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("foo?bar=1"); Assert.Equal("http://example.com/foo?bar=1", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Theory] @@ -98,34 +139,54 @@ public async Task CheckRedirectPathWithQueryString() public async Task CheckRedirectToHttps(int statusCode) { var options = new RewriteOptions().AddRedirectToHttps(statusCode: statusCode); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("http://example.com")); Assert.Equal("https://example.com/", response.Headers.Location.OriginalString); Assert.Equal(statusCode, (int)response.StatusCode); + + await host.StopAsync(); } [Fact] public async Task CheckPermanentRedirectToHttps() { var options = new RewriteOptions().AddRedirectToHttpsPermanent(); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("http://example.com")); Assert.Equal("https://example.com/", response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status301MovedPermanently, (int)response.StatusCode); + + await host.StopAsync(); } [Theory] @@ -134,17 +195,27 @@ public async Task CheckPermanentRedirectToHttps() public async Task CheckRedirectToHttpsWithSslPort(int sslPort, string expected) { var options = new RewriteOptions().AddRedirectToHttps(statusCode: StatusCodes.Status301MovedPermanently, sslPort: sslPort); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("http://example.com")); Assert.Equal(expected, response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status301MovedPermanently, (int)response.StatusCode); + + await host.StopAsync(); } [Theory] @@ -155,17 +226,27 @@ public async Task CheckRedirectToHttpsWithSslPort(int sslPort, string expected) public async Task CheckRedirectToWwwWithStatusCode(int statusCode) { var options = new RewriteOptions().AddRedirectToWww(statusCode: statusCode); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("https://example.com")); Assert.Equal("https://www.example.com/", response.Headers.Location.OriginalString); Assert.Equal(statusCode, (int)response.StatusCode); + + await host.StopAsync(); } [Theory] @@ -176,34 +257,54 @@ public async Task CheckRedirectToWwwWithStatusCode(int statusCode) public async Task CheckRedirectToWww(string requestUri, string redirectUri) { var options = new RewriteOptions().AddRedirectToWww(); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri(requestUri)); Assert.Equal(redirectUri, response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status307TemporaryRedirect, (int)response.StatusCode); + + await host.StopAsync(); } [Fact] public async Task CheckPermanentRedirectToWww() { var options = new RewriteOptions().AddRedirectToWwwPermanent(); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("https://example.com")); Assert.Equal("https://www.example.com/", response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status308PermanentRedirect, (int)response.StatusCode); + + await host.StopAsync(); } [Theory] @@ -220,16 +321,26 @@ public async Task CheckPermanentRedirectToWww() public async Task CheckNoRedirectToWww(string requestUri) { var options = new RewriteOptions().AddRedirectToWww(); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri(requestUri)); Assert.Null(response.Headers.Location); + + await host.StopAsync(); } [Theory] @@ -240,17 +351,27 @@ public async Task CheckNoRedirectToWww(string requestUri) public async Task CheckRedirectToNonWwwWithStatusCode(int statusCode) { var options = new RewriteOptions().AddRedirectToNonWww(statusCode: statusCode); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("https://www.example.com")); Assert.Equal("https://example.com/", response.Headers.Location.OriginalString); Assert.Equal(statusCode, (int)response.StatusCode); + + await host.StopAsync(); } [Theory] @@ -261,87 +382,138 @@ public async Task CheckRedirectToNonWwwWithStatusCode(int statusCode) public async Task CheckRedirectToNonWww(string requestUri, string redirectUri) { var options = new RewriteOptions().AddRedirectToNonWww(); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri(requestUri)); Assert.Equal(redirectUri, response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status307TemporaryRedirect, (int)response.StatusCode); + + await host.StopAsync(); } [Fact] public async Task CheckPermanentRedirectToNonWww() { var options = new RewriteOptions().AddRedirectToNonWwwPermanent(); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("https://www.example.com")); Assert.Equal("https://example.com/", response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status308PermanentRedirect, (int)response.StatusCode); + + await host.StopAsync(); } [Fact] public async Task CheckIfEmptyStringRedirectCorrectly() { var options = new RewriteOptions().AddRedirect("(.*)", "$1", statusCode: StatusCodes.Status301MovedPermanently); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(""); Assert.Equal("/", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Fact] public async Task CheckIfEmptyStringRewriteCorrectly() { var options = new RewriteOptions().AddRewrite("(.*)", "$1", skipRemainingRules: false); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync( - context.Request.Path + - context.Request.QueryString)); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(""); Assert.Equal("/", response); + + await host.StopAsync(); } [Fact] public async Task SettingPathBase() { var options = new RewriteOptions().AddRedirect("(.*)", "$1"); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync( - context.Request.Path + - context.Request.QueryString)); - }); - var server = new TestServer(builder) { BaseAddress = new Uri("http://localhost:5000/foo") }; + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("http://localhost:5000/foo"); var response = await server.CreateClient().GetAsync(""); Assert.Equal("/foo", response.Headers.Location.OriginalString); + + await host.StopAsync(); } [Theory] @@ -353,16 +525,26 @@ public async Task SettingPathBase() public async Task CheckNoRedirectToWwwInNonWhitelistedDomains(string requestUri) { var options = new RewriteOptions().AddRedirectToWww("example2.com"); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri(requestUri)); Assert.Null(response.Headers.Location); + + await host.StopAsync(); } [Theory] @@ -373,34 +555,54 @@ public async Task CheckNoRedirectToWwwInNonWhitelistedDomains(string requestUri) public async Task CheckRedirectToWwwInWhitelistedDomains(string requestUri, string redirectUri) { var options = new RewriteOptions().AddRedirectToWww("example.com"); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri(requestUri)); Assert.Equal(redirectUri, response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status307TemporaryRedirect, (int)response.StatusCode); + + await host.StopAsync(); } [Fact] public async Task CheckPermanentRedirectToWwwInWhitelistedDomains() { var options = new RewriteOptions().AddRedirectToWwwPermanent("example.com"); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("https://example.com")); Assert.Equal("https://www.example.com/", response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status308PermanentRedirect, (int)response.StatusCode); + + await host.StopAsync(); } [Theory] @@ -411,17 +613,27 @@ public async Task CheckPermanentRedirectToWwwInWhitelistedDomains() public async Task CheckRedirectToWwwWithStatusCodeInWhitelistedDomains(int statusCode) { var options = new RewriteOptions().AddRedirectToWww(statusCode: statusCode, "example.com"); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("https://example.com")); Assert.Equal("https://www.example.com/", response.Headers.Location.OriginalString); Assert.Equal(statusCode, (int)response.StatusCode); + + await host.StopAsync(); } } From 961f696e9fae172d698e1136df718d93d6cb73ca Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:09:21 -0700 Subject: [PATCH 16/20] Session --- src/Middleware/Session/samples/Startup.cs | 21 +- src/Middleware/Session/test/SessionTests.cs | 1032 +++++++++++-------- 2 files changed, 624 insertions(+), 429 deletions(-) diff --git a/src/Middleware/Session/samples/Startup.cs b/src/Middleware/Session/samples/Startup.cs index 9bc4265dafa1..c440f6e9b1fd 100644 --- a/src/Middleware/Session/samples/Startup.cs +++ b/src/Middleware/Session/samples/Startup.cs @@ -2,10 +2,12 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace SessionSample @@ -81,16 +83,19 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .ConfigureLogging(factory => factory.AddConsole()) - .UseKestrel() - .UseIISIntegration() - .UseStartup() - .Build(); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .ConfigureLogging(factory => factory.AddConsole()) + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/Session/test/SessionTests.cs b/src/Middleware/Session/test/SessionTests.cs index 1b0a55e4474c..d34bb25ba4d4 100644 --- a/src/Middleware/Session/test/SessionTests.cs +++ b/src/Middleware/Session/test/SessionTests.cs @@ -14,6 +14,7 @@ using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Internal; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -29,54 +30,70 @@ public class SessionTests [Fact] public async Task ReadingEmptySessionDoesNotCreateCookie() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseSession(); - app.Run(context => + app.Run(context => + { + Assert.Null(context.Session.GetString("NotFound")); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - Assert.Null(context.Session.GetString("NotFound")); - return Task.FromResult(0); + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); response.EnsureSuccessStatusCode(); Assert.False(response.Headers.TryGetValues("Set-Cookie", out var _)); } + + await host.StopAsync(); } [Fact] public async Task SettingAValueCausesTheCookieToBeCreated() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseSession(); + app.Run(context => + { + Assert.Null(context.Session.GetString("Key")); + context.Session.SetString("Key", "Value"); + Assert.Equal("Value", context.Session.GetString("Key")); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - Assert.Null(context.Session.GetString("Key")); - context.Session.SetString("Key", "Value"); - Assert.Equal("Value", context.Session.GetString("Key")); - return Task.FromResult(0); + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -85,6 +102,8 @@ public async Task SettingAValueCausesTheCookieToBeCreated() Assert.Single(values); Assert.True(!string.IsNullOrWhiteSpace(values.First())); } + + await host.StopAsync(); } [Theory] @@ -99,32 +118,39 @@ public async Task SecureSessionBasedOnHttpsAndSecurePolicy( string requestUri, bool shouldBeSecureOnly) { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseSession(new SessionOptions - { - Cookie = - { - Name = "TestCookie", - SecurePolicy = cookieSecurePolicy - } - }); - app.Run(context => - { - Assert.Null(context.Session.GetString("Key")); - context.Session.SetString("Key", "Value"); - Assert.Equal("Value", context.Session.GetString("Key")); - return Task.FromResult(0); - }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); - - using (var server = new TestServer(builder)) + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseSession(new SessionOptions + { + Cookie = + { + Name = "TestCookie", + SecurePolicy = cookieSecurePolicy + } + }); + app.Run(context => + { + Assert.Null(context.Session.GetString("Key")); + context.Session.SetString("Key", "Value"); + Assert.Equal("Value", context.Session.GetString("Key")); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => + { + services.AddDistributedMemoryCache(); + services.AddSession(); + }); + }).Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(requestUri); @@ -140,35 +166,44 @@ public async Task SecureSessionBasedOnHttpsAndSecurePolicy( Assert.DoesNotContain("; secure", values.First()); } } + + await host.StopAsync(); } [Fact] public async Task SessionCanBeAccessedOnTheNextRequest() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - int? value = context.Session.GetInt32("Key"); - if (context.Request.Path == new PathString("/first")) + app.UseSession(); + app.Run(context => { - Assert.False(value.HasValue); - value = 0; - } - Assert.True(value.HasValue); - context.Session.SetInt32("Key", value.Value + 1); - return context.Response.WriteAsync(value.Value.ToString()); + int? value = context.Session.GetInt32("Key"); + if (context.Request.Path == new PathString("/first")) + { + Assert.False(value.HasValue); + value = 0; + } + Assert.True(value.HasValue); + context.Session.SetInt32("Key", value.Value + 1); + return context.Response.WriteAsync(value.Value.ToString()); + }); + }) + .ConfigureServices(services => + { + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("first"); @@ -181,47 +216,56 @@ public async Task SessionCanBeAccessedOnTheNextRequest() Assert.Equal("1", await client.GetStringAsync("/")); Assert.Equal("2", await client.GetStringAsync("/")); Assert.Equal("3", await client.GetStringAsync("/")); + + await host.StopAsync(); } } [Fact] public async Task RemovedItemCannotBeAccessedAgain() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - int? value = context.Session.GetInt32("Key"); - if (context.Request.Path == new PathString("/first")) - { - Assert.False(value.HasValue); - value = 0; - context.Session.SetInt32("Key", 1); - } - else if (context.Request.Path == new PathString("/second")) - { - Assert.True(value.HasValue); - Assert.Equal(1, value); - context.Session.Remove("Key"); - } - else if (context.Request.Path == new PathString("/third")) + app.UseSession(); + app.Run(context => { - Assert.False(value.HasValue); - value = 2; - } - return context.Response.WriteAsync(value.Value.ToString()); + int? value = context.Session.GetInt32("Key"); + if (context.Request.Path == new PathString("/first")) + { + Assert.False(value.HasValue); + value = 0; + context.Session.SetInt32("Key", 1); + } + else if (context.Request.Path == new PathString("/second")) + { + Assert.True(value.HasValue); + Assert.Equal(1, value); + context.Session.Remove("Key"); + } + else if (context.Request.Path == new PathString("/third")) + { + Assert.False(value.HasValue); + value = 2; + } + return context.Response.WriteAsync(value.Value.ToString()); + }); + }) + .ConfigureServices( + services => + { + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices( - services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("first"); @@ -234,45 +278,54 @@ public async Task RemovedItemCannotBeAccessedAgain() Assert.Equal("1", await client.GetStringAsync("/second")); Assert.Equal("2", await client.GetStringAsync("/third")); } + + await host.StopAsync(); } [Fact] public async Task ClearedItemsCannotBeAccessedAgain() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - int? value = context.Session.GetInt32("Key"); - if (context.Request.Path == new PathString("/first")) + app.UseSession(); + app.Run(context => { - Assert.False(value.HasValue); - value = 0; - context.Session.SetInt32("Key", 1); - } - else if (context.Request.Path == new PathString("/second")) - { - Assert.True(value.HasValue); - Assert.Equal(1, value); - context.Session.Clear(); - } - else if (context.Request.Path == new PathString("/third")) - { - Assert.False(value.HasValue); - value = 2; - } - return context.Response.WriteAsync(value.Value.ToString()); + int? value = context.Session.GetInt32("Key"); + if (context.Request.Path == new PathString("/first")) + { + Assert.False(value.HasValue); + value = 0; + context.Session.SetInt32("Key", 1); + } + else if (context.Request.Path == new PathString("/second")) + { + Assert.True(value.HasValue); + Assert.Equal(1, value); + context.Session.Clear(); + } + else if (context.Request.Path == new PathString("/third")) + { + Assert.False(value.HasValue); + value = 2; + } + return context.Response.WriteAsync(value.Value.ToString()); + }); + }) + .ConfigureServices(services => + { + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("first"); @@ -285,6 +338,8 @@ public async Task ClearedItemsCannotBeAccessedAgain() Assert.Equal("1", await client.GetStringAsync("/second")); Assert.Equal("2", await client.GetStringAsync("/third")); } + + await host.StopAsync(); } [Fact] @@ -294,24 +349,31 @@ public async Task SessionStart_LogsInformation() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseSession(); + app.Run(context => + { + context.Session.SetString("Key", "Value"); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - context.Session.SetString("Key", "Value"); - return Task.FromResult(0); + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -325,6 +387,8 @@ public async Task SessionStart_LogsInformation() Assert.Equal(LogLevel.Information, sessionLogMessages[0].LogLevel); Assert.Contains("stored", sessionLogMessages[1].State.ToString()); Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel); + + await host.StopAsync(); } [Fact] @@ -334,36 +398,43 @@ public async Task ExpiredSession_LogsInfo() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - int? value = context.Session.GetInt32("Key"); - if (context.Request.Path == new PathString("/first")) + app.UseSession(); + app.Run(context => { - Assert.False(value.HasValue); - value = 1; - context.Session.SetInt32("Key", 1); - } - else if (context.Request.Path == new PathString("/second")) - { - Assert.False(value.HasValue); - value = 2; - } - return context.Response.WriteAsync(value.Value.ToString()); + int? value = context.Session.GetInt32("Key"); + if (context.Request.Path == new PathString("/first")) + { + Assert.False(value.HasValue); + value = 1; + context.Session.SetInt32("Key", 1); + } + else if (context.Request.Path == new PathString("/second")) + { + Assert.False(value.HasValue); + value = 2; + } + return context.Response.WriteAsync(value.Value.ToString()); + }); + }) + .ConfigureServices(services => + { + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddDistributedMemoryCache(); + services.AddSession(o => o.IdleTimeout = TimeSpan.FromMilliseconds(30)); }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddDistributedMemoryCache(); - services.AddSession(o => o.IdleTimeout = TimeSpan.FromMilliseconds(30)); - }); + }).Build(); + + await host.StartAsync(); string result; - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("first"); @@ -386,46 +457,55 @@ public async Task ExpiredSession_LogsInfo() Assert.Equal(LogLevel.Information, sessionLogMessages[0].LogLevel); Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel); Assert.Equal(LogLevel.Information, sessionLogMessages[2].LogLevel); + + await host.StopAsync(); } [Fact] public async Task RefreshesSession_WhenSessionData_IsNotModified() { var clock = new TestClock(); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - string responseData = string.Empty; - if (context.Request.Path == new PathString("/AddDataToSession")) - { - context.Session.SetInt32("Key", 10); - responseData = "added data to session"; - } - else if (context.Request.Path == new PathString("/AccessSessionData")) - { - var value = context.Session.GetInt32("Key"); - responseData = (value == null) ? "No value found in session." : value.ToString(); - } - else if (context.Request.Path == new PathString("/DoNotAccessSessionData")) + app.UseSession(); + app.Run(context => { - responseData = "did not access session data"; - } - - return context.Response.WriteAsync(responseData); + string responseData = string.Empty; + if (context.Request.Path == new PathString("/AddDataToSession")) + { + context.Session.SetInt32("Key", 10); + responseData = "added data to session"; + } + else if (context.Request.Path == new PathString("/AccessSessionData")) + { + var value = context.Session.GetInt32("Key"); + responseData = (value == null) ? "No value found in session." : value.ToString(); + } + else if (context.Request.Path == new PathString("/DoNotAccessSessionData")) + { + responseData = "did not access session data"; + } + + return context.Response.WriteAsync(responseData); + }); + }) + .ConfigureServices(services => + { + services.AddSingleton(typeof(ILoggerFactory), NullLoggerFactory.Instance); + services.AddDistributedMemoryCache(); + services.AddSession(o => o.IdleTimeout = TimeSpan.FromMinutes(20)); + services.Configure(o => o.Clock = clock); }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), NullLoggerFactory.Instance); - services.AddDistributedMemoryCache(); - services.AddSession(o => o.IdleTimeout = TimeSpan.FromMinutes(20)); - services.Configure(o => o.Clock = clock); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("AddDataToSession"); @@ -445,113 +525,142 @@ public async Task RefreshesSession_WhenSessionData_IsNotModified() var data = await client.GetStringAsync("/AccessSessionData"); Assert.Equal("10", data); } + + await host.StopAsync(); } [Fact] public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (httpContext, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - await next(); + app.Use(async (httpContext, next) => + { + await next(); - Assert.Null(httpContext.Features.Get()); - }); + Assert.Null(httpContext.Features.Get()); + }); - app.UseSession(); + app.UseSession(); - app.Run(context => + app.Run(context => + { + context.Session.SetString("key", "value"); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - context.Session.SetString("key", "value"); - return Task.FromResult(0); + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); response.EnsureSuccessStatusCode(); } + + await host.StopAsync(); } [Fact] public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut_AndAnUnhandledExcetionIsThrown() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (httpContext, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - var exceptionThrown = false; - try + app.Use(async (httpContext, next) => { - await next(); - } - catch + var exceptionThrown = false; + try + { + await next(); + } + catch + { + exceptionThrown = true; + } + + Assert.True(exceptionThrown); + Assert.Null(httpContext.Features.Get()); + }); + + app.UseSession(); + + app.Run(context => { - exceptionThrown = true; - } - - Assert.True(exceptionThrown); - Assert.Null(httpContext.Features.Get()); - }); - - app.UseSession(); - - app.Run(context => + throw new InvalidOperationException("An error occurred."); + }); + }) + .ConfigureServices(services => { - throw new InvalidOperationException("An error occurred."); + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); } + + await host.StopAsync(); } [Fact] public async Task SessionKeys_AreCaseSensitive() { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - context.Session.SetString("KEY", "VALUE"); - context.Session.SetString("key", "value"); - Assert.Equal("VALUE", context.Session.GetString("KEY")); - Assert.Equal("value", context.Session.GetString("key")); - return Task.FromResult(0); + app.UseSession(); + app.Run(context => + { + context.Session.SetString("KEY", "VALUE"); + context.Session.SetString("key", "value"); + Assert.Equal("VALUE", context.Session.GetString("KEY")); + Assert.Equal("value", context.Session.GetString("key")); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => + { + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); response.EnsureSuccessStatusCode(); } + + await host.StopAsync(); } [Fact] @@ -561,30 +670,37 @@ public async Task SessionLogsCacheReadException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.False(context.Session.TryGetValue("key", out var value)); - Assert.Null(value); - Assert.Equal(string.Empty, context.Session.Id); - Assert.False(context.Session.Keys.Any()); - return Task.FromResult(0); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(context => + { + Assert.False(context.Session.TryGetValue("key", out var value)); + Assert.Null(value); + Assert.Equal(string.Empty, context.Session.Id); + Assert.False(context.Session.Keys.Any()); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - DisableGet = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DisableGet = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -594,6 +710,8 @@ public async Task SessionLogsCacheReadException() var message = Assert.Single(sink.Writes); Assert.Contains("Session cache read exception", message.State.ToString()); Assert.Equal(LogLevel.Error, message.LogLevel); + + await host.StopAsync(); } [Fact] @@ -603,29 +721,36 @@ public async Task SessionLogsCacheLoadAsyncException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await Assert.ThrowsAsync(() => context.Session.LoadAsync()); - Assert.False(context.Session.IsAvailable); - Assert.Equal(string.Empty, context.Session.Id); - Assert.False(context.Session.Keys.Any()); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(async context => + { + await Assert.ThrowsAsync(() => context.Session.LoadAsync()); + Assert.False(context.Session.IsAvailable); + Assert.Equal(string.Empty, context.Session.Id); + Assert.False(context.Session.Keys.Any()); + }); + }) + .ConfigureServices(services => { - DisableGet = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DisableGet = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -635,6 +760,8 @@ public async Task SessionLogsCacheLoadAsyncException() var message = Assert.Single(sink.Writes); Assert.Contains("Session cache read exception", message.State.ToString()); Assert.Equal(LogLevel.Error, message.LogLevel); + + await host.StopAsync(); } [Fact] @@ -644,29 +771,36 @@ public async Task SessionLogsCacheLoadAsyncTimeoutException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(new SessionOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - IOTimeout = TimeSpan.FromSeconds(0.5) - }); - app.Run(async context => - { - await Assert.ThrowsAsync(() => context.Session.LoadAsync()); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(new SessionOptions() + { + IOTimeout = TimeSpan.FromSeconds(0.5) + }); + app.Run(async context => + { + await Assert.ThrowsAsync(() => context.Session.LoadAsync()); + }); + }) + .ConfigureServices(services => { - DelayGetAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DelayGetAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -676,6 +810,8 @@ public async Task SessionLogsCacheLoadAsyncTimeoutException() var message = Assert.Single(sink.Writes); Assert.Contains("Loading the session timed out.", message.State.ToString()); Assert.Equal(LogLevel.Warning, message.LogLevel); + + await host.StopAsync(); } [Fact] @@ -685,29 +821,36 @@ public async Task SessionLoadAsyncCanceledException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - var cts = new CancellationTokenSource(); - var token = cts.Token; - cts.Cancel(); - await Assert.ThrowsAsync(() => context.Session.LoadAsync(token)); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(async context => + { + var cts = new CancellationTokenSource(); + var token = cts.Token; + cts.Cancel(); + await Assert.ThrowsAsync(() => context.Session.LoadAsync(token)); + }); + }) + .ConfigureServices(services => { - DelayGetAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DelayGetAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -715,6 +858,8 @@ public async Task SessionLoadAsyncCanceledException() } Assert.Empty(sink.Writes); + + await host.StopAsync(); } [Fact] @@ -732,27 +877,34 @@ public async Task SessionLogsCacheCommitException() || beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName); }); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - context.Session.SetInt32("key", 0); - return Task.FromResult(0); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(context => + { + context.Session.SetInt32("key", 0); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - DisableSetAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DisableSetAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -768,6 +920,8 @@ public async Task SessionLogsCacheCommitException() Assert.Contains("Error closing the session.", sessionMiddlewareLogMessage.State.ToString()); Assert.Equal(LogLevel.Error, sessionMiddlewareLogMessage.LogLevel); + + await host.StopAsync(); } [Fact] @@ -785,30 +939,37 @@ public async Task SessionLogsCacheCommitTimeoutException() || beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName); }); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(new SessionOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - IOTimeout = TimeSpan.FromSeconds(0.5) - }); - app.Run(context => - { - context.Session.SetInt32("key", 0); - return Task.FromResult(0); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(new SessionOptions() + { + IOTimeout = TimeSpan.FromSeconds(0.5) + }); + app.Run(context => + { + context.Session.SetInt32("key", 0); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - DelaySetAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DelaySetAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -827,6 +988,8 @@ public async Task SessionLogsCacheCommitTimeoutException() Assert.Contains("Committing the session was canceled.", sessionMiddlewareLogs[0].State.ToString()); Assert.Equal(LogLevel.Information, sessionMiddlewareLogs[0].LogLevel); + + await host.StopAsync(); } [Fact] @@ -844,30 +1007,37 @@ public async Task SessionLogsCacheCommitCanceledException() || beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName); }); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - context.Session.SetInt32("key", 0); - var cts = new CancellationTokenSource(); - var token = cts.Token; - cts.Cancel(); - await Assert.ThrowsAsync(() => context.Session.CommitAsync(token)); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(async context => + { + context.Session.SetInt32("key", 0); + var cts = new CancellationTokenSource(); + var token = cts.Token; + cts.Cancel(); + await Assert.ThrowsAsync(() => context.Session.CommitAsync(token)); + }); + }) + .ConfigureServices(services => { - DelaySetAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DelaySetAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -884,6 +1054,8 @@ public async Task SessionLogsCacheCommitCanceledException() Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel); Assert.Empty(sink.Writes.Where(message => message.LoggerName.Equals(typeof(SessionMiddleware).FullName, StringComparison.Ordinal))); + + await host.StopAsync(); } [Fact] @@ -901,31 +1073,38 @@ public async Task RequestAbortedIgnored() || beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName); }); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - context.Session.SetInt32("key", 0); - var cts = new CancellationTokenSource(); - var token = cts.Token; - cts.Cancel(); - context.RequestAborted = token; - return Task.CompletedTask; - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(context => + { + context.Session.SetInt32("key", 0); + var cts = new CancellationTokenSource(); + var token = cts.Token; + cts.Cancel(); + context.RequestAborted = token; + return Task.CompletedTask; + }); + }) + .ConfigureServices(services => { - DelaySetAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DelaySetAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -941,6 +1120,8 @@ public async Task RequestAbortedIgnored() Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel); Assert.Empty(sink.Writes.Where(message => message.LoggerName.Equals(typeof(SessionMiddleware).FullName, StringComparison.Ordinal))); + + await host.StopAsync(); } [Fact] @@ -950,27 +1131,34 @@ public async Task SessionLogsCacheRefreshException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - // The middleware calls context.Session.CommitAsync() once per request - return Task.FromResult(0); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(context => + { + // The middleware calls context.Session.CommitAsync() once per request + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - DisableRefreshAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DisableRefreshAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -980,6 +1168,8 @@ public async Task SessionLogsCacheRefreshException() var message = Assert.Single(sink.Writes); Assert.Contains("Error closing the session.", message.State.ToString()); Assert.Equal(LogLevel.Error, message.LogLevel); + + await host.StopAsync(); } private class TestClock : ISystemClock From 6e6e1901a394d4d57611eb768b988e38dc6cf5f9 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:09:51 -0700 Subject: [PATCH 17/20] StaticFiles --- .../samples/StaticFileSample/Startup.cs | 31 +- .../FunctionalTests/FallbackStaticFileTest.cs | 133 ++++---- .../test/FunctionalTests/Helpers.cs | 7 +- .../StaticFileMiddlewareTests.cs | 304 ++++++++++-------- .../UnitTests/StaticFileMiddlewareTests.cs | 61 +++- .../test/UnitTests/StaticFilesTestServer.cs | 20 +- 6 files changed, 325 insertions(+), 231 deletions(-) diff --git a/src/Middleware/StaticFiles/samples/StaticFileSample/Startup.cs b/src/Middleware/StaticFiles/samples/StaticFileSample/Startup.cs index b0d553e15d51..bbaea9dcd43a 100644 --- a/src/Middleware/StaticFiles/samples/StaticFileSample/Startup.cs +++ b/src/Middleware/StaticFiles/samples/StaticFileSample/Startup.cs @@ -1,8 +1,10 @@ using System; using System.IO; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace StaticFilesSample @@ -25,22 +27,25 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment host) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .ConfigureLogging(factory => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - factory.AddFilter("Console", level => level >= LogLevel.Debug); - factory.AddConsole(); - }) - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseKestrel() - // .UseHttpSys() - .UseIISIntegration() - .UseStartup() - .Build(); + webHostBuilder + .ConfigureLogging(factory => + { + factory.AddFilter("Console", level => level >= LogLevel.Debug); + factory.AddConsole(); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseKestrel() + // .UseHttpSys() + .UseIISIntegration() + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs b/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs index e3c1073174bd..e9723a819f89 100644 --- a/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs +++ b/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs @@ -15,6 +15,7 @@ using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging.Testing; using Xunit; @@ -25,94 +26,104 @@ public class FallbackStaticFileTest : LoggedTest [Fact] public async Task ReturnsFileForDefaultPattern() { - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddRouting(); - services.AddSingleton(LoggerFactory); - }) - .UseKestrel() - .UseWebRoot(AppContext.BaseDirectory) - .Configure(app => - { - var environment = app.ApplicationServices.GetRequiredService(); - app.UseRouting(); - app.UseEndpoints(endpoints => + webHostBuilder + .ConfigureServices(services => + { + services.AddRouting(); + services.AddSingleton(LoggerFactory); + }) + .UseKestrel() + .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) + .UseWebRoot(AppContext.BaseDirectory) + .Configure(app => { - endpoints.Map("/hello", context => + var environment = app.ApplicationServices.GetRequiredService(); + app.UseRouting(); + app.UseEndpoints(endpoints => { - return context.Response.WriteAsync("Hello, world!"); - }); + endpoints.Map("/hello", context => + { + return context.Response.WriteAsync("Hello, world!"); + }); - endpoints.MapFallbackToFile("default.html", new StaticFileOptions() - { - FileProvider = new PhysicalFileProvider(Path.Combine(environment.WebRootPath, "SubFolder")), + endpoints.MapFallbackToFile("default.html", new StaticFileOptions() + { + FileProvider = new PhysicalFileProvider(Path.Combine(environment.WebRootPath, "SubFolder")), + }); }); }); - }); + }).Build(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) + await host.StartAsync(); + + var environment = host.Services.GetRequiredService(); + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { - var environment = server.Services.GetRequiredService(); - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var response = await client.GetAsync("hello"); - var responseText = await response.Content.ReadAsStringAsync(); + var response = await client.GetAsync("hello"); + var responseText = await response.Content.ReadAsStringAsync(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Hello, world!", responseText); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("Hello, world!", responseText); - response = await client.GetAsync("/"); - var responseContent = await response.Content.ReadAsByteArrayAsync(); + response = await client.GetAsync("/"); + var responseContent = await response.Content.ReadAsByteArrayAsync(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - AssertFileEquals(environment, "SubFolder/default.html", responseContent); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + AssertFileEquals(environment, "SubFolder/default.html", responseContent); } + + await host.StopAsync(); } [Fact] public async Task ReturnsFileForCustomPattern() { - var builder = new WebHostBuilder() - .ConfigureServices(services => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddRouting(); - services.AddSingleton(LoggerFactory); - }) - .UseKestrel() - .UseWebRoot(AppContext.BaseDirectory) - .Configure(app => - { - app.UseRouting(); - app.UseEndpoints(endpoints => + webHostBuilder + .ConfigureServices(services => + { + services.AddRouting(); + services.AddSingleton(LoggerFactory); + }) + .UseKestrel() + .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) + .UseWebRoot(AppContext.BaseDirectory) + .Configure(app => { - endpoints.Map("/hello", context => + app.UseRouting(); + app.UseEndpoints(endpoints => { - return context.Response.WriteAsync("Hello, world!"); - }); + endpoints.Map("/hello", context => + { + return context.Response.WriteAsync("Hello, world!"); + }); - endpoints.MapFallbackToFile("/prefix/{*path:nonfile}", "TestDocument.txt"); + endpoints.MapFallbackToFile("/prefix/{*path:nonfile}", "TestDocument.txt"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) + var environment = host.Services.GetRequiredService(); + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { - var environment = server.Services.GetRequiredService(); - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var response = await client.GetAsync("hello"); - var responseText = await response.Content.ReadAsStringAsync(); + var response = await client.GetAsync("hello"); + var responseText = await response.Content.ReadAsStringAsync(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Hello, world!", responseText); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("Hello, world!", responseText); - response = await client.GetAsync("prefix/Some-Path"); - var responseContent = await response.Content.ReadAsByteArrayAsync(); + response = await client.GetAsync("prefix/Some-Path"); + var responseContent = await response.Content.ReadAsByteArrayAsync(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - AssertFileEquals(environment, "TestDocument.txt", responseContent); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + AssertFileEquals(environment, "TestDocument.txt", responseContent); } } diff --git a/src/Middleware/StaticFiles/test/FunctionalTests/Helpers.cs b/src/Middleware/StaticFiles/test/FunctionalTests/Helpers.cs index 12e634cda156..57e0e30da5c6 100644 --- a/src/Middleware/StaticFiles/test/FunctionalTests/Helpers.cs +++ b/src/Middleware/StaticFiles/test/FunctionalTests/Helpers.cs @@ -3,15 +3,18 @@ using System.Linq; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.StaticFiles { public static class Helpers { - public static string GetAddress(IWebHost server) + public static string GetAddress(IHost server) { - return server.ServerFeatures.Get().Addresses.First(); + return server.Services.GetService().Features.Get().Addresses.First(); } } } diff --git a/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs b/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs index b4ca20cf0a5c..2808124c6c10 100644 --- a/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs @@ -18,6 +18,7 @@ using Microsoft.AspNetCore.Server.IntegrationTesting.Common; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging.Testing; using Xunit; @@ -28,85 +29,103 @@ public class StaticFileMiddlewareTests : LoggedTest [Fact] public async Task ReturnsNotFoundWithoutWwwroot() { - var builder = new WebHostBuilder() - .ConfigureServices(services => services.AddSingleton(LoggerFactory)) - .UseKestrel() - .Configure(app => app.UseStaticFiles()); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .ConfigureServices(services => services.AddSingleton(LoggerFactory)) + .UseKestrel() + .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) + .Configure(app => app.UseStaticFiles()); + }).Build(); + + await host.StartAsync(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var response = await client.GetAsync("TestDocument.txt"); + var response = await client.GetAsync("TestDocument.txt"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } + + await host.StopAsync(); } [Fact] public async Task Endpoint_PassesThrough() { - var builder = new WebHostBuilder() - .ConfigureServices(services => { services.AddSingleton(LoggerFactory); services.AddRouting(); }) - .UseKestrel() - .UseWebRoot(AppContext.BaseDirectory) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - // Routing first => static files noops - app.UseRouting(); - - app.Use(next => context => + webHostBuilder + .ConfigureServices(services => { services.AddSingleton(LoggerFactory); services.AddRouting(); }) + .UseKestrel() + .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) + .UseWebRoot(AppContext.BaseDirectory) + .Configure(app => { - // Assign an endpoint, this will make the default files noop. - context.SetEndpoint(new Endpoint((c) => + // Routing first => static files noops + app.UseRouting(); + + app.Use(next => context => { - return context.Response.WriteAsync("Hi from endpoint."); - }, - new EndpointMetadataCollection(), - "test")); + // Assign an endpoint, this will make the default files noop. + context.SetEndpoint(new Endpoint((c) => + { + return context.Response.WriteAsync("Hi from endpoint."); + }, + new EndpointMetadataCollection(), + "test")); - return next(context); - }); + return next(context); + }); + + app.UseStaticFiles(); - app.UseStaticFiles(); + app.UseEndpoints(endpoints => { }); + }); + }).Build(); - app.UseEndpoints(endpoints => {}); - }); + await host.StartAsync(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var response = await client.GetAsync("TestDocument.txt"); + var response = await client.GetAsync("TestDocument.txt"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Hi from endpoint.", await response.Content.ReadAsStringAsync()); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("Hi from endpoint.", await response.Content.ReadAsStringAsync()); } + + await host.StopAsync(); } [Fact] public async Task FoundFile_LastModifiedTrimsSeconds() { - var builder = new WebHostBuilder() - .ConfigureServices(services => services.AddSingleton(LoggerFactory)) - .UseKestrel() - .UseWebRoot(AppContext.BaseDirectory) - .Configure(app => app.UseStaticFiles()); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .ConfigureServices(services => services.AddSingleton(LoggerFactory)) + .UseKestrel() + .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) + .UseWebRoot(AppContext.BaseDirectory) + .Configure(app => app.UseStaticFiles()); + }).Build(); + + await host.StartAsync(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var last = File.GetLastWriteTimeUtc(Path.Combine(AppContext.BaseDirectory, "TestDocument.txt")); - var response = await client.GetAsync("TestDocument.txt"); + var last = File.GetLastWriteTimeUtc(Path.Combine(AppContext.BaseDirectory, "TestDocument.txt")); + var response = await client.GetAsync("TestDocument.txt"); - var trimmed = new DateTimeOffset(last.Year, last.Month, last.Day, last.Hour, last.Minute, last.Second, TimeSpan.Zero).ToUniversalTime(); + var trimmed = new DateTimeOffset(last.Year, last.Month, last.Day, last.Hour, last.Minute, last.Second, TimeSpan.Zero).ToUniversalTime(); - Assert.Equal(response.Content.Headers.LastModified.Value, trimmed); - } + Assert.Equal(response.Content.Headers.LastModified.Value, trimmed); } + + await host.StopAsync(); } [Theory] @@ -130,69 +149,80 @@ public async Task FoundFile_Served_Windows(string baseUrl, string baseDir, strin private async Task FoundFile_Served(string baseUrl, string baseDir, string requestUrl) { - var builder = new WebHostBuilder() - .ConfigureServices(services => services.AddSingleton(LoggerFactory)) - .UseKestrel() - .UseWebRoot(Path.Combine(AppContext.BaseDirectory, baseDir)) - .Configure(app => app.UseStaticFiles(new StaticFileOptions + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - RequestPath = new PathString(baseUrl), - })); + webHostBuilder + .ConfigureServices(services => services.AddSingleton(LoggerFactory)) + .UseKestrel() + .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) + .UseWebRoot(Path.Combine(AppContext.BaseDirectory, baseDir)) + .Configure(app => app.UseStaticFiles(new StaticFileOptions + { + RequestPath = new PathString(baseUrl), + })); + }).Build(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) - { - var hostingEnvironment = server.Services.GetService(); + await host.StartAsync(); - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var fileInfo = hostingEnvironment.WebRootFileProvider.GetFileInfo(Path.GetFileName(requestUrl)); - var response = await client.GetAsync(requestUrl); - var responseContent = await response.Content.ReadAsByteArrayAsync(); + var hostingEnvironment = host.Services.GetService(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); - Assert.True(response.Content.Headers.ContentLength == fileInfo.Length); - Assert.Equal(response.Content.Headers.ContentLength, responseContent.Length); + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) + { + var fileInfo = hostingEnvironment.WebRootFileProvider.GetFileInfo(Path.GetFileName(requestUrl)); + var response = await client.GetAsync(requestUrl); + var responseContent = await response.Content.ReadAsByteArrayAsync(); - using (var stream = fileInfo.CreateReadStream()) - { - var fileContents = new byte[stream.Length]; - stream.Read(fileContents, 0, (int)stream.Length); - Assert.True(responseContent.SequenceEqual(fileContents)); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); + Assert.True(response.Content.Headers.ContentLength == fileInfo.Length); + Assert.Equal(response.Content.Headers.ContentLength, responseContent.Length); + + using (var stream = fileInfo.CreateReadStream()) + { + var fileContents = new byte[stream.Length]; + stream.Read(fileContents, 0, (int)stream.Length); + Assert.True(responseContent.SequenceEqual(fileContents)); } } + + await host.StopAsync(); } [Theory] [MemberData(nameof(ExistingFiles))] public async Task HeadFile_HeadersButNotBodyServed(string baseUrl, string baseDir, string requestUrl) { - var builder = new WebHostBuilder() - .ConfigureServices(services => services.AddSingleton(LoggerFactory)) - .UseKestrel() - .UseWebRoot(Path.Combine(AppContext.BaseDirectory, baseDir)) - .Configure(app => app.UseStaticFiles(new StaticFileOptions + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - RequestPath = new PathString(baseUrl), - })); + webHostBuilder + .ConfigureServices(services => services.AddSingleton(LoggerFactory)) + .UseKestrel() + .UseWebRoot(Path.Combine(AppContext.BaseDirectory, baseDir)) + .Configure(app => app.UseStaticFiles(new StaticFileOptions + { + RequestPath = new PathString(baseUrl), + })); + }).Build(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) - { - var hostingEnvironment = server.Services.GetService(); + await host.StartAsync(); - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var fileInfo = hostingEnvironment.WebRootFileProvider.GetFileInfo(Path.GetFileName(requestUrl)); - var request = new HttpRequestMessage(HttpMethod.Head, requestUrl); - var response = await client.SendAsync(request); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); - Assert.True(response.Content.Headers.ContentLength == fileInfo.Length); - Assert.Empty((await response.Content.ReadAsByteArrayAsync())); - } + var hostingEnvironment = host.Services.GetService(); + + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) + { + var fileInfo = hostingEnvironment.WebRootFileProvider.GetFileInfo(Path.GetFileName(requestUrl)); + var request = new HttpRequestMessage(HttpMethod.Head, requestUrl); + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); + Assert.True(response.Content.Headers.ContentLength == fileInfo.Length); + Assert.Empty((await response.Content.ReadAsByteArrayAsync())); } + + await host.StopAsync(); } public static IEnumerable ExistingFiles => new[] @@ -226,51 +256,57 @@ private async Task ClientDisconnect_NoWriteExceptionThrown(ServerType serverType var requestCancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var responseComplete = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); Exception exception = null; - var builder = new WebHostBuilder() - .ConfigureServices(services => services.AddSingleton(LoggerFactory)) - .UseWebRoot(Path.Combine(AppContext.BaseDirectory)) - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (context, next) => + webHostBuilder + .ConfigureServices(services => services.AddSingleton(LoggerFactory)) + .UseWebRoot(Path.Combine(AppContext.BaseDirectory)) + .Configure(app => { - try - { - requestReceived.SetResult(0); - await requestCancelled.Task.TimeoutAfter(interval); - Assert.True(context.RequestAborted.WaitHandle.WaitOne(interval), "not aborted"); - await next(); - } - catch (Exception ex) + app.Use(async (context, next) => { - exception = ex; - } - responseComplete.SetResult(0); - }); - app.UseStaticFiles(); - }); + try + { + requestReceived.SetResult(0); + await requestCancelled.Task.TimeoutAfter(interval); + Assert.True(context.RequestAborted.WaitHandle.WaitOne(interval), "not aborted"); + await next(); + } + catch (Exception ex) + { + exception = ex; + } + responseComplete.SetResult(0); + }); + app.UseStaticFiles(); + }) + .UseUrls(TestUrlHelper.GetTestUrl(serverType)); + + if (serverType == ServerType.HttpSys) + { + webHostBuilder.UseHttpSys(); + } + else if (serverType == ServerType.Kestrel) + { + webHostBuilder.UseKestrel(); + } + }).Build(); - if (serverType == ServerType.HttpSys) - { - builder.UseHttpSys(); - } - else if (serverType == ServerType.Kestrel) - { - builder.UseKestrel(); - } + await host.StartAsync(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(serverType))) - { - // We don't use HttpClient here because it's disconnect behavior varies across platforms. - var socket = SendSocketRequestAsync(Helpers.GetAddress(server), "/TestDocument1MB.txt"); - await requestReceived.Task.TimeoutAfter(interval); + // We don't use HttpClient here because it's disconnect behavior varies across platforms. + var socket = SendSocketRequestAsync(Helpers.GetAddress(host), "/TestDocument1MB.txt"); + await requestReceived.Task.TimeoutAfter(interval); - socket.LingerState = new LingerOption(true, 0); - socket.Dispose(); - requestCancelled.SetResult(0); + socket.LingerState = new LingerOption(true, 0); + socket.Dispose(); + requestCancelled.SetResult(0); - await responseComplete.Task.TimeoutAfter(interval); - Assert.Null(exception); - } + await responseComplete.Task.TimeoutAfter(interval); + Assert.Null(exception); + + await host.StopAsync(); } private Socket SendSocketRequestAsync(string address, string path, string method = "GET") diff --git a/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs b/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs index a91ac3efce0c..e7c9487b8422 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs @@ -16,6 +16,7 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.FileProviders; +using Microsoft.Extensions.Hosting; using Moq; using Xunit; @@ -26,14 +27,24 @@ public class StaticFileMiddlewareTests [Fact] public async Task ReturnsNotFoundWithoutWwwroot() { - var builder = new WebHostBuilder() - .Configure(app => app.UseStaticFiles()); - var server = new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => app.UseStaticFiles()); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/ranges.txt"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Null(response.Headers.ETag); + + await host.StopAsync(); } [ConditionalFact] @@ -47,15 +58,25 @@ public async Task ReturnsNotFoundForBrokenSymlink() try { - var builder = new WebHostBuilder() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() .Configure(app => app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true })) .UseWebRoot(AppContext.BaseDirectory); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(Path.GetFileName(badLink)); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Null(response.Headers.ETag); + + await host.StopAsync(); } finally { @@ -70,23 +91,33 @@ public async Task ReturnsNotFoundIfSendFileThrows() mockSendFile.Setup(m => m.SendFileAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ThrowsAsync(new FileNotFoundException()); mockSendFile.Setup(m => m.Stream).Returns(Stream.Null); - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (ctx, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - ctx.Features.Set(mockSendFile.Object); - await next(); - }); - app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true }); - }) - .UseWebRoot(AppContext.BaseDirectory); - var server = new TestServer(builder); + app.Use(async (ctx, next) => + { + ctx.Features.Set(mockSendFile.Object); + await next(); + }); + app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true }); + }) + .UseWebRoot(AppContext.BaseDirectory); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("TestDocument.txt"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Null(response.Headers.ETag); + + await host.StopAsync(); } [Fact] diff --git a/src/Middleware/StaticFiles/test/UnitTests/StaticFilesTestServer.cs b/src/Middleware/StaticFiles/test/UnitTests/StaticFilesTestServer.cs index d4bdf06eed76..f43c1b448fdb 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/StaticFilesTestServer.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/StaticFilesTestServer.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.StaticFiles { @@ -23,11 +24,18 @@ public static TestServer Create(Action configureApp, Action new KeyValuePair("webroot", ".") }) .Build(); - var builder = new WebHostBuilder() - .UseConfiguration(configuration) - .Configure(configureApp) - .ConfigureServices(configureServices ?? defaultConfigureServices); - return new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseConfiguration(configuration) + .Configure(configureApp) + .ConfigureServices(configureServices ?? defaultConfigureServices); + }).Build(); + + host.Start(); + return host.GetTestServer(); } } -} \ No newline at end of file +} From ecf27eb4c3f75775d5370b98dd0b586aae834a58 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Thu, 2 Jul 2020 11:10:20 -0700 Subject: [PATCH 18/20] WebSockets --- .../WebSockets/samples/EchoApp/Program.cs | 22 ++-- .../AutobahnTestApp/Program.cs | 105 +++++++++--------- .../test/UnitTests/IHostPortExtensions.cs | 33 ++++++ .../test/UnitTests/IWebHostPortExtensions.cs | 30 ----- .../test/UnitTests/KestrelWebSocketHelpers.cs | 22 ++-- 5 files changed, 113 insertions(+), 99 deletions(-) create mode 100644 src/Middleware/WebSockets/test/UnitTests/IHostPortExtensions.cs delete mode 100644 src/Middleware/WebSockets/test/UnitTests/IWebHostPortExtensions.cs diff --git a/src/Middleware/WebSockets/samples/EchoApp/Program.cs b/src/Middleware/WebSockets/samples/EchoApp/Program.cs index 07dd98e134be..0723252c76e7 100644 --- a/src/Middleware/WebSockets/samples/EchoApp/Program.cs +++ b/src/Middleware/WebSockets/samples/EchoApp/Program.cs @@ -1,24 +1,26 @@ -using System; -using System.Collections.Generic; using System.IO; -using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; namespace EchoApp { public class Program { - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/Program.cs b/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/Program.cs index ddd340a6e003..c65ab23ac2dc 100644 --- a/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/Program.cs +++ b/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/Program.cs @@ -1,76 +1,81 @@ using System; using System.IO; using System.Net; -using System.Runtime.Loader; +using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace AutobahnTestApp { public class Program { - public static void Main(string[] args) + public static Task Main(string[] args) { var scenarioName = "Unknown"; var config = new ConfigurationBuilder() .AddCommandLine(args) .Build(); - var builder = new WebHostBuilder() - .ConfigureLogging(loggingBuilder => loggingBuilder.AddConsole()) - .UseConfiguration(config) - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseStartup(); - - if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal)) - { - scenarioName = "HttpSysServer"; - Console.WriteLine("Using HttpSys server"); - builder.UseHttpSys(); - } - else if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PORT"))) - { - // ANCM is hosting the process. - // The port will not yet be configured at this point, but will also not require HTTPS. - scenarioName = "AspNetCoreModule"; - Console.WriteLine("Detected ANCM, using Kestrel"); - builder.UseKestrel(); - } - else - { - // Also check "server.urls" for back-compat. - var urls = builder.GetSetting(WebHostDefaults.ServerUrlsKey) ?? builder.GetSetting("server.urls"); - builder.UseSetting(WebHostDefaults.ServerUrlsKey, string.Empty); - - Console.WriteLine($"Using Kestrel, URL: {urls}"); - - if (urls.Contains(";")) + var builder = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - throw new NotSupportedException("This test app does not support multiple endpoints."); - } + webHostBuilder + .ConfigureLogging(loggingBuilder => loggingBuilder.AddConsole()) + .UseConfiguration(config) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseStartup(); - var uri = new Uri(urls); - - builder.UseKestrel(options => - { - options.Listen(IPAddress.Loopback, uri.Port, listenOptions => + if (string.Equals(webHostBuilder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal)) { - if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) + scenarioName = "HttpSysServer"; + Console.WriteLine("Using HttpSys server"); + webHostBuilder.UseHttpSys(); + } + else if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PORT"))) + { + // ANCM is hosting the process. + // The port will not yet be configured at this point, but will also not require HTTPS. + scenarioName = "AspNetCoreModule"; + Console.WriteLine("Detected ANCM, using Kestrel"); + webHostBuilder.UseKestrel(); + } + else + { + // Also check "server.urls" for back-compat. + var urls = webHostBuilder.GetSetting(WebHostDefaults.ServerUrlsKey) ?? webHostBuilder.GetSetting("server.urls"); + webHostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, string.Empty); + + Console.WriteLine($"Using Kestrel, URL: {urls}"); + + if (urls.Contains(";")) { - scenarioName = "Kestrel(SSL)"; - var certPath = Path.Combine(AppContext.BaseDirectory, "TestResources", "testCert.pfx"); - Console.WriteLine($"Using SSL with certificate: {certPath}"); - listenOptions.UseHttps(certPath, "testPassword"); + throw new NotSupportedException("This test app does not support multiple endpoints."); } - else + + var uri = new Uri(urls); + + webHostBuilder.UseKestrel(options => { - scenarioName = "Kestrel(NonSSL)"; - } - }); + options.Listen(IPAddress.Loopback, uri.Port, listenOptions => + { + if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) + { + scenarioName = "Kestrel(SSL)"; + var certPath = Path.Combine(AppContext.BaseDirectory, "TestResources", "testCert.pfx"); + Console.WriteLine($"Using SSL with certificate: {certPath}"); + listenOptions.UseHttps(certPath, "testPassword"); + } + else + { + scenarioName = "Kestrel(NonSSL)"; + } + }); + }); + } }); - } var host = builder.Build(); @@ -80,7 +85,7 @@ public static void Main(string[] args) }; Console.WriteLine($"Starting Server for Scenario: {scenarioName}"); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/WebSockets/test/UnitTests/IHostPortExtensions.cs b/src/Middleware/WebSockets/test/UnitTests/IHostPortExtensions.cs new file mode 100644 index 000000000000..3cea6f8e92f4 --- /dev/null +++ b/src/Middleware/WebSockets/test/UnitTests/IHostPortExtensions.cs @@ -0,0 +1,33 @@ +// 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; +using System.Collections.Generic; +using System.Linq; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Microsoft.AspNetCore.Hosting +{ + public static class IHostPortExtensions + { + public static int GetPort(this IHost host) + { + return host.GetPorts().First(); + } + + public static IEnumerable GetPorts(this IHost host) + { + return host.GetUris() + .Select(u => u.Port); + } + + public static IEnumerable GetUris(this IHost host) + { + return host.Services.GetService().Features.Get().Addresses + .Select(a => new Uri(a)); + } + } +} diff --git a/src/Middleware/WebSockets/test/UnitTests/IWebHostPortExtensions.cs b/src/Middleware/WebSockets/test/UnitTests/IWebHostPortExtensions.cs deleted file mode 100644 index d3b53681f40b..000000000000 --- a/src/Middleware/WebSockets/test/UnitTests/IWebHostPortExtensions.cs +++ /dev/null @@ -1,30 +0,0 @@ -// 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; -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Hosting.Server.Features; - -namespace Microsoft.AspNetCore.Hosting -{ - public static class IWebHostPortExtensions - { - public static int GetPort(this IWebHost host) - { - return host.GetPorts().First(); - } - - public static IEnumerable GetPorts(this IWebHost host) - { - return host.GetUris() - .Select(u => u.Port); - } - - public static IEnumerable GetUris(this IWebHost host) - { - return host.ServerFeatures.Get().Addresses - .Select(a => new Uri(a)); - } - } -} \ No newline at end of file diff --git a/src/Middleware/WebSockets/test/UnitTests/KestrelWebSocketHelpers.cs b/src/Middleware/WebSockets/test/UnitTests/KestrelWebSocketHelpers.cs index 8f24cb92e7dd..1d591e8e43b6 100644 --- a/src/Middleware/WebSockets/test/UnitTests/KestrelWebSocketHelpers.cs +++ b/src/Middleware/WebSockets/test/UnitTests/KestrelWebSocketHelpers.cs @@ -9,6 +9,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.WebSockets.Test { @@ -48,16 +49,19 @@ public static IDisposable CreateServer(ILoggerFactory loggerFactory, out int por var config = configBuilder.Build(); config["server.urls"] = $"http://127.0.0.1:0"; - var host = new WebHostBuilder() - .ConfigureServices(s => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - s.AddWebSockets(configure); - s.AddSingleton(loggerFactory); - }) - .UseConfiguration(config) - .UseKestrel() - .Configure(startup) - .Build(); + webHostBuilder + .ConfigureServices(s => + { + s.AddWebSockets(configure); + s.AddSingleton(loggerFactory); + }) + .UseConfiguration(config) + .UseKestrel() + .Configure(startup); + }).Build(); host.Start(); port = host.GetPort(); From fdf8be62f215a77b4b1a91a2175a549ce61d5443 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Mon, 6 Jul 2020 16:06:32 -0700 Subject: [PATCH 19/20] dispose --- .../test/UnitTests/CorsMiddlewareTests.cs | 20 ++--- .../DatabaseErrorPageMiddlewareTest.cs | 35 +++++---- .../MigrationsEndPointMiddlewareTest.cs | 12 +-- .../test/FunctionalTests/TestFixture.cs | 8 +- .../DeveloperExceptionPageMiddlewareTest.cs | 14 ++-- .../test/UnitTests/ExceptionHandlerTest.cs | 16 ++-- .../UnitTests/StatusCodeMiddlewareTest.cs | 6 +- .../test/HeaderPropagationIntegrationTest.cs | 10 +-- ...CheckEndpointRouteBuilderExtensionsTest.cs | 6 +- .../HealthCheckMiddlewareSampleTest.cs | 8 +- .../UnitTests/HealthCheckMiddlewareTests.cs | 52 ++++++------- .../test/HostFilteringMiddlewareTests.cs | 12 +-- .../test/CertificateForwardingTest.cs | 10 +-- .../test/ForwardedHeadersMiddlewareTest.cs | 48 ++++++------ .../test/HttpMethodOverrideMiddlewareTest.cs | 12 +-- .../HttpsPolicy/test/HstsMiddlewareTests.cs | 16 ++-- .../HttpsPolicy/test/HttpsPolicyTests.cs | 2 +- .../test/HttpsRedirectionMiddlewareTests.cs | 18 ++--- .../RouteDataRequestCultureProviderTest.cs | 6 +- .../FunctionalTests/LocalizationSampleTest.cs | 2 +- .../test/FunctionalTests/LocalizationTest.cs | 2 +- ...anguageHeaderRequestCultureProviderTest.cs | 8 +- .../CookieRequestCultureProviderTest.cs | 10 +-- .../CustomRequestCultureProviderTest.cs | 2 +- .../QueryStringRequestCultureProviderTest.cs | 16 ++-- .../test/MiddlewareAnalysisTests.cs | 2 +- .../test/ResponseCachingTests.cs | 74 +++++++++---------- .../test/ResponseCompressionMiddlewareTest.cs | 32 ++++---- .../ModRewriteMiddlewareTest.cs | 34 ++++----- .../test/IISUrlRewrite/MiddleWareTests.cs | 40 +++++----- .../Rewrite/test/MiddlewareTests.cs | 42 +++++------ src/Middleware/Session/test/SessionTests.cs | 42 +++++------ .../FunctionalTests/FallbackStaticFileTest.cs | 4 +- .../StaticFileMiddlewareTests.cs | 12 +-- .../test/UnitTests/CacheHeaderTests.cs | 63 ++++++++++------ .../UnitTests/DefaultFilesMiddlewareTests.cs | 21 ++++-- .../DirectoryBrowserMiddlewareTests.cs | 37 ++++++---- .../test/UnitTests/RangeHeaderTests.cs | 70 ++++++++++++------ .../UnitTests/StaticFileMiddlewareTests.cs | 27 ++++--- .../test/UnitTests/StaticFilesTestServer.cs | 7 +- 40 files changed, 468 insertions(+), 390 deletions(-) diff --git a/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs b/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs index 3e9db89da246..c6849f236193 100644 --- a/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs +++ b/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs @@ -28,7 +28,7 @@ public class CorsMiddlewareTests public async Task CorsRequest_MatchesPolicy_OnCaseInsensitiveAccessControlRequestMethod(string accessControlRequestMethod) { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -70,7 +70,7 @@ public async Task CorsRequest_MatchesPolicy_OnCaseInsensitiveAccessControlReques public async Task CorsRequest_MatchPolicy_SetsResponseHeaders() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -121,7 +121,7 @@ public async Task PreFlight_MatchesPolicy_OnCaseInsensitiveOptionsMethod(string policy.Origins.Add(OriginUrl); policy.Methods.Add("PUT"); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -172,7 +172,7 @@ public async Task PreFlight_MatchesPolicy_SetsResponseHeaders() policy.Headers.Add("Header1"); policy.ExposedHeaders.Add("AllowedHeader"); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -239,7 +239,7 @@ public async Task PreFlight_WithCredentialsAllowed_ReflectsRequestHeaders() .AllowCredentials() .Build(); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -306,7 +306,7 @@ public async Task PreFlight_WithCredentialsAllowed_ReflectsRequestHeaders() public async Task PreFlightRequest_DoesNotMatchPolicy_SetsResponseHeadersAndReturnsNoContent() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -349,7 +349,7 @@ public async Task PreFlightRequest_DoesNotMatchPolicy_SetsResponseHeadersAndRetu public async Task CorsRequest_DoesNotMatchPolicy_DoesNotSetHeaders() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -451,7 +451,7 @@ public async Task DoesNotSetHeaders_ForNoPolicy() public async Task PreFlight_MatchesDefaultPolicy_SetsResponseHeaders() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -526,7 +526,7 @@ public async Task PreFlight_MatchesDefaultPolicy_SetsResponseHeaders() public async Task CorsRequest_SetsResponseHeaders() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -588,7 +588,7 @@ public async Task CorsRequest_SetsResponseHeader_IfExceptionHandlerClearsRespons { // Arrange var exceptionSeen = true; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs index 12bee7e91e29..ee157a8168d1 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs @@ -28,7 +28,7 @@ public class DatabaseErrorPageMiddlewareTest [Fact] public async Task Successful_requests_pass_thru() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -65,7 +65,7 @@ public virtual async Task Invoke(HttpContext context) [Fact] public async Task Non_database_exceptions_pass_thru() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -105,7 +105,8 @@ public async Task Existing_database_not_using_migrations_exception_passes_thru() { using (var database = SqlTestStore.CreateScratch()) { - using TestServer server = await SetupTestServer(database); + using var host = await SetupServer(database); + using var server = host.GetTestServer(); var ex = await Assert.ThrowsAsync(async () => await server.CreateClient().GetAsync("http://localhost/")); @@ -137,7 +138,8 @@ public async Task Error_page_displayed_no_migrations() { using (var database = SqlTestStore.CreateScratch()) { - using TestServer server = await SetupTestServer(database); + using var host = await SetupServer(database); + using var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -169,7 +171,7 @@ public async Task No_exception_on_diagnostic_event_received_when_null_state() { using (var database = SqlTestStore.CreateScratch()) { - using (var server = await SetupTestServer(database)) + using (var server = await SetupServer(database)) { using (var db = server.Services.GetService()) { @@ -195,7 +197,8 @@ public async Task Error_page_displayed_pending_migrations() { using (var database = SqlTestStore.CreateScratch()) { - using TestServer server = await SetupTestServer(database); + using var host = await SetupServer(database); + using var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -231,7 +234,8 @@ public async Task Error_page_displayed_pending_model_changes() { using (var database = SqlTestStore.CreateScratch()) { - using TestServer server = await SetupTestServer(database); + using var host = await SetupServer(database); + using var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -268,7 +272,8 @@ public async Task Error_page_then_apply_migrations() { using (var database = SqlTestStore.CreateScratch()) { - using TestServer server = await SetupTestServer(database); + using var host = await SetupServer(database); + using var server = host.GetTestServer(); var client = server.CreateClient(); var expectedMigrationsEndpoint = "/ApplyDatabaseMigrations"; @@ -325,7 +330,7 @@ public async Task Customize_migrations_end_point() using (var database = SqlTestStore.CreateScratch()) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -368,7 +373,7 @@ public async Task Pass_thru_when_context_not_in_services() { var logProvider = new TestLoggerProvider(); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -434,7 +439,8 @@ public async Task Pass_thru_when_exception_in_logic() { var logProvider = new TestLoggerProvider(); - var server = await SetupTestServer(database, logProvider); + using var host = await SetupServer(database, logProvider); + using var server = host.GetTestServer(); try { @@ -473,7 +479,8 @@ public async Task Error_page_displayed_when_exception_wrapped() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = await SetupTestServer(database); + using var host = await SetupServer(database); + using var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -504,7 +511,7 @@ public virtual Task Invoke(HttpContext context) } } - private static async Task SetupTestServer(SqlTestStore database, ILoggerProvider logProvider = null) + private static async Task SetupServer(SqlTestStore database, ILoggerProvider logProvider = null) where TContext : DbContext { var host = new HostBuilder() @@ -533,7 +540,7 @@ private static async Task SetupTestServer(Sql await host.StartAsync(); - return host.GetTestServer(); + return host; } private static UrlEncoder _urlEncoder = UrlEncoder.Default; diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs index 79ee7b96d648..138519e60fa6 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs @@ -28,7 +28,7 @@ public class MigrationsEndPointMiddlewareTest [Fact] public async Task Non_migration_requests_pass_thru() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -87,7 +87,7 @@ private async Task Migration_request(bool useCustomPath) var path = useCustomPath ? new PathString("/EndPoints/ApplyMyMigrations") : MigrationsEndPointOptions.DefaultPath; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -150,7 +150,7 @@ private async Task Migration_request(bool useCustomPath) [Fact] public async Task Context_type_not_specified() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -180,7 +180,7 @@ public async Task Context_type_not_specified() [Fact] public async Task Invalid_context_type_specified() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -214,7 +214,7 @@ public async Task Invalid_context_type_specified() [Fact] public async Task Context_not_registered_in_services() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -249,7 +249,7 @@ public async Task Exception_while_applying_migrations() { using (var database = SqlTestStore.CreateScratch()) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Diagnostics/test/FunctionalTests/TestFixture.cs b/src/Middleware/Diagnostics/test/FunctionalTests/TestFixture.cs index b628c26b023e..e24d1bc41a5e 100644 --- a/src/Middleware/Diagnostics/test/FunctionalTests/TestFixture.cs +++ b/src/Middleware/Diagnostics/test/FunctionalTests/TestFixture.cs @@ -13,6 +13,7 @@ namespace Microsoft.AspNetCore.Diagnostics.FunctionalTests public class TestFixture : IDisposable { private readonly TestServer _server; + private readonly IHost _host; public TestFixture() { @@ -21,7 +22,7 @@ public TestFixture() // (DefaultRequestCulture) is consistent regardless of system configuration or personal preferences. using (new CultureReplacer()) { - var host = new HostBuilder() + _host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -29,8 +30,8 @@ public TestFixture() .UseStartup(typeof(TStartup)); }).Build(); - host.Start(); - _server = host.GetTestServer(); + _host.Start(); + _server = _host.GetTestServer(); } Client = _server.CreateClient(); @@ -43,6 +44,7 @@ public void Dispose() { Client.Dispose(); _server.Dispose(); + _host.Dispose(); } } } diff --git a/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs b/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs index d630fbe4e349..f2ae02fb4a5f 100644 --- a/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs +++ b/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs @@ -23,7 +23,7 @@ public async Task UnhandledErrorsWriteToDiagnosticWhenUsingExceptionPage() { // Arrange DiagnosticListener diagnosticListener = null; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -61,7 +61,7 @@ public async Task UnhandledErrorsWriteToDiagnosticWhenUsingExceptionPage() public async Task ErrorPageWithAcceptHeaderForHtmlReturnsHtml() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -98,7 +98,7 @@ public async Task ErrorPageWithAcceptHeaderForHtmlReturnsHtml() public async Task ErrorPageWithoutAcceptHeaderForHtmlReturnsPlainText() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -133,7 +133,7 @@ public async Task ErrorPageWithoutAcceptHeaderForHtmlReturnsPlainText() public async Task ExceptionPageFiltersAreApplied() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -169,7 +169,7 @@ public async Task ExceptionPageFiltersAreApplied() public async Task ExceptionFilterCallingNextWorks() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -207,7 +207,7 @@ public async Task ExceptionFilterCallingNextWorks() public async Task ExceptionPageFiltersAreAppliedInOrder() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -302,7 +302,7 @@ public async Task NullInfoInCompilationException_ShouldNotThrowExceptionGenerati { // Arrange DiagnosticListener diagnosticListener = null; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs b/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs index 0a33c78e2b1f..ca794ce18bec 100644 --- a/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs +++ b/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs @@ -29,7 +29,7 @@ public class ExceptionHandlerTest [InlineData(HttpStatusCode.InternalServerError)] public async Task OnlyHandles_UnhandledExceptions(HttpStatusCode expectedStatusCode) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -71,7 +71,7 @@ public async Task OnlyHandles_UnhandledExceptions(HttpStatusCode expectedStatusC [Fact] public async Task DoesNotHandle_UnhandledExceptions_WhenResponseAlreadyStarted() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -129,7 +129,7 @@ public async Task DoesNotHandle_UnhandledExceptions_WhenResponseAlreadyStarted() public async Task ClearsResponseBuffer_BeforeRequestIsReexecuted() { var expectedResponseBody = "New response body"; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -209,7 +209,7 @@ public async Task ClearsCacheHeaders_SetByReexecutionPathHandlers() { var expiresTime = DateTime.UtcNow.AddDays(5).ToString("R"); var expectedResponseBody = "Handled error in a custom way."; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -267,7 +267,7 @@ public async Task DoesNotModifyCacheHeaders_WhenNoExceptionIsThrown() { var expiresTime = DateTime.UtcNow.AddDays(10).ToString("R"); var expectedResponseBody = "Hello world!"; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -326,7 +326,7 @@ public async Task DoesNotModifyCacheHeaders_WhenNoExceptionIsThrown() public async Task DoesNotClearCacheHeaders_WhenResponseHasAlreadyStarted() { var expiresTime = DateTime.UtcNow.AddDays(10).ToString("R"); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -405,7 +405,7 @@ public async Task HandledErrorsWriteToDiagnosticWhenUsingExceptionHandler() // Arrange DiagnosticListener diagnosticListener = null; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -460,7 +460,7 @@ public void UsingExceptionHandler_ThrowsAnException_WhenExceptionHandlingPathNot // Arrange DiagnosticListener diagnosticListener = null; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs b/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs index 6bca5a112f2c..16526bddad76 100644 --- a/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs +++ b/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs @@ -22,7 +22,7 @@ public async Task Redirect_StatusPage() { var expectedStatusCode = 432; var destination = "/location"; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -78,7 +78,7 @@ public async Task Reexecute_CanRetrieveInformationAboutOriginalRequest() { var expectedStatusCode = 432; var destination = "/location"; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -141,7 +141,7 @@ public async Task Reexecute_ClearsEndpointAndRouteData() { var expectedStatusCode = 432; var destination = "/location"; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/HeaderPropagation/test/HeaderPropagationIntegrationTest.cs b/src/Middleware/HeaderPropagation/test/HeaderPropagationIntegrationTest.cs index 6809470f582e..5fd20bec26b8 100644 --- a/src/Middleware/HeaderPropagation/test/HeaderPropagationIntegrationTest.cs +++ b/src/Middleware/HeaderPropagation/test/HeaderPropagationIntegrationTest.cs @@ -25,7 +25,7 @@ public async Task HeaderPropagation_WithoutMiddleware_Throws() // Arrange Exception captured = null; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -106,7 +106,7 @@ public async Task HeaderInRequest_AddCorrectValue() { // Arrange var handler = new SimpleHandler(); - var host = await CreateHost(c => + using var host = await CreateHost(c => c.Headers.Add("in", "out"), handler); var server = host.GetTestServer(); @@ -131,7 +131,7 @@ public async Task MultipleHeaders_HeadersInRequest_AddAllHeaders() { // Arrange var handler = new SimpleHandler(); - var host = await CreateHost(c => + using var host = await CreateHost(c => { c.Headers.Add("first"); c.Headers.Add("second"); @@ -160,7 +160,7 @@ public async Task MultipleHeaders_HeadersInRequest_AddAllHeaders() [Fact] public async Task Builder_UseHeaderPropagation_Without_AddHeaderPropagation_Throws() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -182,7 +182,7 @@ public async Task HeaderInRequest_OverrideHeaderPerClient_AddCorrectValue() { // Arrange var handler = new SimpleHandler(); - var host = await CreateHost( + using var host = await CreateHost( c => c.Headers.Add("in", "out"), handler, c => c.Headers.Add("out", "different")); diff --git a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs index 7df7443b2acc..ff9db28925fe 100644 --- a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs +++ b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs @@ -22,7 +22,7 @@ public class HealthCheckEndpointRouteBuilderExtensionsTest [Fact] public void ThrowFriendlyErrorWhenServicesNotRegistered() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -54,7 +54,7 @@ public void ThrowFriendlyErrorWhenServicesNotRegistered() public async Task MapHealthChecks_ReturnsOk() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -94,7 +94,7 @@ public async Task MapHealthChecks_ReturnsOk() public async Task MapHealthChecks_WithOptions_ReturnsOk() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs index 657abce13746..4546e0b80342 100644 --- a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs +++ b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs @@ -15,7 +15,7 @@ public class HealthCheckMiddlewareSampleTest [Fact] public async Task BasicStartup() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -39,7 +39,7 @@ public async Task BasicStartup() [Fact] public async Task CustomWriterStartup() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -64,7 +64,7 @@ public async Task CustomWriterStartup() [Fact] public async Task LivenessProbeStartup_Liveness() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -88,7 +88,7 @@ public async Task LivenessProbeStartup_Liveness() [Fact] public async Task LivenessProbeStartup_Readiness() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs index d2235447243b..a6e17b9ddde3 100644 --- a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs +++ b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs @@ -23,7 +23,7 @@ public class HealthCheckMiddlewareTests [Fact] public void ThrowFriendlyErrorWhenServicesNotRegistered() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -46,7 +46,7 @@ public void ThrowFriendlyErrorWhenServicesNotRegistered() [Fact] // Matches based on '.Map' public async Task IgnoresRequestThatDoesNotMatchPath() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -75,7 +75,7 @@ public async Task IgnoresRequestThatDoesNotMatchPath() [Fact] // Matches based on '.Map' public async Task MatchIsCaseInsensitive() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -104,7 +104,7 @@ public async Task MatchIsCaseInsensitive() [Fact] public async Task ReturnsPlainTextStatus() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -136,7 +136,7 @@ public async Task ReturnsPlainTextStatus() [Fact] public async Task StatusCodeIs200IfNoChecks() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -168,7 +168,7 @@ public async Task StatusCodeIs200IfNoChecks() [Fact] public async Task StatusCodeIs200IfAllChecksHealthy() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -203,7 +203,7 @@ public async Task StatusCodeIs200IfAllChecksHealthy() [Fact] public async Task StatusCodeIs200IfCheckIsDegraded() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -238,7 +238,7 @@ public async Task StatusCodeIs200IfCheckIsDegraded() [Fact] public async Task StatusCodeIs503IfCheckIsUnhealthy() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -273,7 +273,7 @@ public async Task StatusCodeIs503IfCheckIsUnhealthy() [Fact] public async Task StatusCodeIs503IfCheckHasUnhandledException() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -313,7 +313,7 @@ public async Task CanUseCustomWriter() status = "Unhealthy", }); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -357,7 +357,7 @@ public async Task CanUseCustomWriter() [Fact] public async Task NoResponseWriterReturnsEmptyBody() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -394,7 +394,7 @@ public async Task NoResponseWriterReturnsEmptyBody() [Fact] public async Task CanSetCustomStatusCodes() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -431,7 +431,7 @@ public async Task CanSetCustomStatusCodes() [Fact] public async Task SetsCacheHeaders() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -465,7 +465,7 @@ public async Task SetsCacheHeaders() [Fact] public async Task CanSuppressCacheHeaders() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -502,7 +502,7 @@ public async Task CanSuppressCacheHeaders() [Fact] public async Task CanFilterChecks() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -541,7 +541,7 @@ public async Task CanFilterChecks() [Fact] public async Task CanListenWithoutPath_AcceptsRequest() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -573,7 +573,7 @@ public async Task CanListenWithoutPath_AcceptsRequest() [Fact] public async Task CanListenWithPath_AcceptsRequestWithExtraSlash() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -603,7 +603,7 @@ public async Task CanListenWithPath_AcceptsRequestWithExtraSlash() [Fact] public async Task CanListenWithPath_AcceptsRequestWithCaseInsensitiveMatch() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -635,7 +635,7 @@ public async Task CanListenWithPath_AcceptsRequestWithCaseInsensitiveMatch() [Fact] public async Task CanListenWithPath_RejectsRequestWithExtraSegments() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -666,7 +666,7 @@ public async Task CanListenWithPath_RejectsRequestWithExtraSegments() [Fact] public async Task CanListenWithPath_MultipleMiddleware_LeastSpecificFirst() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -705,7 +705,7 @@ public async Task CanListenWithPath_MultipleMiddleware_LeastSpecificFirst() [Fact] public async Task CanListenWithPath_MultipleMiddleware_MostSpecificFirst() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -743,7 +743,7 @@ public async Task CanListenWithPath_MultipleMiddleware_MostSpecificFirst() [Fact] public async Task CanListenOnPort_AcceptsRequest_OnSpecifiedPort() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -783,7 +783,7 @@ public async Task CanListenOnPort_AcceptsRequest_OnSpecifiedPort() [Fact] public async Task CanListenOnPortWithoutPath_AcceptsRequest_OnSpecifiedPort() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -823,7 +823,7 @@ public async Task CanListenOnPortWithoutPath_AcceptsRequest_OnSpecifiedPort() [Fact] public async Task CanListenOnPort_RejectsRequest_OnOtherPort() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -861,7 +861,7 @@ public async Task CanListenOnPort_RejectsRequest_OnOtherPort() [Fact] public async Task CanListenOnPort_MultipleMiddleware() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -907,7 +907,7 @@ public async Task CanListenOnPort_MultipleMiddleware() [Fact] public async Task CanListenOnPort_MultipleMiddleware_DifferentPorts() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs b/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs index 8e6f9e2480fc..82b74a928d77 100644 --- a/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs +++ b/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs @@ -22,7 +22,7 @@ public class HostFilteringMiddlewareTests [Fact] public async Task MissingConfigThrows() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -45,7 +45,7 @@ public async Task MissingConfigThrows() [InlineData(false, 400)] public async Task AllowsMissingHost(bool allowed, int status) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -88,7 +88,7 @@ public async Task AllowsMissingHost(bool allowed, int status) [InlineData(false, 400)] public async Task AllowsEmptyHost(bool allowed, int status) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -146,7 +146,7 @@ public async Task AllowsEmptyHost(bool allowed, int status) [InlineData("[::1]:80", "[::1]")] public async Task AllowsSpecifiedHost(string hosturl, string allowedHost) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -200,7 +200,7 @@ public async Task AllowsSpecifiedHost(string hosturl, string allowedHost) [InlineData("[::1:80", "[::1]")] public async Task RejectsMismatchedHosts(string hosturl, string allowedHost) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -242,7 +242,7 @@ public async Task SupportsDynamicOptionsReload() config["AllowedHosts"] = "localhost"; var currentHost = "otherHost"; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs b/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs index 717510e7fa54..150f82f2b644 100644 --- a/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs +++ b/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs @@ -43,7 +43,7 @@ public void VerifySettingEmptyHeaderOptionThrows() [Fact] public async Task VerifyHeaderIsUsedIfNoCertificateAlreadySet() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -83,7 +83,7 @@ public async Task VerifyHeaderIsUsedIfNoCertificateAlreadySet() [Fact] public async Task VerifyHeaderOverridesCertificateEvenAlreadySet() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -124,7 +124,7 @@ public async Task VerifyHeaderOverridesCertificateEvenAlreadySet() [Fact] public async Task VerifySettingTheAzureHeaderOnTheForwarderOptionsWorks() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -164,7 +164,7 @@ public async Task VerifySettingTheAzureHeaderOnTheForwarderOptionsWorks() [Fact] public async Task VerifyACustomHeaderFailsIfTheHeaderIsNotPresent() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -204,7 +204,7 @@ public async Task VerifyACustomHeaderFailsIfTheHeaderIsNotPresent() [Fact] public async Task VerifyArrHeaderEncodedCertFailsOnBadEncoding() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs b/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs index 8663d870062f..6e4d8d9b71c4 100644 --- a/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs +++ b/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs @@ -20,7 +20,7 @@ public class ForwardedHeadersMiddlewareTests [Fact] public async Task XForwardedForDefaultSettingsChangeRemoteIpAndPort() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -57,7 +57,7 @@ public async Task XForwardedForDefaultSettingsChangeRemoteIpAndPort() [InlineData(1, "11.111.111.11.12345", "10.0.0.1", 99)] // Invalid public async Task XForwardedForFirstValueIsInvalid(int limit, string header, string expectedIp, int expectedPort) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -113,7 +113,7 @@ public async Task XForwardedForFirstValueIsInvalid(int limit, string header, str [InlineData(3, "13.113.113.13:34567, 12.112.112.12:23456, 11.111.111.11:12345", "13.113.113.13", 34567, "", true)] public async Task XForwardedForForwardLimit(int limit, string header, string expectedIp, int expectedPort, string remainingHeader, bool requireSymmetry) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -158,7 +158,7 @@ public async Task XForwardedForForwardLimit(int limit, string header, string exp [InlineData("::", false)] public async Task XForwardedForLoopback(string originalIp, bool expectForwarded) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -226,7 +226,7 @@ public async Task XForwardedForLoopback(string originalIp, bool expectForwarded) [InlineData(3, "13.113.113.13;34567, 12.112.112.12:23456, 11.111.111.11:12345", "10.0.0.1,11.111.111.11,12.112.112.12", "12.112.112.12", 23456, true)] // Invalid 3rd IP public async Task XForwardedForForwardKnownIps(int limit, string header, string knownIPs, string expectedIp, int expectedPort, bool requireSymmetry) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -267,7 +267,7 @@ public async Task XForwardedForForwardKnownIps(int limit, string header, string [Fact] public async Task XForwardedForOverrideBadIpDoesntChangeRemoteIp() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -298,7 +298,7 @@ public async Task XForwardedForOverrideBadIpDoesntChangeRemoteIp() [Fact] public async Task XForwardedHostOverrideChangesRequestHost() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -366,7 +366,7 @@ public async Task XForwardedHostAllowsValidCharacters(string hostHeader) { var assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -453,7 +453,7 @@ public async Task XForwardedHostFailsForInvalidCharacters(string hostHeader) { var assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -505,7 +505,7 @@ await server.SendAsync(c => public async Task XForwardedHostAllowsSpecifiedHost(string hostHeader, string allowedHost) { bool assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -558,7 +558,7 @@ public async Task XForwardedHostAllowsSpecifiedHost(string hostHeader, string al public async Task XForwardedHostFailsMismatchedHosts(string hostHeader, string allowedHost) { bool assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -595,7 +595,7 @@ public async Task XForwardedHostFailsMismatchedHosts(string hostHeader, string a public async Task XForwardedHostStopsAtFirstUnspecifiedHost() { bool assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -639,7 +639,7 @@ public async Task XForwardedHostStopsAtFirstUnspecifiedHost() [InlineData(10, "h3, h2, h1", "h3")] public async Task XForwardedProtoOverrideChangesRequestProtocol(int limit, string header, string expected) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -690,7 +690,7 @@ public async Task XForwardedProtoAcceptsValidProtocols(string scheme) { var assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -749,7 +749,7 @@ public async Task XForwardedProtoRejectsInvalidProtocols(string scheme) { var assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -793,7 +793,7 @@ await server.SendAsync(c => [InlineData(10, "h3, h2, h1", "::1, badip, ::1", "h1")] public async Task XForwardedProtoOverrideLimitedByXForwardedForCount(int limit, string protoHeader, string forHeader, string expected) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -837,7 +837,7 @@ public async Task XForwardedProtoOverrideLimitedByXForwardedForCount(int limit, [InlineData(10, "h3, h2, h1", "::1, badip, ::1", "h1")] public async Task XForwardedProtoOverrideCanBeIndependentOfXForwardedForCount(int limit, string protoHeader, string forHeader, string expected) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -883,7 +883,7 @@ public async Task XForwardedProtoOverrideCanBeIndependentOfXForwardedForCount(in [InlineData("h2, h1", "E::, D::", "F::", true, "http")] public async Task XForwardedProtoOverrideLimitedByLoopback(string protoHeader, string forHeader, string remoteIp, bool loopback, string expected) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -934,7 +934,7 @@ public void AllForwardsDisabledByDefault() [Fact] public async Task AllForwardsEnabledChangeRequestRemoteIpHostandProtocol() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -969,7 +969,7 @@ public async Task AllForwardsEnabledChangeRequestRemoteIpHostandProtocol() [Fact] public async Task AllOptionsDisabledRequestDoesntChange() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -1004,7 +1004,7 @@ public async Task AllOptionsDisabledRequestDoesntChange() [Fact] public async Task PartiallyEnabledForwardsPartiallyChangesRequest() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -1063,7 +1063,7 @@ public async Task XForwardForIPv4ToIPv6Mapping(string forHeader, string knownPro options.KnownNetworks.Add(new IPNetwork(networkIp, prefixLength)); } - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -1093,7 +1093,7 @@ public async Task XForwardForIPv4ToIPv6Mapping(string forHeader, string knownPro [InlineData(2, "httpa, httpb, httpc", "httpb", "httpa")] public async Task ForwardersWithDIOptionsRunsOnce(int limit, string header, string expectedScheme, string remainingHeader) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -1135,7 +1135,7 @@ public async Task ForwardersWithDIOptionsRunsOnce(int limit, string header, stri [InlineData(2, "httpa, httpb, httpc", "httpa", "")] public async Task ForwardersWithDirectOptionsRunsTwice(int limit, string header, string expectedScheme, string remainingHeader) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs b/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs index af8893f3ab2d..363f57aa4536 100644 --- a/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs +++ b/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs @@ -18,7 +18,7 @@ public class HttpMethodOverrideMiddlewareTest public async Task XHttpMethodOverrideHeaderAvaiableChangesRequestMethod() { var assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -51,7 +51,7 @@ public async Task XHttpMethodOverrideHeaderAvaiableChangesRequestMethod() public async Task XHttpMethodOverrideHeaderUnavaiableDoesntChangeRequestMethod() { var assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -83,7 +83,7 @@ public async Task XHttpMethodOverrideHeaderUnavaiableDoesntChangeRequestMethod() public async Task XHttpMethodOverrideFromGetRequestDoesntChangeMethodType() { var assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -116,7 +116,7 @@ public async Task XHttpMethodOverrideFromGetRequestDoesntChangeMethodType() public async Task FormFieldAvailableChangesRequestMethod() { var assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -157,7 +157,7 @@ public async Task FormFieldAvailableChangesRequestMethod() public async Task FormFieldUnavailableDoesNotChangeRequestMethod() { var assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -197,7 +197,7 @@ public async Task FormFieldUnavailableDoesNotChangeRequestMethod() public async Task FormFieldEmptyDoesNotChangeRequestMethod() { var assertsExecuted = false; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs b/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs index 37d44fe489d2..c74dfc8388e0 100644 --- a/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs +++ b/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs @@ -25,7 +25,7 @@ public class HstsMiddlewareTests [Fact] public async Task SetOptionsWithDefault_SetsMaxAgeToCorrectValue() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -68,7 +68,7 @@ public async Task SetOptionsWithDefault_SetsMaxAgeToCorrectValue() [InlineData(50000, true, true, "max-age=50000; includeSubDomains; preload")] public async Task SetOptionsThroughConfigure_SetsHeaderCorrectly(int maxAge, bool includeSubDomains, bool preload, string expected) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -116,7 +116,7 @@ public async Task SetOptionsThroughConfigure_SetsHeaderCorrectly(int maxAge, boo [InlineData(50000, true, true, "max-age=50000; includeSubDomains; preload")] public async Task SetOptionsThroughHelper_SetsHeaderCorrectly(int maxAge, bool includeSubDomains, bool preload, string expected) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -168,7 +168,7 @@ public async Task DefaultExcludesCommonLocalhostDomains_DoesNotSetHstsHeader(str TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -220,7 +220,7 @@ public async Task AllowLocalhostDomainsIfListIsReset_SetHstsHeader(string hostUr TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -277,7 +277,7 @@ public async Task AddExcludedDomains_DoesNotAddHstsHeader(string hostUrl) TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -331,7 +331,7 @@ public async Task WhenRequestIsInsecure_DoesNotAddHstsHeader() TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -380,7 +380,7 @@ public async Task WhenRequestIsSecure_AddsHstsHeader() TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs b/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs index 457042331832..b187f02af3fd 100644 --- a/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs +++ b/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs @@ -31,7 +31,7 @@ public class HttpsPolicyTests [InlineData(302, 5050, 2592000, true, true, "max-age=2592000; includeSubDomains; preload", "https://localhost:5050/")] public async Task SetsBothHstsAndHttpsRedirection_RedirectOnFirstRequest_HstsOnSecondRequest(int statusCode, int? tlsPort, int maxAge, bool includeSubDomains, bool preload, string expectedHstsHeader, string expectedUrl) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs b/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs index d83c1a93dce3..cb3df2f789f2 100644 --- a/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs +++ b/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs @@ -30,7 +30,7 @@ public async Task SetOptions_NotEnabledByDefault() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -82,7 +82,7 @@ public async Task SetOptions_SetStatusCodeHttpsPort(int statusCode, int? httpsPo TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -140,7 +140,7 @@ public async Task SetOptionsThroughHelperMethod_SetStatusCodeAndHttpsPort(int st TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -198,7 +198,7 @@ public async Task SetOptionsThroughHelperMethod_SetStatusCodeAndHttpsPort(int st public async Task SetHttpsPortEnvironmentVariableAndServerFeature_ReturnsCorrectStatusCodeOnResponse( int? optionsHttpsPort, string configHttpsPort, string serverAddressFeatureUrl, string expectedUrl) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -249,7 +249,7 @@ public async Task SetServerAddressesFeature_SingleHttpsAddress_Success() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -302,7 +302,7 @@ public async Task SetServerAddressesFeature_MultipleHttpsAddresses_LogsAndFailsT TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -354,7 +354,7 @@ public async Task SetServerAddressesFeature_MultipleHttpsAddressesWithSamePort_S TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -409,7 +409,7 @@ public async Task NoServerAddressFeature_DoesNotThrow_DoesNotRedirect() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -453,7 +453,7 @@ public async Task SetNullAddressFeature_DoesNotThrow() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs b/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs index b3743d32efd8..eb00fb27e9c7 100644 --- a/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs +++ b/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs @@ -31,7 +31,7 @@ public async Task GetCultureInfo_FromRouteData( string expectedCulture, string expectedUICulture) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -97,7 +97,7 @@ public async Task GetCultureInfo_FromRouteData( [Fact] public async Task GetDefaultCultureInfo_IfCultureKeysAreMissing() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -154,7 +154,7 @@ public async Task GetCultureInfo_FromRouteData_WithCustomKeys( string expectedCulture, string expectedUICulture) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs b/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs index f514098016e2..c3424193f2ad 100644 --- a/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs +++ b/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs @@ -20,7 +20,7 @@ public class LocalizationSampleTest public async Task LocalizationSampleSmokeTest() { // Arrange - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs b/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs index 8e971155188c..344746231240 100644 --- a/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs +++ b/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs @@ -98,7 +98,7 @@ public Task Localization_BuilderAPIs() private async Task RunTest(Type startupType, string culture, string expected) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs index 30e6bee3dba7..0cbf91709ce3 100644 --- a/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs @@ -18,7 +18,7 @@ public class AcceptLanguageHeaderRequestCultureProviderTest [Fact] public async Task GetFallbackLanguage_ReturnsFirstNonNullCultureFromSupportedCultureList() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -61,7 +61,7 @@ public async Task GetFallbackLanguage_ReturnsFirstNonNullCultureFromSupportedCul [Fact] public async Task GetFallbackLanguage_ReturnsFromSupportedCulture_AcceptLanguageListContainsSupportedCultures() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -103,7 +103,7 @@ public async Task GetFallbackLanguage_ReturnsFromSupportedCulture_AcceptLanguage [Fact] public async Task GetFallbackLanguage_ReturnsDefault_AcceptLanguageListDoesnotContainSupportedCultures() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -146,7 +146,7 @@ public async Task GetFallbackLanguage_ReturnsDefault_AcceptLanguageListDoesnotCo [Fact] public async Task OmitDefaultRequestCultureShouldNotThrowNullReferenceException_And_ShouldGetTheRightCulture() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs index 09ad71e05050..524cab81ef3e 100644 --- a/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs @@ -22,7 +22,7 @@ public class CookieRequestCultureProviderTest [Fact] public async Task GetCultureInfoFromPersistentCookie() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -77,7 +77,7 @@ public async Task GetCultureInfoFromPersistentCookie() [Fact] public async Task GetDefaultCultureInfoIfCultureKeysAreMissingOrInvalid() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -128,7 +128,7 @@ public async Task GetDefaultCultureInfoIfCultureKeysAreMissingOrInvalid() [Fact] public async Task GetDefaultCultureInfoIfCookieDoesNotExist() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -181,7 +181,7 @@ public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedCultures( TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -243,7 +243,7 @@ public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedUICulture TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs index 96b40ced09de..526cea685483 100644 --- a/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs @@ -20,7 +20,7 @@ public class CustomRequestCultureProviderTest [Fact] public async Task CustomRequestCultureProviderThatGetsCultureInfoFromUrl() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs index b6568ac5fb97..0b3ba6ab998b 100644 --- a/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs @@ -18,7 +18,7 @@ public class QueryStringRequestCultureProviderTest [Fact] public async Task GetCultureInfoFromQueryString() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -62,7 +62,7 @@ public async Task GetCultureInfoFromQueryString() [Fact] public async Task GetDefaultCultureInfoIfCultureKeysAreMissing() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -98,7 +98,7 @@ public async Task GetDefaultCultureInfoIfCultureKeysAreMissing() [Fact] public async Task GetDefaultCultureInfoIfCultureIsInSupportedCultureList() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -141,7 +141,7 @@ public async Task GetDefaultCultureInfoIfCultureIsInSupportedCultureList() [Fact] public async Task GetDefaultCultureInfoIfUICultureIsNotInSupportedList() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -184,7 +184,7 @@ public async Task GetDefaultCultureInfoIfUICultureIsNotInSupportedList() [Fact] public async Task GetSameCultureInfoIfCultureKeyIsMissing() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -228,7 +228,7 @@ public async Task GetSameCultureInfoIfCultureKeyIsMissing() [Fact] public async Task GetSameCultureInfoIfUICultureKeyIsMissing() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -272,7 +272,7 @@ public async Task GetSameCultureInfoIfUICultureKeyIsMissing() [Fact] public async Task GetCultureInfoFromQueryStringWithCustomKeys() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -321,7 +321,7 @@ public async Task GetCultureInfoFromQueryStringWithCustomKeys() [Fact] public async Task GetTheRightCultureInfoRegardlessOfCultureNameCasing() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs b/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs index 9a6646d6c5e5..b6df216d6957 100644 --- a/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs +++ b/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs @@ -20,7 +20,7 @@ public async Task ExceptionWrittenToDiagnostics() { DiagnosticListener diagnosticListener = null; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs b/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs index 25040684d9c8..afd2a860f4af 100644 --- a/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs +++ b/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs @@ -22,7 +22,7 @@ public async Task ServesCachedContent_IfAvailable(string method) foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -48,7 +48,7 @@ public async Task ServesFreshContent_IfNotAvailable(string method) foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -72,7 +72,7 @@ public async Task ServesFreshContent_Post() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -96,7 +96,7 @@ public async Task ServesFreshContent_Head_Get() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -120,7 +120,7 @@ public async Task ServesFreshContent_Get_Head() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -145,7 +145,7 @@ public async Task ServesFreshContent_If_CacheControlNoCache(string method) foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -180,7 +180,7 @@ public async Task ServesFreshContent_If_PragmaNoCache(string method) foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -215,7 +215,7 @@ public async Task ServesCachedContent_If_PathCasingDiffers(string method) foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -241,7 +241,7 @@ public async Task ServesFreshContent_If_ResponseExpired(string method) foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -267,7 +267,7 @@ public async Task ServesFreshContent_If_Authorization_HeaderExists(string method foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -292,7 +292,7 @@ public async Task ServesCachedContent_IfVaryHeader_Matches() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -317,7 +317,7 @@ public async Task ServesFreshContent_IfVaryHeader_Mismatches() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -343,7 +343,7 @@ public async Task ServesCachedContent_IfVaryQueryKeys_Matches() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -367,7 +367,7 @@ public async Task ServesCachedContent_IfVaryQueryKeysExplicit_Matches_QueryKeyCa foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -391,7 +391,7 @@ public async Task ServesCachedContent_IfVaryQueryKeyStar_Matches_QueryKeyCaseIns foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -415,7 +415,7 @@ public async Task ServesCachedContent_IfVaryQueryKeyExplicit_Matches_OrderInsens foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -439,7 +439,7 @@ public async Task ServesCachedContent_IfVaryQueryKeyStar_Matches_OrderInsensitiv foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -463,7 +463,7 @@ public async Task ServesFreshContent_IfVaryQueryKey_Mismatches() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -487,7 +487,7 @@ public async Task ServesFreshContent_IfVaryQueryKeyExplicit_Mismatch_QueryKeyCas foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -511,7 +511,7 @@ public async Task ServesFreshContent_IfVaryQueryKeyStar_Mismatch_QueryKeyValueCa foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -535,7 +535,7 @@ public async Task ServesFreshContent_IfRequestRequirements_NotMet() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -563,7 +563,7 @@ public async Task Serves504_IfOnlyIfCachedHeader_IsSpecified() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -592,7 +592,7 @@ public async Task ServesFreshContent_IfSetCookie_IsSpecified() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -616,7 +616,7 @@ public async Task ServesCachedContent_IfSubsequentRequestContainsNoStore() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -644,7 +644,7 @@ public async Task ServesFreshContent_IfInitialRequestContainsNoStore() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -672,7 +672,7 @@ public async Task ServesFreshContent_IfInitialResponseContainsNoStore() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -701,7 +701,7 @@ public async Task Serves304_IfIfModifiedSince_Satisfied() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -728,7 +728,7 @@ public async Task ServesCachedContent_IfIfModifiedSince_NotSatisfied() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -758,7 +758,7 @@ public async Task Serves304_IfIfNoneMatch_Satisfied() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -785,7 +785,7 @@ public async Task ServesCachedContent_IfIfNoneMatch_NotSatisfied() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -813,7 +813,7 @@ public async Task ServesCachedContent_IfBodySize_IsCacheable() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -840,7 +840,7 @@ public async Task ServesFreshContent_IfBodySize_IsNotCacheable() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -867,7 +867,7 @@ public async Task ServesFreshContent_CaseSensitivePaths_IsNotCacheable() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -891,7 +891,7 @@ public async Task ServesCachedContent_WithoutReplacingCachedVaryBy_OnCacheMiss() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -919,7 +919,7 @@ public async Task ServesFreshContent_IfCachedVaryByUpdated_OnCacheMiss() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -956,7 +956,7 @@ public async Task ServesCachedContent_IfCachedVaryByNotUpdated_OnCacheMiss() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); @@ -993,7 +993,7 @@ public async Task ServesCachedContent_IfAvailable_UsingHead_WithContentLength() foreach (var builder in builders) { - var host = builder.Build(); + using var host = builder.Build(); await host.StartAsync(); diff --git a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs index 44ca99b5f7d4..3f4833335da7 100644 --- a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs +++ b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs @@ -135,7 +135,7 @@ public async Task ContentType_WithCharset_Compress(string contentType) [Fact] public async Task GZipCompressionProvider_OptionsSetInDI_Compress() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -296,7 +296,7 @@ public async Task NoIncludedMimeTypes_UseDefaults() [InlineData("text/plain2")] public async Task NoBody_NotCompressed(string contentType) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -432,7 +432,7 @@ public async Task Request_Https_CompressedIfEnabled(bool enableHttps, int expect TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -495,7 +495,7 @@ public async Task Request_Https_CompressedIfOptIn(HttpsCompressionMode mode, int TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -560,7 +560,7 @@ public async Task Request_Https_NotCompressedIfOptOut(HttpsCompressionMode mode, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -620,7 +620,7 @@ public async Task FlushHeaders_SendsHeaders_Compresses(string encoding, int expe { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -668,7 +668,7 @@ public async Task FlushAsyncHeaders_SendsHeaders_Compresses(string encoding, int { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -715,7 +715,7 @@ public async Task FlushBody_CompressesAndFlushes(string encoding) { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -776,7 +776,7 @@ public async Task FlushAsyncBody_CompressesAndFlushes(string encoding) { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -838,7 +838,7 @@ public async Task TrickleWriteAndFlush_FlushesEachWrite(string encoding) new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously), }; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -910,7 +910,7 @@ public async Task TrickleWriteAndFlushAsync_FlushesEachWrite(string encoding) new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously), }; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -968,7 +968,7 @@ public async Task SendFileAsync_DifferentContentType_NotBypassed() { FakeSendFileFeature fakeSendFile = null; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -1020,7 +1020,7 @@ public async Task SendFileAsync_FirstWrite_CompressesAndFlushes() { FakeSendFileFeature fakeSendFile = null; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -1072,7 +1072,7 @@ public async Task SendFileAsync_AfterFirstWrite_CompressesAndFlushes() { FakeSendFileFeature fakeSendFile = null; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -1125,7 +1125,7 @@ public async Task Dispose_SyncWriteOrFlushNotCalled(string encoding) { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -1191,7 +1191,7 @@ public async Task Dispose_SyncWriteOrFlushNotCalled(string encoding) TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs b/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs index 98740759d142..2c566dd4f5e0 100644 --- a/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs +++ b/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs @@ -20,7 +20,7 @@ public class ModRewriteMiddlewareTest public async Task Invoke_RewritePathWhenMatching() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader("RewriteRule /hey/(.*) /$1 ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -48,7 +48,7 @@ public async Task Invoke_RewritePathTerminatesOnFirstSuccessOfRule() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader("RewriteRule /hey/(.*) /$1 [L]")) .AddApacheModRewrite(new StringReader("RewriteRule /hello /what")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -76,7 +76,7 @@ public async Task Invoke_RewritePathDoesNotTerminateOnFirstSuccessOfRule() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader("RewriteRule /hey/(.*) /$1")) .AddApacheModRewrite(new StringReader("RewriteRule /hello /what")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -103,7 +103,7 @@ public async Task Invoke_RewritePathDoesNotTerminateOnFirstSuccessOfRule() public async Task Invoke_ShouldIgnoreComments() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader("#RewriteRule ^/hey/(.*) /$1 ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -130,7 +130,7 @@ public async Task Invoke_ShouldIgnoreComments() public async Task Invoke_ShouldRewriteHomepage() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteRule ^/$ /homepage.html")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -157,7 +157,7 @@ public async Task Invoke_ShouldRewriteHomepage() public async Task Invoke_ShouldIgnorePorts() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteRule ^/$ /homepage.html")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -184,7 +184,7 @@ public async Task Invoke_ShouldIgnorePorts() public async Task Invoke_HandleNegatedRewriteRules() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteRule !^/$ /homepage.html")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -213,7 +213,7 @@ public async Task Invoke_HandleNegatedRewriteRules() public async Task Invoke_BackReferencesShouldBeApplied(string url, string rule, string expected) { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(rule)); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -246,7 +246,7 @@ public async Task Invoke_BackReferencesShouldBeApplied(string url, string rule, public async Task Invoke_ShouldHandleFlagNoCase(string url, string rule, string expected) { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(rule)); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -274,7 +274,7 @@ public async Task Invoke_CheckFullUrlWithOnlyPath() { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader(@"RewriteRule (.+) http://www.example.com$1/")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -302,7 +302,7 @@ public async Task Invoke_CheckFullUrlWithUFlag() { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader(@"RewriteRule (.+) http://www.example.com$1/")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -330,7 +330,7 @@ public async Task Invoke_CheckModFileConditions() { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader(@"RewriteRule (.+) http://www.example.com$1/")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -359,7 +359,7 @@ public async Task Invoke_EnsureHttps(string input) { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader("RewriteCond %{REQUEST_URI} /foo/ \nRewriteCond %{HTTPS} !on \nRewriteRule ^(.*)$ https://www.example.com$1 [R=301,L]")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -389,7 +389,7 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRedirectLocationHasForwa { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader("RewriteRule ^(.*)$ $1 [R=301,L]")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -419,7 +419,7 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRewriteHasForwardSlash(s { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader("RewriteRule ^(.*)$ $1 [L]")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -445,7 +445,7 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRewriteHasForwardSlash(s public async Task Invoke_CaptureEmptyStringInRegexAssertLocationHeaderContainsPathBase() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteRule ^(.*)$ $1 [R=301,L]")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -477,7 +477,7 @@ public async Task CapturedVariablesInConditionsArePreservedToRewriteRule() var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteCond %{REQUEST_URI} /home RewriteCond %{QUERY_STRING} report_id=(.+) RewriteRule (.*) http://localhost:80/home/report/%1 [R=301,L,QSD]")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs b/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs index 94e89e76591b..b0f2ce5233bd 100644 --- a/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs +++ b/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs @@ -34,7 +34,7 @@ public async Task Invoke_RedirectPathToPathAndQuery() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -68,7 +68,7 @@ public async Task Invoke_RewritePathToPathAndQuery() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -106,7 +106,7 @@ public async Task Invoke_RewriteBasedOnQueryStringParameters() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -140,7 +140,7 @@ public async Task Invoke_RedirectToLowerCase() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -178,7 +178,7 @@ public async Task Invoke_RedirectRemoveTrailingSlash() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -215,7 +215,7 @@ public async Task Invoke_RedirectAddTrailingSlash() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -251,7 +251,7 @@ public async Task Invoke_RedirectToHttps() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -287,7 +287,7 @@ public async Task Invoke_RewriteToHttps() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -326,7 +326,7 @@ public async Task Invoke_ReverseProxyToAnotherSite() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -365,7 +365,7 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRedirectLocationHasForwa ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -404,7 +404,7 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRewriteLocationHasForwar ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -440,7 +440,7 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertLocationHeaderContainsPa ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -484,7 +484,7 @@ public async Task VerifyIsFileAndIsDirectoryParsing(string matchType) ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -522,7 +522,7 @@ public async Task VerifyTrackAllCaptures() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -560,7 +560,7 @@ public async Task VerifyTrackAllCapturesRuleAndConditionCapture() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -599,7 +599,7 @@ public async Task ThrowIndexOutOfRangeExceptionWithCorrectMessage() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -637,7 +637,7 @@ public async Task Invoke_GlobalRuleConditionMatchesAgainstFullUri_ParsedRule() "; var options = new RewriteOptions().AddIISUrlRewrite(new StringReader(xml)); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -684,7 +684,7 @@ public async Task Invoke_ReverseProxyToAnotherSiteUsingXmlConfiguredRewriteMap(s ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -718,7 +718,7 @@ public async Task Invoke_CustomResponse() ")); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -775,7 +775,7 @@ public async Task Invoke_GlobalRuleConditionMatchesAgainstFullUri_CodedRule(stri ruleBuilder.AddUrlAction(action); var options = new RewriteOptions().Add(ruleBuilder.Build()); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Rewrite/test/MiddlewareTests.cs b/src/Middleware/Rewrite/test/MiddlewareTests.cs index 1c1534ff06f3..7f627e573ffd 100644 --- a/src/Middleware/Rewrite/test/MiddlewareTests.cs +++ b/src/Middleware/Rewrite/test/MiddlewareTests.cs @@ -19,7 +19,7 @@ public class MiddlewareTests public async Task CheckRewritePath() { var options = new RewriteOptions().AddRewrite("(.*)", "http://example.com/$1", skipRemainingRules: false); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -51,7 +51,7 @@ public async Task CheckRewritePath() public async Task CheckRedirectPath() { var options = new RewriteOptions().AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -76,7 +76,7 @@ public async Task CheckRedirectPath() [Fact] public async Task RewriteRulesCanComeFromConfigureOptions() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -109,7 +109,7 @@ public async Task RewriteRulesCanComeFromConfigureOptions() public async Task CheckRedirectPathWithQueryString() { var options = new RewriteOptions().AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -139,7 +139,7 @@ public async Task CheckRedirectPathWithQueryString() public async Task CheckRedirectToHttps(int statusCode) { var options = new RewriteOptions().AddRedirectToHttps(statusCode: statusCode); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -166,7 +166,7 @@ public async Task CheckRedirectToHttps(int statusCode) public async Task CheckPermanentRedirectToHttps() { var options = new RewriteOptions().AddRedirectToHttpsPermanent(); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -195,7 +195,7 @@ public async Task CheckPermanentRedirectToHttps() public async Task CheckRedirectToHttpsWithSslPort(int sslPort, string expected) { var options = new RewriteOptions().AddRedirectToHttps(statusCode: StatusCodes.Status301MovedPermanently, sslPort: sslPort); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -226,7 +226,7 @@ public async Task CheckRedirectToHttpsWithSslPort(int sslPort, string expected) public async Task CheckRedirectToWwwWithStatusCode(int statusCode) { var options = new RewriteOptions().AddRedirectToWww(statusCode: statusCode); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -257,7 +257,7 @@ public async Task CheckRedirectToWwwWithStatusCode(int statusCode) public async Task CheckRedirectToWww(string requestUri, string redirectUri) { var options = new RewriteOptions().AddRedirectToWww(); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -284,7 +284,7 @@ public async Task CheckRedirectToWww(string requestUri, string redirectUri) public async Task CheckPermanentRedirectToWww() { var options = new RewriteOptions().AddRedirectToWwwPermanent(); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -321,7 +321,7 @@ public async Task CheckPermanentRedirectToWww() public async Task CheckNoRedirectToWww(string requestUri) { var options = new RewriteOptions().AddRedirectToWww(); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -351,7 +351,7 @@ public async Task CheckNoRedirectToWww(string requestUri) public async Task CheckRedirectToNonWwwWithStatusCode(int statusCode) { var options = new RewriteOptions().AddRedirectToNonWww(statusCode: statusCode); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -382,7 +382,7 @@ public async Task CheckRedirectToNonWwwWithStatusCode(int statusCode) public async Task CheckRedirectToNonWww(string requestUri, string redirectUri) { var options = new RewriteOptions().AddRedirectToNonWww(); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -409,7 +409,7 @@ public async Task CheckRedirectToNonWww(string requestUri, string redirectUri) public async Task CheckPermanentRedirectToNonWww() { var options = new RewriteOptions().AddRedirectToNonWwwPermanent(); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -436,7 +436,7 @@ public async Task CheckPermanentRedirectToNonWww() public async Task CheckIfEmptyStringRedirectCorrectly() { var options = new RewriteOptions().AddRedirect("(.*)", "$1", statusCode: StatusCodes.Status301MovedPermanently); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -461,7 +461,7 @@ public async Task CheckIfEmptyStringRedirectCorrectly() public async Task CheckIfEmptyStringRewriteCorrectly() { var options = new RewriteOptions().AddRewrite("(.*)", "$1", skipRemainingRules: false); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -490,7 +490,7 @@ public async Task CheckIfEmptyStringRewriteCorrectly() public async Task SettingPathBase() { var options = new RewriteOptions().AddRedirect("(.*)", "$1"); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -525,7 +525,7 @@ public async Task SettingPathBase() public async Task CheckNoRedirectToWwwInNonWhitelistedDomains(string requestUri) { var options = new RewriteOptions().AddRedirectToWww("example2.com"); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -555,7 +555,7 @@ public async Task CheckNoRedirectToWwwInNonWhitelistedDomains(string requestUri) public async Task CheckRedirectToWwwInWhitelistedDomains(string requestUri, string redirectUri) { var options = new RewriteOptions().AddRedirectToWww("example.com"); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -582,7 +582,7 @@ public async Task CheckRedirectToWwwInWhitelistedDomains(string requestUri, stri public async Task CheckPermanentRedirectToWwwInWhitelistedDomains() { var options = new RewriteOptions().AddRedirectToWwwPermanent("example.com"); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -613,7 +613,7 @@ public async Task CheckPermanentRedirectToWwwInWhitelistedDomains() public async Task CheckRedirectToWwwWithStatusCodeInWhitelistedDomains(int statusCode) { var options = new RewriteOptions().AddRedirectToWww(statusCode: statusCode, "example.com"); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/Session/test/SessionTests.cs b/src/Middleware/Session/test/SessionTests.cs index d34bb25ba4d4..c2c920ef2549 100644 --- a/src/Middleware/Session/test/SessionTests.cs +++ b/src/Middleware/Session/test/SessionTests.cs @@ -30,7 +30,7 @@ public class SessionTests [Fact] public async Task ReadingEmptySessionDoesNotCreateCookie() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -68,7 +68,7 @@ public async Task ReadingEmptySessionDoesNotCreateCookie() [Fact] public async Task SettingAValueCausesTheCookieToBeCreated() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -118,7 +118,7 @@ public async Task SecureSessionBasedOnHttpsAndSecurePolicy( string requestUri, bool shouldBeSecureOnly) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -173,7 +173,7 @@ public async Task SecureSessionBasedOnHttpsAndSecurePolicy( [Fact] public async Task SessionCanBeAccessedOnTheNextRequest() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -224,7 +224,7 @@ public async Task SessionCanBeAccessedOnTheNextRequest() [Fact] public async Task RemovedItemCannotBeAccessedAgain() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -285,7 +285,7 @@ public async Task RemovedItemCannotBeAccessedAgain() [Fact] public async Task ClearedItemsCannotBeAccessedAgain() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -349,7 +349,7 @@ public async Task SessionStart_LogsInformation() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -398,7 +398,7 @@ public async Task ExpiredSession_LogsInfo() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -465,7 +465,7 @@ public async Task ExpiredSession_LogsInfo() public async Task RefreshesSession_WhenSessionData_IsNotModified() { var clock = new TestClock(); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -532,7 +532,7 @@ public async Task RefreshesSession_WhenSessionData_IsNotModified() [Fact] public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -576,7 +576,7 @@ public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut() [Fact] public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut_AndAnUnhandledExcetionIsThrown() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -627,7 +627,7 @@ public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut_AndAnUnhand [Fact] public async Task SessionKeys_AreCaseSensitive() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -670,7 +670,7 @@ public async Task SessionLogsCacheReadException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -721,7 +721,7 @@ public async Task SessionLogsCacheLoadAsyncException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -771,7 +771,7 @@ public async Task SessionLogsCacheLoadAsyncTimeoutException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -821,7 +821,7 @@ public async Task SessionLoadAsyncCanceledException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -877,7 +877,7 @@ public async Task SessionLogsCacheCommitException() || beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName); }); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -939,7 +939,7 @@ public async Task SessionLogsCacheCommitTimeoutException() || beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName); }); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -1007,7 +1007,7 @@ public async Task SessionLogsCacheCommitCanceledException() || beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName); }); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -1073,7 +1073,7 @@ public async Task RequestAbortedIgnored() || beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName); }); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -1131,7 +1131,7 @@ public async Task SessionLogsCacheRefreshException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs b/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs index e9723a819f89..6d867a0564e9 100644 --- a/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs +++ b/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs @@ -26,7 +26,7 @@ public class FallbackStaticFileTest : LoggedTest [Fact] public async Task ReturnsFileForDefaultPattern() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -81,7 +81,7 @@ public async Task ReturnsFileForDefaultPattern() [Fact] public async Task ReturnsFileForCustomPattern() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs b/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs index 2808124c6c10..6d255b06f8ea 100644 --- a/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs @@ -29,7 +29,7 @@ public class StaticFileMiddlewareTests : LoggedTest [Fact] public async Task ReturnsNotFoundWithoutWwwroot() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -54,7 +54,7 @@ public async Task ReturnsNotFoundWithoutWwwroot() [Fact] public async Task Endpoint_PassesThrough() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -102,7 +102,7 @@ public async Task Endpoint_PassesThrough() [Fact] public async Task FoundFile_LastModifiedTrimsSeconds() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -149,7 +149,7 @@ public async Task FoundFile_Served_Windows(string baseUrl, string baseDir, strin private async Task FoundFile_Served(string baseUrl, string baseDir, string requestUrl) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -193,7 +193,7 @@ private async Task FoundFile_Served(string baseUrl, string baseDir, string reque [MemberData(nameof(ExistingFiles))] public async Task HeadFile_HeadersButNotBodyServed(string baseUrl, string baseDir, string requestUrl) { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -256,7 +256,7 @@ private async Task ClientDisconnect_NoWriteExceptionThrown(ServerType serverType var requestCancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var responseComplete = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); Exception exception = null; - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder diff --git a/src/Middleware/StaticFiles/test/UnitTests/CacheHeaderTests.cs b/src/Middleware/StaticFiles/test/UnitTests/CacheHeaderTests.cs index 7c70ce4551f7..8f02132ea0fc 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/CacheHeaderTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/CacheHeaderTests.cs @@ -18,7 +18,8 @@ public class CacheHeaderTests [Fact] public async Task ServerShouldReturnETag() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); Assert.NotNull(response.Headers.ETag); @@ -28,7 +29,8 @@ public async Task ServerShouldReturnETag() [Fact] public async Task SameETagShouldBeReturnedAgain() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage response1 = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); HttpResponseMessage response2 = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); @@ -47,7 +49,8 @@ public async Task SameETagShouldBeReturnedAgain() [MemberData(nameof(SupportedMethods))] public async Task IfMatchShouldReturn412WhenNotListed(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); req.Headers.Add("If-Match", "\"fake\""); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -58,7 +61,8 @@ public async Task IfMatchShouldReturn412WhenNotListed(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task IfMatchShouldBeServedWhenListed(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); var req = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); @@ -71,7 +75,8 @@ public async Task IfMatchShouldBeServedWhenListed(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task IfMatchShouldBeServedForAsterisk(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); req.Headers.Add("If-Match", "*"); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -82,7 +87,8 @@ public async Task IfMatchShouldBeServedForAsterisk(HttpMethod method) [MemberData(nameof(UnsupportedMethods))] public async Task IfMatchShouldBeIgnoredForUnsupportedMethods(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); req.Headers.Add("If-Match", "*"); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -107,7 +113,8 @@ public async Task IfMatchShouldBeIgnoredForUnsupportedMethods(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task IfNoneMatchShouldReturn304ForMatching(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage resp1 = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); var req2 = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); @@ -120,7 +127,8 @@ public async Task IfNoneMatchShouldReturn304ForMatching(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task IfNoneMatchAllShouldReturn304ForMatching(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage resp1 = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); var req2 = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); @@ -133,7 +141,8 @@ public async Task IfNoneMatchAllShouldReturn304ForMatching(HttpMethod method) [MemberData(nameof(UnsupportedMethods))] public async Task IfNoneMatchShouldBeIgnoredForNonTwoHundredAnd304Responses(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage resp1 = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); var req2 = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); @@ -156,7 +165,8 @@ public async Task IfNoneMatchShouldBeIgnoredForNonTwoHundredAnd304Responses(Http [MemberData(nameof(SupportedMethods))] public async Task ServerShouldReturnLastModified(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().SendAsync( new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml")); @@ -179,7 +189,8 @@ public async Task ServerShouldReturnLastModified(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task MatchingBothConditionsReturnsNotModified(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage resp1 = await server .CreateRequest("/SubFolder/extra.xml") .SendAsync(method.Method); @@ -198,7 +209,8 @@ public async Task MatchingBothConditionsReturnsNotModified(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task MatchingAtLeastOneETagReturnsNotModified(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage resp1 = await server .CreateRequest("/SubFolder/extra.xml") .SendAsync(method.Method); @@ -223,7 +235,8 @@ public async Task MatchingAtLeastOneETagReturnsNotModified(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task MissingEitherOrBothConditionsReturnsNormally(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage resp1 = await server .CreateRequest("/SubFolder/extra.xml") .SendAsync(method.Method); @@ -271,7 +284,8 @@ public async Task MissingEitherOrBothConditionsReturnsNormally(HttpMethod method [MemberData(nameof(SupportedMethods))] public async Task InvalidIfModifiedSinceDateFormatGivesNormalGet(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res = await server .CreateRequest("/SubFolder/extra.xml") @@ -285,7 +299,8 @@ public async Task InvalidIfModifiedSinceDateFormatGivesNormalGet(HttpMethod meth [MemberData(nameof(SupportedMethods))] public async Task FutureIfModifiedSinceDateFormatGivesNormalGet(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res = await server .CreateRequest("/SubFolder/extra.xml") @@ -306,7 +321,8 @@ public async Task FutureIfModifiedSinceDateFormatGivesNormalGet(HttpMethod metho [MemberData(nameof(SupportedMethods))] public async Task IfModifiedSinceDateGreaterThanLastModifiedShouldReturn304(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res1 = await server .CreateRequest("/SubFolder/extra.xml") @@ -324,7 +340,8 @@ public async Task IfModifiedSinceDateGreaterThanLastModifiedShouldReturn304(Http [MemberData(nameof(SupportedMethods))] public async Task SupportsIfModifiedDateFormats(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res1 = await server .CreateRequest("/SubFolder/extra.xml") .SendAsync(method.Method); @@ -351,7 +368,8 @@ public async Task SupportsIfModifiedDateFormats(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task IfModifiedSinceDateLessThanLastModifiedShouldReturn200(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res1 = await server .CreateRequest("/SubFolder/extra.xml") @@ -369,7 +387,8 @@ public async Task IfModifiedSinceDateLessThanLastModifiedShouldReturn200(HttpMet [MemberData(nameof(SupportedMethods))] public async Task InvalidIfUnmodifiedSinceDateFormatGivesNormalGet(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res = await server .CreateRequest("/SubFolder/extra.xml") @@ -383,7 +402,8 @@ public async Task InvalidIfUnmodifiedSinceDateFormatGivesNormalGet(HttpMethod me [MemberData(nameof(SupportedMethods))] public async Task FutureIfUnmodifiedSinceDateFormatGivesNormalGet(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res = await server .CreateRequest("/SubFolder/extra.xml") @@ -397,7 +417,8 @@ public async Task FutureIfUnmodifiedSinceDateFormatGivesNormalGet(HttpMethod met [MemberData(nameof(SupportedMethods))] public async Task IfUnmodifiedSinceDateLessThanLastModifiedShouldReturn412(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res1 = await server .CreateRequest("/SubFolder/extra.xml") diff --git a/src/Middleware/StaticFiles/test/UnitTests/DefaultFilesMiddlewareTests.cs b/src/Middleware/StaticFiles/test/UnitTests/DefaultFilesMiddlewareTests.cs index 08e86714a4cb..16411ea59f5c 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/DefaultFilesMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/DefaultFilesMiddlewareTests.cs @@ -24,10 +24,12 @@ public class DefaultFilesMiddlewareTests public async Task NullArguments() { // No exception, default provided - StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions { FileProvider = null })); + using (await StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions { FileProvider = null }))) + { } // PathString(null) is OK. - var server = StaticFilesTestServer.Create(app => app.UseDefaultFiles((string)null)); + using var host = await StaticFilesTestServer.Create(app => app.UseDefaultFiles((string)null)); + using var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -64,7 +66,7 @@ private async Task NoMatch_PassesThrough(string baseUrl, string baseDir, string { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => + using var host = await StaticFilesTestServer.Create(app => { app.UseDefaultFiles(new DefaultFilesOptions { @@ -74,6 +76,7 @@ private async Task NoMatch_PassesThrough(string baseUrl, string baseDir, string }); app.Run(context => context.Response.WriteAsync(context.Request.Path.Value)); }); + using var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(requestUrl); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -86,7 +89,7 @@ public async Task Endpoint_PassesThrough() { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, "."))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => { app.UseRouting(); @@ -113,6 +116,7 @@ public async Task Endpoint_PassesThrough() app.UseEndpoints(endpoints => { }); }, services => { services.AddDirectoryBrowser(); services.AddRouting(); }); + using var server = host.GetTestServer(); var response = await server.CreateRequest("/SubFolder/").GetAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -165,7 +169,7 @@ private async Task FoundDirectoryWithDefaultFile_PathModified(string baseUrl, st { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => + using var host = await StaticFilesTestServer.Create(app => { app.UseDefaultFiles(new DefaultFilesOptions { @@ -175,6 +179,7 @@ private async Task FoundDirectoryWithDefaultFile_PathModified(string baseUrl, st }); app.Run(context => context.Response.WriteAsync(context.Request.Path.Value)); }); + using var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(requestUrl); @@ -211,11 +216,12 @@ private async Task NearMatch_RedirectAddSlash(string baseUrl, string baseDir, st { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions + using var host = await StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider })); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl + queryString).GetAsync(); Assert.Equal(HttpStatusCode.Moved, response.StatusCode); @@ -265,12 +271,13 @@ private async Task PostDirectory_PassesThrough(string baseUrl, string baseDir, s { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions + using var host = await StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider, RedirectToAppendTrailingSlash = appendTrailingSlash })); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).GetAsync(); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // Passed through diff --git a/src/Middleware/StaticFiles/test/UnitTests/DirectoryBrowserMiddlewareTests.cs b/src/Middleware/StaticFiles/test/UnitTests/DirectoryBrowserMiddlewareTests.cs index 5a39ec3ef9b0..e3cc2fa32dbf 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/DirectoryBrowserMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/DirectoryBrowserMiddlewareTests.cs @@ -21,10 +21,10 @@ namespace Microsoft.AspNetCore.StaticFiles public class DirectoryBrowserMiddlewareTests { [Fact] - public void WorksWithoutEncoderRegistered() + public async Task WorksWithoutEncoderRegistered() { // No exception, uses HtmlEncoder.Default - StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser()); } @@ -32,19 +32,24 @@ public void WorksWithoutEncoderRegistered() public async Task NullArguments() { // No exception, default provided - StaticFilesTestServer.Create( + using (await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { Formatter = null }), - services => services.AddDirectoryBrowser()); + services => services.AddDirectoryBrowser())) + { + } // No exception, default provided - StaticFilesTestServer.Create( + using (await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { FileProvider = null }), - services => services.AddDirectoryBrowser()); + services => services.AddDirectoryBrowser())) + { + } // PathString(null) is OK. - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser((string)null), services => services.AddDirectoryBrowser()); + using var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -82,7 +87,7 @@ private async Task NoMatch_PassesThrough(string baseUrl, string baseDir, string { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { RequestPath = new PathString(baseUrl), @@ -90,6 +95,7 @@ private async Task NoMatch_PassesThrough(string baseUrl, string baseDir, string RedirectToAppendTrailingSlash = appendTrailingSlash }), services => services.AddDirectoryBrowser()); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).GetAsync(); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -100,7 +106,7 @@ public async Task Endpoint_PassesThrough() { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, "."))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => { app.UseRouting(); @@ -128,6 +134,7 @@ public async Task Endpoint_PassesThrough() app.UseEndpoints(endpoints => { }); }, services => { services.AddDirectoryBrowser(); services.AddRouting(); }); + using var server = host.GetTestServer(); var response = await server.CreateRequest("/").GetAsync(); Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); @@ -174,7 +181,7 @@ private async Task FoundDirectory_Served(string baseUrl, string baseDir, string { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { RequestPath = new PathString(baseUrl), @@ -182,6 +189,7 @@ private async Task FoundDirectory_Served(string baseUrl, string baseDir, string RedirectToAppendTrailingSlash = appendTrailingSlash, }), services => services.AddDirectoryBrowser()); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).GetAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -217,13 +225,14 @@ private async Task NearMatch_RedirectAddSlash(string baseUrl, string baseDir, st { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider }), services => services.AddDirectoryBrowser()); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl + queryString).GetAsync(); @@ -266,7 +275,7 @@ private async Task PostDirectory_PassesThrough(string baseUrl, string baseDir, s { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { RequestPath = new PathString(baseUrl), @@ -274,6 +283,7 @@ private async Task PostDirectory_PassesThrough(string baseUrl, string baseDir, s RedirectToAppendTrailingSlash = appendTrailingSlash }), services => services.AddDirectoryBrowser()); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).PostAsync(); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -313,7 +323,7 @@ private async Task HeadDirectory_HeadersButNotBodyServed(string baseUrl, string { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { RequestPath = new PathString(baseUrl), @@ -321,6 +331,7 @@ private async Task HeadDirectory_HeadersButNotBodyServed(string baseUrl, string RedirectToAppendTrailingSlash = appendTrailingSlash }), services => services.AddDirectoryBrowser()); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).SendAsync("HEAD"); diff --git a/src/Middleware/StaticFiles/test/UnitTests/RangeHeaderTests.cs b/src/Middleware/StaticFiles/test/UnitTests/RangeHeaderTests.cs index 71e1d7274dce..2879616c8bbc 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/RangeHeaderTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/RangeHeaderTests.cs @@ -14,12 +14,13 @@ namespace Microsoft.AspNetCore.StaticFiles public class RangeHeaderTests { // 14.27 If-Range - // If the entity tag given in the If-Range header matches the current entity tag for the entity, then the server SHOULD + // If the entity tag given in the If-Range header matches the current entity tag for the entity, then the server SHOULD // provide the specified sub-range of the entity using a 206 (Partial content) response. [Fact] public async Task IfRangeWithCurrentEtagShouldServePartialContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); @@ -39,7 +40,8 @@ public async Task IfRangeWithCurrentEtagShouldServePartialContent() [Fact] public async Task HEADIfRangeWithCurrentEtagShouldReturn200Ok() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); @@ -59,7 +61,8 @@ public async Task HEADIfRangeWithCurrentEtagShouldReturn200Ok() [Fact] public async Task IfRangeWithCurrentDateShouldServePartialContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); @@ -75,7 +78,8 @@ public async Task IfRangeWithCurrentDateShouldServePartialContent() [Fact] public async Task IfModifiedSinceWithPastDateShouldServePartialContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); @@ -91,7 +95,8 @@ public async Task IfModifiedSinceWithPastDateShouldServePartialContent() [Fact] public async Task IfModifiedSinceWithCurrentDateShouldReturn304() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); @@ -107,7 +112,8 @@ public async Task IfModifiedSinceWithCurrentDateShouldReturn304() [Fact] public async Task HEADIfRangeWithCurrentDateShouldReturn200Ok() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); @@ -127,7 +133,8 @@ public async Task HEADIfRangeWithCurrentDateShouldReturn200Ok() [Fact] public async Task IfRangeWithOldEtagShouldServeFullContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); req.Headers.Add("If-Range", "\"OldEtag\""); req.Headers.Add("Range", "bytes=0-10"); @@ -143,7 +150,8 @@ public async Task IfRangeWithOldEtagShouldServeFullContent() [Fact] public async Task HEADIfRangeWithOldEtagShouldServeFullContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); req.Headers.Add("If-Range", "\"OldEtag\""); req.Headers.Add("Range", "bytes=0-10"); @@ -159,7 +167,8 @@ public async Task HEADIfRangeWithOldEtagShouldServeFullContent() [Fact] public async Task IfRangeWithOldDateShouldServeFullContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); @@ -177,7 +186,8 @@ public async Task IfRangeWithOldDateShouldServeFullContent() [Fact] public async Task HEADIfRangeWithOldDateShouldServeFullContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); @@ -191,12 +201,13 @@ public async Task HEADIfRangeWithOldDateShouldServeFullContent() } // 14.27 If-Range - // The If-Range header SHOULD only be used together with a Range header, and MUST be ignored if the request + // The If-Range header SHOULD only be used together with a Range header, and MUST be ignored if the request // does not include a Range header, or if the server does not support the sub-range operation. [Fact] public async Task IfRangeWithoutRangeShouldServeFullContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); @@ -222,7 +233,8 @@ public async Task IfRangeWithoutRangeShouldServeFullContent() [Fact] public async Task HEADIfRangeWithoutRangeShouldServeFullContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); @@ -256,7 +268,8 @@ public async Task HEADIfRangeWithoutRangeShouldServeFullContent() [InlineData("-1001", "0-61", 62, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")] public async Task SingleValidRangeShouldServePartialContent(string range, string expectedRange, int length, string expectedData) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); req.Headers.Add("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -276,7 +289,8 @@ public async Task SingleValidRangeShouldServePartialContent(string range, string [InlineData("0-2", "0-0", 1, "A")] public async Task SingleValidRangeShouldServePartialContentSingleByteFile(string range, string expectedRange, int length, string expectedData) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/SingleByte.txt"); req.Headers.Add("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -296,7 +310,8 @@ public async Task SingleValidRangeShouldServePartialContentSingleByteFile(string [InlineData("0-2")] public async Task SingleValidRangeShouldServeRequestedRangeNotSatisfiableEmptyFile(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/Empty.txt"); req.Headers.Add("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -309,7 +324,8 @@ public async Task SingleValidRangeShouldServeRequestedRangeNotSatisfiableEmptyFi [InlineData("10-35")] public async Task HEADSingleValidRangeShouldReturnOk(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); req.Headers.Add("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -326,7 +342,8 @@ public async Task HEADSingleValidRangeShouldReturnOk(string range) [InlineData("-0")] // Suffix range must be non-zero public async Task SingleNotSatisfiableRange(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); req.Headers.TryAddWithoutValidation("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -340,7 +357,8 @@ public async Task SingleNotSatisfiableRange(string range) [InlineData("1000-1001")] // Out of range public async Task HEADSingleNotSatisfiableRangeReturnsOk(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); req.Headers.TryAddWithoutValidation("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -359,7 +377,8 @@ public async Task HEADSingleNotSatisfiableRangeReturnsOk(string range) [InlineData("a-b")] public async Task SingleInvalidRangeIgnored(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); req.Headers.TryAddWithoutValidation("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -380,7 +399,8 @@ public async Task SingleInvalidRangeIgnored(string range) [InlineData("a-b")] public async Task HEADSingleInvalidRangeIgnored(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); req.Headers.TryAddWithoutValidation("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -400,7 +420,8 @@ public async Task HEADSingleInvalidRangeIgnored(string range) [InlineData("0-0,6-6,8-8,2-2,4-4")] public async Task MultipleValidRangesShouldServeFullContent(string ranges) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); req.Headers.Add("Range", "bytes=" + ranges); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -419,7 +440,8 @@ public async Task MultipleValidRangesShouldServeFullContent(string ranges) [InlineData("2-2,0-0")] // SHOULD send in the requested order. public async Task HEADMultipleValidRangesShouldServeFullContent(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); req.Headers.Add("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); diff --git a/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs b/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs index e7c9487b8422..265ba1e16c76 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs @@ -27,7 +27,7 @@ public class StaticFileMiddlewareTests [Fact] public async Task ReturnsNotFoundWithoutWwwroot() { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -58,7 +58,7 @@ public async Task ReturnsNotFoundForBrokenSymlink() try { - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -91,7 +91,7 @@ public async Task ReturnsNotFoundIfSendFileThrows() mockSendFile.Setup(m => m.SendFileAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ThrowsAsync(new FileNotFoundException()); mockSendFile.Setup(m => m.Stream).Returns(Stream.Null); - var host = new HostBuilder() + using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder @@ -125,10 +125,11 @@ public async Task FoundFile_LastModifiedTrimsSeconds() { using (var fileProvider = new PhysicalFileProvider(AppContext.BaseDirectory)) { - var server = StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions + using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { FileProvider = fileProvider })); + using var server = host.GetTestServer(); var fileInfo = fileProvider.GetFileInfo("TestDocument.txt"); var response = await server.CreateRequest("TestDocument.txt").GetAsync(); @@ -143,13 +144,16 @@ public async Task FoundFile_LastModifiedTrimsSeconds() public async Task NullArguments() { // No exception, default provided - StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = null })); + using (await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = null }))) + { } // No exception, default provided - StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { FileProvider = null })); + using (await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { FileProvider = null }))) + { } // PathString(null) is OK. - var server = StaticFilesTestServer.Create(app => app.UseStaticFiles((string)null)); + using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles((string)null)); + using var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -177,11 +181,12 @@ private async Task FoundFile_Served(string baseUrl, string baseDir, string reque { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions + using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider })); + using var server = host.GetTestServer(); var fileInfo = fileProvider.GetFileInfo(Path.GetFileName(requestUrl)); var response = await server.CreateRequest(requestUrl).GetAsync(); var responseContent = await response.Content.ReadAsByteArrayAsync(); @@ -207,11 +212,12 @@ public async Task HeadFile_HeadersButNotBodyServed(string baseUrl, string baseDi { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions + using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider })); + using var server = host.GetTestServer(); var fileInfo = fileProvider.GetFileInfo(Path.GetFileName(requestUrl)); var response = await server.CreateRequest(requestUrl).SendAsync("HEAD"); @@ -266,11 +272,12 @@ private async Task PassesThrough(string method, string baseUrl, string baseDir, { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions + using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider })); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).SendAsync(method); Assert.Null(response.Content.Headers.LastModified); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); diff --git a/src/Middleware/StaticFiles/test/UnitTests/StaticFilesTestServer.cs b/src/Middleware/StaticFiles/test/UnitTests/StaticFilesTestServer.cs index f43c1b448fdb..8f2723745097 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/StaticFilesTestServer.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/StaticFilesTestServer.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Runtime.InteropServices; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; @@ -15,7 +16,7 @@ namespace Microsoft.AspNetCore.StaticFiles { public static class StaticFilesTestServer { - public static TestServer Create(Action configureApp, Action configureServices = null) + public static async Task Create(Action configureApp, Action configureServices = null) { Action defaultConfigureServices = services => { }; var configuration = new ConfigurationBuilder() @@ -34,8 +35,8 @@ public static TestServer Create(Action configureApp, Action .ConfigureServices(configureServices ?? defaultConfigureServices); }).Build(); - host.Start(); - return host.GetTestServer(); + await host.StartAsync(); + return host; } } } From c9bd09db6310e9cdc43796ebec374700d859fb2b Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Tue, 7 Jul 2020 15:55:10 -0700 Subject: [PATCH 20/20] rm stopasync --- .../test/UnitTests/CorsMiddlewareTests.cs | 18 ----- .../DatabaseErrorPageMiddlewareTest.cs | 8 -- .../MigrationsEndPointMiddlewareTest.cs | 12 --- .../DeveloperExceptionPageMiddlewareTest.cs | 12 --- .../test/UnitTests/ExceptionHandlerTest.cs | 14 ---- .../UnitTests/StatusCodeMiddlewareTest.cs | 6 -- .../test/HeaderPropagationIntegrationTest.cs | 8 -- ...CheckEndpointRouteBuilderExtensionsTest.cs | 4 - .../HealthCheckMiddlewareSampleTest.cs | 8 -- .../UnitTests/HealthCheckMiddlewareTests.cs | 50 ------------- .../test/HostFilteringMiddlewareTests.cs | 12 --- .../test/CertificateForwardingTest.cs | 10 --- .../test/ForwardedHeadersMiddlewareTest.cs | 48 ------------ .../test/HttpMethodOverrideMiddlewareTest.cs | 12 --- .../HttpsPolicy/test/HstsMiddlewareTests.cs | 16 ---- .../HttpsPolicy/test/HttpsPolicyTests.cs | 2 - .../test/HttpsRedirectionMiddlewareTests.cs | 18 ----- .../RouteDataRequestCultureProviderTest.cs | 6 -- .../FunctionalTests/LocalizationSampleTest.cs | 2 - .../test/FunctionalTests/LocalizationTest.cs | 2 - ...anguageHeaderRequestCultureProviderTest.cs | 8 -- .../CookieRequestCultureProviderTest.cs | 10 --- .../CustomRequestCultureProviderTest.cs | 2 - .../QueryStringRequestCultureProviderTest.cs | 16 ---- .../test/MiddlewareAnalysisTests.cs | 2 - .../test/ResponseCachingTests.cs | 73 ------------------- .../test/ResponseCompressionMiddlewareTest.cs | 32 -------- .../ModRewriteMiddlewareTest.cs | 34 --------- .../test/IISUrlRewrite/MiddleWareTests.cs | 40 ---------- .../Rewrite/test/MiddlewareTests.cs | 42 ----------- src/Middleware/Session/test/SessionTests.cs | 42 ----------- .../FunctionalTests/FallbackStaticFileTest.cs | 2 - .../StaticFileMiddlewareTests.cs | 12 --- .../UnitTests/StaticFileMiddlewareTests.cs | 6 -- 34 files changed, 589 deletions(-) diff --git a/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs b/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs index c6849f236193..bf4848307a41 100644 --- a/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs +++ b/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs @@ -62,8 +62,6 @@ public async Task CorsRequest_MatchesPolicy_OnCaseInsensitiveAccessControlReques Assert.Equal("Cross origin response", await response.Content.ReadAsStringAsync()); Assert.Equal(OriginUrl, response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault()); } - - await host.StopAsync(); } [Fact] @@ -107,8 +105,6 @@ public async Task CorsRequest_MatchPolicy_SetsResponseHeaders() Assert.Equal(OriginUrl, response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault()); Assert.Equal("AllowedHeader", response.Headers.GetValues(CorsConstants.AccessControlExposeHeaders).FirstOrDefault()); } - - await host.StopAsync(); } [Theory] @@ -158,8 +154,6 @@ public async Task PreFlight_MatchesPolicy_OnCaseInsensitiveOptionsMethod(string Assert.Single(response.Headers); Assert.Equal(OriginUrl, response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault()); } - - await host.StopAsync(); } [Fact] @@ -225,8 +219,6 @@ public async Task PreFlight_MatchesPolicy_SetsResponseHeaders() Assert.Equal(new[] { OriginUrl }, kvp.Value); }); } - - await host.StopAsync(); } [Fact] @@ -298,8 +290,6 @@ public async Task PreFlight_WithCredentialsAllowed_ReflectsRequestHeaders() Assert.Equal(new[] { OriginUrl }, kvp.Value); }); } - - await host.StopAsync(); } [Fact] @@ -383,8 +373,6 @@ public async Task CorsRequest_DoesNotMatchPolicy_DoesNotSetHeaders() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Empty(response.Headers); } - - await host.StopAsync(); } [Fact] @@ -518,8 +506,6 @@ public async Task PreFlight_MatchesDefaultPolicy_SetsResponseHeaders() Assert.Equal(new[] { OriginUrl }, kvp.Value); }); } - - await host.StopAsync(); } [Fact] @@ -579,8 +565,6 @@ public async Task CorsRequest_SetsResponseHeaders() Assert.Equal("Cross origin response", await response.Content.ReadAsStringAsync()); } - - await host.StopAsync(); } [Fact] @@ -652,8 +636,6 @@ public async Task CorsRequest_SetsResponseHeader_IfExceptionHandlerClearsRespons Assert.Equal("AllowedHeader", Assert.Single(kvp.Value)); }); } - - await host.StopAsync(); } [Fact] diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs index ee157a8168d1..2acd8258ad20 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs @@ -46,8 +46,6 @@ public async Task Successful_requests_pass_thru() Assert.Equal("Request Handled", await response.Content.ReadAsStringAsync()); Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - await host.StopAsync(); } class SuccessMiddleware @@ -83,8 +81,6 @@ public async Task Non_database_exceptions_pass_thru() await server.CreateClient().GetAsync("http://localhost/")); Assert.Equal("Exception requested from TestMiddleware", ex.Message); - - await host.StopAsync(); } class ExceptionMiddleware @@ -361,8 +357,6 @@ public async Task Customize_migrations_end_point() var content = await response.Content.ReadAsStringAsync(); Assert.Contains("req.open(\"POST\", \"" + JavaScriptEncode(migrationsEndpoint) + "\", true);", content); - - await host.StopAsync(); } } @@ -405,8 +399,6 @@ 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 diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs index 138519e60fa6..ba93e736d722 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs @@ -46,8 +46,6 @@ public async Task Non_migration_requests_pass_thru() Assert.Equal("Request Handled", await response.Content.ReadAsStringAsync()); Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - await host.StopAsync(); } class SuccessMiddleware @@ -142,8 +140,6 @@ private async Task Migration_request(bool useCustomPath) Assert.Equal("111111111111111_MigrationOne", appliedMigrations.ElementAt(0).MigrationId); Assert.Equal("222222222222222_MigrationTwo", appliedMigrations.ElementAt(1).MigrationId); } - - await host.StopAsync(); } } @@ -173,8 +169,6 @@ public async Task Context_type_not_specified() Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.StartsWith(StringsHelpers.GetResourceString("MigrationsEndPointMiddleware_NoContextType"), content); Assert.True(content.Length > 512); - - await host.StopAsync(); } [Fact] @@ -207,8 +201,6 @@ public async Task Invalid_context_type_specified() Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.StartsWith(StringsHelpers.GetResourceString("FormatMigrationsEndPointMiddleware_InvalidContextType", typeName), content); Assert.True(content.Length > 512); - - await host.StopAsync(); } [Fact] @@ -238,8 +230,6 @@ public async Task Context_not_registered_in_services() Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.StartsWith(StringsHelpers.GetResourceString("FormatMigrationsEndPointMiddleware_ContextNotRegistered", typeof(BloggingContext)), content); Assert.True(content.Length > 512); - - await host.StopAsync(); } [ConditionalFact] @@ -278,8 +268,6 @@ public async Task Exception_while_applying_migrations() Assert.StartsWith(StringsHelpers.GetResourceString("FormatMigrationsEndPointMiddleware_Exception", typeof(BloggingContextWithSnapshotThatThrows)), ex.Message); Assert.Equal("Welcome to the invalid migration!", ex.InnerException.Message); - - await host.StopAsync(); } } } diff --git a/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs b/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs index f2ae02fb4a5f..c22c9b5368b9 100644 --- a/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs +++ b/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs @@ -53,8 +53,6 @@ public async Task UnhandledErrorsWriteToDiagnosticWhenUsingExceptionPage() Assert.NotNull(listener.DiagnosticUnhandledException?.Exception); Assert.Null(listener.DiagnosticHandledException?.HttpContext); Assert.Null(listener.DiagnosticHandledException?.Exception); - - await host.StopAsync(); } [Fact] @@ -90,8 +88,6 @@ public async Task ErrorPageWithAcceptHeaderForHtmlReturnsHtml() Assert.Equal("text/html", response.Content.Headers.ContentType.MediaType); Assert.Contains(" CreateHost(Action configure, HttpMessageHandler primaryHandler, Action configureClient = null) diff --git a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs index ff9db28925fe..857b5835899f 100644 --- a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs +++ b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs @@ -86,8 +86,6 @@ public async Task MapHealthChecks_ReturnsOk() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -133,8 +131,6 @@ public async Task MapHealthChecks_WithOptions_ReturnsOk() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Custom!", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } } } diff --git a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs index 4546e0b80342..0d5d648a8734 100644 --- a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs +++ b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs @@ -32,8 +32,6 @@ public async Task BasicStartup() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -57,8 +55,6 @@ public async Task CustomWriterStartup() Assert.Equal("application/json", response.Content.Headers.ContentType.ToString()); // Ignoring the body since it contains a bunch of statistics - - await host.StopAsync(); } [Fact] @@ -81,8 +77,6 @@ public async Task LivenessProbeStartup_Liveness() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -105,8 +99,6 @@ public async Task LivenessProbeStartup_Readiness() Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Unhealthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } } } diff --git a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs index a6e17b9ddde3..9cbd0532bdac 100644 --- a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs +++ b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs @@ -68,8 +68,6 @@ public async Task IgnoresRequestThatDoesNotMatchPath() var response = await client.GetAsync("/frob"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - - await host.StopAsync(); } [Fact] // Matches based on '.Map' @@ -97,8 +95,6 @@ public async Task MatchIsCaseInsensitive() var response = await client.GetAsync("/HEALTH"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - await host.StopAsync(); } [Fact] @@ -129,8 +125,6 @@ public async Task ReturnsPlainTextStatus() Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -161,8 +155,6 @@ public async Task StatusCodeIs200IfNoChecks() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -196,8 +188,6 @@ public async Task StatusCodeIs200IfAllChecksHealthy() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -231,8 +221,6 @@ public async Task StatusCodeIs200IfCheckIsDegraded() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Degraded", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -266,8 +254,6 @@ public async Task StatusCodeIs503IfCheckIsUnhealthy() Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Unhealthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -301,8 +287,6 @@ public async Task StatusCodeIs503IfCheckHasUnhandledException() Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Unhealthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -350,8 +334,6 @@ public async Task CanUseCustomWriter() var result = await response.Content.ReadAsStringAsync(); Assert.Equal(expectedJson, result); - - await host.StopAsync(); } [Fact] @@ -387,8 +369,6 @@ public async Task NoResponseWriterReturnsEmptyBody() Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -424,8 +404,6 @@ public async Task CanSetCustomStatusCodes() Assert.Equal(HttpStatusCode.Created, response.StatusCode); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -458,8 +436,6 @@ public async Task SetsCacheHeaders() Assert.Equal("no-store, no-cache", response.Headers.CacheControl.ToString()); Assert.Equal("no-cache", response.Headers.Pragma.ToString()); Assert.Equal(new string[] { "Thu, 01 Jan 1970 00:00:00 GMT" }, response.Content.Headers.GetValues(HeaderNames.Expires)); - - await host.StopAsync(); } [Fact] @@ -495,8 +471,6 @@ public async Task CanSuppressCacheHeaders() Assert.Null(response.Headers.CacheControl); Assert.Empty(response.Headers.Pragma.ToString()); Assert.False(response.Content.Headers.Contains(HeaderNames.Expires)); - - await host.StopAsync(); } [Fact] @@ -534,8 +508,6 @@ public async Task CanFilterChecks() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -566,8 +538,6 @@ public async Task CanListenWithoutPath_AcceptsRequest() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -596,8 +566,6 @@ public async Task CanListenWithPath_AcceptsRequestWithExtraSlash() var response = await client.GetAsync("http://localhost:5001/health/"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - - await host.StopAsync(); } [Fact] @@ -628,8 +596,6 @@ public async Task CanListenWithPath_AcceptsRequestWithCaseInsensitiveMatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -658,8 +624,6 @@ public async Task CanListenWithPath_RejectsRequestWithExtraSegments() var response = await client.GetAsync("http://localhost:5001/health/detailed"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - - await host.StopAsync(); } // See: https://github.com/aspnet/Diagnostics/issues/511 @@ -697,8 +661,6 @@ public async Task CanListenWithPath_MultipleMiddleware_LeastSpecificFirst() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } // See: https://github.com/aspnet/Diagnostics/issues/511 @@ -736,8 +698,6 @@ public async Task CanListenWithPath_MultipleMiddleware_MostSpecificFirst() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -776,8 +736,6 @@ public async Task CanListenOnPort_AcceptsRequest_OnSpecifiedPort() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -816,8 +774,6 @@ public async Task CanListenOnPortWithoutPath_AcceptsRequest_OnSpecifiedPort() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -854,8 +810,6 @@ public async Task CanListenOnPort_RejectsRequest_OnOtherPort() var response = await client.GetAsync("http://localhost:5000/health"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - - await host.StopAsync(); } [Fact] @@ -900,8 +854,6 @@ public async Task CanListenOnPort_MultipleMiddleware() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] @@ -946,8 +898,6 @@ public async Task CanListenOnPort_MultipleMiddleware_DifferentPorts() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } [Fact] diff --git a/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs b/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs index 82b74a928d77..9908f9248cc9 100644 --- a/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs +++ b/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs @@ -36,8 +36,6 @@ public async Task MissingConfigThrows() await host.StartAsync(); await Assert.ThrowsAsync(() => host.GetTestServer().SendAsync(_ => { })); - - await host.StopAsync(); } [Theory] @@ -79,8 +77,6 @@ public async Task AllowsMissingHost(bool allowed, int status) var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(status, (int)response.StatusCode); - - await host.StopAsync(); } [Theory] @@ -124,8 +120,6 @@ public async Task AllowsEmptyHost(bool allowed, int status) var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(status, (int)response.StatusCode); - - await host.StopAsync(); } [Theory] @@ -177,8 +171,6 @@ public async Task AllowsSpecifiedHost(string hosturl, string allowedHost) var server = host.GetTestServer(); var response = await server.CreateRequest("/").GetAsync(); Assert.Equal(200, (int)response.StatusCode); - - await host.StopAsync(); } [Theory] @@ -231,8 +223,6 @@ public async Task RejectsMismatchedHosts(string hosturl, string allowedHost) var server = host.GetTestServer(); var response = await server.CreateRequest("/").GetAsync(); Assert.Equal(400, (int)response.StatusCode); - - await host.StopAsync(); } [Fact] @@ -277,8 +267,6 @@ public async Task SupportsDynamicOptionsReload() response = await server.CreateRequest("/").GetAsync(); Assert.Equal(200, (int)response.StatusCode); - - await host.StopAsync(); } private class ReloadableMemorySource : IConfigurationSource diff --git a/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs b/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs index 150f82f2b644..6579a17b15ca 100644 --- a/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs +++ b/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs @@ -76,8 +76,6 @@ public async Task VerifyHeaderIsUsedIfNoCertificateAlreadySet() { c.Request.Headers["X-Client-Cert"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData); }); - - await host.StopAsync(); } [Fact] @@ -117,8 +115,6 @@ public async Task VerifyHeaderOverridesCertificateEvenAlreadySet() { c.Request.Headers["X-Client-Cert"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData); }); - - await host.StopAsync(); } [Fact] @@ -157,8 +153,6 @@ public async Task VerifySettingTheAzureHeaderOnTheForwarderOptionsWorks() { c.Request.Headers["X-ARR-ClientCert"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData); }); - - await host.StopAsync(); } [Fact] @@ -197,8 +191,6 @@ public async Task VerifyACustomHeaderFailsIfTheHeaderIsNotPresent() { c.Request.Headers["not-the-right-header"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData); }); - - await host.StopAsync(); } [Fact] @@ -237,8 +229,6 @@ public async Task VerifyArrHeaderEncodedCertFailsOnBadEncoding() { c.Request.Headers["X-Client-Cert"] = "OOPS" + Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData); }); - - await host.StopAsync(); } private static class Certificates diff --git a/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs b/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs index 6e4d8d9b71c4..86d56585218f 100644 --- a/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs +++ b/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs @@ -49,8 +49,6 @@ public async Task XForwardedForDefaultSettingsChangeRemoteIpAndPort() Assert.False(context.Request.Headers.ContainsKey("X-Original-For")); // Should have been consumed and removed Assert.False(context.Request.Headers.ContainsKey("X-Forwarded-For")); - - await host.StopAsync(); } [Theory] @@ -88,8 +86,6 @@ public async Task XForwardedForFirstValueIsInvalid(int limit, string header, str Assert.False(context.Request.Headers.ContainsKey("X-Original-For")); Assert.True(context.Request.Headers.ContainsKey("X-Forwarded-For")); Assert.Equal(header, context.Request.Headers["X-Forwarded-For"]); - - await host.StopAsync(); } [Theory] @@ -146,8 +142,6 @@ public async Task XForwardedForForwardLimit(int limit, string header, string exp Assert.Equal(expectedIp, context.Connection.RemoteIpAddress.ToString()); Assert.Equal(expectedPort, context.Connection.RemotePort); Assert.Equal(remainingHeader, context.Request.Headers["X-Forwarded-For"].ToString()); - - await host.StopAsync(); } [Theory] @@ -197,8 +191,6 @@ public async Task XForwardedForLoopback(string originalIp, bool expectForwarded) Assert.Equal(99, context.Connection.RemotePort); Assert.False(context.Request.Headers.ContainsKey("X-Original-For")); } - - await host.StopAsync(); } [Theory] @@ -260,8 +252,6 @@ public async Task XForwardedForForwardKnownIps(int limit, string header, string Assert.Equal(expectedIp, context.Connection.RemoteIpAddress.ToString()); Assert.Equal(expectedPort, context.Connection.RemotePort); - - await host.StopAsync(); } [Fact] @@ -291,8 +281,6 @@ public async Task XForwardedForOverrideBadIpDoesntChangeRemoteIp() }); Assert.Null(context.Connection.RemoteIpAddress); - - await host.StopAsync(); } [Fact] @@ -322,8 +310,6 @@ public async Task XForwardedHostOverrideChangesRequestHost() }); Assert.Equal("testhost", context.Request.Host.ToString()); - - await host.StopAsync(); } public static TheoryData HostHeaderData @@ -395,8 +381,6 @@ await server.SendAsync(c => c.Request.Headers["X-Forwarded-Host"] = hostHeader; }); Assert.True(assertsExecuted); - - await host.StopAsync(); } public static TheoryData HostHeaderInvalidData @@ -482,8 +466,6 @@ await server.SendAsync(c => c.Request.Headers["X-Forwarded-Host"] = hostHeader; }); Assert.True(assertsExecuted); - - await host.StopAsync(); } [Theory] @@ -534,8 +516,6 @@ public async Task XForwardedHostAllowsSpecifiedHost(string hostHeader, string al ctx.Request.Headers["X-forwarded-Host"] = hostHeader; }); Assert.True(assertsExecuted); - - await host.StopAsync(); } [Theory] @@ -587,8 +567,6 @@ public async Task XForwardedHostFailsMismatchedHosts(string hostHeader, string a ctx.Request.Headers["X-forwarded-Host"] = hostHeader; }); Assert.True(assertsExecuted); - - await host.StopAsync(); } [Fact] @@ -625,8 +603,6 @@ public async Task XForwardedHostStopsAtFirstUnspecifiedHost() ctx.Request.Headers["X-forwarded-Host"] = "stuff:523, bar.foo.com:432, bar.com:80"; }); Assert.True(assertsExecuted); - - await host.StopAsync(); } [Theory] @@ -664,8 +640,6 @@ public async Task XForwardedProtoOverrideChangesRequestProtocol(int limit, strin }); Assert.Equal(expected, context.Request.Scheme); - - await host.StopAsync(); } public static TheoryData ProtoHeaderData @@ -719,8 +693,6 @@ await server.SendAsync(c => c.Request.Headers["X-Forwarded-Proto"] = scheme; }); Assert.True(assertsExecuted); - - await host.StopAsync(); } public static TheoryData ProtoHeaderInvalidData @@ -778,8 +750,6 @@ await server.SendAsync(c => c.Request.Headers["X-Forwarded-Proto"] = scheme; }); Assert.True(assertsExecuted); - - await host.StopAsync(); } [Theory] @@ -820,8 +790,6 @@ public async Task XForwardedProtoOverrideLimitedByXForwardedForCount(int limit, }); Assert.Equal(expected, context.Request.Scheme); - - await host.StopAsync(); } [Theory] @@ -864,8 +832,6 @@ public async Task XForwardedProtoOverrideCanBeIndependentOfXForwardedForCount(in }); Assert.Equal(expected, context.Request.Scheme); - - await host.StopAsync(); } [Theory] @@ -917,8 +883,6 @@ public async Task XForwardedProtoOverrideLimitedByLoopback(string protoHeader, s }); Assert.Equal(expected, context.Request.Scheme); - - await host.StopAsync(); } [Fact] @@ -962,8 +926,6 @@ public async Task AllForwardsEnabledChangeRequestRemoteIpHostandProtocol() Assert.Equal("11.111.111.11", context.Connection.RemoteIpAddress.ToString()); Assert.Equal("testhost", context.Request.Host.ToString()); Assert.Equal("Protocol", context.Request.Scheme); - - await host.StopAsync(); } [Fact] @@ -997,8 +959,6 @@ public async Task AllOptionsDisabledRequestDoesntChange() Assert.Null(context.Connection.RemoteIpAddress); Assert.Equal("localhost", context.Request.Host.ToString()); Assert.Equal("http", context.Request.Scheme); - - await host.StopAsync(); } [Fact] @@ -1031,8 +991,6 @@ public async Task PartiallyEnabledForwardsPartiallyChangesRequest() Assert.Equal("11.111.111.11", context.Connection.RemoteIpAddress.ToString()); Assert.Equal("localhost", context.Request.Host.ToString()); Assert.Equal("Protocol", context.Request.Scheme); - - await host.StopAsync(); } [Theory] @@ -1084,8 +1042,6 @@ public async Task XForwardForIPv4ToIPv6Mapping(string forHeader, string knownPro }); Assert.Equal(expectedRemoteIp, context.Connection.RemoteIpAddress.ToString()); - - await host.StopAsync(); } [Theory] @@ -1126,8 +1082,6 @@ public async Task ForwardersWithDIOptionsRunsOnce(int limit, string header, stri Assert.Equal(expectedScheme, context.Request.Scheme); Assert.Equal(remainingHeader, context.Request.Headers["X-Forwarded-Proto"].ToString()); - - await host.StopAsync(); } [Theory] @@ -1165,8 +1119,6 @@ public async Task ForwardersWithDirectOptionsRunsTwice(int limit, string header, Assert.Equal(expectedScheme, context.Request.Scheme); Assert.Equal(remainingHeader, context.Request.Headers["X-Forwarded-Proto"].ToString()); - - await host.StopAsync(); } } } diff --git a/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs b/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs index 363f57aa4536..d36cc29c77a8 100644 --- a/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs +++ b/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs @@ -43,8 +43,6 @@ public async Task XHttpMethodOverrideHeaderAvaiableChangesRequestMethod() req.Headers.Add("X-Http-Method-Override", "DELETE"); await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); - - await host.StopAsync(); } [Fact] @@ -75,8 +73,6 @@ public async Task XHttpMethodOverrideHeaderUnavaiableDoesntChangeRequestMethod() var req = new HttpRequestMessage(HttpMethod.Post, ""); await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); - - await host.StopAsync(); } [Fact] @@ -107,8 +103,6 @@ public async Task XHttpMethodOverrideFromGetRequestDoesntChangeMethodType() var req = new HttpRequestMessage(HttpMethod.Get, ""); await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); - - await host.StopAsync(); } @@ -149,8 +143,6 @@ public async Task FormFieldAvailableChangesRequestMethod() await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); - - await host.StopAsync(); } [Fact] @@ -189,8 +181,6 @@ public async Task FormFieldUnavailableDoesNotChangeRequestMethod() await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); - - await host.StopAsync(); } [Fact] @@ -230,8 +220,6 @@ public async Task FormFieldEmptyDoesNotChangeRequestMethod() await server.CreateClient().SendAsync(req); Assert.True(assertsExecuted); - - await host.StopAsync(); } } } diff --git a/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs b/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs index c74dfc8388e0..232f2e474803 100644 --- a/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs +++ b/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs @@ -55,8 +55,6 @@ public async Task SetOptionsWithDefault_SetsMaxAgeToCorrectValue() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("max-age=2592000", response.Headers.GetValues(HeaderNames.StrictTransportSecurity).FirstOrDefault()); - - await host.StopAsync(); } [Theory] @@ -103,8 +101,6 @@ public async Task SetOptionsThroughConfigure_SetsHeaderCorrectly(int maxAge, boo Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expected, response.Headers.GetValues(HeaderNames.StrictTransportSecurity).FirstOrDefault()); - - await host.StopAsync(); } [Theory] @@ -151,8 +147,6 @@ public async Task SetOptionsThroughHelper_SetsHeaderCorrectly(int maxAge, bool i Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expected, response.Headers.GetValues(HeaderNames.StrictTransportSecurity).FirstOrDefault()); - - await host.StopAsync(); } [Theory] @@ -205,8 +199,6 @@ public async Task DefaultExcludesCommonLocalhostDomains_DoesNotSetHstsHeader(str var message = logMessages.Single(); Assert.Equal(LogLevel.Debug, message.LogLevel); Assert.Equal($"The host '{hostUrl}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true); - - await host.StopAsync(); } [Theory] @@ -262,8 +254,6 @@ public async Task AllowLocalhostDomainsIfListIsReset_SetHstsHeader(string hostUr var message = logMessages.Single(); Assert.Equal(LogLevel.Trace, message.LogLevel); Assert.Equal("Adding HSTS header to response.", message.State.ToString()); - - await host.StopAsync(); } [Theory] @@ -319,8 +309,6 @@ public async Task AddExcludedDomains_DoesNotAddHstsHeader(string hostUrl) var message = logMessages.Single(); Assert.Equal(LogLevel.Debug, message.LogLevel); Assert.Equal($"The host '{hostUrl}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true); - - await host.StopAsync(); } [Fact] @@ -368,8 +356,6 @@ public async Task WhenRequestIsInsecure_DoesNotAddHstsHeader() var message = logMessages.Single(); Assert.Equal(LogLevel.Debug, message.LogLevel); Assert.Equal("The request is insecure. Skipping HSTS header.", message.State.ToString()); - - await host.StopAsync(); } [Fact] @@ -416,8 +402,6 @@ public async Task WhenRequestIsSecure_AddsHstsHeader() var message = logMessages.Single(); Assert.Equal(LogLevel.Trace, message.LogLevel); Assert.Equal("Adding HSTS header to response.", message.State.ToString()); - - await host.StopAsync(); } } } diff --git a/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs b/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs index b187f02af3fd..d246c6255f01 100644 --- a/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs +++ b/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs @@ -81,8 +81,6 @@ public async Task SetsBothHstsAndHttpsRedirection_RedirectOnFirstRequest_HstsOnS response = await client.SendAsync(request); Assert.Equal(expectedHstsHeader, response.Headers.GetValues(HeaderNames.StrictTransportSecurity).FirstOrDefault()); - - await host.StopAsync(); } } } diff --git a/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs b/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs index cb3df2f789f2..c2a4e8e1caca 100644 --- a/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs +++ b/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs @@ -66,8 +66,6 @@ public async Task SetOptions_NotEnabledByDefault() var message = logMessages.Single(); Assert.Equal(LogLevel.Warning, message.LogLevel); Assert.Equal("Failed to determine the https port for redirect.", message.State.ToString()); - - await host.StopAsync(); } [Theory] @@ -124,8 +122,6 @@ public async Task SetOptions_SetStatusCodeHttpsPort(int statusCode, int? httpsPo var message = logMessages.Single(); Assert.Equal(LogLevel.Debug, message.LogLevel); Assert.Equal($"Redirecting to '{expected}'.", message.State.ToString()); - - await host.StopAsync(); } [Theory] @@ -182,8 +178,6 @@ public async Task SetOptionsThroughHelperMethod_SetStatusCodeAndHttpsPort(int st var message = logMessages.Single(); Assert.Equal(LogLevel.Debug, message.LogLevel); Assert.Equal($"Redirecting to '{expectedUrl}'.", message.State.ToString()); - - await host.StopAsync(); } [Theory] @@ -238,8 +232,6 @@ public async Task SetHttpsPortEnvironmentVariableAndServerFeature_ReturnsCorrect var response = await client.SendAsync(request); Assert.Equal(expectedUrl, response.Headers.Location.ToString()); - - await host.StopAsync(); } [Fact] @@ -291,8 +283,6 @@ public async Task SetServerAddressesFeature_SingleHttpsAddress_Success() message = logMessages.Skip(1).First(); Assert.Equal(LogLevel.Debug, message.LogLevel); Assert.Equal("Redirecting to 'https://localhost:5050/'.", message.State.ToString()); - - await host.StopAsync(); } [Fact] @@ -343,8 +333,6 @@ public async Task SetServerAddressesFeature_MultipleHttpsAddresses_LogsAndFailsT Assert.Equal(LogLevel.Warning, message.LogLevel); Assert.Equal("Cannot determine the https port from IServerAddressesFeature, multiple values were found. " + "Please set the desired port explicitly on HttpsRedirectionOptions.HttpsPort.", message.State.ToString()); - - await host.StopAsync(); } [Fact] @@ -398,8 +386,6 @@ public async Task SetServerAddressesFeature_MultipleHttpsAddressesWithSamePort_S message = logMessages.Skip(1).First(); Assert.Equal(LogLevel.Debug, message.LogLevel); Assert.Equal("Redirecting to 'https://localhost:5050/'.", message.State.ToString()); - - await host.StopAsync(); } [Fact] @@ -442,8 +428,6 @@ public async Task NoServerAddressFeature_DoesNotThrow_DoesNotRedirect() var message = logMessages.First(); Assert.Equal(LogLevel.Warning, message.LogLevel); Assert.Equal("Failed to determine the https port for redirect.", message.State.ToString()); - - await host.StopAsync(); } [Fact] @@ -488,8 +472,6 @@ public async Task SetNullAddressFeature_DoesNotThrow() var message = logMessages.First(); Assert.Equal(LogLevel.Warning, message.LogLevel); Assert.Equal("Failed to determine the https port for redirect.", message.State.ToString()); - - await host.StopAsync(); } } } diff --git a/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs b/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs index eb00fb27e9c7..9aa142ce55a9 100644 --- a/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs +++ b/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs @@ -90,8 +90,6 @@ public async Task GetCultureInfo_FromRouteData( var data = await response.Content.ReadAsStringAsync(); Assert.Equal($"{expectedCulture},{expectedUICulture}", data); } - - await host.StopAsync(); } [Fact] @@ -138,8 +136,6 @@ public async Task GetDefaultCultureInfo_IfCultureKeysAreMissing() var data = await response.Content.ReadAsStringAsync(); Assert.Equal("en-US,en-US", data); } - - await host.StopAsync(); } [Theory] @@ -216,8 +212,6 @@ public async Task GetCultureInfo_FromRouteData_WithCustomKeys( var data = await response.Content.ReadAsStringAsync(); Assert.Equal($"{expectedCulture},{expectedUICulture}", data); } - - await host.StopAsync(); } } } diff --git a/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs b/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs index c3424193f2ad..f264be58e152 100644 --- a/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs +++ b/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs @@ -43,8 +43,6 @@ public async Task LocalizationSampleSmokeTest() // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Contains("

Bonjour

", await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } } } diff --git a/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs b/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs index 344746231240..7c2cf51063e7 100644 --- a/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs +++ b/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs @@ -119,8 +119,6 @@ private async Task RunTest(Type startupType, string culture, string expected) Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expected, await response.Content.ReadAsStringAsync()); - - await host.StopAsync(); } } } diff --git a/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs index 0cbf91709ce3..d1e6f789f0d0 100644 --- a/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs @@ -54,8 +54,6 @@ public async Task GetFallbackLanguage_ReturnsFirstNonNullCultureFromSupportedCul var response = await client.GetAsync(string.Empty); Assert.Equal(3, count); } - - await host.StopAsync(); } [Fact] @@ -96,8 +94,6 @@ public async Task GetFallbackLanguage_ReturnsFromSupportedCulture_AcceptLanguage var count = client.DefaultRequestHeaders.AcceptLanguage.Count; var response = await client.GetAsync(string.Empty); } - - await host.StopAsync(); } [Fact] @@ -139,8 +135,6 @@ public async Task GetFallbackLanguage_ReturnsDefault_AcceptLanguageListDoesnotCo var response = await client.GetAsync(string.Empty); Assert.Equal(3, count); } - - await host.StopAsync(); } [Fact] @@ -187,8 +181,6 @@ public async Task OmitDefaultRequestCultureShouldNotThrowNullReferenceException_ var response = await client.GetAsync(string.Empty); Assert.Equal(3, count); } - - await host.StopAsync(); } } } diff --git a/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs index 524cab81ef3e..6e5bffcb3d9f 100644 --- a/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs @@ -70,8 +70,6 @@ public async Task GetCultureInfoFromPersistentCookie() var response = await client.GetAsync(string.Empty); Assert.Equal("c=ar-SA|uic=ar-SA", value); } - - await host.StopAsync(); } [Fact] @@ -121,8 +119,6 @@ public async Task GetDefaultCultureInfoIfCultureKeysAreMissingOrInvalid() client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue("Preferences", "uic=ar-SA").ToString()); var response = await client.GetAsync(string.Empty); } - - await host.StopAsync(); } [Fact] @@ -170,8 +166,6 @@ public async Task GetDefaultCultureInfoIfCookieDoesNotExist() var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); } - - await host.StopAsync(); } [Fact] @@ -232,8 +226,6 @@ public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedCultures( var write = Assert.Single(sink.Writes); Assert.Equal(LogLevel.Debug, write.LogLevel); Assert.Equal(expectedMessage, write.State.ToString()); - - await host.StopAsync(); } [Fact] @@ -293,8 +285,6 @@ public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedUICulture var write = Assert.Single(sink.Writes); Assert.Equal(LogLevel.Debug, write.LogLevel); Assert.Equal(expectedMessage, write.State.ToString()); - - await host.StopAsync(); } } } diff --git a/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs index 526cea685483..2f5c2fb353fd 100644 --- a/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs @@ -63,8 +63,6 @@ public async Task CustomRequestCultureProviderThatGetsCultureInfoFromUrl() var client = server.CreateClient(); var response = await client.GetAsync("/ar/page"); } - - await host.StopAsync(); } private string GetCultureInfoFromUrl(HttpContext context, IList supportedCultures) diff --git a/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs index 0b3ba6ab998b..6284e1c022d4 100644 --- a/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs @@ -55,8 +55,6 @@ public async Task GetCultureInfoFromQueryString() var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-SA&ui-culture=ar-YE"); } - - await host.StopAsync(); } [Fact] @@ -91,8 +89,6 @@ public async Task GetDefaultCultureInfoIfCultureKeysAreMissing() var client = server.CreateClient(); var response = await client.GetAsync("/page"); } - - await host.StopAsync(); } [Fact] @@ -134,8 +130,6 @@ public async Task GetDefaultCultureInfoIfCultureIsInSupportedCultureList() var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-XY&ui-culture=ar-SA"); } - - await host.StopAsync(); } [Fact] @@ -177,8 +171,6 @@ public async Task GetDefaultCultureInfoIfUICultureIsNotInSupportedList() var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-SA&ui-culture=ar-XY"); } - - await host.StopAsync(); } [Fact] @@ -221,8 +213,6 @@ public async Task GetSameCultureInfoIfCultureKeyIsMissing() var client = server.CreateClient(); var response = await client.GetAsync("/page?ui-culture=ar-SA"); } - - await host.StopAsync(); } [Fact] @@ -265,8 +255,6 @@ public async Task GetSameCultureInfoIfUICultureKeyIsMissing() var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-SA"); } - - await host.StopAsync(); } [Fact] @@ -314,8 +302,6 @@ public async Task GetCultureInfoFromQueryStringWithCustomKeys() var client = server.CreateClient(); var response = await client.GetAsync("/page?c=ar-SA&uic=ar-YE"); } - - await host.StopAsync(); } [Fact] @@ -364,8 +350,6 @@ public async Task GetTheRightCultureInfoRegardlessOfCultureNameCasing() var client = server.CreateClient(); var response = await client.GetAsync("/page?c=FR&uic=FR"); } - - await host.StopAsync(); } } } diff --git a/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs b/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs index b6df216d6957..4bf4f4eaab69 100644 --- a/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs +++ b/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs @@ -57,8 +57,6 @@ public async Task ExceptionWrittenToDiagnostics() // reversed "Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware" Assert.Equal(1, listener.MiddlewareFinished.Count); Assert.Equal("Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware", listener.MiddlewareFinished[0]); - - await host.StopAsync(); } } } diff --git a/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs b/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs index afd2a860f4af..9a56152b8651 100644 --- a/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs +++ b/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs @@ -34,8 +34,6 @@ public async Task ServesCachedContent_IfAvailable(string method) await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -60,8 +58,6 @@ public async Task ServesFreshContent_IfNotAvailable(string method) await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -84,8 +80,6 @@ public async Task ServesFreshContent_Post() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -108,8 +102,6 @@ public async Task ServesFreshContent_Head_Get() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -132,7 +124,6 @@ public async Task ServesFreshContent_Get_Head() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - await host.StopAsync(); } } @@ -166,8 +157,6 @@ public async Task ServesFreshContent_If_CacheControlNoCache(string method) await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -201,8 +190,6 @@ public async Task ServesFreshContent_If_PragmaNoCache(string method) await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -227,8 +214,6 @@ public async Task ServesCachedContent_If_PathCasingDiffers(string method) await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -253,8 +238,6 @@ public async Task ServesFreshContent_If_ResponseExpired(string method) await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -280,8 +263,6 @@ public async Task ServesFreshContent_If_Authorization_HeaderExists(string method await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -305,8 +286,6 @@ public async Task ServesCachedContent_IfVaryHeader_Matches() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -331,8 +310,6 @@ public async Task ServesFreshContent_IfVaryHeader_Mismatches() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -355,8 +332,6 @@ public async Task ServesCachedContent_IfVaryQueryKeys_Matches() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -379,8 +354,6 @@ public async Task ServesCachedContent_IfVaryQueryKeysExplicit_Matches_QueryKeyCa await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -403,8 +376,6 @@ public async Task ServesCachedContent_IfVaryQueryKeyStar_Matches_QueryKeyCaseIns await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -427,8 +398,6 @@ public async Task ServesCachedContent_IfVaryQueryKeyExplicit_Matches_OrderInsens await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -451,8 +420,6 @@ public async Task ServesCachedContent_IfVaryQueryKeyStar_Matches_OrderInsensitiv await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -475,8 +442,6 @@ public async Task ServesFreshContent_IfVaryQueryKey_Mismatches() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -499,8 +464,6 @@ public async Task ServesFreshContent_IfVaryQueryKeyExplicit_Mismatch_QueryKeyCas await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -523,8 +486,6 @@ public async Task ServesFreshContent_IfVaryQueryKeyStar_Mismatch_QueryKeyValueCa await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -551,8 +512,6 @@ public async Task ServesFreshContent_IfRequestRequirements_NotMet() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -580,8 +539,6 @@ public async Task Serves504_IfOnlyIfCachedHeader_IsSpecified() initialResponse.EnsureSuccessStatusCode(); Assert.Equal(System.Net.HttpStatusCode.GatewayTimeout, subsequentResponse.StatusCode); } - - await host.StopAsync(); } } @@ -604,8 +561,6 @@ public async Task ServesFreshContent_IfSetCookie_IsSpecified() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -632,8 +587,6 @@ public async Task ServesCachedContent_IfSubsequentRequestContainsNoStore() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -660,8 +613,6 @@ public async Task ServesFreshContent_IfInitialRequestContainsNoStore() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -684,8 +635,6 @@ public async Task ServesFreshContent_IfInitialResponseContainsNoStore() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -716,8 +665,6 @@ public async Task Serves304_IfIfModifiedSince_Satisfied() Assert.Equal(System.Net.HttpStatusCode.NotModified, subsequentResponse.StatusCode); Assert304Headers(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -741,8 +688,6 @@ public async Task ServesCachedContent_IfIfModifiedSince_NotSatisfied() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -773,8 +718,6 @@ public async Task Serves304_IfIfNoneMatch_Satisfied() Assert.Equal(System.Net.HttpStatusCode.NotModified, subsequentResponse.StatusCode); Assert304Headers(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -798,8 +741,6 @@ public async Task ServesCachedContent_IfIfNoneMatch_NotSatisfied() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -825,8 +766,6 @@ public async Task ServesCachedContent_IfBodySize_IsCacheable() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -852,8 +791,6 @@ public async Task ServesFreshContent_IfBodySize_IsNotCacheable() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -879,8 +816,6 @@ public async Task ServesFreshContent_CaseSensitivePaths_IsNotCacheable() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -907,8 +842,6 @@ public async Task ServesCachedContent_WithoutReplacingCachedVaryBy_OnCacheMiss() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -944,8 +877,6 @@ public async Task ServesFreshContent_IfCachedVaryByUpdated_OnCacheMiss() await AssertFreshResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -981,8 +912,6 @@ public async Task ServesCachedContent_IfCachedVaryByNotUpdated_OnCacheMiss() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } @@ -1005,8 +934,6 @@ public async Task ServesCachedContent_IfAvailable_UsingHead_WithContentLength() await AssertCachedResponseAsync(initialResponse, subsequentResponse); } - - await host.StopAsync(); } } diff --git a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs index 3f4833335da7..ee04190af9f1 100644 --- a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs +++ b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs @@ -168,8 +168,6 @@ public async Task GZipCompressionProvider_OptionsSetInDI_Compress() var response = await client.SendAsync(request); CheckResponseCompressed(response, expectedBodyLength: 133, expectedEncoding: "gzip"); - - await host.StopAsync(); } [Theory] @@ -328,8 +326,6 @@ public async Task NoBody_NotCompressed(string contentType) var response = await client.SendAsync(request); CheckResponseNotCompressed(response, expectedBodyLength: 0, sendVaryHeader: false); - - await host.StopAsync(); } [Fact] @@ -480,8 +476,6 @@ public async Task Request_Https_CompressedIfEnabled(bool enableHttps, int expect { AssertLog(logMessages.Skip(1).Single(), LogLevel.Debug, "No response compression available for HTTPS requests. See ResponseCompressionOptions.EnableForHttps."); } - - await host.StopAsync(); } [Theory] @@ -545,8 +539,6 @@ public async Task Request_Https_CompressedIfOptIn(HttpsCompressionMode mode, int { AssertLog(logMessages.Skip(1).Single(), LogLevel.Debug, "No response compression available for HTTPS requests. See ResponseCompressionOptions.EnableForHttps."); } - - await host.StopAsync(); } [Theory] @@ -610,8 +602,6 @@ public async Task Request_Https_NotCompressedIfOptOut(HttpsCompressionMode mode, { AssertCompressedWithLog(logMessages, "gzip"); } - - await host.StopAsync(); } [Theory] @@ -658,8 +648,6 @@ public async Task FlushHeaders_SendsHeaders_Compresses(string encoding, int expe await response.Content.LoadIntoBufferAsync(); CheckResponseCompressed(response, expectedBodyLength, encoding); - - await host.StopAsync(); } [Theory] @@ -705,8 +693,6 @@ public async Task FlushAsyncHeaders_SendsHeaders_Compresses(string encoding, int await response.Content.LoadIntoBufferAsync(); CheckResponseCompressed(response, expectedBodyLength, encoding); - - await host.StopAsync(); } [Theory] @@ -766,8 +752,6 @@ public async Task FlushBody_CompressesAndFlushes(string encoding) read = await body.ReadAsync(new byte[100], 0, 100); Assert.True(read > 0); - - await host.StopAsync(); } [Theory] @@ -821,8 +805,6 @@ public async Task FlushAsyncBody_CompressesAndFlushes(string encoding) read = await body.ReadAsync(new byte[100], 0, 100); Assert.True(read > 0); - - await host.StopAsync(); } [Theory] @@ -893,8 +875,6 @@ public async Task TrickleWriteAndFlush_FlushesEachWrite(string encoding) signal.SetResult(0); } - - await host.StopAsync(); } [Theory] @@ -959,8 +939,6 @@ public async Task TrickleWriteAndFlushAsync_FlushesEachWrite(string encoding) signal.SetResult(0); } - - await host.StopAsync(); } [Fact] @@ -1011,8 +989,6 @@ public async Task SendFileAsync_DifferentContentType_NotBypassed() CheckResponseNotCompressed(response, expectedBodyLength: 1024, sendVaryHeader: false); Assert.True(fakeSendFile.SendFileInvoked); - - await host.StopAsync(); } [Fact] @@ -1063,8 +1039,6 @@ public async Task SendFileAsync_FirstWrite_CompressesAndFlushes() CheckResponseCompressed(response, expectedBodyLength: 34, expectedEncoding: "gzip"); Assert.False(fakeSendFile.SendFileInvoked); - - await host.StartAsync(); } [Fact] @@ -1115,8 +1089,6 @@ public async Task SendFileAsync_AfterFirstWrite_CompressesAndFlushes() CheckResponseCompressed(response, expectedBodyLength: 46, expectedEncoding: "gzip"); Assert.False(fakeSendFile.SendFileInvoked); - - await host.StopAsync(); } [Theory] @@ -1175,8 +1147,6 @@ public async Task Dispose_SyncWriteOrFlushNotCalled(string encoding) read = await body.ReadAsync(new byte[100], 0, 100); Assert.True(read > 0); - - await host.StopAsync(); } private async Task<(HttpResponseMessage, List)> InvokeMiddleware( @@ -1227,8 +1197,6 @@ public async Task Dispose_SyncWriteOrFlushNotCalled(string encoding) var response = await client.SendAsync(request); - await host.StopAsync(); - return (response, sink.Writes.ToList()); } diff --git a/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs b/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs index 2c566dd4f5e0..003d5f5f993d 100644 --- a/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs +++ b/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs @@ -39,8 +39,6 @@ public async Task Invoke_RewritePathWhenMatching() var response = await server.CreateClient().GetStringAsync("/hey/hello"); Assert.Equal("/hello", response); - - await host.StopAsync(); } [Fact] @@ -67,8 +65,6 @@ public async Task Invoke_RewritePathTerminatesOnFirstSuccessOfRule() var response = await server.CreateClient().GetStringAsync("/hey/hello"); Assert.Equal("/hello", response); - - await host.StopAsync(); } [Fact] @@ -95,8 +91,6 @@ public async Task Invoke_RewritePathDoesNotTerminateOnFirstSuccessOfRule() var response = await server.CreateClient().GetStringAsync("/hey/hello"); Assert.Equal("/what", response); - - await host.StopAsync(); } [Fact] @@ -122,8 +116,6 @@ public async Task Invoke_ShouldIgnoreComments() var response = await server.CreateClient().GetStringAsync("/hey/hello"); Assert.Equal("/hey/hello", response); - - await host.StopAsync(); } [Fact] @@ -149,8 +141,6 @@ public async Task Invoke_ShouldRewriteHomepage() var response = await server.CreateClient().GetStringAsync("http://www.foo.org/"); Assert.Equal("/homepage.html", response); - - await host.StopAsync(); } [Fact] @@ -176,8 +166,6 @@ public async Task Invoke_ShouldIgnorePorts() var response = await server.CreateClient().GetStringAsync("http://www.foo.org:42/"); Assert.Equal("/homepage.html", response); - - await host.StopAsync(); } [Fact] @@ -203,8 +191,6 @@ public async Task Invoke_HandleNegatedRewriteRules() var response = await server.CreateClient().GetStringAsync("http://www.foo.org/"); Assert.Equal("/", response); - - await host.StopAsync(); } [Theory] @@ -232,8 +218,6 @@ public async Task Invoke_BackReferencesShouldBeApplied(string url, string rule, var response = await server.CreateClient().GetStringAsync(url); Assert.Equal(expected, response); - - await host.StopAsync(); } [Theory] @@ -265,8 +249,6 @@ public async Task Invoke_ShouldHandleFlagNoCase(string url, string rule, string var response = await server.CreateClient().GetStringAsync(url); Assert.Equal(expected, response); - - await host.StopAsync(); } [Fact] @@ -293,8 +275,6 @@ public async Task Invoke_CheckFullUrlWithOnlyPath() var response = await server.CreateClient().GetStringAsync("http://www.foo.org/blog/2016-jun"); Assert.Equal(@"/blog/2016-jun/", response); - - await host.StopAsync(); } [Fact] @@ -321,8 +301,6 @@ public async Task Invoke_CheckFullUrlWithUFlag() var response = await server.CreateClient().GetStringAsync("http://www.foo.org/blog/2016-jun"); Assert.Equal(@"http://www.example.com/blog/2016-jun/", response); - - await host.StopAsync(); } [Fact] @@ -349,8 +327,6 @@ public async Task Invoke_CheckModFileConditions() var response = await server.CreateClient().GetStringAsync("http://www.foo.org/blog/2016-jun"); Assert.Equal(@"http://www.example.com/blog/2016-jun/", response); - - await host.StopAsync(); } [Theory] @@ -379,8 +355,6 @@ public async Task Invoke_EnsureHttps(string input) Assert.Equal(response.StatusCode, (HttpStatusCode)301); Assert.Equal(@"https://www.example.com/foo/", response.Headers.Location.AbsoluteUri); - - await host.StopAsync(); } [Theory] @@ -409,8 +383,6 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRedirectLocationHasForwa Assert.Equal(HttpStatusCode.MovedPermanently, response.StatusCode); Assert.Equal("/", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Theory] @@ -437,8 +409,6 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRewriteHasForwardSlash(s var response = await server.CreateClient().GetStringAsync(input); Assert.Equal("/", response); - - await host.StopAsync(); } [Fact] @@ -467,8 +437,6 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertLocationHeaderContainsPa var response = await server.CreateClient().GetAsync(""); Assert.Equal("/foo", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -498,8 +466,6 @@ public async Task CapturedVariablesInConditionsArePreservedToRewriteRule() var response = await server.CreateClient().GetAsync("/home?report_id=123"); Assert.Equal("http://localhost:80/home/report/123", response.Headers.Location.OriginalString); - - await host.StopAsync(); } } } diff --git a/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs b/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs index b0f2ce5233bd..35e4958cb29d 100644 --- a/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs +++ b/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs @@ -53,8 +53,6 @@ public async Task Invoke_RedirectPathToPathAndQuery() var response = await server.CreateClient().GetAsync("article/10/hey"); Assert.Equal("/article.aspx?id=10&title=hey", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -87,8 +85,6 @@ public async Task Invoke_RewritePathToPathAndQuery() var response = await server.CreateClient().GetStringAsync("/article/10/hey"); Assert.Equal("/article.aspx?id=10&title=hey", response); - - await host.StopAsync(); } [Fact] @@ -125,8 +121,6 @@ public async Task Invoke_RewriteBasedOnQueryStringParameters() var response = await server.CreateClient().GetStringAsync("page.asp?p2=321&p1=123"); Assert.Equal("/newpage.aspx?param1=123¶m2=321", response); - - await host.StopAsync(); } [Fact] @@ -159,8 +153,6 @@ public async Task Invoke_RedirectToLowerCase() var response = await server.CreateClient().GetAsync("HElLo"); Assert.Equal("/hello", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -196,8 +188,6 @@ public async Task Invoke_RedirectRemoveTrailingSlash() var response = await server.CreateClient().GetAsync("hey/hello/"); Assert.Equal("/hey/hello", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -233,8 +223,6 @@ public async Task Invoke_RedirectAddTrailingSlash() var response = await server.CreateClient().GetAsync("hey/hello"); Assert.Equal("/hey/hello/", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -269,8 +257,6 @@ public async Task Invoke_RedirectToHttps() var response = await server.CreateClient().GetAsync(new Uri("http://example.com")); Assert.Equal("https://example.com/", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -311,8 +297,6 @@ public async Task Invoke_RewriteToHttps() var response = await server.CreateClient().GetStringAsync(new Uri("http://example.com")); Assert.Equal("https://example.com/", response); - - await host.StopAsync(); } [Fact] @@ -350,8 +334,6 @@ public async Task Invoke_ReverseProxyToAnotherSite() var response = await server.CreateClient().GetStringAsync(new Uri("http://example.com/")); Assert.Equal("http://internalserver/", response); - - await host.StopAsync(); } [Fact] @@ -389,8 +371,6 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRedirectLocationHasForwa var response = await server.CreateClient().GetAsync(new Uri("http://example.com/")); Assert.Equal("/", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -425,8 +405,6 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRewriteLocationHasForwar var response = await server.CreateClient().GetStringAsync(new Uri("http://example.com/")); Assert.Equal("/", response); - - await host.StopAsync(); } [Fact] @@ -462,8 +440,6 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertLocationHeaderContainsPa var response = await server.CreateClient().GetAsync(""); Assert.Equal("/foo", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Theory] @@ -502,8 +478,6 @@ public async Task VerifyIsFileAndIsDirectoryParsing(string matchType) var response = await server.CreateClient().GetAsync("hey/hello"); Assert.Equal("/hey/hello/", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -540,8 +514,6 @@ public async Task VerifyTrackAllCaptures() var response = await server.CreateClient().GetAsync("article/23?p1=123&p2=abc"); Assert.Equal("/blogposts/article/abc?p1=123&p2=abc", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -578,8 +550,6 @@ public async Task VerifyTrackAllCapturesRuleAndConditionCapture() var response = await server.CreateClient().GetAsync("article/23?p1=123&p2=abc"); Assert.Equal("/blog/article/23/abc?p1=123&p2=abc", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -617,8 +587,6 @@ public async Task ThrowIndexOutOfRangeExceptionWithCorrectMessage() var ex = await Assert.ThrowsAsync(() => server.CreateClient().GetAsync("article/23?p1=123&p2=abc")); Assert.Equal("Cannot access back reference at index 9. Only 5 back references were captured.", ex.Message); - - await host.StopAsync(); } [Fact] @@ -658,8 +626,6 @@ public async Task Invoke_GlobalRuleConditionMatchesAgainstFullUri_ParsedRule() // assert Assert.Equal("http://www.test.com/foo/bar", response); - - await host.StopAsync(); } [Theory] @@ -703,8 +669,6 @@ public async Task Invoke_ReverseProxyToAnotherSiteUsingXmlConfiguredRewriteMap(s var response = await server.CreateClient().GetStringAsync(new Uri(requestUri)); Assert.Equal(expectedRewrittenUri, response); - - await host.StopAsync(); } [Fact] @@ -739,8 +703,6 @@ public async Task Invoke_CustomResponse() Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); Assert.Equal("reason", response.ReasonPhrase); Assert.Equal("description", content); - - await host.StopAsync(); } [Theory] @@ -796,8 +758,6 @@ public async Task Invoke_GlobalRuleConditionMatchesAgainstFullUri_CodedRule(stri // assert Assert.Equal(expectedResult, response); - - await host.StopAsync(); } } } diff --git a/src/Middleware/Rewrite/test/MiddlewareTests.cs b/src/Middleware/Rewrite/test/MiddlewareTests.cs index 7f627e573ffd..21fb4bdef8f6 100644 --- a/src/Middleware/Rewrite/test/MiddlewareTests.cs +++ b/src/Middleware/Rewrite/test/MiddlewareTests.cs @@ -43,8 +43,6 @@ public async Task CheckRewritePath() var response = await server.CreateClient().GetStringAsync("foo"); Assert.Equal("http://example.com/foo", response); - - await host.StopAsync(); } [Fact] @@ -69,8 +67,6 @@ public async Task CheckRedirectPath() var response = await server.CreateClient().GetAsync("foo"); Assert.Equal("http://example.com/foo", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -101,8 +97,6 @@ public async Task RewriteRulesCanComeFromConfigureOptions() var response = await server.CreateClient().GetAsync("foo"); Assert.Equal("http://example.com/foo", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -127,8 +121,6 @@ public async Task CheckRedirectPathWithQueryString() var response = await server.CreateClient().GetAsync("foo?bar=1"); Assert.Equal("http://example.com/foo?bar=1", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Theory] @@ -158,8 +150,6 @@ public async Task CheckRedirectToHttps(int statusCode) Assert.Equal("https://example.com/", response.Headers.Location.OriginalString); Assert.Equal(statusCode, (int)response.StatusCode); - - await host.StopAsync(); } [Fact] @@ -185,8 +175,6 @@ public async Task CheckPermanentRedirectToHttps() Assert.Equal("https://example.com/", response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status301MovedPermanently, (int)response.StatusCode); - - await host.StopAsync(); } [Theory] @@ -214,8 +202,6 @@ public async Task CheckRedirectToHttpsWithSslPort(int sslPort, string expected) Assert.Equal(expected, response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status301MovedPermanently, (int)response.StatusCode); - - await host.StopAsync(); } [Theory] @@ -245,8 +231,6 @@ public async Task CheckRedirectToWwwWithStatusCode(int statusCode) Assert.Equal("https://www.example.com/", response.Headers.Location.OriginalString); Assert.Equal(statusCode, (int)response.StatusCode); - - await host.StopAsync(); } [Theory] @@ -276,8 +260,6 @@ public async Task CheckRedirectToWww(string requestUri, string redirectUri) Assert.Equal(redirectUri, response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status307TemporaryRedirect, (int)response.StatusCode); - - await host.StopAsync(); } [Fact] @@ -303,8 +285,6 @@ public async Task CheckPermanentRedirectToWww() Assert.Equal("https://www.example.com/", response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status308PermanentRedirect, (int)response.StatusCode); - - await host.StopAsync(); } [Theory] @@ -339,8 +319,6 @@ public async Task CheckNoRedirectToWww(string requestUri) var response = await server.CreateClient().GetAsync(new Uri(requestUri)); Assert.Null(response.Headers.Location); - - await host.StopAsync(); } [Theory] @@ -370,8 +348,6 @@ public async Task CheckRedirectToNonWwwWithStatusCode(int statusCode) Assert.Equal("https://example.com/", response.Headers.Location.OriginalString); Assert.Equal(statusCode, (int)response.StatusCode); - - await host.StopAsync(); } [Theory] @@ -401,8 +377,6 @@ public async Task CheckRedirectToNonWww(string requestUri, string redirectUri) Assert.Equal(redirectUri, response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status307TemporaryRedirect, (int)response.StatusCode); - - await host.StopAsync(); } [Fact] @@ -428,8 +402,6 @@ public async Task CheckPermanentRedirectToNonWww() Assert.Equal("https://example.com/", response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status308PermanentRedirect, (int)response.StatusCode); - - await host.StopAsync(); } [Fact] @@ -453,8 +425,6 @@ public async Task CheckIfEmptyStringRedirectCorrectly() var response = await server.CreateClient().GetAsync(""); Assert.Equal("/", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Fact] @@ -482,8 +452,6 @@ public async Task CheckIfEmptyStringRewriteCorrectly() var response = await server.CreateClient().GetStringAsync(""); Assert.Equal("/", response); - - await host.StopAsync(); } [Fact] @@ -512,8 +480,6 @@ public async Task SettingPathBase() var response = await server.CreateClient().GetAsync(""); Assert.Equal("/foo", response.Headers.Location.OriginalString); - - await host.StopAsync(); } [Theory] @@ -543,8 +509,6 @@ public async Task CheckNoRedirectToWwwInNonWhitelistedDomains(string requestUri) var response = await server.CreateClient().GetAsync(new Uri(requestUri)); Assert.Null(response.Headers.Location); - - await host.StopAsync(); } [Theory] @@ -574,8 +538,6 @@ public async Task CheckRedirectToWwwInWhitelistedDomains(string requestUri, stri Assert.Equal(redirectUri, response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status307TemporaryRedirect, (int)response.StatusCode); - - await host.StopAsync(); } [Fact] @@ -601,8 +563,6 @@ public async Task CheckPermanentRedirectToWwwInWhitelistedDomains() Assert.Equal("https://www.example.com/", response.Headers.Location.OriginalString); Assert.Equal(StatusCodes.Status308PermanentRedirect, (int)response.StatusCode); - - await host.StopAsync(); } [Theory] @@ -632,8 +592,6 @@ public async Task CheckRedirectToWwwWithStatusCodeInWhitelistedDomains(int statu Assert.Equal("https://www.example.com/", response.Headers.Location.OriginalString); Assert.Equal(statusCode, (int)response.StatusCode); - - await host.StopAsync(); } } diff --git a/src/Middleware/Session/test/SessionTests.cs b/src/Middleware/Session/test/SessionTests.cs index c2c920ef2549..1a31e37d38d7 100644 --- a/src/Middleware/Session/test/SessionTests.cs +++ b/src/Middleware/Session/test/SessionTests.cs @@ -61,8 +61,6 @@ public async Task ReadingEmptySessionDoesNotCreateCookie() response.EnsureSuccessStatusCode(); Assert.False(response.Headers.TryGetValues("Set-Cookie", out var _)); } - - await host.StopAsync(); } [Fact] @@ -102,8 +100,6 @@ public async Task SettingAValueCausesTheCookieToBeCreated() Assert.Single(values); Assert.True(!string.IsNullOrWhiteSpace(values.First())); } - - await host.StopAsync(); } [Theory] @@ -166,8 +162,6 @@ public async Task SecureSessionBasedOnHttpsAndSecurePolicy( Assert.DoesNotContain("; secure", values.First()); } } - - await host.StopAsync(); } [Fact] @@ -216,8 +210,6 @@ public async Task SessionCanBeAccessedOnTheNextRequest() Assert.Equal("1", await client.GetStringAsync("/")); Assert.Equal("2", await client.GetStringAsync("/")); Assert.Equal("3", await client.GetStringAsync("/")); - - await host.StopAsync(); } } @@ -278,8 +270,6 @@ public async Task RemovedItemCannotBeAccessedAgain() Assert.Equal("1", await client.GetStringAsync("/second")); Assert.Equal("2", await client.GetStringAsync("/third")); } - - await host.StopAsync(); } [Fact] @@ -338,8 +328,6 @@ public async Task ClearedItemsCannotBeAccessedAgain() Assert.Equal("1", await client.GetStringAsync("/second")); Assert.Equal("2", await client.GetStringAsync("/third")); } - - await host.StopAsync(); } [Fact] @@ -387,8 +375,6 @@ public async Task SessionStart_LogsInformation() Assert.Equal(LogLevel.Information, sessionLogMessages[0].LogLevel); Assert.Contains("stored", sessionLogMessages[1].State.ToString()); Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel); - - await host.StopAsync(); } [Fact] @@ -457,8 +443,6 @@ public async Task ExpiredSession_LogsInfo() Assert.Equal(LogLevel.Information, sessionLogMessages[0].LogLevel); Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel); Assert.Equal(LogLevel.Information, sessionLogMessages[2].LogLevel); - - await host.StopAsync(); } [Fact] @@ -525,8 +509,6 @@ public async Task RefreshesSession_WhenSessionData_IsNotModified() var data = await client.GetStringAsync("/AccessSessionData"); Assert.Equal("10", data); } - - await host.StopAsync(); } [Fact] @@ -569,8 +551,6 @@ public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut() var response = await client.GetAsync(string.Empty); response.EnsureSuccessStatusCode(); } - - await host.StopAsync(); } [Fact] @@ -620,8 +600,6 @@ public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut_AndAnUnhand var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); } - - await host.StopAsync(); } [Fact] @@ -659,8 +637,6 @@ public async Task SessionKeys_AreCaseSensitive() var response = await client.GetAsync(string.Empty); response.EnsureSuccessStatusCode(); } - - await host.StopAsync(); } [Fact] @@ -710,8 +686,6 @@ public async Task SessionLogsCacheReadException() var message = Assert.Single(sink.Writes); Assert.Contains("Session cache read exception", message.State.ToString()); Assert.Equal(LogLevel.Error, message.LogLevel); - - await host.StopAsync(); } [Fact] @@ -760,8 +734,6 @@ public async Task SessionLogsCacheLoadAsyncException() var message = Assert.Single(sink.Writes); Assert.Contains("Session cache read exception", message.State.ToString()); Assert.Equal(LogLevel.Error, message.LogLevel); - - await host.StopAsync(); } [Fact] @@ -810,8 +782,6 @@ public async Task SessionLogsCacheLoadAsyncTimeoutException() var message = Assert.Single(sink.Writes); Assert.Contains("Loading the session timed out.", message.State.ToString()); Assert.Equal(LogLevel.Warning, message.LogLevel); - - await host.StopAsync(); } [Fact] @@ -858,8 +828,6 @@ public async Task SessionLoadAsyncCanceledException() } Assert.Empty(sink.Writes); - - await host.StopAsync(); } [Fact] @@ -920,8 +888,6 @@ public async Task SessionLogsCacheCommitException() Assert.Contains("Error closing the session.", sessionMiddlewareLogMessage.State.ToString()); Assert.Equal(LogLevel.Error, sessionMiddlewareLogMessage.LogLevel); - - await host.StopAsync(); } [Fact] @@ -988,8 +954,6 @@ public async Task SessionLogsCacheCommitTimeoutException() Assert.Contains("Committing the session was canceled.", sessionMiddlewareLogs[0].State.ToString()); Assert.Equal(LogLevel.Information, sessionMiddlewareLogs[0].LogLevel); - - await host.StopAsync(); } [Fact] @@ -1054,8 +1018,6 @@ public async Task SessionLogsCacheCommitCanceledException() Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel); Assert.Empty(sink.Writes.Where(message => message.LoggerName.Equals(typeof(SessionMiddleware).FullName, StringComparison.Ordinal))); - - await host.StopAsync(); } [Fact] @@ -1120,8 +1082,6 @@ public async Task RequestAbortedIgnored() Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel); Assert.Empty(sink.Writes.Where(message => message.LoggerName.Equals(typeof(SessionMiddleware).FullName, StringComparison.Ordinal))); - - await host.StopAsync(); } [Fact] @@ -1168,8 +1128,6 @@ public async Task SessionLogsCacheRefreshException() var message = Assert.Single(sink.Writes); Assert.Contains("Error closing the session.", message.State.ToString()); Assert.Equal(LogLevel.Error, message.LogLevel); - - await host.StopAsync(); } private class TestClock : ISystemClock diff --git a/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs b/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs index 6d867a0564e9..dff351cedf41 100644 --- a/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs +++ b/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs @@ -74,8 +74,6 @@ public async Task ReturnsFileForDefaultPattern() Assert.Equal(HttpStatusCode.OK, response.StatusCode); AssertFileEquals(environment, "SubFolder/default.html", responseContent); } - - await host.StopAsync(); } [Fact] diff --git a/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs b/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs index 6d255b06f8ea..14183c0647f4 100644 --- a/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs @@ -47,8 +47,6 @@ public async Task ReturnsNotFoundWithoutWwwroot() Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } - - await host.StopAsync(); } [Fact] @@ -95,8 +93,6 @@ public async Task Endpoint_PassesThrough() Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("Hi from endpoint.", await response.Content.ReadAsStringAsync()); } - - await host.StopAsync(); } [Fact] @@ -124,8 +120,6 @@ public async Task FoundFile_LastModifiedTrimsSeconds() Assert.Equal(response.Content.Headers.LastModified.Value, trimmed); } - - await host.StopAsync(); } [Theory] @@ -185,8 +179,6 @@ private async Task FoundFile_Served(string baseUrl, string baseDir, string reque Assert.True(responseContent.SequenceEqual(fileContents)); } } - - await host.StopAsync(); } [Theory] @@ -221,8 +213,6 @@ public async Task HeadFile_HeadersButNotBodyServed(string baseUrl, string baseDi Assert.True(response.Content.Headers.ContentLength == fileInfo.Length); Assert.Empty((await response.Content.ReadAsByteArrayAsync())); } - - await host.StopAsync(); } public static IEnumerable ExistingFiles => new[] @@ -305,8 +295,6 @@ private async Task ClientDisconnect_NoWriteExceptionThrown(ServerType serverType await responseComplete.Task.TimeoutAfter(interval); Assert.Null(exception); - - await host.StopAsync(); } private Socket SendSocketRequestAsync(string address, string path, string method = "GET") diff --git a/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs b/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs index 265ba1e16c76..518927b50976 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs @@ -43,8 +43,6 @@ public async Task ReturnsNotFoundWithoutWwwroot() Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Null(response.Headers.ETag); - - await host.StopAsync(); } [ConditionalFact] @@ -75,8 +73,6 @@ public async Task ReturnsNotFoundForBrokenSymlink() Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Null(response.Headers.ETag); - - await host.StopAsync(); } finally { @@ -116,8 +112,6 @@ public async Task ReturnsNotFoundIfSendFileThrows() Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Null(response.Headers.ETag); - - await host.StopAsync(); } [Fact]