Do not use the default 5000 port for functional tests

This commit is contained in:
John Luo 2018-10-29 17:39:18 -07:00
parent 9949306ca3
commit 27efce1042
7 changed files with 115 additions and 137 deletions

View File

@ -4,31 +4,20 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.IntegrationTesting; using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Testing.xunit; using Microsoft.AspNetCore.Testing.xunit;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk; using Xunit.Sdk;
namespace Microsoft.AspNetCore.Tests namespace Microsoft.AspNetCore.Tests
{ {
public class WebHostFunctionalTests : LoggedTest public class WebHostFunctionalTests : LoggedTest
{ {
private readonly string _testSitesPath;
public WebHostFunctionalTests(ITestOutputHelper output) : base(output)
{
_testSitesPath = GetTestSitesPath();
}
[Fact] [Fact]
public async Task Start_RequestDelegate_Url() public async Task Start_RequestDelegate_Url()
{ {
@ -60,8 +49,6 @@ namespace Microsoft.AspNetCore.Tests
{ {
// Assert server is Kestrel // Assert server is Kestrel
Assert.Equal("Kestrel", response.Headers.Server.ToString()); Assert.Equal("Kestrel", response.Headers.Server.ToString());
// Set from default config
Assert.Equal("http://localhost:5002/", deploymentResult.ApplicationBaseUri);
// The application name will be sent in response when all asserts succeed in the test app. // The application name will be sent in response when all asserts succeed in the test app.
Assert.Equal(applicationName, responseText); Assert.Equal(applicationName, responseText);
} }
@ -87,8 +74,6 @@ namespace Microsoft.AspNetCore.Tests
{ {
// Assert server is Kestrel // Assert server is Kestrel
Assert.Equal("Kestrel", response.Headers.Server.ToString()); Assert.Equal("Kestrel", response.Headers.Server.ToString());
// Set from default config
Assert.Equal("http://localhost:5002/", deploymentResult.ApplicationBaseUri);
// The application name will be sent in response when all asserts succeed in the test app. // The application name will be sent in response when all asserts succeed in the test app.
Assert.Equal(applicationName, responseText); Assert.Equal(applicationName, responseText);
} }
@ -139,7 +124,7 @@ namespace Microsoft.AspNetCore.Tests
} }
} }
"); ");
using (var webHost = WebHost.Start(context => context.Response.WriteAsync("Hello, World!"))) using (var webHost = WebHost.Start("http://127.0.0.1:0", context => context.Response.WriteAsync("Hello, World!")))
{ {
var factory = (ILoggerFactory)webHost.Services.GetService(typeof(ILoggerFactory)); var factory = (ILoggerFactory)webHost.Services.GetService(typeof(ILoggerFactory));
var logger = factory.CreateLogger("Test"); var logger = factory.CreateLogger("Test");
@ -171,13 +156,13 @@ namespace Microsoft.AspNetCore.Tests
public async Task RunsInIISExpressInProcess() public async Task RunsInIISExpressInProcess()
{ {
var applicationName = "CreateDefaultBuilderApp"; var applicationName = "CreateDefaultBuilderApp";
var deploymentParameters = new DeploymentParameters(Path.Combine(_testSitesPath, applicationName), ServerType.IISExpress, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64) var deploymentParameters = new DeploymentParameters(Path.Combine(GetTestSitesPath(), applicationName), ServerType.IISExpress, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64)
{ {
TargetFramework = "netcoreapp2.2", TargetFramework = "netcoreapp2.2",
HostingModel = HostingModel.InProcess, HostingModel = HostingModel.InProcess,
AncmVersion = AncmVersion.AspNetCoreModuleV2 AncmVersion = AncmVersion.AspNetCoreModuleV2
}; };
SetEnvironmentVariables(deploymentParameters, "Development"); SetEnvironmentVariables(deploymentParameters, "Development");
using (var deployer = IISApplicationDeployerFactory.Create(deploymentParameters, LoggerFactory)) using (var deployer = IISApplicationDeployerFactory.Create(deploymentParameters, LoggerFactory))
@ -227,22 +212,18 @@ namespace Microsoft.AspNetCore.Tests
bool setTestEnvVars = false, bool setTestEnvVars = false,
string environment = "Development") string environment = "Development")
{ {
using (StartLog(out var loggerFactory, applicationName)) var deploymentParameters = new DeploymentParameters(Path.Combine(GetTestSitesPath(), applicationName), ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64);
if (setTestEnvVars)
{ {
var logger = loggerFactory.CreateLogger(nameof(WebHost.Start)); SetEnvironmentVariables(deploymentParameters, environment);
var deploymentParameters = new DeploymentParameters(Path.Combine(_testSitesPath, applicationName), ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64); }
if (setTestEnvVars) using (var deployer = IISApplicationDeployerFactory.Create(deploymentParameters, LoggerFactory))
{ {
SetEnvironmentVariables(deploymentParameters, environment); var deploymentResult = await deployer.DeployAsync();
}
using (var deployer = IISApplicationDeployerFactory.Create(deploymentParameters, loggerFactory)) await assertAction(deploymentResult, Logger);
{
var deploymentResult = await deployer.DeployAsync();
await assertAction(deploymentResult, logger);
}
} }
} }
@ -271,10 +252,5 @@ namespace Microsoft.AspNetCore.Tests
throw new Exception($"Solution root could not be found using {applicationBasePath}"); throw new Exception($"Solution root could not be found using {applicationBasePath}");
} }
private static int GetWebHostPort(IWebHost webHost)
=> webHost.ServerFeatures.Get<IServerAddressesFeature>().Addresses
.Select(serverAddress => new Uri(serverAddress).Port)
.FirstOrDefault();
} }
} }

