[Kestrel] Move to GenericHost (#24279)

* [Kestrel] Move to GenericHost

* Change TransportSelector

* Add an empty app for TestServer

* Add an empty app for TestServer

* Set app

* Stop host

* Stop the TestSserver

* Stop more hosts!

* Stop host in dispose

* implement IAsyncDisposable for TestServer

* configure await

* catch OperationCanceledException

* Apply suggestions from code review

Co-authored-by: Brennan <brecon@microsoft.com>
This commit is contained in:
Kahbazi 2020-08-06 02:18:53 +04:30 committed by GitHub
parent 25948ab962
commit b2c7d514c9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 915 additions and 735 deletions

View File

@ -16,6 +16,7 @@ using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Microsoft.AspNetCore.Server.Kestrel.Performance namespace Microsoft.AspNetCore.Server.Kestrel.Performance
{ {
@ -33,7 +34,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Performance
private static readonly string _plaintextPipelinedExpectedResponse = private static readonly string _plaintextPipelinedExpectedResponse =
string.Concat(Enumerable.Repeat(_plaintextExpectedResponse, RequestParsingData.Pipelining)); string.Concat(Enumerable.Repeat(_plaintextExpectedResponse, RequestParsingData.Pipelining));
private IWebHost _host; private IHost _host;
private InMemoryConnection _connection; private InMemoryConnection _connection;
[GlobalSetup(Target = nameof(Plaintext) + "," + nameof(PlaintextPipelined))] [GlobalSetup(Target = nameof(Plaintext) + "," + nameof(PlaintextPipelined))]
@ -41,14 +42,18 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Performance
{ {
var transportFactory = new InMemoryTransportFactory(connectionsPerEndPoint: 1); var transportFactory = new InMemoryTransportFactory(connectionsPerEndPoint: 1);
_host = new WebHostBuilder() _host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
// Prevent VS from attaching to hosting startup which could impact results // Prevent VS from attaching to hosting startup which could impact results
.UseSetting("preventHostingStartup", "true") .UseSetting("preventHostingStartup", "true")
.UseKestrel() .UseKestrel()
// Bind to a single non-HTTPS endpoint // Bind to a single non-HTTPS endpoint
.UseUrls("http://127.0.0.1:5000") .UseUrls("http://127.0.0.1:5000")
.Configure(app => app.UseMiddleware<PlaintextMiddleware>());
})
.ConfigureServices(services => services.AddSingleton<IConnectionListenerFactory>(transportFactory)) .ConfigureServices(services => services.AddSingleton<IConnectionListenerFactory>(transportFactory))
.Configure(app => app.UseMiddleware<PlaintextMiddleware>())
.Build(); .Build();
_host.Start(); _host.Start();

View File

@ -1,12 +1,12 @@
using System; using System;
using System.IO; using System.IO;
using System.Net;
using System.Security.Authentication; using System.Security.Authentication;
using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Http2SampleApp namespace Http2SampleApp
@ -15,13 +15,10 @@ namespace Http2SampleApp
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
var hostBuilder = new WebHostBuilder() var hostBuilder = new HostBuilder()
.ConfigureLogging((_, factory) => .ConfigureWebHost(webHostBuilder =>
{ {
// Set logging to the MAX. webHostBuilder
factory.SetMinimumLevel(LogLevel.Trace);
factory.AddConsole();
})
.UseKestrel() .UseKestrel()
.ConfigureKestrel((context, options) => .ConfigureKestrel((context, options) =>
{ {
@ -63,6 +60,13 @@ namespace Http2SampleApp
}) })
.UseContentRoot(Directory.GetCurrentDirectory()) .UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>(); .UseStartup<Startup>();
})
.ConfigureLogging((_, factory) =>
{
// Set logging to the MAX.
factory.SetMinimumLevel(LogLevel.Trace);
factory.AddConsole();
});
hostBuilder.Build().Run(); hostBuilder.Build().Run();
} }

View File

@ -7,6 +7,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace LargeResponseApp namespace LargeResponseApp
{ {
@ -38,13 +39,17 @@ namespace LargeResponseApp
public static Task Main(string[] args) public static Task Main(string[] args)
{ {
var host = new WebHostBuilder() var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(IPAddress.Loopback, 5001); options.Listen(IPAddress.Loopback, 5001);
}) })
.UseContentRoot(Directory.GetCurrentDirectory()) .UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>() .UseStartup<Startup>();
})
.Build(); .Build();
return host.RunAsync(); return host.RunAsync();

View File

@ -10,6 +10,7 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace PlaintextApp namespace PlaintextApp
{ {
@ -34,13 +35,17 @@ namespace PlaintextApp
public static async Task Main(string[] args) public static async Task Main(string[] args)
{ {
var host = new WebHostBuilder() var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(IPAddress.Loopback, 5001); options.Listen(IPAddress.Loopback, 5001);
}) })
.UseContentRoot(Directory.GetCurrentDirectory()) .UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>() .UseStartup<Startup>();
})
.Build(); .Build();
await host.RunAsync(); await host.RunAsync();

View File

@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace QuicSampleApp namespace QuicSampleApp
@ -22,12 +23,10 @@ namespace QuicSampleApp
public static void Main(string[] args) public static void Main(string[] args)
{ {
var hostBuilder = new WebHostBuilder() var hostBuilder = new HostBuilder()
.ConfigureLogging((_, factory) => .ConfigureWebHost(webHostBuilder =>
{ {
factory.SetMinimumLevel(LogLevel.Debug); webHostBuilder
factory.AddConsole();
})
.UseKestrel() .UseKestrel()
.UseQuic(options => .UseQuic(options =>
{ {
@ -76,6 +75,12 @@ namespace QuicSampleApp
}); });
}) })
.UseStartup<Startup>(); .UseStartup<Startup>();
})
.ConfigureLogging((_, factory) =>
{
factory.SetMinimumLevel(LogLevel.Debug);
factory.AddConsole();
});
hostBuilder.Build().Run(); hostBuilder.Build().Run();
} }

View File

