Updating functional tests to restore CallContextServiceLocator.Locator.Service on test finish

This commit is contained in:
Pranav K 2014-10-08 12:08:55 -07:00
parent b19764d922
commit ad208442d8
5 changed files with 135 additions and 100 deletions

View File

@ -1,8 +1,5 @@
using System; using System;
using System.IO;
using System.Net; using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.TestHost; using Microsoft.AspNet.TestHost;
@ -26,35 +23,39 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task CustomUrlHelper_GeneratesUrlFromController() public async Task CustomUrlHelper_GeneratesUrlFromController()
{ {
// Arrange using (TestHelper.ReplaceCallContextServiceLocationService(_services))
var server = TestServer.Create(_services, _app); {
var client = server.CreateClient(); // Arrange
var server = TestServer.Create(_services, _app);
var client = server.CreateClient();
// Act // Act
var response = await client.GetAsync("http://localhost/Home/UrlContent"); var response = await client.GetAsync("http://localhost/Home/UrlContent");
var responseData = await response.Content.ReadAsStringAsync();
string responseData = await response.Content.ReadAsStringAsync(); //Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
//Assert Assert.Equal(_cdnServerBaseUrl + "/bootstrap.min.css", responseData);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
Assert.Equal(_cdnServerBaseUrl + "/bootstrap.min.css", responseData);
} }
[Fact] [Fact]
public async Task CustomUrlHelper_GeneratesUrlFromView() public async Task CustomUrlHelper_GeneratesUrlFromView()
{ {
// Arrange using (TestHelper.ReplaceCallContextServiceLocationService(_services))
var server = TestServer.Create(_services, _app); {
var client = server.CreateClient(); // Arrange
var server = TestServer.Create(_services, _app);
var client = server.CreateClient();
// Act // Act
var response = await client.GetAsync("http://localhost/Home/Index"); var response = await client.GetAsync("http://localhost/Home/Index");
var responseData = await response.Content.ReadAsStringAsync();
string responseData = await response.Content.ReadAsStringAsync(); //Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
//Assert Assert.Contains(_cdnServerBaseUrl + "/bootstrap.min.css", responseData);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
Assert.Contains(_cdnServerBaseUrl + "/bootstrap.min.css", responseData);
} }
[Theory] [Theory]
@ -62,18 +63,20 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("http://localhost/Home/LinkByUrlAction", "/home/urlcontent")] [InlineData("http://localhost/Home/LinkByUrlAction", "/home/urlcontent")]
public async Task LowercaseUrls_LinkGeneration(string url, string expectedLink) public async Task LowercaseUrls_LinkGeneration(string url, string expectedLink)
{ {
// Arrange using (TestHelper.ReplaceCallContextServiceLocationService(_services))
var server = TestServer.Create(_services, _app); {
var client = server.CreateClient(); // Arrange
var server = TestServer.Create(_services, _app);
var client = server.CreateClient();
// Act // Act
var response = await client.GetAsync(url); var response = await client.GetAsync(url);
var responseData = await response.Content.ReadAsStringAsync();
string responseData = await response.Content.ReadAsStringAsync(); //Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
//Assert Assert.Equal(expectedLink, responseData, ignoreCase: false);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
Assert.Equal(expectedLink, responseData, ignoreCase: false);
} }
} }
} }

View File