View File

@ -2,7 +2,6 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.IO;
using Microsoft.AspNetCore; using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
@ -15,24 +14,29 @@ namespace CreateDefaultBuilderApp
{ {
static void Main(string[] args) static void Main(string[] args)
{ {
string responseMessage = string.Empty; string responseMessage = null;
WebHost.CreateDefaultBuilder(new[] { "--cliKey", "cliValue" }) WebHost.CreateDefaultBuilder(new[] { "--cliKey", "cliValue" })
.ConfigureServices((context, services) => .ConfigureServices((context, services) => responseMessage = responseMessage ?? GetResponseMessage(context))
{ .ConfigureKestrel(options => options
responseMessage = GetResponseMessage(context, services); .Configure(options.ConfigurationLoader.Configuration)
}) .Endpoint("HTTP", endpointOptions =>
.Configure(app =>
{
app.Run(context =>
{ {
return context.Response.WriteAsync(responseMessage); if (responseMessage == null
}); && !string.Equals("KestrelEndPointSettingValue", endpointOptions.ConfigSection["KestrelEndPointSettingName"]))
}) {
responseMessage = "Default Kestrel configuration not read.";
}
}))
.Configure(app => app.Run(context =>
{
var hostingEnvironment = app.ApplicationServices.GetRequiredService<IHostingEnvironment>();
return context.Response.WriteAsync(responseMessage ?? hostingEnvironment.ApplicationName);
}))
.Build().Run(); .Build().Run();
} }
private static string GetResponseMessage(WebHostBuilderContext context, IServiceCollection services) private static string GetResponseMessage(WebHostBuilderContext context)
{ {
// Verify ContentRootPath set // Verify ContentRootPath set
var contentRoot = Environment.GetEnvironmentVariable("ASPNETCORE_CONTENTROOT"); var contentRoot = Environment.GetEnvironmentVariable("ASPNETCORE_CONTENTROOT");
@ -71,7 +75,7 @@ namespace CreateDefaultBuilderApp
// TODO: Verify AddDebug called // TODO: Verify AddDebug called
// TODO: Verify UseIISIntegration called // TODO: Verify UseIISIntegration called
return context.HostingEnvironment.ApplicationName; return null;
} }
} }
} }

View File

@ -3,7 +3,8 @@
"Kestrel": { "Kestrel": {
"Endpoints": { "Endpoints": {
"HTTP": { "HTTP": {
"Url": "http://localhost:5002" "Url": "http://127.0.0.1:0",
"KestrelEndPointSettingName": "KestrelEndPointSettingValue"
} }
} }
} }

View File

@ -1,14 +1,92 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNetCore; using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.HostFiltering;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace CreateDefaultBuilderOfTApp namespace CreateDefaultBuilderOfTApp
{ {
public class Program public class Program
{ {
static void Main(string[] args) => WebHost.CreateDefaultBuilder<Startup>(new[] { "--cliKey", "cliValue" }) .Build().Run(); static void Main(string[] args)
{
string responseMessage = null;
WebHost.CreateDefaultBuilder(new[] { "--cliKey", "cliValue" })
.ConfigureServices((context, service) => responseMessage = responseMessage ?? GetResponseMessage(context))
.ConfigureKestrel(options => options
.Configure(options.ConfigurationLoader.Configuration)
.Endpoint("HTTP", endpointOptions =>
{
if (responseMessage == null
&& !string.Equals("KestrelEndPointSettingValue", endpointOptions.ConfigSection["KestrelEndPointSettingName"]))
{
responseMessage = "Default Kestrel configuration not read.";
}
}))
.Configure(app => app.Run(context =>
{
// Verify allowed hosts were loaded
var hostFilteringOptions = app.ApplicationServices.GetRequiredService<IOptions<HostFilteringOptions>>();
var hosts = string.Join(',', hostFilteringOptions.Value.AllowedHosts);
if (responseMessage == null && !string.Equals("example.com,127.0.0.1", hosts, StringComparison.Ordinal))
{
responseMessage = "AllowedHosts not loaded into Options.";
}
var hostingEnvironment = app.ApplicationServices.GetRequiredService<IHostingEnvironment>();
return context.Response.WriteAsync(responseMessage ?? hostingEnvironment.ApplicationName);
}))
.Build()
.Run();
}
private static string GetResponseMessage(WebHostBuilderContext context)
{
// Verify ContentRootPath set
var contentRoot = Environment.GetEnvironmentVariable("ASPNETCORE_CONTENTROOT");
if (!string.Equals(contentRoot, context.HostingEnvironment.ContentRootPath, StringComparison.Ordinal))
{
return $"ContentRootPath incorrect. Expected: {contentRoot} Actual: {context.HostingEnvironment.ContentRootPath}";
}
// Verify appsettings.json loaded
if (!string.Equals("settingsValue", context.Configuration["settingsKey"], StringComparison.Ordinal))
{
return $"appsettings.json not loaded into Configuration.";
}
// Verify appsettings.environment.json loaded
if (!string.Equals("devSettingsValue", context.Configuration["devSettingsKey"], StringComparison.Ordinal))
{
return $"appsettings.{context.HostingEnvironment.EnvironmentName}.json not loaded into Configuration.";
}
// TODO: Verify UserSecrets loaded
// Verify environment variables loaded
if (!string.Equals("envValue", context.Configuration["envKey"], StringComparison.Ordinal))
{
return $"Environment variables not loaded into Configuration.";
}
// Verify command line arguments loaded
if (!string.Equals("cliValue", context.Configuration["cliKey"], StringComparison.Ordinal))
{
return $"Command line arguments not loaded into Configuration.";
}
// TODO: Verify AddConsole called
// TODO: Verify AddDebug called
// TODO: Verify UseIISIntegration called
return null;
}
} }
} }