@ -62,18 +62,10 @@ namespace SampleApp
Console.WriteLine("Unobserved exception: {0}", e.Exception); Console.WriteLine("Unobserved exception: {0}", e.Exception);
}; };
var hostBuilder = new WebHostBuilder() var hostBuilder = new HostBuilder()
.ConfigureLogging((_, factory) => .ConfigureWebHost(webHostBuilder =>
{ {
factory.SetMinimumLevel(LogLevel.Debug); webHostBuilder
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) => .UseKestrel((context, options) =>
{ {
if (context.HostingEnvironment.IsDevelopment()) if (context.HostingEnvironment.IsDevelopment())
@ -158,13 +150,25 @@ namespace SampleApp
{ {
// Use libuv if activated by systemd, since that's currently the only transport that supports being passed a socket handle. // Use libuv if activated by systemd, since that's currently the only transport that supports being passed a socket handle.
#pragma warning disable CS0618 #pragma warning disable CS0618
hostBuilder.UseLibuv(options => webHostBuilder.UseLibuv(options =>
{ {
// Uncomment the following line to change the default number of libuv threads for all endpoints. // Uncomment the following line to change the default number of libuv threads for all endpoints.
// options.ThreadCount = 4; // options.ThreadCount = 4;
}); });
#pragma warning restore CS0618 #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(); return hostBuilder.Build().RunAsync();
} }

View File

@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace SystemdTestApp namespace SystemdTestApp
@ -41,11 +42,10 @@ namespace SystemdTestApp
Console.WriteLine("Unobserved exception: {0}", e.Exception); Console.WriteLine("Unobserved exception: {0}", e.Exception);
}; };
var hostBuilder = new WebHostBuilder() var hostBuilder = new HostBuilder()
.ConfigureLogging((_, factory) => .ConfigureWebHost(webHostBuilder =>
{ {
factory.AddConsole(); webHostBuilder
})
.UseKestrel((context, options) => .UseKestrel((context, options) =>
{ {
var basePort = context.Configuration.GetValue<int?>("BASE_PORT") ?? 5000; var basePort = context.Configuration.GetValue<int?>("BASE_PORT") ?? 5000;
@ -76,13 +76,18 @@ namespace SystemdTestApp
{ {
// Use libuv if activated by systemd, since that's currently the only transport that supports being passed a socket handle. // Use libuv if activated by systemd, since that's currently the only transport that supports being passed a socket handle.
#pragma warning disable CS0618 #pragma warning disable CS0618
hostBuilder.UseLibuv(options => webHostBuilder.UseLibuv(options =>
{ {
// Uncomment the following line to change the default number of libuv threads for all endpoints. // Uncomment the following line to change the default number of libuv threads for all endpoints.
// options.ThreadCount = 4; // options.ThreadCount = 4;
}); });
#pragma warning restore CS0618 #pragma warning restore CS0618
} }
})
.ConfigureLogging((_, factory) =>
{
factory.AddConsole();
});
return hostBuilder.Build().RunAsync(); return hostBuilder.Build().RunAsync();
} }

View File

@ -26,9 +26,9 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
/// <summary> /// <summary>
/// Summary description for TestServer /// Summary description for TestServer
/// </summary> /// </summary>
internal class TestServer : IDisposable, IStartup internal class TestServer : IAsyncDisposable, IStartup
{ {
private IWebHost _host; private IHost _host;
private ListenOptions _listenOptions; private ListenOptions _listenOptions;
private readonly RequestDelegate _app; private readonly RequestDelegate _app;
@ -70,7 +70,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
_app = app; _app = app;
Context = context; Context = context;
_host = TransportSelector.GetWebHostBuilder(context.MemoryPoolFactory, context.ServerOptions.Limits.MaxRequestBufferSize) _host = TransportSelector.GetHostBuilder(context.MemoryPoolFactory, context.ServerOptions.Limits.MaxRequestBufferSize)
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
configureKestrel(options); configureKestrel(options);
@ -96,6 +99,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
}) })
.UseSetting(WebHostDefaults.ApplicationKey, typeof(TestServer).GetTypeInfo().Assembly.FullName) .UseSetting(WebHostDefaults.ApplicationKey, typeof(TestServer).GetTypeInfo().Assembly.FullName)
.UseSetting(WebHostDefaults.ShutdownTimeoutKey, TestConstants.DefaultTimeout.TotalSeconds.ToString()) .UseSetting(WebHostDefaults.ShutdownTimeoutKey, TestConstants.DefaultTimeout.TotalSeconds.ToString())
.Configure(app => { app.Run(_app); });
})
.Build(); .Build();
_host.Start(); _host.Start();
@ -130,9 +135,11 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
return _host.StopAsync(token); return _host.StopAsync(token);
} }
public void Dispose() public async ValueTask DisposeAsync()
{ {
_host.Dispose(); await _host.StopAsync().ConfigureAwait(false);
// The concrete Host implements IAsyncDisposable
await ((IAsyncDisposable)_host).DisposeAsync().ConfigureAwait(false);
} }
} }
} }

View File

