diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ActionResultTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ActionResultTests.cs index a604d0aad6..dc843fb09c 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ActionResultTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ActionResultTests.cs @@ -12,9 +12,9 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ActionResultTests : IClassFixture> + public class ActionResultTests : IClassFixture> { - public ActionResultTests(MvcFixture fixture) + public ActionResultTests(MvcTestFixture fixture) { Client = fixture.Client; } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ActivatorTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ActivatorTests.cs index 146dbe4899..afde2fe3b7 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ActivatorTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ActivatorTests.cs @@ -8,9 +8,9 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ActivatorTests : IClassFixture> + public class ActivatorTests : IClassFixture> { - public ActivatorTests(MvcFixture fixture) + public ActivatorTests(MvcTestFixture fixture) { Client = fixture.Client; } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/AntiforgeryTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/AntiforgeryTests.cs index e3bad7b019..67c05676d1 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/AntiforgeryTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/AntiforgeryTests.cs @@ -1,35 +1,31 @@ // 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.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class AntiforgeryTests + public class AntiforgeryTests : IClassFixture> { - private const string SiteName = nameof(AntiforgeryTokenWebSite); - private readonly Action _app = new AntiforgeryTokenWebSite.Startup().Configure; - private readonly Action _configureServices = new AntiforgeryTokenWebSite.Startup().ConfigureServices; + public AntiforgeryTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task MultipleAFTokensWithinTheSamePage_GeneratesASingleCookieToken() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Account/Login"); - // Act - var response = await client.GetAsync("http://localhost/Account/Login"); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var header = Assert.Single(response.Headers.GetValues("X-Frame-Options")); Assert.Equal("SAMEORIGIN", header); @@ -45,11 +41,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task MultipleFormPostWithingASingleView_AreAllowed() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // do a get response. - var getResponse = await client.GetAsync("http://localhost/Account/Login"); + // Do a get request. + var getResponse = await Client.GetAsync("http://localhost/Account/Login"); var responseBody = await getResponse.Content.ReadAsStringAsync(); // Get the AF token for the second login. If the cookies are generated twice(i.e are different), @@ -69,7 +62,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -80,10 +73,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task InvalidCookieToken_Throws() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - var getResponse = await client.GetAsync("http://localhost/Account/Login"); + var getResponse = await Client.GetAsync("http://localhost/Account/Login"); var responseBody = await getResponse.Content.ReadAsStringAsync(); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseBody, "Account/Login"); @@ -101,7 +91,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var exception = response.GetServerException(); @@ -112,10 +102,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task InvalidFormToken_Throws() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - var getResponse = await client.GetAsync("http://localhost/Account/Login"); + var getResponse = await Client.GetAsync("http://localhost/Account/Login"); var responseBody = await getResponse.Content.ReadAsStringAsync(); var cookieToken = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Account/Login"); @@ -131,7 +118,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var exception = response.GetServerException(); @@ -142,16 +129,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task IncompatibleCookieToken_Throws() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // do a get response. // We do two requests to get two different sets of antiforgery cookie and token values. - var getResponse1 = await client.GetAsync("http://localhost/Account/Login"); + var getResponse1 = await Client.GetAsync("http://localhost/Account/Login"); var responseBody1 = await getResponse1.Content.ReadAsStringAsync(); var formToken1 = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseBody1, "Account/Login"); - var getResponse2 = await client.GetAsync("http://localhost/Account/Login"); + var getResponse2 = await Client.GetAsync("http://localhost/Account/Login"); var responseBody2 = await getResponse2.Content.ReadAsStringAsync(); var cookieToken2 = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse2); @@ -169,7 +153,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var exception = response.GetServerException(); @@ -180,11 +164,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task MissingCookieToken_Throws() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // do a get response. - var getResponse = await client.GetAsync("http://localhost/Account/Login"); + var getResponse = await Client.GetAsync("http://localhost/Account/Login"); var responseBody = await getResponse.Content.ReadAsStringAsync(); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseBody, "Account/Login"); var cookieTokenKey = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse).Key; @@ -200,7 +181,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var exception = response.GetServerException(); @@ -213,9 +194,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task MissingAFToken_Throws() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var getResponse = await client.GetAsync("http://localhost/Account/Login"); + var getResponse = await Client.GetAsync("http://localhost/Account/Login"); var responseBody = await getResponse.Content.ReadAsStringAsync(); var cookieToken = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); @@ -230,7 +209,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var exception = response.GetServerException(); @@ -241,12 +220,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task SetCookieAndHeaderBeforeFlushAsync_GeneratesCookieTokenAndHeader() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Account/FlushAsyncLogin"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Account/FlushAsyncLogin"); // Assert var header = Assert.Single(response.Headers.GetValues("X-Frame-Options")); @@ -260,11 +235,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task SetCookieAndHeaderBeforeFlushAsync_PostToForm() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // do a get response. - var getResponse = await client.GetAsync("http://localhost/Account/FlushAsyncLogin"); + var getResponse = await Client.GetAsync("http://localhost/Account/FlushAsyncLogin"); var responseBody = await getResponse.Content.ReadAsStringAsync(); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseBody, "Account/FlushAsyncLogin"); @@ -282,7 +254,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ApiExplorerTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ApiExplorerTest.cs index caeeb7a5fd..8f7ae2a2ed 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ApiExplorerTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ApiExplorerTest.cs @@ -1,35 +1,31 @@ // 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.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.Formatters; using Microsoft.AspNet.Mvc.ModelBinding; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ApiExplorerTest + public class ApiExplorerTest : IClassFixture> { - private const string SiteName = nameof(ApiExplorerWebSite); - private readonly Action _app = new ApiExplorerWebSite.Startup().Configure; - private readonly Action _configureServices = new ApiExplorerWebSite.Startup().ConfigureServices; + public ApiExplorerTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task ApiExplorer_IsVisible_EnabledWithConvention() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerVisbilityEnabledByConvention"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerVisbilityEnabledByConvention"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -41,12 +37,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_IsVisible_DisabledWithConvention() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerVisbilityDisabledByConvention"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerVisbilityDisabledByConvention"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -58,12 +50,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_IsVisible_DisabledWithAttribute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerVisibilitySetExplicitly/Disabled"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerVisibilitySetExplicitly/Disabled"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -75,12 +63,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_IsVisible_EnabledWithAttribute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerVisibilitySetExplicitly/Enabled"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerVisibilitySetExplicitly/Enabled"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -92,12 +76,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_GroupName_SetByConvention() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerNameSetByConvention"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerNameSetByConvention"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -110,12 +90,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_GroupName_SetByAttributeOnController() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerNameSetExplicitly/SetOnController"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerNameSetExplicitly/SetOnController"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -128,12 +104,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_GroupName_SetByAttributeOnAction() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerNameSetExplicitly/SetOnAction"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerNameSetExplicitly/SetOnAction"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -146,12 +118,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_RouteTemplate_DisplaysFixedRoute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerRouteAndPathParametersInformation"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerRouteAndPathParametersInformation"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -164,12 +132,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_RouteTemplate_DisplaysRouteWithParameters() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerRouteAndPathParametersInformation/5"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerRouteAndPathParametersInformation/5"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -189,12 +153,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiExplorer_RouteTemplate_StripsInlineConstraintsFromThePath() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/Constraint/5"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -214,12 +176,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiExplorer_RouteTemplate_StripsCatchAllsFromThePath() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/CatchAll/5"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -238,12 +198,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiExplorer_RouteTemplate_StripsCatchAllsWithConstraintsFromThePath() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/CatchAllAndConstraint/5"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -265,9 +223,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiExplorer_RouteTemplateStripsMultipleConstraints_OnTheSamePathSegment() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/" + "MultipleParametersInSegment/12-01-1987"; @@ -275,7 +230,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests + "MultipleParametersInSegment/{month}-{day}-{year}"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -304,8 +259,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiExplorer_RouteTemplateStripsMultipleConstraints_InMultipleSegments() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/" + "MultipleParametersInMultipleSegments/12/01/1987"; @@ -313,7 +266,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests + "MultipleParametersInMultipleSegments/{month}/{day}/{year}"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -342,15 +295,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiExplorer_DescribeParameters_FromAllSources() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/MultipleTypesOfParameters/1/2/3"; var expectedRelativePath = "ApiExplorerRouteAndPathParametersInformation/" + "MultipleTypesOfParameters/{path}/{pathAndQuery}/{pathAndFromBody}"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -372,12 +323,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_RouteTemplate_MakesParametersOptional() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerRouteAndPathParametersInformation/Optional/"); + // Arrange & Act + var response = await Client.GetAsync( + "http://localhost/ApiExplorerRouteAndPathParametersInformation/Optional/"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -394,12 +342,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_HttpMethod_All() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerHttpMethod/All"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerHttpMethod/All"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -412,12 +356,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_HttpMethod_Single() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerHttpMethod/Get"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerHttpMethod/Get"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -435,15 +375,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiExplorer_HttpMethod_Single(string httpMethod) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod(httpMethod), "http://localhost/ApiExplorerHttpMethod/Single"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -460,12 +397,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("GetTask")] public async Task ApiExplorer_ResponseType_VoidWithoutAttribute(string action) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/ApiExplorerResponseTypeWithoutAttribute/" + action); var body = await response.Content.ReadAsStringAsync(); @@ -485,12 +418,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("GetTaskOfDerivedActionResult")] public async Task ApiExplorer_ResponseType_UnknownWithoutAttribute(string action) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/ApiExplorerResponseTypeWithoutAttribute/" + action); var body = await response.Content.ReadAsStringAsync(); @@ -508,12 +437,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("GetTaskOfInt", "System.Int32")] public async Task ApiExplorer_ResponseType_KnownWithoutAttribute(string action, string type) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/ApiExplorerResponseTypeWithoutAttribute/" + action); var body = await response.Content.ReadAsStringAsync(); @@ -532,12 +457,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("GetTask", "System.Int32")] public async Task ApiExplorer_ResponseType_KnownWithAttribute(string action, string type) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/ApiExplorerResponseTypeWithAttribute/" + action); var body = await response.Content.ReadAsStringAsync(); @@ -553,12 +474,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("Action", "ApiExplorerWebSite.Customer")] public async Task ApiExplorer_ResponseType_OverrideOnAction(string action, string type) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/ApiExplorerResponseTypeOverrideOnAction/" + action); var body = await response.Content.ReadAsStringAsync(); @@ -574,12 +491,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task ApiExplorer_ResponseContentType_Unset() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerResponseContentType/Unset"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerResponseContentType/Unset"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -604,12 +517,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_ResponseContentType_Specific() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerResponseContentType/Specific"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerResponseContentType/Specific"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -630,12 +539,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_ResponseContentType_NoMatch() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerResponseContentType/NoMatch"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerResponseContentType/NoMatch"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -657,12 +562,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests string contentType, string formatterType) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/ApiExplorerResponseContentTypeOverrideOnAction/" + action); var body = await response.Content.ReadAsStringAsync(); @@ -679,12 +580,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_Parameters_SimpleTypes_Default() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerParameters/SimpleParameters"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerParameters/SimpleParameters"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -707,12 +604,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_Parameters_SimpleTypes_BinderMetadataOnParameters() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerParameters/SimpleParametersWithBinderMetadata"); + // Arrange & Act + var response = await Client.GetAsync( + "http://localhost/ApiExplorerParameters/SimpleParametersWithBinderMetadata"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -735,12 +629,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_ParametersSimpleModel() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerParameters/SimpleModel"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerParameters/SimpleModel"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -763,12 +653,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_Parameters_SimpleTypes_SimpleModel_FromBody() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerParameters/SimpleModelFromBody/5"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerParameters/SimpleModelFromBody/5"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); @@ -791,12 +677,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiExplorer_Parameters_SimpleTypes_ComplexModel() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApiExplorerParameters/ComplexModel"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApiExplorerParameters/ComplexModel"); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject>(body); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ApplicationModelTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ApplicationModelTest.cs index 9e7cf42f4f..3f9b7c5b4d 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ApplicationModelTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ApplicationModelTest.cs @@ -1,31 +1,27 @@ // 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.Net; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ApplicationModelTest + public class ApplicationModelTest : IClassFixture> { - private const string SiteName = nameof(ApplicationModelWebSite); - private readonly Action _app = new ApplicationModelWebSite.Startup().Configure; - private readonly Action _configureServices = new ApplicationModelWebSite.Startup().ConfigureServices; + public ApplicationModelTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task ControllerModel_CustomizedWithAttribute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CoolController/GetControllerName"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/CoolController/GetControllerName"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -37,12 +33,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ActionModel_CustomizedWithAttribute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ActionModel/ActionName"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ActionModel/ActionName"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -54,12 +46,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ParameterModel_CustomizedWithAttribute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ParameterModel/GetParameterMetadata"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ParameterModel/GetParameterMetadata"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -71,12 +59,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApplicationModel_AddPropertyToActionDescriptor_FromApplicationModel() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/GetCommonDescription"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/GetCommonDescription"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -88,12 +72,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApplicationModel_AddPropertyToActionDescriptor_ControllerModelOverwritesCommonApplicationProperty() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApplicationModel/GetControllerDescription"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApplicationModel/GetControllerDescription"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -105,12 +85,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApplicationModel_ProvidesMetadataToActionDescriptor_ActionModelOverwritesControllerModelProperty() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ApplicationModel/GetActionSpecificDescription"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ApplicationModel/GetActionSpecificDescription"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -122,12 +98,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApplicationModelExtensions_AddsConventionToAllControllers() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Lisence/GetLisence"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Lisence/GetLisence"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -142,14 +114,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApplicationModelExtensions_AddsConventionToAllActions() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/GetHelloWorld"); request.Headers.Add("helloWorld", "HelloWorld"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/BasicTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/BasicTests.cs index f2683db546..a2f847358b 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/BasicTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/BasicTests.cs @@ -14,7 +14,7 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class BasicTests : IClassFixture> + public class BasicTests : IClassFixture> { // Some tests require comparing the actual response body against an expected response baseline // so they require a reference to the assembly on which the resources are located, in order to @@ -22,7 +22,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // use it on all the rest of the tests. private static readonly Assembly _resourcesAssembly = typeof(BasicTests).GetTypeInfo().Assembly; - public BasicTests(MvcFixture fixture) + public BasicTests(MvcTestFixture fixture) { Client = fixture.Client; } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/BestEffortLinkGenerationTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/BestEffortLinkGenerationTest.cs index 818c9c7fb8..03e1bd1582 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/BestEffortLinkGenerationTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/BestEffortLinkGenerationTest.cs @@ -1,39 +1,37 @@ // 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.Net; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class BestEffortLinkGenerationTest + public class BestEffortLinkGenerationTest : IClassFixture> { - private const string SiteName = nameof(BestEffortLinkGenerationWebSite); - private readonly Action _app = new BestEffortLinkGenerationWebSite.Startup().Configure; - private readonly Action _configureServices = new BestEffortLinkGenerationWebSite.Startup().ConfigureServices; - private const string ExpectedOutput = @" About Us "; + public BestEffortLinkGenerationTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } + [Fact] public async Task GenerateLink_NonExistentAction() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/Home/Index"; + // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); var content = await response.Content.ReadAsStringAsync(); // Assert diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/CompilationOptionsTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/CompilationOptionsTests.cs index 1412126ed3..0c33d46132 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/CompilationOptionsTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/CompilationOptionsTests.cs @@ -1,22 +1,22 @@ // 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.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using RazorWebSite; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { // Test to verify compilation options from the application are used to compile // precompiled and dynamically compiled views. - public class CompilationOptionsTests + public class CompilationOptionsTests : IClassFixture> { - private const string SiteName = nameof(RazorWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public CompilationOptionsTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task CompilationOptions_AreUsedByViewsAndPartials() @@ -31,11 +31,9 @@ This method is only defined in DNX451"; @"This method is running from DNXCORE50 This method is only defined in DNXCORE50"; #endif - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync("http://localhost/ViewsConsumingCompilationOptions/"); + var body = await Client.GetStringAsync("http://localhost/ViewsConsumingCompilationOptions/"); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/CompositeViewEngineTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/CompositeViewEngineTests.cs index 6a96b675b4..27c00ee7d9 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/CompositeViewEngineTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/CompositeViewEngineTests.cs @@ -1,29 +1,26 @@ // 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.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class CompositeViewEngineTests + public class CompositeViewEngineTests : IClassFixture> { - private const string SiteName = nameof(CompositeViewEngineWebSite); - private readonly Action _app = new CompositeViewEngineWebSite.Startup().Configure; - private readonly Action _configureServices = new CompositeViewEngineWebSite.Startup().ConfigureServices; + public CompositeViewEngineTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task CompositeViewEngine_FindsPartialViewsAcrossAllEngines() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync("http://localhost/"); + // Arrange & Act + var body = await Client.GetStringAsync("http://localhost/"); // Assert Assert.Equal("Hello world", body.Trim()); @@ -32,12 +29,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task CompositeViewEngine_FindsViewsAcrossAllEngines() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync("http://localhost/Home/TestView"); + // Arrange & Act + var body = await Client.GetStringAsync("http://localhost/Home/TestView"); // Assert Assert.Equal("Content from test view", body.Trim()); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ConsumesAttributeTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ConsumesAttributeTests.cs index b0622bc043..45548ef84c 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ConsumesAttributeTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ConsumesAttributeTests.cs @@ -1,41 +1,39 @@ // 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.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using ActionConstraintsWebSite; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.Actions; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ConsumesAttributeTests + public class ConsumesAttributeTests : IClassFixture> { - private const string SiteName = nameof(ActionConstraintsWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ConsumesAttributeTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task NoRequestContentType_SelectsActionWithoutConstraint() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage( HttpMethod.Post, "http://localhost/ConsumesAttribute_Company/CreateProduct"); // Act - var response = await client.SendAsync(request); - var product = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var response = await Client.SendAsync(request); + var product = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); + // Assert Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Null(product); @@ -45,14 +43,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task NoRequestContentType_Throws_IfMultipleActionsWithConstraints() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage( HttpMethod.Post, "http://localhost/ConsumesAttribute_AmbiguousActions/CreateProduct"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var exception = response.GetServerException(); // Assert @@ -72,17 +68,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task NoRequestContentType_Selects_IfASingleActionWithConstraintIsPresent() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( HttpMethod.Post, "http://localhost/ConsumesAttribute_PassThrough/CreateProduct"); // Act - var response = await client.SendAsync(request); - var product = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var response = await Client.SendAsync(request); + var product = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); + // Assert Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Null(product); @@ -94,18 +87,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task Selects_Action_BasedOnRequestContentType(string requestContentType) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "{SampleString:\""+requestContentType+"\"}"; var request = new HttpRequestMessage( HttpMethod.Post, "http://localhost/ConsumesAttribute_AmbiguousActions/CreateProduct"); request.Content = new StringContent(input, Encoding.UTF8, requestContentType); + // Act - var response = await client.SendAsync(request); - var product = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var response = await Client.SendAsync(request); + var product = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(requestContentType, product.SampleString); @@ -117,9 +108,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ActionLevelAttribute_OveridesClassLevel(string requestContentType) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "{SampleString:\"" + requestContentType + "\"}"; var request = new HttpRequestMessage( HttpMethod.Post, @@ -128,9 +116,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var expectedString = "ConsumesAttribute_OverridesBaseController_" + requestContentType; // Act - var response = await client.SendAsync(request); - var product = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var response = await Client.SendAsync(request); + var product = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedString, product.SampleString); @@ -142,9 +130,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task DerivedClassLevelAttribute_OveridesBaseClassLevel() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "" + "application/xml"; @@ -155,9 +140,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var expectedString = "ConsumesAttribute_OverridesController_application/xml"; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var responseString = await response.Content.ReadAsStringAsync(); var product = JsonConvert.DeserializeObject(responseString); + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedString, product.SampleString); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ContentNegotiationTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ContentNegotiationTest.cs index 1fdb9987c9..a2ba06ba4a 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ContentNegotiationTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ContentNegotiationTest.cs @@ -7,34 +7,31 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; -using ContentNegotiationWebSite; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ContentNegotiationTest + public class ContentNegotiationTest : IClassFixture> { - private const string SiteName = nameof(ContentNegotiationWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ContentNegotiationTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task ProducesAttribute_SingleContentType_PicksTheFirstSupportedFormatter() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // Selects custom even though it is last in the list. var expectedContentType = MediaTypeHeaderValue.Parse("application/custom;charset=utf-8"); var expectedBody = "Written using custom format."; // Act - var response = await client.GetAsync("http://localhost/Normal/WriteUserUsingCustomFormat"); + var response = await Client.GetAsync("http://localhost/Normal/WriteUserUsingCustomFormat"); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -46,14 +43,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ProducesAttribute_MultipleContentTypes_RunsConnegToSelectFormatter() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); var expectedBody = $"{{{Environment.NewLine} \"Name\": \"My name\",{Environment.NewLine}" + $" \"Address\": \"My address\"{Environment.NewLine}}}"; // Act - var response = await client.GetAsync("http://localhost/Normal/MultipleAllowedContentTypes"); + var response = await Client.GetAsync("http://localhost/Normal/MultipleAllowedContentTypes"); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -65,13 +60,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task NoProducesAttribute_ActionReturningString_RunsUsingTextFormatter() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedContentType = MediaTypeHeaderValue.Parse("text/plain;charset=utf-8"); var expectedBody = "NormalController"; // Act - var response = await client.GetAsync("http://localhost/Normal/ReturnClassName"); + var response = await Client.GetAsync("http://localhost/Normal/ReturnClassName"); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -83,12 +76,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task NoProducesAttribute_ActionReturningAnyObject_RunsUsingDefaultFormatters() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); // Act - var response = await client.GetAsync("http://localhost/Normal/ReturnUser"); + var response = await Client.GetAsync("http://localhost/Normal/ReturnUser"); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -98,14 +89,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ProducesAttributeWithTypeOnly_RunsRegularContentNegotiation() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); var expectedOutput = "{\"Name\":\"John\",\"Address\":\"One Microsoft Way\"}"; + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/UserInfo_ProducesWithTypeOnly"); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Act - var response = await client.GetAsync("http://localhost/Home/UserInfo_ProducesWithTypeOnly"); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -120,16 +110,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ProducesAttribute_WithTypeAndContentType_UsesContentType() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); var expectedContentType = MediaTypeHeaderValue.Parse("application/xml;charset=utf-8"); var expectedOutput = "" + "
One Microsoft Way
John
"; + var request = new HttpRequestMessage( + HttpMethod.Get, + "http://localhost/Home/UserInfo_ProducesWithTypeAndContentType"); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); // Act - var response = await client.GetAsync("http://localhost/Home/UserInfo_ProducesWithTypeAndContentType"); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -144,12 +135,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task NoAcceptAndRequestContentTypeHeaders_UsesFirstFormatterWhichCanWriteType(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); // Act - var response = await client.GetAsync(url + "?input=100"); + var response = await Client.GetAsync(url + "?input=100"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -161,12 +150,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task NoMatchingFormatter_ForTheGivenContentType_Returns406() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Normal/ReturnUser_NoMatchingFormatter"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Normal/ReturnUser_NoMatchingFormatter"); // Assert Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); @@ -193,12 +178,8 @@ END:VCARD string expectedMediaType, string expectedResponseBody) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ProducesWithMediaTypeParameters/" + action); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ProducesWithMediaTypeParameters/" + action); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -214,16 +195,14 @@ END:VCARD [Fact] public async Task ProducesAttribute_OnAction_OverridesTheValueOnClass() { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - + // Arrange // Value on the class is application/json. var expectedContentType = MediaTypeHeaderValue.Parse( "application/custom_ProducesContentBaseController_Action;charset=utf-8"); var expectedBody = "ProducesContentBaseController"; // Act - var response = await client.GetAsync("http://localhost/ProducesContentBase/ReturnClassName"); + var response = await Client.GetAsync("http://localhost/ProducesContentBase/ReturnClassName"); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -234,15 +213,14 @@ END:VCARD [Fact] public async Task ProducesAttribute_OnDerivedClass_OverridesTheValueOnBaseClass() { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange var expectedContentType = MediaTypeHeaderValue.Parse( "application/custom_ProducesContentOnClassController;charset=utf-8"); var expectedBody = "ProducesContentOnClassController"; // Act - var response = await client.GetAsync( - "http://localhost/ProducesContentOnClass/ReturnClassNameWithNoContentTypeOnAction"); + var response = await Client.GetAsync( + "http://localhost/ProducesContentOnClass/ReturnClassNameWithNoContentTypeOnAction"); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -253,14 +231,13 @@ END:VCARD [Fact] public async Task ProducesAttribute_OnDerivedAction_OverridesTheValueOnBaseClass() { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange var expectedContentType = MediaTypeHeaderValue.Parse( "application/custom_NoProducesContentOnClassController_Action;charset=utf-8"); var expectedBody = "NoProducesContentOnClassController"; // Act - var response = await client.GetAsync("http://localhost/NoProducesContentOnClass/ReturnClassName"); + var response = await Client.GetAsync("http://localhost/NoProducesContentOnClass/ReturnClassName"); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -271,14 +248,13 @@ END:VCARD [Fact] public async Task ProducesAttribute_OnDerivedAction_OverridesTheValueOnBaseAction() { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arange var expectedContentType = MediaTypeHeaderValue.Parse( "application/custom_NoProducesContentOnClassController_Action;charset=utf-8"); var expectedBody = "NoProducesContentOnClassController"; // Act - var response = await client.GetAsync("http://localhost/NoProducesContentOnClass/ReturnClassName"); + var response = await Client.GetAsync("http://localhost/NoProducesContentOnClass/ReturnClassName"); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -290,14 +266,12 @@ END:VCARD public async Task ProducesAttribute_OnDerivedClassAndAction_OverridesTheValueOnBaseClass() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedContentType = MediaTypeHeaderValue.Parse( "application/custom_ProducesContentOnClassController_Action;charset=utf-8"); var expectedBody = "ProducesContentOnClassController"; // Act - var response = await client.GetAsync("http://localhost/ProducesContentOnClass/ReturnClassNameContentTypeOnDerivedAction"); + var response = await Client.GetAsync("http://localhost/ProducesContentOnClass/ReturnClassNameContentTypeOnDerivedAction"); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -309,13 +283,11 @@ END:VCARD public async Task ProducesAttribute_IsNotHonored_ForJsonResult() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); var expectedBody = "{\"MethodName\":\"Produces_WithNonObjectResult\"}"; // Act - var response = await client.GetAsync("http://localhost/JsonResult/Produces_WithNonObjectResult"); + var response = await Client.GetAsync("http://localhost/JsonResult/Produces_WithNonObjectResult"); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -329,10 +301,6 @@ END:VCARD public async Task XmlFormatter_SupportedMediaType_DoesNotChangeAcrossRequests() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); - client.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue("utf-8")); var expectedContentType = MediaTypeHeaderValue.Parse("application/xml;charset=utf-8"); var expectedBody = @"
" @@ -340,8 +308,12 @@ END:VCARD for (int i = 0; i < 5; i++) { + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/UserInfo"); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); + request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue("utf-8")); + // Act and Assert - var response = await client.GetAsync("http://localhost/Home/UserInfo"); + var response = await Client.SendAsync(request); Assert.Equal(expectedContentType, response.Content.Headers.ContentType); var body = await response.Content.ReadAsStringAsync(); @@ -355,8 +327,6 @@ END:VCARD public async Task NoMatchOn_RequestContentType_FallsBackOnTypeBasedMatch_MatchFound(string actionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); var expectedBody = "1234"; var targetUri = "http://localhost/FallbackOnTypeBasedMatch/" + actionName + "/?input=1234"; @@ -366,7 +336,7 @@ END:VCARD request.Content = content; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -380,15 +350,13 @@ END:VCARD public async Task ObjectResult_WithStringReturnType_WritesTextPlainFormat(bool matchFormatterOnObjectType) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var targetUri = "http://localhost/FallbackOnTypeBasedMatch/ReturnString?matchFormatterOnObjectType=" + matchFormatterOnObjectType; var request = new HttpRequestMessage(HttpMethod.Get, targetUri); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -403,8 +371,6 @@ END:VCARD public async Task NoMatchOn_RequestContentType_SkipTypeMatchByAddingACustomFormatter(string actionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var targetUri = "http://localhost/FallbackOnTypeBasedMatch/" + actionName + "/?input=1234"; var content = new StringContent("1234", Encoding.UTF8, "application/custom"); var request = new HttpRequestMessage(HttpMethod.Post, targetUri); @@ -412,7 +378,7 @@ END:VCARD request.Content = content; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); @@ -422,8 +388,6 @@ END:VCARD public async Task NoMatchOn_RequestContentType_FallsBackOnTypeBasedMatch_NoMatchFound_Returns406() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var targetUri = "http://localhost/FallbackOnTypeBasedMatch/FallbackGivesNoMatch/?input=1234"; var content = new StringContent("1234", Encoding.UTF8, "application/custom"); var request = new HttpRequestMessage(HttpMethod.Post, targetUri); @@ -431,7 +395,7 @@ END:VCARD request.Content = content; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); @@ -441,12 +405,10 @@ END:VCARD public async Task ProducesAttribute_And_FormatFilterAttribute_Conflicting() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedContentType = MediaTypeHeaderValue.Parse("application/json"); // Act - var response = await client.GetAsync("http://localhost/FormatFilter/MethodWithFormatFilter.json"); + var response = await Client.GetAsync("http://localhost/FormatFilter/MethodWithFormatFilter.json"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -455,12 +417,8 @@ END:VCARD [Fact] public async Task ProducesAttribute_And_FormatFilterAttribute_Collaborating() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/FormatFilter/MethodWithFormatFilter"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/FormatFilter/MethodWithFormatFilter"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ControllerDiscoveryConventionTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ControllerDiscoveryConventionTests.cs index 6adbcd2e1e..c5b07d56df 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ControllerDiscoveryConventionTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ControllerDiscoveryConventionTests.cs @@ -1,36 +1,34 @@ // 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.Collections.Generic; -using System.Linq; using System.Net; +using System.Net.Http; using System.Threading.Tasks; -using ControllerDiscoveryConventionsWebSite; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using Microsoft.Dnx.Runtime; using Xunit; -using Microsoft.AspNet.Mvc.Actions; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ControllerDiscoveryConventionTests + public class ControllerDiscoveryConventionTests : + IClassFixture>, + IClassFixture> { - private const string SiteName = nameof(ControllerDiscoveryConventionsWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ControllerDiscoveryConventionTests( + MvcTestFixture fixture, + FilteredDefaultAssemblyProviderFixture filteredFixture) + { + Client = fixture.Client; + FilteredClient = filteredFixture.Client; + } + + public HttpClient Client { get; } + + public HttpClient FilteredClient { get; } [Fact] public async Task AbstractControllers_AreSkipped() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost/"); - - // Act - var response = await client.GetAsync("Abstract/GetValue"); + // Arrange & Act + var response = await Client.GetAsync("Abstract/GetValue"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -39,13 +37,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TypesDerivingFromControllerBaseTypesThatDoNotReferenceMvc_AreSkipped() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost/"); - - // Act - var response = await client.GetAsync("SqlTransactionManager/GetValue"); + // Arrange & Act + var response = await Client.GetAsync("SqlTransactionManager/GetValue"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -54,13 +47,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TypesMarkedWithNonController_AreSkipped() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost/"); - - // Act - var response = await client.GetAsync("NonController/GetValue"); + // Arrange & Act + var response = await Client.GetAsync("NonController/GetValue"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -69,13 +57,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task PocoTypesWithControllerSuffix_AreDiscovered() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost/"); - - // Act - var response = await client.GetAsync("Poco/GetValue"); + // Arrange & Act + var response = await Client.GetAsync("Poco/GetValue"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -85,13 +68,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TypesDerivingFromTypesWithControllerSuffix_AreDiscovered() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost/"); - - // Act - var response = await client.GetAsync("ChildOfAbstract/GetValue"); + // Arrange & Act + var response = await Client.GetAsync("ChildOfAbstract/GetValue"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -101,45 +79,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TypesDerivingFromApiController_AreDiscovered() { - // Arrange - // TestHelper.CreateServer normally replaces the DefaultAssemblyProvider with a provider that - // limits the set of candidate assemblies to the executing application. For this test, - // we'll switch it back to using a filtered default assembly provider. - var server = TestHelper.CreateServer( - _app, - SiteName, - services => - { - _configureServices(services); - services.AddTransient(); - }); - - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost/"); - - // Act - var response = await client.GetAsync("PersonApi/GetValue"); + // Arrange & Act + var response = await FilteredClient.GetAsync("PersonApi/GetValue"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("PersonApi", await response.Content.ReadAsStringAsync()); } - - private class FilteredDefaultAssemblyProvider : DefaultAssemblyProvider - { - public FilteredDefaultAssemblyProvider(ILibraryManager libraryManager) - : base(libraryManager) - { - - } - - protected override IEnumerable GetCandidateLibraries() - { - var libraries = base.GetCandidateLibraries(); - // Filter out other WebSite projects - return libraries.Where(library => !library.Name.Contains("WebSite") || - library.Name.Equals(nameof(ControllerDiscoveryConventionsWebSite), StringComparison.Ordinal)); - } - } } } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ControllerFromServicesTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ControllerFromServicesTests.cs index 1666f2bc83..f710010db2 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ControllerFromServicesTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ControllerFromServicesTests.cs @@ -12,26 +12,29 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ControllerFromServicesTest + public class ControllerFromServicesTest : IClassFixture> { - private const string SiteName = nameof(ControllersFromServicesWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Func _configureServices = new Startup().ConfigureServices; + public ControllerFromServicesTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task ControllersWithConstructorInjectionAreCreatedAndActivated() { // Arrange var expected = "/constructorinjection 14 test-header-value"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.DefaultRequestHeaders.TryAddWithoutValidation("Test-Header", "test-header-value"); + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/constructorinjection?value=14"); + request.Headers.TryAddWithoutValidation("Test-Header", "test-header-value"); // Act - var response = await client.GetStringAsync("http://localhost/constructorinjection?value=14"); + var response = await Client.SendAsync(request); + var responseText = await response.Content.ReadAsStringAsync(); // Assert - Assert.Equal(expected, response); + Assert.Equal(expected, responseText); } [Fact] @@ -39,11 +42,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = "No schedules available for 23"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var response = await client.GetStringAsync("http://localhost/schedule/23"); + var response = await Client.GetStringAsync("http://localhost/schedule/23"); // Assert Assert.Equal(expected, response); @@ -54,11 +55,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = "4"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var response = await client.GetStringAsync("http://localhost/inventory/"); + var response = await Client.GetStringAsync("http://localhost/inventory/"); // Assert Assert.Equal(expected, response); @@ -69,12 +68,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = "Updated record employee303"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var response = await client.PutAsync("http://localhost/employee/update_records?recordId=employee303", - new StringContent(string.Empty)); + var response = await Client.PutAsync( + "http://localhost/employee/update_records?recordId=employee303", + new StringContent(string.Empty)); // Assert response.EnsureSuccessStatusCode(); @@ -86,12 +84,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = "Saved record employee #211"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var response = await client.PostAsync("http://localhost/employeerecords/save/211", - new StringContent(string.Empty)); + var response = await Client.PostAsync( + "http://localhost/employeerecords/save/211", + new StringContent(string.Empty)); // Assert response.EnsureSuccessStatusCode(); @@ -105,12 +102,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("ClientUIStub/GetClientContent/5")] public async Task AddControllersFromServices_UsesControllerDiscoveryContentions(string action) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/" + action); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/" + action); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/CorsMiddlewareTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/CorsMiddlewareTests.cs index 74ec919a8a..d1f8e063ce 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/CorsMiddlewareTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/CorsMiddlewareTests.cs @@ -4,6 +4,7 @@ using System; using System.Linq; using System.Net; +using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Cors.Core; @@ -12,11 +13,14 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class CorsMiddlewareTests + public class CorsMiddlewareTests : IClassFixture> { - private const string SiteName = nameof(CorsMiddlewareWebSite); - private readonly Action _app = new CorsMiddlewareWebSite.Startup().Configure; - private readonly Action _configureServices = new CorsMiddlewareWebSite.Startup().ConfigureServices; + public CorsMiddlewareTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("GET")] @@ -25,16 +29,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ResourceWithSimpleRequestPolicy_Allows_SimpleRequests(string method) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var origin = "http://example.com"; - - var requestBuilder = server - .CreateRequest("http://localhost/CorsMiddleware/GetExclusiveContent") - .AddHeader(CorsConstants.Origin, origin); + var request = new HttpRequestMessage( + new HttpMethod(method), + "http://localhost/CorsMiddleware/GetExclusiveContent"); + request.Headers.Add(CorsConstants.Origin, origin); // Act - var response = await requestBuilder.SendAsync(method); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -54,18 +56,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task PolicyFailed_Disallows_PreFlightRequest(string method) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var request = new HttpRequestMessage( + new HttpMethod(CorsConstants.PreflightHttpMethod), + "http://localhost/CorsMiddleware/GetExclusiveContent"); - // Adding a custom header makes it a non simple request. - var requestBuilder = server - .CreateRequest("http://localhost/CorsMiddleware/GetExclusiveContent") - .AddHeader(CorsConstants.Origin, "http://example.com") - .AddHeader(CorsConstants.AccessControlRequestMethod, method) - .AddHeader(CorsConstants.AccessControlRequestHeaders, "Custom"); + // Adding a custom header makes it a non-simple request. + request.Headers.Add(CorsConstants.Origin, "http://example.com"); + request.Headers.Add(CorsConstants.AccessControlRequestMethod, method); + request.Headers.Add(CorsConstants.AccessControlRequestHeaders, "Custom"); // Act - var response = await requestBuilder.SendAsync(CorsConstants.PreflightHttpMethod); + var response = await Client.SendAsync(request); // Assert // Middleware applied the policy and since that did not pass, there were no access control headers. @@ -81,16 +82,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task PolicyFailed_Allows_ActualRequest_WithMissingResponseHeaders() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var request = new HttpRequestMessage(HttpMethod.Put, "http://localhost/CorsMiddleware/GetExclusiveContent"); // Adding a custom header makes it a non simple request. - var requestBuilder = server - .CreateRequest("http://localhost/CorsMiddleware/GetExclusiveContent") - .AddHeader(CorsConstants.Origin, "http://example2.com"); + request.Headers.Add(CorsConstants.Origin, "http://example2.com"); // Act - var response = await requestBuilder.SendAsync("PUT"); + var response = await Client.SendAsync(request); // Assert // Middleware applied the policy and since that did not pass, there were no access control headers. diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/CorsTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/CorsTests.cs index 7e27920d9f..e9979f9c74 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/CorsTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/CorsTests.cs @@ -1,22 +1,23 @@ // 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.Linq; using System.Net; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Cors.Core; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class CorsTests + public class CorsTests : IClassFixture> { - private const string SiteName = nameof(CorsWebSite); - private readonly Action _app = new CorsWebSite.Startup().Configure; - private readonly Action _configureServices = new CorsWebSite.Startup().ConfigureServices; + public CorsTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("GET")] @@ -25,16 +26,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ResourceWithSimpleRequestPolicy_Allows_SimpleRequests(string method) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var origin = "http://example.com"; - - var requestBuilder = server - .CreateRequest("http://localhost/Cors/GetBlogComments") - .AddHeader(CorsConstants.Origin, origin); + var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Cors/GetBlogComments"); + request.Headers.Add(CorsConstants.Origin, origin); // Act - var response = await requestBuilder.SendAsync(method); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -54,18 +51,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task PolicyFailed_Disallows_PreFlightRequest(string method) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var request = new HttpRequestMessage( + new HttpMethod(CorsConstants.PreflightHttpMethod), + "http://localhost/Cors/GetBlogComments"); - // Adding a custom header makes it a non simple request. - var requestBuilder = server - .CreateRequest("http://localhost/Cors/GetBlogComments") - .AddHeader(CorsConstants.Origin, "http://example.com") - .AddHeader(CorsConstants.AccessControlRequestMethod, method) - .AddHeader(CorsConstants.AccessControlRequestHeaders, "Custom"); + // Adding a custom header makes it a non-simple request. + request.Headers.Add(CorsConstants.Origin, "http://example.com"); + request.Headers.Add(CorsConstants.AccessControlRequestMethod, method); + request.Headers.Add(CorsConstants.AccessControlRequestHeaders, "Custom"); // Act - var response = await requestBuilder.SendAsync(CorsConstants.PreflightHttpMethod); + var response = await Client.SendAsync(request); // Assert // MVC applied the policy and since that did not pass, there were no access control headers. @@ -81,17 +77,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task SuccessfulCorsRequest_AllowsCredentials_IfThePolicyAllowsCredentials() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var request = new HttpRequestMessage( + HttpMethod.Put, + "http://localhost/Cors/EditUserComment?userComment=abcd"); - // Adding a custom header makes it a non simple request. - var requestBuilder = server - .CreateRequest("http://localhost/Cors/EditUserComment?userComment=abcd") - .AddHeader(CorsConstants.Origin, "http://example.com") - .AddHeader(CorsConstants.AccessControlExposeHeaders, "exposed1,exposed2"); + // Adding a custom header makes it a non-simple request. + request.Headers.Add(CorsConstants.Origin, "http://example.com"); + request.Headers.Add(CorsConstants.AccessControlExposeHeaders, "exposed1,exposed2"); // Act - var response = await requestBuilder.SendAsync("PUT"); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -114,18 +109,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task SuccessfulPreflightRequest_AllowsCredentials_IfThePolicyAllowsCredentials() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var request = new HttpRequestMessage( + new HttpMethod(CorsConstants.PreflightHttpMethod), + "http://localhost/Cors/EditUserComment?userComment=abcd"); - // Adding a custom header makes it a non simple request. - var requestBuilder = server - .CreateRequest("http://localhost/Cors/EditUserComment?userComment=abcd") - .AddHeader(CorsConstants.Origin, "http://example.com") - .AddHeader(CorsConstants.AccessControlRequestMethod, "PUT") - .AddHeader(CorsConstants.AccessControlRequestHeaders, "header1,header2"); + // Adding a custom header makes it a non-simple request. + request.Headers.Add(CorsConstants.Origin, "http://example.com"); + request.Headers.Add(CorsConstants.AccessControlRequestMethod, "PUT"); + request.Headers.Add(CorsConstants.AccessControlRequestHeaders, "header1,header2"); // Act - var response = await requestBuilder.SendAsync(CorsConstants.PreflightHttpMethod); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -151,16 +145,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task PolicyFailed_Allows_ActualRequest_WithMissingResponseHeaders() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var request = new HttpRequestMessage(HttpMethod.Put, "http://localhost/Cors/GetUserComments"); // Adding a custom header makes it a non simple request. - var requestBuilder = server - .CreateRequest("http://localhost/Cors/GetUserComments") - .AddHeader(CorsConstants.Origin, "http://example2.com"); + request.Headers.Add(CorsConstants.Origin, "http://example2.com"); // Act - var response = await requestBuilder.SendAsync("PUT"); + var response = await Client.SendAsync(request); // Assert // MVC applied the policy and since that did not pass, there were no access control headers. @@ -179,16 +170,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task DisableCors_ActionsCanOverride_ControllerLevel(string method) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Cors/GetExclusiveContent"); // Exclusive content is not available on other sites. - var requestBuilder = server - .CreateRequest("http://localhost/Cors/GetExclusiveContent") - .AddHeader(CorsConstants.Origin, "http://example.com"); + request.Headers.Add(CorsConstants.Origin, "http://example.com"); // Act - var response = await requestBuilder.SendAsync(method); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -206,18 +194,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task DisableCors_PreFlight_ActionsCanOverride_ControllerLevel(string method) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var request = new HttpRequestMessage( + new HttpMethod(CorsConstants.PreflightHttpMethod), + "http://localhost/Cors/GetExclusiveContent"); // Exclusive content is not available on other sites. - var requestBuilder = server - .CreateRequest("http://localhost/Cors/GetExclusiveContent") - .AddHeader(CorsConstants.Origin, "http://example.com") - .AddHeader(CorsConstants.AccessControlRequestMethod, method) - .AddHeader(CorsConstants.AccessControlRequestHeaders, "Custom"); + request.Headers.Add(CorsConstants.Origin, "http://example.com"); + request.Headers.Add(CorsConstants.AccessControlRequestMethod, method); + request.Headers.Add(CorsConstants.AccessControlRequestHeaders, "Custom"); // Act - var response = await requestBuilder.SendAsync(CorsConstants.PreflightHttpMethod); + var response = await Client.SendAsync(request); // Assert // Since there are no response headers, the client should step in to block the content. diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/CustomRouteTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/CustomRouteTest.cs index 0aa5f13f20..cacb941b95 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/CustomRouteTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/CustomRouteTest.cs @@ -1,22 +1,21 @@ // 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.Net; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class CustomRouteTest + public class CustomRouteTest : IClassFixture> { - private const string SiteName = nameof(CustomRouteWebSite); - private readonly Action _app = new CustomRouteWebSite.Startup().Configure; - private readonly Action _configureServices = new CustomRouteWebSite.Startup().ConfigureServices; + public CustomRouteTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + public HttpClient Client { get; } [Theory] [InlineData("Javier", "Hola from Spain.")] @@ -25,14 +24,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task RouteToLocale_ConventionalRoute_BasedOnUser(string user, string expected) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/CustomRoute_Products/Index"); request.Headers.Add("User", user); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -47,14 +43,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task RouteWithAttributeRoute_IncludesLocale_BasedOnUser(string user, string expected) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/CustomRoute_Orders/5"); request.Headers.Add("User", user); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/CustomUrlHelperTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/CustomUrlHelperTests.cs index c0a9e4dc69..ab868995f8 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/CustomUrlHelperTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/CustomUrlHelperTests.cs @@ -1,11 +1,9 @@ // 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.Net; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests @@ -17,26 +15,25 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests /// 1. Based on configuration, generate Content urls pointing to local or a CDN server /// 2. Based on configuration, generate lower case urls /// - public class CustomUrlHelperTests + public class CustomUrlHelperTests : IClassFixture> { - private const string SiteName = nameof(UrlHelperWebSite); - private readonly Action _app = new UrlHelperWebSite.Startup().Configure; - private readonly Action _configureServices = new UrlHelperWebSite.Startup().ConfigureServices; - private const string _cdnServerBaseUrl = "http://cdn.contoso.com"; + public CustomUrlHelperTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } + [Fact] public async Task CustomUrlHelper_GeneratesUrlFromController() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/UrlContent"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/UrlContent"); var responseData = await response.Content.ReadAsStringAsync(); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(_cdnServerBaseUrl + "/bootstrap.min.css", responseData); } @@ -44,15 +41,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task CustomUrlHelper_GeneratesUrlFromView() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/Index"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/Index"); var responseData = await response.Content.ReadAsStringAsync(); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Contains(_cdnServerBaseUrl + "/bootstrap.min.css", responseData); } @@ -62,15 +55,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("http://localhost/Home/LinkByUrlAction", "/home/urlcontent")] public async Task LowercaseUrls_LinkGeneration(string url, string expectedLink) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync(url); + // Arrange & Act + var response = await Client.GetAsync(url); var responseData = await response.Content.ReadAsStringAsync(); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedLink, responseData, ignoreCase: false); } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultOrderTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultOrderTest.cs index a7063847f6..f14203c94f 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultOrderTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultOrderTest.cs @@ -3,23 +3,25 @@ using System; using System.Net; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.ActionConstraints; using Microsoft.AspNet.Mvc.Actions; using Microsoft.AspNet.Mvc.ApiExplorer; using Microsoft.AspNet.Mvc.Filters; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { // Tests that various MVC services have the correct order. - public class DefaultOrderTest + public class DefaultOrderTest : IClassFixture> { - private const string SiteName = nameof(BasicWebSite); - private readonly Action _app = new BasicWebSite.Startup().Configure; - private readonly Action _configureServices = new BasicWebSite.Startup().ConfigureServices; + public DefaultOrderTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData(typeof(IActionDescriptorProvider), typeof(ControllerActionDescriptorProvider), -1000)] @@ -30,9 +32,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ServiceOrder_GetOrder(Type serviceType, Type actualType, int order) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/Order/GetServiceOrder?serviceType=" + serviceType.AssemblyQualifiedName; if (actualType != null) @@ -41,7 +40,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests } // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); var content = await response.Content.ReadAsStringAsync(); // Assert diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultValuesTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultValuesTest.cs index ef6c805e2d..a5edd894a5 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultValuesTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultValuesTest.cs @@ -1,33 +1,30 @@ // 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.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class DefaultValuesTest + public class DefaultValuesTest : IClassFixture> { - private const string SiteName = nameof(BasicWebSite); - private readonly Action _app = new BasicWebSite.Startup().Configure; - private readonly Action _configureServices = new BasicWebSite.Startup().ConfigureServices; + public DefaultValuesTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task Controller_WithDefaultValueAttribut_ReturnsDefault() { // Arrange var expected = "hello"; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/DefaultValues/EchoValue_DefaultValueAttribute"; // Act - var response = await client.GetStringAsync(url); + var response = await Client.GetStringAsync(url); // Assert Assert.Equal(expected, response); @@ -38,14 +35,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = "cool"; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/DefaultValues/EchoValue_DefaultValueAttribute?input=cool"; // Act - var response = await client.GetStringAsync(url); + var response = await Client.GetStringAsync(url); // Assert Assert.Equal(expected, response); @@ -56,14 +49,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = "world"; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/DefaultValues/EchoValue_DefaultParameterValue"; // Act - var response = await client.GetStringAsync(url); + var response = await Client.GetStringAsync(url); // Assert Assert.Equal(expected, response); @@ -74,14 +63,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = "cool"; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/DefaultValues/EchoValue_DefaultParameterValue?input=cool"; // Act - var response = await client.GetStringAsync(url); + var response = await Client.GetStringAsync(url); // Assert Assert.Equal(expected, response); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/DependencyResolverTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/DependencyResolverTests.cs index 06f4e829b6..5ed21ef7d9 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/DependencyResolverTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/DependencyResolverTests.cs @@ -1,20 +1,20 @@ // 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.Net.Http; using System.Threading.Tasks; -using AutofacWebSite; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class DependencyResolverTests + public class DependencyResolverTests : IClassFixture> { - private const string SiteName = nameof(AutofacWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Func _configureServices = new Startup().ConfigureServices; + public DependencyResolverTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("http://localhost/di", "