@ -6,7 +6,6 @@ using System.IO;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.TestHost; using Microsoft.AspNet.TestHost;
@ -24,56 +23,65 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task Home_Index_ReturnsSuccess() public async Task Home_Index_ReturnsSuccess()
{ {
// Arrange using (TestHelper.ReplaceCallContextServiceLocationService(_services))
var server = TestServer.Create(_services, _app); {
var client = server.CreateClient(); // Arrange
var server = TestServer.Create(_services, _app);
var client = server.CreateClient();
// Act // Act
var response = await client.GetAsync("http://localhost/Home/Index"); var response = await client.GetAsync("http://localhost/Home/Index");
// Assert // Assert
Assert.NotNull(response); Assert.NotNull(response);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
} }
[Fact] [Fact]
public async Task Home_NotFoundAction_Returns404() public async Task Home_NotFoundAction_Returns404()
{ {
// Arrange using (TestHelper.ReplaceCallContextServiceLocationService(_services))
var server = TestServer.Create(_services, _app); {
var client = server.CreateClient(); // Arrange
var server = TestServer.Create(_services, _app);
var client = server.CreateClient();
// Act // Act
var response = await client.GetAsync("http://localhost/Home/NotFound"); var response = await client.GetAsync("http://localhost/Home/NotFound");
// Assert // Assert
Assert.NotNull(response); Assert.NotNull(response);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
} }
[Fact] [Fact]
public async Task Home_CreateUser_ReturnsXmlBasedOnAcceptHeader() public async Task Home_CreateUser_ReturnsXmlBasedOnAcceptHeader()
{ {
// Arrange using (TestHelper.ReplaceCallContextServiceLocationService(_services))
var server = TestServer.Create(_services, _app); {
var client = server.CreateClient(); // Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/ReturnUser"); var server = TestServer.Create(_services, _app);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8")); var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/ReturnUser");
// Act request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8"));
var response = await client.SendAsync(request);
// Assert // Act
Assert.NotNull(response); var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("<User xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=" + // Assert
"\"http://schemas.datacontract.org/2004/07/MvcSample.Web.Models\"><About>I like playing Football" + Assert.NotNull(response);
"</About><Address>My address</Address><Age>13</Age><Alive>true</Alive><Dependent><About i:nil=\"true\" />" + Assert.Equal(HttpStatusCode.OK, response.StatusCode);
"<Address>Dependents address</Address><Age>0</Age><Alive>false</Alive><Dependent i:nil=\"true\" />" + Assert.Equal("<User xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=" +
"<GPA>0</GPA><Log i:nil=\"true\" /><Name>Dependents name</Name><Password i:nil=\"true\" />" + "\"http://schemas.datacontract.org/2004/07/MvcSample.Web.Models\"><About>I like playing Football" +
"<Profession i:nil=\"true\" /></Dependent><GPA>13.37</GPA><Log i:nil=\"true\" />" + "</About><Address>My address</Address><Age>13</Age><Alive>true</Alive><Dependent><About i:nil=\"true\" />" +
"<Name>My name</Name><Password>Secure string</Password><Profession>Software Engineer</Profession></User>", "<Address>Dependents address</Address><Age>0</Age><Alive>false</Alive><Dependent i:nil=\"true\" />" +
new StreamReader(await response.Content.ReadAsStreamAsync(), Encoding.UTF8).ReadToEnd()); "<GPA>0</GPA><Log i:nil=\"true\" /><Name>Dependents name</Name><Password i:nil=\"true\" />" +
"<Profession i:nil=\"true\" /></Dependent><GPA>13.37</GPA><Log i:nil=\"true\" />" +
"<Name>My name</Name><Password>Secure string</Password><Profession>Software Engineer</Profession></User>",
await response.Content.ReadAsStringAsync());
}
} }
[Theory] [Theory]
@ -82,33 +90,38 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("http://localhost/Filters/NotGrantedClaim", HttpStatusCode.Unauthorized)] [InlineData("http://localhost/Filters/NotGrantedClaim", HttpStatusCode.Unauthorized)]
public async Task FiltersController_Tests(string url, HttpStatusCode statusCode) public async Task FiltersController_Tests(string url, HttpStatusCode statusCode)
{ {
// Arrange using (TestHelper.ReplaceCallContextServiceLocationService(_services))
var server = TestServer.Create(_services, _app); {
var client = server.CreateClient(); // Arrange
var server = TestServer.Create(_services, _app);
var client = server.CreateClient();
// Act // Act
var response = await client.GetAsync(url); var response = await client.GetAsync(url);
// Assert // Assert
Assert.NotNull(response); Assert.NotNull(response);
Assert.Equal(statusCode, response.StatusCode); Assert.Equal(statusCode, response.StatusCode);
}
} }
[Fact] [Fact]
public async Task FiltersController_Crash_ThrowsException() public async Task FiltersController_Crash_ThrowsException()
{ {
// Arrange using (TestHelper.ReplaceCallContextServiceLocationService(_services))
var server = TestServer.Create(_services, _app); {
var client = server.CreateClient(); // Arrange
var server = TestServer.Create(_services, _app);
var client = server.CreateClient();
// Act // Act
var response = await client.GetAsync("http://localhost/Filters/Crash?message=HelloWorld"); var response = await client.GetAsync("http://localhost/Filters/Crash?message=HelloWorld");
// Assert // Assert
Assert.NotNull(response); Assert.NotNull(response);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("Boom HelloWorld", Assert.Equal("Boom HelloWorld", await response.Content.ReadAsStringAsync());
new StreamReader(await response.Content.ReadAsStreamAsync(), Encoding.UTF8).ReadToEnd()); }
} }
} }
} }