@ -21,8 +21,11 @@ using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.Extensions.Hosting;
using Xunit; using Xunit;
using Xunit.Sdk; using Xunit.Sdk;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{ {
@ -182,7 +185,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
private async Task RegisterAddresses_Success(string addressInput, string[] testUrls, int testPort = 0) private async Task RegisterAddresses_Success(string addressInput, string[] testUrls, int testPort = 0)
{ {
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(serverOptions => .UseKestrel(serverOptions =>
{ {
serverOptions.ConfigureHttpsDefaults(httpsOptions => serverOptions.ConfigureHttpsDefaults(httpsOptions =>
@ -190,9 +196,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
httpsOptions.ServerCertificate = TestResources.GetTestCertificate(); httpsOptions.ServerCertificate = TestResources.GetTestCertificate();
}); });
}) })
.ConfigureServices(AddTestLogging)
.UseUrls(addressInput) .UseUrls(addressInput)
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -214,6 +221,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
Assert.Equal(uri.ToString(), response); Assert.Equal(uri.ToString(), response);
} }
await host.StopAsync();
} }
} }
@ -226,7 +235,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
[Fact] [Fact]
public async Task RegisterHttpAddress_UpgradedToHttpsByConfigureEndpointDefaults() public async Task RegisterHttpAddress_UpgradedToHttpsByConfigureEndpointDefaults()
{ {
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(serverOptions => .UseKestrel(serverOptions =>
{ {
serverOptions.ConfigureEndpointDefaults(listenOptions => serverOptions.ConfigureEndpointDefaults(listenOptions =>
@ -234,7 +246,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
listenOptions.UseHttps(TestResources.GetTestCertificate()); listenOptions.UseHttps(TestResources.GetTestCertificate());
}); });
}) })
.ConfigureServices(AddTestLogging)
.UseUrls("http://127.0.0.1:0") .UseUrls("http://127.0.0.1:0")
.Configure(app => .Configure(app =>
{ {
@ -245,6 +256,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
return context.Response.WriteAsync(serverAddresses.Addresses.First()); return context.Response.WriteAsync(serverAddresses.Addresses.First());
}); });
}); });
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -254,6 +267,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var response = await HttpClientSlim.GetStringAsync(expectedUrl, validateCertificate: false); var response = await HttpClientSlim.GetStringAsync(expectedUrl, validateCertificate: false);
Assert.Equal(expectedUrl, response); Assert.Equal(expectedUrl, response);
await host.StopAsync();
} }
} }
@ -293,8 +308,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
private async Task RegisterIPEndPoint_Success(IPEndPoint endPoint, string testUrl, int testPort = 0) private async Task RegisterIPEndPoint_Success(IPEndPoint endPoint, string testUrl, int testPort = 0)
{ {
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(endPoint, listenOptions => options.Listen(endPoint, listenOptions =>
@ -306,6 +323,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
}); });
}) })
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -353,13 +372,17 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
private async Task ListenAnyIP_Success(string[] testUrls, int testPort = 0) private async Task ListenAnyIP_Success(string[] testUrls, int testPort = 0)
{ {
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.ListenAnyIP(testPort); options.ListenAnyIP(testPort);
}) })
.ConfigureServices(AddTestLogging)
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -396,13 +419,17 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
private async Task ListenLocalhost_Success(string[] testUrls, int testPort = 0) private async Task ListenLocalhost_Success(string[] testUrls, int testPort = 0)
{ {
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.ListenLocalhost(testPort); options.ListenLocalhost(testPort);
}) })
.ConfigureServices(AddTestLogging)
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -478,8 +505,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
private async Task RegisterDefaultServerAddresses_Success(IEnumerable<string> addresses, bool mockHttps = false) private async Task RegisterDefaultServerAddresses_Success(IEnumerable<string> addresses, bool mockHttps = false)
{ {
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
if (mockHttps) if (mockHttps)
@ -488,6 +517,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
}) })
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -514,7 +545,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
[Fact] [Fact]
public void ThrowsWhenBindingToIPv4AddressInUse() public async Task ThrowsWhenBindingToIPv4AddressInUse()
{ {
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{ {
@ -522,22 +553,28 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
socket.Listen(0); socket.Listen(0);
var port = ((IPEndPoint)socket.LocalEndPoint).Port; var port = ((IPEndPoint)socket.LocalEndPoint).Port;
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel() .UseKestrel()
.UseUrls($"http://127.0.0.1:{port}") .UseUrls($"http://127.0.0.1:{port}")
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
});
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
var exception = Assert.Throws<IOException>(() => host.Start()); var exception = Assert.Throws<IOException>(() => host.Start());
Assert.Equal(CoreStrings.FormatEndpointAlreadyInUse($"http://127.0.0.1:{port}"), exception.Message); Assert.Equal(CoreStrings.FormatEndpointAlreadyInUse($"http://127.0.0.1:{port}"), exception.Message);
await host.StopAsync();
} }
} }
} }
[ConditionalFact] [ConditionalFact]
[IPv6SupportedCondition] [IPv6SupportedCondition]
public void ThrowsWhenBindingToIPv6AddressInUse() public async Task ThrowsWhenBindingToIPv6AddressInUse()
{ {
TestApplicationErrorLogger.IgnoredExceptions.Add(typeof(IOException)); TestApplicationErrorLogger.IgnoredExceptions.Add(typeof(IOException));
@ -547,16 +584,22 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
socket.Listen(0); socket.Listen(0);
var port = ((IPEndPoint)socket.LocalEndPoint).Port; var port = ((IPEndPoint)socket.LocalEndPoint).Port;
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel() .UseKestrel()
.UseUrls($"http://[::1]:{port}") .UseUrls($"http://[::1]:{port}")
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
var exception = Assert.Throws<IOException>(() => host.Start()); var exception = Assert.Throws<IOException>(() => host.Start());
Assert.Equal(CoreStrings.FormatEndpointAlreadyInUse($"http://[::1]:{port}"), exception.Message); Assert.Equal(CoreStrings.FormatEndpointAlreadyInUse($"http://[::1]:{port}"), exception.Message);
await host.StopAsync();
} }
} }
} }
@ -565,7 +608,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
public async Task OverrideDirectConfigurationWithIServerAddressesFeature_Succeeds() public async Task OverrideDirectConfigurationWithIServerAddressesFeature_Succeeds()
{ {
var useUrlsAddress = $"http://127.0.0.1:0"; var useUrlsAddress = $"http://127.0.0.1:0";
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions =>
@ -575,8 +621,9 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
}) })
.UseUrls(useUrlsAddress) .UseUrls(useUrlsAddress)
.PreferHostingUrls(true) .PreferHostingUrls(true)
.ConfigureServices(AddTestLogging)
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -586,7 +633,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
// If this isn't working properly, we'll get the HTTPS endpoint defined in UseKestrel // If this isn't working properly, we'll get the HTTPS endpoint defined in UseKestrel
// instead of the HTTP endpoint defined in UseUrls. // instead of the HTTP endpoint defined in UseUrls.
var serverAddresses = host.ServerFeatures.Get<IServerAddressesFeature>().Addresses; var serverAddresses = host.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>().Addresses;
Assert.Equal(1, serverAddresses.Count); Assert.Equal(1, serverAddresses.Count);
var useUrlsAddressWithPort = $"http://127.0.0.1:{port}"; var useUrlsAddressWithPort = $"http://127.0.0.1:{port}";
Assert.Equal(serverAddresses.First(), useUrlsAddressWithPort); Assert.Equal(serverAddresses.First(), useUrlsAddressWithPort);
@ -606,8 +653,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{ {
var useUrlsAddress = $"http://127.0.0.1:0"; var useUrlsAddress = $"http://127.0.0.1:0";
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions =>
@ -618,6 +667,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
.UseUrls($"http://127.0.0.1:0") .UseUrls($"http://127.0.0.1:0")
.PreferHostingUrls(false) .PreferHostingUrls(false)
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -627,7 +678,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
// If this isn't working properly, we'll get the HTTP endpoint defined in UseUrls // If this isn't working properly, we'll get the HTTP endpoint defined in UseUrls
// instead of the HTTPS endpoint defined in UseKestrel. // instead of the HTTPS endpoint defined in UseKestrel.
var serverAddresses = host.ServerFeatures.Get<IServerAddressesFeature>().Addresses; var serverAddresses = host.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>().Addresses;
Assert.Equal(1, serverAddresses.Count); Assert.Equal(1, serverAddresses.Count);
var endPointAddress = $"https://127.0.0.1:{port}"; var endPointAddress = $"https://127.0.0.1:{port}";
Assert.Equal(serverAddresses.First(), endPointAddress); Assert.Equal(serverAddresses.First(), endPointAddress);
@ -644,8 +695,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
[Fact] [Fact]
public async Task DoesNotOverrideDirectConfigurationWithIServerAddressesFeature_IfAddressesEmpty() public async Task DoesNotOverrideDirectConfigurationWithIServerAddressesFeature_IfAddressesEmpty()
{ {
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions =>
@ -655,6 +708,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
}) })
.PreferHostingUrls(true) .PreferHostingUrls(true)
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -663,7 +718,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var port = host.GetPort(); var port = host.GetPort();
// If this isn't working properly, we'll not get the HTTPS endpoint defined in UseKestrel. // If this isn't working properly, we'll not get the HTTPS endpoint defined in UseKestrel.
var serverAddresses = host.ServerFeatures.Get<IServerAddressesFeature>().Addresses; var serverAddresses = host.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>().Addresses;
Assert.Equal(1, serverAddresses.Count); Assert.Equal(1, serverAddresses.Count);
var endPointAddress = $"https://127.0.0.1:{port}"; var endPointAddress = $"https://127.0.0.1:{port}";
Assert.Equal(serverAddresses.First(), endPointAddress); Assert.Equal(serverAddresses.First(), endPointAddress);
@ -688,38 +743,50 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
[Fact] [Fact]
public void ThrowsWhenBindingLocalhostToDynamicPort() public async Task ThrowsWhenBindingLocalhostToDynamicPort()
{ {
TestApplicationErrorLogger.IgnoredExceptions.Add(typeof(InvalidOperationException)); TestApplicationErrorLogger.IgnoredExceptions.Add(typeof(InvalidOperationException));
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel() .UseKestrel()
.UseUrls("http://localhost:0") .UseUrls("http://localhost:0")
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
Assert.Throws<InvalidOperationException>(() => host.Start()); Assert.Throws<InvalidOperationException>(() => host.Start());
await host.StopAsync();
} }
} }
[Theory] [Theory]
[InlineData("ftp://localhost")] [InlineData("ftp://localhost")]
[InlineData("ssh://localhost")] [InlineData("ssh://localhost")]
public void ThrowsForUnsupportedAddressFromHosting(string address) public async Task ThrowsForUnsupportedAddressFromHosting(string address)
{ {
TestApplicationErrorLogger.IgnoredExceptions.Add(typeof(InvalidOperationException)); TestApplicationErrorLogger.IgnoredExceptions.Add(typeof(InvalidOperationException));
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel() .UseKestrel()
.UseUrls(address) .UseUrls(address)
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
Assert.Throws<InvalidOperationException>(() => host.Start()); Assert.Throws<InvalidOperationException>(() => host.Start());
await host.StopAsync();
} }
} }
@ -729,13 +796,17 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var port = GetNextPort(); var port = GetNextPort();
var endPointAddress = $"http://127.0.0.1:{port}/"; var endPointAddress = $"http://127.0.0.1:{port}/";
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(IPAddress.Loopback, port); options.Listen(IPAddress.Loopback, port);
}) })
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -746,12 +817,16 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
await host.StopAsync(); await host.StopAsync();
} }
hostBuilder = TransportSelector.GetWebHostBuilder() hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(IPAddress.Loopback, port); options.Listen(IPAddress.Loopback, port);
}) })
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
});
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -771,14 +846,18 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var ipv4endPointAddress = $"http://127.0.0.1:{port}/"; var ipv4endPointAddress = $"http://127.0.0.1:{port}/";
var ipv6endPointAddress = $"http://[::1]:{port}/"; var ipv6endPointAddress = $"http://[::1]:{port}/";
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(IPAddress.Loopback, port); options.Listen(IPAddress.Loopback, port);
options.Listen(IPAddress.IPv6Loopback, port); options.Listen(IPAddress.IPv6Loopback, port);
}) })
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -790,13 +869,17 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
await host.StopAsync(); await host.StopAsync();
} }
hostBuilder = TransportSelector.GetWebHostBuilder() hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(IPAddress.Loopback, port); options.Listen(IPAddress.Loopback, port);
options.Listen(IPAddress.IPv6Loopback, port); options.Listen(IPAddress.IPv6Loopback, port);
}) })
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
});
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -816,7 +899,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
public async Task EndpointDefaultsConfig_CanSetProtocolForUrlsConfig(string input, HttpProtocols expected) public async Task EndpointDefaultsConfig_CanSetProtocolForUrlsConfig(string input, HttpProtocols expected)
{ {
KestrelServerOptions capturedOptions = null; KestrelServerOptions capturedOptions = null;
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
var config = new ConfigurationBuilder().AddInMemoryCollection(new[] var config = new ConfigurationBuilder().AddInMemoryCollection(new[]
@ -827,9 +913,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
capturedOptions = options; capturedOptions = options;
}) })
.ConfigureServices(AddTestLogging)
.UseUrls("http://127.0.0.1:0") .UseUrls("http://127.0.0.1:0")
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -875,11 +962,15 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
continue; continue;
} }
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel() .UseKestrel()
.UseUrls($"http://localhost:{port}") .UseUrls($"http://localhost:{port}")
.Configure(ConfigureEchoAddress); .Configure(ConfigureEchoAddress);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {

View File

@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var serviceContext = new TestServiceContext(LoggerFactory); 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()) using (var connection = server.CreateConnection())
{ {
@ -41,7 +41,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
}); });
} }
await server.StopAsync();
} }
} }
} }