Builder Output: Hello from builder.

")] @@ -22,14 +22,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AutofacDIContainerCanUseMvc(string url, string expectedResponseBody) { // Arrange & Act & Assert (does not throw) - // This essentially calls into the Startup.Configuration method - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - // Make a request to start resolving DI pieces - var response = await server.CreateClient().GetAsync(url); + var responseText = await Client.GetStringAsync(url); - var actualResponseBody = await response.Content.ReadAsStringAsync(); - Assert.Equal(expectedResponseBody, actualResponseBody); + Assert.Equal(expectedResponseBody, responseText); } } } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/DirectivesTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/DirectivesTest.cs index 0d76e5105f..84e4a05e2c 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/DirectivesTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/DirectivesTest.cs @@ -1,30 +1,30 @@ // 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.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using RazorWebSite; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class DirectivesTest + public class DirectivesTest : IClassFixture> { - private const string SiteName = nameof(RazorWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public DirectivesTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task ViewsInheritsUsingsAndInjectDirectivesFromViewStarts() { + // Arrange var expected = @"Hello Person1"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync("http://localhost/Directives/ViewInheritsInjectAndUsingsFromViewImports"); + var body = await Client.GetStringAsync( + "http://localhost/Directives/ViewInheritsInjectAndUsingsFromViewImports"); // Assert Assert.Equal(expected, body.Trim()); @@ -33,12 +33,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ViewInheritsBasePageFromViewStarts() { + // Arrange var expected = @"WriteLiteral says:layout:Write says:Write says:Hello Person2"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync("http://localhost/Directives/ViewInheritsBasePageFromViewImports"); + var body = await Client.GetStringAsync("http://localhost/Directives/ViewInheritsBasePageFromViewImports"); // Assert Assert.Equal(expected, body.Trim()); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ErrorPageTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ErrorPageTests.cs index be169b9d99..a14bffb202 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ErrorPageTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ErrorPageTests.cs @@ -1,14 +1,10 @@ // 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 System.Net; +using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; -using ErrorPageMiddlewareWebSite; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests @@ -16,11 +12,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests /// /// Functional test to verify the error reporting of Razor compilation by diagnostic middleware. /// - public class ErrorPageTests + public class ErrorPageTests : IClassFixture> { - private const string SiteName = nameof(ErrorPageMiddlewareWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ErrorPageTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("CompilationFailure", "Cannot implicitly convert type 'int' to 'string'")] @@ -31,12 +30,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CompilationFailuresAreListedByErrorPageMiddleware(string action, string expected) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); // Act - var response = await client.GetAsync("http://localhost/" + action); + var response = await Client.GetAsync("http://localhost/" + action); // Assert Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -52,12 +49,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Arrange var expectedMessage = "The type or namespace name 'NamespaceDoesNotExist' could not be found (" + "are you missing a using directive or an assembly reference?)"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); // Act - var response = await client.GetAsync("http://localhost/ErrorFromViewImports"); + var response = await Client.GetAsync("http://localhost/ErrorFromViewImports"); // Assert Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/FileResultTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/FileResultTests.cs index 163c74b7fa..64716ffd67 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/FileResultTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/FileResultTests.cs @@ -1,33 +1,30 @@ // 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.Net; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class FileResultTests + public class FileResultTests : IClassFixture> { - private const string SiteName = nameof(FilesWebSite); - private readonly Action _app = new FilesWebSite.Startup().Configure; - private readonly Action _configureServices = new FilesWebSite.Startup().ConfigureServices; + public FileResultTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [ConditionalFact] // https://github.com/aspnet/Mvc/issues/2727 [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task FileFromDisk_CanBeEnabled_WithMiddleware() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/DownloadFiles/DowloadFromDisk"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/DownloadFiles/DowloadFromDisk"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -45,12 +42,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task FileFromDisk_ReturnsFileWithFileName() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/DownloadFiles/DowloadFromDiskWithFileName"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/DownloadFiles/DowloadFromDiskWithFileName"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -70,12 +63,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FileFromStream_ReturnsFile() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/DownloadFiles/DowloadFromStream"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/DownloadFiles/DowloadFromStream"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -91,12 +80,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FileFromStream_ReturnsFileWithFileName() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/DownloadFiles/DowloadFromStreamWithFileName"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/DownloadFiles/DowloadFromStreamWithFileName"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -116,12 +101,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FileFromBinaryData_ReturnsFile() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/DownloadFiles/DowloadFromBinaryData"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/DownloadFiles/DowloadFromBinaryData"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -137,12 +118,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FileFromBinaryData_ReturnsFileWithFileName() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/DownloadFiles/DowloadFromBinaryDataWithFileName"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/DownloadFiles/DowloadFromBinaryDataWithFileName"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -163,12 +140,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FileFromEmbeddedResources_ReturnsFileWithFileName() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedBody = "Sample text file as embedded resource."; // Act - var response = await client.GetAsync("http://localhost/EmbeddedFiles/DownloadFileWithFileName"); + var response = await Client.GetAsync("http://localhost/EmbeddedFiles/DownloadFileWithFileName"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/FilteredDefaultAssemblyProviderFixtureOfT.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/FilteredDefaultAssemblyProviderFixtureOfT.cs new file mode 100644 index 0000000000..ad4ce9415f --- /dev/null +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/FilteredDefaultAssemblyProviderFixtureOfT.cs @@ -0,0 +1,41 @@ +// 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.Collections.Generic; +using System.Linq; +using Microsoft.AspNet.Mvc.Actions; +using Microsoft.Dnx.Runtime; +using Microsoft.Framework.DependencyInjection; + +namespace Microsoft.AspNet.Mvc.FunctionalTests +{ + public class FilteredDefaultAssemblyProviderFixture : MvcTestFixture + where TStartup : new() + { + protected override void AddAdditionalServices(IServiceCollection services) + { + // TestHelper.CreateServer normally replaces the DefaultAssemblyProvider with a provider that limits the + // set of candidate assemblies to the executing application. Switch it back to using a filtered default + // assembly provider. + services.AddTransient(); + } + + private class FilteredDefaultAssemblyProvider : DefaultAssemblyProvider + { + public FilteredDefaultAssemblyProvider(ILibraryManager libraryManager) + : base(libraryManager) + { + } + + protected override IEnumerable GetCandidateLibraries() + { + var libraries = base.GetCandidateLibraries(); + + // Filter out other WebSite projects + return libraries.Where(library => !library.Name.Contains("WebSite") || + library.Name.Equals(nameof(ControllerDiscoveryConventionsWebSite), StringComparison.Ordinal)); + } + } + } +} diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/FiltersTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/FiltersTest.cs index a61a847dac..b1dcae76c3 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/FiltersTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/FiltersTest.cs @@ -7,19 +7,19 @@ using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.Formatters.Xml; -using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class FiltersTest + public class FiltersTest : IClassFixture> { - private const string SiteName = nameof(FiltersWebSite); - private readonly Action _app = new FiltersWebSite.Startup().Configure; - private readonly Action _configureServices = new FiltersWebSite.Startup().ConfigureServices; + public FiltersTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } // A controller can only be an action filter and result filter, so we don't have entries // for the other filter types implemented by the controller. @@ -27,9 +27,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ListAllFilters() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var expected = new string[] { "Global Authorization Filter - OnAuthorization", @@ -61,7 +58,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.GetAsync("http://localhost/Products/GetPrice/5"); + var response = await Client.GetAsync("http://localhost/Products/GetPrice/5"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -82,12 +79,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AnonymousUsersAreBlocked() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Anonymous/GetHelloWorld"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Anonymous/GetHelloWorld"); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -96,12 +89,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AllowsAnonymousUsersToAccessController() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/RandomNumber/GetRandomNumber"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/RandomNumber/GetRandomNumber"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -115,13 +104,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("ApiManagers")] public async Task CanAuthorize(string testAction) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( - "http://localhost/AuthorizeUser/"+testAction); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/AuthorizeUser/"+testAction); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -131,13 +115,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AllowAnonymousOverridesAuthorize() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( - "http://localhost/AuthorizeUser/AlwaysCanCallAllowAnonymous"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/AuthorizeUser/AlwaysCanCallAllowAnonymous"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -147,13 +126,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ImpossiblePolicyFailsAuthorize() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( - "http://localhost/AuthorizeUser/Impossible"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/AuthorizeUser/Impossible"); // Assert Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); @@ -162,12 +136,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ServiceFilterUsesRegisteredServicesAsFilter() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/RandomNumber/GetRandomNumber"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/RandomNumber/GetRandomNumber"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -178,12 +148,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ServiceFilterThrowsIfServiceIsNotRegistered() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/RandomNumber/GetAuthorizedRandomNumber"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var exception = response.GetServerException(); @@ -194,12 +162,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task TypeFilterInitializesArguments() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/RandomNumber/GetModifiedRandomNumber?randomNumber=10"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -210,12 +176,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task TypeFilterThrowsIfServicesAreNotRegistered() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/RandomNumber/GetHalfOfModifiedRandomNumber?randomNumber=3"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var exception = response.GetServerException(); @@ -225,14 +189,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ActionFilterOverridesActionExecuted() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/XmlSerializer/GetDummyClass?sampleInput=10"); - // Act - var response = await client.GetAsync("http://localhost/XmlSerializer/GetDummyClass?sampleInput=10"); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); XmlAssert.Equal("10", @@ -242,12 +202,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResultFilterOverridesOnResultExecuting() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/DummyClass/GetDummyClass"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/DummyClass/GetDummyClass"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -259,12 +215,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResultFilterOverridesOnResultExecuted() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/DummyClass/GetEmptyActionResult"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/DummyClass/GetEmptyActionResult"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -276,12 +228,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task OrderOfExecutionOfFilters_WhenOrderAttribute_IsNotMentioned() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/GetSampleString"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/GetSampleString"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -294,12 +242,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ExceptionsHandledInActionFilters_WillNotShortCircuitResultFilters() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/ThrowExceptionAndHandleInActionFilter"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/ThrowExceptionAndHandleInActionFilter"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -311,12 +255,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ExceptionFilter_OnAction_ShortCircuitsResultFilters() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/ThrowExcpetion"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/ThrowExcpetion"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -330,12 +270,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GlobalExceptionFilter_HandlesAnException() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Exception/GetError?error=RandomError"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Exception/GetError?error=RandomError"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -347,12 +283,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ExceptionFilter_Scope() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ExceptionOrder/GetError"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ExceptionOrder/GetError"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -368,12 +300,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ActionFilter_Scope() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ActionFilter/GetHelloWorld"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ActionFilter/GetHelloWorld"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -395,12 +323,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResultFilter_Scope() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ResultFilter/GetHelloWorld"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ResultFilter/GetHelloWorld"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -418,12 +342,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FiltersWithOrder() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/RandomNumber/GetOrderedRandomNumber"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/RandomNumber/GetOrderedRandomNumber"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -435,12 +355,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ActionFiltersWithOrder() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/ActionFilterOrder"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/ActionFilterOrder"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -456,12 +372,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResultFiltersWithOrder() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/ResultFilterOrder"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/ResultFilterOrder"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -475,12 +387,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ActionFilterShortCircuitsAction() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/DummyClass/ActionNeverGetsExecuted"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/DummyClass/ActionNeverGetsExecuted"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -492,12 +400,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResultFilterShortCircuitsResult() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/DummyClass/ResultNeverGetsExecuted"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/DummyClass/ResultNeverGetsExecuted"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -509,12 +413,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ExceptionFilterShortCircuitsAnotherExceptionFilter() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/ThrowRandomExcpetion"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/ThrowRandomExcpetion"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -526,12 +426,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ThrowingFilters_ResultFilter_NotHandledByGlobalExceptionFilter() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/ThrowingResultFilter"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/ThrowingResultFilter"); // Assert var exception = response.GetServerException(); @@ -543,12 +439,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ThrowingFilters_ActionFilter_HandledByGlobalExceptionFilter() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/ThrowingActionFilter"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/ThrowingActionFilter"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -560,12 +452,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ThrowingFilters_AuthFilter_NotHandledByGlobalExceptionFilter() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/ThrowingAuthorizationFilter"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/ThrowingAuthorizationFilter"); // Assert var exception = response.GetServerException(); @@ -577,12 +465,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ThrowingExceptionFilter_ExceptionFilter_NotHandledByGlobalExceptionFilter() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/ThrowingExceptionFilter"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/ThrowingExceptionFilter"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -594,15 +478,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var input = "{ sampleInt: 10 }"; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/ResourceFilter/Post"); request.Content = new StringContent(input, Encoding.UTF8, "application/json"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert // Uses formatters from options. @@ -617,15 +497,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var input = "{ sampleInt: 10 }"; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/ResourceFilter/Get"); request.Content = new StringContent(input, Encoding.UTF8, "application/json"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -638,15 +514,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var input = "{ sampleInt: 10 }"; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Json"); request.Content = new StringContent(input, Encoding.UTF8, "application/json"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -659,15 +531,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var input = "{ sampleInt: 10 }"; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Json"); request.Content = new StringContent(input, Encoding.UTF8, "application/json"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -683,16 +551,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests "10" + ""; - // There's nothing that can deserialize the body, so the result contains the default - // value. - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - + // There's nothing that can deserialize the body, so the result contains the default value. var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Json"); request.Content = new StringContent(input, Encoding.UTF8, "application/xml"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/FlushPointTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/FlushPointTest.cs index c862a75db3..8eccef31d6 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/FlushPointTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/FlushPointTest.cs @@ -182,7 +182,7 @@ More content from layout", Assert.Equal("Initial content", GetTrimmedString(stream)); waitService.WaitForServer(); - //Assert - 2 + // Assert - 2 try { GetTrimmedString(stream); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/FormatFilterTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/FormatFilterTest.cs index c026b687a6..e9d166e035 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/FormatFilterTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/FormatFilterTest.cs @@ -1,30 +1,27 @@ // 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.Net; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class FormatFilterTest + public class FormatFilterTest : IClassFixture> { - private const string SiteName = nameof(FormatFilterWebSite); - private readonly Action _app = new FormatFilterWebSite.Startup().Configure; - private readonly Action _configureServices = new FormatFilterWebSite.Startup().ConfigureServices; + public FormatFilterTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task FormatFilter_NoExtensionInRequest() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/FormatFilter/GetProduct/5"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/FormatFilter/GetProduct/5"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -34,12 +31,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FormatFilter_ExtensionInRequest_Default() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/FormatFilter/GetProduct/5.json"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/FormatFilter/GetProduct/5.json"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -49,12 +42,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FormatFilter_ExtensionInRequest_Optional() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/FormatFilter/GetProduct.json"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/FormatFilter/GetProduct.json"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -64,12 +53,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FormatFilter_ExtensionInRequest_Custom() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/FormatFilter/GetProduct/5.custom"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/FormatFilter/GetProduct/5.custom"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -79,12 +64,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FormatFilter_ExtensionInRequest_CaseInsensitivity() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/FormatFilter/GetProduct/5.Custom"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/FormatFilter/GetProduct/5.Custom"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -94,12 +75,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FormatFilter_ExtensionInRequest_NonExistant() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/FormatFilter/GetProduct/5.xml"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/FormatFilter/GetProduct/5.xml"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -108,12 +85,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FormatFilter_And_ProducesFilter_Match() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/FormatFilter/ProducesMethod/5.json"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/FormatFilter/ProducesMethod/5.json"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -123,12 +96,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FormatFilter_And_ProducesFilter_Conflict() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/FormatFilter/ProducesMethod/5.xml"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/FormatFilter/ProducesMethod/5.xml"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -137,12 +106,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FormatFilter_And_OverrideProducesFilter() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ProducesOverride/ReturnClassName"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ProducesOverride/ReturnClassName"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/HtmlGenerationTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/HtmlGenerationTest.cs index 8d4d3a49f0..0508767165 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/HtmlGenerationTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/HtmlGenerationTest.cs @@ -9,25 +9,37 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading.Tasks; -using HtmlGenerationWebSite; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.Internal; using Microsoft.AspNet.Mvc.TagHelpers; -using Microsoft.AspNet.Testing; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection.Extensions; -using Microsoft.Framework.WebEncoders; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class HtmlGenerationTest + public class HtmlGenerationTest : + IClassFixture>, + IClassFixture> { private const string SiteName = nameof(HtmlGenerationWebSite); private static readonly Assembly _resourcesAssembly = typeof(HtmlGenerationTest).GetTypeInfo().Assembly; - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + private readonly Action _app = new HtmlGenerationWebSite.Startup().Configure; + private readonly Action _configureServices = + new HtmlGenerationWebSite.Startup().ConfigureServices; + + public HtmlGenerationTest( + MvcTestFixture fixture, + MvcEncodedTestFixture encodedFixture) + { + Client = fixture.Client; + EncodedClient = encodedFixture.Client; + } + + public HttpClient Client { get; } + + public HttpClient EncodedClient { get; } [Theory] [InlineData("Index", null)] @@ -60,8 +72,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task HtmlGenerationWebSite_GeneratesExpectedResults(string action, string antiforgeryPath) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".html"; var expectedContent = @@ -69,7 +79,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Act // The host is not important as everything runs in memory and tests are isolated from each other. - var response = await client.GetAsync("http://localhost/HtmlGeneration_Home/" + action); + var response = await Client.GetAsync("http://localhost/HtmlGeneration_Home/" + action); var responseContent = await response.Content.ReadAsStringAsync(); // Assert @@ -119,14 +129,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task HtmlGenerationWebSite_GenerateEncodedResults(string action, string antiforgeryPath) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, services => - { - _configureServices(services); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - }); - var client = server.CreateClient(); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".Encoded.html"; var expectedContent = @@ -134,7 +136,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Act // The host is not important as everything runs in memory and tests are isolated from each other. - var response = await client.GetAsync("http://localhost/HtmlGeneration_Home/" + action); + var response = await EncodedClient.GetAsync("http://localhost/HtmlGeneration_Home/" + action); var responseContent = await response.Content.ReadAsStringAsync(); // Assert @@ -176,8 +178,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ValidationTagHelpers_GeneratesExpectedSpansAndDivs() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Customer.Index.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); @@ -194,7 +194,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var responseContent = await response.Content.ReadAsStringAsync(); // Assert @@ -224,10 +224,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Arrange var assertFile = "compiler/resources/CacheTagHelper_CanCachePortionsOfViewsPartialViewsAndViewComponents.Assert"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost"); - client.DefaultRequestHeaders.Add("Locale", "North"); var outputFile1 = assertFile + "1.txt"; var expected1 = @@ -242,8 +238,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Act - 1 // Verify that content gets cached based on vary-by-params var targetUrl = "/catalog?categoryId=1&correlationid=1"; - var response1 = await client.GetStringAsync(targetUrl); - var response2 = await client.GetStringAsync(targetUrl); + var request = RequestWithLocale(targetUrl, "North"); + var response1 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); + request = RequestWithLocale(targetUrl, "North"); + var response2 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); // Assert - 1 #if GENERATE_BASELINES @@ -256,8 +254,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Act - 2 // Verify content gets changed in partials when one of the vary by parameters is changed targetUrl = "/catalog?categoryId=3&correlationid=2"; - var response3 = await client.GetStringAsync(targetUrl); - var response4 = await client.GetStringAsync(targetUrl); + request = RequestWithLocale(targetUrl, "North"); + var response3 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); + request = RequestWithLocale(targetUrl, "North"); + var response4 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); // Assert - 2 #if GENERATE_BASELINES @@ -269,12 +269,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Act - 3 // Verify content gets changed in a View Component when the Vary-by-header parameters is changed - client.DefaultRequestHeaders.Remove("Locale"); - client.DefaultRequestHeaders.Add("Locale", "East"); - targetUrl = "/catalog?categoryId=3&correlationid=3"; - var response5 = await client.GetStringAsync(targetUrl); - var response6 = await client.GetStringAsync(targetUrl); + request = RequestWithLocale(targetUrl, "East"); + var response5 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); + request = RequestWithLocale(targetUrl, "East"); + var response6 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); // Assert - 3 #if GENERATE_BASELINES @@ -288,13 +287,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task CacheTagHelper_ExpiresContent_BasedOnExpiresParameter() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost"); - - // Act - 1 - var response1 = await client.GetStringAsync("/catalog/2"); + // Arrange & Act - 1 + var response1 = await Client.GetStringAsync("/catalog/2"); // Assert - 1 var expected1 = "Cached content for 2"; @@ -302,7 +296,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Act - 2 await Task.Delay(TimeSpan.FromSeconds(1)); - var response2 = await client.GetStringAsync("/catalog/3"); + var response2 = await Client.GetStringAsync("/catalog/3"); // Assert - 2 var expected2 = "Cached content for 3"; @@ -312,21 +306,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task CacheTagHelper_UsesVaryByCookie_ToVaryContent() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost"); - - // Act - 1 - var response1 = await client.GetStringAsync("/catalog/cart?correlationid=1"); + // Arrange & Act - 1 + var response1 = await Client.GetStringAsync("/catalog/cart?correlationid=1"); // Assert - 1 var expected1 = "Cart content for 1"; Assert.Equal(expected1, response1.Trim()); // Act - 2 - client.DefaultRequestHeaders.Add("Cookie", "CartId=10"); - var response2 = await client.GetStringAsync("/catalog/cart?correlationid=2"); + var request = new HttpRequestMessage(HttpMethod.Get, "/catalog/cart?correlationid=2"); + request.Headers.Add("Cookie", "CartId=10"); + var response2 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync(); // Assert - 2 var expected2 = "Cart content for 2"; @@ -334,8 +324,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Act - 3 // Resend the cookiesless request and cached result from the first response. - client.DefaultRequestHeaders.Remove("Cookie"); - var response3 = await client.GetStringAsync("/catalog/cart?correlationid=3"); + var response3 = await Client.GetStringAsync("/catalog/cart?correlationid=3"); // Assert - 3 Assert.Equal(expected1, response3.Trim()); @@ -344,13 +333,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task CacheTagHelper_VariesByRoute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost"); - - // Act - 1 - var response1 = await client.GetStringAsync( + // Arrange & Act - 1 + var response1 = await Client.GetStringAsync( "/catalog/north-west/confirm-payment?confirmationId=1"); // Assert - 1 @@ -358,7 +342,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests Assert.Equal(expected1, response1.Trim()); // Act - 2 - var response2 = await client.GetStringAsync( + var response2 = await Client.GetStringAsync( "/catalog/south-central/confirm-payment?confirmationId=2"); // Assert - 2 @@ -366,14 +350,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests Assert.Equal(expected2, response2.Trim()); // Act 3 - var response3 = await client.GetStringAsync( + var response3 = await Client.GetStringAsync( "/catalog/north-west/Silver/confirm-payment?confirmationId=4"); var expected3 = "Welcome Silver member. Your confirmation id is 4. (Region north-west)"; Assert.Equal(expected3, response3.Trim()); // Act 4 - var response4 = await client.GetStringAsync( + var response4 = await Client.GetStringAsync( "/catalog/north-west/Gold/confirm-payment?confirmationId=5"); var expected4 = "Welcome Gold member. Your confirmation id is 5. (Region north-west)"; @@ -381,13 +365,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Act - 4 // Resend the responses and expect cached results. - response1 = await client.GetStringAsync( + response1 = await Client.GetStringAsync( "/catalog/north-west/confirm-payment?confirmationId=301"); - response2 = await client.GetStringAsync( + response2 = await Client.GetStringAsync( "/catalog/south-central/confirm-payment?confirmationId=402"); - response3 = await client.GetStringAsync( + response3 = await Client.GetStringAsync( "/catalog/north-west/Silver/confirm-payment?confirmationId=503"); - response4 = await client.GetStringAsync( + response4 = await Client.GetStringAsync( "/catalog/north-west/Gold/confirm-payment?confirmationId=608"); // Assert - 4 @@ -400,14 +384,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task CacheTagHelper_VariesByUserId() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost"); - - // Act - 1 - var response1 = await client.GetStringAsync("/catalog/past-purchases/test1?correlationid=1"); - var response2 = await client.GetStringAsync("/catalog/past-purchases/test1?correlationid=2"); + // Arrange & Act - 1 + var response1 = await Client.GetStringAsync("/catalog/past-purchases/test1?correlationid=1"); + var response2 = await Client.GetStringAsync("/catalog/past-purchases/test1?correlationid=2"); // Assert - 1 var expected1 = "Past purchases for user test1 (1)"; @@ -415,8 +394,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests Assert.Equal(expected1, response2.Trim()); // Act - 2 - var response3 = await client.GetStringAsync("/catalog/past-purchases/test2?correlationid=3"); - var response4 = await client.GetStringAsync("/catalog/past-purchases/test2?correlationid=4"); + var response3 = await Client.GetStringAsync("/catalog/past-purchases/test2?correlationid=3"); + var response4 = await Client.GetStringAsync("/catalog/past-purchases/test2?correlationid=4"); // Assert - 2 var expected2 = "Past purchases for user test2 (3)"; @@ -427,13 +406,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task CacheTagHelper_BubblesExpirationOfNestedTagHelpers() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost"); - - // Act - 1 - var response1 = await client.GetStringAsync("/categories/Books?correlationId=1"); + // Arrange & Act - 1 + var response1 = await Client.GetStringAsync("/categories/Books?correlationId=1"); // Assert - 1 var expected1 = @@ -442,7 +416,7 @@ Products: Book1, Book2 (1)"; Assert.Equal(expected1, response1.Trim(), ignoreLineEndingDifferences: true); // Act - 2 - var response2 = await client.GetStringAsync("/categories/Electronics?correlationId=2"); + var response2 = await Client.GetStringAsync("/categories/Electronics?correlationId=2"); // Assert - 2 var expected2 = @@ -452,10 +426,10 @@ Products: Book1, Book2 (1)"; // Act - 3 // Trigger an expiration - var response3 = await client.PostAsync("/categories/update-products", new StringContent(string.Empty)); + var response3 = await Client.PostAsync("/categories/update-products", new StringContent(string.Empty)); response3.EnsureSuccessStatusCode(); - var response4 = await client.GetStringAsync("/categories/Electronics?correlationId=3"); + var response4 = await Client.GetStringAsync("/categories/Electronics?correlationId=3"); // Assert - 3 var expected3 = @@ -467,15 +441,10 @@ Products: Laptops (3)"; [Fact] public async Task CacheTagHelper_DoesNotCacheIfDisabled() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.BaseAddress = new Uri("http://localhost"); - - // Act - var response1 = await client.GetStringAsync("/catalog/GetDealPercentage/20?isEnabled=true"); - var response2 = await client.GetStringAsync("/catalog/GetDealPercentage/40?isEnabled=true"); - var response3 = await client.GetStringAsync("/catalog/GetDealPercentage/30?isEnabled=false"); + // Arrange & Act + var response1 = await Client.GetStringAsync("/catalog/GetDealPercentage/20?isEnabled=true"); + var response2 = await Client.GetStringAsync("/catalog/GetDealPercentage/40?isEnabled=true"); + var response3 = await Client.GetStringAsync("/catalog/GetDealPercentage/30?isEnabled=false"); // Assert Assert.Equal("Deal percentage is 20", response1.Trim()); @@ -538,8 +507,6 @@ Products: Laptops (3)"; public async Task EditorTemplateWithNoModel_RendersWithCorrectMetadata() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expected = PlatformNormalizer.NormalizeContent( "" + Environment.NewLine + "" + Environment.NewLine + Environment.NewLine + @@ -548,7 +515,7 @@ Products: Laptops (3)"; Environment.NewLine + Environment.NewLine); // Act - var response = await client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingSharedEditorTemplate"); + var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingSharedEditorTemplate"); // Assert Assert.Equal(expected, response); @@ -558,16 +525,22 @@ Products: Laptops (3)"; public async Task EditorTemplateWithSpecificModel_RendersWithCorrectMetadata() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expected = "" + Environment.NewLine + "" + Environment.NewLine + Environment.NewLine; // Act - var response = await client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingModelSpecificEditorTemplate"); + var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingModelSpecificEditorTemplate"); // Assert Assert.Equal(expected, response); } + + private static HttpRequestMessage RequestWithLocale(string url, string locale) + { + var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.Add("Locale", locale); + + return request; + } } } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/HtmlHelperOptionsTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/HtmlHelperOptionsTest.cs index 5d103399fb..d7f71e2839 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/HtmlHelperOptionsTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/HtmlHelperOptionsTest.cs @@ -1,21 +1,21 @@ // 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.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Testing; -using Microsoft.Framework.DependencyInjection; -using RazorWebSite; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class HtmlHelperOptionsTest + public class HtmlHelperOptionsTest : IClassFixture> { - private const string SiteName = nameof(RazorWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public HtmlHelperOptionsTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task AppWideDefaultsInViewAndPartialView() @@ -40,11 +40,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests False"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // Act - var body = await client.GetStringAsync("http://localhost/HtmlHelperOptions/HtmlHelperOptionsDefaultsInView"); + var body = await Client.GetStringAsync("http://localhost/HtmlHelperOptions/HtmlHelperOptionsDefaultsInView"); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -75,11 +72,8 @@ True True"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // Act - var body = await client.GetStringAsync("http://localhost/HtmlHelperOptions/OverrideAppWideDefaultsInView"); + var body = await Client.GetStringAsync("http://localhost/HtmlHelperOptions/OverrideAppWideDefaultsInView"); // Assert // Mono issue - https://github.com/aspnet/External/issues/19 diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/InlineConstraintTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/InlineConstraintTests.cs index 972de79070..94037b6897 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/InlineConstraintTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/InlineConstraintTests.cs @@ -6,30 +6,25 @@ using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; -using InlineConstraints; -using Microsoft.AspNet.Builder; -using Microsoft.AspNet.Testing; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class InlineConstraintTests + public class InlineConstraintTests : IClassFixture> { - private const string SiteName = nameof(InlineConstraintsWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public InlineConstraintTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task RoutingToANonExistantArea_WithExistConstraint_RoutesToCorrectAction() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/area-exists/Users"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/area-exists/Users"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -40,12 +35,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task RoutingToANonExistantArea_WithoutExistConstraint_RoutesToIncorrectAction() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/area-withoutexists/Users"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/area-withoutexists/Users"); // Assert var exception = response.GetServerException(); @@ -62,12 +53,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductById_IntConstraintForOptionalId_IdPresent() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductById/5"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductById/5"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -81,12 +68,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductById_IntConstraintForOptionalId_NoId() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductById"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductById"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -98,12 +81,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductById_IntConstraintForOptionalId_NotIntId() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductById/asdf"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductById/asdf"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -112,12 +91,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByName_AlphaContraintForMandatoryName_ValidName() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductByName/asdf"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductByName/asdf"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -130,12 +105,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByName_AlphaContraintForMandatoryName_NonAlphaName() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductByName/asd123"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductByName/asd123"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -144,12 +115,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByName_AlphaContraintForMandatoryName_NoName() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductByName"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductByName"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -158,13 +125,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByManufacturingDate_DateTimeConstraintForMandatoryDateTime_ValidDateTime() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act + // Arrange & Act var response = - await client.GetAsync(@"http://localhost/products/GetProductByManufacturingDate/2014-10-11T13:45:30"); + await Client.GetAsync(@"http://localhost/products/GetProductByManufacturingDate/2014-10-11T13:45:30"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -178,12 +141,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByCategoryName_StringLengthConstraint_ForOptionalCategoryName_ValidCatName() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductByCategoryName/Sports"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductByCategoryName/Sports"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -196,13 +155,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByCategoryName_StringLengthConstraint_ForOptionalCategoryName_InvalidCatName() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act + // Arrange & Act var response = - await client.GetAsync("http://localhost/products/GetProductByCategoryName/SportsSportsSportsSports"); + await Client.GetAsync("http://localhost/products/GetProductByCategoryName/SportsSportsSportsSports"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -211,12 +166,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByCategoryName_StringLength1To20Constraint_ForOptionalCategoryName_NoCatName() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductByCategoryName"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductByCategoryName"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -228,12 +179,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByCategoryId_Int10To100Constraint_ForMandatoryCatId_ValidId() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductByCategoryId/40"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductByCategoryId/40"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -246,12 +193,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByCategoryId_Int10To100Constraint_ForMandatoryCatId_InvalidId() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductByCategoryId/5"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductByCategoryId/5"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -260,12 +203,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByCategoryId_Int10To100Constraint_ForMandatoryCatId_NotIntId() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductByCategoryId/asdf"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductByCategoryId/asdf"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -274,12 +213,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByPrice_FloatContraintForOptionalPrice_Valid() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductByPrice/4023.23423"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductByPrice/4023.23423"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -292,12 +227,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByPrice_FloatContraintForOptionalPrice_NoPrice() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductByPrice"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductByPrice"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -309,12 +240,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByManufacturerId_IntMin10Constraint_ForOptionalManufacturerId_Valid() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductByManufacturerId/57"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductByManufacturerId/57"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -327,12 +254,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetProductByManufacturerId_IntMin10Cinstraint_ForOptionalManufacturerId_NoId() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetProductByManufacturerId"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetProductByManufacturerId"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -344,12 +267,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetUserByName_RegExConstraint_ForMandatoryName_Valid() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetUserByName/abc"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetUserByName/abc"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -362,12 +281,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetUserByName_RegExConstraint_ForMandatoryName_InValid() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/products/GetUserByName/abcd"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/products/GetUserByName/abcd"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -376,13 +291,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetStoreById_GuidConstraintForOptionalId_Valid() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act + // Arrange & Act var response = - await client.GetAsync("http://localhost/Store/GetStoreById/691cf17a-791b-4af8-99fd-e739e168170f"); + await Client.GetAsync("http://localhost/Store/GetStoreById/691cf17a-791b-4af8-99fd-e739e168170f"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -395,12 +306,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetStoreById_GuidConstraintForOptionalId_NoId() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Store/GetStoreById"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Store/GetStoreById"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -412,12 +319,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetStoreById_GuidConstraintForOptionalId_NotGuidId() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Store/GetStoreById/691cf17a-791b"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Store/GetStoreById/691cf17a-791b"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -426,12 +329,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetStoreByLocation_StringLengthConstraint_AlphaConstraint_ForMandatoryLocation_Valid() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Store/GetStoreByLocation/Bellevue"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Store/GetStoreByLocation/Bellevue"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -444,12 +343,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetStoreByLocation_StringLengthConstraint_AlphaConstraint_ForMandatoryLocation_MoreLength() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Store/GetStoreByLocation/BellevueRedmond"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Store/GetStoreByLocation/BellevueRedmond"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -458,12 +353,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetStoreByLocation_StringLengthConstraint_AlphaConstraint_ForMandatoryLocation_LessLength() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Store/GetStoreByLocation/Be"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Store/GetStoreByLocation/Be"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -472,12 +363,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task GetStoreByLocation_StringLengthConstraint_AlphaConstraint_ForMandatoryLocation_NoAlpha() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Store/GetStoreByLocation/Bell124"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Store/GetStoreByLocation/Bell124"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -490,12 +377,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("1-234-56789-X", "10 Digit ISBN Number")] public async Task CustomInlineConstraint_Add_Update(string isbn, string expectedBody) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/book/index/" + isbn); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/book/index/" + isbn); var body = await response.Content.ReadAsStringAsync(); // Assert @@ -505,7 +388,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public static IEnumerable QueryParameters { - // The first four parameters are controller name, action name, parameters in the query and their values. + // The first four parameters are controller name, action name, parameters in the query and their values. // These are used to generate a link, the last parameter is expected generated link get { @@ -649,13 +532,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests string parameterValue, string expectedLink) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act + // Arrange & Act string url; - if (parameterName == null) { url = string.Format( @@ -675,7 +553,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests parameterValue); } - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/InputFormatterTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/InputFormatterTests.cs index 81e40d8964..b30fe2ba8b 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/InputFormatterTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/InputFormatterTests.cs @@ -1,26 +1,25 @@ // 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.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class InputFormatterTests + public class InputFormatterTests : IClassFixture> { - private const string SiteName = nameof(FormatterWebSite); - private readonly Action _app = new FormatterWebSite.Startup().Configure; - private readonly Action _configureServices = new FormatterWebSite.Startup().ConfigureServices; + public InputFormatterTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + public HttpClient Client { get; } [ConditionalFact] // Mono issue - https://github.com/aspnet/External/issues/18 @@ -28,8 +27,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CheckIfXmlInputFormatterIsBeingCalled() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var sampleInputInt = 10; var input = "" + "" @@ -37,9 +34,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var content = new StringContent(input, Encoding.UTF8, "application/xml"); // Act - var response = await client.PostAsync("http://localhost/Home/Index", content); + var response = await Client.PostAsync("http://localhost/Home/Index", content); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(sampleInputInt.ToString(), await response.Content.ReadAsStringAsync()); } @@ -53,16 +50,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonInputFormatter_IsSelectedForJsonRequest(string requestContentType) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var sampleInputInt = 10; var input = "{\"SampleInt\":10}"; var content = new StringContent(input, Encoding.UTF8, requestContentType); // Act - var response = await client.PostAsync("http://localhost/Home/Index", content); + var response = await Client.PostAsync("http://localhost/Home/Index", content); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(sampleInputInt.ToString(), await response.Content.ReadAsStringAsync()); } @@ -78,15 +73,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("invalid", false)] [InlineData("application/custom", false)] [InlineData("image/jpg", false)] - public async Task ModelStateErrorValidation_NoInputFormatterFound_ForGivenContentType(string requestContentType, - bool filterHandlesModelStateError) + public async Task ModelStateErrorValidation_NoInputFormatterFound_ForGivenContentType( + string requestContentType, + bool filterHandlesModelStateError) { // Arrange var actionName = filterHandlesModelStateError ? "ActionFilterHandlesError" : "ActionHandlesError"; var expectedSource = filterHandlesModelStateError ? "filter" : "action"; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "{\"SampleInt\":10}"; var content = new StringContent(input); content.Headers.Clear(); @@ -96,7 +89,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/InputFormatter/" + actionName); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); request.Content = content; - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var responseBody = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(responseBody); @@ -113,18 +106,19 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Theory] [InlineData("application/json", "{\"SampleInt\":10}", 10)] [InlineData("application/json", "{}", 0)] - public async Task JsonInputFormatter_IsModelStateValid_ForValidContentType(string requestContentType, string jsonInput, int expectedSampleIntValue) + public async Task JsonInputFormatter_IsModelStateValid_ForValidContentType( + string requestContentType, + string jsonInput, + int expectedSampleIntValue) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new StringContent(jsonInput, Encoding.UTF8, requestContentType); // Act - var response = await client.PostAsync("http://localhost/JsonFormatter/ReturnInput/", content); + var response = await Client.PostAsync("http://localhost/JsonFormatter/ReturnInput/", content); var responseBody = await response.Content.ReadAsStringAsync(); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedSampleIntValue.ToString(), responseBody); } @@ -136,15 +130,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonInputFormatter_ReturnsDefaultValue_ForValueTypes(string input) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new StringContent(input, Encoding.UTF8, "application/json"); // Act - var response = await client.PostAsync("http://localhost/JsonFormatter/ValueTypeAsBody/", content); + var response = await Client.PostAsync("http://localhost/JsonFormatter/ValueTypeAsBody/", content); var responseBody = await response.Content.ReadAsStringAsync(); - //Assert + // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal("0", responseBody); } @@ -154,15 +146,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = "1773"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new StringContent(expected, Encoding.UTF8, "application/json"); // Act - var response = await client.PostAsync("http://localhost/JsonFormatter/ValueTypeAsBody/", content); + var response = await Client.PostAsync("http://localhost/JsonFormatter/ValueTypeAsBody/", content); var responseBody = await response.Content.ReadAsStringAsync(); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expected, responseBody); } @@ -174,35 +164,36 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonInputFormatter_IsModelStateInvalid_ForEmptyContentType(string jsonInput) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new StringContent(jsonInput, Encoding.UTF8, "application/json"); content.Headers.Clear(); // Act - var response = await client.PostAsync("http://localhost/JsonFormatter/ReturnInput/", content); + var response = await Client.PostAsync("http://localhost/JsonFormatter/ReturnInput/", content); var responseBody = await response.Content.ReadAsStringAsync(); - //Assert + // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } [Theory] [InlineData("application/json", "{\"SampleInt\":10}", 10)] [InlineData("application/json", "{}", 0)] - public async Task JsonInputFormatter_IsModelStateValid_ForTransferEncodingChunk(string requestContentType, string jsonInput, int expectedSampleIntValue) + public async Task JsonInputFormatter_IsModelStateValid_ForTransferEncodingChunk( + string requestContentType, + string jsonInput, + int expectedSampleIntValue) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new StringContent(jsonInput, Encoding.UTF8, requestContentType); - client.DefaultRequestHeaders.TransferEncodingChunked = true; + var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/JsonFormatter/ReturnInput/"); + request.Headers.TransferEncodingChunked = true; + request.Content = content; // Act - var response = await client.PostAsync("http://localhost/JsonFormatter/ReturnInput/", content); + var response = await Client.SendAsync(request); var responseBody = await response.Content.ReadAsStringAsync(); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedSampleIntValue.ToString(), responseBody); } @@ -213,15 +204,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CustomFormatter_IsSelected_ForSupportedContentTypeAndEncoding(string encoding) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new StringContent("Test Content", Encoding.GetEncoding(encoding), "text/plain"); // Act - var response = await client.PostAsync("http://localhost/InputFormatter/ReturnInput/", content); + var response = await Client.PostAsync("http://localhost/InputFormatter/ReturnInput/", content); var responseBody = await response.Content.ReadAsStringAsync(); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("Test Content", responseBody); } @@ -232,15 +221,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CustomFormatter_NotSelected_ForUnsupportedContentType(string contentType) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new StringContent("Test Content", Encoding.UTF8, contentType); // Act - var response = await client.PostAsync("http://localhost/InputFormatter/ReturnInput/", content); + var response = await Client.PostAsync("http://localhost/InputFormatter/ReturnInput/", content); var responseBody = await response.Content.ReadAsStringAsync(); - //Assert + // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/InputObjectValidationTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/InputObjectValidationTests.cs index 5d88db18ee..206d80cd96 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/InputObjectValidationTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/InputObjectValidationTests.cs @@ -1,27 +1,27 @@ // 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.Collections.Generic; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Testing; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class InputObjectValidationTests + public class InputObjectValidationTests : IClassFixture> { - private const string SiteName = nameof(FormatterWebSite); - private readonly Action _app = new FormatterWebSite.Startup().Configure; - private readonly Action _configureServices = new FormatterWebSite.Startup().ConfigureServices; + public InputObjectValidationTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } // Parameters: Request Content, Expected status code, Expected model state error message public static IEnumerable SimpleTypePropertiesModelRequestData @@ -51,8 +51,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CheckIfObjectIsDeserializedWithoutErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var sampleId = 2; var sampleName = "SampleUser"; var sampleAlias = "SampleAlias"; @@ -66,7 +64,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var content = new StringContent(input, Encoding.UTF8, "application/xml"); // Act - var response = await client.PostAsync("http://localhost/Validation/Index", content); + var response = await Client.PostAsync("http://localhost/Validation/Index", content); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -78,8 +76,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CheckIfObjectIsDeserialized_WithErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var sampleId = 0; var sampleName = "user"; var sampleAlias = "a"; @@ -90,7 +86,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var content = new StringContent(input, Encoding.UTF8, "application/json"); // Act - var response = await client.PostAsync("http://localhost/Validation/Index", content); + var response = await Client.PostAsync("http://localhost/Validation/Index", content); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -108,12 +104,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CheckIfExcludedFieldsAreNotValidated() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new StringContent("{\"Alias\":\"xyz\"}", Encoding.UTF8, "application/json"); // Act - var response = await client.PostAsync("http://localhost/Validation/GetDeveloperName", content); + var response = await Client.PostAsync("http://localhost/Validation/GetDeveloperName", content); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -125,8 +119,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ShallowValidation_HappensOnExcluded_ComplexTypeProperties() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var requestData = "{\"Name\":\"Library Manager\", \"Suppliers\": [{\"Name\":\"Contoso Corp\"}]}"; var content = new StringContent(requestData, Encoding.UTF8, "application/json"); var expectedModelStateErrorMessage @@ -135,7 +127,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests = "The field Name must be a string or array type with a maximum length of '5'."; // Act - var response = await client.PostAsync("http://localhost/Validation/CreateProject", content); + var response = await Client.PostAsync("http://localhost/Validation/CreateProject", content); // Assert Assert.Equal(StatusCodes.Status400BadRequest, (int)response.StatusCode); @@ -158,12 +150,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests string expectedModelStateErrorMessage) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new StringContent(requestContent, Encoding.UTF8, "application/json"); // Act - var response = await client.PostAsync( + var response = await Client.PostAsync( "http://localhost/Validation/CreateSimpleTypePropertiesModel", content); @@ -181,14 +171,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CheckIfExcludedField_IsNotValidatedForNonBodyBoundModels() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var kvps = new List>(); kvps.Add(new KeyValuePair("Alias", "xyz")); var content = new FormUrlEncodedContent(kvps); // Act - var response = await client.PostAsync("http://localhost/Validation/GetDeveloperAlias", content); + var response = await Client.PostAsync("http://localhost/Validation/GetDeveloperAlias", content); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/JsonOutputFormatterTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/JsonOutputFormatterTests.cs index a62f916cd0..d20aef496d 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/JsonOutputFormatterTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/JsonOutputFormatterTests.cs @@ -1,27 +1,26 @@ // 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.Collections.Generic; 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.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class JsonOutputFormatterTests + public class JsonOutputFormatterTests : IClassFixture> { - private const string SiteName = nameof(FormatterWebSite); - private readonly Action _app = new FormatterWebSite.Startup().Configure; - private readonly Action _configureServices = new FormatterWebSite.Startup().ConfigureServices; + public JsonOutputFormatterTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + public HttpClient Client { get; } [Fact] public async Task JsonOutputFormatter_ReturnsIndentedJson() @@ -40,11 +39,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests serializerSettings.Formatting = Formatting.Indented; var expectedBody = JsonConvert.SerializeObject(user, serializerSettings); - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // Act - var response = await client.GetAsync("http://localhost/JsonFormatter/ReturnsIndentedJson"); + var response = await Client.GetAsync("http://localhost/JsonFormatter/ReturnsIndentedJson"); // Assert var actualBody = await response.Content.ReadAsStringAsync(); @@ -57,9 +53,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task SerializableErrorIsReturnedInExpectedFormat() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "" + "" + "2foo"; @@ -72,7 +65,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new StringContent(input, Encoding.UTF8, "application/xml"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/JsonPatchTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/JsonPatchTest.cs index 0102b229db..5a02b5dfd0 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/JsonPatchTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/JsonPatchTest.cs @@ -6,21 +6,21 @@ using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; -using JsonPatchWebSite; using JsonPatchWebSite.Models; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class JsonPatchTest + public class JsonPatchTest : IClassFixture> { - private const string SiteName = nameof(JsonPatchWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public JsonPatchTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("http://localhost/jsonpatch/JsonPatchWithoutModelState")] @@ -29,9 +29,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonPatch_ValidAddOperation_Success(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "[{ \"op\": \"add\", " + "\"path\": \"Orders/2\", " + "\"value\": { \"OrderName\": \"Name2\" }}]"; @@ -43,7 +40,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -58,9 +55,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonPatch_ValidReplaceOperation_Success(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "[{ \"op\": \"replace\", " + "\"path\": \"Orders/0/OrderName\", " + "\"value\": \"ReplacedOrder\" }]"; @@ -72,7 +66,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -87,9 +81,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonPatch_ValidCopyOperation_Success(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "[{ \"op\": \"copy\", " + "\"path\": \"Orders/1/OrderName\", " + "\"from\": \"Orders/0/OrderName\"}]"; @@ -101,7 +92,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -116,9 +107,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonPatch_ValidMoveOperation_Success(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "[{ \"op\": \"move\", " + "\"path\": \"Orders/1/OrderName\", " + "\"from\": \"Orders/0/OrderName\"}]"; @@ -130,7 +118,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -147,9 +135,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonPatch_ValidRemoveOperation_Success(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "[{ \"op\": \"remove\", " + "\"path\": \"Orders/1/OrderName\"}]"; var request = new HttpRequestMessage @@ -160,7 +145,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -175,9 +160,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonPatch_MultipleValidOperations_Success(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "[{ \"op\": \"add\", "+ "\"path\": \"Orders/2\", " + "\"value\": { \"OrderName\": \"Name2\" }}, " + @@ -195,7 +177,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -262,9 +244,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonPatch_InvalidOperations_failure(string url, string input, string errorMessage) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage { Content = new StringContent(input, Encoding.UTF8, "application/json-patch+json"), @@ -273,7 +252,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -284,9 +263,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonPatch_InvalidData_FormatterErrorInModelState_Failure() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "{ \"op\": \"add\", " + "\"path\": \"Orders/2\", " + "\"value\": { \"OrderName\": \"Name2\" }}"; @@ -298,7 +274,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -309,9 +285,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonPatch_JsonConverterOnProperty_Success() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "[{ \"op\": \"add\", " + "\"path\": \"Orders/2\", " + "\"value\": { \"OrderType\": \"Type2\" }}]"; @@ -323,7 +296,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -335,9 +308,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonPatch_JsonConverterOnClass_Success() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var input = "[{ \"op\": \"add\", " + "\"path\": \"ProductCategory\", " + "\"value\": { \"CategoryName\": \"Name2\" }}]"; @@ -349,7 +319,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/JsonResultTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/JsonResultTest.cs index 6addb861ef..15cfe20fe5 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/JsonResultTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/JsonResultTest.cs @@ -1,35 +1,31 @@ // 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.Net; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class JsonResultTest + public class JsonResultTest : IClassFixture> { - private const string SiteName = nameof(BasicWebSite); - private readonly Action _app = new BasicWebSite.Startup().Configure; - private readonly Action _configureServices = new BasicWebSite.Startup().ConfigureServices; + public JsonResultTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task JsonResult_UsesDefaultContentType() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/JsonResult/Plain"; - var request = new HttpRequestMessage(HttpMethod.Get, url); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -46,16 +42,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonResult_Conneg_Fails(string mediaType) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/JsonResult/Plain"; - var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.TryAddWithoutValidation("Accept", mediaType); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -69,15 +61,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonResult_Null() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/JsonResult/Null"; - var request = new HttpRequestMessage(HttpMethod.Get, url); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -91,15 +79,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonResult_String() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/JsonResult/String"; - var request = new HttpRequestMessage(HttpMethod.Get, url); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -112,15 +96,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonResult_Uses_CustomSerializerSettings() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/JsonResult/CustomSerializerSettings"; - var request = new HttpRequestMessage(HttpMethod.Get, url); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -132,15 +112,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonResult_CustomContentType() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/JsonResult/CustomContentType"; - var request = new HttpRequestMessage(HttpMethod.Get, url); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/LinkGenerationTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/LinkGenerationTests.cs index 77d673e532..777b39919b 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/LinkGenerationTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/LinkGenerationTests.cs @@ -12,7 +12,7 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class LinkGenerationTests : IClassFixture> + public class LinkGenerationTests : IClassFixture> { // Some tests require comparing the actual response body against an expected response baseline // so they require a reference to the assembly on which the resources are located, in order to @@ -20,7 +20,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // use it on all the rest of the tests. private static readonly Assembly _resourcesAssembly = typeof(LinkGenerationTests).GetTypeInfo().Assembly; - public LinkGenerationTests(MvcFixture fixture) + public LinkGenerationTests(MvcTestFixture fixture) { Client = fixture.Client; } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/LocalizationTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/LocalizationTest.cs index ddc17ef783..6fa31b8819 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/LocalizationTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/LocalizationTest.cs @@ -1,29 +1,30 @@ // 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.Collections.Generic; using System.IO; +using System.Net.Http; using System.Reflection; using System.Resources; using System.Threading.Tasks; using System.Xml.Linq; -using LocalizationWebSite; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Testing; -using Microsoft.Framework.DependencyInjection; using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class LocalizationTest + public class LocalizationTest : IClassFixture> { private const string SiteName = nameof(LocalizationWebSite); private static readonly Assembly _assembly = typeof(LocalizationTest).GetTypeInfo().Assembly; - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public LocalizationTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } public static IEnumerable LocalizationData { @@ -62,15 +63,15 @@ mypartial public async Task Localization_SuffixViewName(string value, string expected) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var cultureCookie = "c=" + value + "|uic=" + value; - client.DefaultRequestHeaders.Add( + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/"); + request.Headers.Add( "Cookie", new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString()); // Act - var body = await client.GetStringAsync("http://localhost/"); + var response = await Client.SendAsync(request); + var body = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -112,23 +113,23 @@ Hi"; public async Task Localization_Resources_ReturnExpectedValues(string value, string expected) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var cultureCookie = "c=" + value + "|uic=" + value; - client.DefaultRequestHeaders.Add( + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/Locpage"); + request.Headers.Add( "Cookie", new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString()); if (!value.StartsWith("en")) { - // Manually generating .resources file since we don't autogenerate .resources file yet. + // Manually generating .resources file since we don't autogenerate .resources file yet. WriteResourceFile("HomeController." + value + ".resx"); WriteResourceFile("Views.Shared._LocalizationLayout.cshtml." + value + ".resx"); } WriteResourceFile("Views.Home.Locpage.cshtml." + value + ".resx"); // Act - var body = await client.GetStringAsync("http://localhost/Home/Locpage"); + var response = await Client.SendAsync(request); + var body = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(expected, body.Trim()); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingBindingBehaviorTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingBindingBehaviorTest.cs index 7a9f8c0e82..d17261123c 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingBindingBehaviorTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingBindingBehaviorTest.cs @@ -1,13 +1,10 @@ // 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.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using ModelBindingWebSite; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -15,19 +12,19 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ModelBindingBindingBehaviorTest + public class ModelBindingBindingBehaviorTest : IClassFixture> { - private const string SiteName = nameof(ModelBindingWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ModelBindingBindingBehaviorTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task BindingBehavior_MissingRequiredProperties_ValidationErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/BindingBehavior/EchoModelValues"; var request = new HttpRequestMessage(HttpMethod.Post, url); var formData = new List> @@ -38,7 +35,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(formData); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -63,9 +60,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task BindingBehavior_OptionalIsOptional() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/BindingBehavior/EchoModelValues"; var request = new HttpRequestMessage(HttpMethod.Post, url); var formData = new List> @@ -77,7 +71,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(formData); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -96,9 +90,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task BindingBehavior_Never_IsNotBound() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/BindingBehavior/EchoModelValues"; var request = new HttpRequestMessage(HttpMethod.Post, url); var formData = new List> @@ -114,7 +105,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(formData); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingDataMemberRequiredTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingDataMemberRequiredTest.cs index 881d385079..9c86b2dd04 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingDataMemberRequiredTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingDataMemberRequiredTest.cs @@ -1,13 +1,10 @@ // 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.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using ModelBindingWebSite; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -15,19 +12,19 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ModelBindingDataMemberRequiredTest + public class ModelBindingDataMemberRequiredTest : IClassFixture> { - private const string SiteName = nameof(ModelBindingWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ModelBindingDataMemberRequiredTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task DataMember_MissingRequiredProperty_ValidationError() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/DataMemberRequired/EchoModelValues"; var request = new HttpRequestMessage(HttpMethod.Post, url); var formData = new List> @@ -38,7 +35,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(formData); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -58,9 +55,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task DataMember_RequiredPropertyProvided_Success() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/DataMemberRequired/EchoModelValues"; var request = new HttpRequestMessage(HttpMethod.Post, url); var formData = new List> @@ -73,7 +67,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(formData); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromFormTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromFormTest.cs index 45dadb6d76..a36ee72987 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromFormTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromFormTest.cs @@ -1,12 +1,9 @@ // 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.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using ModelBindingWebSite; using ModelBindingWebSite.Controllers; using ModelBindingWebSite.Models; @@ -15,19 +12,19 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ModelBindingFromFormTest + public class ModelBindingFromFormTest : IClassFixture> { - private const string SiteName = nameof(ModelBindingWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ModelBindingFromFormTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task FromForm_CustomModelPrefix_ForParameter() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/FromFormAttribute_Company/CreateCompany"; var request = new HttpRequestMessage(HttpMethod.Post, url); var nameValueCollection = new List> @@ -38,7 +35,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -53,9 +50,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromForm_CustomModelPrefix_ForCollectionParameter() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/FromFormAttribute_Company/CreateCompanyFromEmployees"; var request = new HttpRequestMessage(HttpMethod.Post, url); var nameValueCollection = new List> @@ -65,7 +59,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -79,9 +73,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromForm_CustomModelPrefix_ForProperty() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/FromFormAttribute_Company/CreateCompany"; var request = new HttpRequestMessage(HttpMethod.Post, url); var nameValueCollection = new List> @@ -91,7 +82,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -105,9 +96,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromForm_CustomModelPrefix_ForCollectionProperty() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/FromFormAttribute_Company/CreateDepartment"; var request = new HttpRequestMessage(HttpMethod.Post, url); var nameValueCollection = new List> @@ -117,7 +105,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -132,9 +120,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromForm_NonExistingValueAddsValidationErrors_OnProperty_UsingCustomModelPrefix() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/FromFormAttribute_Company/ValidateDepartment"; var request = new HttpRequestMessage(HttpMethod.Post, url); @@ -143,7 +128,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromHeaderTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromHeaderTest.cs index 11fa0c57c7..6157fcba36 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromHeaderTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromHeaderTest.cs @@ -12,12 +12,15 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ModelBindingFromHeaderTest + public class ModelBindingFromHeaderTest : IClassFixture> { - private const string SiteName = nameof(ModelBindingWebSite); - private readonly Action _app = new ModelBindingWebSite.Startup().Configure; - private readonly Action _configureServices = new ModelBindingWebSite.Startup().ConfigureServices; - + public ModelBindingFromHeaderTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } + // The action that this test hits will echo back the model-bound value [Theory] [InlineData("transactionId", "1e331f25-0869-4c87-8a94-64e6e40cb5a0")] @@ -27,15 +30,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = headerValue; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToStringParameter"); request.Headers.TryAddWithoutValidation(headerName, headerValue); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -51,16 +50,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Arrange var title = "How to make really really good soup."; var tags = new string[] { "Cooking", "Recipes", "Awesome" }; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToProperty/CustomName"); request.Headers.TryAddWithoutValidation("BlogTitle", title); request.Headers.TryAddWithoutValidation("BlogTags", string.Join(", ", tags)); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -77,15 +72,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var tags = new string[] { "Cooking", "Recipes", "Awesome" }; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToProperty/CustomName"); request.Headers.TryAddWithoutValidation("BlogTags", string.Join(", ", tags)); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -101,14 +92,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromHeader_NonExistingHeaderAddsValidationErrors_OnCollectionProperty_CustomName() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToProperty/CustomName"); request.Headers.TryAddWithoutValidation("BlogTitle", "Cooking Receipes."); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -126,15 +114,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = "1e331f25-0869-4c87-8a94-64e6e40cb5a0"; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToStringParameter/CustomName"); request.Headers.TryAddWithoutValidation("tId", "1e331f25-0869-4c87-8a94-64e6e40cb5a0"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -154,15 +138,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = headerValue; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToStringParameter"); request.Headers.TryAddWithoutValidation(headerName, headerValue); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -183,16 +163,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests string headerValue) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - + // Intentionally not setting a header value var request = new HttpRequestMessage( HttpMethod.Get, "http://localhost/Blog/BindToStringParameterDefaultValue"); - // Intentionally not setting a header value // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -213,15 +190,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = headerValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToStringArrayParameter"); request.Headers.TryAddWithoutValidation(headerName, headerValue); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -241,17 +214,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Arrange var title = "How to make really really good soup."; var tags = new string[] { "Cooking", "Recipes", "Awesome" }; - - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToModel?author=Marvin"); - request.Headers.TryAddWithoutValidation("title", title); request.Headers.TryAddWithoutValidation("tags", string.Join(", ", tags)); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -270,15 +238,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromHeader_BindHeader_ToModel_NoValues_ValidationError() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - + // Intentionally not setting a title or tags var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToModel?author=Marvin"); - // Intentionally not setting a title or tags - // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -300,17 +264,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromHeader_BindHeader_ToModel_NoValues_InitializedValue_NoValidationError() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - + // Intentionally not setting a title or tags var request = new HttpRequestMessage( HttpMethod.Get, "http://localhost/Blog/BindToModelWithInitializedValue?author=Marvin"); - // Intentionally not setting a title or tags - // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromQueryTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromQueryTest.cs index dd1496b377..282d51fb74 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromQueryTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromQueryTest.cs @@ -1,10 +1,8 @@ // 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.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using ModelBindingWebSite; using ModelBindingWebSite.Controllers; using ModelBindingWebSite.Models; @@ -13,25 +11,25 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ModelBindingFromQueryTest + public class ModelBindingFromQueryTest : IClassFixture> { - private const string SiteName = nameof(ModelBindingWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ModelBindingFromQueryTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task FromQuery_CustomModelPrefix_ForParameter() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // [FromQuery(Name = "customPrefix")] is used to apply a prefix var url = "http://localhost/FromQueryAttribute_Company/CreateCompany?customPrefix.Employees[0].Name=somename"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -45,14 +43,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromQuery_CustomModelPrefix_ForCollectionParameter() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/FromQueryAttribute_Company/CreateCompanyFromEmployees?customPrefix[0].Name=somename"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -66,15 +61,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromQuery_CustomModelPrefix_ForProperty() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // [FromQuery(Name = "EmployeeId")] is used to apply a prefix var url = "http://localhost/FromQueryAttribute_Company/CreateCompany?customPrefix.Employees[0].EmployeeId=1234"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -89,13 +81,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromQuery_CustomModelPrefix_ForCollectionProperty() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/FromQueryAttribute_Company/CreateDepartment?TestEmployees[0].EmployeeId=1234"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -110,14 +99,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromQuery_NonExistingValueAddsValidationErrors_OnProperty_UsingCustomModelPrefix() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/FromQueryAttribute_Company/ValidateDepartment?TestEmployees[0].Department=contoso"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromRouteTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromRouteTest.cs index 1da2c1ad23..3cdac27316 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromRouteTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingFromRouteTest.cs @@ -1,12 +1,9 @@ // 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.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using ModelBindingWebSite; using ModelBindingWebSite.Models; using Newtonsoft.Json; @@ -14,25 +11,24 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ModelBindingFromRouteTest + public class ModelBindingFromRouteTest : IClassFixture> { - private const string SiteName = nameof(ModelBindingWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ModelBindingFromRouteTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task FromRoute_CustomModelPrefix_ForParameter() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // [FromRoute(Name = "customPrefix")] is used to apply a prefix - var url = - "http://localhost/FromRouteAttribute_Company/CreateEmployee/somename"; + var url = "http://localhost/FromRouteAttribute_Company/CreateEmployee/somename"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -44,15 +40,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromRoute_CustomModelPrefix_ForProperty() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // [FromRoute(Name = "EmployeeId")] is used to apply a prefix - var url = - "http://localhost/FromRouteAttribute_Company/CreateEmployee/somename/1234"; + var url = "http://localhost/FromRouteAttribute_Company/CreateEmployee/somename/1234"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -65,12 +57,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FromRoute_NonExistingValueAddsValidationErrors_OnProperty_UsingCustomModelPrefix() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // [FromRoute(Name = "TestEmployees")] is used to apply a prefix - var url = - "http://localhost/FromRouteAttribute_Company/ValidateDepartment/contoso"; + var url = "http://localhost/FromRouteAttribute_Company/ValidateDepartment/contoso"; var request = new HttpRequestMessage(HttpMethod.Post, url); // No values. @@ -78,7 +66,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingModelBinderAttributeTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingModelBinderAttributeTest.cs index df0d8cb72c..a63e4e56f5 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingModelBinderAttributeTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingModelBinderAttributeTest.cs @@ -1,36 +1,33 @@ // 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.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using ModelBindingWebSite.Models; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ModelBindingModelBinderAttributeTest + public class ModelBindingModelBinderAttributeTest : IClassFixture> { - private const string SiteName = nameof(ModelBindingWebSite); - private readonly Action _app = new ModelBindingWebSite.Startup().Configure; - private readonly Action _configureServices = new ModelBindingWebSite.Startup().ConfigureServices; + public ModelBindingModelBinderAttributeTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + public HttpClient Client { get; } [Fact] public async Task ModelBinderAttribute_CustomModelPrefix() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // [ModelBinder(Name = "customPrefix")] is used to apply a prefix - var url = + var url = "http://localhost/ModelBinderAttribute_Company/GetCompany?customPrefix.Employees[0].Name=somename"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -44,14 +41,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelBinderAttribute_CustomModelPrefix_OnProperty() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - var url = - "http://localhost/ModelBinderAttribute_Company/CreateCompany?employees[0].Alias=somealias"; + var url = "http://localhost/ModelBinderAttribute_Company/CreateCompany?employees[0].Alias=somealias"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -65,16 +58,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelBinderAttribute_WithPrefixOnParameter() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // [ModelBinder(Name = "customPrefix")] is used to apply a prefix - var url = - "http://localhost/ModelBinderAttribute_Product/GetBinderType_UseModelBinderOnType" + + var url = "http://localhost/ModelBinderAttribute_Product/GetBinderType_UseModelBinderOnType" + "?customPrefix.ProductId=5"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -87,20 +76,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelBinderAttribute_WithBinderOnParameter() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - var url = - "http://localhost/ModelBinderAttribute_Product/GetBinderType_UseModelBinder/" + + var url = "http://localhost/ModelBinderAttribute_Product/GetBinderType_UseModelBinder/" + "?model.productId=5"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); Assert.Equal( - "ModelBindingWebSite.Controllers.ModelBinderAttribute_ProductController+ProductModelBinder", + "ModelBindingWebSite.Controllers.ModelBinderAttribute_ProductController+ProductModelBinder", body); } @@ -108,16 +93,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelBinderAttribute_WithBinderOnEnum() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - var url = - "http://localhost/ModelBinderAttribute_Product/" + - "ModelBinderAttribute_UseModelBinderOnEnum" + + var url = "http://localhost/ModelBinderAttribute_Product/ModelBinderAttribute_UseModelBinderOnEnum" + "?status=Shipped"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingTest.cs index 23b377c4f1..c50d9604ef 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingTest.cs @@ -10,10 +10,8 @@ using System.Net.Http; using System.Reflection; using System.Text; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Testing; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using ModelBindingWebSite.Models; using ModelBindingWebSite.ViewModels; using Newtonsoft.Json; @@ -21,23 +19,22 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ModelBindingTest + public class ModelBindingTest : IClassFixture> { - private const string SiteName = nameof(ModelBindingWebSite); private static readonly Assembly _assembly = typeof(ModelBindingTest).GetTypeInfo().Assembly; - private readonly Action _app = new ModelBindingWebSite.Startup().Configure; - private readonly Action _configureServices = new ModelBindingWebSite.Startup().ConfigureServices; + public ModelBindingTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task DoNotValidate_ParametersOrControllerProperties_IfSourceNotFromRequest() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/Validation/DoNotValidateParameter"); + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/Validation/DoNotValidateParameter"); // Assert Assert.Equal("true", response); @@ -46,12 +43,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ModelValidation_DoesNotValidate_AnAlreadyValidatedObject() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/Validation/AvoidRecursive?Name=selfish"); + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/Validation/AvoidRecursive?Name=selfish"); // Assert Assert.Equal("true", response); @@ -64,11 +57,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CompositeModelBinder_Restricts_ValueProviders(string actionName, string expectedValue) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // Provide all three values, it should bind based on the attribute on the action method. - var request = new HttpRequestMessage(HttpMethod.Post, + var request = new HttpRequestMessage( + HttpMethod.Post, string.Format("http://localhost/CompositeTest/{0}/valueFromRoute?param=valueFromQuery", actionName)); var nameValueCollection = new List> { @@ -78,7 +69,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -89,21 +80,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task TryUpdateModel_WithAPropertyFromBody() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // the name would be of customer.Department.Name // and not for the top level customer object. var input = "{\"Name\":\"RandomDepartment\"}"; var content = new StringContent(input, Encoding.UTF8, "application/json"); // Act - var response = await client.PostAsync("http://localhost/Home/GetCustomer?Id=1234", content); + var response = await Client.PostAsync("http://localhost/Home/GetCustomer?Id=1234", content); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var customer = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var customer = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.NotNull(customer.Department); Assert.Equal("RandomDepartment", customer.Department.Name); Assert.Equal(1234, customer.Id); @@ -114,14 +101,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task CanModelBindServiceToAnArgument() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/FromServices_Calculator/Add?left=1234&right=1"); - // Act - var response = await client.GetAsync("http://localhost/FromServices_Calculator/Add?left=1234&right=1"); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("1235", await response.Content.ReadAsStringAsync()); } @@ -129,14 +112,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task CanModelBindServiceToAProperty() { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/FromServices_Calculator/Calculate?Left=10&Right=5&Operator=*"); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("50", await response.Content.ReadAsStringAsync()); } @@ -144,14 +124,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task CanModelBindServiceToAProperty_OnBaseType() { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/FromServices_Calculator/CalculateWithPrecision?Left=10&Right=5&Operator=*"); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("50", await response.Content.ReadAsStringAsync()); } @@ -159,12 +136,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ControllerPropertyAndAnActionWithoutFromBody_InvokesWithoutErrors() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/FromBodyControllerProperty/GetSiteUser"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/FromBodyControllerProperty/GetSiteUser"); // Assert Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); @@ -174,10 +147,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanBind_MultipleParameters_UsingFromForm() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Post, + var request = new HttpRequestMessage( + HttpMethod.Post, "http://localhost/FromAttributes/MultipleFromFormParameters"); var nameValueCollection = new List> { @@ -192,12 +163,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var user = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var user = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.Equal("WA_Form_Home", user.HomeAddress.State); Assert.Equal(1, user.HomeAddress.Street); @@ -212,10 +182,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanBind_MultipleProperties_UsingFromForm() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - var request = new HttpRequestMessage(HttpMethod.Post, + var request = new HttpRequestMessage( + HttpMethod.Post, "http://localhost/FromAttributes/MultipleFromFormParameterAndProperty"); var nameValueCollection = new List> { @@ -230,12 +198,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var user = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var user = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.Equal("WA_Form_Home", user.HomeAddress.State); Assert.Equal(1, user.HomeAddress.Street); @@ -250,11 +217,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanBind_ComplexData_OnParameters_UsingFromAttributes() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // Provide all three values, it should bind based on the attribute on the action method. - var request = new HttpRequestMessage(HttpMethod.Post, + var request = new HttpRequestMessage( + HttpMethod.Post, "http://localhost/FromAttributes/GetUser/5/WA_Route/6" + "?Street=3&State=WA_Query&Zip=4"); var nameValueCollection = new List> @@ -267,12 +232,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var user = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var user = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); // Assert FromRoute Assert.Equal("WA_Route", user.HomeAddress.State); @@ -294,11 +258,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanBind_ComplexData_OnProperties_UsingFromAttributes() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // Provide all three values, it should bind based on the attribute on the action method. - var request = new HttpRequestMessage(HttpMethod.Post, + var request = new HttpRequestMessage( + HttpMethod.Post, "http://localhost/FromAttributes/GetUser_FromForm/5/WA_Route/6" + "?ShippingAddress.Street=3&ShippingAddress.State=WA_Query&ShippingAddress.Zip=4"); var nameValueCollection = new List> @@ -311,12 +273,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var user = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var user = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); // Assert FromRoute Assert.Equal("WA_Route", user.HomeAddress.State); @@ -338,11 +299,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanBind_ComplexData_OnProperties_UsingFromAttributes_WithBody() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // Provide all three values, it should bind based on the attribute on the action method. - var request = new HttpRequestMessage(HttpMethod.Post, + var request = new HttpRequestMessage( + HttpMethod.Post, "http://localhost/FromAttributes/GetUser_FromBody/5/WA_Route/6" + "?ShippingAddress.Street=3&ShippingAddress.State=WA_Query&ShippingAddress.Zip=4"); var input = "{\"State\":\"WA_Body\",\"Street\":1,\"Zip\":2}"; @@ -350,12 +309,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content = new StringContent(input, Encoding.UTF8, "application/json"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var user = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var user = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); // Assert FromRoute Assert.Equal("WA_Route", user.HomeAddress.State); @@ -377,15 +335,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task NonExistingModelBinder_ForABinderMetadata_DoesNotRecurseInfinitely() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act & Assert - var response = await client.GetStringAsync("http://localhost/WithBinderMetadata/EchoDocument"); - - var document = JsonConvert.DeserializeObject - (response); + // Arrange & Act & Assert + var response = await Client.GetStringAsync("http://localhost/WithBinderMetadata/EchoDocument"); + var document = JsonConvert.DeserializeObject(response); Assert.NotNull(document); Assert.Null(document.Version); @@ -395,20 +347,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ParametersWithNoValueProviderMetadataUseTheAvailableValueProviders() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/WithBinderMetadata" + + "/ParametersWithNoValueProviderMetadataUseTheAvailableValueProviders" + + "?Name=somename&Age=12"); - // Act - var response = await - client.GetAsync("http://localhost/WithBinderMetadata" + - "/ParametersWithNoValueProviderMetadataUseTheAvailableValueProviders" + - "?Name=somename&Age=12"); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var emp = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var emp = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.Null(emp.Department); Assert.Equal("somename", emp.Name); Assert.Equal(12, emp.Age); @@ -417,20 +363,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ParametersAreAlwaysCreated_IfValuesAreProvidedWithoutModelName() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/WithoutBinderMetadata" + + "/GetPersonParameter" + + "?Name=somename&Age=12"); - // Act - var response = await - client.GetAsync("http://localhost/WithoutBinderMetadata" + - "/GetPersonParameter" + - "?Name=somename&Age=12"); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var person = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var person = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.NotNull(person); Assert.Equal("somename", person.Name); Assert.Equal(12, person.Age); @@ -439,19 +379,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ParametersAreAlwaysCreated_IfValueIsProvidedForModelName() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + // here p is the model name. + var response = await Client.GetAsync("http://localhost/WithoutBinderMetadata/GetPersonParameter?p="); - // Act - var response = await - client.GetAsync("http://localhost/WithoutBinderMetadata" + - "/GetPersonParameter?p="); // here p is the model name. - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var person = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var person = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.NotNull(person); Assert.Null(person.Name); Assert.Equal(0, person.Age); @@ -460,19 +394,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ParametersAreAlwaysCreated_IfNoValuesAreProvided() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/WithoutBinderMetadata/GetPersonParameter"); - // Act - var response = await - client.GetAsync("http://localhost/WithoutBinderMetadata" + - "/GetPersonParameter"); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var person = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var person = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.NotNull(person); Assert.Null(person.Name); Assert.Equal(0, person.Age); @@ -481,19 +408,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task PropertiesAreBound_IfTheyAreProvidedByValueProviders() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync( + "http://localhost/Properties/GetCompany?Employees[0].Name=somename&Age=12"); - // Act - var response = await - client.GetAsync("http://localhost/Properties" + - "/GetCompany?Employees[0].Name=somename&Age=12"); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var company = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var company = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.NotNull(company); Assert.NotNull(company.Employees); Assert.Equal(1, company.Employees.Count); @@ -503,19 +424,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task PropertiesAreBound_IfTheyAreMarkedExplicitly() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Properties/GetCompany"); - // Act - var response = await - client.GetAsync("http://localhost/Properties" + - "/GetCompany"); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var company = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var company = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.NotNull(company); Assert.NotNull(company.CEO); Assert.Null(company.CEO.Name); @@ -524,19 +438,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task PropertiesAreBound_IfTheyArePocoMetadataMarkedTypes() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Properties/GetCompany"); - // Act - var response = await - client.GetAsync("http://localhost/Properties" + - "/GetCompany"); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var company = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var company = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.NotNull(company); // Department property is not null because it was a marker poco. @@ -549,19 +456,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task PropertiesAreNotBound_ByDefault() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Properties/GetCompany"); - // Act - var response = await - client.GetAsync("http://localhost/Properties" + - "/GetCompany"); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var company = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var company = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.NotNull(company); Assert.Null(company.Employees); } @@ -569,19 +469,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task PocoGetsCreated_IfTopLevelNoProperties() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await - client.GetAsync("http://localhost/Properties" + - "/GetPerson"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Properties/GetPerson"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var person = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + await response.Content.ReadAsStringAsync()); Assert.NotNull(person); Assert.Null(person.Name); } @@ -589,19 +483,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ArrayOfPocoGetsCreated_PoCoWithNoProperties() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await - client.GetAsync("http://localhost/Properties" + - "/GetPeople?people[0].Name=asdf"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Properties/GetPeople?people[0].Name=asdf"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var arrperson = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + await response.Content.ReadAsStringAsync()); Assert.NotNull(arrperson); Assert.NotNull(arrperson.people); Assert.Equal(0, arrperson.people.Length); @@ -612,15 +500,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("http://localhost/Home/ActionWithPersonFromUrlWithoutPrefix/Javier/26")] public async Task CanBind_ComplexData_FromRouteData(string url) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync(url); - // Act - var response = await - client.GetAsync(url); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); @@ -635,14 +518,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ModelBindCancellationTokenParameteres() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/ActionWithCancellationToken"); - // Act - var response = await client.GetAsync("http://localhost/Home/ActionWithCancellationToken"); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("true", await response.Content.ReadAsStringAsync()); } @@ -650,15 +529,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ModelBindCancellationToken_ForProperties() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/Home/ActionWithCancellationTokenModel?wrapper=bogusValue"); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("true", await response.Content.ReadAsStringAsync()); } @@ -666,14 +541,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ModelBindingBindsBase64StringsToByteArrays() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/Index?byteValues=SGVsbG9Xb3JsZA=="); - // Act - var response = await client.GetAsync("http://localhost/Home/Index?byteValues=SGVsbG9Xb3JsZA=="); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("HelloWorld", await response.Content.ReadAsStringAsync()); } @@ -681,14 +552,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ModelBindingBindsEmptyStringsToByteArrays() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/Index?byteValues="); - // Act - var response = await client.GetAsync("http://localhost/Home/Index?byteValues="); - - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); } @@ -697,14 +564,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelBinding_LimitsErrorsToMaxErrorCount_DoesNotValidateMembersOfMissingProperties() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var queryString = string.Join("=&", Enumerable.Range(0, 10).Select(i => "field" + i)); // Act - var response = await client.GetStringAsync("http://localhost/Home/ModelWithTooManyValidationErrors?" + queryString); + var response = await Client.GetStringAsync( + "http://localhost/Home/ModelWithTooManyValidationErrors?" + queryString); - //Assert + // Assert var json = JsonConvert.DeserializeObject>(response); // 8 is the value of MaxModelValidationErrors for the application being tested. @@ -723,18 +589,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ModelBinding_FallsBackAndValidatesAllPropertiesInModel() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/Home/ModelWithFewValidationErrors?model="); + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/Home/ModelWithFewValidationErrors?model="); // Assert var json = JsonConvert.DeserializeObject>(response); Assert.Equal(3, json.Count); - // The model prefix 'model' is used in the modelstate keys because the key 'model' is present in the + // The model prefix 'model' is used in the modelstate keys because the key 'model' is present in the // query string. This causes modelbinding to commit to using the prefix. // // Mono issue - https://github.com/aspnet/External/issues/19 @@ -747,8 +609,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelBinding_FallsBackAndSuccessfullyBindsStructCollection() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var contentDictionary = new Dictionary { { "[0]", "23" }, @@ -758,7 +618,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var requestContent = new FormUrlEncodedContent(contentDictionary); // Act - var response = await client.PostAsync("http://localhost/integers", requestContent); + var response = await Client.PostAsync("http://localhost/integers", requestContent); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -776,8 +636,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelBinding_FallsBackAndSuccessfullyBindsPOCOCollection() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var contentDictionary = new Dictionary { { "[0].CityCode", "YYZ" }, @@ -788,7 +646,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var requestContent = new FormUrlEncodedContent(contentDictionary); // Act - var response = await client.PostAsync("http://localhost/cities", requestContent); + var response = await Client.PostAsync("http://localhost/cities", requestContent); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -806,12 +664,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task BindAttribute_Filters_UsingDefaultPropertyFilterProvider_WithExpressions() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/BindAttribute/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/BindAttribute/" + "EchoUser" + "?user.UserName=someValue&user.RegisterationMonth=March&user.Id=123"); @@ -829,12 +683,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task BindAttribute_Filters_UsingPropertyFilterProvider_UsingServices() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/BindAttribute/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/BindAttribute/" + "EchoUserUsingServices" + "?user.UserName=someValue&user.RegisterationMonth=March&user.Id=123"); @@ -852,12 +702,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task BindAttribute_Filters_UsingDefaultPropertyFilterProvider_WithPredicate() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/BindAttribute/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/BindAttribute/" + "UpdateUserId_BlackListingAtEitherLevelDoesNotBind" + "?param1.LastName=someValue¶m2.Id=123"); @@ -871,12 +717,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task BindAttribute_AppliesAtBothParameterAndTypeLevelTogether_BlacklistedAtEitherLevelIsNotBound() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/BindAttribute/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/BindAttribute/" + "UpdateUserId_BlackListingAtEitherLevelDoesNotBind" + "?param1.LastName=someValue¶m2.Id=123"); @@ -890,12 +732,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task BindAttribute_AppliesAtBothParameterAndTypeLevelTogether_IncludedAtBothLevelsIsBound() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/BindAttribute/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/BindAttribute/" + "UpdateFirstName_IncludingAtBothLevelBinds" + "?param1.FirstName=someValue¶m2.Id=123"); @@ -908,12 +746,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task BindAttribute_AppliesAtBothParameterAndTypeLevelTogether_IncludingAtOneLevelIsNotBound() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/BindAttribute/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/BindAttribute/" + "UpdateIsAdmin_IncludingAtOnlyOneLevelDoesNotBind" + "?param1.FirstName=someValue¶m1.IsAdmin=true"); @@ -927,12 +761,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task BindAttribute_BindsUsingParameterPrefix() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/BindAttribute/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/BindAttribute/" + "BindParameterUsingParameterPrefix" + "?randomPrefix.Value=someValue"); @@ -943,12 +773,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task BindAttribute_FallsBackOnTypePrefixIfNoParameterPrefixIsProvided() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/BindAttribute/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/BindAttribute/" + "TypePrefixIsUsed" + "?TypePrefix.Value=someValue"); @@ -959,12 +785,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task BindAttribute_DoesNotFallBackOnEmptyPrefixIfParameterPrefixIsProvided() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/BindAttribute/" + + // Arrange & Act + var response = await Client.GetAsync("http://localhost/BindAttribute/" + "BindParameterUsingParameterPrefix" + "?Value=someValue"); @@ -976,12 +798,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TryUpdateModel_IncludeTopLevelProperty_IncludesAllSubProperties() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/TryUpdateModel/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/TryUpdateModel/" + "GetUserAsync_IncludesAllSubProperties" + "?id=123&Key=34&RegistrationMonth=March&Address.Street=123&Address.Country.Name=USA&" + "Address.State=WA&Address.Country.Cities[0].CityName=Seattle&Address.Country.Cities[0].CityCode=SEA"); @@ -1006,17 +824,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task TryUpdateModel_ChainedPropertyExpression_Throws() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); Expression> expression = model => model.Address.Country; - var expected = string.Format( "The passed expression of expression node type '{0}' is invalid." + " Only simple member access expressions for model properties are supported.", expression.Body.NodeType); // Act - var response = await client.GetAsync("http://localhost/TryUpdateModel/GetUserAsync_WithChainedProperties?id=123"); + var response = await Client.GetAsync( + "http://localhost/TryUpdateModel/GetUserAsync_WithChainedProperties?id=123"); // Assert var exception = response.GetServerException(); @@ -1027,31 +843,21 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TryUpdateModel_FailsToUpdateProperties() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/TryUpdateModel/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/TryUpdateModel/" + "TryUpdateModelFails" + "?id=123&RegisterationMonth=March&Key=123&UserName=SomeName"); // Assert var result = JsonConvert.DeserializeObject(response); - - // Act Assert.False(result); } [Fact] public async Task TryUpdateModel_IncludeExpression_WorksOnlyAtTopLevel() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/TryUpdateModel/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/TryUpdateModel/" + "GetPerson" + "?Parent.Name=fatherName&Parent.Parent.Name=grandFatherName"); @@ -1069,12 +875,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TryUpdateModel_Validates_ForTopLevelNotIncludedProperties() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/TryUpdateModel/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/TryUpdateModel/" + "CreateAndUpdateUser" + "?RegistedeburationMonth=March"); @@ -1086,12 +888,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TryUpdateModelExcludeSpecific_Properties() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/TryUpdateModel/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/TryUpdateModel/" + "GetUserAsync_ExcludeSpecificProperties" + "?id=123&RegisterationMonth=March&Key=123&UserName=SomeName"); @@ -1109,12 +907,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TryUpdateModelIncludeSpecific_Properties() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/TryUpdateModel/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/TryUpdateModel/" + "GetUserAsync_IncludeSpecificProperties" + "?id=123&RegisterationMonth=March&Key=123&UserName=SomeName"); @@ -1132,12 +926,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TryUpdateModelIncludesAllProperties_ByDefault() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/TryUpdateModel/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/TryUpdateModel/" + "GetUserAsync_IncludeAllByDefault" + "?id=123&RegisterationMonth=March&Key=123&UserName=SomeName"); @@ -1156,8 +946,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task UpdateVehicle_WithJson_ProducesModelStateErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new { Year = 3012, @@ -1170,7 +958,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.PutAsJsonAsync("http://localhost/api/vehicles/520", content); + var response = await Client.PutAsJsonAsync("http://localhost/api/vehicles/520", content); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -1180,10 +968,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests Assert.Equal(2, modelStateErrors.Count); // OrderBy is used because the order of the results may very depending on the platform / client. - Assert.Equal(new[] { + Assert.Equal( + new[] + { "The field Year must be between 1980 and 2034.", "Year is invalid" - }, modelStateErrors["Year"].OrderBy(item => item, StringComparer.Ordinal)); + }, + modelStateErrors["Year"].OrderBy(item => item, StringComparer.Ordinal)); var vinError = Assert.Single(modelStateErrors["Vin"]); // Mono issue - https://github.com/aspnet/External/issues/19 @@ -1194,8 +985,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task UpdateVehicle_WithJson_DoesPropertyValidationPriorToValidationAtType() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new { Year = 2007, @@ -1207,10 +996,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests Model = "Epsum", Vin = "Pqrs" }; - client.DefaultRequestHeaders.TryAddWithoutValidation("X-TrackingId", "trackingid"); + var request = new HttpRequestMessage(HttpMethod.Put, "http://localhost/api/vehicles/520"); + request.Content = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json"); + request.Headers.TryAddWithoutValidation("X-TrackingId", "trackingid"); // Act - var response = await client.PutAsJsonAsync("http://localhost/api/vehicles/520", content); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -1228,8 +1019,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task UpdateVehicle_WithJson_BindsBodyAndServices() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var trackingId = Guid.NewGuid().ToString(); var postedContent = new { @@ -1243,10 +1032,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests Model = "Epsum", Vin = "PQRS" }; - client.DefaultRequestHeaders.TryAddWithoutValidation("X-TrackingId", trackingId); + var request = new HttpRequestMessage(HttpMethod.Put, "http://localhost/api/vehicles/520"); + request.Content = new StringContent( + JsonConvert.SerializeObject(postedContent), + Encoding.UTF8, + "application/json"); + request.Headers.TryAddWithoutValidation("X-TrackingId", trackingId); // Act - var response = await client.PutAsJsonAsync("http://localhost/api/vehicles/520", postedContent); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1267,8 +1061,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task UpdateVehicle_WithXml_BindsBodyServicesAndHeaders() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var trackingId = Guid.NewGuid().ToString(); var postedContent = new VehicleViewModel { @@ -1282,10 +1074,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests Model = "Epsum", Vin = "PQRS" }; - client.DefaultRequestHeaders.TryAddWithoutValidation("X-TrackingId", trackingId); + var request = new HttpRequestMessage(HttpMethod.Put, "http://localhost/api/vehicles/520"); + request.Content = new StringContent( + JsonConvert.SerializeObject(postedContent), + Encoding.UTF8, + "application/json"); + request.Headers.TryAddWithoutValidation("X-TrackingId", trackingId); // Act - var response = await client.PutAsXmlAsync("http://localhost/api/vehicles/520", postedContent); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1305,8 +1102,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task UpdateDealerVehicle_PopulatesPropertyErrorsInViews() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var outputFile = "compiler/resources/UpdateDealerVehicle_PopulatesPropertyErrorsInViews.txt"; var expectedContent = await ResourceFile.ReadResourceAsync(_assembly, outputFile, sourceFile: false); var postedContent = new @@ -1324,7 +1119,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var url = "http://localhost/dealers/32/update-vehicle?dealer.name=TestCarDealer&dealer.location=SE"; // Act - var response = await client.PostAsJsonAsync(url, postedContent); + var response = await Client.PostAsJsonAsync(url, postedContent); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1352,8 +1147,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task UpdateDealerVehicle_PopulatesValidationSummary() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var outputFile = "compiler/resources/UpdateDealerVehicle_PopulatesValidationSummary.txt"; var expectedContent = await ResourceFile.ReadResourceAsync(_assembly, outputFile, sourceFile: false); var postedContent = new @@ -1371,7 +1164,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var url = "http://localhost/dealers/43/update-vehicle?dealer.name=TestCarDealer&dealer.location=SE"; // Act - var response = await client.PostAsJsonAsync(url, postedContent); + var response = await Client.PostAsJsonAsync(url, postedContent); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1392,8 +1185,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task UpdateDealerVehicle_UsesDefaultValuesForOptionalProperties() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var outputFile = "compiler/resources/UpdateDealerVehicle_UpdateSuccessful.txt"; var expectedContent = await ResourceFile.ReadResourceAsync(_assembly, outputFile, sourceFile: false); var postedContent = new @@ -1411,7 +1202,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var url = "http://localhost/dealers/43/update-vehicle?dealer.name=TestCarDealer&dealer.location=NE"; // Act - var response = await client.PostAsJsonAsync(url, postedContent); + var response = await Client.PostAsJsonAsync(url, postedContent); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1428,19 +1219,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FormFileModelBinder_CanBind_SingleFile() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/FileUpload/UploadSingle"; var formData = new MultipartFormDataContent("Upload----"); formData.Add(new StringContent("Test Content"), "file", "test.txt"); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var fileDetails = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var fileDetails = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.Equal("test.txt", fileDetails.Filename); Assert.Equal("Test Content", fileDetails.Content); } @@ -1449,20 +1237,18 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FormFileModelBinder_CanBind_MultipleFiles() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/FileUpload/UploadMultiple"; var formData = new MultipartFormDataContent("Upload----"); formData.Add(new StringContent("Test Content 1"), "files", "test1.txt"); formData.Add(new StringContent("Test Content 2"), "files", "test2.txt"); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var fileDetailsArray = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + await response.Content.ReadAsStringAsync()); Assert.Equal(2, fileDetailsArray.Length); Assert.Equal("test1.txt", fileDetailsArray[0].Filename); Assert.Equal("Test Content 1", fileDetailsArray[0].Content); @@ -1474,8 +1260,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FormFileModelBinder_CanBind_MultipleListOfFiles() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/FileUpload/UploadMultipleList"; var formData = new MultipartFormDataContent("Upload----"); formData.Add(new StringContent("Test Content 1"), "filelist1", "test1.txt"); @@ -1484,12 +1268,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests formData.Add(new StringContent("Test Content 4"), "filelist2", "test4.txt"); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var fileDetailsLookup = JsonConvert.DeserializeObject>>( - await response.Content.ReadAsStringAsync()); + await response.Content.ReadAsStringAsync()); Assert.Equal(2, fileDetailsLookup.Count); var fileDetailsList1 = fileDetailsLookup["filelist1"]; var fileDetailsList2 = fileDetailsLookup["filelist2"]; @@ -1509,20 +1293,18 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FormFileModelBinder_CanBind_FileInsideModel() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/FileUpload/UploadModelWithFile"; var formData = new MultipartFormDataContent("Upload----"); formData.Add(new StringContent("Test Book"), "Name"); formData.Add(new StringContent("Test Content"), "File", "test.txt"); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var book = JsonConvert.DeserializeObject>( - await response.Content.ReadAsStringAsync()); + await response.Content.ReadAsStringAsync()); var bookName = book.Key; var fileDetails = book.Value; Assert.Equal("Test Book", bookName); @@ -1533,12 +1315,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TryUpdateModel_ReturnDerivedAndBaseProperties() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/TryUpdateModel/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/TryUpdateModel/" + "GetEmployeeAsync_BindToBaseDeclaredType" + "?Parent.Name=fatherName&Parent.Parent.Name=grandFatherName&Department=Sales"); @@ -1555,14 +1333,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task HtmlHelper_DisplayFor_ShowsPropertiesInModelMetadataOrder() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var outputFile = "compiler/resources/ModelBindingWebSite.Vehicle.Details.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_assembly, outputFile, sourceFile: false); var url = "http://localhost/vehicles/42"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1579,14 +1355,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task HtmlHelper_EditorFor_ShowsPropertiesInModelMetadataOrder() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var outputFile = "compiler/resources/ModelBindingWebSite.Vehicle.Edit.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_assembly, outputFile, sourceFile: false); var url = "http://localhost/vehicles/42/edit"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1607,8 +1381,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task HtmlHelper_EditorFor_ShowsPropertiesAndErrorsInModelMetadataOrder() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var outputFile = "compiler/resources/ModelBindingWebSite.Vehicle.Edit.Invalid.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_assembly, outputFile, sourceFile: false); var url = "http://localhost/vehicles/42/edit"; @@ -1633,7 +1405,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var requestContent = new FormUrlEncodedContent(contentDictionary); // Act - var response = await client.PostAsync(url, requestContent); + var response = await Client.PostAsync(url, requestContent); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1655,8 +1427,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/Home/GetErrorMessage"; var nameValueCollection = new List> @@ -1666,7 +1436,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var formData = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1678,8 +1448,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task OverriddenMetadataProvider_CanChangeAdditionalValues() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/AdditionalValues"; var expectedDictionary = new Dictionary { @@ -1688,7 +1456,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1701,8 +1469,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task OverriddenMetadataProvider_CanUseAttributesToChangeAdditionalValues() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/GroupNames"; var expectedDictionary = new Dictionary { @@ -1715,7 +1481,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1727,12 +1493,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TryUpdateModelNonGeneric_IncludesAllProperties_CanBind() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/TryUpdateModel/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/TryUpdateModel/" + "GetUserAsync_ModelType_IncludeAll" + "?id=123&RegisterationMonth=March&Key=123&UserName=SomeName"); @@ -1751,8 +1513,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FormCollectionModelBinder_CanBind_FormValues() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/FormCollection/ReturnValuesAsList"; var nameValueCollection = new List> { @@ -1762,12 +1522,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var formData = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var valuesList = JsonConvert.DeserializeObject>( - await response.Content.ReadAsStringAsync()); + var valuesList = JsonConvert.DeserializeObject>(await response.Content.ReadAsStringAsync()); Assert.Equal(new List { "value1", "value2" }, valuesList); } @@ -1775,8 +1534,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FormCollectionModelBinder_CanBind_FormValuesWithDuplicateKeys() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/FormCollection/ReturnValuesAsList"; var nameValueCollection = new List> { @@ -1787,12 +1544,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var formData = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var valuesList = JsonConvert.DeserializeObject>( - await response.Content.ReadAsStringAsync()); + var valuesList = JsonConvert.DeserializeObject>(await response.Content.ReadAsStringAsync()); Assert.Equal(new List { "value1,value3", "value2" }, valuesList); } @@ -1800,18 +1556,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FormCollectionModelBinder_CannotBind_NonFormValues() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/FormCollection/ReturnCollectionCount"; var data = new StringContent("Non form content"); // Act - var response = await client.PostAsync(url, data); + var response = await Client.PostAsync(url, data); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var collectionCount = JsonConvert.DeserializeObject( - await response.Content.ReadAsStringAsync()); + var collectionCount = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); Assert.Equal(0, collectionCount); } @@ -1819,15 +1572,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FormCollectionModelBinder_CanBind_FormWithFile() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/FormCollection/ReturnFileContent"; var expectedContent = "Test Content"; var formData = new MultipartFormDataContent("Upload----"); formData.Add(new StringContent(expectedContent), "File", "test.txt"); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1838,12 +1589,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task TryUpdateModelNonGenericIncludesAllProperties_ByDefault() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/TryUpdateModel/" + + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/TryUpdateModel/" + "GetUserAsync_ModelType_IncludeAllByDefault" + "?id=123&RegisterationMonth=March&Key=123&UserName=SomeName"); @@ -1862,8 +1609,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task BindModelAsync_WithCollection() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new Dictionary { { "AddressLines[0].Line", "Street Address 0" }, @@ -1874,7 +1619,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var formData = new FormUrlEncodedContent(content); // Act - var response = await client.PutAsync(url, formData); + var response = await Client.PutAsync(url, formData); // Assert var address = await ReadValue(response); @@ -1888,8 +1633,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task BindModelAsync_WithCollection_SpecifyingIndex() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new[] { new KeyValuePair("AddressLines.index", "3"), @@ -1901,7 +1644,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var formData = new FormUrlEncodedContent(content); // Act - var response = await client.PutAsync(url, formData); + var response = await Client.PutAsync(url, formData); // Assert var address = await ReadValue(response); @@ -1914,8 +1657,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task BindModelAsync_WithNestedCollection() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new Dictionary { { "Addresses[0].AddressLines[0].Line", "Street Address 00" }, @@ -1928,7 +1669,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var formData = new FormUrlEncodedContent(content); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert var result = await ReadValue(response); @@ -1949,8 +1690,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task BindModelAsync_WithIncorrectlyFormattedNestedCollectionValue_BindsSingleNullEntry() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new Dictionary { { "Addresses", "Street Address 00" }, @@ -1959,7 +1698,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var formData = new FormUrlEncodedContent(content); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert var result = await ReadValue(response); @@ -1970,8 +1709,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task BindModelAsync_WithNestedCollectionContainingRecursiveRelation() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new Dictionary { { "People[0].Name", "Person 0" }, @@ -1984,7 +1721,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var formData = new FormUrlEncodedContent(content); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert var result = await ReadValue(response); @@ -2009,8 +1746,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests BindModelAsync_WithNestedCollectionContainingRecursiveRelation_WithMalformedValue_BindsSingleNullEntry() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new Dictionary { { "People", "Person 0" }, @@ -2019,7 +1754,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var formData = new FormUrlEncodedContent(content); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert var result = await ReadValue(response); @@ -2035,8 +1770,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests bool expectedResult) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new List> { new KeyValuePair("isValid", firstValue), @@ -2046,7 +1779,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var formData = new FormUrlEncodedContent(content); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert var result = await ReadValue(response); @@ -2057,8 +1790,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task BindModelAsync_CheckBoxesList_BindSuccessful() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var content = new List> { new KeyValuePair("userPreferences[0].Id", "1"), @@ -2070,7 +1801,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var formData = new FormUrlEncodedContent(content); // Act - var response = await client.PostAsync(url, formData); + var response = await Client.PostAsync(url, formData); // Assert var result = await ReadValue>(response); @@ -2082,12 +1813,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task TryUpdateModel_ClearsModelStateEntries() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost/TryUpdateModel/TryUpdateModel_ClearsModelStateEntries"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelMetadataAttributeTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelMetadataAttributeTest.cs index d441e7c61a..f7e9a46d18 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelMetadataAttributeTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelMetadataAttributeTest.cs @@ -1,31 +1,28 @@ // 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.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.AspNet.Testing; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ModelMetadataAttributeTest + public class ModelMetadataAttributeTest : IClassFixture> { - private const string SiteName = nameof(ValidationWebSite); - private readonly Action _app = new ValidationWebSite.Startup().Configure; - private readonly Action _configureServices = new ValidationWebSite.Startup().ConfigureServices; + public ModelMetadataAttributeTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task ModelMetaDataTypeAttribute_ValidBaseClass_EmptyResponseBody() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "{ \"Name\": \"MVC\", \"Contact\":\"4258959019\", \"Category\":\"Technology\"," + "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 21, \"ProductDetails\": {\"Detail1\": \"d1\"," + " \"Detail2\": \"d2\", \"Detail3\": \"d3\"}}"; @@ -34,7 +31,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata"; // Act - var response = await client.PostAsync(url, content); + var response = await Client.PostAsync(url, content); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -45,15 +42,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelMetaDataTypeAttribute_InvalidPropertiesAndSubPropertiesOnBaseClass_ReturnsErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "{ \"Price\": 2, \"ProductDetails\": {\"Detail1\": \"d1\"}}"; var content = new StringContent(input, Encoding.UTF8, "application/json"); var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata"; // Act - var response = await client.PostAsync(url, content); + var response = await Client.PostAsync(url, content); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -76,8 +71,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelMetaDataTypeAttribute_InvalidComplexTypePropertyOnBaseClass_ReturnsErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "{ \"Contact\":\"4255678765\", \"Category\":\"Technology\"," + "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 21 }"; var content = new StringContent(input, Encoding.UTF8, "application/json"); @@ -85,7 +78,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata"; // Act - var response = await client.PostAsync(url, content); + var response = await Client.PostAsync(url, content); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -101,8 +94,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelMetaDataTypeAttribute_InvalidClassAttributeOnBaseClass_ReturnsErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "{ \"Contact\":\"4258959019\", \"Category\":\"Technology\"," + "\"CompanyName\":\"Microsoft\", \"Country\":\"UK\",\"Price\": 21, \"ProductDetails\": {\"Detail1\": \"d1\"," + " \"Detail2\": \"d2\", \"Detail3\": \"d3\"}}"; @@ -112,7 +103,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata"; // Act - var response = await client.PostAsync(url, content); + var response = await Client.PostAsync(url, content); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -125,8 +116,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelMetaDataTypeAttribute_ValidDerivedClass_EmptyResponseBody() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "{ \"Name\": \"MVC\", \"Contact\":\"4258959019\", \"Category\":\"Technology\"," + "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\", \"Version\":\"2\"," + "\"DatePurchased\": \"/Date(1297246301973)/\", \"Price\" : \"110\" }"; @@ -135,7 +124,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var url = "http://localhost/ModelMetadataTypeValidation/ValidateSoftwareViewModelIncludingMetadata"; // Act - var response = await client.PostAsync(url, content); + var response = await Client.PostAsync(url, content); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -146,8 +135,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelMetaDataTypeAttribute_InvalidPropertiesOnDerivedClass_ReturnsErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "{ \"Name\": \"MVC\", \"Contact\":\"425-895-9019\", \"Category\":\"Technology\"," + "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 2}"; var content = new StringContent(input, Encoding.UTF8, "application/json"); @@ -155,7 +142,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var url = "http://localhost/ModelMetadataTypeValidation/ValidateSoftwareViewModelIncludingMetadata"; // Act - var response = await client.PostAsync(url, content); + var response = await Client.PostAsync(url, content); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -169,8 +156,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelMetaDataTypeAttribute_InvalidClassAttributeOnBaseClassProduct_ReturnsErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "{ \"Contact\":\"4258959019\", \"Category\":\"Technology\"," + "\"CompanyName\":\"Microsoft\", \"Country\":\"UK\",\"Version\":\"2\"," + "\"DatePurchased\": \"/Date(1297246301973)/\", \"Price\" : \"110\" }"; @@ -179,7 +164,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var url = "http://localhost/ModelMetadataTypeValidation/ValidateSoftwareViewModelIncludingMetadata"; // Act - var response = await client.PostAsync(url, content); + var response = await Client.PostAsync(url, content); // Assert var body = await response.Content.ReadAsStringAsync(); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcEncodedTestFixtureOfT.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcEncodedTestFixtureOfT.cs new file mode 100644 index 0000000000..c04acee3ad --- /dev/null +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcEncodedTestFixtureOfT.cs @@ -0,0 +1,20 @@ +// 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 Microsoft.Framework.DependencyInjection; +using Microsoft.Framework.WebEncoders; +using Microsoft.Framework.WebEncoders.Testing; + +namespace Microsoft.AspNet.Mvc.FunctionalTests +{ + public class MvcEncodedTestFixture : MvcTestFixture + where TStartup : new() + { + protected override void AddAdditionalServices(IServiceCollection services) + { + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + } + } +} diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs index 4bf2c2209e..fa2c2c03b7 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcSampleTests.cs @@ -1,30 +1,25 @@ // 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 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.Mvc.Formatters.Xml; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class MvcSampleTests + public class MvcSampleTests : IClassFixture> { - private const string SiteName = nameof(MvcSample) + "." + nameof(MvcSample.Web); + public MvcSampleTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } - // Path relative to Mvc\\test\Microsoft.AspNet.Mvc.FunctionalTests - private readonly static string SamplesFolder = Path.Combine("..", "..", "samples"); - - private readonly Action _app = new MvcSample.Web.Startup().Configure; - private readonly Func _configureServices = new MvcSample.Web.Startup().ConfigureServices; + public HttpClient Client { get; } [Theory] [InlineData("")] // Shared/MyView.cshtml @@ -41,12 +36,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("/Home/ValidationSummary")] // Home/ValidationSummary.cshtml public async Task Home_Pages_ReturnSuccess(string path) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost" + path); + // Arrange & Act + var response = await Client.GetAsync("http://localhost" + path); // Assert Assert.NotNull(response); @@ -69,14 +60,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task FormUrlEncoded_ReturnsAppropriateResults(string input, string expectedOutput) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/FormUrlEncoded/IsValidPerson"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Content = new StringContent(input, Encoding.UTF8, "application/x-www-form-urlencoded"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(expectedOutput, await response.Content.ReadAsStringAsync()); @@ -85,12 +74,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FormUrlEncoded_Index_ReturnSuccess() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/FormUrlEncoded"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/FormUrlEncoded"); // Assert Assert.NotNull(response); @@ -100,12 +85,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task Home_NotFoundAction_Returns404() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/NotFound"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/NotFound"); // Assert Assert.NotNull(response); @@ -118,13 +99,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task Home_CreateUser_ReturnsXmlBasedOnAcceptHeader() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices); - 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(request); + var response = await Client.SendAsync(request); // Assert Assert.NotNull(response); @@ -145,12 +124,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("http://localhost/Filters/NotGrantedClaim", HttpStatusCode.Unauthorized)] public async Task FiltersController_Tests(string url, HttpStatusCode statusCode) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync(url); + // Arrange & Act + var response = await Client.GetAsync(url); // Assert Assert.NotNull(response); @@ -160,12 +135,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task FiltersController_Crash_ThrowsException() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Filters/Crash?message=HelloWorld"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Filters/Crash?message=HelloWorld"); // Assert Assert.NotNull(response); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcTestFixture.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcTestFixture.cs index 1ae14d08b3..dd15f73fc1 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcTestFixture.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcTestFixture.cs @@ -2,62 +2,105 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Reflection; -using System.Runtime.Versioning; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Mvc.Actions; using Microsoft.AspNet.TestHost; +using Microsoft.AspNet.Testing; using Microsoft.Dnx.Runtime; using Microsoft.Dnx.Runtime.Infrastructure; using Microsoft.Framework.DependencyInjection; +using Microsoft.Framework.Logging; +using Microsoft.Framework.Logging.Testing; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class MvcFixture : IDisposable + public class MvcTestFixture : IDisposable { - public MvcFixture(object startupInstance) + private readonly TestServer _server; + + public MvcTestFixture(object startupInstance) { var startupTypeInfo = startupInstance.GetType().GetTypeInfo(); - var configureMethod = (Action)startupTypeInfo + var configureApplication = (Action)startupTypeInfo .DeclaredMethods - .First(m => m.Name == "Configure") - .CreateDelegate(typeof(Action), startupInstance); + .FirstOrDefault(m => m.Name == "Configure" && m.GetParameters().Length == 1) + ?.CreateDelegate(typeof(Action), startupInstance); + if (configureApplication == null) + { + var configureWithLogger = (Action)startupTypeInfo + .DeclaredMethods + .FirstOrDefault(m => m.Name == "Configure" && m.GetParameters().Length == 2) + ?.CreateDelegate(typeof(Action), startupInstance); + Debug.Assert(configureWithLogger != null); - var configureServices = (Action)startupTypeInfo + configureApplication = application => configureWithLogger(application, NullLoggerFactory.Instance); + } + + var buildServices = (Func)startupTypeInfo .DeclaredMethods - .First(m => m.Name == "ConfigureServices") - .CreateDelegate(typeof(Action), startupInstance); + .FirstOrDefault(m => m.Name == "ConfigureServices" && m.ReturnType == typeof(IServiceProvider)) + ?.CreateDelegate(typeof(Func), startupInstance); + if (buildServices == null) + { + var configureServices = (Action)startupTypeInfo + .DeclaredMethods + .FirstOrDefault(m => m.Name == "ConfigureServices" && m.ReturnType == typeof(void)) + ?.CreateDelegate(typeof(Action), startupInstance); + Debug.Assert(configureServices != null); - Server = TestServer.Create( - CallContextServiceLocator.Locator.ServiceProvider, - configureMethod, - configureServices: InitializeServices(startupTypeInfo.Assembly, configureServices)); + buildServices = services => + { + configureServices(services); + return services.BuildServiceProvider(); + }; + } - Client = Server.CreateClient(); + // RequestLocalizationOptions saves the current culture when constructed, potentially changing response + // localization i.e. RequestLocalizationMiddleware behavior. Ensure the saved culture + // (DefaultRequestCulture) is consistent regardless of system configuration or personal preferences. + using (new CultureReplacer()) + { + _server = TestServer.Create( + CallContextServiceLocator.Locator.ServiceProvider, + configureApplication, + configureServices: InitializeServices(startupTypeInfo.Assembly, buildServices)); + } + + Client = _server.CreateClient(); Client.BaseAddress = new Uri("http://localhost"); } - public TestServer Server { get; } - public HttpClient Client { get; } public void Dispose() { Client.Dispose(); - Server.Dispose(); + _server.Dispose(); } - public static Func InitializeServices( + protected virtual void AddAdditionalServices(IServiceCollection services) + { + } + + private Func InitializeServices( Assembly startupAssembly, - Action configureServices) + Func buildServices) { var applicationServices = CallContextServiceLocator.Locator.ServiceProvider; var libraryManager = applicationServices.GetRequiredService(); + // When an application executes in a regular context, the application base path points to the root + // directory where the application is located, for example .../samples/MvcSample.Web. However, when + // executing an application as part of a test, the ApplicationBasePath of the IApplicationEnvironment + // points to the root folder of the test project. + // To compensate, we need to calculate the correct project path and override the application + // environment value so that components like the view engine work properly in the context of the test. var applicationName = startupAssembly.GetName().Name; var library = libraryManager.GetLibrary(applicationName); var applicationRoot = Path.GetDirectoryName(library.Path); @@ -73,47 +116,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests hostingEnvironment.Initialize(applicationRoot, "Production"); services.AddInstance(hostingEnvironment); + // Inject a custom assembly provider. Overrides AddMvc() because that uses TryAdd(). var assemblyProvider = new StaticAssemblyProvider(); assemblyProvider.CandidateAssemblies.Add(startupAssembly); services.AddInstance(assemblyProvider); - configureServices(services); + AddAdditionalServices(services); - return services.BuildServiceProvider(); + return buildServices(services); }; } - - private class TestApplicationEnvironment : IApplicationEnvironment - { - private readonly IApplicationEnvironment _original; - - public TestApplicationEnvironment(IApplicationEnvironment original, string name, string path) - { - _original = original; - - ApplicationName = name; - ApplicationBasePath = path; - } - - public string ApplicationBasePath { get; } - - public string ApplicationName { get; } - - public string ApplicationVersion => _original.ApplicationVersion; - - public string Configuration => _original.Configuration; - - public FrameworkName RuntimeFramework => _original.RuntimeFramework; - - public object GetData(string name) - { - return _original.GetData(name); - } - - public void SetData(string name, object value) - { - _original.SetData(name, value); - } - } } } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcTestFixtureOfT.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcTestFixtureOfT.cs index 9a3ce4c2e8..39f97d3766 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcTestFixtureOfT.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/MvcTestFixtureOfT.cs @@ -3,10 +3,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class MvcFixture : MvcFixture + public class MvcTestFixture : MvcTestFixture where TStartup : new() { - public MvcFixture() + public MvcTestFixture() : base(new TStartup()) { } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/OutputFormatterTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/OutputFormatterTest.cs index 86ceedad16..aa95bbe546 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/OutputFormatterTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/OutputFormatterTest.cs @@ -1,22 +1,22 @@ // 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.Net; +using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; -using ContentNegotiationWebSite; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class OutputFormatterTest + public class OutputFormatterTest : IClassFixture> { - private const string SiteName = nameof(ContentNegotiationWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public OutputFormatterTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("ReturnTaskOfString")] @@ -26,13 +26,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task StringOutputFormatter_ForStringValues_GetsSelectedReturnsTextPlainContentType(string actionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedContentType = MediaTypeHeaderValue.Parse("text/plain;charset=utf-8"); var expectedBody = actionName; // Act - var response = await client.GetAsync("http://localhost/TextPlain/" + actionName); + var response = await Client.GetAsync("http://localhost/TextPlain/" + actionName); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -46,12 +44,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task JsonOutputFormatter_ForNonStringValue_GetsSelected(string actionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); // Act - var response = await client.GetAsync("http://localhost/TextPlain/" + actionName); + var response = await Client.GetAsync("http://localhost/TextPlain/" + actionName); // Assert Assert.Equal(expectedContentType, response.Content.Headers.ContentType); @@ -62,12 +58,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("ReturnVoid")] public async Task NoContentFormatter_ForVoidAndTaskReturnType_DoesNotRun(string actionName) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/NoContent/" + actionName); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/NoContent/" + actionName); // Assert Assert.Null(response.Content.Headers.ContentType); @@ -84,12 +76,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("ReturnObject_NullValue")] public async Task NoContentFormatter_ForNullValue_ByDefault_GetsSelectedAndWritesResponse(string actionName) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/NoContent/" + actionName); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/NoContent/" + actionName); // Assert Assert.Null(response.Content.Headers.ContentType); @@ -107,12 +95,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task NoContentFormatter_ForNullValue_AndTreatNullAsNoContentFlagSetToFalse_DoesNotGetSelected(string actionName) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/NoContentDoNotTreatNullValueAsNoContent/" + + // Arrange & Act + var response = await Client.GetAsync("http://localhost/NoContentDoNotTreatNullValueAsNoContent/" + actionName); // Assert diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/PrecompilationTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/PrecompilationTest.cs index 7588f31a1d..85d399f60f 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/PrecompilationTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/PrecompilationTest.cs @@ -5,6 +5,7 @@ using System; using System.IO; using System.Linq; using System.Net; +using System.Net.Http; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNet.Builder; @@ -17,13 +18,20 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class PrecompilationTest + public class PrecompilationTest : IClassFixture> { private const string SiteName = nameof(PrecompilationWebSite); private static readonly TimeSpan _cacheDelayInterval = TimeSpan.FromSeconds(1); private readonly Action _app = new Startup().Configure; private readonly Action _configureServices = new Startup().ConfigureServices; + public PrecompilationTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } + [ConditionalFact] [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task PrecompiledView_RendersCorrectly() @@ -90,11 +98,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests @"Value set inside DNXCORE50 " + assemblyNamePrefix; #endif - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - // Act - var response = await client.GetAsync("http://localhost/Home/PrecompiledViewsCanConsumeCompilationOptions"); + var response = await Client.GetAsync("http://localhost/Home/PrecompiledViewsCanConsumeCompilationOptions"); var responseContent = await response.Content.ReadAsStringAsync(); // Assert @@ -112,11 +117,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests @" data-val-range=""The field Age must be between 10 and 100."" data-val-range-max=""100"" "+ @"data-val-range-min=""10"" data-val-required=""The Age field is required."" " + @"id=""Age"" name=""Age"" value="""" />Back to List"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var response = await client.GetStringAsync("http://localhost/TagHelpers/Add"); + var response = await Client.GetStringAsync("http://localhost/TagHelpers/Add"); // Assert var responseLines = response.Split(new[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); @@ -131,11 +134,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Arrange var assemblyNamePrefix = GetAssemblyNamePrefix(); var expected = @"root-content"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var response = await client.GetStringAsync("http://localhost/TagHelpers/Remove"); + var response = await Client.GetStringAsync("http://localhost/TagHelpers/Remove"); // Assert var responseLines = response.Split(new[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/RazorEmbeddedViewsTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/RazorEmbeddedViewsTest.cs index 44a110f60e..a7bf7385d9 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/RazorEmbeddedViewsTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/RazorEmbeddedViewsTest.cs @@ -1,31 +1,29 @@ // 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.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using RazorEmbeddedViewsWebSite; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class RazorEmbeddedViewsTest + public class RazorEmbeddedViewsTest : IClassFixture> { - private const string SiteName = nameof(RazorEmbeddedViewsWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public RazorEmbeddedViewsTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task RazorViewEngine_UsesFileProviderOnViewEngineOptionsToLocateViews() { // Arrange var expectedMessage = "Hello test-user, this is /RazorEmbeddedViews_Home"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var response = await client.GetStringAsync("http://localhost/RazorEmbeddedViews_Home?User=test-user"); + var response = await Client.GetStringAsync("http://localhost/RazorEmbeddedViews_Home?User=test-user"); // Assert Assert.Equal(expectedMessage, response); @@ -36,12 +34,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expectedMessage = "Hello admin-user, this is /Restricted/RazorEmbeddedViews_Admin/Login"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var target = "http://localhost/Restricted/RazorEmbeddedViews_Admin/Login?AdminUser=admin-user"; // Act - var response = await client.GetStringAsync(target); + var response = await Client.GetStringAsync(target); // Assert Assert.Equal(expectedMessage, response); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/RazorFileSystemCaseSensitivityTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/RazorFileSystemCaseSensitivityTest.cs index 31081d7dd3..9400628654 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/RazorFileSystemCaseSensitivityTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/RazorFileSystemCaseSensitivityTest.cs @@ -1,33 +1,31 @@ // 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.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using RazorEmbeddedViewsWebSite; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { // The EmbeddedFileSystem used by RazorEmbeddedViewsWebSite performs case sensitive lookups for files. // These tests verify that we correctly normalize route values when constructing view lookup paths. - public class RazorFileSystemCaseSensitivityTest + public class RazorFileSystemCaseSensitivityTest : IClassFixture> { - private const string SiteName = nameof(RazorEmbeddedViewsWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public RazorFileSystemCaseSensitivityTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task RazorViewEngine_NormalizesActionName_WhenLookingUpViewPaths() { // Arrange var expectedMessage = "Hello test-user, this is /RazorEmbeddedViews_Home"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var response = await client.GetStringAsync("http://localhost/RazorEmbeddedViews_Home/index?User=test-user"); + var response = await Client.GetStringAsync("http://localhost/RazorEmbeddedViews_Home/index?User=test-user"); // Assert Assert.Equal(expectedMessage, response); @@ -38,11 +36,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expectedMessage = "Hello test-user, this is /razorembeddedviews_home"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var response = await client.GetStringAsync("http://localhost/razorembeddedviews_home?User=test-user"); + var response = await Client.GetStringAsync("http://localhost/razorembeddedviews_home?User=test-user"); // Assert Assert.Equal(expectedMessage, response); @@ -53,12 +49,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expectedMessage = "Hello admin-user, this is /restricted/razorembeddedviews_admin/login"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var target = "http://localhost/restricted/razorembeddedviews_admin/login?AdminUser=admin-user"; // Act - var response = await client.GetStringAsync(target); + var response = await Client.GetStringAsync(target); // Assert Assert.Equal(expectedMessage, response); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/RazorViewLocationSpecificationTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/RazorViewLocationSpecificationTest.cs index 1715bc6e58..6ff2c9cd13 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/RazorViewLocationSpecificationTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/RazorViewLocationSpecificationTest.cs @@ -1,21 +1,22 @@ // 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.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using RazorWebSite; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class RazorViewLocationSpecificationTest + public class RazorViewLocationSpecificationTest : IClassFixture> { private const string BaseUrl = "http://localhost/ViewNameSpecification_Home/"; - private const string SiteName = nameof(RazorWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + + public RazorViewLocationSpecificationTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("LayoutSpecifiedWithPartialPathInViewStart")] @@ -24,15 +25,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("LayoutSpecifiedWithPartialPathInViewStart_ForViewSpecifiedWithAppRelativePathWithExtension")] public async Task PartialLayoutPaths_SpecifiedInViewStarts_GetResolvedByViewEngine(string action) { + // Arrange var expected = @" _ViewStart that specifies partial Layout "; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync(BaseUrl + action); + var body = await Client.GetStringAsync(BaseUrl + action); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -45,14 +45,13 @@ _ViewStart that specifies partial Layout [InlineData("LayoutSpecifiedWithPartialPathInPageWithAppRelativePathWithExtension")] public async Task PartialLayoutPaths_SpecifiedInPage_GetResolvedByViewEngine(string actionName) { + // Arrange var expected = @"Layout specified in page "; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync(BaseUrl + actionName); + var body = await Client.GetStringAsync(BaseUrl + actionName); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -63,14 +62,13 @@ _ViewStart that specifies partial Layout [InlineData("LayoutSpecifiedWithNonPartialPathWithExtension")] public async Task NonPartialLayoutPaths_GetResolvedByViewEngine(string actionName) { + // Arrange var expected = @"Page With Non Partial Layout "; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync(BaseUrl + actionName); + var body = await Client.GetStringAsync(BaseUrl + actionName); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -82,16 +80,15 @@ _ViewStart that specifies partial Layout [InlineData("ViewWithPartial_SpecifiedWithAbsoluteNameAndExtension")] public async Task PartialsCanBeSpecifiedWithPartialPath(string actionName) { + // Arrange var expected = @" Non Shared Partial "; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync(BaseUrl + actionName); + var body = await Client.GetStringAsync(BaseUrl + actionName); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/RemoteAttributeValidationTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/RemoteAttributeValidationTest.cs index 2b67b60d21..5d84875d64 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/RemoteAttributeValidationTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/RemoteAttributeValidationTest.cs @@ -1,26 +1,26 @@ // 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.Collections.Generic; using System.Net; using System.Net.Http; using System.Reflection; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class RemoteAttributeValidationTest + public class RemoteAttributeValidationTest : IClassFixture> { - private const string SiteName = nameof(ValidationWebSite); private static readonly Assembly _resourcesAssembly = typeof(RemoteAttributeValidationTest).GetTypeInfo().Assembly; - private readonly Action _app = new ValidationWebSite.Startup().Configure; - private readonly Action _configureServices = new ValidationWebSite.Startup().ConfigureServices; + public RemoteAttributeValidationTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("Aria", "/Aria")] @@ -28,15 +28,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task RemoteAttribute_LeadsToExpectedValidationAttributes(string areaName, string pathSegment) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var outputFile = "compiler/resources/ValidationWebSite." + areaName + ".RemoteAttribute_Home.Create.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); var url = "http://localhost" + pathSegment + "/RemoteAttribute_Home/Create"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -65,13 +63,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests string expectedContent) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost" + pathSegment + "/RemoteAttribute_Verify/IsIdAvailable?UserId1=Joe1&UserId2=Joe2&UserId3=Joe3&UserId4=Joe4"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -89,8 +85,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests string expectedContent) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var url = "http://localhost" + pathSegment + "/RemoteAttribute_Verify/IsIdAvailable"; var contentDictionary = new Dictionary { @@ -102,7 +96,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var content = new FormUrlEncodedContent(contentDictionary); // Act - var response = await client.PostAsync(url, content); + var response = await Client.PostAsync(url, content); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/RequestServicesTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/RequestServicesTest.cs index 8d4be447f0..c52a10e8f2 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/RequestServicesTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/RequestServicesTest.cs @@ -5,19 +5,20 @@ using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { // Each of these tests makes two requests, because we want each test to verify that the data is // PER-REQUEST and does not linger around to impact the next request. - public class RequestServicesTest + public class RequestServicesTest : IClassFixture> { - private const string SiteName = nameof(RequestServicesWebSite); - private readonly Action _app = new RequestServicesWebSite.Startup().Configure; - private readonly Action _configureServices = new RequestServicesWebSite.Startup().ConfigureServices; + public RequestServicesTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("http://localhost/RequestScoped/FromController")] @@ -28,19 +29,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("http://localhost/Other/FromActionArgument")] public async Task RequestServices(string url) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act & Assert for (var i = 0; i < 2; i++) { + // Arrange var requestId = Guid.NewGuid().ToString(); var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.TryAddWithoutValidation("RequestId", requestId); - var response = await client.SendAsync(request); + // Act + var response = await Client.SendAsync(request); + // Assert var body = (await response.Content.ReadAsStringAsync()).Trim(); Assert.Equal(requestId, body); } @@ -50,9 +49,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task RequestServices_TagHelper() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/Other/FromTagHelper"; // Act & Assert @@ -62,7 +58,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.TryAddWithoutValidation("RequestId", requestId); - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var body = (await response.Content.ReadAsStringAsync()).Trim(); @@ -75,9 +71,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task RequestServices_ActionConstraint() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/Other/FromActionConstraint"; // Act & Assert @@ -85,7 +78,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var request1 = new HttpRequestMessage(HttpMethod.Get, url); request1.Headers.TryAddWithoutValidation("RequestId", requestId1); - var response1 = await client.SendAsync(request1); + var response1 = await Client.SendAsync(request1); var body1 = (await response1.Content.ReadAsStringAsync()).Trim(); Assert.Equal(requestId1, body1); @@ -94,7 +87,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var request2 = new HttpRequestMessage(HttpMethod.Get, url); request2.Headers.TryAddWithoutValidation("RequestId", requestId2); - var response2 = await client.SendAsync(request2); + var response2 = await Client.SendAsync(request2); Assert.Equal(HttpStatusCode.NotFound, response2.StatusCode); } } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/RespectBrowserAcceptHeaderTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/RespectBrowserAcceptHeaderTests.cs index 07879fd4a0..d03e70e3ff 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/RespectBrowserAcceptHeaderTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/RespectBrowserAcceptHeaderTests.cs @@ -1,24 +1,24 @@ // 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.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class RespectBrowserAcceptHeaderTests + public class RespectBrowserAcceptHeaderTests : IClassFixture> { - private const string SiteName = nameof(FormatterWebSite); - private readonly Action _app = new FormatterWebSite.Startup().Configure; - private readonly Action _configureServices = new FormatterWebSite.Startup().ConfigureServices; + public RespectBrowserAcceptHeaderTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("application/xml,*/*;0.2")] @@ -26,12 +26,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AllMediaRangeAcceptHeader_FirstFormatterInListWritesResponse(string acceptHeader) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.DefaultRequestHeaders.Add("Accept", acceptHeader); + var request = RequestWithAccept("http://localhost/RespectBrowserAcceptHeader/EmployeeInfo", acceptHeader); // Act - var response = await client.GetAsync("http://localhost/RespectBrowserAcceptHeader/EmployeeInfo"); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -50,15 +48,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AllMediaRangeAcceptHeader_ProducesAttributeIsHonored(string acceptHeader) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.DefaultRequestHeaders.Add("Accept", acceptHeader); - var expectedResponseData = "20Mike" + - ""; + var request = RequestWithAccept( + "http://localhost/RespectBrowserAcceptHeader/EmployeeInfoWithProduces", + acceptHeader); + var expectedResponseData = + "20Mike" + + ""; // Act - var response = await client.GetAsync("http://localhost/RespectBrowserAcceptHeader/EmployeeInfoWithProduces"); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -77,16 +76,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AllMediaRangeAcceptHeader_WithContentTypeHeader_ContentTypeIsHonored(string acceptHeader) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.DefaultRequestHeaders.Add("Accept", acceptHeader); - var requestData = "35Jimmy" + - ""; + var requestData = + "35Jimmy" + + ""; + var request = RequestWithAccept("http://localhost/RespectBrowserAcceptHeader/CreateEmployee", acceptHeader); + request.Content = new StringContent(requestData, Encoding.UTF8, "application/xml"); + request.Method = HttpMethod.Post; // Act - var response = await client.PostAsync("http://localhost/RespectBrowserAcceptHeader/CreateEmployee", - new StringContent(requestData, Encoding.UTF8, "application/xml")); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -96,5 +95,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var responseData = await response.Content.ReadAsStringAsync(); Assert.Equal(requestData, responseData); } + + private static HttpRequestMessage RequestWithAccept(string url, string accept) + { + var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.Add("Accept", accept); + + return request; + } } } \ No newline at end of file diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ResponseCacheTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ResponseCacheTest.cs index 516ebf852c..60c34d42f4 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ResponseCacheTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ResponseCacheTest.cs @@ -4,29 +4,26 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using ResponseCacheWebSite; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ResponseCacheTest + public class ResponseCacheTest : IClassFixture> { - private const string SiteName = nameof(ResponseCacheWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ResponseCacheTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task ResponseCache_SetsAllHeaders() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheHeaders/Index"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/CacheHeaders/Index"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -50,12 +47,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [MemberData(nameof(CacheControlData))] public async Task ResponseCache_SetsDifferentCacheControlHeaders(string url, string expected) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync(url); + // Arrange & Act + var response = await Client.GetAsync(url); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -65,13 +58,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task SetsHeadersForAllActionsOfClass() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response1 = await client.GetAsync("http://localhost/ClassLevelCache/GetHelloWorld"); - var response2 = await client.GetAsync("http://localhost/ClassLevelCache/GetFooBar"); + // Arrange & Act + var response1 = await Client.GetAsync("http://localhost/ClassLevelCache/GetHelloWorld"); + var response2 = await Client.GetAsync("http://localhost/ClassLevelCache/GetFooBar"); // Assert var data = Assert.Single(response1.Headers.GetValues("Cache-control")); @@ -88,12 +77,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task HeadersSetInActionOverridesTheOnesInClass() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ClassLevelCache/ConflictExistingHeader"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ClassLevelCache/ConflictExistingHeader"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -103,12 +88,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task HeadersToNotCacheAParticularAction() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ClassLevelCache/DoNotCacheThisAction"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ClassLevelCache/DoNotCacheThisAction"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -118,12 +99,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ClassLevelHeadersAreUnsetByActionLevelHeaders() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ClassLevelNoStore/CacheThisAction"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ClassLevelNoStore/CacheThisAction"); // Assert var data = Assert.Single(response.Headers.GetValues("Vary")); @@ -138,12 +115,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task SetsCacheControlPublicByDefault() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheHeaders/SetsCacheControlPublicByDefault"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/CacheHeaders/SetsCacheControlPublicByDefault"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -153,13 +126,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ThrowsWhenDurationIsNotSet() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act & Assert + // Arrange & Act var ex = await Assert.ThrowsAsync( - () => client.GetAsync("http://localhost/CacheHeaders/ThrowsWhenDurationIsNotSet")); + () => Client.GetAsync("http://localhost/CacheHeaders/ThrowsWhenDurationIsNotSet")); Assert.Equal( "If the 'NoStore' property is not set to true, 'Duration' property must be specified.", ex.Message); @@ -169,12 +138,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResponseCache_SetsAllHeaders_FromCacheProfile() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheProfiles/PublicCache30Sec"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/CacheProfiles/PublicCache30Sec"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -184,12 +149,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResponseCache_SetsAllHeaders_ChosesTheRightProfile() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheProfiles/PrivateCache30Sec"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/CacheProfiles/PrivateCache30Sec"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -199,12 +160,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResponseCache_SetsNoCacheHeaders() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheProfiles/NoCache"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/CacheProfiles/NoCache"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -216,12 +173,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResponseCache_AddsHeaders() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheProfiles/CacheProfileAddParameter"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/CacheProfiles/CacheProfileAddParameter"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -233,12 +186,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResponseCache_ModifiesHeaders() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheProfiles/CacheProfileOverride"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/CacheProfiles/CacheProfileOverride"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -248,12 +197,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResponseCache_FallbackToFilter_IfNoAttribute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheProfiles/FallbackToFilter"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/CacheProfiles/FallbackToFilter"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -265,12 +210,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResponseCacheAttribute_OnAction_OverridesTheValuesOnClass() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/ClassLevelNoStore/CacheThisActionWithProfileSettings"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/ClassLevelNoStore/CacheThisActionWithProfileSettings"); // Assert var data = Assert.Single(response.Headers.GetValues("Vary")); @@ -286,12 +227,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResponseCacheAttribute_OverridesProfileDuration_FromAttributeProperty() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecTo15Sec"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecTo15Sec"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -301,12 +238,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResponseCacheAttribute_OverridesProfileLocation_FromAttributeProperty() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecToPrivateCache"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecToPrivateCache"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -316,12 +249,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResponseCacheAttribute_OverridesProfileNoStore_FromAttributeProperty() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecToNoStore"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecToNoStore"); // Assert var data = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -331,12 +260,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResponseCacheAttribute_OverridesProfileVaryBy_FromAttributeProperty() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecWithVaryByAcceptToVaryByTest"); + // Arrange & Act + var response = await Client.GetAsync( + "http://localhost/CacheProfileOverrides/PublicCache30SecWithVaryByAcceptToVaryByTest"); // Assert var cacheControl = Assert.Single(response.Headers.GetValues("Cache-control")); @@ -348,12 +274,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ResponseCacheAttribute_OverridesProfileVaryBy_FromAttributeProperty_AndRemovesVaryHeader() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecWithVaryByAcceptToVaryByNone"); + // Arrange & Act + var response = await Client.GetAsync( + "http://localhost/CacheProfileOverrides/PublicCache30SecWithVaryByAcceptToVaryByNone"); // Assert var cacheControl = Assert.Single(response.Headers.GetValues("Cache-control")); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/RoundTripTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/RoundTripTests.cs index d834e043ae..15a7c26ada 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/RoundTripTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/RoundTripTests.cs @@ -1,13 +1,9 @@ // 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.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using ModelBindingWebSite; using ModelBindingWebSite.Models; using Newtonsoft.Json; using Xunit; @@ -22,28 +18,28 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests /// 3) The server returns the bound object. We verify if the property specified by the expression in step 1 /// has the expected value. /// - public class RoundTripTests + public class RoundTripTests : IClassFixture> { - private const string SiteName = nameof(ModelBindingWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public RoundTripTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } - // Uses the expression p => p.Name [Fact] public async Task RoundTrippedValues_GetsModelBound_ForSimpleExpressions() { // Arrange var expected = "test-name"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var expression = await client.GetStringAsync("http://localhost/RoundTrip/GetPerson"); + var expression = await Client.GetStringAsync("http://localhost/RoundTrip/GetPerson"); var keyValuePairs = new[] { new KeyValuePair(expression, expected) }; - var result = await GetPerson(client, keyValuePairs); + var result = await GetPerson(Client, keyValuePairs); // Assert Assert.Equal("Name", expression); @@ -56,16 +52,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = 40; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var expression = await client.GetStringAsync("http://localhost/RoundTrip/GetPersonParentAge"); + var expression = await Client.GetStringAsync("http://localhost/RoundTrip/GetPersonParentAge"); var keyValuePairs = new[] { new KeyValuePair(expression, expected.ToString()) }; - var result = await GetPerson(client, keyValuePairs); + var result = await GetPerson(Client, keyValuePairs); // Assert Assert.Equal("Parent.Age", expression); @@ -78,16 +72,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = 12; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var expression = await client.GetStringAsync("http://localhost/RoundTrip/GetPersonDependentAge"); + var expression = await Client.GetStringAsync("http://localhost/RoundTrip/GetPersonDependentAge"); var keyValuePairs = new[] { new KeyValuePair(expression, expected.ToString()) }; - var result = await GetPerson(client, keyValuePairs); + var result = await GetPerson(Client, keyValuePairs); // Assert Assert.Equal("Dependents[0].Age", expression); @@ -99,17 +91,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task RoundTrippedValues_GetsModelBound_ForStringIndexedProperties() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expected = "6 feet"; // Act - var expression = await client.GetStringAsync("http://localhost/RoundTrip/GetPersonParentHeightAttribute"); + var expression = await Client.GetStringAsync("http://localhost/RoundTrip/GetPersonParentHeightAttribute"); var keyValuePairs = new[] { new KeyValuePair(expression, expected), }; - var result = await GetPerson(client, keyValuePairs); + var result = await GetPerson(Client, keyValuePairs); // Assert Assert.Equal("Parent.Attributes[height]", expression); @@ -122,16 +112,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var expected = "test-nested-name"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var expression = await client.GetStringAsync("http://localhost/RoundTrip/GetDependentPersonName"); + var expression = await Client.GetStringAsync("http://localhost/RoundTrip/GetDependentPersonName"); var keyValuePairs = new[] { new KeyValuePair(expression, expected.ToString()) }; - var result = await GetPerson(client, keyValuePairs); + var result = await GetPerson(Client, keyValuePairs); // Assert Assert.Equal("Dependents[0].Dependents[0].Name", expression); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/RouteDataTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/RouteDataTest.cs index 4e8fdc453e..b216f36412 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/RouteDataTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/RouteDataTest.cs @@ -1,36 +1,33 @@ // 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.Collections.Generic; using System.Net; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.Actions; using Microsoft.AspNet.Mvc.Routing; using Microsoft.AspNet.Routing; using Microsoft.AspNet.Routing.Template; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class RouteDataTest + public class RouteDataTest : IClassFixture> { - private const string SiteName = nameof(BasicWebSite); - private readonly Action _app = new BasicWebSite.Startup().Configure; - private readonly Action _configureServices = new BasicWebSite.Startup().ConfigureServices; + public RouteDataTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task RouteData_Routers_ConventionalRoute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Routing/Conventional"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Routing/Conventional"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -38,7 +35,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - Assert.Equal(new string[] + Assert.Equal( + new string[] { typeof(RouteCollection).FullName, typeof(TemplateRoute).FullName, @@ -50,12 +48,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task RouteData_Routers_AttributeRoute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Routing/Attribute"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Routing/Attribute"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -80,10 +74,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task RouteData_DataTokens_FilterCanSetDataTokens() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - var response = await client.GetAsync("http://localhost/Routing/DataTokens"); + var response = await Client.GetAsync("http://localhost/Routing/DataTokens"); // Guard var body = await response.Content.ReadAsStringAsync(); @@ -92,7 +83,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests Assert.Single(result.DataTokens, kvp => kvp.Key == "actionName" && ((string)kvp.Value) == "DataTokens"); // Act - response = await client.GetAsync("http://localhost/Routing/Conventional"); + response = await Client.GetAsync("http://localhost/Routing/Conventional"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/RoutingLowercaseUrlTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/RoutingLowercaseUrlTest.cs index 6fb123afca..fd86768356 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/RoutingLowercaseUrlTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/RoutingLowercaseUrlTest.cs @@ -1,22 +1,22 @@ // 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.Net; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class RoutingLowercaseUrlTest + // This website sets the generation of lowercase URLs to true + public class RoutingLowercaseUrlTest : IClassFixture> { - private const string SiteName = nameof(LowercaseUrlsWebSite); + public RoutingLowercaseUrlTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } - // This website sets the generation of lowercase URLs to true - private readonly Action _app = new LowercaseUrlsWebSite.Startup().Configure; - private readonly Action _configureServices = new LowercaseUrlsWebSite.Startup().ConfigureServices; + public HttpClient Client { get; } [Theory] // Generating lower case URL doesnt lowercase the query parameters @@ -35,12 +35,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("Api/Employee/GetEmployee/JohnDoe", "/api/employee/getemployee/johndoe")] public async Task GenerateLowerCaseUrlsTests(string path, string expectedUrl) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/" + path); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/" + path); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/RoutingTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/RoutingTests.cs index 8773e89ded..be11efa8eb 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/RoutingTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/RoutingTests.cs @@ -7,29 +7,26 @@ using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Routing; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class RoutingTests + public class RoutingTests : IClassFixture> { - private const string SiteName = nameof(RoutingWebSite); - private readonly Action _app = new RoutingWebSite.Startup().Configure; - private readonly Action _configureServices = new RoutingWebSite.Startup().ConfigureServices; + public RoutingTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task ConventionalRoutedController_ActionIsReachable() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/Index"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/Index"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -52,12 +49,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ConventionalRoutedController_ActionIsReachable_WithDefaults() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -80,12 +73,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ConventionalRoutedController_NonActionIsNotReachable() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/NotAnAction"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/NotAnAction"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -94,12 +83,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ConventionalRoutedController_InArea_ActionIsReachable() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Travel/Flight/Index"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Travel/Flight/Index"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -123,12 +108,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ConventionalRoutedController_InArea_ActionBlockedByHttpMethod() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Travel/Flight/BuyTickets"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Travel/Flight/BuyTickets"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -139,12 +120,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("CustomPath", "/Home/OptionalPath/CustomPath")] public async Task ConventionalRoutedController_WithOptionalSegment(string optionalSegment, string expected) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/OptionalPath/" + optionalSegment); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/OptionalPath/" + optionalSegment); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -158,12 +135,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AttributeRoutedAction_IsReachable() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Store/Shop/Products"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Store/Shop/Products"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -189,12 +162,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("http://localhost/api/v2/Maps")] public async Task AttributeRoutedAction_MultipleRouteAttributes_WorksWithNameAndOrder(string url) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync(url); + // Arrange & Act + var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -219,11 +188,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var url = "http://localhost/api/v2/Maps"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Post, url)); + var response = await Client.SendAsync(new HttpRequestMessage(HttpMethod.Post, url)); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -247,11 +214,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests { // Arrange var url = "http://localhost/api/v1/Maps"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var response = await client.SendAsync(new HttpRequestMessage(new HttpMethod("POST"), url)); + var response = await Client.SendAsync(new HttpRequestMessage(new HttpMethod("POST"), url)); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -266,12 +231,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests string url, string method) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.SendAsync(new HttpRequestMessage(new HttpMethod(method), url)); + // Arrange & Act + var response = await Client.SendAsync(new HttpRequestMessage(new HttpMethod(method), url)); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -296,12 +257,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_MultipleHttpAttributesAndTokenReplacement(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedUrl = new Uri(url).AbsolutePath; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -330,12 +289,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests string method) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedUrl = new Uri(url).AbsolutePath; // Act - var response = await client.SendAsync(new HttpRequestMessage(new HttpMethod(method), url)); + var response = await Client.SendAsync(new HttpRequestMessage(new HttpMethod(method), url)); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -345,12 +302,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AttributeRoutedAction_IsNotReachableWithTraditionalRoute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Store/ListProducts"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Store/ListProducts"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -361,12 +314,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AttributeRoutedAction_TriedBeforeConventionalRouting() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Home/About"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Home/About"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -382,12 +331,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AttributeRoutedAction_ControllerLevelRoute_WithActionParameter_IsReachable() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Blog/Edit/5"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Blog/Edit/5"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -416,12 +361,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AttributeRoutedAction_ControllerLevelRoute_IsReachable() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Employee"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Employee"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -429,7 +370,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Contains("/api/Employee", result.ExpectedUrls); Assert.Equal("Employee", result.Controller); Assert.Equal("List", result.Action); @@ -446,12 +386,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_RouteAttributeOnAction_IsReachable(string method) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Store/Shop/Orders"); // Act - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -473,12 +411,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_RouteAttributeOnActionAndController_IsReachable(string method) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/api/Employee/5/Salary"); // Act - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -495,12 +431,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_RouteAttributeOnActionAndHttpGetOnDifferentAction_ReachesHttpGetAction() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Store/Shop/Orders"); // Act - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -520,12 +454,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_ControllerLevelRoute_WithAcceptVerbs_IsReachable(string verb) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(new HttpMethod(verb), "http://localhost/api/Employee"); // Act - var message = new HttpRequestMessage(new HttpMethod(verb), "http://localhost/api/Employee"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -544,12 +476,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_ControllerLevelRoute_WithAcceptVerbsAndRouteTemplate_IsReachable(string verb) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(new HttpMethod(verb), "http://localhost/api/Employee/Manager"); // Act - var message = new HttpRequestMessage(new HttpMethod(verb), "http://localhost/api/Employee/Manager"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -570,13 +500,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_AcceptVerbsAndRouteTemplate_IsReachable(string verb, string path) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedUrl = "/Bank"; + var message = new HttpRequestMessage(new HttpMethod(verb), "http://localhost/" + path); // Act - var message = new HttpRequestMessage(new HttpMethod(verb), "http://localhost/" + path); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -593,12 +521,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_WithCustomHttpAttributes_IsReachable() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(new HttpMethod("MERGE"), "http://localhost/api/Employee/5"); // Act - var message = new HttpRequestMessage(new HttpMethod("MERGE"), "http://localhost/api/Employee/5"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -606,7 +532,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Contains("/api/Employee/5", result.ExpectedUrls); Assert.Equal("Employee", result.Controller); Assert.Equal("MergeEmployee", result.Action); @@ -619,12 +544,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_ControllerLevelRoute_CombinedWithActionRoute_IsReachable(string verb, string action) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(new HttpMethod(verb), "http://localhost/api/Employee/5/Administrator"); // Act - var message = new HttpRequestMessage(new HttpMethod(verb), "http://localhost/api/Employee/5/Administrator"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -644,12 +567,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AttributeRoutedAction_ActionLevelRouteWithTildeSlash_OverridesControllerLevelRoute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Manager/5"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Manager/5"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -669,12 +588,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AttributeRoutedAction_OverrideActionOverridesOrderOnController() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Team/5"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Team/5"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -694,12 +609,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AttributeRoutedAction_OrderOnActionOverridesOrderOnController() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Teams"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Teams"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -715,12 +626,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AttributeRoutedAction_LinkGeneration_OverrideActionOverridesOrderOnController() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/Organization/5"); + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/Organization/5"); // Assert Assert.NotNull(response); @@ -730,12 +637,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AttributeRoutedAction_LinkGeneration_OrderOnActionOverridesOrderOnController() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/Teams/AllTeams"); + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/Teams/AllTeams"); // Assert Assert.NotNull(response); @@ -747,12 +650,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("CustomName", "/TeamName/CustomName")] public async Task AttributeRoutedAction_PreservesDefaultValue_IfRouteValueIsNull(string teamName, string expected) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync("http://localhost/TeamName/" + teamName); + // Arrange & Act + var body = await Client.GetStringAsync("http://localhost/TeamName/" + teamName); // Assert Assert.NotNull(body); @@ -764,19 +663,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_LinkToSelf() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var url = LinkFrom("http://localhost/api/Employee").To(new { }); // Act - var url = LinkFrom("http://localhost/api/Employee").To(new { }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Employee", result.Controller); Assert.Equal("List", result.Action); @@ -787,19 +683,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_LinkWithAmbientController() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var url = LinkFrom("http://localhost/api/Employee").To(new { action = "Get", id = 5 }); // Act - var url = LinkFrom("http://localhost/api/Employee").To(new { action = "Get", id = 5 }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Employee", result.Controller); Assert.Equal("List", result.Action); @@ -810,20 +703,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_LinkToAttributeRoutedController() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var url = LinkFrom("http://localhost/api/Employee").To(new { action = "ShowPosts", controller = "Blog" }); // Act - var url = LinkFrom("http://localhost/api/Employee").To(new { action = "ShowPosts", controller = "Blog" }); - var response = await client.GetAsync(url); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Employee", result.Controller); Assert.Equal("List", result.Action); @@ -834,19 +723,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_LinkToConventionalController() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var url = LinkFrom("http://localhost/api/Employee").To(new { action = "Index", controller = "Home" }); // Act - var url = LinkFrom("http://localhost/api/Employee").To(new { action = "Index", controller = "Home" }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Employee", result.Controller); Assert.Equal("List", result.Action); @@ -856,22 +742,21 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Theory] [InlineData("GET", "Get")] [InlineData("PUT", "Put")] - public async Task AttributeRoutedAction_LinkWithName_WithNameInheritedFromControllerRoute(string method, string actionName) + public async Task AttributeRoutedAction_LinkWithName_WithNameInheritedFromControllerRoute( + string method, + string actionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/api/Company/5"); // Act - var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/api/Company/5"); - var response = await client.SendAsync(message); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var response = await Client.SendAsync(message); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Company", result.Controller); Assert.Equal(actionName, result.Action); @@ -882,19 +767,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AttributeRoutedAction_LinkWithName_WithNameOverrridenFromController() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.DeleteAsync("http://localhost/api/Company/5"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + // Arrange & Act + var response = await Client.DeleteAsync("http://localhost/api/Company/5"); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Company", result.Controller); Assert.Equal("Delete", result.Action); @@ -906,21 +786,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_Link_WithNonEmptyActionRouteTemplateAndNoActionRouteName() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = LinkFrom("http://localhost") .To(new { id = 5 }); // Act - var response = await client.GetAsync("http://localhost/api/Company/5/Employees"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var response = await Client.GetAsync("http://localhost/api/Company/5/Employees"); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Company", result.Controller); Assert.Equal("GetEmployees", result.Action); @@ -931,19 +807,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AttributeRoutedAction_LinkWithName_WithNonEmptyActionRouteTemplateAndActionRouteName() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Company/5/Departments"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Company/5/Departments"); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Company", result.Controller); Assert.Equal("GetDepartments", result.Action); @@ -959,13 +830,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_ThowsIfConventionalRouteWithTheSameName(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var expectedMessage = "The supplied route name 'DuplicateRoute' is ambiguous and matched more than one route."; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var exception = response.GetServerException(); @@ -976,20 +844,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ConventionalRoutedAction_LinkToArea() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act var url = LinkFrom("http://localhost/") .To(new { action = "BuyTickets", controller = "Flight", area = "Travel" }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + // Act + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Home", result.Controller); Assert.Equal("Index", result.Action); @@ -1000,19 +865,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ConventionalRoutedAction_InArea_ImplicitLinkToArea() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var url = LinkFrom("http://localhost/Travel/Flight").To(new { action = "BuyTickets" }); // Act - var url = LinkFrom("http://localhost/Travel/Flight").To(new { action = "BuyTickets" }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Flight", result.Controller); Assert.Equal("Index", result.Action); @@ -1023,19 +885,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ConventionalRoutedAction_InArea_ExplicitLeaveArea() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var url = LinkFrom("http://localhost/Travel/Flight") + .To(new { action = "Index", controller = "Home", area = "" }); // Act - var url = LinkFrom("http://localhost/Travel/Flight").To(new { action = "Index", controller = "Home", area = "" }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Flight", result.Controller); Assert.Equal("Index", result.Action); @@ -1046,19 +906,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ConventionalRoutedAction_InArea_ImplicitLeaveArea() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var url = LinkFrom("http://localhost/Travel/Flight").To(new { action = "Contact", controller = "Home", }); // Act - var url = LinkFrom("http://localhost/Travel/Flight").To(new { action = "Contact", controller = "Home", }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Flight", result.Controller); Assert.Equal("Index", result.Action); @@ -1069,20 +926,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_LinkToArea() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act var url = LinkFrom("http://localhost/api/Employee") .To(new { action = "Schedule", controller = "Rail", area = "Travel" }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + // Act + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Employee", result.Controller); Assert.Equal("List", result.Action); @@ -1093,19 +947,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_InArea_ImplicitLinkToArea() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var url = LinkFrom("http://localhost/ContosoCorp/Trains/CheckSchedule").To(new { action = "Index" }); // Act - var url = LinkFrom("http://localhost/ContosoCorp/Trains/CheckSchedule").To(new { action = "Index" }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Rail", result.Controller); Assert.Equal("Schedule", result.Action); @@ -1116,20 +967,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_InArea_ExplicitLeaveArea() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act var url = LinkFrom("http://localhost/ContosoCorp/Trains/CheckSchedule") .To(new { action = "Index", controller = "Home", area = "" }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + // Act + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Rail", result.Controller); Assert.Equal("Schedule", result.Action); @@ -1140,20 +988,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_InArea_ImplicitLeaveArea() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act var url = LinkFrom("http://localhost/ContosoCorp/Trains") .To(new { action = "Contact", controller = "Home", }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + // Act + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Rail", result.Controller); Assert.Equal("Index", result.Action); @@ -1164,21 +1009,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_InArea_LinkToConventionalRoutedActionInArea() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act var url = LinkFrom("http://localhost/ContosoCorp/Trains") .To(new { action = "Index", controller = "Flight", }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + // Act + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Rail", result.Controller); Assert.Equal("Index", result.Action); @@ -1189,21 +1030,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ConventionalRoutedAction_InArea_LinkToAttributeRoutedActionInArea() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act var url = LinkFrom("http://localhost/Travel/Flight") .To(new { action = "Index", controller = "Rail", }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + // Act + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Flight", result.Controller); Assert.Equal("Index", result.Action); @@ -1214,21 +1051,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ConventionalRoutedAction_InArea_LinkToAnotherArea() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act var url = LinkFrom("http://localhost/Travel/Flight") .To(new { action = "ListUsers", controller = "UserManagement", area = "Admin" }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + // Act + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Flight", result.Controller); Assert.Equal("Index", result.Action); @@ -1239,21 +1072,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_InArea_LinkToAnotherArea() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act var url = LinkFrom("http://localhost/ContosoCorp/Trains") .To(new { action = "ListUsers", controller = "UserManagement", area = "Admin" }); - var response = await client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + // Act + var response = await Client.GetAsync(url); // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Equal("Rail", result.Controller); Assert.Equal("Index", result.Action); @@ -1263,12 +1092,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ControllerWithCatchAll_CanReachSpecificCountry() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Products/US/GetProducts"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Products/US/GetProducts"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1293,12 +1118,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ControllerWithCatchAll_CannotReachWithoutCountry() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Products/GetProducts"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Products/GetProducts"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -1308,19 +1129,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ControllerWithCatchAll_GenerateLinkForSpecificCountry() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var url = LinkFrom("http://localhost/") + .To(new { action = "GetProducts", controller = "Products", country = "US" }); // Act - var url = - LinkFrom("http://localhost/") - .To(new { action = "GetProducts", controller = "Products", country = "US" }); - var response = await client.GetAsync(url); - - var body = await response.Content.ReadAsStringAsync(); - var result = JsonConvert.DeserializeObject(body); + var response = await Client.GetAsync(url); // Assert + var body = await response.Content.ReadAsStringAsync(); + var result = JsonConvert.DeserializeObject(body); Assert.Equal("/api/Products/US/GetProducts", result.Link); } @@ -1328,19 +1145,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ControllerWithCatchAll_GenerateLinkForFallback() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var url = LinkFrom("http://localhost/") + .To(new { action = "GetProducts", controller = "Products", country = "CA" }); // Act - var url = - LinkFrom("http://localhost/") - .To(new { action = "GetProducts", controller = "Products", country = "CA" }); - var response = await client.GetAsync(url); - - var body = await response.Content.ReadAsStringAsync(); - var result = JsonConvert.DeserializeObject(body); + var response = await Client.GetAsync(url); // Assert + var body = await response.Content.ReadAsStringAsync(); + var result = JsonConvert.DeserializeObject(body); Assert.Equal("/api/Products/CA/GetProducts", result.Link); } @@ -1348,19 +1161,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ControllerWithCatchAll_GenerateLink_FailsWithoutCountry() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var url = LinkFrom("http://localhost/") + .To(new { action = "GetProducts", controller = "Products", country = (string)null }); // Act - var url = - LinkFrom("http://localhost/") - .To(new { action = "GetProducts", controller = "Products", country = (string)null }); - var response = await client.GetAsync(url); - - var body = await response.Content.ReadAsStringAsync(); - var result = JsonConvert.DeserializeObject(body); + var response = await Client.GetAsync(url); // Assert + var body = await response.Content.ReadAsStringAsync(); + var result = JsonConvert.DeserializeObject(body); Assert.Null(result.Link); } @@ -1373,13 +1182,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRouting_MixedAcceptVerbsAndRoute_Reachable(string path, string verb, string actionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod(verb), "http://localhost" + path); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -1400,13 +1206,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRouting_MixedAcceptVerbsAndRoute_Unreachable(string path, string verb) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod(verb), "http://localhost" + path); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -1420,13 +1223,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRouting_RouteNameTokenReplace_Reachable(string path, string verb, string actionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod(verb), "http://localhost" + path); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/SerializableErrorTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/SerializableErrorTests.cs index ffe953e76c..aec97e3514 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/SerializableErrorTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/SerializableErrorTests.cs @@ -1,26 +1,26 @@ // 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.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Testing; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class SerializableErrorTests + public class SerializableErrorTests : IClassFixture> { - private const string SiteName = nameof(XmlFormattersWebSite); - private readonly Action _app = new XmlFormattersWebSite.Startup().Configure; - private readonly Action _configureServices = new XmlFormattersWebSite.Startup().ConfigureServices; + public SerializableErrorTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } public static TheoryData AcceptHeadersData { @@ -46,15 +46,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ModelStateErrors_AreSerialized(string acceptHeader) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SerializableError/ModelStateErrors"); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); var expectedXml = "key1-errorThe input was not valid."; // Act - var response = await client.GetAsync("http://localhost/SerializableError/ModelStateErrors"); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(response.Content); Assert.NotNull(response.Content.Headers.ContentType); @@ -73,14 +72,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task PostedSerializableError_IsBound(string acceptHeader) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); var expectedXml = "key1-errorThe input was not valid."; - var requestContent = new StringContent(expectedXml, Encoding.UTF8, acceptHeader); + var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/SerializableError/LogErrors"); + request.Content = new StringContent(expectedXml, Encoding.UTF8, acceptHeader); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); // Act - var response = await client.PostAsync("http://localhost/SerializableError/LogErrors", requestContent); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -101,20 +99,18 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task IsReturnedInExpectedFormat(string acceptHeader) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "" + "" + "2foo"; var expected = "The field Id must be between 10 and 100." + - "The field Name must be a string or array type with a minimum " + - "length of '15'."; + "The field Name must be a string or array type with a minimum " + + "length of '15'."; var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/SerializableError/CreateEmployee"); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(acceptHeader)); request.Content = new StringContent(input, Encoding.UTF8, "application/xml-dcs"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/StreamOutputFormatterTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/StreamOutputFormatterTest.cs index 551a36e97f..9ee2d46752 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/StreamOutputFormatterTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/StreamOutputFormatterTest.cs @@ -1,20 +1,20 @@ // 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.Net.Http; using System.Threading.Tasks; -using FormatterWebSite; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class StreamOutputFormatterTest + public class StreamOutputFormatterTest : IClassFixture> { - private const string SiteName = nameof(FormatterWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public StreamOutputFormatterTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("SimpleMemoryStream", null)] @@ -24,12 +24,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("MemoryStreamOverridesContentTypeWithProduces", "text/plain")] public async Task StreamOutputFormatter_ReturnsAppropriateContentAndContentType(string actionName, string contentType) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/Stream/" + actionName); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Stream/" + actionName); var body = await response.Content.ReadAsStringAsync(); // Assert diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/TagHelperSampleTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/TagHelperSampleTest.cs index bfc8913e59..df311f67da 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/TagHelperSampleTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/TagHelperSampleTest.cs @@ -1,106 +1,55 @@ // 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.Collections.Generic; -using System.IO; using System.Net; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using Microsoft.Framework.Logging; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class TagHelperSampleTest + public class TagHelperSampleTest : IClassFixture> { - private const string SiteName = nameof(TagHelperSample) + "." + nameof(TagHelperSample.Web); - - // Path relative to Mvc\\test\Microsoft.AspNet.Mvc.FunctionalTests - private readonly static string SamplesFolder = Path.Combine("..", "..", "samples"); - - private static readonly List Paths = new List + public TagHelperSampleTest(MvcTestFixture fixture) { - string.Empty, - "/", - "/Home/Create", - "/Home/Create?Name=Billy&Blurb=hello&DateOfBirth=2000-11-30&YearsEmployeed=0", - "/Home/Create", - "/Home/Create?Name=Joe&Blurb=goodbye&DateOfBirth=1980-10-20&YearsEmployeed=1", - "/Home/Edit/0", - "/Home/Edit/0?Name=Bobby&Blurb=howdy&DateOfBirth=1999-11-30&YearsEmployeed=1", - "/Home/Edit/1", - "/Home/Edit/1?Name=Jack&Blurb=goodbye&DateOfBirth=1979-10-20&YearsEmployeed=4", - "/Home/Edit/0", - "/Home/Edit/0?Name=Bobby&Blurb=howdy&DateOfBirth=1999-11-30&YearsEmployeed=2", - "/Home/Index", - }; + Client = fixture.Client; + } - private readonly ILoggerFactory _loggerFactory = new TestLoggerFactory(); - private readonly Action _app = new TagHelperSample.Web.Startup().Configure; - private readonly Action _configureServices = new TagHelperSample.Web.Startup().ConfigureServices; + public HttpClient Client { get; } - [Fact] - public async Task Home_Pages_ReturnSuccess() + public static TheoryData PathData { - // Arrange - var server = TestHelper.CreateServer(app => _app(app, _loggerFactory), SiteName, SamplesFolder, _configureServices); - var client = server.CreateClient(); - - for (var index = 0; index < Paths.Count; index++) + get { - // Act - var path = Paths[index]; - var response = await client.GetAsync("http://localhost" + path); - - // Assert - Assert.NotNull(response); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + return new TheoryData + { + string.Empty, + "/", + "/Home/Create", + "/Home/Create?Name=Billy&Blurb=hello&DateOfBirth=2000-11-30&YearsEmployeed=0", + "/Home/Create", + "/Home/Create?Name=Joe&Blurb=goodbye&DateOfBirth=1980-10-20&YearsEmployeed=1", + "/Home/Edit/0", + "/Home/Edit/0?Name=Bobby&Blurb=howdy&DateOfBirth=1999-11-30&YearsEmployeed=1", + "/Home/Edit/1", + "/Home/Edit/1?Name=Jack&Blurb=goodbye&DateOfBirth=1979-10-20&YearsEmployeed=4", + "/Home/Edit/0", + "/Home/Edit/0?Name=Bobby&Blurb=howdy&DateOfBirth=1999-11-30&YearsEmployeed=2", + "/Home/Index", + }; } } - private class TestLoggerFactory : ILoggerFactory + [Theory] + [MemberData(nameof(PathData))] + public async Task Home_Pages_ReturnSuccess(string path) { - public LogLevel MinimumLevel { get; set; } + // Arrange & Act + var response = await Client.GetAsync("http://localhost" + path); - public void AddProvider(ILoggerProvider provider) - { - - } - - public ILogger CreateLogger(string name) - { - return new TestLogger(); - } - - public void Dispose() - { - } - } - - private class TestLogger : ILogger - { - public bool IsEnabled(LogLevel level) - { - return false; - } - - public IDisposable BeginScopeImpl(object scope) - { - return new TestDisposable(); - } - - public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func formatter) - { - } - } - - private class TestDisposable : IDisposable - { - public void Dispose() - { - } + // Assert + Assert.NotNull(response); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } \ No newline at end of file diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/TagHelpersTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/TagHelpersTest.cs index 383979c20c..62b975320d 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/TagHelpersTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/TagHelpersTest.cs @@ -1,33 +1,37 @@ // 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.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading.Tasks; -using BasicWebSite; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using Microsoft.Framework.WebEncoders; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class TagHelpersTest + public class TagHelpersTest : + IClassFixture>, + IClassFixture> { - private const string SiteName = nameof(TagHelpersWebSite); - // Some tests require comparing the actual response body against an expected response baseline // so they require a reference to the assembly on which the resources are located, in order to // make the tests less verbose, we get a reference to the assembly with the resources and we // use it on all the rest of the tests. private static readonly Assembly _resourcesAssembly = typeof(TagHelpersTest).GetTypeInfo().Assembly; - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public TagHelpersTest( + MvcTestFixture fixture, + MvcEncodedTestFixture encodedFixture) + { + Client = fixture.Client; + EncodedClient = encodedFixture.Client; + } + + public HttpClient Client { get; } + + public HttpClient EncodedClient { get; } [Theory] [InlineData("Index")] @@ -37,8 +41,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanRenderViewsWithTagHelpers(string action) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/TagHelpersWebSite.Home." + action + ".html"; var expectedContent = @@ -46,7 +48,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Act // The host is not important as everything runs in memory and tests are isolated from each other. - var response = await client.GetAsync("http://localhost/Home/" + action); + var response = await Client.GetAsync("http://localhost/Home/" + action); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -64,12 +66,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanRenderViewsWithTagHelpersAndUnboundDynamicAttributes_Encoded() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, services => - { - _configureServices(services); - services.AddTransient(); - }); - var client = server.CreateClient(); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/TagHelpersWebSite.Home.UnboundDynamicAttributes.Encoded.html"; var expectedContent = @@ -77,7 +73,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Act // The host is not important as everything runs in memory and tests are isolated from each other. - var response = await client.GetAsync("http://localhost/Home/UnboundDynamicAttributes"); + var response = await EncodedClient.GetAsync("http://localhost/Home/UnboundDynamicAttributes"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -146,12 +142,8 @@ page:root-content" [MemberData(nameof(TagHelpersAreInheritedFromViewImportsPagesData))] public async Task TagHelpersAreInheritedFromViewImportsPages(string action, string expected) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var result = await client.GetStringAsync("http://localhost/Home/" + action); + // Arrange & Act + var result = await Client.GetStringAsync("http://localhost/Home/" + action); // Assert Assert.Equal(expected, result.Trim(), ignoreLineEndingDifferences: true); @@ -161,14 +153,12 @@ page:root-content" public async Task ViewsWithModelMetadataAttributes_CanRenderForm() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Create.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act - var response = await client.GetAsync("http://localhost/Employee/Create"); + var response = await Client.GetAsync("http://localhost/Employee/Create"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -189,8 +179,6 @@ page:root-content" public async Task ViewsWithModelMetadataAttributes_CanRenderPostedValue() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Details.AfterCreate.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); @@ -206,7 +194,7 @@ page:root-content" var postContent = new FormUrlEncodedContent(validPostValues); // Act - var response = await client.PostAsync("http://localhost/Employee/Create", postContent); + var response = await Client.PostAsync("http://localhost/Employee/Create", postContent); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -223,8 +211,6 @@ page:root-content" public async Task ViewsWithModelMetadataAttributes_CanHandleInvalidData() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Create.Invalid.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); @@ -240,7 +226,7 @@ page:root-content" var postContent = new FormUrlEncodedContent(validPostValues); // Act - var response = await client.PostAsync("http://localhost/Employee/Create", postContent); + var response = await Client.PostAsync("http://localhost/Employee/Create", postContent); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/TempDataTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/TempDataTest.cs index 55747164b1..09f2cdc237 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/TempDataTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/TempDataTest.cs @@ -7,26 +7,25 @@ using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class TempDataTest + public class TempDataTest : IClassFixture> { - private const string SiteName = nameof(TempDataWebSite); - private readonly Action _app = new TempDataWebSite.Startup().Configure; - private readonly Action _configureServices = new TempDataWebSite.Startup().ConfigureServices; + public TempDataTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task TempData_PersistsJustForNextRequest() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var nameValueCollection = new List> { new KeyValuePair("value", "Foo"), @@ -34,13 +33,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var content = new FormUrlEncodedContent(nameValueCollection); // Act 1 - var response = await client.PostAsync("/Home/SetTempData", content); + var response = await Client.PostAsync("/Home/SetTempData", content); // Assert 1 Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Act 2 - response = await client.SendAsync(GetRequest("Home/GetTempData", response)); + response = await Client.SendAsync(GetRequest("Home/GetTempData", response)); // Assert 2 Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -48,7 +47,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests Assert.Equal("Foo", body); // Act 3 - response = await client.SendAsync(GetRequest("Home/GetTempData", response)); + response = await Client.SendAsync(GetRequest("Home/GetTempData", response)); // Assert 3 Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); @@ -58,8 +57,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ViewRendersTempData() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var nameValueCollection = new List> { new KeyValuePair("value", "Foo"), @@ -67,8 +64,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var content = new FormUrlEncodedContent(nameValueCollection); // Act - var response = await client.PostAsync("http://localhost/Home/DisplayTempData", content); - + var response = await Client.PostAsync("http://localhost/Home/DisplayTempData", content); + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); @@ -81,8 +78,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task Redirect_RetainsTempData_EvenIfAccessed() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var nameValueCollection = new List> { new KeyValuePair("value", "Foo"), @@ -90,19 +85,19 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var content = new FormUrlEncodedContent(nameValueCollection); // Act 1 - var response = await client.PostAsync("/Home/SetTempData", content); + var response = await Client.PostAsync("/Home/SetTempData", content); // Assert 1 Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Act 2 - var redirectResponse = await client.SendAsync(GetRequest("/Home/GetTempDataAndRedirect", response)); + var redirectResponse = await Client.SendAsync(GetRequest("/Home/GetTempDataAndRedirect", response)); // Assert 2 Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode); // Act 3 - response = await client.SendAsync(GetRequest(redirectResponse.Headers.Location.ToString(), response)); + response = await Client.SendAsync(GetRequest(redirectResponse.Headers.Location.ToString(), response)); // Assert 3 Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -114,8 +109,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task Peek_RetainsTempData() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var nameValueCollection = new List> { new KeyValuePair("value", "Foo"), @@ -123,13 +116,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var content = new FormUrlEncodedContent(nameValueCollection); // Act 1 - var response = await client.PostAsync("/Home/SetTempData", content); + var response = await Client.PostAsync("/Home/SetTempData", content); // Assert 1 Assert.Equal(HttpStatusCode.OK, response.StatusCode); // Act 2 - var peekResponse = await client.SendAsync(GetRequest("/Home/PeekTempData", response)); + var peekResponse = await Client.SendAsync(GetRequest("/Home/PeekTempData", response)); // Assert 2 Assert.Equal(HttpStatusCode.OK, peekResponse.StatusCode); @@ -137,7 +130,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests Assert.Equal("Foo", body); // Act 3 - var getResponse = await client.SendAsync(GetRequest("/Home/GetTempData", response)); + var getResponse = await Client.SendAsync(GetRequest("/Home/GetTempData", response)); // Assert 3 Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); @@ -151,8 +144,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task TempData_ValidTypes_RoundTripProperly() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var testGuid = Guid.NewGuid(); var nameValueCollection = new List> { @@ -167,13 +158,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var content = new FormUrlEncodedContent(nameValueCollection); // Act 1 - var redirectResponse = await client.PostAsync("/Home/SetTempDataMultiple", content); + var redirectResponse = await Client.PostAsync("/Home/SetTempDataMultiple", content); // Assert 1 Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode); // Act 2 - var response = await client.SendAsync(GetRequest(redirectResponse.Headers.Location.ToString(), redirectResponse)); + var response = await Client.SendAsync(GetRequest(redirectResponse.Headers.Location.ToString(), redirectResponse)); // Assert 2 Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -185,8 +176,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task TempData_InvalidType_Throws() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var nameValueCollection = new List> { new KeyValuePair("value", "Foo"), @@ -196,7 +185,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Act & Assert var exception = await Assert.ThrowsAsync(async () => { - await client.PostAsync("/Home/SetTempDataInvalidType", content); + await Client.PostAsync("/Home/SetTempDataInvalidType", content); }); Assert.Equal("The '" + typeof(SessionStateTempDataProvider).FullName + "' cannot serialize an object of type '" + typeof(TempDataWebSite.Controllers.HomeController.NonSerializableType).FullName + "' to session state.", exception.Message); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/TestApplicationEnvironment.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/TestApplicationEnvironment.cs index 0978258777..ce5d2bbce0 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/TestApplicationEnvironment.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/TestApplicationEnvironment.cs @@ -6,59 +6,57 @@ using Microsoft.Dnx.Runtime; namespace Microsoft.AspNet.Mvc.FunctionalTests { - // Represents an application environment that overrides the base path of the original + // An application environment that overrides the base path of the original // application environment in order to make it point to the folder of the original web - // aplication so that components like ViewEngines can find views as if they were executing + // aaplication so that components like ViewEngines can find views as if they were executing // in a regular context. public class TestApplicationEnvironment : IApplicationEnvironment { - private readonly IApplicationEnvironment _originalAppEnvironment; - private readonly string _applicationBasePath; - private readonly string _applicationName; + private readonly IApplicationEnvironment _original; - public TestApplicationEnvironment(IApplicationEnvironment originalAppEnvironment, string appBasePath, string appName) + public TestApplicationEnvironment(IApplicationEnvironment original, string name, string basePath) { - _originalAppEnvironment = originalAppEnvironment; - _applicationBasePath = appBasePath; - _applicationName = appName; + _original = original; + ApplicationName = name; + ApplicationBasePath = basePath; } - public string ApplicationName - { - get { return _applicationName; } - } + public string ApplicationName { get; } public string ApplicationVersion { - get { return _originalAppEnvironment.ApplicationVersion; } + get + { + return _original.ApplicationVersion; + } } - public string ApplicationBasePath - { - get { return _applicationBasePath; } - } + public string ApplicationBasePath { get; } public string Configuration { get { - return _originalAppEnvironment.Configuration; + return _original.Configuration; } } public FrameworkName RuntimeFramework { - get { return _originalAppEnvironment.RuntimeFramework; } + get + { + return _original.RuntimeFramework; + } } public object GetData(string name) { - return _originalAppEnvironment.GetData(name); + return _original.GetData(name); } public void SetData(string name, object value) { - _originalAppEnvironment.SetData(name, value); + _original.SetData(name, value); } } } \ 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 478ac6ea50..2d3a8c69e3 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/TestHelper.cs @@ -6,11 +6,10 @@ using System.IO; using System.Reflection; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; -using Microsoft.AspNet.TestHost; -using Microsoft.Framework.DependencyInjection; -using Microsoft.Dnx.Runtime; -using Microsoft.Dnx.Runtime.Infrastructure; using Microsoft.AspNet.Mvc.Actions; +using Microsoft.AspNet.TestHost; +using Microsoft.Dnx.Runtime; +using Microsoft.Framework.DependencyInjection; namespace Microsoft.AspNet.Mvc.FunctionalTests { @@ -20,19 +19,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests private static readonly string WebsitesDirectoryPath = Path.Combine("..", "WebSites"); public static TestServer CreateServer(Action builder, string applicationWebSiteName) - { - return CreateServer(builder, applicationWebSiteName, applicationPath: null); - } - - public static TestServer CreateServer( - Action builder, - string applicationWebSiteName, - string applicationPath) { return CreateServer( builder, applicationWebSiteName, - applicationPath, + applicationPath: null, configureServices: (Action)null); } @@ -48,7 +39,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests configureServices: configureServices); } - public static TestServer CreateServer( + private static TestServer CreateServer( Action builder, string applicationWebSiteName, string applicationPath, @@ -59,34 +50,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests services => AddTestServices(services, applicationWebSiteName, applicationPath, configureServices)); } - public static TestServer CreateServer( - Action builder, - string applicationWebSiteName, - Func configureServices) - { - return CreateServer( - builder, - applicationWebSiteName, - applicationPath: null, - configureServices: configureServices); - } - - public static TestServer CreateServer( - Action builder, - string applicationWebSiteName, - string applicationPath, - Func configureServices) - { - return TestServer.Create( - CallContextServiceLocator.Locator.ServiceProvider, - builder, - services => - { - AddTestServices(services, applicationWebSiteName, applicationPath, configureServices: null); - return (configureServices != null) ? configureServices(services) : services.BuildServiceProvider(); - }); - } - private static void AddTestServices( IServiceCollection services, string applicationWebSiteName, @@ -112,8 +75,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests applicationPath); var environment = new TestApplicationEnvironment( originalEnvironment, - applicationBasePath, - applicationWebSiteName); + applicationWebSiteName, + applicationBasePath); services.AddInstance(environment); var hostingEnvironment = new HostingEnvironment(); hostingEnvironment.Initialize(applicationBasePath, environmentName: null); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/TryValidateModelTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/TryValidateModelTest.cs index e52c24d4b9..00da4f37c8 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/TryValidateModelTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/TryValidateModelTest.cs @@ -8,26 +8,25 @@ using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Testing; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class TryValidateModelTest + public class TryValidateModelTest : IClassFixture> { - private const string SiteName = nameof(ValidationWebSite); - private readonly Action _app = new ValidationWebSite.Startup().Configure; - private readonly Action _configureServices = new ValidationWebSite.Startup().ConfigureServices; + public TryValidateModelTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task TryValidateModel_ClearParameterValidationError_ReturnsErrorsForInvalidProperties() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "{ \"Price\": 2, \"Contact\": \"acvrdzersaererererfdsfdsfdsfsdf\", " + "\"ProductDetails\": {\"Detail1\": \"d1\", \"Detail2\": \"d2\", \"Detail3\": \"d3\"}}"; var content = new StringContent(input, Encoding.UTF8, "application/json"); @@ -36,7 +35,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests "TryValidateModelAfterClearingValidationErrorInParameter?theImpossibleString=test"; // Act - var response = await client.PostAsync(url, content); + var response = await Client.PostAsync(url, content); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -50,7 +49,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests json["Category"]); AssertErrorEquals( "The field Contact Us must be a string with a maximum length of 20." + - "The field Contact Us must match the regular expression " + + "The field Contact Us must match the regular expression " + (TestPlatformHelper.IsMono ? "^[0-9]*$." : "'^[0-9]*$'."), json["Contact"]); } @@ -59,13 +58,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task TryValidateModel_InvalidTypeOnDerivedModel_ReturnsErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = - "http://localhost/ModelMetadataTypeValidation/TryValidateModelSoftwareViewModelWithPrefix"; + var url = "http://localhost/ModelMetadataTypeValidation/TryValidateModelSoftwareViewModelWithPrefix"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -78,13 +74,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task TryValidateModel_ValidDerivedModel_ReturnsEmptyResponseBody() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = - "http://localhost/ModelMetadataTypeValidation/TryValidateModelValidModelNoPrefix"; + var url = "http://localhost/ModelMetadataTypeValidation/TryValidateModelValidModelNoPrefix"; // Act - var response = await client.GetAsync(url); + var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -96,8 +89,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task TryValidateModel_CollectionsModel_ReturnsErrorsForInvalidProperties() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "[ { \"Price\": 2, \"Contact\": \"acvrdzersaererererfdsfdsfdsfsdf\", " + "\"ProductDetails\": {\"Detail1\": \"d1\", \"Detail2\": \"d2\", \"Detail3\": \"d3\"} }," + "{\"Price\": 2, \"Contact\": \"acvrdzersaererererfdsfdsfdsfsdf\", " + @@ -107,7 +98,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests "http://localhost/ModelMetadataTypeValidation/TryValidateModelWithCollectionsModel"; // Act - var response = await client.PostAsync(url, content); + var response = await Client.PostAsync(url, content); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -120,7 +111,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests json["[0].Category"]); AssertErrorEquals( "The field Contact Us must be a string with a maximum length of 20." + - "The field Contact Us must match the regular expression " + + "The field Contact Us must match the regular expression " + (TestPlatformHelper.IsMono ? "^[0-9]*$." : "'^[0-9]*$'."), json["[0].Contact"]); Assert.Equal("CompanyName cannot be null or empty.", json["[1].CompanyName"]); @@ -130,7 +121,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests json["[1].Category"]); AssertErrorEquals( "The field Contact Us must be a string with a maximum length of 20." + - "The field Contact Us must match the regular expression " + + "The field Contact Us must match the regular expression " + (TestPlatformHelper.IsMono ? "^[0-9]*$." : "'^[0-9]*$'."), json["[1].Contact"]); } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/UrlResolutionTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/UrlResolutionTest.cs index e222c49f85..8640655d0a 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/UrlResolutionTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/UrlResolutionTest.cs @@ -1,36 +1,41 @@ // 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.Net.Http; using System.Reflection; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using Microsoft.Framework.WebEncoders; -using RazorWebSite; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class UrlResolutionTest + public class UrlResolutionTest : + IClassFixture>, + IClassFixture> { - private const string SiteName = nameof(RazorWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; private static readonly Assembly _resourcesAssembly = typeof(UrlResolutionTest).GetTypeInfo().Assembly; + public UrlResolutionTest( + MvcTestFixture fixture, + MvcEncodedTestFixture encodedFixture) + { + Client = fixture.Client; + EncodedClient = encodedFixture.Client; + } + + public HttpClient Client { get; } + + public HttpClient EncodedClient { get; } + [Fact] public async Task AppRelativeUrlsAreResolvedCorrectly() { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - - var client = server.CreateClient(); + // Arrange var outputFile = "compiler/resources/RazorWebSite.UrlResolution.Index.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act - var response = await client.GetAsync("http://localhost/UrlResolution/Index"); + var response = await Client.GetAsync("http://localhost/UrlResolution/Index"); var responseContent = await response.Content.ReadAsStringAsync(); // Assert @@ -45,18 +50,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task AppRelativeUrlsAreResolvedAndEncodedCorrectly() { - var server = TestHelper.CreateServer(_app, SiteName, services => - { - _configureServices(services); - services.AddTransient(); - }); - var client = server.CreateClient(); + // Arrange var outputFile = "compiler/resources/RazorWebSite.UrlResolution.Index.Encoded.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act - var response = await client.GetAsync("http://localhost/UrlResolution/Index"); + var response = await EncodedClient.GetAsync("http://localhost/UrlResolution/Index"); var responseContent = await response.Content.ReadAsStringAsync(); // Assert diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ValueProviderTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ValueProviderTest.cs index 2bf31cc621..cd9b915c2f 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ValueProviderTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ValueProviderTest.cs @@ -1,30 +1,26 @@ // 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.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using ValueProvidersWebSite; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ValueProviderTest + public class ValueProviderTest : IClassFixture> { - private const string SiteName = nameof(ValueProvidersWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ValueProviderTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task ValueProviderFactories_AreVisitedInSequentialOrder_ForValueProviders() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync("http://localhost/Home/TestValueProvider?test=not-test-value"); + // Arrange & Act + var body = await Client.GetStringAsync("http://localhost/Home/TestValueProvider?test=not-test-value"); // Assert Assert.Equal("custom-value-provider-value", body.Trim()); @@ -33,12 +29,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ValueProviderFactories_ReturnsValuesFromQueryValueProvider() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync("http://localhost/Home/DefaultValueProviders?test=query-value"); + // Arrange & Act + var body = await Client.GetStringAsync("http://localhost/Home/DefaultValueProviders?test=query-value"); // Assert Assert.Equal("query-value", body.Trim()); @@ -47,12 +39,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ValueProviderFactories_ReturnsValuesFromRouteValueProvider() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync("http://localhost/RouteTest/route-value"); + // Arrange & Act + var body = await Client.GetStringAsync("http://localhost/RouteTest/route-value"); // Assert Assert.Equal("route-value", body.Trim()); @@ -67,12 +55,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("http://localhost/Home/GetFlagValuesAsInt?flags=Value1,Value2", "3")] public async Task ValueProvider_DeserializesEnumsWithFlags(string url, string expected) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync(url); + // Arrange & Act + var body = await Client.GetStringAsync(url); // Assert Assert.Equal(expected, body.Trim()); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/VersioningTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/VersioningTests.cs index ba7d49ff4b..4103c0dd54 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/VersioningTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/VersioningTests.cs @@ -1,23 +1,23 @@ // 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.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class VersioningTests + public class VersioningTests : IClassFixture> { - private const string SiteName = nameof(VersioningWebSite); - readonly Action _app = new VersioningWebSite.Startup().Configure; - private readonly Action _configureServices = new VersioningWebSite.Startup().ConfigureServices; + public VersioningTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("1")] @@ -25,12 +25,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_WithVersionedRoutes_IsNotAmbiguous(string version) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/Addresses?version=" + version); // Act - var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/Addresses?version=" + version); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -38,7 +36,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Contains("api/addresses", result.ExpectedUrls); Assert.Equal("Address", result.Controller); Assert.Equal("GetV" + version, result.Action); @@ -50,14 +47,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task AttributeRoutedAction_WithAmbiguousVersionedRoutes_CanBeDisambiguatedUsingOrder(string version) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var query = "?version=" + version; var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/Addresses/All" + query); // Act - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -65,7 +60,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var body = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject(body); - // Assert Assert.Contains("/api/addresses/all?version=" + version, result.ExpectedUrls); Assert.Equal("Address", result.Controller); Assert.Equal("GetAllV" + version, result.Action); @@ -75,12 +69,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanReachV1Operations_OnTheSameController_WithNoVersionSpecified() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets"); // Act - var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -98,12 +90,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanReachV1Operations_OnTheSameController_WithVersionSpecified() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets?version=2"); // Act - var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets?version=2"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -119,12 +109,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanReachV1OperationsWithParameters_OnTheSameController() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets/5"); // Act - var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets/5"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -140,12 +128,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanReachV1OperationsWithParameters_OnTheSameController_WithVersionSpecified() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets/5?version=2"); // Act - var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets/5?version=2"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -169,12 +155,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanReachOtherVersionOperations_OnTheSameController(string version) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Tickets?version=" + version); // Act - var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Tickets?version=" + version); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -195,12 +179,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanNotReachOtherVersionOperations_OnTheSameController_WithNoVersionSpecified() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Tickets"); // Act - var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Tickets"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -222,12 +204,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests string version) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Tickets/5?version=" + version); // Act - var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Tickets/5?version=" + version); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -250,12 +230,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanNotReachOtherVersionOperationsWithParameters_OnTheSameController_WithNoVersionSpecified(string method) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Tickets/5"); // Act - var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Tickets/5"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -271,12 +249,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanUseOrderToDisambiguate_OverlappingVersionRanges(string version) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Books?version=" + version); // Act - var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Books?version=" + version); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -295,12 +271,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_OverlappingVersionRanges_FallsBackToLowerOrderAction(string version) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Books?version=" + version); // Act - var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Books?version=" + version); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -319,12 +293,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanReachV1Operations_OnTheOriginalController_WithNoVersionSpecified(string method, string action) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Movies"); // Act - var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Movies"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -342,12 +314,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanReachV1Operations_OnTheOriginalController_WithVersionSpecified(string method, string action) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Movies?version=2"); // Act - var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Movies?version=2"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -366,12 +336,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanReachV1OperationsWithParameters_OnTheOriginalController(string method, string action) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Movies/5"); // Act - var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Movies/5"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -389,12 +357,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanReachV1OperationsWithParameters_OnTheOriginalController_WithVersionSpecified(string method, string action) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Movies/5?version=2"); // Act - var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Movies/5?version=2"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -410,12 +376,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanReachOtherVersionOperationsWithParameters_OnTheV2Controller() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Put, "http://localhost/Movies/5?version=2"); // Act - var message = new HttpRequestMessage(HttpMethod.Put, "http://localhost/Movies/5?version=2"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -434,12 +398,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanHaveTwoRoutesWithVersionOnTheUrl_OnTheSameAction(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/" + url); // Act - var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/" + url); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -457,12 +419,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanHaveTwoRoutesWithVersionOnTheUrl_OnDifferentActions(string url, string version) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/" + url); // Act - var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/" + url); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -480,12 +440,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanHaveTwoRoutesWithVersionOnTheUrl_OnDifferentActions_WithInlineConstraint(string url, string version) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/" + url); // Act - var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/" + url); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -506,12 +464,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanProvideVersioningInformation_UsingPlainActionConstraint(string url, string query, string actionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/" + url + query); // Act - var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/" + url + query); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -527,12 +483,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_ConstraintOrder_IsRespected() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/" + "Customers?version=2"); // Act - var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/" + "Customers?version=2"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -548,12 +502,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_CanUseConstraintOrder_ToChangeSelectedAction() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); + var message = new HttpRequestMessage(HttpMethod.Delete, "http://localhost/" + "Customers/5?version=2"); // Act - var message = new HttpRequestMessage(HttpMethod.Delete, "http://localhost/" + "Customers/5?version=2"); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -571,13 +523,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task VersionedApi_MultipleVersionsUsingAttributeRouting_OnTheSameMethod(string version) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var path = "/" + version + "/Vouchers?version=" + version; + var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost" + path); // Act - var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost" + path); - var response = await client.SendAsync(message); + var response = await Client.SendAsync(message); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ViewComponentTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ViewComponentTests.cs index 219c40eb9c..b289cd8e7f 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ViewComponentTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ViewComponentTests.cs @@ -1,21 +1,21 @@ // 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.Collections.Generic; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; -using ViewComponentWebSite; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ViewComponentTests + public class ViewComponentTests : IClassFixture> { - private const string SiteName = nameof(ViewComponentWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ViewComponentTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } public static IEnumerable ViewViewComponents_AreRenderedCorrectlyData { @@ -41,11 +41,8 @@ ViewWithSyncComponents Invoke: hello from viewdatacomponent" [MemberData(nameof(ViewViewComponents_AreRenderedCorrectlyData))] public async Task ViewViewComponents_AreRenderedCorrectly(string actionName, string expected) { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync("http://localhost/Home/" + actionName); + // Arrange & Act + var body = await Client.GetStringAsync("http://localhost/Home/" + actionName); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -54,11 +51,8 @@ ViewWithSyncComponents Invoke: hello from viewdatacomponent" [Fact] public async Task ViewComponents_SupportsValueType() { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync("http://localhost/Home/ViewWithIntegerViewComponent"); + // Arrange & Act + var body = await Client.GetStringAsync("http://localhost/Home/ViewWithIntegerViewComponent"); // Assert Assert.Equal("10", body.Trim()); @@ -67,11 +61,8 @@ ViewWithSyncComponents Invoke: hello from viewdatacomponent" [Fact] public async Task ViewComponents_InvokeWithViewComponentResult() { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync("http://localhost/ViewComponentResult/Invoke?number=31"); + // Arrange & Act + var body = await Client.GetStringAsync("http://localhost/ViewComponentResult/Invoke?number=31"); // Assert Assert.Equal("31", body.Trim()); @@ -86,14 +77,11 @@ ViewWithSyncComponents Invoke: hello from viewdatacomponent" [InlineData("http://localhost/Home/ViewComponentWithEnumerableModelUsingUnion", "Union")] public async Task ViewComponents_SupportsEnumerableModel(string url, string linqQueryType) { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act + // Arrange & Act // https://github.com/aspnet/Mvc/issues/1354 // The invoked ViewComponent/View has a model which is an internal type implementing Enumerable. // For ex - TestEnumerableObject.Select(t => t) returns WhereSelectListIterator - var body = await client.GetStringAsync(url); + var body = await Client.GetStringAsync(url); // Assert Assert.Equal("