View File

@ -15,7 +15,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public static class TestHelper public static class TestHelper
{ {
// Path from Mvc\\test\\Microsoft.AspNet.Mvc.FunctionalTests // Path from Mvc\\test\\Microsoft.AspNet.Mvc.FunctionalTests
private static readonly string WebsitesDirectoryPath = Path.Combine("..", "websites"); private static readonly string WebsitesDirectoryPath = Path.Combine("..", "WebSites");
public static IServiceProvider CreateServices(string applicationWebSiteName) public static IServiceProvider CreateServices(string applicationWebSiteName)
{ {
@ -58,9 +58,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
typeof(ILoggerFactory), typeof(ILoggerFactory),
NullLoggerFactory.Instance); NullLoggerFactory.Instance);
var tempServiceProvider = services.BuildServiceProvider(originalProvider); return services.BuildServiceProvider(originalProvider);
CallContextServiceLocator.Locator.ServiceProvider = tempServiceProvider;
return tempServiceProvider;
} }
// Calculate the path relative to the application base path. // Calculate the path relative to the application base path.
@ -72,6 +70,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Path.Combine(appEnvironment.ApplicationBasePath, websitePath, applicationWebSiteName)); Path.Combine(appEnvironment.ApplicationBasePath, websitePath, applicationWebSiteName));
} }
/// <summary>
/// Creates a disposable action that replaces the service provider <see cref="CallContextServiceLocator.Locator"/>
/// with the passed in service that is switched back on <see cref="IDisposable.Dispose"/>.
/// </summary>
/// <remarks>This is required for config since it uses the static property to get to
/// <see cref="IApplicationEnvironment"/>.</remarks>
public static IDisposable ReplaceCallContextServiceLocationService(IServiceProvider serviceProvider)
{
return new CallContextProviderAction(serviceProvider);
}
private static Type CreateAssemblyProviderType(string siteName) private static Type CreateAssemblyProviderType(string siteName)
{ {
// Creates a service type that will limit MVC to only the controllers in the test site. // Creates a service type that will limit MVC to only the controllers in the test site.
@ -81,5 +90,21 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var providerType = typeof(TestAssemblyProvider<>).MakeGenericType(assembly.GetExportedTypes()[0]); var providerType = typeof(TestAssemblyProvider<>).MakeGenericType(assembly.GetExportedTypes()[0]);
return providerType; return providerType;
} }
private sealed class CallContextProviderAction : IDisposable
{
private readonly IServiceProvider _originalProvider;
public CallContextProviderAction(IServiceProvider provider)
{
_originalProvider = CallContextServiceLocator.Locator.ServiceProvider;
CallContextServiceLocator.Locator.ServiceProvider = provider;
}
public void Dispose()
{
CallContextServiceLocator.Locator.ServiceProvider = _originalProvider;
}
}
} }
} }

View File

@ -1,5 +0,0 @@
{
"ServeCDNContent": "true",
"CDNServerBaseUrl" : "http://cdn.contoso.com",
"GenerateLowercaseUrls": "true"
}

View File

@ -12,16 +12,15 @@ namespace UrlHelperWebSite
public void Configure(IApplicationBuilder app) public void Configure(IApplicationBuilder app)
{ {
var configuration = app.GetTestConfiguration(); var configuration = app.GetTestConfiguration();
configuration.AddJsonFile("config.json");
// Set up application services // Set up application services
app.UsePerRequestServices(services => app.UsePerRequestServices(services =>
{ {
services.ConfigureOptions<AppOptions>(optionsSetup => services.ConfigureOptions<AppOptions>(optionsSetup =>
{ {
optionsSetup.ServeCDNContent = Convert.ToBoolean(configuration.Get("ServeCDNContent")); optionsSetup.ServeCDNContent = true;
optionsSetup.CDNServerBaseUrl = configuration.Get("CDNServerBaseUrl"); optionsSetup.CDNServerBaseUrl = "http://cdn.contoso.com";
optionsSetup.GenerateLowercaseUrls = Convert.ToBoolean(configuration.Get("GenerateLowercaseUrls")); optionsSetup.GenerateLowercaseUrls = true;
}); });
// Add MVC services to the services container // Add MVC services to the services container