View File

@ -83,7 +83,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests.Http2
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10)] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10)]
public async Task TlsAlpnHandshakeSelectsHttp2From1and2() public async Task TlsAlpnHandshakeSelectsHttp2From1and2()
{ {
using (var server = new TestServer(context => await using (var server = new TestServer(context =>
{ {
var tlsFeature = context.Features.Get<ITlsApplicationProtocolFeature>(); var tlsFeature = context.Features.Get<ITlsApplicationProtocolFeature>();
Assert.NotNull(tlsFeature); Assert.NotNull(tlsFeature);
@ -103,8 +103,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests.Http2
{ {
var result = await Client.GetStringAsync($"https://localhost:{server.Port}/"); var result = await Client.GetStringAsync($"https://localhost:{server.Port}/");
Assert.Equal("hello world HTTP/2", result); Assert.Equal("hello world HTTP/2", result);
await server.StopAsync();
} }
} }
@ -113,7 +111,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests.Http2
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10)] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10)]
public async Task TlsAlpnHandshakeSelectsHttp2() public async Task TlsAlpnHandshakeSelectsHttp2()
{ {
using (var server = new TestServer(context => await using (var server = new TestServer(context =>
{ {
var tlsFeature = context.Features.Get<ITlsApplicationProtocolFeature>(); var tlsFeature = context.Features.Get<ITlsApplicationProtocolFeature>();
Assert.NotNull(tlsFeature); Assert.NotNull(tlsFeature);
@ -133,7 +131,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests.Http2
{ {
var result = await Client.GetStringAsync($"https://localhost:{server.Port}/"); var result = await Client.GetStringAsync($"https://localhost:{server.Port}/");
Assert.Equal("hello world HTTP/2", result); Assert.Equal("hello world HTTP/2", result);
await server.StopAsync();
} }
} }
} }

View File

@ -61,7 +61,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests.Http2
testContext.InitializeHeartbeat(); testContext.InitializeHeartbeat();
using (var server = new TestServer(async context => await using (var server = new TestServer(async context =>
{ {
requestStarted.SetResult(); requestStarted.SetResult();
await requestUnblocked.Task.DefaultTimeout(); await requestUnblocked.Task.DefaultTimeout();
@ -115,7 +115,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests.Http2
TestApplicationErrorLogger.ThrowOnUngracefulShutdown = false; TestApplicationErrorLogger.ThrowOnUngracefulShutdown = false;
// Abortive shutdown leaves one request hanging // Abortive shutdown leaves one request hanging
using (var server = new TestServer(async context => await using (var server = new TestServer(async context =>
{ {
requestStarted.SetResult(); requestStarted.SetResult();
await requestUnblocked.Task.DefaultTimeout(); await requestUnblocked.Task.DefaultTimeout();
@ -145,8 +145,16 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests.Http2
await closingMessageTask; await closingMessageTask;
cts.Cancel(); cts.Cancel();
try
{
await stopServerTask; await stopServerTask;
} }
// Remove when https://github.com/dotnet/runtime/issues/40290 is fixed
catch (OperationCanceledException)
{
}
}
Assert.Contains(TestApplicationErrorLogger.Messages, m => m.Message.Contains("is closing.")); Assert.Contains(TestApplicationErrorLogger.Messages, m => m.Message.Contains("is closing."));
Assert.Contains(TestApplicationErrorLogger.Messages, m => m.Message.Contains("is closed. The last processed stream ID was 1.")); Assert.Contains(TestApplicationErrorLogger.Messages, m => m.Message.Contains("is closed. The last processed stream ID was 1."));

View File

@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{ {
_canListenToOpenTcpSocketHandleSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); _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))) new ListenOptions((ulong)_canListenToOpenTcpSocketHandleSocket.Handle)))
{ {
using (var connection = new TestConnection(((IPEndPoint)_canListenToOpenTcpSocketHandleSocket.LocalEndPoint).Port)) using (var connection = new TestConnection(((IPEndPoint)_canListenToOpenTcpSocketHandleSocket.LocalEndPoint).Port))
@ -42,7 +42,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
"", "",
""); "");
} }
await server.StopAsync();
} }
} }
} }

View File

@ -14,7 +14,8 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
@ -124,7 +125,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var memoryPoolFactory = new DiagnosticMemoryPoolFactory(allowLateReturn: true); 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(); var port = host.GetPort();
using (var socket = CreateSocket(port)) using (var socket = CreateSocket(port))
@ -217,7 +218,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var memoryPoolFactory = new DiagnosticMemoryPoolFactory(allowLateReturn: true); 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(); var port = host.GetPort();
using (var socket = CreateSocket(port)) using (var socket = CreateSocket(port))
@ -271,7 +272,15 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
// Dispose host prior to closing connection to verify the server doesn't throw during shutdown // 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. // if a connection no longer has alloc and read callbacks configured.
try
{
await host.StopAsync(); await host.StopAsync();
}
// Remove when https://github.com/dotnet/runtime/issues/40290 is fixed
catch (OperationCanceledException)
{
}
host.Dispose(); host.Dispose();
} }
} }
@ -281,15 +290,17 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
await memoryPoolFactory.WhenAllBlocksReturned(TestConstants.DefaultTimeout); await memoryPoolFactory.WhenAllBlocksReturned(TestConstants.DefaultTimeout);
} }
private async Task<IWebHost> StartWebHost(long? maxRequestBufferSize, private async Task<IHost> StartHost(long? maxRequestBufferSize,
byte[] expectedBody, byte[] expectedBody,
bool useConnectionAdapter, bool useConnectionAdapter,
TaskCompletionSource startReadingRequestBody, TaskCompletionSource startReadingRequestBody,
TaskCompletionSource clientFinishedSendingRequestBody, TaskCompletionSource clientFinishedSendingRequestBody,
Func<MemoryPool<byte>> memoryPoolFactory = null) Func<MemoryPool<byte>> memoryPoolFactory = null)
{ {
var host = TransportSelector.GetWebHostBuilder(memoryPoolFactory, maxRequestBufferSize) var host = TransportSelector.GetHostBuilder(memoryPoolFactory, maxRequestBufferSize)
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions =>
@ -341,7 +352,9 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
await context.Response.WriteAsync($"bytesRead: {bytesRead.ToString()}"); await context.Response.WriteAsync($"bytesRead: {bytesRead.ToString()}");
})) }));
})
.ConfigureServices(AddTestLogging)
.Build(); .Build();
await host.StartAsync(); await host.StartAsync();