View File

@ -1,75 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.HostFiltering;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace CreateDefaultBuilderOfTApp
{
class Startup
{
public void Configure(IApplicationBuilder app, WebHostBuilderContext webHostBuilderContext)
{
app.Run(context =>
{
var message = GetResponseMessage(webHostBuilderContext, app.ApplicationServices.GetRequiredService<IOptions<HostFilteringOptions>>());
return context.Response.WriteAsync(message);
});
}
private static string GetResponseMessage(WebHostBuilderContext context, IOptions<HostFilteringOptions> hostFilteringOptions)
{
// Verify ContentRootPath set
var contentRoot = Environment.GetEnvironmentVariable("ASPNETCORE_CONTENTROOT");
if (!string.Equals(contentRoot, context.HostingEnvironment.ContentRootPath, StringComparison.Ordinal))
{
return $"ContentRootPath incorrect. Expected: {contentRoot} Actual: {context.HostingEnvironment.ContentRootPath}";
}
// Verify appsettings.json loaded
if (!string.Equals("settingsValue", context.Configuration["settingsKey"], StringComparison.Ordinal))
{
return $"appsettings.json not loaded into Configuration.";
}
// Verify appsettings.environment.json loaded
if (!string.Equals("devSettingsValue", context.Configuration["devSettingsKey"], StringComparison.Ordinal))
{
return $"appsettings.{context.HostingEnvironment.EnvironmentName}.json not loaded into Configuration.";
}
// TODO: Verify UserSecrets loaded
// Verify environment variables loaded
if (!string.Equals("envValue", context.Configuration["envKey"], StringComparison.Ordinal))
{
return $"Environment variables not loaded into Configuration.";
}
// Verify command line arguments loaded
if (!string.Equals("cliValue", context.Configuration["cliKey"], StringComparison.Ordinal))
{
return $"Command line arguments not loaded into Configuration.";
}
// Verify allowed hosts were loaded
var hosts = string.Join(',', hostFilteringOptions.Value.AllowedHosts);
if (!string.Equals("example.com,localhost", hosts, StringComparison.Ordinal))
{
return $"AllowedHosts not loaded into Options.";
}
// TODO: Verify AddConsole called
// TODO: Verify AddDebug called
// TODO: Verify UseIISIntegration called
return context.HostingEnvironment.ApplicationName;
}
}
}

View File

@ -1,10 +1,11 @@
{ {
"settingsKey": "settingsValue", "settingsKey": "settingsValue",
"AllowedHosts": "example.com;localhost", "AllowedHosts": "example.com;127.0.0.1",
"Kestrel": { "Kestrel": {
"Endpoints": { "Endpoints": {
"HTTP": { "HTTP": {
"Url": "http://localhost:5002" "Url": "http://127.0.0.1:0",
"KestrelEndPointSettingName": "KestrelEndPointSettingValue"
} }
} }
} }

View File

@ -2,18 +2,11 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore; using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
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.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;
namespace CreateDefaultBuilderApp namespace CreateDefaultBuilderApp
{ {
@ -22,7 +15,7 @@ namespace CreateDefaultBuilderApp
static void Main(string[] args) static void Main(string[] args)
{ {
WebHost.CreateDefaultBuilder() WebHost.CreateDefaultBuilder()
.UseUrls("http://localhost:5002") .UseUrls("http://127.0.0.1:0")
.ConfigureServices((context, services) => .ConfigureServices((context, services) =>
{ {
services.AddSingleton(typeof(IService<>), typeof(Service<>)); services.AddSingleton(typeof(IService<>), typeof(Service<>));