Hello

World

Sample

Test

" @@ -105,11 +93,8 @@ ViewWithSyncComponents Invoke: hello from viewdatacomponent" [InlineData("ViewComponentWebSite.Namespace2.SameName")] public async Task ViewComponents_FullName(string name) { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync("http://localhost/FullName/Invoke?name=" + name); + // Arrange & Act + var body = await Client.GetStringAsync("http://localhost/FullName/Invoke?name=" + name); // Assert Assert.Equal(name, body.Trim()); @@ -118,13 +103,11 @@ ViewWithSyncComponents Invoke: hello from viewdatacomponent" [Fact] public async Task ViewComponents_ShortNameUsedForViewLookup() { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - + // Arrange var name = "ViewComponentWebSite.Integer"; // Act - var body = await client.GetStringAsync("http://localhost/FullName/Invoke?name=" + name); + var body = await Client.GetStringAsync("http://localhost/FullName/Invoke?name=" + name); // Assert Assert.Equal("17", body.Trim()); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ViewEngineTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ViewEngineTests.cs index b8c5eb2fcb..9d8e7e50bb 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ViewEngineTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ViewEngineTests.cs @@ -1,26 +1,26 @@ // 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.Collections.Generic; +using System.Net.Http; using System.Reflection; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Testing; -using Microsoft.Framework.DependencyInjection; using Microsoft.Net.Http.Headers; -using RazorWebSite; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class ViewEngineTests + public class ViewEngineTests : IClassFixture> { - private const string SiteName = nameof(RazorWebSite); private static readonly Assembly _assembly = typeof(ViewEngineTests).GetTypeInfo().Assembly; - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public ViewEngineTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } public static IEnumerable RazorView_ExecutesPageAndLayoutData { @@ -64,11 +64,8 @@ ViewWithNestedLayout-Content [MemberData(nameof(RazorView_ExecutesPageAndLayoutData))] public async Task RazorView_ExecutesPageAndLayout(string actionName, string expected) { - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync("http://localhost/ViewEngine/" + actionName); + // Arrange & Act + var body = await Client.GetStringAsync("http://localhost/ViewEngine/" + actionName); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -77,6 +74,7 @@ ViewWithNestedLayout-Content [Fact] public async Task RazorView_ExecutesPartialPagesWithCorrectContext() { + // Arrange var expected = @"98052 @@ -84,11 +82,9 @@ ViewWithNestedLayout-Content test-value"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync("http://localhost/ViewEngine/ViewWithPartial"); + var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewWithPartial"); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -99,11 +95,9 @@ test-value"; { // Arrange var expected = "HelloWorld"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync( + var body = await Client.GetStringAsync( "http://localhost/ViewEngine/ViewWithPartialTakingModelFromIEnumerable"); // Assert @@ -113,14 +107,13 @@ test-value"; [Fact] public async Task RazorView_PassesViewContextBetweenViewAndLayout() { + // Arrange var expected = @"Page title partial-contentcomponent-content"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync("http://localhost/ViewEngine/ViewPassesViewDataToLayout"); + var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewPassesViewDataToLayout"); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -153,15 +146,13 @@ expander-partial"; public async Task RazorViewEngine_UsesViewExpandersForViewsAndPartials(string value, string expected) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var cultureCookie = "c=" + value + "|uic=" + value; - client.DefaultRequestHeaders.Add( - "Cookie", - new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString()); + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/TemplateExpander"); + request.Headers.Add("Cookie", new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString()); // Act - var body = await client.GetStringAsync("http://localhost/TemplateExpander"); + var response = await Client.SendAsync(request); + var body = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -183,12 +174,8 @@ expander-partial"; [MemberData(nameof(ViewLocationExpanders_PassesInIsPartialToViewLocationExpanderContextData))] public async Task ViewLocationExpanders_PassesInIsPartialToViewLocationExpanderContext(string action, string expected) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync($"http://localhost/ExpanderViews/{action}"); + // Arrange & Act + var body = await Client.GetStringAsync($"http://localhost/ExpanderViews/{action}"); // Assert Assert.Equal(expected, body.Trim()); @@ -244,12 +231,8 @@ ViewWithNestedLayout-Content [MemberData(nameof(RazorViewEngine_RendersPartialViewsData))] public async Task RazorViewEngine_RendersPartialViews(string actionName, string expected) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var body = await client.GetStringAsync("http://localhost/PartialViewEngine/" + actionName); + // Arrange & Act + var body = await Client.GetStringAsync("http://localhost/PartialViewEngine/" + actionName); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -262,11 +245,9 @@ ViewWithNestedLayout-Content var expected = @"viewstart-value ~/Views/NestedViewStarts/NestedViewStarts/Layout.cshtml index-content"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync("http://localhost/NestedViewStarts"); + var body = await Client.GetStringAsync("http://localhost/NestedViewStarts"); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -301,15 +282,13 @@ index-content"; public async Task RazorViewEngine_UsesExpandersForLayouts(string value, string expected) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var cultureCookie = "c=" + value + "|uic=" + value; - client.DefaultRequestHeaders.Add( - "Cookie", - new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString()); + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/TemplateExpander/ViewWithLayout"); + request.Headers.Add("Cookie", new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString()); // Act - var body = await client.GetStringAsync("http://localhost/TemplateExpander/ViewWithLayout"); + var response = await Client.SendAsync(request); + var body = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -322,12 +301,10 @@ index-content"; var expected = @"Hello Controller-Person Hello Controller-Person"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var target = "http://localhost/NestedViewImports"; // Act - var body = await client.GetStringAsync(target); + var body = await Client.GetStringAsync(target); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -342,11 +319,9 @@ index-content"; Page Content ViewComponent With Title Component With Layout"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync("http://localhost/ViewEngine/ViewWithComponentThatHasLayout"); + var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewWithComponentThatHasLayout"); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -357,11 +332,9 @@ Page Content { // Arrange var expected = @"ViewComponent With ViewStart"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync("http://localhost/ViewEngine/ViewWithComponentThatHasViewStart"); + var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewWithComponentThatHasViewStart"); // Assert Assert.Equal(expected, body.Trim()); @@ -372,11 +345,9 @@ Page Content { // Arrange var expected = "Partial that does not specify Layout"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync("http://localhost/PartialsWithLayout/PartialDoesNotExecuteViewStarts"); + var body = await Client.GetStringAsync("http://localhost/PartialsWithLayout/PartialDoesNotExecuteViewStarts"); // Assert Assert.Equal(expected, body.Trim()); @@ -389,11 +360,9 @@ Page Content var expected = @"Partial that specifies Layout Partial that does not specify Layout"; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync("http://localhost/PartialsWithLayout/PartialsRenderedViaRenderPartial"); + var body = await Client.GetStringAsync("http://localhost/PartialsWithLayout/PartialsRenderedViaRenderPartial"); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -408,11 +377,9 @@ Page Content Partial that does not specify Layout "; - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); // Act - var body = await client.GetStringAsync("http://localhost/PartialsWithLayout/PartialsRenderedViaPartialAsync"); + var body = await Client.GetStringAsync("http://localhost/PartialsWithLayout/PartialsRenderedViaPartialAsync"); // Assert Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); @@ -422,13 +389,11 @@ Partial that does not specify Layout public async Task RazorView_SetsViewPathAndExecutingPagePath() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var outputFile = "compiler/resources/ViewEngineController.ViewWithPaths.txt"; var expectedContent = await ResourceFile.ReadResourceAsync(_assembly, outputFile, sourceFile: false); // Act - var responseContent = await client.GetStringAsync("http://localhost/ViewWithPaths"); + var responseContent = await Client.GetStringAsync("http://localhost/ViewWithPaths"); // Assert responseContent = responseContent.Trim(); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimActionResultTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimActionResultTest.cs index 4be9460258..1673bec787 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimActionResultTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimActionResultTest.cs @@ -3,28 +3,26 @@ using System; using System.Net; +using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class WebApiCompatShimActionResultTest + public class WebApiCompatShimActionResultTest : IClassFixture> { - private const string SiteName = nameof(WebApiCompatShimWebSite); - private readonly Action _app = new WebApiCompatShimWebSite.Startup().Configure; - private readonly Action _configureServices = new WebApiCompatShimWebSite.Startup().ConfigureServices; + public WebApiCompatShimActionResultTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task ApiController_BadRequest() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetBadRequest"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetBadRequest"); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -33,12 +31,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_BadRequestMessage() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetBadRequestMessage"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetBadRequestMessage"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -50,13 +44,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_BadRequestModelState() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var expected = "{\"Message\":\"The request is invalid.\",\"ModelState\":{\"product.Name\":[\"Name is required.\"]}}"; // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetBadRequestModelState"); + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetBadRequestModelState"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -67,12 +58,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_Conflict() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetConflict"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetConflict"); // Assert Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); @@ -81,12 +68,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_Content() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetContent"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetContent"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -97,12 +80,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_CreatedRelative() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedRelative"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedRelative"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -114,12 +93,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_CreatedAbsolute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedAbsolute"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedAbsolute"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -131,12 +106,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_CreatedQualified() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedQualified"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedQualified"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -148,12 +119,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_CreatedUri() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedUri"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedUri"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -165,12 +132,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_CreatedAtRoute() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedAtRoute"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedAtRoute"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -182,12 +145,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_InternalServerError() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetInternalServerError"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetInternalServerError"); // Assert Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -196,12 +155,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_InternalServerErrorException() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetInternalServerErrorException"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetInternalServerErrorException"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -212,12 +167,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_Json() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetJson"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetJson"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -229,16 +180,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_JsonSettings() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var expected = "{" + Environment.NewLine + " \"Name\": \"Test User\"" + Environment.NewLine + "}"; // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetJsonSettings"); + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetJsonSettings"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -250,16 +198,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_JsonSettingsEncoding() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var expected = "{" + Environment.NewLine + " \"Name\": \"Test User\"" + Environment.NewLine + "}"; // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetJsonSettingsEncoding"); + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetJsonSettingsEncoding"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -271,12 +216,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_NotFound() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetNotFound"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetNotFound"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -285,12 +226,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_Ok() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetOk"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetOk"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -299,12 +236,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_OkContent() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetOkContent"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetOkContent"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -315,12 +248,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_RedirectString() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetRedirectString"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetRedirectString"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); @@ -334,12 +263,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests "/api/Blog/BasicApi/WriteToHttpContext")] public async Task ApiController_RedirectUri(string url, string expected) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync(url); + // Arrange & Act + var response = await Client.GetAsync(url); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); @@ -349,12 +274,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_ResponseMessage() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetResponseMessage"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetResponseMessage"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -364,12 +285,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_StatusCode() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetStatusCode"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetStatusCode"); // Assert Assert.Equal(HttpStatusCode.PaymentRequired, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimActionSelectionTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimActionSelectionTest.cs index d19b9caf55..8d73f8ecef 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimActionSelectionTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimActionSelectionTest.cs @@ -1,23 +1,23 @@ // 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.Net; using System.Net.Http; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.Actions; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class WebApiCompatShimActionSelectionTest + public class WebApiCompatShimActionSelectionTest : IClassFixture> { - private const string SiteName = nameof(WebApiCompatShimWebSite); - private readonly Action _app = new WebApiCompatShimWebSite.Startup().Configure; - private readonly Action _configureServices = new WebApiCompatShimWebSite.Startup().ConfigureServices; + public WebApiCompatShimActionSelectionTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("GET", "GetItems")] @@ -30,20 +30,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_TakesHttpMethodFromPrefix_UnnamedAction(string httpMethod, string actionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod(httpMethod), "http://localhost/api/Admin/WebAPIActionConventions"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(actionName, result.ActionName); } @@ -59,20 +55,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_TakesHttpMethodFromPrefix_NamedAction(string httpMethod, string actionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod(httpMethod), "http://localhost/api/Blog/WebAPIActionConventions/" + actionName); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(actionName, result.ActionName); } @@ -81,17 +73,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_TakesHttpMethodFromPrefix_NamedAction_MismatchedVerb() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("POST"), "http://localhost/api/Blog/WebAPIActionConventions/GetItems"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -99,20 +88,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_TakesHttpMethodFromPrefix_UnnamedAction_DefaultVerbIsPost_Success() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("POST"), "http://localhost/api/Admin/WebApiActionConventionsDefaultPost"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("DefaultVerbIsPost", result.ActionName); } @@ -121,20 +106,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_TakesHttpMethodFromPrefix_NamedAction_DefaultVerbIsPost_Success() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("POST"), "http://localhost/api/Blog/WebAPIActionConventionsDefaultPost/DefaultVerbIsPost"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("DefaultVerbIsPost", result.ActionName); } @@ -143,17 +124,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_TakesHttpMethodFromPrefix_UnnamedAction_DefaultVerbIsPost_VerbMismatch() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("GET"), "http://localhost/api/Admin/WebApiActionConventionsDefaultPost"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -161,17 +139,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_TakesHttpMethodFromPrefix_NamedAction_DefaultVerbIsPost_VerbMismatch() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("PUT"), "http://localhost/api/Blog/WebApiActionConventionsDefaultPost/DefaultVerbIsPost"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -179,20 +154,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_TakesHttpMethodFromMethodName_NotActionName_UnnamedAction_Success() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("POST"), "http://localhost/api/Admin/WebAPIActionConventionsActionName"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("GetItems", result.ActionName); } @@ -201,20 +172,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_TakesHttpMethodFromMethodName_NotActionName_NamedAction_Success() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("POST"), "http://localhost/api/Blog/WebAPIActionConventionsActionName/GetItems"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("GetItems", result.ActionName); } @@ -223,17 +190,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_TakesHttpMethodFromMethodName_NotActionName_UnnamedAction_VerbMismatch() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("Get"), "http://localhost/api/Admin/WebAPIActionConventionsActionName"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -241,17 +205,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_TakesHttpMethodFromMethodName_NotActionName_NamedAction_VerbMismatch() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("GET"), "http://localhost/api/Blog/WebAPIActionConventionsActionName/GetItems"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -259,20 +220,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_HttpMethodOverride_UnnamedAction_Success() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("GET"), "http://localhost/api/Admin/WebAPIActionConventionsVerbOverride"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("PostItems", result.ActionName); } @@ -281,20 +238,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_HttpMethodOverride_NamedAction_Success() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("GET"), "http://localhost/api/Blog/WebAPIActionConventionsVerbOverride/PostItems"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("PostItems", result.ActionName); } @@ -303,17 +256,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_HttpMethodOverride_UnnamedAction_VerbMismatch() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("POST"), "http://localhost/api/Admin/WebAPIActionConventionsVerbOverride"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -321,21 +271,18 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebAPIConvention_HttpMethodOverride_NamedAction_VerbMismatch() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( new HttpMethod("POST"), "http://localhost/api/Blog/WebAPIActionConventionsVerbOverride/PostItems"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } - // This was ported from the WebAPI 5.2 codebase. Kept the same intentionally for compatability. + // This was ported from the WebAPI 5.2 codebase. Kept the same intentionally for compatibility. [Theory] [InlineData("GET", "api/Admin/Test", "GetUsers")] [InlineData("GET", "api/Admin/Test/2", "GetUser")] @@ -370,18 +317,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task LegacyActionSelection_OverloadedAction_WithUnnamedAction(string httpMethod, string requestUrl, string expectedActionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedActionName, result.ActionName); } @@ -397,18 +340,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task LegacyActionSelection_OverloadedAction_NonIdRouteParameter(string httpMethod, string requestUrl, string expectedActionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedActionName, result.ActionName); } @@ -421,18 +360,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task LegacyActionSelection_OverloadedAction_Parameter_Casing(string httpMethod, string requestUrl, string expectedActionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedActionName, result.ActionName); } @@ -448,18 +383,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task LegacyActionSelection_RouteWithActionName(string httpMethod, string requestUrl, string expectedActionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedActionName, result.ActionName); } @@ -475,18 +406,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task LegacyActionSelection_RouteWithActionName_Casing(string httpMethod, string requestUrl, string expectedActionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedActionName, result.ActionName); } @@ -500,18 +427,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task LegacyActionSelection_RouteWithoutActionName(string httpMethod, string requestUrl, string expectedActionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedActionName, result.ActionName); } @@ -528,18 +451,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task LegacyActionSelection_ModelBindingParameterAttribute_AreAppliedWhenSelectingActions(string httpMethod, string requestUrl, string expectedActionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedActionName, result.ActionName); } @@ -552,18 +471,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task LegacyActionSelection_ActionsThatHaveSubsetOfRouteParameters_AreConsideredForSelection(string httpMethod, string requestUrl, string expectedActionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedActionName, result.ActionName); } @@ -574,13 +489,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task LegacyActionSelection_RequestToAmbiguousAction_OnDefaultRoute() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod("POST"), "http://localhost/api/Admin/Test?name=mario"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert var exception = response.GetServerException(); @@ -595,18 +507,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task LegacyActionSelection_SelectAction_ReturnsActionDescriptor_ForEnumParameterOverloads(string httpMethod, string requestUrl, string expectedActionName) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); + // Assert var data = Assert.Single(response.Headers.GetValues("ActionSelection")); var result = JsonConvert.DeserializeObject(data); - - //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedActionName, result.ActionName); } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimBasicTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimBasicTest.cs index 003a5f8ebf..be84ed7351 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimBasicTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimBasicTest.cs @@ -19,21 +19,25 @@ using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class WebApiCompatShimBasicTest + public class WebApiCompatShimBasicTest : IClassFixture> { private const string SiteName = nameof(WebApiCompatShimWebSite); private readonly Action _app = new WebApiCompatShimWebSite.Startup().Configure; - private readonly Action _configureServices = new WebApiCompatShimWebSite.Startup().ConfigureServices; + private readonly Action _configureServices = + new WebApiCompatShimWebSite.Startup().ConfigureServices; + + public WebApiCompatShimBasicTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task ApiController_Activates_HttpContextAndUser() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/BasicApi/WriteToHttpContext"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/BasicApi/WriteToHttpContext"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -46,12 +50,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_Activates_UrlHelper() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/BasicApi/GenerateUrl"); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/BasicApi/GenerateUrl"); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -61,24 +61,21 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests content); } -#if !DNXCORE50 - [Fact] public async Task Options_SetsDefaultFormatters() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var expected = new string[] { typeof(JsonMediaTypeFormatter).FullName, typeof(XmlMediaTypeFormatter).FullName, +#if !DNXCORE50 typeof(FormUrlEncodedMediaTypeFormatter).FullName, +#endif }; // Act - var response = await client.GetAsync("http://localhost/api/Blog/BasicApi/GetFormatters"); + var response = await Client.GetAsync("http://localhost/api/Blog/BasicApi/GetFormatters"); var content = await response.Content.ReadAsStringAsync(); var formatters = JsonConvert.DeserializeObject(content); @@ -88,17 +85,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests Assert.Equal(expected, formatters); } -#endif - [Fact] public async Task ActionThrowsHttpResponseException_WithStatusCode() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/api/Blog/HttpResponseException/ThrowsHttpResponseExceptionWithHttpStatusCode"); // Assert @@ -110,12 +101,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ActionThrowsHttpResponseException_WithResponse() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/api/Blog/HttpResponseException" + "/ThrowsHttpResponseExceptionWithHttpResponseMessage?message=send some message"); @@ -128,12 +115,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ActionThrowsHttpResponseException_EnsureGlobalHttpresponseExceptionActionFilter_IsInvoked() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/api/Blog/HttpResponseException/ThrowsHttpResponseExceptionEnsureGlobalFilterRunsLast"); // Assert @@ -146,12 +129,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ActionThrowsHttpResponseException_EnsureGlobalFilterConvention_IsApplied() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync( + // Arrange & Act + var response = await Client.GetAsync( "http://localhost/api/Blog/" + "HttpResponseException/ThrowsHttpResponseExceptionInjectAFilterToHandleHttpResponseException"); @@ -165,12 +144,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_CanValidateCustomObjectWithPrefix_Fails() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync( + // Arrange & Act + var response = await Client.GetStringAsync( "http://localhost/api/Blog/BasicApi/ValidateObjectWithPrefixFails?prefix=prefix"); // Assert @@ -182,12 +157,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_CanValidateCustomObject_IsSuccessFul() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/api/Blog/BasicApi/ValidateObject_Passes"); + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/api/Blog/BasicApi/ValidateObject_Passes"); // Assert Assert.Equal("true", response); @@ -196,12 +167,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [Fact] public async Task ApiController_CanValidateCustomObject_Fails() { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetStringAsync("http://localhost/api/Blog/BasicApi/ValidateObjectFails"); + // Arrange & Act + var response = await Client.GetStringAsync("http://localhost/api/Blog/BasicApi/ValidateObjectFails"); // Assert var json = JsonConvert.DeserializeObject>(response); @@ -215,15 +182,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_RequestProperty() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - var expected = - "POST http://localhost/api/Blog/HttpRequestMessage/EchoProperty localhost " + + var expected = "POST http://localhost/api/Blog/HttpRequestMessage/EchoProperty localhost " + "13 Hello, world!"; // Act - var response = await client.PostAsync( + var response = await Client.PostAsync( "http://localhost/api/Blog/HttpRequestMessage/EchoProperty", new StringContent("Hello, world!")); var content = await response.Content.ReadAsStringAsync(); @@ -239,15 +202,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_RequestParameter() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var expected = "POST http://localhost/api/Blog/HttpRequestMessage/EchoParameter localhost " + "17 Hello, the world!"; // Act - var response = await client.PostAsync( + var response = await Client.PostAsync( "http://localhost/api/Blog/HttpRequestMessage/EchoParameter", new StringContent("Hello, the world!")); var content = await response.Content.ReadAsStringAsync(); @@ -261,14 +221,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_ResponseReturned() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - var expected = - "POST Hello, HttpResponseMessage world!"; + var expected = "POST Hello, HttpResponseMessage world!"; // Act - var response = await client.PostAsync( + var response = await Client.PostAsync( "http://localhost/api/Blog/HttpRequestMessage/EchoWithResponseMessage", new StringContent("Hello, HttpResponseMessage world!")); var content = await response.Content.ReadAsStringAsync(); @@ -287,22 +243,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_ExplicitChunkedEncoding_IsIgnored() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - var expected = - "POST Hello, HttpResponseMessage world!"; - - // Act + var expected = "POST Hello, HttpResponseMessage world!"; var request = new HttpRequestMessage(); request.Method = HttpMethod.Post; request.RequestUri = new Uri("http://localhost/api/Blog/HttpRequestMessage/EchoWithResponseMessageChunked"); request.Content = new StringContent("Hello, HttpResponseMessage world!"); + // Act // HttpClient buffers the response by default and this would set the Content-Length header and so // this will not provide us accurate information as to whether the server set the header or // the client. So here we explicitly mention to only read the headers and not the body. - var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); + var response = await Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -315,7 +266,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests Assert.Null(response.Headers.TransferEncodingChunked); - // When HttpClient by default reads and buffers the resposne body, it diposes the + // When HttpClient by default reads and buffers the response body, it disposes the // response stream for us. But since we are reading the content explicitly, we need // to close it. var responseStream = await response.Content.ReadAsStreamAsync(); @@ -343,7 +294,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var request = new HttpRequestMessage( HttpMethod.Get, "http://localhost/api/Blog/HttpRequestMessage/GetUser"); - request.Headers.Accept.ParseAdd(accept); // Act @@ -393,7 +343,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var request = new HttpRequestMessage( HttpMethod.Get, "http://localhost/api/Blog/HttpRequestMessage/Fail"); - request.Headers.Accept.ParseAdd(accept); // Act @@ -410,9 +359,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_CreateResponse_HardcodedFormatter() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage( HttpMethod.Get, "http://localhost/api/Blog/HttpRequestMessage/GetUserJson"); @@ -421,7 +367,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml")); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var user = await response.Content.ReadAsAsync(); // Assert @@ -436,13 +382,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebApiRouting_AccessMvcController(string url, HttpStatusCode expected) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, url); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(expected, response.StatusCode); @@ -454,13 +397,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task WebApiRouting_AccessWebApiController(string url, HttpStatusCode expected) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, url); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); // Assert Assert.Equal(expected, response.StatusCode); @@ -470,12 +410,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_Returns_ByteArrayContent() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedBody = "Hello from ByteArrayContent!!"; // Act - var response = await client.GetAsync("http://localhost/api/Blog/HttpRequestMessage/ReturnByteArrayContent"); + var response = await Client.GetAsync("http://localhost/api/Blog/HttpRequestMessage/ReturnByteArrayContent"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -490,12 +428,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_Returns_StreamContent() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedBody = "This content is from a file"; // Act - var response = await client.GetAsync("http://localhost/api/Blog/HttpRequestMessage/ReturnStreamContent"); + var response = await Client.GetAsync("http://localhost/api/Blog/HttpRequestMessage/ReturnStreamContent"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -513,12 +449,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests [InlineData("ReturnPushStreamContentSync", "Hello from PushStreamContent Sync!!")] public async Task ApiController_Returns_PushStreamContent(string action, string expectedBody) { - // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - - // Act - var response = await client.GetAsync("http://localhost/api/Blog/HttpRequestMessage/" + action); + // Arrange & Act + var response = await Client.GetAsync("http://localhost/api/Blog/HttpRequestMessage/" + action); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -533,13 +465,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_Returns_PushStreamContentWithCustomHeaders() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var expectedBody = "Hello from PushStreamContent with custom headers!!"; var multipleValues = new[] { "value1", "value2" }; // Act - var response = await client.GetAsync("http://localhost/api/Blog/HttpRequestMessage/ReturnPushStreamContentWithCustomHeaders"); + var response = await Client.GetAsync( + "http://localhost/api/Blog/HttpRequestMessage/ReturnPushStreamContentWithCustomHeaders"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimParameterBindingTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimParameterBindingTest.cs index 95c5fd1ed0..08c169d9b0 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimParameterBindingTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/WebApiCompatShimParameterBindingTest.cs @@ -1,24 +1,24 @@ // 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.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class WebApiCompatShimParameterBindingTest + public class WebApiCompatShimParameterBindingTest : IClassFixture> { - private const string SiteName = nameof(WebApiCompatShimWebSite); - private readonly Action _app = new WebApiCompatShimWebSite.Startup().Configure; - private readonly Action _configureServices = new WebApiCompatShimWebSite.Startup().ConfigureServices; + public WebApiCompatShimParameterBindingTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("http://localhost/api/Blog/Employees/PostByIdDefault/5")] @@ -26,13 +26,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_SimpleParameter_Default_ReadsFromUrl(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Post, url); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -44,9 +41,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_SimpleParameter_Default_DoesNotReadFormData() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/api/Blog/Employees/PostByIdDefault"; var request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = new FormUrlEncodedContent(new Dictionary() @@ -55,7 +49,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -69,13 +63,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_SimpleParameter_ModelBinder_ReadsFromUrl(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Post, url); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -87,9 +78,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_SimpleParameter_ModelBinder_ReadsFromFormData() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/api/Blog/Employees/PostByIdModelBinder"; var request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = new FormUrlEncodedContent(new Dictionary() @@ -98,7 +86,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -112,13 +100,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_SimpleParameter_FromQuery_ReadsFromQueryNotRouteData(string url, string expected) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Post, url); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -130,9 +115,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_SimpleParameter_FromQuery_DoesNotReadFormData() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/api/Blog/Employees/PostByIdFromQuery"; var request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = new FormUrlEncodedContent(new Dictionary() @@ -141,7 +123,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -153,9 +135,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_ComplexParameter_Default_ReadsFromBody() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/api/Blog/Employees/PutEmployeeDefault"; var request = new HttpRequestMessage(HttpMethod.Put, url); request.Content = new StringContent(JsonConvert.SerializeObject(new @@ -166,7 +145,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -178,9 +157,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_ComplexParameter_ModelBinder_ReadsFormAndUrl() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/api/Blog/Employees/PutEmployeeModelBinder/5"; var request = new HttpRequestMessage(HttpMethod.Put, url); request.Content = new FormUrlEncodedContent(new Dictionary() @@ -189,7 +165,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests }); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert @@ -202,9 +178,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ApiController_TwoParameters_DefaultSources() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - var url = "http://localhost/api/Blog/Employees/PutEmployeeBothDefault?name=Name_Override"; var request = new HttpRequestMessage(HttpMethod.Put, url); request.Content = new StringContent(JsonConvert.SerializeObject(new @@ -215,7 +188,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); // Assert diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/XmlDataContractSerializerFormattersWrappingTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/XmlDataContractSerializerFormattersWrappingTest.cs index 245729d9aa..b114d8b7d0 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/XmlDataContractSerializerFormattersWrappingTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/XmlDataContractSerializerFormattersWrappingTest.cs @@ -1,24 +1,24 @@ // 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.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class XmlDataContractSerializerFormattersWrappingTest + public class XmlDataContractSerializerFormattersWrappingTest : IClassFixture> { - private const string SiteName = nameof(XmlFormattersWebSite); - private readonly Action _app = new XmlFormattersWebSite.Startup().Configure; - private readonly Action _configureServices = new XmlFormattersWebSite.Startup().ConfigureServices; + public XmlDataContractSerializerFormattersWrappingTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [ConditionalTheory] // Mono issue - https://github.com/aspnet/External/issues/18 @@ -28,21 +28,20 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanWrite_ValueTypes(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var result = await response.Content.ReadAsStringAsync(); - XmlAssert.Equal("" + - "1020", - result); + XmlAssert.Equal( + "" + + "1020", + result); } [ConditionalTheory] @@ -53,21 +52,20 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanWrite_NonWrappedTypes(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var result = await response.Content.ReadAsStringAsync(); - XmlAssert.Equal("" + - "value1value2", - result); + XmlAssert.Equal( + "" + + "value1value2", + result); } [ConditionalTheory] @@ -78,20 +76,19 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanWrite_NonWrappedTypes_Empty(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var result = await response.Content.ReadAsStringAsync(); - XmlAssert.Equal("", - result); + XmlAssert.Equal( + "", + result); } [ConditionalTheory] @@ -102,20 +99,19 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanWrite_NonWrappedTypes_NullInstance(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var result = await response.Content.ReadAsStringAsync(); - XmlAssert.Equal("", - result); + XmlAssert.Equal( + "", + result); } [ConditionalTheory] @@ -126,18 +122,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanWrite_WrappedTypes(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var result = await response.Content.ReadAsStringAsync(); - XmlAssert.Equal("" + "3510Mike35" + "11Jimmy", @@ -152,18 +147,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanWrite_WrappedTypes_Empty(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var result = await response.Content.ReadAsStringAsync(); - XmlAssert.Equal("", result); } @@ -176,18 +170,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanWrite_WrappedTypes_NullInstance(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var result = await response.Content.ReadAsStringAsync(); - XmlAssert.Equal("", result); } @@ -198,18 +191,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanWrite_IEnumerableOf_SerializableErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/IEnumerable/SerializableErrors"); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var result = await response.Content.ReadAsStringAsync(); - XmlAssert.Equal("" + "key1-errorkey2-error" + "key1-errorkey2-error" + diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/XmlDataContractSerializerInputFormatterTest.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/XmlDataContractSerializerInputFormatterTest.cs index a0485f54f2..8b1d8082ac 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/XmlDataContractSerializerInputFormatterTest.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/XmlDataContractSerializerInputFormatterTest.cs @@ -1,7 +1,6 @@ // 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.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; @@ -11,19 +10,14 @@ using System.Net.Http.Headers; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using XmlFormattersWebSite; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class XmlDataContractSerializerInputFormatterTest + public class XmlDataContractSerializerInputFormatterTest : IClassFixture> { - private const string SiteName = nameof(XmlFormattersWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; private readonly string errorMessageFormat = string.Format( "{{1}}:{0} does not recognize '{1}', so instead use '{2}' with '{3}' set to '{4}' for value " + "type property '{{0}}' on type '{{1}}'.", @@ -33,19 +27,24 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests nameof(DataMemberAttribute.IsRequired), bool.TrueString); + public XmlDataContractSerializerInputFormatterTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } + [ConditionalFact] // Mono issue - https://github.com/aspnet/External/issues/18 [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task ThrowsOnInvalidInput_AndAddsToModelState() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "Not a valid xml document"; var content = new StringContent(input, Encoding.UTF8, "application/xml-dcs"); // Act - var response = await client.PostAsync("http://localhost/Home/Index", content); + var response = await Client.PostAsync("http://localhost/Home/Index", content); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); @@ -63,18 +62,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task RequiredDataIsProvided_AndModelIsBound_NoValidationErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml-dcs")); var input = "
WA" + - "98052
10
"; - var content = new StringContent(input, Encoding.UTF8, "application/xml-dcs"); + "xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">
WA" + + "98052
10"; + var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Validation/CreateStore"); + request.Content = new StringContent(input, Encoding.UTF8, "application/xml-dcs"); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml-dcs")); // Act - var response = await client.PostAsync("http://localhost/Validation/CreateStore", content); + var response = await Client.SendAsync(request); - //Assert + // Assert var dcsSerializer = new DataContractSerializer(typeof(ModelBindingInfo)); var responseStream = await response.Content.ReadAsStreamAsync(); var modelBindingInfo = dcsSerializer.ReadObject(responseStream) as ModelBindingInfo; @@ -94,21 +92,20 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task DataMissingForRefereneceTypeProperties_AndModelIsBound_AndHasMixedValidationErrors() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml-dcs")); var input = "" + - "
10"; - var content = new StringContent(input, Encoding.UTF8, "application/xml-dcs"); + " xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" + + "
10"; + var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Validation/CreateStore"); + request.Content = new StringContent(input, Encoding.UTF8, "application/xml-dcs"); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml-dcs")); var expectedErrorMessages = new List(); expectedErrorMessages.Add("Address:The Address field is required."); // Act - var response = await client.PostAsync("http://localhost/Validation/CreateStore", content); + var response = await Client.SendAsync(request); - //Assert + // Assert var dcsSerializer = new DataContractSerializer(typeof(ModelBindingInfo)); var responseStream = await response.Content.ReadAsStreamAsync(); var modelBindingInfo = dcsSerializer.ReadObject(responseStream) as ModelBindingInfo; @@ -121,8 +118,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests foreach (var expectedErrorMessage in expectedErrorMessages) { Assert.Contains( - modelBindingInfo.ModelStateErrorMessages, - (actualErrorMessage) => actualErrorMessage.Equals(expectedErrorMessage)); + modelBindingInfo.ModelStateErrorMessages, + (actualErrorMessage) => actualErrorMessage.Equals(expectedErrorMessage)); } } } diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/XmlOutputFormatterTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/XmlOutputFormatterTests.cs index da357c8bcf..f94f44adc2 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/XmlOutputFormatterTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/XmlOutputFormatterTests.cs @@ -1,25 +1,24 @@ // 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.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; -using FormatterWebSite; -using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Testing.xunit; -using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { - public class XmlOutputFormatterTests + public class XmlOutputFormatterTests : IClassFixture> { - private const string SiteName = nameof(FormatterWebSite); - private readonly Action _app = new Startup().Configure; - private readonly Action _configureServices = new Startup().ConfigureServices; + public XmlOutputFormatterTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [ConditionalFact] // Mono.Xml2.XmlTextReader.ReadText is unable to read the XML. This is fixed in mono 4.3.0. @@ -27,17 +26,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task XmlDataContractSerializerOutputFormatterIsCalled() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage( HttpMethod.Post, "http://localhost/Home/GetDummyClass?sampleInput=10"); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8")); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); XmlAssert.Equal( "> { - private const string SiteName = nameof(XmlFormattersWebSite); - private readonly Action _app = new XmlFormattersWebSite.Startup().Configure; - private readonly Action _configureServices = new XmlFormattersWebSite.Startup().ConfigureServices; + public XmlSerializerFormattersWrappingTest(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Theory] [InlineData("http://localhost/IEnumerable/ValueTypes")] @@ -25,15 +25,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task CanWrite_ValueTypes(string url) { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser")); // Act - var response = await client.SendAsync(request); + var response = await Client.SendAsync(request); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var result = await response.Content.ReadAsStringAsync(); XmlAssert.Equal("> { - private const string SiteName = nameof(XmlFormattersWebSite); - private readonly Action _app = new XmlFormattersWebSite.Startup().Configure; - private readonly Action _configureServices = new XmlFormattersWebSite.Startup().ConfigureServices; + public XmlSerializerInputFormatterTests(MvcTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } [Fact] public async Task CheckIfXmlSerializerInputFormatterIsCalled() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var sampleInputInt = 10; var input = "" + "" @@ -32,9 +30,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests var content = new StringContent(input, Encoding.UTF8, "application/xml-xmlser"); // Act - var response = await client.PostAsync("http://localhost/Home/Index", content); + var response = await Client.PostAsync("http://localhost/Home/Index", content); - //Assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(sampleInputInt.ToString(), await response.Content.ReadAsStringAsync()); } @@ -45,13 +43,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests public async Task ThrowsOnInvalidInput_AndAddsToModelState() { // Arrange - var server = TestHelper.CreateServer(_app, SiteName, _configureServices); - var client = server.CreateClient(); var input = "Not a valid xml document"; var content = new StringContent(input, Encoding.UTF8, "application/xml-xmlser"); // Act - var response = await client.PostAsync("http://localhost/Home/Index", content); + var response = await Client.PostAsync("http://localhost/Home/Index", content); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home.Link.Encoded.html b/test/Microsoft.AspNet.Mvc.FunctionalTests/compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home.Link.Encoded.html index 8a38510597..96eb7ef151 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home.Link.Encoded.html +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home.Link.Encoded.html @@ -1,4 +1,4 @@ - + @@ -39,63 +39,63 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -120,7 +120,7 @@ - + diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home.Script.Encoded.html b/test/Microsoft.AspNet.Mvc.FunctionalTests/compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home.Script.Encoded.html index f1f2158a0a..89e6020c72 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home.Script.Encoded.html +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home.Script.Encoded.html @@ -1,4 +1,4 @@ - + @@ -13,27 +13,27 @@ - + - + - + - + - + - + - + - + - +