View File

@ -23,6 +23,7 @@ using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.Hosting;
using Moq; using Moq;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@ -55,8 +56,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
Assert.True(contentLength % bufferLength == 0, $"{nameof(contentLength)} sent must be evenly divisible by {bufferLength}."); 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"); Assert.True(bufferLength % 256 == 0, $"{nameof(bufferLength)} must be evenly divisible by 256");
var builder = TransportSelector.GetWebHostBuilder() var builder = TransportSelector.GetHostBuilder()
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Limits.MaxRequestBodySize = contentLength; options.Limits.MaxRequestBodySize = contentLength;
@ -88,6 +91,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
await context.Response.WriteAsync($"bytesRead: {total.ToString()}"); await context.Response.WriteAsync($"bytesRead: {total.ToString()}");
}); });
}); });
})
.ConfigureServices(AddTestLogging);
using (var host = builder.Build()) using (var host = builder.Build())
{ {
@ -140,10 +145,12 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
[Fact] [Fact]
public async Task DoesNotHangOnConnectionCloseRequest() public async Task DoesNotHangOnConnectionCloseRequest()
{ {
var builder = TransportSelector.GetWebHostBuilder() var builder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel() .UseKestrel()
.UseUrls("http://127.0.0.1:0") .UseUrls("http://127.0.0.1:0")
.ConfigureServices(AddTestLogging)
.Configure(app => .Configure(app =>
{ {
app.Run(async context => app.Run(async context =>
@ -151,6 +158,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
await context.Response.WriteAsync("hello, world"); await context.Response.WriteAsync("hello, world");
}); });
}); });
})
.ConfigureServices(AddTestLogging);
using (var host = builder.Build()) using (var host = builder.Build())
using (var client = new HttpClient()) using (var client = new HttpClient())
@ -173,7 +182,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var requestNumber = 0; var requestNumber = 0;
var ensureConcurrentRequestTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); 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) if (Interlocked.Increment(ref requestNumber) == 1)
{ {
@ -210,7 +219,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
"", "",
""); "");
} }
await server.StopAsync();
} }
} }
@ -245,7 +253,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
}; };
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()) using (var connection = server.CreateConnection())
{ {
@ -260,8 +268,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
// is still in flight when the connection is aborted, leading to the reset never being received // is still in flight when the connection is aborted, leading to the reset never being received
// and therefore not logged. // and therefore not logged.
Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout)); Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout));
await server.StopAsync();
} }
Assert.False(loggedHigherThanDebug); Assert.False(loggedHigherThanDebug);
@ -293,7 +299,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
}; };
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()) using (var connection = server.CreateConnection())
{ {
@ -321,7 +327,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
// is still in flight when the connection is aborted, leading to the reset never being received // is still in flight when the connection is aborted, leading to the reset never being received
// and therefore not logged. // and therefore not logged.
Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout)); Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout));
await server.StopAsync();
} }
Assert.False(loggedHigherThanDebug); Assert.False(loggedHigherThanDebug);
@ -355,7 +360,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
}; };
using (var server = new TestServer(async context => await using (var server = new TestServer(async context =>
{ {
requestStarted.Release(); requestStarted.Release();
await connectionClosing.WaitAsync(); await connectionClosing.WaitAsync();
@ -378,7 +383,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
// and therefore not logged. // and therefore not logged.
Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout), "Connection reset event should have been logged"); Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout), "Connection reset event should have been logged");
connectionClosing.Release(); connectionClosing.Release();
await server.StopAsync();
} }
Assert.False(loggedHigherThanDebug, "Logged event should not have been higher than debug."); Assert.False(loggedHigherThanDebug, "Logged event should not have been higher than debug.");
@ -392,8 +396,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var appDone = new SemaphoreSlim(0); var appDone = new SemaphoreSlim(0);
var expectedExceptionThrown = false; var expectedExceptionThrown = false;
var builder = TransportSelector.GetWebHostBuilder() var builder = TransportSelector.GetHostBuilder()
.ConfigureServices(AddTestLogging) .ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel() .UseKestrel()
.UseUrls("http://127.0.0.1:0") .UseUrls("http://127.0.0.1:0")
.Configure(app => app.Run(async context => .Configure(app => app.Run(async context =>
@ -412,6 +418,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
appDone.Release(); appDone.Release();
})); }));
})
.ConfigureServices(AddTestLogging);
using (var host = builder.Build()) using (var host = builder.Build())
{ {
@ -439,10 +447,12 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{ {
var appStarted = new SemaphoreSlim(0); var appStarted = new SemaphoreSlim(0);
var requestAborted = new SemaphoreSlim(0); var requestAborted = new SemaphoreSlim(0);
var builder = TransportSelector.GetWebHostBuilder() var builder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel() .UseKestrel()
.UseUrls("http://127.0.0.1:0") .UseUrls("http://127.0.0.1:0")
.ConfigureServices(AddTestLogging)
.Configure(app => app.Run(async context => .Configure(app => app.Run(async context =>
{ {
appStarted.Release(); appStarted.Release();
@ -451,6 +461,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
token.Register(() => requestAborted.Release(2)); token.Register(() => requestAborted.Release(2));
await requestAborted.WaitAsync().DefaultTimeout(); await requestAborted.WaitAsync().DefaultTimeout();
})); }));
})
.ConfigureServices(AddTestLogging);
using (var host = builder.Build()) using (var host = builder.Build())
{ {
@ -472,15 +484,19 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
[Fact] [Fact]
public async Task AbortingTheConnectionSendsFIN() public async Task AbortingTheConnectionSendsFIN()
{ {
var builder = TransportSelector.GetWebHostBuilder() var builder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel() .UseKestrel()
.UseUrls("http://127.0.0.1:0") .UseUrls("http://127.0.0.1:0")
.ConfigureServices(AddTestLogging)
.Configure(app => app.Run(context => .Configure(app => app.Run(context =>
{ {
context.Abort(); context.Abort();
return Task.CompletedTask; return Task.CompletedTask;
})); }));
})
.ConfigureServices(AddTestLogging);
using (var host = builder.Build()) using (var host = builder.Build())
{ {
@ -507,7 +523,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var appStartedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var appStartedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var connectionClosedTcs = 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(); appStartedTcs.SetResult();
@ -531,7 +547,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
await connectionClosedTcs.Task.DefaultTimeout(); await connectionClosedTcs.Task.DefaultTimeout();
} }
await server.StopAsync();
} }
} }
@ -542,7 +557,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var testContext = new TestServiceContext(LoggerFactory); var testContext = new TestServiceContext(LoggerFactory);
var connectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var connectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using (var server = new TestServer(context => await using (var server = new TestServer(context =>
{ {
var connectionLifetimeFeature = context.Features.Get<IConnectionLifetimeFeature>(); var connectionLifetimeFeature = context.Features.Get<IConnectionLifetimeFeature>();
connectionLifetimeFeature.ConnectionClosed.Register(() => connectionClosedTcs.SetResult()); connectionLifetimeFeature.ConnectionClosed.Register(() => connectionClosedTcs.SetResult());
@ -568,7 +583,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
"", "",
""); "");
} }
await server.StopAsync();
} }
} }
@ -579,7 +593,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var testContext = new TestServiceContext(LoggerFactory); var testContext = new TestServiceContext(LoggerFactory);
var connectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var connectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using (var server = new TestServer(context => await using (var server = new TestServer(context =>
{ {
var connectionLifetimeFeature = context.Features.Get<IConnectionLifetimeFeature>(); var connectionLifetimeFeature = context.Features.Get<IConnectionLifetimeFeature>();
connectionLifetimeFeature.ConnectionClosed.Register(() => connectionClosedTcs.SetResult()); connectionLifetimeFeature.ConnectionClosed.Register(() => connectionClosedTcs.SetResult());
@ -610,7 +624,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
// isn't guaranteed but not unexpected. // isn't guaranteed but not unexpected.
} }
} }
await server.StopAsync();
} }
} }
@ -627,7 +640,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var registrationTcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); var registrationTcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
var requestId = 0; var requestId = 0;
using (var server = new TestServer(async httpContext => await using (var server = new TestServer(async httpContext =>
{ {
requestId++; requestId++;
@ -692,7 +705,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
""); "");
await connection.WaitForConnectionClose(); await connection.WaitForConnectionClose();
} }
await server.StopAsync();
} }
await Assert.ThrowsAsync<TaskCanceledException>(async () => await readTcs.Task); await Assert.ThrowsAsync<TaskCanceledException>(async () => await readTcs.Task);
@ -752,7 +764,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var scratchBuffer = new byte[maxRequestBufferSize * 8]; var scratchBuffer = new byte[maxRequestBufferSize * 8];
using (var server = new TestServer(async context => await using (var server = new TestServer(async context =>
{ {
await clientClosedConnection.Task; await clientClosedConnection.Task;
@ -781,7 +793,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
clientClosedConnection.SetResult(); clientClosedConnection.SetResult();
await appFuncCompleted.Task.DefaultTimeout(); await appFuncCompleted.Task.DefaultTimeout();
await server.StopAsync();
} }
mockKestrelTrace.Verify(t => t.ConnectionStop(It.IsAny<string>()), Times.Once()); mockKestrelTrace.Verify(t => t.ConnectionStop(It.IsAny<string>()), Times.Once());
@ -799,7 +810,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var scratchBuffer = new byte[4096]; var scratchBuffer = new byte[4096];
using (var server = new TestServer(async context => await using (var server = new TestServer(async context =>
{ {
appStartedTcs.SetResult(); appStartedTcs.SetResult();
@ -834,7 +845,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
await Assert.ThrowsAnyAsync<IOException>(() => readTcs.Task).DefaultTimeout(); await Assert.ThrowsAnyAsync<IOException>(() => readTcs.Task).DefaultTimeout();
await server.StopAsync();
} }
mockKestrelTrace.Verify(t => t.ConnectionStop(It.IsAny<string>()), Times.Once()); mockKestrelTrace.Verify(t => t.ConnectionStop(It.IsAny<string>()), Times.Once());
@ -842,10 +852,12 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
private async Task TestRemoteIPAddress(string registerAddress, string requestAddress, string expectAddress) private async Task TestRemoteIPAddress(string registerAddress, string requestAddress, string expectAddress)
{ {
var builder = TransportSelector.GetWebHostBuilder() var builder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel() .UseKestrel()
.UseUrls($"http://{registerAddress}:0") .UseUrls($"http://{registerAddress}:0")
.ConfigureServices(AddTestLogging)
.Configure(app => .Configure(app =>
{ {
app.Run(async context => app.Run(async context =>
@ -860,6 +872,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
})); }));
}); });
}); });
})
.ConfigureServices(AddTestLogging);
using (var host = builder.Build()) using (var host = builder.Build())
using (var client = new HttpClient()) using (var client = new HttpClient())

