From 42b356f2b14b07fc3e98733ba175fe76f4906640 Mon Sep 17 00:00:00 2001 From: Kahbazi Date: Fri, 24 Jul 2020 17:46:52 +0430 Subject: [PATCH 01/13] [Kestrel] Move to GenericHost --- .../InMemoryTransportBenchmark.cs | 23 +- .../Kestrel/samples/Http2SampleApp/Program.cs | 86 ++-- .../samples/LargeResponseApp/Startup.cs | 17 +- .../Kestrel/samples/PlaintextApp/Startup.cs | 15 +- .../Kestrel/samples/QuicSampleApp/Program.cs | 99 ++--- .../Kestrel/samples/SampleApp/Startup.cs | 180 ++++----- .../Kestrel/samples/SystemdTestApp/Startup.cs | 71 ++-- .../test/TransportTestHelpers/TestServer.cs | 52 +-- .../BindTests/AddressRegistrationTests.cs | 367 +++++++++++------- .../MaxRequestBufferSizeTests.cs | 109 +++--- .../test/FunctionalTests/RequestTests.cs | 201 +++++----- .../test/FunctionalTests/ResponseTests.cs | 73 ++-- .../FunctionalTests/UnixDomainSocketsTests.cs | 55 ++- .../TestTransport/TestServer.cs | 11 +- .../Interop.FunctionalTests/ChromeTests.cs | 47 ++- .../Interop.FunctionalTests/H2SpecTests.cs | 27 +- .../TransportSelector.cs | 18 +- 17 files changed, 821 insertions(+), 630 deletions(-) diff --git a/src/Servers/Kestrel/perf/Kestrel.Performance/InMemoryTransportBenchmark.cs b/src/Servers/Kestrel/perf/Kestrel.Performance/InMemoryTransportBenchmark.cs index b3b6229d5e95..182cc336d2c4 100644 --- a/src/Servers/Kestrel/perf/Kestrel.Performance/InMemoryTransportBenchmark.cs +++ b/src/Servers/Kestrel/perf/Kestrel.Performance/InMemoryTransportBenchmark.cs @@ -16,6 +16,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.Server.Kestrel.Performance { @@ -33,22 +34,26 @@ public class InMemoryTransportBenchmark private static readonly string _plaintextPipelinedExpectedResponse = string.Concat(Enumerable.Repeat(_plaintextExpectedResponse, RequestParsingData.Pipelining)); - private IWebHost _host; + private IHost _host; private InMemoryConnection _connection; [GlobalSetup(Target = nameof(Plaintext) + "," + nameof(PlaintextPipelined))] public void GlobalSetupPlaintext() { var transportFactory = new InMemoryTransportFactory(connectionsPerEndPoint: 1); - - _host = new WebHostBuilder() - // Prevent VS from attaching to hosting startup which could impact results - .UseSetting("preventHostingStartup", "true") - .UseKestrel() - // Bind to a single non-HTTPS endpoint - .UseUrls("http://127.0.0.1:5000") + + _host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + // Prevent VS from attaching to hosting startup which could impact results + .UseSetting("preventHostingStartup", "true") + .UseKestrel() + // Bind to a single non-HTTPS endpoint + .UseUrls("http://127.0.0.1:5000") + .Configure(app => app.UseMiddleware()); + }) .ConfigureServices(services => services.AddSingleton(transportFactory)) - .Configure(app => app.UseMiddleware()) .Build(); _host.Start(); diff --git a/src/Servers/Kestrel/samples/Http2SampleApp/Program.cs b/src/Servers/Kestrel/samples/Http2SampleApp/Program.cs index 2b26fe09c608..3747571a666f 100644 --- a/src/Servers/Kestrel/samples/Http2SampleApp/Program.cs +++ b/src/Servers/Kestrel/samples/Http2SampleApp/Program.cs @@ -1,12 +1,12 @@ using System; using System.IO; -using System.Net; using System.Security.Authentication; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Http2SampleApp @@ -15,54 +15,58 @@ public class Program { public static void Main(string[] args) { - var hostBuilder = new WebHostBuilder() - .ConfigureLogging((_, factory) => + var hostBuilder = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - // Set logging to the MAX. - factory.SetMinimumLevel(LogLevel.Trace); - factory.AddConsole(); - }) - .UseKestrel() - .ConfigureKestrel((context, options) => - { - var basePort = context.Configuration.GetValue("BASE_PORT") ?? 5000; - - // Http/1.1 endpoint for comparison - options.ListenAnyIP(basePort, listenOptions => - { - listenOptions.Protocols = HttpProtocols.Http1; - }); - - // TLS Http/1.1 or HTTP/2 endpoint negotiated via ALPN - options.ListenAnyIP(basePort + 1, listenOptions => - { - listenOptions.Protocols = HttpProtocols.Http1AndHttp2; - listenOptions.UseHttps(); - listenOptions.Use((context, next) => + webHostBuilder + .UseKestrel() + .ConfigureKestrel((context, options) => { - // https://tools.ietf.org/html/rfc7540#appendix-A - // Allows filtering TLS handshakes on a per connection basis + var basePort = context.Configuration.GetValue("BASE_PORT") ?? 5000; - var tlsFeature = context.Features.Get(); + // Http/1.1 endpoint for comparison + options.ListenAnyIP(basePort, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http1; + }); - if (tlsFeature.CipherAlgorithm == CipherAlgorithmType.Null) + // TLS Http/1.1 or HTTP/2 endpoint negotiated via ALPN + options.ListenAnyIP(basePort + 1, listenOptions => { - throw new NotSupportedException("Prohibited cipher: " + tlsFeature.CipherAlgorithm); - } + listenOptions.Protocols = HttpProtocols.Http1AndHttp2; + listenOptions.UseHttps(); + listenOptions.Use((context, next) => + { + // https://tools.ietf.org/html/rfc7540#appendix-A + // Allows filtering TLS handshakes on a per connection basis - return next(); - }); - }); + var tlsFeature = context.Features.Get(); - // Prior knowledge, no TLS handshake. WARNING: Not supported by browsers - // but useful for the h2spec tests - options.ListenAnyIP(basePort + 5, listenOptions => - { - listenOptions.Protocols = HttpProtocols.Http2; - }); + if (tlsFeature.CipherAlgorithm == CipherAlgorithmType.Null) + { + throw new NotSupportedException("Prohibited cipher: " + tlsFeature.CipherAlgorithm); + } + + return next(); + }); + }); + + // Prior knowledge, no TLS handshake. WARNING: Not supported by browsers + // but useful for the h2spec tests + options.ListenAnyIP(basePort + 5, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http2; + }); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseStartup(); }) - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseStartup(); + .ConfigureLogging((_, factory) => + { + // Set logging to the MAX. + factory.SetMinimumLevel(LogLevel.Trace); + factory.AddConsole(); + }); hostBuilder.Build().Run(); } diff --git a/src/Servers/Kestrel/samples/LargeResponseApp/Startup.cs b/src/Servers/Kestrel/samples/LargeResponseApp/Startup.cs index 8135247cf98f..2d1f7eb44e7c 100644 --- a/src/Servers/Kestrel/samples/LargeResponseApp/Startup.cs +++ b/src/Servers/Kestrel/samples/LargeResponseApp/Startup.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; namespace LargeResponseApp { @@ -38,13 +39,17 @@ public void Configure(IApplicationBuilder app) public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel(options => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(IPAddress.Loopback, 5001); - }) - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseStartup() + webHostBuilder + .UseKestrel(options => + { + options.Listen(IPAddress.Loopback, 5001); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseStartup(); + }) .Build(); return host.RunAsync(); diff --git a/src/Servers/Kestrel/samples/PlaintextApp/Startup.cs b/src/Servers/Kestrel/samples/PlaintextApp/Startup.cs index 044e8b5dfed2..44dd6eb7e8bc 100644 --- a/src/Servers/Kestrel/samples/PlaintextApp/Startup.cs +++ b/src/Servers/Kestrel/samples/PlaintextApp/Startup.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; namespace PlaintextApp { @@ -34,13 +35,17 @@ public void Configure(IApplicationBuilder app) public static async Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel(options => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(IPAddress.Loopback, 5001); + webHostBuilder + .UseKestrel(options => + { + options.Listen(IPAddress.Loopback, 5001); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseStartup(); }) - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseStartup() .Build(); await host.RunAsync(); diff --git a/src/Servers/Kestrel/samples/QuicSampleApp/Program.cs b/src/Servers/Kestrel/samples/QuicSampleApp/Program.cs index 54a11c63a054..ca3cc0e64391 100644 --- a/src/Servers/Kestrel/samples/QuicSampleApp/Program.cs +++ b/src/Servers/Kestrel/samples/QuicSampleApp/Program.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace QuicSampleApp @@ -22,60 +23,64 @@ public void Configure(IApplicationBuilder app) public static void Main(string[] args) { - var hostBuilder = new WebHostBuilder() - .ConfigureLogging((_, factory) => - { - factory.SetMinimumLevel(LogLevel.Debug); - factory.AddConsole(); - }) - .UseKestrel() - .UseQuic(options => - { - options.Certificate = null; - options.Alpn = "QuicTest"; - options.IdleTimeout = TimeSpan.FromHours(1); - }) - .ConfigureKestrel((context, options) => - { - var basePort = 5555; + var hostBuilder = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseQuic(options => + { + options.Certificate = null; + options.Alpn = "QuicTest"; + options.IdleTimeout = TimeSpan.FromHours(1); + }) + .ConfigureKestrel((context, options) => + { + var basePort = 5555; - options.Listen(IPAddress.Any, basePort, listenOptions => - { - listenOptions.Protocols = HttpProtocols.Http3; + options.Listen(IPAddress.Any, basePort, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http3; - async Task EchoServer(MultiplexedConnectionContext connection) - { - // For graceful shutdown + async Task EchoServer(MultiplexedConnectionContext connection) + { + // For graceful shutdown - while (true) - { - var stream = await connection.AcceptAsync(); - while (true) - { - var result = await stream.Transport.Input.ReadAsync(); + while (true) + { + var stream = await connection.AcceptAsync(); + while (true) + { + var result = await stream.Transport.Input.ReadAsync(); - if (result.IsCompleted) - { - break; - } + if (result.IsCompleted) + { + break; + } - await stream.Transport.Output.WriteAsync(result.Buffer.ToArray()); + await stream.Transport.Output.WriteAsync(result.Buffer.ToArray()); - stream.Transport.Input.AdvanceTo(result.Buffer.End); - } - } - } + stream.Transport.Input.AdvanceTo(result.Buffer.End); + } + } + } - ((IMultiplexedConnectionBuilder)listenOptions).Use(next => - { - return context => - { - return EchoServer(context); - }; - }); - }); - }) - .UseStartup(); + ((IMultiplexedConnectionBuilder)listenOptions).Use(next => + { + return context => + { + return EchoServer(context); + }; + }); + }); + }) + .UseStartup(); + }) + .ConfigureLogging((_, factory) => + { + factory.SetMinimumLevel(LogLevel.Debug); + factory.AddConsole(); + }); hostBuilder.Build().Run(); } diff --git a/src/Servers/Kestrel/samples/SampleApp/Startup.cs b/src/Servers/Kestrel/samples/SampleApp/Startup.cs index 6f6afe3facdd..baed7b92b3b1 100644 --- a/src/Servers/Kestrel/samples/SampleApp/Startup.cs +++ b/src/Servers/Kestrel/samples/SampleApp/Startup.cs @@ -62,109 +62,113 @@ public static Task Main(string[] args) Console.WriteLine("Unobserved exception: {0}", e.Exception); }; - 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((context, options) => - { - if (context.HostingEnvironment.IsDevelopment()) - { - ShowConfig(context.Configuration); - } + webHostBuilder + .UseKestrel((context, options) => + { + if (context.HostingEnvironment.IsDevelopment()) + { + ShowConfig(context.Configuration); + } - var basePort = context.Configuration.GetValue("BASE_PORT") ?? 5000; + var basePort = context.Configuration.GetValue("BASE_PORT") ?? 5000; - options.ConfigureHttpsDefaults(httpsOptions => - { - httpsOptions.SslProtocols = SslProtocols.Tls12; - }); + options.ConfigureHttpsDefaults(httpsOptions => + { + httpsOptions.SslProtocols = SslProtocols.Tls12; + }); - options.Listen(IPAddress.Loopback, basePort, listenOptions => - { - // Uncomment the following to enable Nagle's algorithm for this endpoint. - //listenOptions.NoDelay = false; + options.Listen(IPAddress.Loopback, basePort, listenOptions => + { + // Uncomment the following to enable Nagle's algorithm for this endpoint. + //listenOptions.NoDelay = false; - listenOptions.UseConnectionLogging(); - }); + listenOptions.UseConnectionLogging(); + }); - options.Listen(IPAddress.Loopback, basePort + 1, listenOptions => - { - listenOptions.UseHttps(); - listenOptions.UseConnectionLogging(); - }); - - options.ListenLocalhost(basePort + 2, listenOptions => - { - // Use default dev cert - listenOptions.UseHttps(); - }); + options.Listen(IPAddress.Loopback, basePort + 1, listenOptions => + { + listenOptions.UseHttps(); + listenOptions.UseConnectionLogging(); + }); - options.ListenAnyIP(basePort + 3); + options.ListenLocalhost(basePort + 2, listenOptions => + { + // Use default dev cert + listenOptions.UseHttps(); + }); - options.ListenAnyIP(basePort + 4, listenOptions => - { - listenOptions.UseHttps(StoreName.My, "localhost", allowInvalid: true); - }); + options.ListenAnyIP(basePort + 3); - options.ListenAnyIP(basePort + 5, listenOptions => - { - listenOptions.UseHttps(httpsOptions => - { - var localhostCert = CertificateLoader.LoadFromStoreCert("localhost", "My", StoreLocation.CurrentUser, allowInvalid: true); - httpsOptions.ServerCertificateSelector = (features, name) => + options.ListenAnyIP(basePort + 4, listenOptions => { - // Here you would check the name, select an appropriate cert, and provide a fallback or fail for null names. - return localhostCert; - }; - }); - }); - - options - .Configure() - .Endpoint(IPAddress.Loopback, basePort + 6) - .LocalhostEndpoint(basePort + 7) - .Load(); - - // reloadOnChange: true is the default - options - .Configure(context.Configuration.GetSection("Kestrel"), reloadOnChange: true) - .Endpoint("NamedEndpoint", opt => - { + listenOptions.UseHttps(StoreName.My, "localhost", allowInvalid: true); + }); + options.ListenAnyIP(basePort + 5, listenOptions => + { + listenOptions.UseHttps(httpsOptions => + { + var localhostCert = CertificateLoader.LoadFromStoreCert("localhost", "My", StoreLocation.CurrentUser, allowInvalid: true); + httpsOptions.ServerCertificateSelector = (features, name) => + { + // Here you would check the name, select an appropriate cert, and provide a fallback or fail for null names. + return localhostCert; + }; + }); + }); + + options + .Configure() + .Endpoint(IPAddress.Loopback, basePort + 6) + .LocalhostEndpoint(basePort + 7) + .Load(); + + // reloadOnChange: true is the default + options + .Configure(context.Configuration.GetSection("Kestrel"), reloadOnChange: true) + .Endpoint("NamedEndpoint", opt => + { + + }) + .Endpoint("NamedHttpsEndpoint", opt => + { + opt.HttpsOptions.SslProtocols = SslProtocols.Tls12; + }); + + options.UseSystemd(); + + // The following section should be used to demo sockets + //options.ListenUnixSocket("/tmp/kestrel-test.sock"); }) - .Endpoint("NamedHttpsEndpoint", opt => - { - opt.HttpsOptions.SslProtocols = SslProtocols.Tls12; - }); - - options.UseSystemd(); + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseStartup(); - // The following section should be used to demo sockets - //options.ListenUnixSocket("/tmp/kestrel-test.sock"); - }) - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseStartup(); - - if (string.Equals(Process.GetCurrentProcess().Id.ToString(), Environment.GetEnvironmentVariable("LISTEN_PID"))) - { - // Use libuv if activated by systemd, since that's currently the only transport that supports being passed a socket handle. + if (string.Equals(Process.GetCurrentProcess().Id.ToString(), Environment.GetEnvironmentVariable("LISTEN_PID"))) + { + // Use libuv if activated by systemd, since that's currently the only transport that supports being passed a socket handle. #pragma warning disable CS0618 - hostBuilder.UseLibuv(options => - { - // Uncomment the following line to change the default number of libuv threads for all endpoints. - // options.ThreadCount = 4; - }); + webHostBuilder.UseLibuv(options => + { + // Uncomment the following line to change the default number of libuv threads for all endpoints. + // options.ThreadCount = 4; + }); #pragma warning restore CS0618 - } + } + }) + .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); + }); return hostBuilder.Build().RunAsync(); } diff --git a/src/Servers/Kestrel/samples/SystemdTestApp/Startup.cs b/src/Servers/Kestrel/samples/SystemdTestApp/Startup.cs index 8a01fac6d9f6..3b7f1cfde9cb 100644 --- a/src/Servers/Kestrel/samples/SystemdTestApp/Startup.cs +++ b/src/Servers/Kestrel/samples/SystemdTestApp/Startup.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace SystemdTestApp @@ -41,48 +42,52 @@ public static Task Main(string[] args) Console.WriteLine("Unobserved exception: {0}", e.Exception); }; - var hostBuilder = new WebHostBuilder() - .ConfigureLogging((_, factory) => - { - factory.AddConsole(); - }) - .UseKestrel((context, options) => + var hostBuilder = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var basePort = context.Configuration.GetValue("BASE_PORT") ?? 5000; + webHostBuilder + .UseKestrel((context, options) => + { + var basePort = context.Configuration.GetValue("BASE_PORT") ?? 5000; - options.Listen(IPAddress.Loopback, basePort, listenOptions => - { - // Uncomment the following to enable Nagle's algorithm for this endpoint. - //listenOptions.NoDelay = false; + options.Listen(IPAddress.Loopback, basePort, listenOptions => + { + // Uncomment the following to enable Nagle's algorithm for this endpoint. + //listenOptions.NoDelay = false; - listenOptions.UseConnectionLogging(); - }); + listenOptions.UseConnectionLogging(); + }); - options.Listen(IPAddress.Loopback, basePort + 1, listenOptions => - { - listenOptions.UseHttps(); - listenOptions.UseConnectionLogging(); - }); + options.Listen(IPAddress.Loopback, basePort + 1, listenOptions => + { + listenOptions.UseHttps(); + listenOptions.UseConnectionLogging(); + }); - options.UseSystemd(); + options.UseSystemd(); - // The following section should be used to demo sockets - //options.ListenUnixSocket("/tmp/kestrel-test.sock"); - }) - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseStartup(); + // The following section should be used to demo sockets + //options.ListenUnixSocket("/tmp/kestrel-test.sock"); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseStartup(); - if (string.Equals(Process.GetCurrentProcess().Id.ToString(), Environment.GetEnvironmentVariable("LISTEN_PID"))) - { - // Use libuv if activated by systemd, since that's currently the only transport that supports being passed a socket handle. + if (string.Equals(Process.GetCurrentProcess().Id.ToString(), Environment.GetEnvironmentVariable("LISTEN_PID"))) + { + // Use libuv if activated by systemd, since that's currently the only transport that supports being passed a socket handle. #pragma warning disable CS0618 - hostBuilder.UseLibuv(options => - { - // Uncomment the following line to change the default number of libuv threads for all endpoints. - // options.ThreadCount = 4; - }); + webHostBuilder.UseLibuv(options => + { + // Uncomment the following line to change the default number of libuv threads for all endpoints. + // options.ThreadCount = 4; + }); #pragma warning restore CS0618 - } + } + }) + .ConfigureLogging((_, factory) => + { + factory.AddConsole(); + }); return hostBuilder.Build().RunAsync(); } diff --git a/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs b/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs index acfb02cd6dd7..ce3380083971 100644 --- a/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs +++ b/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs @@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests /// internal class TestServer : IDisposable, IStartup { - private IWebHost _host; + private IHost _host; private ListenOptions _listenOptions; private readonly RequestDelegate _app; @@ -70,32 +70,36 @@ public TestServer(RequestDelegate app, TestServiceContext context, Action + _host = TransportSelector.GetHostBuilder(context.MemoryPoolFactory, context.ServerOptions.Limits.MaxRequestBufferSize) + .ConfigureWebHost(webHostBuilder => { - configureKestrel(options); - _listenOptions = options.ListenOptions.First(); - }) - .ConfigureServices(services => - { - services.AddSingleton(this); - services.AddSingleton(context.LoggerFactory); - services.AddSingleton(sp => - { - // Manually configure options on the TestServiceContext. - // We're doing this so we can use the same instance that was passed in - var configureOptions = sp.GetServices>(); - foreach (var c in configureOptions) + webHostBuilder + .UseKestrel(options => { - c.Configure(context.ServerOptions); - } - - return new KestrelServer(new List() { sp.GetRequiredService() }, context); - }); - configureServices(services); + configureKestrel(options); + _listenOptions = options.ListenOptions.First(); + }) + .ConfigureServices(services => + { + services.AddSingleton(this); + services.AddSingleton(context.LoggerFactory); + services.AddSingleton(sp => + { + // Manually configure options on the TestServiceContext. + // We're doing this so we can use the same instance that was passed in + var configureOptions = sp.GetServices>(); + foreach (var c in configureOptions) + { + c.Configure(context.ServerOptions); + } + + return new KestrelServer(new List() { sp.GetRequiredService() }, context); + }); + configureServices(services); + }) + .UseSetting(WebHostDefaults.ApplicationKey, typeof(TestServer).GetTypeInfo().Assembly.FullName) + .UseSetting(WebHostDefaults.ShutdownTimeoutKey, TestConstants.DefaultTimeout.TotalSeconds.ToString()); }) - .UseSetting(WebHostDefaults.ApplicationKey, typeof(TestServer).GetTypeInfo().Assembly.FullName) - .UseSetting(WebHostDefaults.ShutdownTimeoutKey, TestConstants.DefaultTimeout.TotalSeconds.ToString()) .Build(); _host.Start(); diff --git a/src/Servers/Kestrel/test/BindTests/AddressRegistrationTests.cs b/src/Servers/Kestrel/test/BindTests/AddressRegistrationTests.cs index 621110b164db..1443b8bd66b3 100644 --- a/src/Servers/Kestrel/test/BindTests/AddressRegistrationTests.cs +++ b/src/Servers/Kestrel/test/BindTests/AddressRegistrationTests.cs @@ -21,8 +21,11 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Microsoft.Extensions.Hosting; using Xunit; using Xunit.Sdk; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests { @@ -182,17 +185,21 @@ public async Task RegisterAddresses_IPv6LocalhostStaticPort_Success() private async Task RegisterAddresses_Success(string addressInput, string[] testUrls, int testPort = 0) { - var hostBuilder = TransportSelector.GetWebHostBuilder() - .UseKestrel(serverOptions => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - serverOptions.ConfigureHttpsDefaults(httpsOptions => - { - httpsOptions.ServerCertificate = TestResources.GetTestCertificate(); - }); + webHostBuilder + .UseKestrel(serverOptions => + { + serverOptions.ConfigureHttpsDefaults(httpsOptions => + { + httpsOptions.ServerCertificate = TestResources.GetTestCertificate(); + }); + }) + .UseUrls(addressInput) + .Configure(ConfigureEchoAddress); }) - .ConfigureServices(AddTestLogging) - .UseUrls(addressInput) - .Configure(ConfigureEchoAddress); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -226,25 +233,29 @@ private Task RegisterAddresses_StaticPort_Success(string addressInput, string[] [Fact] public async Task RegisterHttpAddress_UpgradedToHttpsByConfigureEndpointDefaults() { - var hostBuilder = TransportSelector.GetWebHostBuilder() - .UseKestrel(serverOptions => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - serverOptions.ConfigureEndpointDefaults(listenOptions => - { - listenOptions.UseHttps(TestResources.GetTestCertificate()); - }); + webHostBuilder + .UseKestrel(serverOptions => + { + serverOptions.ConfigureEndpointDefaults(listenOptions => + { + listenOptions.UseHttps(TestResources.GetTestCertificate()); + }); + }) + .UseUrls("http://127.0.0.1:0") + .Configure(app => + { + var serverAddresses = app.ServerFeatures.Get(); + app.Run(context => + { + Assert.Single(serverAddresses.Addresses); + return context.Response.WriteAsync(serverAddresses.Addresses.First()); + }); + }); }) - .ConfigureServices(AddTestLogging) - .UseUrls("http://127.0.0.1:0") - .Configure(app => - { - var serverAddresses = app.ServerFeatures.Get(); - app.Run(context => - { - Assert.Single(serverAddresses.Addresses); - return context.Response.WriteAsync(serverAddresses.Addresses.First()); - }); - }); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -293,19 +304,23 @@ private Task RegisterAddresses_StaticPort_Success(string addressInput, string te private async Task RegisterIPEndPoint_Success(IPEndPoint endPoint, string testUrl, int testPort = 0) { - var hostBuilder = TransportSelector.GetWebHostBuilder() - .ConfigureServices(AddTestLogging) - .UseKestrel(options => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(endPoint, listenOptions => - { - if (testUrl.StartsWith("https")) + webHostBuilder + .UseKestrel(options => { - listenOptions.UseHttps(TestResources.GetTestCertificate()); - } - }); + options.Listen(endPoint, listenOptions => + { + if (testUrl.StartsWith("https")) + { + listenOptions.UseHttps(TestResources.GetTestCertificate()); + } + }); + }) + .Configure(ConfigureEchoAddress); }) - .Configure(ConfigureEchoAddress); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -353,13 +368,17 @@ public async Task ListenAnyIP_HostName_Success() private async Task ListenAnyIP_Success(string[] testUrls, int testPort = 0) { - var hostBuilder = TransportSelector.GetWebHostBuilder() - .UseKestrel(options => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.ListenAnyIP(testPort); + webHostBuilder + .UseKestrel(options => + { + options.ListenAnyIP(testPort); + }) + .Configure(ConfigureEchoAddress); }) - .ConfigureServices(AddTestLogging) - .Configure(ConfigureEchoAddress); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -396,13 +415,17 @@ private Task ListenLocalhost_StaticPort_Success(string[] testUrls) => private async Task ListenLocalhost_Success(string[] testUrls, int testPort = 0) { - var hostBuilder = TransportSelector.GetWebHostBuilder() - .UseKestrel(options => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.ListenLocalhost(testPort); + webHostBuilder + .UseKestrel(options => + { + options.ListenLocalhost(testPort); + }) + .Configure(ConfigureEchoAddress); }) - .ConfigureServices(AddTestLogging) - .Configure(ConfigureEchoAddress); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -478,16 +501,20 @@ public Task DefaultsServerAddress_BindsToIPv6WithHttps() private async Task RegisterDefaultServerAddresses_Success(IEnumerable addresses, bool mockHttps = false) { - var hostBuilder = TransportSelector.GetWebHostBuilder() - .ConfigureServices(AddTestLogging) - .UseKestrel(options => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - if (mockHttps) - { - options.DefaultCertificate = TestResources.GetTestCertificate(); - } + webHostBuilder + .UseKestrel(options => + { + if (mockHttps) + { + options.DefaultCertificate = TestResources.GetTestCertificate(); + } + }) + .Configure(ConfigureEchoAddress); }) - .Configure(ConfigureEchoAddress); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -522,10 +549,14 @@ public void ThrowsWhenBindingToIPv4AddressInUse() socket.Listen(0); var port = ((IPEndPoint)socket.LocalEndPoint).Port; - var hostBuilder = TransportSelector.GetWebHostBuilder() - .UseKestrel() - .UseUrls($"http://127.0.0.1:{port}") - .Configure(ConfigureEchoAddress); + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseUrls($"http://127.0.0.1:{port}") + .Configure(ConfigureEchoAddress); + }); using (var host = hostBuilder.Build()) { @@ -547,11 +578,15 @@ public void ThrowsWhenBindingToIPv6AddressInUse() socket.Listen(0); var port = ((IPEndPoint)socket.LocalEndPoint).Port; - var hostBuilder = TransportSelector.GetWebHostBuilder() - .ConfigureServices(AddTestLogging) - .UseKestrel() - .UseUrls($"http://[::1]:{port}") - .Configure(ConfigureEchoAddress); + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseUrls($"http://[::1]:{port}") + .Configure(ConfigureEchoAddress); + }) + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -565,18 +600,22 @@ public void ThrowsWhenBindingToIPv6AddressInUse() public async Task OverrideDirectConfigurationWithIServerAddressesFeature_Succeeds() { var useUrlsAddress = $"http://127.0.0.1:0"; - var hostBuilder = TransportSelector.GetWebHostBuilder() - .UseKestrel(options => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => - { - listenOptions.UseHttps(TestResources.GetTestCertificate()); - }); + webHostBuilder + .UseKestrel(options => + { + options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => + { + listenOptions.UseHttps(TestResources.GetTestCertificate()); + }); + }) + .UseUrls(useUrlsAddress) + .PreferHostingUrls(true) + .Configure(ConfigureEchoAddress); }) - .UseUrls(useUrlsAddress) - .PreferHostingUrls(true) - .ConfigureServices(AddTestLogging) - .Configure(ConfigureEchoAddress); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -586,7 +625,7 @@ public async Task OverrideDirectConfigurationWithIServerAddressesFeature_Succeed // If this isn't working properly, we'll get the HTTPS endpoint defined in UseKestrel // instead of the HTTP endpoint defined in UseUrls. - var serverAddresses = host.ServerFeatures.Get().Addresses; + var serverAddresses = host.Services.GetRequiredService().Features.Get().Addresses; Assert.Equal(1, serverAddresses.Count); var useUrlsAddressWithPort = $"http://127.0.0.1:{port}"; Assert.Equal(serverAddresses.First(), useUrlsAddressWithPort); @@ -606,18 +645,22 @@ public async Task DoesNotOverrideDirectConfigurationWithIServerAddressesFeature_ { var useUrlsAddress = $"http://127.0.0.1:0"; - var hostBuilder = TransportSelector.GetWebHostBuilder() - .ConfigureServices(AddTestLogging) - .UseKestrel(options => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => - { - listenOptions.UseHttps(TestResources.TestCertificatePath, "testPassword"); - }); + webHostBuilder + .UseKestrel(options => + { + options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => + { + listenOptions.UseHttps(TestResources.TestCertificatePath, "testPassword"); + }); + }) + .UseUrls($"http://127.0.0.1:0") + .PreferHostingUrls(false) + .Configure(ConfigureEchoAddress); }) - .UseUrls($"http://127.0.0.1:0") - .PreferHostingUrls(false) - .Configure(ConfigureEchoAddress); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -627,7 +670,7 @@ public async Task DoesNotOverrideDirectConfigurationWithIServerAddressesFeature_ // If this isn't working properly, we'll get the HTTP endpoint defined in UseUrls // instead of the HTTPS endpoint defined in UseKestrel. - var serverAddresses = host.ServerFeatures.Get().Addresses; + var serverAddresses = host.Services.GetRequiredService().Features.Get().Addresses; Assert.Equal(1, serverAddresses.Count); var endPointAddress = $"https://127.0.0.1:{port}"; Assert.Equal(serverAddresses.First(), endPointAddress); @@ -644,17 +687,21 @@ public async Task DoesNotOverrideDirectConfigurationWithIServerAddressesFeature_ [Fact] public async Task DoesNotOverrideDirectConfigurationWithIServerAddressesFeature_IfAddressesEmpty() { - var hostBuilder = TransportSelector.GetWebHostBuilder() - .ConfigureServices(AddTestLogging) - .UseKestrel(options => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => - { - listenOptions.UseHttps(TestResources.GetTestCertificate()); - }); + webHostBuilder + .UseKestrel(options => + { + options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => + { + listenOptions.UseHttps(TestResources.GetTestCertificate()); + }); + }) + .PreferHostingUrls(true) + .Configure(ConfigureEchoAddress); }) - .PreferHostingUrls(true) - .Configure(ConfigureEchoAddress); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -663,7 +710,7 @@ public async Task DoesNotOverrideDirectConfigurationWithIServerAddressesFeature_ var port = host.GetPort(); // If this isn't working properly, we'll not get the HTTPS endpoint defined in UseKestrel. - var serverAddresses = host.ServerFeatures.Get().Addresses; + var serverAddresses = host.Services.GetRequiredService().Features.Get().Addresses; Assert.Equal(1, serverAddresses.Count); var endPointAddress = $"https://127.0.0.1:{port}"; Assert.Equal(serverAddresses.First(), endPointAddress); @@ -692,11 +739,15 @@ public void ThrowsWhenBindingLocalhostToDynamicPort() { TestApplicationErrorLogger.IgnoredExceptions.Add(typeof(InvalidOperationException)); - var hostBuilder = TransportSelector.GetWebHostBuilder() - .ConfigureServices(AddTestLogging) - .UseKestrel() - .UseUrls("http://localhost:0") - .Configure(ConfigureEchoAddress); + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseUrls("http://localhost:0") + .Configure(ConfigureEchoAddress); + }) + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -711,11 +762,15 @@ public void ThrowsForUnsupportedAddressFromHosting(string address) { TestApplicationErrorLogger.IgnoredExceptions.Add(typeof(InvalidOperationException)); - var hostBuilder = TransportSelector.GetWebHostBuilder() - .ConfigureServices(AddTestLogging) - .UseKestrel() - .UseUrls(address) - .Configure(ConfigureEchoAddress); + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseUrls(address) + .Configure(ConfigureEchoAddress); + }) + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -729,13 +784,17 @@ public async Task CanRebindToEndPoint() var port = GetNextPort(); var endPointAddress = $"http://127.0.0.1:{port}/"; - var hostBuilder = TransportSelector.GetWebHostBuilder() - .ConfigureServices(AddTestLogging) - .UseKestrel(options => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(IPAddress.Loopback, port); + webHostBuilder + .UseKestrel(options => + { + options.Listen(IPAddress.Loopback, port); + }) + .Configure(ConfigureEchoAddress); }) - .Configure(ConfigureEchoAddress); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -746,12 +805,16 @@ public async Task CanRebindToEndPoint() await host.StopAsync(); } - hostBuilder = TransportSelector.GetWebHostBuilder() - .UseKestrel(options => + hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(IPAddress.Loopback, port); - }) - .Configure(ConfigureEchoAddress); + webHostBuilder + .UseKestrel(options => + { + options.Listen(IPAddress.Loopback, port); + }) + .Configure(ConfigureEchoAddress); + }); using (var host = hostBuilder.Build()) { @@ -771,14 +834,18 @@ public async Task CanRebindToMultipleEndPoints() var ipv4endPointAddress = $"http://127.0.0.1:{port}/"; var ipv6endPointAddress = $"http://[::1]:{port}/"; - var hostBuilder = TransportSelector.GetWebHostBuilder() - .ConfigureServices(AddTestLogging) - .UseKestrel(options => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(IPAddress.Loopback, port); - options.Listen(IPAddress.IPv6Loopback, port); + webHostBuilder + .UseKestrel(options => + { + options.Listen(IPAddress.Loopback, port); + options.Listen(IPAddress.IPv6Loopback, port); + }) + .Configure(ConfigureEchoAddress); }) - .Configure(ConfigureEchoAddress); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -790,13 +857,17 @@ public async Task CanRebindToMultipleEndPoints() await host.StopAsync(); } - hostBuilder = TransportSelector.GetWebHostBuilder() - .UseKestrel(options => + hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(IPAddress.Loopback, port); - options.Listen(IPAddress.IPv6Loopback, port); - }) - .Configure(ConfigureEchoAddress); + webHostBuilder + .UseKestrel(options => + { + options.Listen(IPAddress.Loopback, port); + options.Listen(IPAddress.IPv6Loopback, port); + }) + .Configure(ConfigureEchoAddress); + }); using (var host = hostBuilder.Build()) { @@ -816,20 +887,24 @@ public async Task CanRebindToMultipleEndPoints() public async Task EndpointDefaultsConfig_CanSetProtocolForUrlsConfig(string input, HttpProtocols expected) { KestrelServerOptions capturedOptions = null; - var hostBuilder = TransportSelector.GetWebHostBuilder() - .UseKestrel(options => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - var config = new ConfigurationBuilder().AddInMemoryCollection(new[] - { - new KeyValuePair("EndpointDefaults:Protocols", input), - }).Build(); - options.Configure(config); - - capturedOptions = options; + webHostBuilder + .UseKestrel(options => + { + var config = new ConfigurationBuilder().AddInMemoryCollection(new[] + { + new KeyValuePair("EndpointDefaults:Protocols", input), + }).Build(); + options.Configure(config); + + capturedOptions = options; + }) + .UseUrls("http://127.0.0.1:0") + .Configure(ConfigureEchoAddress); }) - .ConfigureServices(AddTestLogging) - .UseUrls("http://127.0.0.1:0") - .Configure(ConfigureEchoAddress); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -875,11 +950,15 @@ private void ThrowsWhenBindingLocalhostToAddressInUse(AddressFamily addressFamil continue; } - var hostBuilder = TransportSelector.GetWebHostBuilder() - .ConfigureServices(AddTestLogging) - .UseKestrel() - .UseUrls($"http://localhost:{port}") - .Configure(ConfigureEchoAddress); + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseUrls($"http://localhost:{port}") + .Configure(ConfigureEchoAddress); + }) + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { diff --git a/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs b/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs index 430e7fbfd012..2120bcb7b622 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs @@ -15,6 +15,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging.Testing; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests @@ -281,67 +282,71 @@ public async Task ServerShutsDownGracefullyWhenMaxRequestBufferSizeExceeded() await memoryPoolFactory.WhenAllBlocksReturned(TestConstants.DefaultTimeout); } - private async Task StartWebHost(long? maxRequestBufferSize, + private async Task StartWebHost(long? maxRequestBufferSize, byte[] expectedBody, bool useConnectionAdapter, TaskCompletionSource startReadingRequestBody, TaskCompletionSource clientFinishedSendingRequestBody, Func> memoryPoolFactory = null) { - var host = TransportSelector.GetWebHostBuilder(memoryPoolFactory, maxRequestBufferSize) - .ConfigureServices(AddTestLogging) - .UseKestrel(options => + var host = TransportSelector.GetHostBuilder(memoryPoolFactory, maxRequestBufferSize) + .ConfigureWebHost(webHostBuilder=> { - options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => - { - if (useConnectionAdapter) + webHostBuilder + .UseKestrel(options => { - listenOptions.UsePassThrough(); - } - }); - - options.Limits.MaxRequestBufferSize = maxRequestBufferSize; - - if (maxRequestBufferSize.HasValue && - maxRequestBufferSize.Value < options.Limits.MaxRequestLineSize) - { - options.Limits.MaxRequestLineSize = (int)maxRequestBufferSize; - } - - if (maxRequestBufferSize.HasValue && - maxRequestBufferSize.Value < options.Limits.MaxRequestHeadersTotalSize) - { - options.Limits.MaxRequestHeadersTotalSize = (int)maxRequestBufferSize; - } - - options.Limits.MinRequestBodyDataRate = null; - - options.Limits.MaxRequestBodySize = _dataLength; + options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => + { + if (useConnectionAdapter) + { + listenOptions.UsePassThrough(); + } + }); + + options.Limits.MaxRequestBufferSize = maxRequestBufferSize; + + if (maxRequestBufferSize.HasValue && + maxRequestBufferSize.Value < options.Limits.MaxRequestLineSize) + { + options.Limits.MaxRequestLineSize = (int)maxRequestBufferSize; + } + + if (maxRequestBufferSize.HasValue && + maxRequestBufferSize.Value < options.Limits.MaxRequestHeadersTotalSize) + { + options.Limits.MaxRequestHeadersTotalSize = (int)maxRequestBufferSize; + } + + options.Limits.MinRequestBodyDataRate = null; + + options.Limits.MaxRequestBodySize = _dataLength; + }) + .UseContentRoot(Directory.GetCurrentDirectory()) + .Configure(app => app.Run(async context => + { + await startReadingRequestBody.Task.TimeoutAfter(TimeSpan.FromSeconds(120)); + + var buffer = new byte[expectedBody.Length]; + var bytesRead = 0; + while (bytesRead < buffer.Length) + { + bytesRead += await context.Request.Body.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead); + } + + await clientFinishedSendingRequestBody.Task.TimeoutAfter(TimeSpan.FromSeconds(120)); + + // Verify client didn't send extra bytes + if (await context.Request.Body.ReadAsync(new byte[1], 0, 1) != 0) + { + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + await context.Response.WriteAsync("Client sent more bytes than expectedBody.Length"); + return; + } + + await context.Response.WriteAsync($"bytesRead: {bytesRead.ToString()}"); + })); }) - .UseContentRoot(Directory.GetCurrentDirectory()) - .Configure(app => app.Run(async context => - { - await startReadingRequestBody.Task.TimeoutAfter(TimeSpan.FromSeconds(120)); - - var buffer = new byte[expectedBody.Length]; - var bytesRead = 0; - while (bytesRead < buffer.Length) - { - bytesRead += await context.Request.Body.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead); - } - - await clientFinishedSendingRequestBody.Task.TimeoutAfter(TimeSpan.FromSeconds(120)); - - // Verify client didn't send extra bytes - if (await context.Request.Body.ReadAsync(new byte[1], 0, 1) != 0) - { - context.Response.StatusCode = StatusCodes.Status500InternalServerError; - await context.Response.WriteAsync("Client sent more bytes than expectedBody.Length"); - return; - } - - await context.Response.WriteAsync($"bytesRead: {bytesRead.ToString()}"); - })) + .ConfigureServices(AddTestLogging) .Build(); await host.StartAsync(); diff --git a/src/Servers/Kestrel/test/FunctionalTests/RequestTests.cs b/src/Servers/Kestrel/test/FunctionalTests/RequestTests.cs index 3086fbc40d41..44ab8e0b03e9 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/RequestTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/RequestTests.cs @@ -23,6 +23,7 @@ using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; +using Microsoft.Extensions.Hosting; using Moq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -55,39 +56,43 @@ public async Task LargeUpload(long contentLength, bool checkBytes) Assert.True(contentLength % bufferLength == 0, $"{nameof(contentLength)} sent must be evenly divisible by {bufferLength}."); Assert.True(bufferLength % 256 == 0, $"{nameof(bufferLength)} must be evenly divisible by 256"); - var builder = TransportSelector.GetWebHostBuilder() - .ConfigureServices(AddTestLogging) - .UseKestrel(options => + var builder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Limits.MaxRequestBodySize = contentLength; - options.Limits.MinRequestBodyDataRate = null; - }) - .UseUrls("http://127.0.0.1:0/") - .Configure(app => - { - app.Run(async context => - { - // Read the full request body - long total = 0; - var receivedBytes = new byte[bufferLength]; - var received = 0; - while ((received = await context.Request.Body.ReadAsync(receivedBytes, 0, receivedBytes.Length)) > 0) + webHostBuilder + .UseKestrel(options => { - if (checkBytes) + options.Limits.MaxRequestBodySize = contentLength; + options.Limits.MinRequestBodyDataRate = null; + }) + .UseUrls("http://127.0.0.1:0/") + .Configure(app => + { + app.Run(async context => { - for (var i = 0; i < received; i++) + // Read the full request body + long total = 0; + var receivedBytes = new byte[bufferLength]; + var received = 0; + while ((received = await context.Request.Body.ReadAsync(receivedBytes, 0, receivedBytes.Length)) > 0) { - // Do not use Assert.Equal here, it is to slow for this hot path - Assert.True((byte)((total + i) % 256) == receivedBytes[i], "Data received is incorrect"); + if (checkBytes) + { + for (var i = 0; i < received; i++) + { + // Do not use Assert.Equal here, it is to slow for this hot path + Assert.True((byte)((total + i) % 256) == receivedBytes[i], "Data received is incorrect"); + } + } + + total += received; } - } - total += received; - } - - await context.Response.WriteAsync($"bytesRead: {total.ToString()}"); - }); - }); + await context.Response.WriteAsync($"bytesRead: {total.ToString()}"); + }); + }); + }) + .ConfigureServices(AddTestLogging); using (var host = builder.Build()) { @@ -140,17 +145,21 @@ public Task RemoteIPv6Address() [Fact] public async Task DoesNotHangOnConnectionCloseRequest() { - var builder = TransportSelector.GetWebHostBuilder() - .UseKestrel() - .UseUrls("http://127.0.0.1:0") - .ConfigureServices(AddTestLogging) - .Configure(app => + var builder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Run(async context => - { - await context.Response.WriteAsync("hello, world"); - }); - }); + webHostBuilder + .UseKestrel() + .UseUrls("http://127.0.0.1:0") + .Configure(app => + { + app.Run(async context => + { + await context.Response.WriteAsync("hello, world"); + }); + }); + }) + .ConfigureServices(AddTestLogging); using (var host = builder.Build()) using (var client = new HttpClient()) @@ -392,26 +401,30 @@ public async Task ThrowsOnReadAfterConnectionError() var appDone = new SemaphoreSlim(0); var expectedExceptionThrown = false; - var builder = TransportSelector.GetWebHostBuilder() - .ConfigureServices(AddTestLogging) - .UseKestrel() - .UseUrls("http://127.0.0.1:0") - .Configure(app => app.Run(async context => + var builder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - requestStarted.Release(); - Assert.True(await connectionReset.WaitAsync(_semaphoreWaitTimeout)); + webHostBuilder + .UseKestrel() + .UseUrls("http://127.0.0.1:0") + .Configure(app => app.Run(async context => + { + requestStarted.Release(); + Assert.True(await connectionReset.WaitAsync(_semaphoreWaitTimeout)); - try - { - await context.Request.Body.ReadAsync(new byte[1], 0, 1); - } - catch (ConnectionResetException) - { - expectedExceptionThrown = true; - } + try + { + await context.Request.Body.ReadAsync(new byte[1], 0, 1); + } + catch (ConnectionResetException) + { + expectedExceptionThrown = true; + } - appDone.Release(); - })); + appDone.Release(); + })); + }) + .ConfigureServices(AddTestLogging); using (var host = builder.Build()) { @@ -439,18 +452,22 @@ public async Task RequestAbortedTokenFiredOnClientFIN() { var appStarted = new SemaphoreSlim(0); var requestAborted = new SemaphoreSlim(0); - var builder = TransportSelector.GetWebHostBuilder() - .UseKestrel() - .UseUrls("http://127.0.0.1:0") - .ConfigureServices(AddTestLogging) - .Configure(app => app.Run(async context => + var builder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - appStarted.Release(); + webHostBuilder + .UseKestrel() + .UseUrls("http://127.0.0.1:0") + .Configure(app => app.Run(async context => + { + appStarted.Release(); - var token = context.RequestAborted; - token.Register(() => requestAborted.Release(2)); - await requestAborted.WaitAsync().DefaultTimeout(); - })); + var token = context.RequestAborted; + token.Register(() => requestAborted.Release(2)); + await requestAborted.WaitAsync().DefaultTimeout(); + })); + }) + .ConfigureServices(AddTestLogging); using (var host = builder.Build()) { @@ -472,15 +489,19 @@ public async Task RequestAbortedTokenFiredOnClientFIN() [Fact] public async Task AbortingTheConnectionSendsFIN() { - var builder = TransportSelector.GetWebHostBuilder() - .UseKestrel() - .UseUrls("http://127.0.0.1:0") - .ConfigureServices(AddTestLogging) - .Configure(app => app.Run(context => + var builder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - context.Abort(); - return Task.CompletedTask; - })); + webHostBuilder + .UseKestrel() + .UseUrls("http://127.0.0.1:0") + .Configure(app => app.Run(context => + { + context.Abort(); + return Task.CompletedTask; + })); + }) + .ConfigureServices(AddTestLogging); using (var host = builder.Build()) { @@ -842,24 +863,28 @@ await connection.Send( private async Task TestRemoteIPAddress(string registerAddress, string requestAddress, string expectAddress) { - var builder = TransportSelector.GetWebHostBuilder() - .UseKestrel() - .UseUrls($"http://{registerAddress}:0") - .ConfigureServices(AddTestLogging) - .Configure(app => + var builder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Run(async context => - { - var connection = context.Connection; - await context.Response.WriteAsync(JsonConvert.SerializeObject(new + webHostBuilder + .UseKestrel() + .UseUrls($"http://{registerAddress}:0") + .Configure(app => { - RemoteIPAddress = connection.RemoteIpAddress?.ToString(), - RemotePort = connection.RemotePort, - LocalIPAddress = connection.LocalIpAddress?.ToString(), - LocalPort = connection.LocalPort - })); - }); - }); + app.Run(async context => + { + var connection = context.Connection; + await context.Response.WriteAsync(JsonConvert.SerializeObject(new + { + RemoteIPAddress = connection.RemoteIpAddress?.ToString(), + RemotePort = connection.RemotePort, + LocalIPAddress = connection.LocalIpAddress?.ToString(), + LocalPort = connection.LocalPort + })); + }); + }); + }) + .ConfigureServices(AddTestLogging); using (var host = builder.Build()) using (var client = new HttpClient()) diff --git a/src/Servers/Kestrel/test/FunctionalTests/ResponseTests.cs b/src/Servers/Kestrel/test/FunctionalTests/ResponseTests.cs index ba88bd678448..11e86e8a2032 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/ResponseTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/ResponseTests.cs @@ -23,6 +23,7 @@ using Microsoft.AspNetCore.Server.Kestrel.Https.Internal; using Microsoft.AspNetCore.Server.Kestrel.Tests; using Microsoft.AspNetCore.Testing; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Primitives; @@ -42,28 +43,32 @@ public class ResponseTests : TestApplicationErrorLoggerLoggedTest [Fact] public async Task LargeDownload() { - var hostBuilder = TransportSelector.GetWebHostBuilder() - .UseKestrel() - .UseUrls("http://127.0.0.1:0/") - .ConfigureServices(AddTestLogging) - .Configure(app => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Run(async context => - { - var bytes = new byte[1024]; - for (int i = 0; i < bytes.Length; i++) + webHostBuilder + .UseKestrel() + .UseUrls("http://127.0.0.1:0/") + .Configure(app => { - bytes[i] = (byte)i; - } - - context.Response.ContentLength = bytes.Length * 1024; - - for (int i = 0; i < 1024; i++) - { - await context.Response.BodyWriter.WriteAsync(new Memory(bytes, 0, bytes.Length)); - } - }); - }); + app.Run(async context => + { + var bytes = new byte[1024]; + for (int i = 0; i < bytes.Length; i++) + { + bytes[i] = (byte)i; + } + + context.Response.ContentLength = bytes.Length * 1024; + + for (int i = 0; i < 1024; i++) + { + await context.Response.BodyWriter.WriteAsync(new Memory(bytes, 0, bytes.Length)); + } + }); + }); + }) + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -96,19 +101,23 @@ public async Task LargeDownload() [Theory, MemberData(nameof(NullHeaderData))] public async Task IgnoreNullHeaderValues(string headerName, StringValues headerValue, string expectedValue) { - var hostBuilder = TransportSelector.GetWebHostBuilder() - .UseKestrel() - .UseUrls("http://127.0.0.1:0/") - .ConfigureServices(AddTestLogging) - .Configure(app => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Run(async context => - { - context.Response.Headers.Add(headerName, headerValue); - - await context.Response.WriteAsync(""); - }); - }); + webHostBuilder + .UseKestrel() + .UseUrls("http://127.0.0.1:0/") + .Configure(app => + { + app.Run(async context => + { + context.Response.Headers.Add(headerName, headerValue); + + await context.Response.WriteAsync(""); + }); + }); + }) + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { diff --git a/src/Servers/Kestrel/test/FunctionalTests/UnixDomainSocketsTests.cs b/src/Servers/Kestrel/test/FunctionalTests/UnixDomainSocketsTests.cs index 7d83625ae2b3..689fc5b3f2a4 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/UnixDomainSocketsTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/UnixDomainSocketsTests.cs @@ -15,6 +15,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Testing; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Xunit; @@ -72,16 +73,20 @@ async Task EchoServer(ConnectionContext connection) } } - var hostBuilder = TransportSelector.GetWebHostBuilder() - .UseKestrel(o => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - o.ListenUnixSocket(path, builder => - { - builder.Run(EchoServer); - }); + webHostBuilder + .UseKestrel(o => + { + o.ListenUnixSocket(path, builder => + { + builder.Run(EchoServer); + }); + }) + .Configure(c => { }); }) - .ConfigureServices(AddTestLogging) - .Configure(c => { }); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -100,7 +105,10 @@ async Task EchoServer(ConnectionContext connection) { var bytesReceived = await socket.ReceiveAsync(buffer.AsMemory(read, buffer.Length - read), SocketFlags.None).DefaultTimeout(); read += bytesReceived; - if (bytesReceived <= 0) break; + if (bytesReceived <= 0) + { + break; + } } Assert.Equal(data, buffer); @@ -134,17 +142,21 @@ public async Task TestUnixDomainSocketWithUrl() try { - var hostBuilder = TransportSelector.GetWebHostBuilder() - .UseUrls(url) - .UseKestrel() - .ConfigureServices(AddTestLogging) - .Configure(app => + var hostBuilder = TransportSelector.GetHostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Run(async context => - { - await context.Response.WriteAsync("Hello World"); - }); - }); + webHostBuilder + .UseUrls(url) + .UseKestrel() + .Configure(app => + { + app.Run(async context => + { + await context.Response.WriteAsync("Hello World"); + }); + }); + }) + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { @@ -165,7 +177,10 @@ public async Task TestUnixDomainSocketWithUrl() { var bytesReceived = await socket.ReceiveAsync(readBuffer.AsMemory(read), SocketFlags.None).DefaultTimeout(); read += bytesReceived; - if (bytesReceived <= 0) break; + if (bytesReceived <= 0) + { + break; + } } var httpResponse = Encoding.ASCII.GetString(readBuffer, 0, read); diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs index 27c0395ed512..73ec6146e3e9 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs @@ -16,6 +16,7 @@ using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport @@ -28,7 +29,7 @@ internal class TestServer : IAsyncDisposable, IDisposable, IStartup private readonly MemoryPool _memoryPool; private readonly RequestDelegate _app; private readonly InMemoryTransportFactory _transportFactory; - private readonly IWebHost _host; + private readonly IHost _host; public TestServer(RequestDelegate app) : this(app, new TestServiceContext()) @@ -69,8 +70,12 @@ public TestServer(RequestDelegate app, TestServiceContext context, Action + { + webHostBuilder + .UseSetting(WebHostDefaults.ShutdownTimeoutKey, TestConstants.DefaultTimeout.TotalSeconds.ToString()); + }) .ConfigureServices(services => { configureServices(services); diff --git a/src/Servers/Kestrel/test/Interop.FunctionalTests/ChromeTests.cs b/src/Servers/Kestrel/test/Interop.FunctionalTests/ChromeTests.cs index 80cb4e890e50..4e940a66bc09 100644 --- a/src/Servers/Kestrel/test/Interop.FunctionalTests/ChromeTests.cs +++ b/src/Servers/Kestrel/test/Interop.FunctionalTests/ChromeTests.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Testing; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using OpenQA.Selenium.Chrome; @@ -46,7 +47,7 @@ private void InitializeArgs() StartupLogPath = Path.Combine(ResolvedLogOutputDirectory, $"{ResolvedTestMethodName}.su.json"); ShutdownLogPath = Path.Combine(ResolvedLogOutputDirectory, $"{ResolvedTestMethodName}.sd.json"); - ChromeArgs = new [] { + ChromeArgs = new[] { $"--headless", $"--no-sandbox", $"--disable-gpu", @@ -62,7 +63,7 @@ private void InitializeArgs() }; } - [ConditionalTheory(Skip="Disabling while debugging. https://github.com/dotnet/aspnetcore-internal/issues/1363")] + [ConditionalTheory(Skip = "Disabling while debugging. https://github.com/dotnet/aspnetcore-internal/issues/1363")] [OSSkipCondition(OperatingSystems.MacOSX, SkipReason = "Missing SslStream ALPN support: https://github.com/dotnet/corefx/issues/30492")] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win81, SkipReason = "Missing Windows ALPN support: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation#Support")] [InlineData("", "Interop HTTP/2 GET")] @@ -71,27 +72,31 @@ public async Task Http2(string requestSuffix, string expectedResponse) { InitializeArgs(); - var hostBuilder = new WebHostBuilder() - .UseKestrel(options => + var hostBuilder = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(IPAddress.Loopback, 0, listenOptions => - { - listenOptions.Protocols = HttpProtocols.Http2; - listenOptions.UseHttps(TestResources.GetTestCertificate()); - }); + webHostBuilder + .UseKestrel(options => + { + options.Listen(IPAddress.Loopback, 0, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http2; + listenOptions.UseHttps(TestResources.GetTestCertificate()); + }); + }) + .Configure(app => app.Run(async context => + { + if (HttpMethods.IsPost(context.Request.Query["TestMethod"])) + { + await context.Response.WriteAsync(_postHtml); + } + else + { + await context.Response.WriteAsync($"Interop {context.Request.Protocol} {context.Request.Method}"); + } + })); }) - .ConfigureServices(AddTestLogging) - .Configure(app => app.Run(async context => - { - if (HttpMethods.IsPost(context.Request.Query["TestMethod"])) - { - await context.Response.WriteAsync(_postHtml); - } - else - { - await context.Response.WriteAsync($"Interop {context.Request.Protocol} {context.Request.Method}"); - } - })); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { diff --git a/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecTests.cs b/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecTests.cs index d7ea94abdd4a..6594cafff81f 100644 --- a/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecTests.cs +++ b/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecTests.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Testing; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging.Testing; using Xunit; using Xunit.Abstractions; @@ -23,20 +24,24 @@ public class H2SpecTests : LoggedTest [MemberData(nameof(H2SpecTestCases))] public async Task RunIndividualTestCase(H2SpecTestCase testCase) { - var hostBuilder = new WebHostBuilder() - .UseKestrel(options => + var hostBuilder = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(IPAddress.Loopback, 0, listenOptions => - { - listenOptions.Protocols = HttpProtocols.Http2; - if (testCase.Https) + webHostBuilder + .UseKestrel(options => { - listenOptions.UseHttps(TestResources.GetTestCertificate()); - } - }); + options.Listen(IPAddress.Loopback, 0, listenOptions => + { + listenOptions.Protocols = HttpProtocols.Http2; + if (testCase.Https) + { + listenOptions.UseHttps(TestResources.GetTestCertificate()); + } + }); + }) + .Configure(ConfigureHelloWorld); }) - .ConfigureServices(AddTestLogging) - .Configure(ConfigureHelloWorld); + .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { diff --git a/src/Servers/Kestrel/test/Libuv.FunctionalTests/TransportSelector.cs b/src/Servers/Kestrel/test/Libuv.FunctionalTests/TransportSelector.cs index 4bd8e32597fb..52061a2ac4d0 100644 --- a/src/Servers/Kestrel/test/Libuv.FunctionalTests/TransportSelector.cs +++ b/src/Servers/Kestrel/test/Libuv.FunctionalTests/TransportSelector.cs @@ -4,20 +4,26 @@ using System; using System.Buffers; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests { public static class TransportSelector { - public static IWebHostBuilder GetWebHostBuilder(Func> memoryPoolFactory = null, + public static IHostBuilder GetHostBuilder(Func> memoryPoolFactory = null, long? maxReadBufferSize = null) { #pragma warning disable CS0618 - return new WebHostBuilder().UseLibuv(options => - { - options.MemoryPoolFactory = memoryPoolFactory ?? options.MemoryPoolFactory; - options.MaxReadBufferSize = maxReadBufferSize; - }); + return new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseLibuv(options => + { + options.MemoryPoolFactory = memoryPoolFactory ?? options.MemoryPoolFactory; + options.MaxReadBufferSize = maxReadBufferSize; + }); + }); #pragma warning restore CS0618 } } From f1aa24d4f9dfb82fef87e73b73957f0cdef89169 Mon Sep 17 00:00:00 2001 From: Kahbazi Date: Fri, 24 Jul 2020 18:40:27 +0430 Subject: [PATCH 02/13] Change TransportSelector --- .../TransportSelector.cs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/Servers/Kestrel/test/Sockets.FunctionalTests/TransportSelector.cs b/src/Servers/Kestrel/test/Sockets.FunctionalTests/TransportSelector.cs index 6d2461866ef6..f50831654436 100644 --- a/src/Servers/Kestrel/test/Sockets.FunctionalTests/TransportSelector.cs +++ b/src/Servers/Kestrel/test/Sockets.FunctionalTests/TransportSelector.cs @@ -4,19 +4,25 @@ using System; using System.Buffers; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests { public static class TransportSelector { - public static IWebHostBuilder GetWebHostBuilder(Func> memoryPoolFactory = null, + public static IHostBuilder GetHostBuilder(Func> memoryPoolFactory = null, long? maxReadBufferSize = null) { - return new WebHostBuilder().UseSockets(options => - { - options.MemoryPoolFactory = memoryPoolFactory ?? options.MemoryPoolFactory; - options.MaxReadBufferSize = maxReadBufferSize; - }); + return new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseSockets(options => + { + options.MemoryPoolFactory = memoryPoolFactory ?? options.MemoryPoolFactory; + options.MaxReadBufferSize = maxReadBufferSize; + }); + }); } } } From ab77c04cdd8cdff64f5ecbe8f86b81e44d40564d Mon Sep 17 00:00:00 2001 From: Kahbazi Date: Sat, 25 Jul 2020 10:58:53 +0430 Subject: [PATCH 03/13] Add an empty app for TestServer --- .../Kestrel/shared/test/TransportTestHelpers/TestServer.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs b/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs index ce3380083971..0d1071eca012 100644 --- a/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs +++ b/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs @@ -98,7 +98,8 @@ public TestServer(RequestDelegate app, TestServiceContext context, Action { }); }) .Build(); From 909ca9112de5672b87bad9ec86b2822bb0a64ae6 Mon Sep 17 00:00:00 2001 From: Kahbazi Date: Sat, 25 Jul 2020 12:51:33 +0430 Subject: [PATCH 04/13] Add an empty app for TestServer --- .../test/InMemory.FunctionalTests/TestTransport/TestServer.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs index 73ec6146e3e9..10e875c13026 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs @@ -74,7 +74,8 @@ public TestServer(RequestDelegate app, TestServiceContext context, Action { webHostBuilder - .UseSetting(WebHostDefaults.ShutdownTimeoutKey, TestConstants.DefaultTimeout.TotalSeconds.ToString()); + .UseSetting(WebHostDefaults.ShutdownTimeoutKey, TestConstants.DefaultTimeout.TotalSeconds.ToString()) + .Configure(app => { }); }) .ConfigureServices(services => { From c47b03e384fafa5c26fc6606e74de20817be7543 Mon Sep 17 00:00:00 2001 From: Kahbazi Date: Sat, 25 Jul 2020 15:23:22 +0430 Subject: [PATCH 05/13] Set app --- .../Kestrel/shared/test/TransportTestHelpers/TestServer.cs | 2 +- .../test/InMemory.FunctionalTests/TestTransport/TestServer.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs b/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs index 0d1071eca012..a21358bb9e04 100644 --- a/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs +++ b/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs @@ -99,7 +99,7 @@ public TestServer(RequestDelegate app, TestServiceContext context, Action { }); + .Configure(app => { app.Run(_app); }); }) .Build(); diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs index 10e875c13026..757b747b9bb3 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs @@ -75,7 +75,7 @@ public TestServer(RequestDelegate app, TestServiceContext context, Action { }); + .Configure(app => { app.Run(_app); }); }) .ConfigureServices(services => { From bd86164274a0b97d3821f3c2168e968528690195 Mon Sep 17 00:00:00 2001 From: Kahbazi Date: Tue, 28 Jul 2020 17:14:33 +0430 Subject: [PATCH 06/13] Stop host --- .../MaxRequestBufferSizeTests.cs | 10 +- .../BadHttpRequestTests.cs | 2 +- .../HttpProtocolSelectionTests.cs | 1 + .../InMemory.FunctionalTests/RequestTests.cs | 31 ++++ .../InMemory.FunctionalTests/ResponseTests.cs | 133 ++++++++++++++++++ .../TestTransport/TestServer.cs | 2 +- 6 files changed, 173 insertions(+), 6 deletions(-) diff --git a/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs b/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs index 2120bcb7b622..4fad2f421ef9 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs @@ -17,6 +17,8 @@ using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Hosting; using Xunit; +using Microsoft.Extensions.DependencyInjection; +using System.Threading; namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests { @@ -125,7 +127,7 @@ public async Task LargeUpload(long? maxRequestBufferSize, bool connectionAdapter var memoryPoolFactory = new DiagnosticMemoryPoolFactory(allowLateReturn: true); - using (var host = await StartWebHost(maxRequestBufferSize, data, connectionAdapter, startReadingRequestBody, clientFinishedSendingRequestBody, memoryPoolFactory.Create)) + using (var host = await StartHost(maxRequestBufferSize, data, connectionAdapter, startReadingRequestBody, clientFinishedSendingRequestBody, memoryPoolFactory.Create)) { var port = host.GetPort(); using (var socket = CreateSocket(port)) @@ -218,7 +220,7 @@ public async Task ServerShutsDownGracefullyWhenMaxRequestBufferSizeExceeded() var memoryPoolFactory = new DiagnosticMemoryPoolFactory(allowLateReturn: true); - using (var host = await StartWebHost(16 * 1024, data, false, startReadingRequestBody, clientFinishedSendingRequestBody, memoryPoolFactory.Create)) + using (var host = await StartHost(16 * 1024, data, false, startReadingRequestBody, clientFinishedSendingRequestBody, memoryPoolFactory.Create)) { var port = host.GetPort(); using (var socket = CreateSocket(port)) @@ -282,7 +284,7 @@ public async Task ServerShutsDownGracefullyWhenMaxRequestBufferSizeExceeded() await memoryPoolFactory.WhenAllBlocksReturned(TestConstants.DefaultTimeout); } - private async Task StartWebHost(long? maxRequestBufferSize, + private async Task StartHost(long? maxRequestBufferSize, byte[] expectedBody, bool useConnectionAdapter, TaskCompletionSource startReadingRequestBody, @@ -290,7 +292,7 @@ private async Task StartWebHost(long? maxRequestBufferSize, Func> memoryPoolFactory = null) { var host = TransportSelector.GetHostBuilder(memoryPoolFactory, maxRequestBufferSize) - .ConfigureWebHost(webHostBuilder=> + .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/BadHttpRequestTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/BadHttpRequestTests.cs index 58ee05782495..cf67cf5d0432 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/BadHttpRequestTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/BadHttpRequestTests.cs @@ -169,7 +169,7 @@ await connection.SendAll( } } - Assert.All(TestSink.Writes, w => Assert.InRange(w.LogLevel, LogLevel.Trace, LogLevel.Debug)); + Assert.All(TestSink.Writes.Where(w => w.LoggerName != "Microsoft.Hosting.Lifetime"), w => Assert.InRange(w.LogLevel, LogLevel.Trace, LogLevel.Debug)); Assert.Contains(TestSink.Writes, w => w.EventId.Id == 17); } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpProtocolSelectionTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpProtocolSelectionTests.cs index 8b29ad1a13aa..7712e2df3068 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpProtocolSelectionTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpProtocolSelectionTests.cs @@ -70,6 +70,7 @@ private async Task TestSuccess(HttpProtocols serverProtocols, string request, st await connection.Send(request); await connection.Receive(expectedResponse); } + await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs index 6f1a6996ae5c..04852725eb6d 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs @@ -146,6 +146,7 @@ await connection.Receive($"HTTP/1.1 200 OK", "", "Read cancelled"); } + await server.StopAsync(); } } @@ -250,6 +251,8 @@ await connection.Receive($"HTTP/1.1 200 OK", Assert.Equal(queryValue, queryTcs.Task.Result["q"]); } } + + await server.StopAsync(); } } @@ -282,6 +285,7 @@ await connection.Receive( "", ""); } + await server.StopAsync(); } } @@ -510,6 +514,7 @@ async Task ExecuteApplication(HttpContext context) await using var server = new TestServer(ExecuteApplication, testContext); await TestAsyncLocalValues(testContext, server); + await server.StopAsync(); } private static async Task TestAsyncLocalValues(TestServiceContext testContext, TestServer server) @@ -611,6 +616,8 @@ await connection.Receive($"HTTP/1.1 200 OK", usedIds.Add(id); } } + + await server.StopAsync(); } } @@ -1234,6 +1241,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1365,6 +1374,7 @@ await connection.Send($"{request} HTTP/1.1", await connection.Receive("HTTP/1.1 200 OK"); } + await server.StopAsync(); } } @@ -1454,6 +1464,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1623,6 +1635,8 @@ await connection.Receive( "", "Hello1"); } + + await server.StopAsync(); } } @@ -1666,6 +1680,8 @@ await connection.Receive( "", "Hello"); } + + await server.StopAsync(); } } @@ -1710,6 +1726,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1752,6 +1770,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1836,6 +1856,8 @@ await connection.Receive( "", "Hello World"); } + + await server.StopAsync(); } } @@ -1880,6 +1902,7 @@ await connection.Receive( "", "Hello World"); } + await server.StopAsync(); } } @@ -1919,6 +1942,7 @@ await connection.Receive( "", ""); } + await server.StopAsync(); } Assert.All(TestSink.Writes, w => Assert.InRange(w.LogLevel, LogLevel.Trace, LogLevel.Information)); @@ -1963,6 +1987,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -2018,6 +2044,8 @@ await connection.Receive( Assert.NotSame(initialCustomHeaderValue, customHeaderValue); Assert.Same(initialContentTypeValue, contentTypeHeaderValue); } + + await server.StopAsync(); } } @@ -2052,6 +2080,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -2117,6 +2147,7 @@ await connection.Receive( "", ""); } + await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ResponseTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ResponseTests.cs index d2e75cdc16c5..51dca596065a 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ResponseTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ResponseTests.cs @@ -66,6 +66,8 @@ await connection.Receive( await onCompletedTcs.Task.DefaultTimeout(); Assert.False(onStartingCalled); } + + await server.StopAsync(); } } @@ -101,6 +103,8 @@ await connection.Receive($"HTTP/1.1 200 OK", Assert.NotNull(ex); } + + await server.StopAsync(); } } @@ -133,6 +137,8 @@ await connection.Receive($"HTTP/1.1 200 OK", Assert.NotNull(ex); } + + await server.StopAsync(); } } @@ -200,6 +206,8 @@ await connection.Receive($"HTTP/1.1 200 OK", await Assert.ThrowsAsync(() => appTcs.Task).DefaultTimeout(); } + + await server.StopAsync(); } } @@ -325,6 +333,8 @@ await connection.Receive($"HTTP/1.1 200 OK", "", ""); } + + await server.StopAsync(); } } @@ -362,6 +372,7 @@ await connection.Receive($"HTTP/1.1 200 OK", } delayTcs.SetResult(); + await server.StopAsync(); } } @@ -470,6 +481,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -497,6 +510,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -523,6 +538,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -674,6 +691,8 @@ await connection.Receive( // might be 1 by the time ProduceEnd() gets called and the message is logged. await logTcs.Task.DefaultTimeout(); } + + await server.StopAsync(); } mockKestrelTrace.Verify(kestrelTrace => @@ -976,6 +995,8 @@ await connection.Receive( "hello,"); } + await server.StopAsync(); + // Verify the request was really aborted. A timeout in // the app would cause a server error and skip the content length // check altogether, making the test pass for the wrong reason. @@ -1021,6 +1042,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } var error = TestApplicationErrorLogger.Messages.Where(message => message.LogLevel == LogLevel.Error); @@ -1059,6 +1082,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } Assert.Empty(TestApplicationErrorLogger.Messages.Where(message => message.LogLevel == LogLevel.Error)); @@ -1131,6 +1156,8 @@ await connection.Receive( "", "hello, world"); } + + await server.StopAsync(); } Assert.Empty(TestApplicationErrorLogger.Messages.Where(message => message.LogLevel == LogLevel.Error)); @@ -1159,6 +1186,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1190,6 +1219,8 @@ await connection.Receive( flushed.SetResult(); } + + await server.StopAsync(); } } @@ -1223,6 +1254,8 @@ await connection.Receive( flushed.SetResult(); } + + await server.StopAsync(); } } @@ -1257,6 +1290,8 @@ await connection.Receive( await connection.Receive("hello, world"); } + + await server.StopAsync(); } } @@ -1432,6 +1467,8 @@ await connection.Receive( "", "hello, world"); } + + await server.StopAsync(); } } @@ -1516,6 +1553,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1561,6 +1600,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1606,6 +1647,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1646,6 +1689,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1689,6 +1734,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1726,6 +1773,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1923,6 +1972,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1979,6 +2030,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -2046,6 +2099,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -2244,6 +2299,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } // The first registered OnStarting callback should have been called, @@ -2294,6 +2351,8 @@ await connection.Receive( await tcs.Task.DefaultTimeout(); } + + await server.StopAsync(); } } @@ -2339,6 +2398,8 @@ await connection.Receive( await tcs.Task.DefaultTimeout(); } + + await server.StopAsync(); } } @@ -2383,6 +2444,8 @@ await connection.Receive( "", "Hello World"); } + + await server.StopAsync(); } // All OnCompleted callbacks should be called even if they throw. @@ -2632,6 +2695,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -2661,6 +2726,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -2689,6 +2756,8 @@ await connection.Receive( "Content-Length: 0", ""); } + + await server.StopAsync(); } } @@ -2719,6 +2788,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -2751,6 +2822,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -2781,6 +2854,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -2876,6 +2951,8 @@ await connection.Receive( // If we reach this point before the app exits, this means the flush finished early. tcs.SetResult(); } + + await server.StopAsync(); } } @@ -2906,6 +2983,8 @@ await connection.Receive( "", "Hello World"); } + + await server.StopAsync(); } } @@ -2936,6 +3015,8 @@ await connection.Receive( "", expectedString); } + + await server.StopAsync(); } } @@ -2985,6 +3066,8 @@ await connection.Receive( "", expectedString); } + + await server.StopAsync(); } } @@ -3016,6 +3099,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -3064,6 +3149,8 @@ await connection.Receive( // Wait for all callbacks to be called. await onStartingTcs.Task.DefaultTimeout(); } + + await server.StopAsync(); } Assert.Equal(1, callOrder.Pop()); @@ -3115,6 +3202,8 @@ await connection.Receive( // Wait for all callbacks to be called. await onCompletedTcs.Task.DefaultTimeout(); } + + await server.StopAsync(); } Assert.Equal(1, callOrder.Pop()); @@ -3209,6 +3298,8 @@ await connection.Receive( "", "Hello!"); } + + await server.StopAsync(); } } @@ -3248,6 +3339,8 @@ await connection.Receive( "", "Hello!"); } + + await server.StopAsync(); } } @@ -3277,6 +3370,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -3310,6 +3405,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -3340,6 +3437,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -3372,6 +3471,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -3451,6 +3552,8 @@ await connection.Receive( "", "Hello World!"); } + + await server.StopAsync(); } } @@ -3477,6 +3580,8 @@ await connection.Receive( "", "hello, world"); } + + await server.StopAsync(); } } @@ -3519,6 +3624,8 @@ await connection.Receive( "hello, world", "hello, world"); } + + await server.StopAsync(); } } @@ -3545,6 +3652,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -3574,6 +3683,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } Assert.NotNull(writeEx); @@ -3628,6 +3739,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -3677,6 +3790,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -3738,6 +3853,8 @@ await connection.Receive( "a"); } } + + await server.StopAsync(); } } @@ -3812,6 +3929,8 @@ await connection.Receive( Assert.Contains(TestSink.Writes, w => w.EventId.Id == 13 && w.LogLevel == LogLevel.Error && w.Exception is ConnectionAbortedException && w.Exception.InnerException == expectedException); } + + await server.StopAsync(); } } @@ -3844,6 +3963,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -3873,6 +3994,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -3908,6 +4031,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -3941,6 +4066,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -3972,6 +4099,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } Assert.NotNull(writeEx); @@ -4006,6 +4135,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -4040,6 +4171,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs index 757b747b9bb3..d64d17135391 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs @@ -132,7 +132,7 @@ IServiceProvider IStartup.ConfigureServices(IServiceCollection services) public async ValueTask DisposeAsync() { - // The concrete WebHost implements IAsyncDisposable + // The concrete Host implements IAsyncDisposable await ((IAsyncDisposable)_host).ConfigureAwait(false).DisposeAsync(); _memoryPool.Dispose(); } From ef982b1548fb5d7f93796aef2c374357a2a64294 Mon Sep 17 00:00:00 2001 From: Kahbazi Date: Wed, 29 Jul 2020 00:55:49 +0430 Subject: [PATCH 07/13] Stop the TestSserver --- .../BadHttpRequestTests.cs | 6 ++ .../ChunkedRequestTests.cs | 30 ++++++++ .../ChunkedResponseTests.cs | 56 +++++++++++++++ .../ConnectionLimitTests.cs | 8 +++ .../DefaultHeaderTests.cs | 2 + .../EventSourceTests.cs | 2 + .../HttpProtocolSelectionTests.cs | 1 + .../KeepAliveTimeoutTests.cs | 12 ++++ .../MaxRequestBodySizeTests.cs | 22 ++++++ .../MaxRequestLineSizeTests.cs | 4 ++ .../RequestBodyTimeoutTests.cs | 6 ++ .../RequestHeaderLimitsTests.cs | 8 +++ .../RequestHeadersTimeoutTests.cs | 8 +++ .../RequestTargetProcessingTests.cs | 6 ++ .../InMemory.FunctionalTests/RequestTests.cs | 62 +++++++++++++++++ .../InMemory.FunctionalTests/ResponseTests.cs | 68 +++++++++++++++++++ .../InMemory.FunctionalTests/UpgradeTests.cs | 18 +++++ 17 files changed, 319 insertions(+) diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/BadHttpRequestTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/BadHttpRequestTests.cs index cf67cf5d0432..e4737cf196ec 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/BadHttpRequestTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/BadHttpRequestTests.cs @@ -167,6 +167,8 @@ await connection.SendAll( ""); await ReceiveBadRequestResponse(connection, "400 Bad Request", server.Context.DateHeaderValue); } + + await server.StopAsync(); } Assert.All(TestSink.Writes.Where(w => w.LoggerName != "Microsoft.Hosting.Lifetime"), w => Assert.InRange(w.LogLevel, LogLevel.Trace, LogLevel.Debug)); @@ -186,6 +188,8 @@ await client.SendAll( await client.Receive("HTTP/1.1 400"); } + + await server.StopAsync(); } } @@ -208,6 +212,8 @@ private async Task TestBadRequest(string request, string expectedResponseStatusC await connection.SendAll(request); await ReceiveBadRequestResponse(connection, expectedResponseStatusCode, server.Context.DateHeaderValue, expectedAllowHeader); } + + await server.StopAsync(); } mockKestrelTrace.Verify(trace => trace.ConnectionBadRequest(It.IsAny(), It.IsAny())); diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedRequestTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedRequestTests.cs index 5549a1635013..d53d10644fef 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedRequestTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedRequestTests.cs @@ -94,6 +94,8 @@ await connection.ReceiveEnd( "", "Hello World"); } + + await server.StopAsync(); } } @@ -123,6 +125,8 @@ await connection.ReceiveEnd( "", "Hello World"); } + + await server.StopAsync(); } } @@ -164,6 +168,8 @@ await connection.ReceiveEnd( "", "Goodbye"); } + + await server.StopAsync(); } } @@ -218,6 +224,8 @@ await connection.Receive( "", "Hello World"); } + + await server.StopAsync(); } } @@ -345,6 +353,8 @@ public async Task TrailingHeadersAreParsed() await connection.Send(fullRequest); await connection.Receive(expectedFullResponse); } + + await server.StopAsync(); } } @@ -475,6 +485,8 @@ public async Task TrailingHeadersAreParsedWithPipe() await connection.Send(fullRequest); await connection.Receive(expectedFullResponse); } + + await server.StopAsync(); } } [Fact] @@ -518,6 +530,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -559,6 +573,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -643,6 +659,8 @@ public async Task ExtensionsAreIgnored() await connection.Send(fullRequest); await connection.Receive(expectedFullResponse); } + + await server.StopAsync(); } } @@ -686,6 +704,7 @@ await connection.ReceiveEnd( "", ""); } + await server.StopAsync(); } } @@ -731,6 +750,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -835,6 +856,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -886,6 +909,8 @@ await connection.SendAll( var badReqEx = await exTcs.Task.TimeoutAfter(TestConstants.DefaultTimeout); Assert.Equal(RequestRejectionReason.UnexpectedEndOfRequestContent, badReqEx.Reason); } + + await server.StopAsync(); } } @@ -943,6 +968,8 @@ await connection.Receive( "", "Hello World"); } + + await server.StopAsync(); } } @@ -993,6 +1020,7 @@ await connection.Receive( "", "Hello World"); } + await server.StopAsync(); } } @@ -1055,6 +1083,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } Assert.All(TestSink.Writes, w => Assert.InRange(w.LogLevel, LogLevel.Trace, LogLevel.Information)); diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedResponseTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedResponseTests.cs index dbd56948244f..fee2d8a83abe 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedResponseTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedResponseTests.cs @@ -47,6 +47,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -75,6 +77,8 @@ await connection.ReceiveEnd( "", "Hello World!"); } + + await server.StopAsync(); } } @@ -111,6 +115,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -147,6 +153,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -184,6 +192,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -225,6 +235,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -266,6 +278,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -302,6 +316,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -338,6 +354,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -382,6 +400,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -412,6 +432,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -445,6 +467,8 @@ await connection.ReceiveEnd( "Hello World!", ""); } + + await server.StopAsync(); } } @@ -477,6 +501,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -523,6 +549,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -561,6 +589,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -605,6 +635,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -648,6 +680,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -702,6 +736,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -758,6 +794,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -815,6 +853,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -857,6 +897,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -904,6 +946,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -945,6 +989,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -985,6 +1031,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1024,6 +1072,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1059,6 +1109,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1097,6 +1149,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1136,6 +1190,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ConnectionLimitTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ConnectionLimitTests.cs index 16236885f808..579d246e3a1e 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ConnectionLimitTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ConnectionLimitTests.cs @@ -43,6 +43,8 @@ public async Task ResetsCountWhenConnectionClosed() Assert.True(await lockedTcs.Task.DefaultTimeout()); requestTcs.TrySetResult(); } + + await server.StopAsync(); } await releasedTcs.Task.DefaultTimeout(); @@ -93,6 +95,8 @@ public async Task UpgradedConnectionsCountsAgainstDifferentLimit() await rejected.WaitForConnectionClose(); } } + + await server.StopAsync(); } } @@ -138,6 +142,8 @@ public async Task RejectsConnectionsWhenLimitReached() requestTcs.TrySetResult(); } + + await server.StopAsync(); } } @@ -193,6 +199,8 @@ public async Task ConnectionCountingReturnsToZero() await closedTcs.Task.TimeoutAfter(TimeSpan.FromSeconds(120)); Assert.Equal(count, opened); Assert.Equal(count, closed); + + await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/DefaultHeaderTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/DefaultHeaderTests.cs index 58a5b99c7fdb..5b301d5ebee3 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/DefaultHeaderTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/DefaultHeaderTests.cs @@ -45,6 +45,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/EventSourceTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/EventSourceTests.cs index 6138585122fa..8af8d57437c3 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/EventSourceTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/EventSourceTests.cs @@ -47,6 +47,8 @@ await connection.SendAll("GET / HTTP/1.1", .DefaultTimeout(); await connection.Receive("HTTP/1.1 200"); } + + await server.StopAsync(); } // capture list here as other tests executing in parallel may log events diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpProtocolSelectionTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpProtocolSelectionTests.cs index 7712e2df3068..994c0a8ba7a3 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpProtocolSelectionTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpProtocolSelectionTests.cs @@ -70,6 +70,7 @@ private async Task TestSuccess(HttpProtocols serverProtocols, string request, st await connection.Send(request); await connection.Receive(expectedResponse); } + await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/KeepAliveTimeoutTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/KeepAliveTimeoutTests.cs index b997898216ea..36f4c48a37c7 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/KeepAliveTimeoutTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/KeepAliveTimeoutTests.cs @@ -49,6 +49,8 @@ await connection.Send( await connection.WaitForConnectionClose(); } + + await server.StopAsync(); } } @@ -78,6 +80,8 @@ await connection.Send( heartbeatManager.OnHeartbeat(testContext.SystemClock.UtcNow); } } + + await server.StopAsync(); } } @@ -119,6 +123,8 @@ await connection.Send( ""); await ReceiveResponse(connection, testContext); } + + await server.StopAsync(); } } @@ -160,6 +166,8 @@ await connection.Send( ""); await ReceiveResponse(connection, testContext); } + + await server.StopAsync(); } } @@ -181,6 +189,8 @@ private async Task ConnectionTimesOutWhenOpenedButNoRequestSent() await connection.WaitForConnectionClose(); } + + await server.StopAsync(); } } @@ -220,6 +230,8 @@ await connection.Receive( await connection.Receive("hello, world"); } + + await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestBodySizeTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestBodySizeTests.cs index 4e75c713e64f..7db2cfb164bd 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestBodySizeTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestBodySizeTests.cs @@ -54,6 +54,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } Assert.NotNull(requestRejectedEx); @@ -104,6 +106,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } Assert.NotNull(requestRejectedEx); @@ -147,6 +151,8 @@ await connection.Receive( "", "A"); } + + await server.StopAsync(); } } @@ -179,6 +185,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -219,6 +227,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } Assert.NotNull(invalidOpEx); @@ -258,6 +268,8 @@ await connection.Receive("HTTP/1.1 101 Switching Protocols", ""); await connection.ReceiveEnd(); } + + await server.StopAsync(); } Assert.NotNull(invalidOpEx); @@ -301,6 +313,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } Assert.NotNull(requestRejectedEx1); @@ -352,6 +366,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } Assert.NotNull(requestRejectedEx); @@ -397,6 +413,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -469,6 +487,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } Assert.NotNull(requestRejectedEx); @@ -512,6 +532,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } Assert.NotNull(requestRejectedEx1); diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestLineSizeTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestLineSizeTests.cs index 70c83b3e8327..6e98ad6009c4 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestLineSizeTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestLineSizeTests.cs @@ -44,6 +44,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -67,6 +69,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestBodyTimeoutTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestBodyTimeoutTests.cs index 139c786c3a90..745da6431a93 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestBodyTimeoutTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestBodyTimeoutTests.cs @@ -88,6 +88,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -133,6 +135,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } Assert.Contains(TestSink.Writes, w => w.EventId.Id == 32 && w.LogLevel == LogLevel.Information); @@ -206,6 +210,8 @@ await connection.ReceiveEnd( "", "hello, world"); } + + await server.StopAsync(); } } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeaderLimitsTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeaderLimitsTests.cs index 5ab5b467e8ce..0e6641e27189 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeaderLimitsTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeaderLimitsTests.cs @@ -43,6 +43,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -75,6 +77,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -98,6 +102,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -122,6 +128,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeadersTimeoutTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeadersTimeoutTests.cs index e217ece3f0db..37f2a479bd87 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeadersTimeoutTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeadersTimeoutTests.cs @@ -44,6 +44,8 @@ await connection.Send( await ReceiveTimeoutResponse(connection, testContext); } + + await server.StopAsync(); } } @@ -75,6 +77,8 @@ await connection.Send( await ReceiveResponse(connection, testContext); } + + await server.StopAsync(); } } @@ -100,6 +104,8 @@ public async Task ConnectionAbortedWhenRequestLineNotReceivedInTime(string reque await ReceiveTimeoutResponse(connection, testContext); } + + await server.StopAsync(); } } @@ -130,6 +136,8 @@ public async Task TimeoutNotResetOnEachRequestLineCharacterReceived() await connection.WaitForConnectionClose(); } + + await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTargetProcessingTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTargetProcessingTests.cs index 8f2ef644f161..be238676a270 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTargetProcessingTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTargetProcessingTests.cs @@ -42,6 +42,8 @@ await connection.Receive( "", "Hello World"); } + + await server.StopAsync(); } } @@ -87,6 +89,8 @@ await connection.Receive( "", "Hello World"); } + + await server.StopAsync(); } } @@ -127,6 +131,8 @@ await connection.Receive( "", "Hello World"); } + + await server.StopAsync(); } } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs index 04852725eb6d..889cfbae4a34 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs @@ -55,6 +55,8 @@ public async Task StreamsAreNotPersistedAcrossRequests() Assert.False(requestBodyPersisted); Assert.False(responseBodyPersisted); + + await server.StopAsync(); } } @@ -78,6 +80,8 @@ public async Task PipesAreNotPersistedAcrossRequests() Assert.Equal("hello, world", await server.HttpClientSlim.GetStringAsync($"http://localhost:{server.Port}/")); Assert.False(responseBodyPersisted); + + await server.StopAsync(); } } @@ -146,6 +150,7 @@ await connection.Receive($"HTTP/1.1 200 OK", "", "Read cancelled"); } + await server.StopAsync(); } } @@ -180,6 +185,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } Assert.True(dataRead); @@ -285,6 +292,7 @@ await connection.Receive( "", ""); } + await server.StopAsync(); } } @@ -321,6 +329,7 @@ Task ExecuteApplication(HttpContext context) await using var server = new TestServer(ExecuteApplication, testContext); await TestAsyncLocalValues(testContext, server); + await server.StopAsync(); } [Fact] @@ -358,6 +367,7 @@ Task ExecuteApplication(HttpContext context) await using var server = new TestServer(ExecuteApplication, testContext); await TestAsyncLocalValues(testContext, server); + await server.StopAsync(); } #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously @@ -392,6 +402,7 @@ Task ExecuteApplication(HttpContext context) await using var server = new TestServer(ExecuteApplication, testContext); await TestAsyncLocalValues(testContext, server); + await server.StopAsync(); } [Fact] @@ -430,6 +441,7 @@ async Task ExecuteApplication(HttpContext context) await using var server = new TestServer(ExecuteApplication, testContext); await TestAsyncLocalValues(testContext, server); + await server.StopAsync(); } [Fact] @@ -471,6 +483,7 @@ async Task ExecuteApplication(HttpContext context) await using var server = new TestServer(ExecuteApplication, testContext); await TestAsyncLocalValues(testContext, server); + await server.StopAsync(); } #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously @@ -560,6 +573,8 @@ public async Task AppCanSetTraceIdentifier() { var requestId = await server.HttpClientSlim.GetStringAsync($"http://localhost:{server.Port}/"); Assert.Equal(knownId, requestId); + + await server.StopAsync(); } } @@ -652,6 +667,8 @@ await connection.ReceiveEnd( "", "Goodbye"); } + + await server.StopAsync(); } } @@ -691,6 +708,8 @@ await connection.ReceiveEnd( "", "Hello World"); } + + await server.StopAsync(); } } @@ -725,6 +744,8 @@ await connection.ReceiveEnd( "", "Goodbye"); } + + await server.StopAsync(); } } @@ -764,6 +785,8 @@ await connection.ReceiveEnd( "", "Goodbye"); } + + await server.StopAsync(); } } @@ -820,6 +843,8 @@ await connection.ReceiveEnd( "", "Goodbye"); } + + await server.StopAsync(); } } @@ -852,6 +877,8 @@ await connection.ReceiveEnd( "", "Hello World"); } + + await server.StopAsync(); } } @@ -898,6 +925,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -945,6 +974,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -977,6 +1008,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -1012,6 +1045,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -1051,6 +1086,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -1125,6 +1162,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -1159,6 +1198,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -1191,6 +1232,8 @@ await connection.Send( await connection.TransportConnection.WaitForCloseTask; await connection.ReceiveEnd(); } + + await server.StopAsync(); } } @@ -1280,6 +1323,8 @@ await connection.ReceiveEnd( "", message); } + + await server.StopAsync(); } } @@ -1353,6 +1398,8 @@ public async Task HeadersAndStreamsAreReusedAcrossRequests() await connection.ReceiveEnd(responseData.ToArray()); } + await server.StopAsync(); + Assert.Equal(1, streamCount); Assert.Equal(1, requestHeadersCount); Assert.Equal(1, responseHeadersCount); @@ -1374,6 +1421,7 @@ await connection.Send($"{request} HTTP/1.1", await connection.Receive("HTTP/1.1 200 OK"); } + await server.StopAsync(); } } @@ -1416,6 +1464,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1492,6 +1542,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -1524,6 +1576,8 @@ await connection.ReceiveEnd( "", "goodbye"); } + + await server.StopAsync(); } } @@ -1584,6 +1638,8 @@ await connection.ReceiveEnd( "", "hello"); } + + await server.StopAsync(); } } @@ -1803,6 +1859,8 @@ await connection.Send( await connection.ReceiveEnd(); } + + await server.StopAsync(); } Assert.Empty(TestApplicationErrorLogger.Messages.Where(m => m.LogLevel >= LogLevel.Warning)); @@ -1902,6 +1960,7 @@ await connection.Receive( "", "Hello World"); } + await server.StopAsync(); } } @@ -1942,6 +2001,7 @@ await connection.Receive( "", ""); } + await server.StopAsync(); } @@ -2111,6 +2171,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ResponseTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ResponseTests.cs index 51dca596065a..0fe29f6639e2 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ResponseTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ResponseTests.cs @@ -406,6 +406,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } await onCompletedTcs.Task.DefaultTimeout(); @@ -442,6 +444,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } Assert.NotNull(readException); @@ -585,6 +589,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -629,6 +635,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -653,6 +661,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -730,6 +740,8 @@ await connection.Receive( await connection.WaitForConnectionClose(); } + + await server.StopAsync(); } var logMessage = Assert.Single(TestApplicationErrorLogger.Messages, message => message.LogLevel == LogLevel.Error); @@ -766,6 +778,8 @@ await connection.ReceiveEnd( "", "hello,"); } + + await server.StopAsync(); } var logMessage = Assert.Single(TestApplicationErrorLogger.Messages, message => message.LogLevel == LogLevel.Error); @@ -804,6 +818,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } var logMessage = Assert.Single(TestApplicationErrorLogger.Messages, message => message.LogLevel == LogLevel.Error); @@ -839,6 +855,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } var logMessage = Assert.Single(TestApplicationErrorLogger.Messages, message => message.LogLevel == LogLevel.Error); @@ -890,6 +908,8 @@ await connection.Receive( // The server should close the connection in this situation. await connection.WaitForConnectionClose(); } + + await server.StopAsync(); } mockTrace.Verify(trace => @@ -948,6 +968,8 @@ await connection.Receive( // The server should close the connection in this situation. await connection.WaitForConnectionClose(); } + + await server.StopAsync(); } mockTrace.Verify(trace => @@ -1120,6 +1142,8 @@ await connection.Receive( "", "hello, world"); } + + await server.StopAsync(); } Assert.Empty(TestApplicationErrorLogger.Messages.Where(message => message.LogLevel == LogLevel.Error)); @@ -1333,6 +1357,8 @@ await connection.ReceiveEnd( "", expectedResponse); } + + await server.StopAsync(); } } @@ -1378,6 +1404,8 @@ await connection.ReceiveEnd( "", "hello, world"); } + + await server.StopAsync(); } } @@ -1424,6 +1452,8 @@ await connection.ReceiveEnd( "", "hello, world"); } + + await server.StopAsync(); } } @@ -1511,6 +1541,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -1803,6 +1835,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } #pragma warning disable CS0618 // Type or member is obsolete @@ -1877,6 +1911,8 @@ await connection.Send( await connection.ReceiveEnd(); } + + await server.StopAsync(); } Assert.True(foundMessage, "Expected log not found"); @@ -1920,6 +1956,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } #pragma warning disable CS0618 // Type or member is obsolete @@ -1998,6 +2036,8 @@ await connection.ReceiveEnd( "", "Hello World"); } + + await server.StopAsync(); } } @@ -2076,6 +2116,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -2150,6 +2192,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } @@ -2196,6 +2240,8 @@ await connection.ReceiveEnd( "", "hello, world"); } + + await server.StopAsync(); } } @@ -2243,6 +2289,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } Assert.False(onStartingCalled); @@ -2489,6 +2537,8 @@ await connection.ReceiveEnd( "", "Hello World"); } + + await server.StopAsync(); } Assert.True(onStartingCalled); @@ -2530,6 +2580,8 @@ await connection.ReceiveEnd( "", "Hello"); } + + await server.StopAsync(); } Assert.True(onStartingCalled); @@ -2563,6 +2615,8 @@ await connection.ReceiveEnd( "", "Hello World"); } + + await server.StopAsync(); } Assert.Empty(TestApplicationErrorLogger.Messages.Where(message => message.LogLevel == LogLevel.Error)); @@ -2588,6 +2642,8 @@ await connection.Send( ""); await connection.ReceiveEnd(); } + + await server.StopAsync(); } } @@ -2611,6 +2667,8 @@ await connection.Send( ""); await connection.ReceiveEnd(); } + + await server.StopAsync(); } Assert.Single(TestApplicationErrorLogger.Messages.Where(m => m.Message.Contains(CoreStrings.ConnectionAbortedByApplication))); @@ -2884,6 +2942,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -2913,6 +2973,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -3237,6 +3299,8 @@ await connection.Receive( "", "Hello1"); } + + await server.StopAsync(); } } @@ -3263,6 +3327,8 @@ await connection.Receive( "", "Hello1"); } + + await server.StopAsync(); } } @@ -3900,6 +3966,8 @@ await connection.Receive( "", ""); } + + await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/UpgradeTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/UpgradeTests.cs index 30b8474ea252..79d2831e959f 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/UpgradeTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/UpgradeTests.cs @@ -51,6 +51,8 @@ await connection.Receive("HTTP/1.1 101 Switching Protocols", await connection.Receive("New protocol data"); await upgrade.Task.DefaultTimeout(); } + + await server.StopAsync(); } } @@ -106,6 +108,8 @@ await connection.Receive("HTTP/1.1 101 Switching Protocols", await upgrade.Task.DefaultTimeout(); } + + await server.StopAsync(); } } @@ -144,6 +148,8 @@ await connection.Receive("HTTP/1.1 101 Switching Protocols", ""); await connection.WaitForConnectionClose(); } + + await server.StopAsync(); } var ex = await Assert.ThrowsAsync(async () => await upgradeTcs.Task.DefaultTimeout()); @@ -172,6 +178,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -196,6 +204,8 @@ await connection.Send("POST / HTTP/1.1", await connection.SendEmptyGetWithUpgrade(); await connection.Receive("HTTP/1.1 200 OK"); } + + await server.StopAsync(); } } @@ -220,6 +230,8 @@ await connection.ReceiveEnd( "", ""); } + + await server.StopAsync(); } } @@ -250,6 +262,8 @@ public async Task ThrowsWhenUpgradingNonUpgradableRequest() await connection.SendEmptyGet(); await connection.Receive("HTTP/1.1 200 OK"); } + + await server.StopAsync(); } var ex = await Assert.ThrowsAsync(async () => await upgradeTcs.Task).DefaultTimeout(); @@ -301,6 +315,8 @@ public async Task RejectsUpgradeWhenLimitReached() await connection.Receive("HTTP/1.1 200"); } } + + await server.StopAsync(); } var exception = await Assert.ThrowsAsync(async () => await upgradeTcs.Task.TimeoutAfter(TimeSpan.FromSeconds(60))); @@ -341,6 +357,8 @@ await connection.Receive("HTTP/1.1 101 Switching Protocols", } await appCompletedTcs.Task.DefaultTimeout(); + + await server.StopAsync(); } } } From a39b5b813a44091567f8fd91de76aec167d4a1a3 Mon Sep 17 00:00:00 2001 From: Kahbazi Date: Thu, 30 Jul 2020 01:23:33 +0430 Subject: [PATCH 08/13] Stop more hosts! --- .../BindTests/AddressRegistrationTests.cs | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/Servers/Kestrel/test/BindTests/AddressRegistrationTests.cs b/src/Servers/Kestrel/test/BindTests/AddressRegistrationTests.cs index 1443b8bd66b3..5980ff8f32d6 100644 --- a/src/Servers/Kestrel/test/BindTests/AddressRegistrationTests.cs +++ b/src/Servers/Kestrel/test/BindTests/AddressRegistrationTests.cs @@ -221,6 +221,8 @@ private async Task RegisterAddresses_Success(string addressInput, string[] testU } Assert.Equal(uri.ToString(), response); } + + await host.StopAsync(); } } @@ -265,6 +267,8 @@ public async Task RegisterHttpAddress_UpgradedToHttpsByConfigureEndpointDefaults var response = await HttpClientSlim.GetStringAsync(expectedUrl, validateCertificate: false); Assert.Equal(expectedUrl, response); + + await host.StopAsync(); } } @@ -541,7 +545,7 @@ private async Task RegisterDefaultServerAddresses_Success(IEnumerable ad } [Fact] - public void ThrowsWhenBindingToIPv4AddressInUse() + public async Task ThrowsWhenBindingToIPv4AddressInUse() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { @@ -562,13 +566,15 @@ public void ThrowsWhenBindingToIPv4AddressInUse() { var exception = Assert.Throws(() => host.Start()); Assert.Equal(CoreStrings.FormatEndpointAlreadyInUse($"http://127.0.0.1:{port}"), exception.Message); + + await host.StopAsync(); } } } [ConditionalFact] [IPv6SupportedCondition] - public void ThrowsWhenBindingToIPv6AddressInUse() + public async Task ThrowsWhenBindingToIPv6AddressInUse() { TestApplicationErrorLogger.IgnoredExceptions.Add(typeof(IOException)); @@ -592,6 +598,8 @@ public void ThrowsWhenBindingToIPv6AddressInUse() { var exception = Assert.Throws(() => host.Start()); Assert.Equal(CoreStrings.FormatEndpointAlreadyInUse($"http://[::1]:{port}"), exception.Message); + + await host.StopAsync(); } } } @@ -735,7 +743,7 @@ public void ThrowsWhenBindingLocalhostToIPv6AddressInUse() } [Fact] - public void ThrowsWhenBindingLocalhostToDynamicPort() + public async Task ThrowsWhenBindingLocalhostToDynamicPort() { TestApplicationErrorLogger.IgnoredExceptions.Add(typeof(InvalidOperationException)); @@ -752,13 +760,15 @@ public void ThrowsWhenBindingLocalhostToDynamicPort() using (var host = hostBuilder.Build()) { Assert.Throws(() => host.Start()); + + await host.StopAsync(); } } [Theory] [InlineData("ftp://localhost")] [InlineData("ssh://localhost")] - public void ThrowsForUnsupportedAddressFromHosting(string address) + public async Task ThrowsForUnsupportedAddressFromHosting(string address) { TestApplicationErrorLogger.IgnoredExceptions.Add(typeof(InvalidOperationException)); @@ -775,6 +785,8 @@ public void ThrowsForUnsupportedAddressFromHosting(string address) using (var host = hostBuilder.Build()) { Assert.Throws(() => host.Start()); + + await host.StopAsync(); } } From 798c3babb505c5facec281e9403c1e12dd87f8b5 Mon Sep 17 00:00:00 2001 From: Kahbazi Date: Sat, 1 Aug 2020 12:00:03 +0430 Subject: [PATCH 09/13] Stop host in dispose --- .../MaxRequestBufferSizeTests.cs | 4 +- .../BadHttpRequestTests.cs | 6 - .../ChunkedRequestTests.cs | 36 +--- .../ChunkedResponseTests.cs | 56 ----- .../ConnectionLimitTests.cs | 8 - .../DefaultHeaderTests.cs | 3 - .../EventSourceTests.cs | 3 - .../Http2/TlsTests.cs | 3 +- .../HttpProtocolSelectionTests.cs | 2 - .../KeepAliveTimeoutTests.cs | 13 -- .../MaxRequestBodySizeTests.cs | 23 -- .../MaxRequestLineSizeTests.cs | 4 - .../RequestBodyTimeoutTests.cs | 7 - .../RequestHeaderLimitsTests.cs | 9 - .../RequestHeadersTimeoutTests.cs | 9 - .../RequestTargetProcessingTests.cs | 7 - .../InMemory.FunctionalTests/RequestTests.cs | 95 -------- .../InMemory.FunctionalTests/ResponseTests.cs | 203 ------------------ .../TestTransport/TestServer.cs | 8 +- .../InMemory.FunctionalTests/UpgradeTests.cs | 18 -- 20 files changed, 5 insertions(+), 512 deletions(-) diff --git a/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs b/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs index 4fad2f421ef9..bcadf5f392f7 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs @@ -14,11 +14,9 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Testing; -using Microsoft.Extensions.Logging.Testing; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Xunit; -using Microsoft.Extensions.DependencyInjection; -using System.Threading; namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests { diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/BadHttpRequestTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/BadHttpRequestTests.cs index e4737cf196ec..cf67cf5d0432 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/BadHttpRequestTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/BadHttpRequestTests.cs @@ -167,8 +167,6 @@ await connection.SendAll( ""); await ReceiveBadRequestResponse(connection, "400 Bad Request", server.Context.DateHeaderValue); } - - await server.StopAsync(); } Assert.All(TestSink.Writes.Where(w => w.LoggerName != "Microsoft.Hosting.Lifetime"), w => Assert.InRange(w.LogLevel, LogLevel.Trace, LogLevel.Debug)); @@ -188,8 +186,6 @@ await client.SendAll( await client.Receive("HTTP/1.1 400"); } - - await server.StopAsync(); } } @@ -212,8 +208,6 @@ private async Task TestBadRequest(string request, string expectedResponseStatusC await connection.SendAll(request); await ReceiveBadRequestResponse(connection, expectedResponseStatusCode, server.Context.DateHeaderValue, expectedAllowHeader); } - - await server.StopAsync(); } mockKestrelTrace.Verify(trace => trace.ConnectionBadRequest(It.IsAny(), It.IsAny())); diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedRequestTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedRequestTests.cs index d53d10644fef..2ec68a9c1808 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedRequestTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedRequestTests.cs @@ -9,12 +9,10 @@ using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Testing; using Xunit; using BadHttpRequestException = Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException; @@ -94,8 +92,6 @@ await connection.ReceiveEnd( "", "Hello World"); } - - await server.StopAsync(); } } @@ -125,8 +121,6 @@ await connection.ReceiveEnd( "", "Hello World"); } - - await server.StopAsync(); } } @@ -168,8 +162,6 @@ await connection.ReceiveEnd( "", "Goodbye"); } - - await server.StopAsync(); } } @@ -224,8 +216,6 @@ await connection.Receive( "", "Hello World"); } - - await server.StopAsync(); } } @@ -353,8 +343,6 @@ public async Task TrailingHeadersAreParsed() await connection.Send(fullRequest); await connection.Receive(expectedFullResponse); } - - await server.StopAsync(); } } @@ -485,8 +473,6 @@ public async Task TrailingHeadersAreParsedWithPipe() await connection.Send(fullRequest); await connection.Receive(expectedFullResponse); } - - await server.StopAsync(); } } [Fact] @@ -530,8 +516,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -573,8 +557,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -659,8 +641,6 @@ public async Task ExtensionsAreIgnored() await connection.Send(fullRequest); await connection.Receive(expectedFullResponse); } - - await server.StopAsync(); } } @@ -704,8 +684,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -750,8 +728,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -856,8 +832,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -909,8 +883,6 @@ await connection.SendAll( var badReqEx = await exTcs.Task.TimeoutAfter(TestConstants.DefaultTimeout); Assert.Equal(RequestRejectionReason.UnexpectedEndOfRequestContent, badReqEx.Reason); } - - await server.StopAsync(); } } @@ -968,8 +940,6 @@ await connection.Receive( "", "Hello World"); } - - await server.StopAsync(); } } @@ -1020,8 +990,6 @@ await connection.Receive( "", "Hello World"); } - - await server.StopAsync(); } } @@ -1083,8 +1051,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } Assert.All(TestSink.Writes, w => Assert.InRange(w.LogLevel, LogLevel.Trace, LogLevel.Information)); @@ -1095,7 +1061,7 @@ public async Task ChunkedRequestCallCompleteWithExceptionCauses500() { var testContext = new TestServiceContext(LoggerFactory); - using (var server = new TestServer(async httpContext => + await using (var server = new TestServer(async httpContext => { var response = httpContext.Response; var request = httpContext.Request; diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedResponseTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedResponseTests.cs index fee2d8a83abe..dbd56948244f 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedResponseTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedResponseTests.cs @@ -47,8 +47,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -77,8 +75,6 @@ await connection.ReceiveEnd( "", "Hello World!"); } - - await server.StopAsync(); } } @@ -115,8 +111,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -153,8 +147,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -192,8 +184,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -235,8 +225,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -278,8 +266,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -316,8 +302,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -354,8 +338,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -400,8 +382,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -432,8 +412,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -467,8 +445,6 @@ await connection.ReceiveEnd( "Hello World!", ""); } - - await server.StopAsync(); } } @@ -501,8 +477,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -549,8 +523,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -589,8 +561,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -635,8 +605,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -680,8 +648,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -736,8 +702,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -794,8 +758,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -853,8 +815,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -897,8 +857,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -946,8 +904,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -989,8 +945,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1031,8 +985,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1072,8 +1024,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1109,8 +1059,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1149,8 +1097,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1190,8 +1136,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ConnectionLimitTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ConnectionLimitTests.cs index 579d246e3a1e..16236885f808 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ConnectionLimitTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ConnectionLimitTests.cs @@ -43,8 +43,6 @@ public async Task ResetsCountWhenConnectionClosed() Assert.True(await lockedTcs.Task.DefaultTimeout()); requestTcs.TrySetResult(); } - - await server.StopAsync(); } await releasedTcs.Task.DefaultTimeout(); @@ -95,8 +93,6 @@ public async Task UpgradedConnectionsCountsAgainstDifferentLimit() await rejected.WaitForConnectionClose(); } } - - await server.StopAsync(); } } @@ -142,8 +138,6 @@ public async Task RejectsConnectionsWhenLimitReached() requestTcs.TrySetResult(); } - - await server.StopAsync(); } } @@ -199,8 +193,6 @@ public async Task ConnectionCountingReturnsToZero() await closedTcs.Task.TimeoutAfter(TimeSpan.FromSeconds(120)); Assert.Equal(count, opened); Assert.Equal(count, closed); - - await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/DefaultHeaderTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/DefaultHeaderTests.cs index 5b301d5ebee3..57166bd98c76 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/DefaultHeaderTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/DefaultHeaderTests.cs @@ -4,7 +4,6 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Testing; -using Microsoft.Extensions.Logging.Testing; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests @@ -45,8 +44,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/EventSourceTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/EventSourceTests.cs index 8af8d57437c3..2fb46cc0f127 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/EventSourceTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/EventSourceTests.cs @@ -10,7 +10,6 @@ using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Testing; -using Microsoft.Extensions.Logging.Testing; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests @@ -47,8 +46,6 @@ await connection.SendAll("GET / HTTP/1.1", .DefaultTimeout(); await connection.Receive("HTTP/1.1 200"); } - - await server.StopAsync(); } // capture list here as other tests executing in parallel may log events diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/TlsTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/TlsTests.cs index 9e3263bb7903..120958c0dfea 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/TlsTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/TlsTests.cs @@ -33,7 +33,7 @@ public class TlsTests : LoggedTest [SkipOnHelix("Ubuntu 20.04 disables TLS1.1 by default which SslStream requires in this scenario", Queues = "Ubuntu.2004.Amd64.Open")] public async Task TlsHandshakeRejectsTlsLessThan12() { - using (var server = new TestServer(context => + await using (var server = new TestServer(context => { var tlsFeature = context.Features.Get(); Assert.NotNull(tlsFeature); @@ -66,7 +66,6 @@ await sslStream.AuthenticateAsClientAsync(new SslClientAuthenticationOptions await WaitForConnectionErrorAsync(reader, ignoreNonGoAwayFrames: false, expectedLastStreamId: 0, expectedErrorCode: Http2ErrorCode.INADEQUATE_SECURITY); reader.Complete(); } - await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpProtocolSelectionTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpProtocolSelectionTests.cs index 994c0a8ba7a3..8b29ad1a13aa 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpProtocolSelectionTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/HttpProtocolSelectionTests.cs @@ -70,8 +70,6 @@ private async Task TestSuccess(HttpProtocols serverProtocols, string request, st await connection.Send(request); await connection.Receive(expectedResponse); } - - await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/KeepAliveTimeoutTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/KeepAliveTimeoutTests.cs index 36f4c48a37c7..dc6f7c83eb6c 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/KeepAliveTimeoutTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/KeepAliveTimeoutTests.cs @@ -11,7 +11,6 @@ using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Testing; -using Microsoft.Extensions.Logging.Testing; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests @@ -49,8 +48,6 @@ await connection.Send( await connection.WaitForConnectionClose(); } - - await server.StopAsync(); } } @@ -80,8 +77,6 @@ await connection.Send( heartbeatManager.OnHeartbeat(testContext.SystemClock.UtcNow); } } - - await server.StopAsync(); } } @@ -123,8 +118,6 @@ await connection.Send( ""); await ReceiveResponse(connection, testContext); } - - await server.StopAsync(); } } @@ -166,8 +159,6 @@ await connection.Send( ""); await ReceiveResponse(connection, testContext); } - - await server.StopAsync(); } } @@ -189,8 +180,6 @@ private async Task ConnectionTimesOutWhenOpenedButNoRequestSent() await connection.WaitForConnectionClose(); } - - await server.StopAsync(); } } @@ -230,8 +219,6 @@ await connection.Receive( await connection.Receive("hello, world"); } - - await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestBodySizeTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestBodySizeTests.cs index 7db2cfb164bd..cd8c95f78b71 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestBodySizeTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestBodySizeTests.cs @@ -10,7 +10,6 @@ using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Testing; -using Microsoft.Extensions.Logging.Testing; using Xunit; using BadHttpRequestException = Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException; @@ -54,8 +53,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } Assert.NotNull(requestRejectedEx); @@ -106,8 +103,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } Assert.NotNull(requestRejectedEx); @@ -151,8 +146,6 @@ await connection.Receive( "", "A"); } - - await server.StopAsync(); } } @@ -185,8 +178,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -227,8 +218,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } Assert.NotNull(invalidOpEx); @@ -268,8 +257,6 @@ await connection.Receive("HTTP/1.1 101 Switching Protocols", ""); await connection.ReceiveEnd(); } - - await server.StopAsync(); } Assert.NotNull(invalidOpEx); @@ -313,8 +300,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } Assert.NotNull(requestRejectedEx1); @@ -366,8 +351,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } Assert.NotNull(requestRejectedEx); @@ -413,8 +396,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -487,8 +468,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } Assert.NotNull(requestRejectedEx); @@ -532,8 +511,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } Assert.NotNull(requestRejectedEx1); diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestLineSizeTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestLineSizeTests.cs index 6e98ad6009c4..70c83b3e8327 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestLineSizeTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/MaxRequestLineSizeTests.cs @@ -44,8 +44,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -69,8 +67,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestBodyTimeoutTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestBodyTimeoutTests.cs index 745da6431a93..cde0e630d803 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestBodyTimeoutTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestBodyTimeoutTests.cs @@ -11,7 +11,6 @@ using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Testing; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests @@ -88,8 +87,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -135,8 +132,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } Assert.Contains(TestSink.Writes, w => w.EventId.Id == 32 && w.LogLevel == LogLevel.Information); @@ -210,8 +205,6 @@ await connection.ReceiveEnd( "", "hello, world"); } - - await server.StopAsync(); } } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeaderLimitsTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeaderLimitsTests.cs index 0e6641e27189..c177d235c67f 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeaderLimitsTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeaderLimitsTests.cs @@ -7,7 +7,6 @@ using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Testing; -using Microsoft.Extensions.Logging.Testing; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests @@ -43,8 +42,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -77,8 +74,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -102,8 +97,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -128,8 +121,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeadersTimeoutTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeadersTimeoutTests.cs index 37f2a479bd87..ca34052301ca 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeadersTimeoutTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestHeadersTimeoutTests.cs @@ -8,7 +8,6 @@ using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Testing; -using Microsoft.Extensions.Logging.Testing; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests @@ -44,8 +43,6 @@ await connection.Send( await ReceiveTimeoutResponse(connection, testContext); } - - await server.StopAsync(); } } @@ -77,8 +74,6 @@ await connection.Send( await ReceiveResponse(connection, testContext); } - - await server.StopAsync(); } } @@ -104,8 +99,6 @@ public async Task ConnectionAbortedWhenRequestLineNotReceivedInTime(string reque await ReceiveTimeoutResponse(connection, testContext); } - - await server.StopAsync(); } } @@ -136,8 +129,6 @@ public async Task TimeoutNotResetOnEachRequestLineCharacterReceived() await connection.WaitForConnectionClose(); } - - await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTargetProcessingTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTargetProcessingTests.cs index be238676a270..693565b30083 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTargetProcessingTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTargetProcessingTests.cs @@ -8,7 +8,6 @@ using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Testing; -using Microsoft.Extensions.Logging.Testing; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests @@ -42,8 +41,6 @@ await connection.Receive( "", "Hello World"); } - - await server.StopAsync(); } } @@ -89,8 +86,6 @@ await connection.Receive( "", "Hello World"); } - - await server.StopAsync(); } } @@ -131,8 +126,6 @@ await connection.Receive( "", "Hello World"); } - - await server.StopAsync(); } } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs index 889cfbae4a34..873b4c9ec772 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs @@ -18,8 +18,6 @@ using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Testing; -using Serilog; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests @@ -55,8 +53,6 @@ public async Task StreamsAreNotPersistedAcrossRequests() Assert.False(requestBodyPersisted); Assert.False(responseBodyPersisted); - - await server.StopAsync(); } } @@ -80,8 +76,6 @@ public async Task PipesAreNotPersistedAcrossRequests() Assert.Equal("hello, world", await server.HttpClientSlim.GetStringAsync($"http://localhost:{server.Port}/")); Assert.False(responseBodyPersisted); - - await server.StopAsync(); } } @@ -150,8 +144,6 @@ await connection.Receive($"HTTP/1.1 200 OK", "", "Read cancelled"); } - - await server.StopAsync(); } } @@ -185,8 +177,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } Assert.True(dataRead); @@ -258,8 +248,6 @@ await connection.Receive($"HTTP/1.1 200 OK", Assert.Equal(queryValue, queryTcs.Task.Result["q"]); } } - - await server.StopAsync(); } } @@ -292,8 +280,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -329,7 +315,6 @@ Task ExecuteApplication(HttpContext context) await using var server = new TestServer(ExecuteApplication, testContext); await TestAsyncLocalValues(testContext, server); - await server.StopAsync(); } [Fact] @@ -367,7 +352,6 @@ Task ExecuteApplication(HttpContext context) await using var server = new TestServer(ExecuteApplication, testContext); await TestAsyncLocalValues(testContext, server); - await server.StopAsync(); } #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously @@ -402,7 +386,6 @@ Task ExecuteApplication(HttpContext context) await using var server = new TestServer(ExecuteApplication, testContext); await TestAsyncLocalValues(testContext, server); - await server.StopAsync(); } [Fact] @@ -441,7 +424,6 @@ async Task ExecuteApplication(HttpContext context) await using var server = new TestServer(ExecuteApplication, testContext); await TestAsyncLocalValues(testContext, server); - await server.StopAsync(); } [Fact] @@ -483,7 +465,6 @@ async Task ExecuteApplication(HttpContext context) await using var server = new TestServer(ExecuteApplication, testContext); await TestAsyncLocalValues(testContext, server); - await server.StopAsync(); } #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously @@ -527,7 +508,6 @@ async Task ExecuteApplication(HttpContext context) await using var server = new TestServer(ExecuteApplication, testContext); await TestAsyncLocalValues(testContext, server); - await server.StopAsync(); } private static async Task TestAsyncLocalValues(TestServiceContext testContext, TestServer server) @@ -573,8 +553,6 @@ public async Task AppCanSetTraceIdentifier() { var requestId = await server.HttpClientSlim.GetStringAsync($"http://localhost:{server.Port}/"); Assert.Equal(knownId, requestId); - - await server.StopAsync(); } } @@ -631,8 +609,6 @@ await connection.Receive($"HTTP/1.1 200 OK", usedIds.Add(id); } } - - await server.StopAsync(); } } @@ -667,8 +643,6 @@ await connection.ReceiveEnd( "", "Goodbye"); } - - await server.StopAsync(); } } @@ -708,8 +682,6 @@ await connection.ReceiveEnd( "", "Hello World"); } - - await server.StopAsync(); } } @@ -744,8 +716,6 @@ await connection.ReceiveEnd( "", "Goodbye"); } - - await server.StopAsync(); } } @@ -785,8 +755,6 @@ await connection.ReceiveEnd( "", "Goodbye"); } - - await server.StopAsync(); } } @@ -843,8 +811,6 @@ await connection.ReceiveEnd( "", "Goodbye"); } - - await server.StopAsync(); } } @@ -877,8 +843,6 @@ await connection.ReceiveEnd( "", "Hello World"); } - - await server.StopAsync(); } } @@ -925,8 +889,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -974,8 +936,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -1008,8 +968,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -1045,8 +1003,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -1086,8 +1042,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -1162,8 +1116,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -1198,8 +1150,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -1232,8 +1182,6 @@ await connection.Send( await connection.TransportConnection.WaitForCloseTask; await connection.ReceiveEnd(); } - - await server.StopAsync(); } } @@ -1284,8 +1232,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1323,8 +1269,6 @@ await connection.ReceiveEnd( "", message); } - - await server.StopAsync(); } } @@ -1398,8 +1342,6 @@ public async Task HeadersAndStreamsAreReusedAcrossRequests() await connection.ReceiveEnd(responseData.ToArray()); } - await server.StopAsync(); - Assert.Equal(1, streamCount); Assert.Equal(1, requestHeadersCount); Assert.Equal(1, responseHeadersCount); @@ -1421,8 +1363,6 @@ await connection.Send($"{request} HTTP/1.1", await connection.Receive("HTTP/1.1 200 OK"); } - - await server.StopAsync(); } } @@ -1464,8 +1404,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1514,8 +1452,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1542,8 +1478,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -1576,8 +1510,6 @@ await connection.ReceiveEnd( "", "goodbye"); } - - await server.StopAsync(); } } @@ -1638,8 +1570,6 @@ await connection.ReceiveEnd( "", "hello"); } - - await server.StopAsync(); } } @@ -1691,8 +1621,6 @@ await connection.Receive( "", "Hello1"); } - - await server.StopAsync(); } } @@ -1736,8 +1664,6 @@ await connection.Receive( "", "Hello"); } - - await server.StopAsync(); } } @@ -1782,8 +1708,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1826,8 +1750,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1859,8 +1781,6 @@ await connection.Send( await connection.ReceiveEnd(); } - - await server.StopAsync(); } Assert.Empty(TestApplicationErrorLogger.Messages.Where(m => m.LogLevel >= LogLevel.Warning)); @@ -1914,8 +1834,6 @@ await connection.Receive( "", "Hello World"); } - - await server.StopAsync(); } } @@ -1960,8 +1878,6 @@ await connection.Receive( "", "Hello World"); } - - await server.StopAsync(); } } @@ -2001,8 +1917,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } Assert.All(TestSink.Writes, w => Assert.InRange(w.LogLevel, LogLevel.Trace, LogLevel.Information)); @@ -2047,8 +1961,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -2104,8 +2016,6 @@ await connection.Receive( Assert.NotSame(initialCustomHeaderValue, customHeaderValue); Assert.Same(initialContentTypeValue, contentTypeHeaderValue); } - - await server.StopAsync(); } } @@ -2140,8 +2050,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -2171,8 +2079,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -2209,7 +2115,6 @@ await connection.Receive( "", ""); } - await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ResponseTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ResponseTests.cs index 0fe29f6639e2..15660cd040ed 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/ResponseTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/ResponseTests.cs @@ -66,8 +66,6 @@ await connection.Receive( await onCompletedTcs.Task.DefaultTimeout(); Assert.False(onStartingCalled); } - - await server.StopAsync(); } } @@ -103,8 +101,6 @@ await connection.Receive($"HTTP/1.1 200 OK", Assert.NotNull(ex); } - - await server.StopAsync(); } } @@ -137,8 +133,6 @@ await connection.Receive($"HTTP/1.1 200 OK", Assert.NotNull(ex); } - - await server.StopAsync(); } } @@ -206,8 +200,6 @@ await connection.Receive($"HTTP/1.1 200 OK", await Assert.ThrowsAsync(() => appTcs.Task).DefaultTimeout(); } - - await server.StopAsync(); } } @@ -333,8 +325,6 @@ await connection.Receive($"HTTP/1.1 200 OK", "", ""); } - - await server.StopAsync(); } } @@ -372,7 +362,6 @@ await connection.Receive($"HTTP/1.1 200 OK", } delayTcs.SetResult(); - await server.StopAsync(); } } @@ -406,8 +395,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } await onCompletedTcs.Task.DefaultTimeout(); @@ -444,8 +431,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } Assert.NotNull(readException); @@ -485,8 +470,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -514,8 +497,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -542,8 +523,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -589,8 +568,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -635,8 +612,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -661,8 +636,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -701,8 +674,6 @@ await connection.Receive( // might be 1 by the time ProduceEnd() gets called and the message is logged. await logTcs.Task.DefaultTimeout(); } - - await server.StopAsync(); } mockKestrelTrace.Verify(kestrelTrace => @@ -740,8 +711,6 @@ await connection.Receive( await connection.WaitForConnectionClose(); } - - await server.StopAsync(); } var logMessage = Assert.Single(TestApplicationErrorLogger.Messages, message => message.LogLevel == LogLevel.Error); @@ -778,8 +747,6 @@ await connection.ReceiveEnd( "", "hello,"); } - - await server.StopAsync(); } var logMessage = Assert.Single(TestApplicationErrorLogger.Messages, message => message.LogLevel == LogLevel.Error); @@ -818,8 +785,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } var logMessage = Assert.Single(TestApplicationErrorLogger.Messages, message => message.LogLevel == LogLevel.Error); @@ -855,8 +820,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } var logMessage = Assert.Single(TestApplicationErrorLogger.Messages, message => message.LogLevel == LogLevel.Error); @@ -908,8 +871,6 @@ await connection.Receive( // The server should close the connection in this situation. await connection.WaitForConnectionClose(); } - - await server.StopAsync(); } mockTrace.Verify(trace => @@ -968,8 +929,6 @@ await connection.Receive( // The server should close the connection in this situation. await connection.WaitForConnectionClose(); } - - await server.StopAsync(); } mockTrace.Verify(trace => @@ -1017,8 +976,6 @@ await connection.Receive( "hello,"); } - await server.StopAsync(); - // Verify the request was really aborted. A timeout in // the app would cause a server error and skip the content length // check altogether, making the test pass for the wrong reason. @@ -1064,8 +1021,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } var error = TestApplicationErrorLogger.Messages.Where(message => message.LogLevel == LogLevel.Error); @@ -1104,8 +1059,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } Assert.Empty(TestApplicationErrorLogger.Messages.Where(message => message.LogLevel == LogLevel.Error)); @@ -1142,8 +1095,6 @@ await connection.Receive( "", "hello, world"); } - - await server.StopAsync(); } Assert.Empty(TestApplicationErrorLogger.Messages.Where(message => message.LogLevel == LogLevel.Error)); @@ -1180,8 +1131,6 @@ await connection.Receive( "", "hello, world"); } - - await server.StopAsync(); } Assert.Empty(TestApplicationErrorLogger.Messages.Where(message => message.LogLevel == LogLevel.Error)); @@ -1210,8 +1159,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1243,8 +1190,6 @@ await connection.Receive( flushed.SetResult(); } - - await server.StopAsync(); } } @@ -1278,8 +1223,6 @@ await connection.Receive( flushed.SetResult(); } - - await server.StopAsync(); } } @@ -1314,8 +1257,6 @@ await connection.Receive( await connection.Receive("hello, world"); } - - await server.StopAsync(); } } @@ -1357,8 +1298,6 @@ await connection.ReceiveEnd( "", expectedResponse); } - - await server.StopAsync(); } } @@ -1404,8 +1343,6 @@ await connection.ReceiveEnd( "", "hello, world"); } - - await server.StopAsync(); } } @@ -1452,8 +1389,6 @@ await connection.ReceiveEnd( "", "hello, world"); } - - await server.StopAsync(); } } @@ -1497,8 +1432,6 @@ await connection.Receive( "", "hello, world"); } - - await server.StopAsync(); } } @@ -1541,8 +1474,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1585,8 +1516,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1632,8 +1561,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1679,8 +1606,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1721,8 +1646,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1766,8 +1689,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1805,8 +1726,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -1835,8 +1754,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } #pragma warning disable CS0618 // Type or member is obsolete @@ -1911,8 +1828,6 @@ await connection.Send( await connection.ReceiveEnd(); } - - await server.StopAsync(); } Assert.True(foundMessage, "Expected log not found"); @@ -1956,8 +1871,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } #pragma warning disable CS0618 // Type or member is obsolete @@ -2010,8 +1923,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -2036,8 +1947,6 @@ await connection.ReceiveEnd( "", "Hello World"); } - - await server.StopAsync(); } } @@ -2070,8 +1979,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -2116,8 +2023,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -2141,8 +2046,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -2192,8 +2095,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -2240,8 +2141,6 @@ await connection.ReceiveEnd( "", "hello, world"); } - - await server.StopAsync(); } } @@ -2289,8 +2188,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } Assert.False(onStartingCalled); @@ -2347,8 +2244,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } // The first registered OnStarting callback should have been called, @@ -2399,8 +2294,6 @@ await connection.Receive( await tcs.Task.DefaultTimeout(); } - - await server.StopAsync(); } } @@ -2446,8 +2339,6 @@ await connection.Receive( await tcs.Task.DefaultTimeout(); } - - await server.StopAsync(); } } @@ -2492,8 +2383,6 @@ await connection.Receive( "", "Hello World"); } - - await server.StopAsync(); } // All OnCompleted callbacks should be called even if they throw. @@ -2537,8 +2426,6 @@ await connection.ReceiveEnd( "", "Hello World"); } - - await server.StopAsync(); } Assert.True(onStartingCalled); @@ -2580,8 +2467,6 @@ await connection.ReceiveEnd( "", "Hello"); } - - await server.StopAsync(); } Assert.True(onStartingCalled); @@ -2615,8 +2500,6 @@ await connection.ReceiveEnd( "", "Hello World"); } - - await server.StopAsync(); } Assert.Empty(TestApplicationErrorLogger.Messages.Where(message => message.LogLevel == LogLevel.Error)); @@ -2642,8 +2525,6 @@ await connection.Send( ""); await connection.ReceiveEnd(); } - - await server.StopAsync(); } } @@ -2667,8 +2548,6 @@ await connection.Send( ""); await connection.ReceiveEnd(); } - - await server.StopAsync(); } Assert.Single(TestApplicationErrorLogger.Messages.Where(m => m.Message.Contains(CoreStrings.ConnectionAbortedByApplication))); @@ -2753,8 +2632,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -2784,8 +2661,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -2814,8 +2689,6 @@ await connection.Receive( "Content-Length: 0", ""); } - - await server.StopAsync(); } } @@ -2846,8 +2719,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -2880,8 +2751,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -2912,8 +2781,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -2942,8 +2809,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -2973,8 +2838,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -3013,8 +2876,6 @@ await connection.Receive( // If we reach this point before the app exits, this means the flush finished early. tcs.SetResult(); } - - await server.StopAsync(); } } @@ -3045,8 +2906,6 @@ await connection.Receive( "", "Hello World"); } - - await server.StopAsync(); } } @@ -3077,8 +2936,6 @@ await connection.Receive( "", expectedString); } - - await server.StopAsync(); } } @@ -3128,8 +2985,6 @@ await connection.Receive( "", expectedString); } - - await server.StopAsync(); } } @@ -3161,8 +3016,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -3211,8 +3064,6 @@ await connection.Receive( // Wait for all callbacks to be called. await onStartingTcs.Task.DefaultTimeout(); } - - await server.StopAsync(); } Assert.Equal(1, callOrder.Pop()); @@ -3264,8 +3115,6 @@ await connection.Receive( // Wait for all callbacks to be called. await onCompletedTcs.Task.DefaultTimeout(); } - - await server.StopAsync(); } Assert.Equal(1, callOrder.Pop()); @@ -3299,8 +3148,6 @@ await connection.Receive( "", "Hello1"); } - - await server.StopAsync(); } } @@ -3327,8 +3174,6 @@ await connection.Receive( "", "Hello1"); } - - await server.StopAsync(); } } @@ -3364,8 +3209,6 @@ await connection.Receive( "", "Hello!"); } - - await server.StopAsync(); } } @@ -3405,8 +3248,6 @@ await connection.Receive( "", "Hello!"); } - - await server.StopAsync(); } } @@ -3436,8 +3277,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -3471,8 +3310,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -3503,8 +3340,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -3537,8 +3372,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -3577,8 +3410,6 @@ await connection.Receive( "", "Hello World!"); } - - await server.StopAsync(); } } @@ -3618,8 +3449,6 @@ await connection.Receive( "", "Hello World!"); } - - await server.StopAsync(); } } @@ -3646,8 +3475,6 @@ await connection.Receive( "", "hello, world"); } - - await server.StopAsync(); } } @@ -3690,8 +3517,6 @@ await connection.Receive( "hello, world", "hello, world"); } - - await server.StopAsync(); } } @@ -3718,8 +3543,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -3749,8 +3572,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } Assert.NotNull(writeEx); @@ -3805,8 +3626,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -3856,8 +3675,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -3919,8 +3736,6 @@ await connection.Receive( "a"); } } - - await server.StopAsync(); } } @@ -3966,8 +3781,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -3997,8 +3810,6 @@ await connection.Receive( Assert.Contains(TestSink.Writes, w => w.EventId.Id == 13 && w.LogLevel == LogLevel.Error && w.Exception is ConnectionAbortedException && w.Exception.InnerException == expectedException); } - - await server.StopAsync(); } } @@ -4031,8 +3842,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -4062,8 +3871,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -4099,8 +3906,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -4134,8 +3939,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -4167,8 +3970,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } Assert.NotNull(writeEx); @@ -4203,8 +4004,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } @@ -4239,8 +4038,6 @@ await connection.Receive( "", ""); } - - await server.StopAsync(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs index d64d17135391..5dfcaf24e995 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs @@ -24,7 +24,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTrans /// /// In-memory TestServer /// _memoryPool; private readonly RequestDelegate _app; @@ -114,11 +114,6 @@ public Task StopAsync(CancellationToken cancellationToken = default) return _host.StopAsync(cancellationToken); } - public void Dispose() - { - _host.Dispose(); - _memoryPool.Dispose(); - } void IStartup.Configure(IApplicationBuilder app) { @@ -133,6 +128,7 @@ IServiceProvider IStartup.ConfigureServices(IServiceCollection services) public async ValueTask DisposeAsync() { // The concrete Host implements IAsyncDisposable + await _host.StopAsync(); await ((IAsyncDisposable)_host).ConfigureAwait(false).DisposeAsync(); _memoryPool.Dispose(); } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/UpgradeTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/UpgradeTests.cs index 79d2831e959f..30b8474ea252 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/UpgradeTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/UpgradeTests.cs @@ -51,8 +51,6 @@ await connection.Receive("HTTP/1.1 101 Switching Protocols", await connection.Receive("New protocol data"); await upgrade.Task.DefaultTimeout(); } - - await server.StopAsync(); } } @@ -108,8 +106,6 @@ await connection.Receive("HTTP/1.1 101 Switching Protocols", await upgrade.Task.DefaultTimeout(); } - - await server.StopAsync(); } } @@ -148,8 +144,6 @@ await connection.Receive("HTTP/1.1 101 Switching Protocols", ""); await connection.WaitForConnectionClose(); } - - await server.StopAsync(); } var ex = await Assert.ThrowsAsync(async () => await upgradeTcs.Task.DefaultTimeout()); @@ -178,8 +172,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -204,8 +196,6 @@ await connection.Send("POST / HTTP/1.1", await connection.SendEmptyGetWithUpgrade(); await connection.Receive("HTTP/1.1 200 OK"); } - - await server.StopAsync(); } } @@ -230,8 +220,6 @@ await connection.ReceiveEnd( "", ""); } - - await server.StopAsync(); } } @@ -262,8 +250,6 @@ public async Task ThrowsWhenUpgradingNonUpgradableRequest() await connection.SendEmptyGet(); await connection.Receive("HTTP/1.1 200 OK"); } - - await server.StopAsync(); } var ex = await Assert.ThrowsAsync(async () => await upgradeTcs.Task).DefaultTimeout(); @@ -315,8 +301,6 @@ public async Task RejectsUpgradeWhenLimitReached() await connection.Receive("HTTP/1.1 200"); } } - - await server.StopAsync(); } var exception = await Assert.ThrowsAsync(async () => await upgradeTcs.Task.TimeoutAfter(TimeSpan.FromSeconds(60))); @@ -357,8 +341,6 @@ await connection.Receive("HTTP/1.1 101 Switching Protocols", } await appCompletedTcs.Task.DefaultTimeout(); - - await server.StopAsync(); } } } From d6907b711bc8a6be7c8e542259b71c579b0b34ce Mon Sep 17 00:00:00 2001 From: Kahbazi Date: Sat, 1 Aug 2020 15:48:29 +0430 Subject: [PATCH 10/13] implement IAsyncDisposable for TestServer --- .../test/TransportTestHelpers/TestServer.cs | 8 +++-- .../ConnectionMiddlewareTests.cs | 3 +- .../FunctionalTests/Http2/HandshakeTests.cs | 7 ++-- .../FunctionalTests/Http2/ShutdownTests.cs | 4 +-- .../test/FunctionalTests/ListenHandleTests.cs | 3 +- .../test/FunctionalTests/RequestTests.cs | 31 ++++++----------- .../test/FunctionalTests/ResponseTests.cs | 34 ++++++------------- .../TestTransport/TestServer.cs | 2 +- 8 files changed, 33 insertions(+), 59 deletions(-) diff --git a/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs b/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs index a21358bb9e04..cb4653de6cd2 100644 --- a/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs +++ b/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs @@ -26,7 +26,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests /// /// Summary description for TestServer /// - internal class TestServer : IDisposable, IStartup + internal class TestServer : IAsyncDisposable, IStartup { private IHost _host; private ListenOptions _listenOptions; @@ -135,9 +135,11 @@ public Task StopAsync(CancellationToken token = default) return _host.StopAsync(token); } - public void Dispose() + public async ValueTask DisposeAsync() { - _host.Dispose(); + await _host.StopAsync(); + // The concrete Host implements IAsyncDisposable + await ((IAsyncDisposable)_host).ConfigureAwait(false).DisposeAsync(); } } } diff --git a/src/Servers/Kestrel/test/FunctionalTests/ConnectionMiddlewareTests.cs b/src/Servers/Kestrel/test/FunctionalTests/ConnectionMiddlewareTests.cs index aa16d48a88f9..2956fc20c979 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/ConnectionMiddlewareTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/ConnectionMiddlewareTests.cs @@ -22,7 +22,7 @@ public async Task ThrowingSynchronousConnectionMiddlewareDoesNotCrashServer() var serviceContext = new TestServiceContext(LoggerFactory); - using (var server = new TestServer(TestApp.EchoApp, serviceContext, listenOptions)) + await using (var server = new TestServer(TestApp.EchoApp, serviceContext, listenOptions)) { using (var connection = server.CreateConnection()) { @@ -41,7 +41,6 @@ await connection.Send( } }); } - await server.StopAsync(); } } } diff --git a/src/Servers/Kestrel/test/FunctionalTests/Http2/HandshakeTests.cs b/src/Servers/Kestrel/test/FunctionalTests/Http2/HandshakeTests.cs index c4a89e9fcfca..7304e7c3593d 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/Http2/HandshakeTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/Http2/HandshakeTests.cs @@ -84,7 +84,7 @@ public void TlsAndHttp2NotSupportedOnWin7() [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10)] public async Task TlsAlpnHandshakeSelectsHttp2From1and2() { - using (var server = new TestServer(context => + await using (var server = new TestServer(context => { var tlsFeature = context.Features.Get(); Assert.NotNull(tlsFeature); @@ -104,8 +104,6 @@ public async Task TlsAlpnHandshakeSelectsHttp2From1and2() { var result = await Client.GetStringAsync($"https://localhost:{server.Port}/"); Assert.Equal("hello world HTTP/2", result); - - await server.StopAsync(); } } @@ -115,7 +113,7 @@ public async Task TlsAlpnHandshakeSelectsHttp2From1and2() [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10)] public async Task TlsAlpnHandshakeSelectsHttp2() { - using (var server = new TestServer(context => + await using (var server = new TestServer(context => { var tlsFeature = context.Features.Get(); Assert.NotNull(tlsFeature); @@ -135,7 +133,6 @@ public async Task TlsAlpnHandshakeSelectsHttp2() { var result = await Client.GetStringAsync($"https://localhost:{server.Port}/"); Assert.Equal("hello world HTTP/2", result); - await server.StopAsync(); } } } diff --git a/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs b/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs index d5788e336912..560a2640163c 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs @@ -62,7 +62,7 @@ public async Task GracefulShutdownWaitsForRequestsToFinish() testContext.InitializeHeartbeat(); - using (var server = new TestServer(async context => + await using (var server = new TestServer(async context => { requestStarted.SetResult(); await requestUnblocked.Task.DefaultTimeout(); @@ -116,7 +116,7 @@ public async Task GracefulTurnsAbortiveIfRequestsDoNotFinish() TestApplicationErrorLogger.ThrowOnUngracefulShutdown = false; // Abortive shutdown leaves one request hanging - using (var server = new TestServer(async context => + await using (var server = new TestServer(async context => { requestStarted.SetResult(); await requestUnblocked.Task.DefaultTimeout(); diff --git a/src/Servers/Kestrel/test/FunctionalTests/ListenHandleTests.cs b/src/Servers/Kestrel/test/FunctionalTests/ListenHandleTests.cs index a9cac6f7885f..28c233d02f7a 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/ListenHandleTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/ListenHandleTests.cs @@ -28,7 +28,7 @@ public async Task CanListenToOpenTcpSocketHandle() { _canListenToOpenTcpSocketHandleSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); - using (var server = new TestServer(_ => Task.CompletedTask, new TestServiceContext(LoggerFactory), + await using (var server = new TestServer(_ => Task.CompletedTask, new TestServiceContext(LoggerFactory), new ListenOptions((ulong)_canListenToOpenTcpSocketHandleSocket.Handle))) { using (var connection = new TestConnection(((IPEndPoint)_canListenToOpenTcpSocketHandleSocket.LocalEndPoint).Port)) @@ -42,7 +42,6 @@ await connection.Receive( "", ""); } - await server.StopAsync(); } } } diff --git a/src/Servers/Kestrel/test/FunctionalTests/RequestTests.cs b/src/Servers/Kestrel/test/FunctionalTests/RequestTests.cs index 44ab8e0b03e9..79860c8420fa 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/RequestTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/RequestTests.cs @@ -182,7 +182,7 @@ public async Task CanHandleMultipleConcurrentRequests() var requestNumber = 0; var ensureConcurrentRequestTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using (var server = new TestServer(async context => + await using (var server = new TestServer(async context => { if (Interlocked.Increment(ref requestNumber) == 1) { @@ -219,7 +219,6 @@ await connection2.Receive($"HTTP/1.1 200 OK", "", ""); } - await server.StopAsync(); } } @@ -254,7 +253,7 @@ public async Task ConnectionResetPriorToRequestIsLoggedAsDebug() } }; - using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory))) + await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory))) { using (var connection = server.CreateConnection()) { @@ -269,8 +268,6 @@ public async Task ConnectionResetPriorToRequestIsLoggedAsDebug() // is still in flight when the connection is aborted, leading to the reset never being received // and therefore not logged. Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout)); - - await server.StopAsync(); } Assert.False(loggedHigherThanDebug); @@ -302,7 +299,7 @@ public async Task ConnectionResetBetweenRequestsIsLoggedAsDebug() } }; - using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory))) + await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory))) { using (var connection = server.CreateConnection()) { @@ -330,7 +327,6 @@ await connection.Receive( // is still in flight when the connection is aborted, leading to the reset never being received // and therefore not logged. Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout)); - await server.StopAsync(); } Assert.False(loggedHigherThanDebug); @@ -364,7 +360,7 @@ public async Task ConnectionResetMidRequestIsLoggedAsDebug() } }; - using (var server = new TestServer(async context => + await using (var server = new TestServer(async context => { requestStarted.Release(); await connectionClosing.WaitAsync(); @@ -387,7 +383,6 @@ public async Task ConnectionResetMidRequestIsLoggedAsDebug() // and therefore not logged. Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout), "Connection reset event should have been logged"); connectionClosing.Release(); - await server.StopAsync(); } Assert.False(loggedHigherThanDebug, "Logged event should not have been higher than debug."); @@ -528,7 +523,7 @@ public async Task ConnectionClosedTokenFiresOnClientFIN(ListenOptions listenOpti var appStartedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var connectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using (var server = new TestServer(context => + await using (var server = new TestServer(context => { appStartedTcs.SetResult(); @@ -552,7 +547,6 @@ await connection.Send( await connectionClosedTcs.Task.DefaultTimeout(); } - await server.StopAsync(); } } @@ -563,7 +557,7 @@ public async Task ConnectionClosedTokenFiresOnServerFIN(ListenOptions listenOpti var testContext = new TestServiceContext(LoggerFactory); var connectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using (var server = new TestServer(context => + await using (var server = new TestServer(context => { var connectionLifetimeFeature = context.Features.Get(); connectionLifetimeFeature.ConnectionClosed.Register(() => connectionClosedTcs.SetResult()); @@ -589,7 +583,6 @@ await connection.ReceiveEnd($"HTTP/1.1 200 OK", "", ""); } - await server.StopAsync(); } } @@ -600,7 +593,7 @@ public async Task ConnectionClosedTokenFiresOnServerAbort(ListenOptions listenOp var testContext = new TestServiceContext(LoggerFactory); var connectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using (var server = new TestServer(context => + await using (var server = new TestServer(context => { var connectionLifetimeFeature = context.Features.Get(); connectionLifetimeFeature.ConnectionClosed.Register(() => connectionClosedTcs.SetResult()); @@ -631,7 +624,6 @@ await connection.Send( // isn't guaranteed but not unexpected. } } - await server.StopAsync(); } } @@ -648,7 +640,7 @@ public async Task RequestsCanBeAbortedMidRead(ListenOptions listenOptions) var registrationTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var requestId = 0; - using (var server = new TestServer(async httpContext => + await using (var server = new TestServer(async httpContext => { requestId++; @@ -713,7 +705,6 @@ await connection.Send("POST / HTTP/1.1", ""); await connection.WaitForConnectionClose(); } - await server.StopAsync(); } await Assert.ThrowsAsync(async () => await readTcs.Task); @@ -773,7 +764,7 @@ public async Task ServerCanAbortConnectionAfterUnobservedClose(ListenOptions lis var scratchBuffer = new byte[maxRequestBufferSize * 8]; - using (var server = new TestServer(async context => + await using (var server = new TestServer(async context => { await clientClosedConnection.Task; @@ -802,7 +793,6 @@ await connection.Send( clientClosedConnection.SetResult(); await appFuncCompleted.Task.DefaultTimeout(); - await server.StopAsync(); } mockKestrelTrace.Verify(t => t.ConnectionStop(It.IsAny()), Times.Once()); @@ -820,7 +810,7 @@ public async Task AppCanHandleClientAbortingConnectionMidRequest(ListenOptions l var scratchBuffer = new byte[4096]; - using (var server = new TestServer(async context => + await using (var server = new TestServer(async context => { appStartedTcs.SetResult(); @@ -855,7 +845,6 @@ await connection.Send( } await Assert.ThrowsAnyAsync(() => readTcs.Task).DefaultTimeout(); - await server.StopAsync(); } mockKestrelTrace.Verify(t => t.ConnectionStop(It.IsAny()), Times.Once()); diff --git a/src/Servers/Kestrel/test/FunctionalTests/ResponseTests.cs b/src/Servers/Kestrel/test/FunctionalTests/ResponseTests.cs index 11e86e8a2032..ac87698310a0 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/ResponseTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/ResponseTests.cs @@ -152,7 +152,7 @@ public async Task WriteAfterConnectionCloseNoops(ListenOptions listenOptions) var requestStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var appCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using (var server = new TestServer(async httpContext => + await using (var server = new TestServer(async httpContext => { try { @@ -184,7 +184,6 @@ await connection.Send( connectionClosed.SetResult(); await appCompleted.Task.DefaultTimeout(); - await server.StopAsync(); } } @@ -202,7 +201,7 @@ public async Task ThrowsOnWriteWithRequestAbortedTokenAfterRequestIsAborted(List var requestAbortedWh = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var requestStartWh = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using (var server = new TestServer(async httpContext => + await using (var server = new TestServer(async httpContext => { requestStartWh.SetResult(); @@ -248,7 +247,6 @@ await connection.Send( // RequestAborted tripped await requestAbortedWh.Task.DefaultTimeout(); - await server.StopAsync(); } } @@ -295,7 +293,7 @@ public async Task WritingToConnectionAfterUnobservedCloseTriggersRequestAbortedT var scratchBuffer = new byte[maxRequestBufferSize * 8]; - using (var server = new TestServer(async context => + await using (var server = new TestServer(async context => { context.RequestAborted.Register(() => requestAborted.SetResult()); @@ -340,7 +338,6 @@ await connection.Send( clientClosedConnection.SetResult(); await Assert.ThrowsAnyAsync(() => writeTcs.Task).DefaultTimeout(); - await server.StopAsync(); } mockKestrelTrace.Verify(t => t.ConnectionStop(It.IsAny()), Times.Once()); @@ -363,7 +360,7 @@ public async Task AppCanHandleClientAbortingConnectionMidResponse(ListenOptions var scratchBuffer = new byte[responseBodySegmentSize]; - using (var server = new TestServer(async context => + await using (var server = new TestServer(async context => { context.RequestAborted.Register(() => requestAborted.SetResult()); @@ -407,7 +404,6 @@ await connection.Send( // On macOS, the default 5 shutdown timeout is insufficient for the write loop to complete, so give it extra time. await appCompletedTcs.Task.DefaultTimeout(); - await server.StopAsync(); } var coreLogs = TestSink.Writes.Where(w => w.LoggerName == "Microsoft.AspNetCore.Server.Kestrel"); @@ -430,7 +426,7 @@ public async Task ClientAbortingConnectionImmediatelyIsNotLoggedHigherThanDebug( // There's not guarantee that the app even gets invoked in this test. The connection reset can be observed // as early as accept. var testServiceContext = new TestServiceContext(LoggerFactory); - using (var server = new TestServer(context => Task.CompletedTask, testServiceContext, listenOptions)) + await using (var server = new TestServer(context => Task.CompletedTask, testServiceContext, listenOptions)) { for (var i = 0; i < numConnections; i++) { @@ -445,7 +441,6 @@ await connection.Send( connection.Reset(); } } - await server.StopAsync(); } var transportLogs = TestSink.Writes.Where(w => w.LoggerName == "Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv" || @@ -530,7 +525,7 @@ async Task App(HttpContext context) } } - using (var server = new TestServer(App, testContext)) + await using (var server = new TestServer(App, testContext)) { using (var connection = server.CreateConnection()) { @@ -555,7 +550,6 @@ await connection.Send( sw.Stop(); logger.LogInformation("Connection was aborted after {totalMilliseconds}ms.", sw.ElapsedMilliseconds); } - await server.StopAsync(); } } @@ -599,7 +593,7 @@ void ConfigureListenOptions(ListenOptions listenOptions) listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = certificate }); } - using (var server = new TestServer(async context => + await using (var server = new TestServer(async context => { context.RequestAborted.Register(() => { @@ -643,7 +637,6 @@ void ConfigureListenOptions(ListenOptions listenOptions) await AssertStreamAborted(connection.Stream, chunkSize * chunks); } } - await server.StopAsync(); } } @@ -708,7 +701,7 @@ async Task App(HttpContext context) copyToAsyncCts.SetException(new Exception("This shouldn't be reached.")); } - using (var server = new TestServer(App, testContext, listenOptions)) + await using (var server = new TestServer(App, testContext, listenOptions)) { using (var connection = server.CreateConnection()) { @@ -737,7 +730,6 @@ await connection.Send( await Assert.ThrowsAnyAsync(() => copyToAsyncCts.Task).DefaultTimeout(); await AssertStreamAborted(connection.Stream, responseSize); } - await server.StopAsync(); } } @@ -785,7 +777,7 @@ async Task App(HttpContext context) appFuncCompleted.SetResult(); } - using (var server = new TestServer(App, testContext, listenOptions)) + await using (var server = new TestServer(App, testContext, listenOptions)) { using (var connection = server.CreateConnection()) { @@ -811,7 +803,6 @@ await connection.Receive( connection.ShutdownSend(); await connection.WaitForConnectionClose(); } - await server.StopAsync(); } mockKestrelTrace.Verify(t => t.ResponseMinimumDataRateNotSatisfied(It.IsAny(), It.IsAny()), Times.Never()); @@ -863,7 +854,7 @@ async Task App(HttpContext context) await context.Response.BodyWriter.FlushAsync(); } - using (var server = new TestServer(App, testContext, listenOptions)) + await using (var server = new TestServer(App, testContext, listenOptions)) { using (var connection = server.CreateConnection()) { @@ -898,8 +889,6 @@ await connection.Receive( connection.ShutdownSend(); await connection.WaitForConnectionClose(); } - - await server.StopAsync(); } mockKestrelTrace.Verify(t => t.ResponseMinimumDataRateNotSatisfied(It.IsAny(), It.IsAny()), Times.Never()); @@ -951,7 +940,7 @@ async Task App(HttpContext context) appFuncCompleted.SetResult(); } - using (var server = new TestServer(App, testContext, listenOptions)) + await using (var server = new TestServer(App, testContext, listenOptions)) { using (var connection = server.CreateConnection()) { @@ -976,7 +965,6 @@ await connection.Receive( await AssertStreamCompletedAtTargetRate(connection.Stream, expectedBytes: 33_553_556, targetBytesPerSecond); await appFuncCompleted.Task.DefaultTimeout(); } - await server.StopAsync(); } mockKestrelTrace.Verify(t => t.ResponseMinimumDataRateNotSatisfied(It.IsAny(), It.IsAny()), Times.Never()); diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs index 5dfcaf24e995..23530407b6ab 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs @@ -127,8 +127,8 @@ IServiceProvider IStartup.ConfigureServices(IServiceCollection services) public async ValueTask DisposeAsync() { - // The concrete Host implements IAsyncDisposable await _host.StopAsync(); + // The concrete Host implements IAsyncDisposable await ((IAsyncDisposable)_host).ConfigureAwait(false).DisposeAsync(); _memoryPool.Dispose(); } From 117e2bba92389c36aba821931d4dfa8d5e3c3a30 Mon Sep 17 00:00:00 2001 From: Kahbazi Date: Tue, 4 Aug 2020 00:35:47 +0430 Subject: [PATCH 11/13] configure await --- .../Kestrel/shared/test/TransportTestHelpers/TestServer.cs | 4 ++-- .../test/InMemory.FunctionalTests/TestTransport/TestServer.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs b/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs index cb4653de6cd2..f24b116ae97e 100644 --- a/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs +++ b/src/Servers/Kestrel/shared/test/TransportTestHelpers/TestServer.cs @@ -137,9 +137,9 @@ public Task StopAsync(CancellationToken token = default) public async ValueTask DisposeAsync() { - await _host.StopAsync(); + await _host.StopAsync().ConfigureAwait(false); // The concrete Host implements IAsyncDisposable - await ((IAsyncDisposable)_host).ConfigureAwait(false).DisposeAsync(); + await ((IAsyncDisposable)_host).DisposeAsync().ConfigureAwait(false); } } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs index 23530407b6ab..e69e7b47644f 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/TestTransport/TestServer.cs @@ -127,9 +127,9 @@ IServiceProvider IStartup.ConfigureServices(IServiceCollection services) public async ValueTask DisposeAsync() { - await _host.StopAsync(); + await _host.StopAsync().ConfigureAwait(false); // The concrete Host implements IAsyncDisposable - await ((IAsyncDisposable)_host).ConfigureAwait(false).DisposeAsync(); + await ((IAsyncDisposable)_host).DisposeAsync().ConfigureAwait(false); _memoryPool.Dispose(); } } From 413f7b5a09dda66a504371736ebf8053faf0af94 Mon Sep 17 00:00:00 2001 From: Kahbazi Date: Tue, 4 Aug 2020 11:29:21 +0430 Subject: [PATCH 12/13] catch OperationCanceledException --- .../Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs | 9 ++++++++- .../test/FunctionalTests/MaxRequestBufferSizeTests.cs | 9 ++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs b/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs index 560a2640163c..874aae77f12f 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs @@ -146,7 +146,14 @@ public async Task GracefulTurnsAbortiveIfRequestsDoNotFinish() await closingMessageTask; cts.Cancel(); - await stopServerTask; + try + { + await stopServerTask; + } + catch (OperationCanceledException) + { + + } } Assert.Contains(TestApplicationErrorLogger.Messages, m => m.Message.Contains("is closing.")); diff --git a/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs b/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs index bcadf5f392f7..3ff23e8ec71b 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs @@ -272,7 +272,14 @@ public async Task ServerShutsDownGracefullyWhenMaxRequestBufferSizeExceeded() // Dispose host prior to closing connection to verify the server doesn't throw during shutdown // if a connection no longer has alloc and read callbacks configured. - await host.StopAsync(); + try + { + await host.StopAsync(); + } + catch (OperationCanceledException) + { + + } host.Dispose(); } } From 86a896bbf41df6fadbaec74a68693bfc8779495a Mon Sep 17 00:00:00 2001 From: Brennan Date: Wed, 5 Aug 2020 13:32:46 -0700 Subject: [PATCH 13/13] Apply suggestions from code review --- src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs | 1 + .../Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs b/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs index 874aae77f12f..eb92dec0b798 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/Http2/ShutdownTests.cs @@ -150,6 +150,7 @@ public async Task GracefulTurnsAbortiveIfRequestsDoNotFinish() { await stopServerTask; } + // Remove when https://github.com/dotnet/runtime/issues/40290 is fixed catch (OperationCanceledException) { diff --git a/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs b/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs index 3ff23e8ec71b..702edf53f9d0 100644 --- a/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs +++ b/src/Servers/Kestrel/test/FunctionalTests/MaxRequestBufferSizeTests.cs @@ -276,6 +276,7 @@ public async Task ServerShutsDownGracefullyWhenMaxRequestBufferSizeExceeded() { await host.StopAsync(); } + // Remove when https://github.com/dotnet/runtime/issues/40290 is fixed catch (OperationCanceledException) {