From 4b012bbfc7d1b0bc13804126cf9dbd3041b37cb1 Mon Sep 17 00:00:00 2001 From: sornaks Date: Fri, 22 Aug 2014 14:29:41 -0700 Subject: [PATCH 1/4] Issue #668: Sample should be covered by a basic functional test. --- global.json | 2 +- samples/MvcSample.Web/Startup.cs | 16 ++- samples/MvcSample.Web/TestAssemblyProvider.cs | 30 +++++ .../MvcSampleTests.cs | 121 ++++++++++++++++++ .../TestHelper.cs | 21 ++- .../project.json | 1 + 6 files changed, 174 insertions(+), 17 deletions(-) create mode 100644 samples/MvcSample.Web/TestAssemblyProvider.cs create mode 100644 test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs diff --git a/global.json b/global.json index b90c8282a0..897f517580 100644 --- a/global.json +++ b/global.json @@ -1,3 +1,3 @@ { - "sources": ["src", "test\\WebSites"] + "sources": ["src", "test\\WebSites", "samples"] } \ No newline at end of file diff --git a/samples/MvcSample.Web/Startup.cs b/samples/MvcSample.Web/Startup.cs index ea107cac99..e195149cf1 100644 --- a/samples/MvcSample.Web/Startup.cs +++ b/samples/MvcSample.Web/Startup.cs @@ -1,5 +1,6 @@ using System; using Microsoft.AspNet.Builder; +using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Routing; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; @@ -21,12 +22,11 @@ public void Configure(IBuilder app) app.UseFileServer(); #if ASPNET50 var configuration = new Configuration() - .AddJsonFile(@"App_Data\config.json") - .AddEnvironmentVariables(); - + .AddJsonFile(@"App_Data\config.json") + .AddEnvironmentVariables(); string diSystem; - if (configuration.TryGet("DependencyInjection", out diSystem) && + if (configuration.TryGet("DependencyInjection", out diSystem) && diSystem.Equals("AutoFac", StringComparison.OrdinalIgnoreCase)) { app.UseMiddleware(); @@ -36,8 +36,11 @@ public void Configure(IBuilder app) services.AddMvc(); services.AddSingleton(); services.AddSingleton(); - services.AddTransient(); + services.AddTransient(); services.Add(OptionsServices.GetDefaultServices()); + // Setup services with a test AssemblyProvider so that only the + // sample's assemblies are loaded + services.AddTransient>(); // Create the autofac container ContainerBuilder builder = new ContainerBuilder(); @@ -63,6 +66,9 @@ public void Configure(IBuilder app) services.AddSingleton(); services.AddSingleton(); services.AddTransient(); + // Setup services with a test AssemblyProvider so that only the + // sample's assemblies are loaded + services.AddTransient>(); }); } diff --git a/samples/MvcSample.Web/TestAssemblyProvider.cs b/samples/MvcSample.Web/TestAssemblyProvider.cs new file mode 100644 index 0000000000..7147468a06 --- /dev/null +++ b/samples/MvcSample.Web/TestAssemblyProvider.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; +using System.Reflection; +using Microsoft.AspNet.Mvc; + +namespace MvcSample.Web +{ + /// + /// Limits MVC to use a single Assembly for controller discovery. + /// This is used by the functional test to limit the Controller discovery to + /// MvcSample.Web Assembly alone. + /// The sample should work in the absense of this file (provided the configuration.json + /// has UseTestConfiguration set to false. + /// + /// + /// This is a generic type because it needs to instantiated by a service provider to replace + /// a built-in MVC service. + /// + public class TestAssemblyProvider : IControllerAssemblyProvider + { + public TestAssemblyProvider() + { + CandidateAssemblies = new Assembly[] { typeof(T).GetTypeInfo().Assembly }; + } + + public IEnumerable CandidateAssemblies { get; private set; } + } +} \ No newline at end of file diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs new file mode 100644 index 0000000000..e60f4eaba6 --- /dev/null +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Microsoft.AspNet.Builder; +using Microsoft.AspNet.TestHost; +using Microsoft.Framework.Runtime; +using Microsoft.Framework.Runtime.Infrastructure; +using Xunit; +using Microsoft.Framework.DependencyInjection; + +namespace Microsoft.AspNet.Mvc.FunctionalTests +{ + public class MvcSampleTests + { + private readonly IServiceProvider _services = TestHelper.CreateServices("MvcSample.Web", true); + private readonly Action _app = new MvcSample.Web.Startup().Configure; + + public MvcSampleTests() + { +#if NET45 + // APPBASE is modified so that AddJsonFile in MVC sample looks in the correct location. + var originalProvider = CallContextServiceLocator.Locator.ServiceProvider; + var appEnvironment = originalProvider.GetService(); + AppDomain.CurrentDomain.SetData("APPBASE", TestHelper.CalculateApplicationBasePath(appEnvironment, "MvcSample.Web", true)); +#endif + } + + [Fact] + public async Task Home_Index_ReturnsSuccess() + { + // Arrange + var server = TestServer.Create(_services, _app); + var client = server.Handler; + + // Act + var response = await client.GetAsync("http://localhost/Home/Index"); + + // Assert + Assert.NotNull(response); + Assert.Equal(200, response.StatusCode); + } + + [Fact] + public async Task Home_NotFoundAction_ReturnsCorrectStatusCode() + { + // Arrange + var server = TestServer.Create(_services, _app); + var client = server.Handler; + + // Act + var response = await client.GetAsync("http://localhost/Home/NotFound"); + + // Assert + Assert.NotNull(response); + Assert.Equal(404, response.StatusCode); + } + + [Fact] + public async Task Home_CreateUser_RetunsXmlBasedOnAcceptHeader() + { + // Arrange + var server = TestServer.Create(_services, _app); + var client = server.Handler; + var headers = new Dictionary(); + headers.Add("Accept", new string[] { "application/xml;charset=utf-8" }); + + // Act + var response = await client.GetAsync("http://localhost/Home/ReturnUser"); + + // Assert + Assert.NotNull(response); + Assert.Equal(200, response.StatusCode); + Assert.Equal("{\"Name\":\"My name\",\"Address\":\"My address\",\"Age\":13,\"GPA\":13.37," + + "\"Dependent\":{\"Name\":\"Dependents name\",\"Address\":\"Dependents address\",\"Age\":0," + + "\"GPA\":0.0,\"Dependent\":null,\"Alive\":false,\"Password\":null,\"Profession\":null,\"About" + + "\":null,\"Log\":null,\"OwnedAddresses\":[],\"ParentsAges\":[]},\"Alive\":true,\"Password\":" + + "\"Secure string\",\"Profession\":\"Software Engineer\",\"About\":\"I like playing Football\",\"" + + "Log\":null,\"OwnedAddresses\":[],\"ParentsAges\":[]}", + new StreamReader(response.Body, Encoding.UTF8).ReadToEnd()); + } + + [Theory] + [InlineData("http://localhost/Filters/ChallengeUser", 401)] + [InlineData("http://localhost/Filters/AllGranted", 401)] + [InlineData("http://localhost/Filters/NotGrantedClaim", 401)] + public async Task FiltersController_Tests(string url, int statusCode) + { + // Arrange + var server = TestServer.Create(_services, _app); + var client = server.Handler; + + // Act + var response = await client.GetAsync(url); + + // Assert + Assert.NotNull(response); + Assert.Equal(statusCode, response.StatusCode); + } + + [Fact] + public async Task FiltersController_Crash_ThrowsException() + { + // Arrange + var server = TestServer.Create(_services, _app); + var client = server.Handler; + + // Act + var response = await client.GetAsync("http://localhost/Filters/Crash?message=HelloWorld"); + + // Assert + Assert.NotNull(response); + Assert.Equal(200, response.StatusCode); + Assert.Equal("Boom HelloWorld", new StreamReader(response.Body, Encoding.UTF8).ReadToEnd()); + } + } +} \ No newline at end of file diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs index 4d719252c7..4012e7cb9b 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs @@ -4,24 +4,17 @@ using System; using System.IO; using System.Reflection; -using System.Threading.Tasks; -using InlineConstraints; -using Microsoft.AspNet.Builder; -using Microsoft.AspNet.Routing; -using Microsoft.AspNet.TestHost; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection.Fallback; +using Microsoft.Framework.Logging; using Microsoft.Framework.Runtime; using Microsoft.Framework.Runtime.Infrastructure; -using Xunit; -using Microsoft.Framework.ConfigurationModel; -using Microsoft.Framework.Logging; namespace Microsoft.AspNet.Mvc.FunctionalTests { public static class TestHelper { - public static IServiceProvider CreateServices(string applicationWebSiteName) + public static IServiceProvider CreateServices(string applicationWebSiteName, bool isSample = false) { var originalProvider = CallContextServiceLocator.Locator.ServiceProvider; var appEnvironment = originalProvider.GetService(); @@ -33,7 +26,7 @@ public static IServiceProvider CreateServices(string applicationWebSiteName) // To compensate for this, we need to calculate the original path and override the application // environment value so that components like the view engine work properly in the context of the // test. - var appBasePath = CalculateApplicationBasePath(appEnvironment, applicationWebSiteName); + var appBasePath = CalculateApplicationBasePath(appEnvironment, applicationWebSiteName, isSample); var services = new ServiceCollection(); services.AddInstance( typeof(IApplicationEnvironment), @@ -61,7 +54,7 @@ public static IServiceProvider CreateServices(string applicationWebSiteName) // Calculate the path relative to the application base path. public static string CalculateApplicationBasePath(IApplicationEnvironment appEnvironment, - string applicationWebSiteName) + string applicationWebSiteName, bool sample) { // Mvc/test/Microsoft.AspNet.Mvc.FunctionalTests var appBase = appEnvironment.ApplicationBasePath; @@ -69,6 +62,12 @@ public static string CalculateApplicationBasePath(IApplicationEnvironment appEnv // Mvc/test var test = Path.GetDirectoryName(appBase); + if (sample) + { + // Mvc/samples/applicationWebSiteName + return Path.GetFullPath(Path.Combine(test, "..", "samples", applicationWebSiteName)); + } + // Mvc/test/WebSites/applicationWebSiteName return Path.GetFullPath(Path.Combine(appBase, "..", "WebSites", applicationWebSiteName)); } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/project.json b/test/Microsoft.AspNet.Mvc.FunctionalTests/project.json index 3798a68b7e..17561a23d1 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/project.json +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/project.json @@ -21,6 +21,7 @@ "Microsoft.Framework.Runtime.Interfaces": "1.0.0-*", "Microsoft.AspNet.PipelineCore": "1.0.0-*", "ModelBindingWebSite": "", + "MvcSample.Web": "", "RoutingWebSite": "", "RazorWebSite": "", "ValueProvidersSite": "", From 2d0ec9210047a78ee35bf8e97f1332ce62a2954e Mon Sep 17 00:00:00 2001 From: sornaks Date: Mon, 25 Aug 2014 14:18:35 -0700 Subject: [PATCH 2/4] PR Comments --- samples/MvcSample.Web/Startup.cs | 6 ++++-- samples/MvcSample.Web/TestAssemblyProvider.cs | 3 +-- .../MvcSampleTests.cs | 13 ++++++++++--- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/samples/MvcSample.Web/Startup.cs b/samples/MvcSample.Web/Startup.cs index e195149cf1..acaa3b103a 100644 --- a/samples/MvcSample.Web/Startup.cs +++ b/samples/MvcSample.Web/Startup.cs @@ -39,7 +39,8 @@ public void Configure(IBuilder app) services.AddTransient(); services.Add(OptionsServices.GetDefaultServices()); // Setup services with a test AssemblyProvider so that only the - // sample's assemblies are loaded + // sample's assemblies are loaded. This prevents loading controllers from other assemblies + // when the sample is used in the Functional Tests. services.AddTransient>(); // Create the autofac container @@ -67,7 +68,8 @@ public void Configure(IBuilder app) services.AddSingleton(); services.AddTransient(); // Setup services with a test AssemblyProvider so that only the - // sample's assemblies are loaded + // sample's assemblies are loaded. This prevents loading controllers from other assemblies + // when the sample is used in the Functional Tests. services.AddTransient>(); }); } diff --git a/samples/MvcSample.Web/TestAssemblyProvider.cs b/samples/MvcSample.Web/TestAssemblyProvider.cs index 7147468a06..b1db4925f5 100644 --- a/samples/MvcSample.Web/TestAssemblyProvider.cs +++ b/samples/MvcSample.Web/TestAssemblyProvider.cs @@ -11,8 +11,7 @@ namespace MvcSample.Web /// Limits MVC to use a single Assembly for controller discovery. /// This is used by the functional test to limit the Controller discovery to /// MvcSample.Web Assembly alone. - /// The sample should work in the absense of this file (provided the configuration.json - /// has UseTestConfiguration set to false. + /// The sample should work in the absense of this file. /// /// /// This is a generic type because it needs to instantiated by a service provider to replace diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs index e60f4eaba6..6dbe47ab6f 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs @@ -24,8 +24,15 @@ public MvcSampleTests() { #if NET45 // APPBASE is modified so that AddJsonFile in MVC sample looks in the correct location. + // The MvcSample uses this to determine the base path. If we do not set this, the base path will + // always point to the FunctionalTests folder - the current context, + // while it is required to point to the WebSite's root directory. var originalProvider = CallContextServiceLocator.Locator.ServiceProvider; var appEnvironment = originalProvider.GetService(); + + // APPBASE is global to a process. So if any other test starts using APPBASE, it might break. + // So this is temporary. Once https://github.com/aspnet/Configuration/issues/109 is fixed, + // this code should be modified to use AppEnvironment. - aspnet/Mvc#1067 AppDomain.CurrentDomain.SetData("APPBASE", TestHelper.CalculateApplicationBasePath(appEnvironment, "MvcSample.Web", true)); #endif } @@ -46,7 +53,7 @@ public async Task Home_Index_ReturnsSuccess() } [Fact] - public async Task Home_NotFoundAction_ReturnsCorrectStatusCode() + public async Task Home_NotFoundAction_Returns404() { // Arrange var server = TestServer.Create(_services, _app); @@ -61,7 +68,7 @@ public async Task Home_NotFoundAction_ReturnsCorrectStatusCode() } [Fact] - public async Task Home_CreateUser_RetunsXmlBasedOnAcceptHeader() + public async Task Home_CreateUser_ShouldReturnXmlBasedOnAcceptHeader_ButOverridenByProducesAttribute() { // Arrange var server = TestServer.Create(_services, _app); @@ -70,7 +77,7 @@ public async Task Home_CreateUser_RetunsXmlBasedOnAcceptHeader() headers.Add("Accept", new string[] { "application/xml;charset=utf-8" }); // Act - var response = await client.GetAsync("http://localhost/Home/ReturnUser"); + var response = await client.SendAsync("GET", "http://localhost/Home/ReturnUser", headers, null, null); // Assert Assert.NotNull(response); From 599f667fa2b2f5d835014f1e73dafb1a9e2bfd71 Mon Sep 17 00:00:00 2001 From: sornaks Date: Thu, 4 Sep 2014 11:26:35 -0700 Subject: [PATCH 3/4] PR comments to fix AppEnvironment.ApplicationBasePath. --- .../MvcSampleTests.cs | 78 ++++++++----------- .../TestHelper.cs | 36 +++++---- 2 files changed, 52 insertions(+), 62 deletions(-) diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs index 6dbe47ab6f..7786be331e 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs @@ -2,16 +2,15 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Collections.Generic; using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.TestHost; -using Microsoft.Framework.Runtime; -using Microsoft.Framework.Runtime.Infrastructure; using Xunit; -using Microsoft.Framework.DependencyInjection; namespace Microsoft.AspNet.Mvc.FunctionalTests { @@ -20,36 +19,19 @@ public class MvcSampleTests private readonly IServiceProvider _services = TestHelper.CreateServices("MvcSample.Web", true); private readonly Action _app = new MvcSample.Web.Startup().Configure; - public MvcSampleTests() - { -#if NET45 - // APPBASE is modified so that AddJsonFile in MVC sample looks in the correct location. - // The MvcSample uses this to determine the base path. If we do not set this, the base path will - // always point to the FunctionalTests folder - the current context, - // while it is required to point to the WebSite's root directory. - var originalProvider = CallContextServiceLocator.Locator.ServiceProvider; - var appEnvironment = originalProvider.GetService(); - - // APPBASE is global to a process. So if any other test starts using APPBASE, it might break. - // So this is temporary. Once https://github.com/aspnet/Configuration/issues/109 is fixed, - // this code should be modified to use AppEnvironment. - aspnet/Mvc#1067 - AppDomain.CurrentDomain.SetData("APPBASE", TestHelper.CalculateApplicationBasePath(appEnvironment, "MvcSample.Web", true)); -#endif - } - [Fact] public async Task Home_Index_ReturnsSuccess() { // Arrange var server = TestServer.Create(_services, _app); - var client = server.Handler; + var client = server.CreateClient(); // Act var response = await client.GetAsync("http://localhost/Home/Index"); // Assert Assert.NotNull(response); - Assert.Equal(200, response.StatusCode); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Fact] @@ -57,49 +39,50 @@ public async Task Home_NotFoundAction_Returns404() { // Arrange var server = TestServer.Create(_services, _app); - var client = server.Handler; + var client = server.CreateClient(); // Act var response = await client.GetAsync("http://localhost/Home/NotFound"); // Assert Assert.NotNull(response); - Assert.Equal(404, response.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } [Fact] - public async Task Home_CreateUser_ShouldReturnXmlBasedOnAcceptHeader_ButOverridenByProducesAttribute() + public async Task Home_CreateUser_ReturnsXmlBasedOnAcceptHeader() { // Arrange var server = TestServer.Create(_services, _app); - var client = server.Handler; - var headers = new Dictionary(); - headers.Add("Accept", new string[] { "application/xml;charset=utf-8" }); - + var client = server.CreateClient(); + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/ReturnUser"); + request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8")); + // Act - var response = await client.SendAsync("GET", "http://localhost/Home/ReturnUser", headers, null, null); + var response = await client.SendAsync(request); // Assert Assert.NotNull(response); - Assert.Equal(200, response.StatusCode); - Assert.Equal("{\"Name\":\"My name\",\"Address\":\"My address\",\"Age\":13,\"GPA\":13.37," + - "\"Dependent\":{\"Name\":\"Dependents name\",\"Address\":\"Dependents address\",\"Age\":0," + - "\"GPA\":0.0,\"Dependent\":null,\"Alive\":false,\"Password\":null,\"Profession\":null,\"About" + - "\":null,\"Log\":null,\"OwnedAddresses\":[],\"ParentsAges\":[]},\"Alive\":true,\"Password\":" + - "\"Secure string\",\"Profession\":\"Software Engineer\",\"About\":\"I like playing Football\",\"" + - "Log\":null,\"OwnedAddresses\":[],\"ParentsAges\":[]}", - new StreamReader(response.Body, Encoding.UTF8).ReadToEnd()); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("I like playing Football" + + "
My address
13true" + + "
Dependents address
0false" + + "0Dependents name" + + "13.37" + + "My nameSecure stringSoftware Engineer
", + new StreamReader(await response.Content.ReadAsStreamAsync(), Encoding.UTF8).ReadToEnd()); } [Theory] - [InlineData("http://localhost/Filters/ChallengeUser", 401)] - [InlineData("http://localhost/Filters/AllGranted", 401)] - [InlineData("http://localhost/Filters/NotGrantedClaim", 401)] - public async Task FiltersController_Tests(string url, int statusCode) + [InlineData("http://localhost/Filters/ChallengeUser", HttpStatusCode.Unauthorized)] + [InlineData("http://localhost/Filters/AllGranted", HttpStatusCode.Unauthorized)] + [InlineData("http://localhost/Filters/NotGrantedClaim", HttpStatusCode.Unauthorized)] + public async Task FiltersController_Tests(string url, HttpStatusCode statusCode) { // Arrange var server = TestServer.Create(_services, _app); - var client = server.Handler; + var client = server.CreateClient(); // Act var response = await client.GetAsync(url); @@ -114,15 +97,16 @@ public async Task FiltersController_Crash_ThrowsException() { // Arrange var server = TestServer.Create(_services, _app); - var client = server.Handler; + var client = server.CreateClient(); // Act var response = await client.GetAsync("http://localhost/Filters/Crash?message=HelloWorld"); // Assert Assert.NotNull(response); - Assert.Equal(200, response.StatusCode); - Assert.Equal("Boom HelloWorld", new StreamReader(response.Body, Encoding.UTF8).ReadToEnd()); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("Boom HelloWorld", + new StreamReader(await response.Content.ReadAsStreamAsync(), Encoding.UTF8).ReadToEnd()); } } } \ No newline at end of file diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs index 4012e7cb9b..f54c8868e4 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs @@ -14,6 +14,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { public static class TestHelper { + // Path from Mvc/test + private static string samplesPath = Path.Combine("..", "samples"); + private static string websitesPath = Path.Combine("websites"); + public static IServiceProvider CreateServices(string applicationWebSiteName, bool isSample = false) { var originalProvider = CallContextServiceLocator.Locator.ServiceProvider; @@ -26,7 +30,16 @@ public static IServiceProvider CreateServices(string applicationWebSiteName, boo // To compensate for this, we need to calculate the original path and override the application // environment value so that components like the view engine work properly in the context of the // test. - var appBasePath = CalculateApplicationBasePath(appEnvironment, applicationWebSiteName, isSample); + var appBasePath = ""; + if (isSample) + { + appBasePath = CalculateApplicationBasePath(appEnvironment, applicationWebSiteName, samplesPath); + } + else + { + appBasePath = CalculateApplicationBasePath(appEnvironment, applicationWebSiteName, websitesPath); + } + var services = new ServiceCollection(); services.AddInstance( typeof(IApplicationEnvironment), @@ -49,27 +62,20 @@ public static IServiceProvider CreateServices(string applicationWebSiteName, boo typeof(ILoggerFactory), NullLoggerFactory.Instance); - return services.BuildServiceProvider(originalProvider); + var tempServiceProvider = services.BuildServiceProvider(originalProvider); + CallContextServiceLocator.Locator.ServiceProvider = tempServiceProvider; + return tempServiceProvider; } // Calculate the path relative to the application base path. public static string CalculateApplicationBasePath(IApplicationEnvironment appEnvironment, - string applicationWebSiteName, bool sample) + string applicationWebSiteName, string websitePath) { - // Mvc/test/Microsoft.AspNet.Mvc.FunctionalTests - var appBase = appEnvironment.ApplicationBasePath; - // Mvc/test - var test = Path.GetDirectoryName(appBase); - - if (sample) - { - // Mvc/samples/applicationWebSiteName - return Path.GetFullPath(Path.Combine(test, "..", "samples", applicationWebSiteName)); - } - + var testDirectory = Path.GetDirectoryName(appEnvironment.ApplicationBasePath); + // Mvc/test/WebSites/applicationWebSiteName - return Path.GetFullPath(Path.Combine(appBase, "..", "WebSites", applicationWebSiteName)); + return Path.GetFullPath(Path.Combine(testDirectory, websitePath, applicationWebSiteName)); } private static Type CreateAssemblyProviderType(string siteName) From c574cbec539a0882ce5e11031607c534e83c9c39 Mon Sep 17 00:00:00 2001 From: sornaks Date: Thu, 4 Sep 2014 13:27:29 -0700 Subject: [PATCH 4/4] Addressing PR comments. --- .../MvcSampleTests.cs | 4 ++- .../TestHelper.cs | 28 ++++++++----------- 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs index 7786be331e..01a66c402c 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs @@ -16,7 +16,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { public class MvcSampleTests { - private readonly IServiceProvider _services = TestHelper.CreateServices("MvcSample.Web", true); + // Path relative to Mvc\\test\Microsoft.AspNet.Mvc.FunctionalTests + private readonly IServiceProvider _services = + TestHelper.CreateServices("MvcSample.Web", Path.Combine("..", "..", "samples")); private readonly Action _app = new MvcSample.Web.Startup().Configure; [Fact] diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs index f54c8868e4..ec59194d90 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs @@ -14,11 +14,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { public static class TestHelper { - // Path from Mvc/test - private static string samplesPath = Path.Combine("..", "samples"); - private static string websitesPath = Path.Combine("websites"); + // Path from Mvc\\test\\Microsoft.AspNet.Mvc.FunctionalTests + private static readonly string WebsitesDirectoryPath = Path.Combine("..", "websites"); - public static IServiceProvider CreateServices(string applicationWebSiteName, bool isSample = false) + public static IServiceProvider CreateServices(string applicationWebSiteName) + { + return CreateServices(applicationWebSiteName, WebsitesDirectoryPath); + } + + public static IServiceProvider CreateServices(string applicationWebSiteName, string applicationPath) { var originalProvider = CallContextServiceLocator.Locator.ServiceProvider; var appEnvironment = originalProvider.GetService(); @@ -30,15 +34,7 @@ public static IServiceProvider CreateServices(string applicationWebSiteName, boo // To compensate for this, we need to calculate the original path and override the application // environment value so that components like the view engine work properly in the context of the // test. - var appBasePath = ""; - if (isSample) - { - appBasePath = CalculateApplicationBasePath(appEnvironment, applicationWebSiteName, samplesPath); - } - else - { - appBasePath = CalculateApplicationBasePath(appEnvironment, applicationWebSiteName, websitesPath); - } + var appBasePath = CalculateApplicationBasePath(appEnvironment, applicationWebSiteName, applicationPath); var services = new ServiceCollection(); services.AddInstance( @@ -71,11 +67,9 @@ public static IServiceProvider CreateServices(string applicationWebSiteName, boo public static string CalculateApplicationBasePath(IApplicationEnvironment appEnvironment, string applicationWebSiteName, string websitePath) { - // Mvc/test - var testDirectory = Path.GetDirectoryName(appEnvironment.ApplicationBasePath); - // Mvc/test/WebSites/applicationWebSiteName - return Path.GetFullPath(Path.Combine(testDirectory, websitePath, applicationWebSiteName)); + return Path.GetFullPath( + Path.Combine(appEnvironment.ApplicationBasePath, websitePath, applicationWebSiteName)); } private static Type CreateAssemblyProviderType(string siteName)