View File

@ -23,6 +23,7 @@ using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.AspNetCore.Server.Kestrel.Https.Internal; using Microsoft.AspNetCore.Server.Kestrel.Https.Internal;
using Microsoft.AspNetCore.Server.Kestrel.Tests; using Microsoft.AspNetCore.Server.Kestrel.Tests;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.Primitives; using Microsoft.Extensions.Primitives;
@ -42,10 +43,12 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
[Fact] [Fact]
public async Task LargeDownload() public async Task LargeDownload()
{ {
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel() .UseKestrel()
.UseUrls("http://127.0.0.1:0/") .UseUrls("http://127.0.0.1:0/")
.ConfigureServices(AddTestLogging)
.Configure(app => .Configure(app =>
{ {
app.Run(async context => app.Run(async context =>
@ -64,6 +67,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
}); });
}); });
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -96,10 +101,12 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
[Theory, MemberData(nameof(NullHeaderData))] [Theory, MemberData(nameof(NullHeaderData))]
public async Task IgnoreNullHeaderValues(string headerName, StringValues headerValue, string expectedValue) public async Task IgnoreNullHeaderValues(string headerName, StringValues headerValue, string expectedValue)
{ {
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel() .UseKestrel()
.UseUrls("http://127.0.0.1:0/") .UseUrls("http://127.0.0.1:0/")
.ConfigureServices(AddTestLogging)
.Configure(app => .Configure(app =>
{ {
app.Run(async context => app.Run(async context =>
@ -109,6 +116,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
await context.Response.WriteAsync(""); await context.Response.WriteAsync("");
}); });
}); });
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -143,7 +152,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var requestStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var requestStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var appCompleted = 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 try
{ {
@ -175,7 +184,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
connectionClosed.SetResult(); connectionClosed.SetResult();
await appCompleted.Task.DefaultTimeout(); await appCompleted.Task.DefaultTimeout();
await server.StopAsync();
} }
} }
@ -193,7 +201,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var requestAbortedWh = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var requestAbortedWh = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var requestStartWh = 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(); requestStartWh.SetResult();
@ -239,7 +247,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
// RequestAborted tripped // RequestAborted tripped
await requestAbortedWh.Task.DefaultTimeout(); await requestAbortedWh.Task.DefaultTimeout();
await server.StopAsync();
} }
} }
@ -286,7 +293,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var scratchBuffer = new byte[maxRequestBufferSize * 8]; 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()); context.RequestAborted.Register(() => requestAborted.SetResult());
@ -331,7 +338,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
clientClosedConnection.SetResult(); clientClosedConnection.SetResult();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => writeTcs.Task).DefaultTimeout(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => writeTcs.Task).DefaultTimeout();
await server.StopAsync();
} }
mockKestrelTrace.Verify(t => t.ConnectionStop(It.IsAny<string>()), Times.Once()); mockKestrelTrace.Verify(t => t.ConnectionStop(It.IsAny<string>()), Times.Once());
@ -354,7 +360,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var scratchBuffer = new byte[responseBodySegmentSize]; 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()); context.RequestAborted.Register(() => requestAborted.SetResult());
@ -398,7 +404,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
// On macOS, the default 5 shutdown timeout is insufficient for the write loop to complete, so give it extra time. // 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 appCompletedTcs.Task.DefaultTimeout();
await server.StopAsync();
} }
var coreLogs = TestSink.Writes.Where(w => w.LoggerName == "Microsoft.AspNetCore.Server.Kestrel"); var coreLogs = TestSink.Writes.Where(w => w.LoggerName == "Microsoft.AspNetCore.Server.Kestrel");
@ -421,7 +426,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
// There's not guarantee that the app even gets invoked in this test. The connection reset can be observed // There's not guarantee that the app even gets invoked in this test. The connection reset can be observed
// as early as accept. // as early as accept.
var testServiceContext = new TestServiceContext(LoggerFactory); 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++) for (var i = 0; i < numConnections; i++)
{ {
@ -436,7 +441,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
connection.Reset(); connection.Reset();
} }
} }
await server.StopAsync();
} }
var transportLogs = TestSink.Writes.Where(w => w.LoggerName == "Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv" || var transportLogs = TestSink.Writes.Where(w => w.LoggerName == "Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv" ||
@ -521,7 +525,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
} }
using (var server = new TestServer(App, testContext)) await using (var server = new TestServer(App, testContext))
{ {
using (var connection = server.CreateConnection()) using (var connection = server.CreateConnection())
{ {
@ -546,7 +550,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
sw.Stop(); sw.Stop();
logger.LogInformation("Connection was aborted after {totalMilliseconds}ms.", sw.ElapsedMilliseconds); logger.LogInformation("Connection was aborted after {totalMilliseconds}ms.", sw.ElapsedMilliseconds);
} }
await server.StopAsync();
} }
} }
@ -590,7 +593,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = certificate }); listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = certificate });
} }
using (var server = new TestServer(async context => await using (var server = new TestServer(async context =>
{ {
context.RequestAborted.Register(() => context.RequestAborted.Register(() =>
{ {
@ -634,7 +637,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
await AssertStreamAborted(connection.Stream, chunkSize * chunks); await AssertStreamAborted(connection.Stream, chunkSize * chunks);
} }
} }
await server.StopAsync();
} }
} }
@ -699,7 +701,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
copyToAsyncCts.SetException(new Exception("This shouldn't be reached.")); 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()) using (var connection = server.CreateConnection())
{ {
@ -728,7 +730,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => copyToAsyncCts.Task).DefaultTimeout(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => copyToAsyncCts.Task).DefaultTimeout();
await AssertStreamAborted(connection.Stream, responseSize); await AssertStreamAborted(connection.Stream, responseSize);
} }
await server.StopAsync();
} }
} }
@ -776,7 +777,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
appFuncCompleted.SetResult(); appFuncCompleted.SetResult();
} }
using (var server = new TestServer(App, testContext, listenOptions)) await using (var server = new TestServer(App, testContext, listenOptions))
{ {
using (var connection = server.CreateConnection()) using (var connection = server.CreateConnection())
{ {
@ -802,7 +803,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
connection.ShutdownSend(); connection.ShutdownSend();
await connection.WaitForConnectionClose(); await connection.WaitForConnectionClose();
} }
await server.StopAsync();
} }
mockKestrelTrace.Verify(t => t.ResponseMinimumDataRateNotSatisfied(It.IsAny<string>(), It.IsAny<string>()), Times.Never()); mockKestrelTrace.Verify(t => t.ResponseMinimumDataRateNotSatisfied(It.IsAny<string>(), It.IsAny<string>()), Times.Never());
@ -854,7 +854,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
await context.Response.BodyWriter.FlushAsync(); 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()) using (var connection = server.CreateConnection())
{ {
@ -889,8 +889,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
connection.ShutdownSend(); connection.ShutdownSend();
await connection.WaitForConnectionClose(); await connection.WaitForConnectionClose();
} }
await server.StopAsync();
} }
mockKestrelTrace.Verify(t => t.ResponseMinimumDataRateNotSatisfied(It.IsAny<string>(), It.IsAny<string>()), Times.Never()); mockKestrelTrace.Verify(t => t.ResponseMinimumDataRateNotSatisfied(It.IsAny<string>(), It.IsAny<string>()), Times.Never());
@ -942,7 +940,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
appFuncCompleted.SetResult(); appFuncCompleted.SetResult();
} }
using (var server = new TestServer(App, testContext, listenOptions)) await using (var server = new TestServer(App, testContext, listenOptions))
{ {
using (var connection = server.CreateConnection()) using (var connection = server.CreateConnection())
{ {
@ -967,7 +965,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
await AssertStreamCompletedAtTargetRate(connection.Stream, expectedBytes: 33_553_556, targetBytesPerSecond); await AssertStreamCompletedAtTargetRate(connection.Stream, expectedBytes: 33_553_556, targetBytesPerSecond);
await appFuncCompleted.Task.DefaultTimeout(); await appFuncCompleted.Task.DefaultTimeout();
} }
await server.StopAsync();
} }
mockKestrelTrace.Verify(t => t.ResponseMinimumDataRateNotSatisfied(It.IsAny<string>(), It.IsAny<string>()), Times.Never()); mockKestrelTrace.Verify(t => t.ResponseMinimumDataRateNotSatisfied(It.IsAny<string>(), It.IsAny<string>()), Times.Never());

View File

@ -15,6 +15,7 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
@ -72,7 +73,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
} }
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(o => .UseKestrel(o =>
{ {
o.ListenUnixSocket(path, builder => o.ListenUnixSocket(path, builder =>
@ -80,8 +84,9 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
builder.Run(EchoServer); builder.Run(EchoServer);
}); });
}) })
.ConfigureServices(AddTestLogging)
.Configure(c => { }); .Configure(c => { });
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -100,7 +105,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{ {
var bytesReceived = await socket.ReceiveAsync(buffer.AsMemory(read, buffer.Length - read), SocketFlags.None).DefaultTimeout(); var bytesReceived = await socket.ReceiveAsync(buffer.AsMemory(read, buffer.Length - read), SocketFlags.None).DefaultTimeout();
read += bytesReceived; read += bytesReceived;
if (bytesReceived <= 0) break; if (bytesReceived <= 0)
{
break;
}
} }
Assert.Equal(data, buffer); Assert.Equal(data, buffer);
@ -134,10 +142,12 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
try try
{ {
var hostBuilder = TransportSelector.GetWebHostBuilder() var hostBuilder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseUrls(url) .UseUrls(url)
.UseKestrel() .UseKestrel()
.ConfigureServices(AddTestLogging)
.Configure(app => .Configure(app =>
{ {
app.Run(async context => app.Run(async context =>
@ -145,6 +155,8 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
await context.Response.WriteAsync("Hello World"); await context.Response.WriteAsync("Hello World");
}); });
}); });
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {
@ -165,7 +177,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{ {
var bytesReceived = await socket.ReceiveAsync(readBuffer.AsMemory(read), SocketFlags.None).DefaultTimeout(); var bytesReceived = await socket.ReceiveAsync(readBuffer.AsMemory(read), SocketFlags.None).DefaultTimeout();
read += bytesReceived; read += bytesReceived;
if (bytesReceived <= 0) break; if (bytesReceived <= 0)
{
break;
}
} }
var httpResponse = Encoding.ASCII.GetString(readBuffer, 0, read); var httpResponse = Encoding.ASCII.GetString(readBuffer, 0, read);

View File

@ -169,7 +169,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests
} }
} }
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); Assert.Contains(TestSink.Writes, w => w.EventId.Id == 17);
} }

View File

@ -9,12 +9,10 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
using BadHttpRequestException = Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException; using BadHttpRequestException = Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException;
@ -686,7 +684,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests
"", "",
""); "");
} }
await server.StopAsync();
} }
} }
@ -993,7 +990,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests
"", "",
"Hello World"); "Hello World");
} }
await server.StopAsync();
} }
} }
@ -1065,7 +1061,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests
{ {
var testContext = new TestServiceContext(LoggerFactory); 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 response = httpContext.Response;
var request = httpContext.Request; var request = httpContext.Request;

View File

@ -4,7 +4,6 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests

View File

@ -10,7 +10,6 @@ using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests

View File

@ -33,7 +33,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.Http2
[SkipOnHelix("Ubuntu 20.04 disables TLS1.1 by default which SslStream requires in this scenario", Queues = "Ubuntu.2004.Amd64.Open")] [SkipOnHelix("Ubuntu 20.04 disables TLS1.1 by default which SslStream requires in this scenario", Queues = "Ubuntu.2004.Amd64.Open")]
public async Task TlsHandshakeRejectsTlsLessThan12() public async Task TlsHandshakeRejectsTlsLessThan12()
{ {
using (var server = new TestServer(context => await using (var server = new TestServer(context =>
{ {
var tlsFeature = context.Features.Get<ITlsApplicationProtocolFeature>(); var tlsFeature = context.Features.Get<ITlsApplicationProtocolFeature>();
Assert.NotNull(tlsFeature); Assert.NotNull(tlsFeature);
@ -66,7 +66,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.Http2
await WaitForConnectionErrorAsync(reader, ignoreNonGoAwayFrames: false, expectedLastStreamId: 0, expectedErrorCode: Http2ErrorCode.INADEQUATE_SECURITY); await WaitForConnectionErrorAsync(reader, ignoreNonGoAwayFrames: false, expectedLastStreamId: 0, expectedErrorCode: Http2ErrorCode.INADEQUATE_SECURITY);
reader.Complete(); reader.Complete();
} }
await server.StopAsync();
} }
} }

View File

@ -11,7 +11,6 @@ using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests

View File

@ -10,7 +10,6 @@ using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
using BadHttpRequestException = Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException; using BadHttpRequestException = Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException;

View File

@ -11,7 +11,6 @@ using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests

View File

@ -7,7 +7,6 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests

View File

@ -8,7 +8,6 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests

View File

@ -8,7 +8,6 @@ using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests

View File

@ -18,8 +18,6 @@ using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Serilog;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests

View File

@ -3410,8 +3410,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests
"", "",
"Hello World!"); "Hello World!");
} }
await server.StopAsync();
} }
} }

View File

@ -16,6 +16,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport
@ -23,12 +24,12 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTrans
/// <summary> /// <summary>
/// In-memory TestServer /// In-memory TestServer
/// </summary /// </summary
internal class TestServer : IAsyncDisposable, IDisposable, IStartup internal class TestServer : IAsyncDisposable, IStartup
{ {
private readonly MemoryPool<byte> _memoryPool; private readonly MemoryPool<byte> _memoryPool;
private readonly RequestDelegate _app; private readonly RequestDelegate _app;
private readonly InMemoryTransportFactory _transportFactory; private readonly InMemoryTransportFactory _transportFactory;
private readonly IWebHost _host; private readonly IHost _host;
public TestServer(RequestDelegate app) public TestServer(RequestDelegate app)
: this(app, new TestServiceContext()) : this(app, new TestServiceContext())
@ -69,8 +70,13 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTrans
_transportFactory = new InMemoryTransportFactory(); _transportFactory = new InMemoryTransportFactory();
HttpClientSlim = new InMemoryHttpClientSlim(this); HttpClientSlim = new InMemoryHttpClientSlim(this);
var hostBuilder = new WebHostBuilder() var hostBuilder = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseSetting(WebHostDefaults.ShutdownTimeoutKey, TestConstants.DefaultTimeout.TotalSeconds.ToString()) .UseSetting(WebHostDefaults.ShutdownTimeoutKey, TestConstants.DefaultTimeout.TotalSeconds.ToString())
.Configure(app => { app.Run(_app); });
})
.ConfigureServices(services => .ConfigureServices(services =>
{ {
configureServices(services); configureServices(services);
@ -108,11 +114,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTrans
return _host.StopAsync(cancellationToken); return _host.StopAsync(cancellationToken);
} }
public void Dispose()
{
_host.Dispose();
_memoryPool.Dispose();
}
void IStartup.Configure(IApplicationBuilder app) void IStartup.Configure(IApplicationBuilder app)
{ {
@ -126,8 +127,9 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTrans
public async ValueTask DisposeAsync() public async ValueTask DisposeAsync()
{ {
// The concrete WebHost implements IAsyncDisposable await _host.StopAsync().ConfigureAwait(false);
await ((IAsyncDisposable)_host).ConfigureAwait(false).DisposeAsync(); // The concrete Host implements IAsyncDisposable
await ((IAsyncDisposable)_host).DisposeAsync().ConfigureAwait(false);
_memoryPool.Dispose(); _memoryPool.Dispose();
} }
} }

View File

@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Logging.Testing;
using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Chrome;
@ -71,7 +72,10 @@ namespace Interop.FunctionalTests
{ {
InitializeArgs(); InitializeArgs();
var hostBuilder = new WebHostBuilder() var hostBuilder = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(IPAddress.Loopback, 0, listenOptions => options.Listen(IPAddress.Loopback, 0, listenOptions =>
@ -80,7 +84,6 @@ namespace Interop.FunctionalTests
listenOptions.UseHttps(TestResources.GetTestCertificate()); listenOptions.UseHttps(TestResources.GetTestCertificate());
}); });
}) })
.ConfigureServices(AddTestLogging)
.Configure(app => app.Run(async context => .Configure(app => app.Run(async context =>
{ {
if (HttpMethods.IsPost(context.Request.Query["TestMethod"])) if (HttpMethods.IsPost(context.Request.Query["TestMethod"]))
@ -92,6 +95,8 @@ namespace Interop.FunctionalTests
await context.Response.WriteAsync($"Interop {context.Request.Protocol} {context.Request.Method}"); await context.Response.WriteAsync($"Interop {context.Request.Protocol} {context.Request.Method}");
} }
})); }));
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {

View File

@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
using Xunit.Abstractions; using Xunit.Abstractions;
@ -23,7 +24,10 @@ namespace Interop.FunctionalTests
[MemberData(nameof(H2SpecTestCases))] [MemberData(nameof(H2SpecTestCases))]
public async Task RunIndividualTestCase(H2SpecTestCase testCase) public async Task RunIndividualTestCase(H2SpecTestCase testCase)
{ {
var hostBuilder = new WebHostBuilder() var hostBuilder = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options => .UseKestrel(options =>
{ {
options.Listen(IPAddress.Loopback, 0, listenOptions => options.Listen(IPAddress.Loopback, 0, listenOptions =>
@ -35,8 +39,9 @@ namespace Interop.FunctionalTests
} }
}); });
}) })
.ConfigureServices(AddTestLogging)
.Configure(ConfigureHelloWorld); .Configure(ConfigureHelloWorld);
})
.ConfigureServices(AddTestLogging);
using (var host = hostBuilder.Build()) using (var host = hostBuilder.Build())
{ {

View File

@ -4,20 +4,26 @@
using System; using System;
using System.Buffers; using System.Buffers;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{ {
public static class TransportSelector public static class TransportSelector
{ {
public static IWebHostBuilder GetWebHostBuilder(Func<MemoryPool<byte>> memoryPoolFactory = null, public static IHostBuilder GetHostBuilder(Func<MemoryPool<byte>> memoryPoolFactory = null,
long? maxReadBufferSize = null) long? maxReadBufferSize = null)
{ {
#pragma warning disable CS0618 #pragma warning disable CS0618
return new WebHostBuilder().UseLibuv(options => return new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseLibuv(options =>
{ {
options.MemoryPoolFactory = memoryPoolFactory ?? options.MemoryPoolFactory; options.MemoryPoolFactory = memoryPoolFactory ?? options.MemoryPoolFactory;
options.MaxReadBufferSize = maxReadBufferSize; options.MaxReadBufferSize = maxReadBufferSize;
}); });
});
#pragma warning restore CS0618 #pragma warning restore CS0618
} }
} }

View File

@ -4,19 +4,25 @@
using System; using System;
using System.Buffers; using System.Buffers;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{ {
public static class TransportSelector public static class TransportSelector
{ {
public static IWebHostBuilder GetWebHostBuilder(Func<MemoryPool<byte>> memoryPoolFactory = null, public static IHostBuilder GetHostBuilder(Func<MemoryPool<byte>> memoryPoolFactory = null,
long? maxReadBufferSize = null) long? maxReadBufferSize = null)
{ {
return new WebHostBuilder().UseSockets(options => return new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseSockets(options =>
{ {
options.MemoryPoolFactory = memoryPoolFactory ?? options.MemoryPoolFactory; options.MemoryPoolFactory = memoryPoolFactory ?? options.MemoryPoolFactory;
options.MaxReadBufferSize = maxReadBufferSize; options.MaxReadBufferSize = maxReadBufferSize;
}); });
});
} }
} }
} }