Use `MvcTextFixture` as much as possible

- #3066
  - reduce `TestServer` -> `PhysicalFileProvider` -> `FileSystemWatcher` count enough to run with Core CLR on Linux
- remove use of `HttpClient.DefaultRequestHeaders`; any client change affects other tests
- remove use of `RequestBuilder` class; creates a per-test `HttpClient` and requires the `TestServer`
- updated a few expectations because `CommonTestEncoder` does JavaScript a bit differently
  - "JavaScriptEncode[[...]]" -> "JavaScriptStringEncode[[...]]"
- side benefit: xUnit reports functional tests execute for only ~12.4s; was >30s before this change

Infrastructure: Enhance `MvcTestFixture`
- handle `ConfigureServices()` methods that are not `void`
- handle `Configure(IApplicationBuilder, ILoggerFactory)`
- ensure server is initialized with consistent `CurrentCulture` and `CurrentUICulture`
- add `FilteredDefaultAssemblyProviderFixture<TStartup>` and `MvcEncodedTestFixture<TStartup>`
  - add `MvcTextFixture.AddAdditionalServices()` extension point supporting these

- do not expose the `TestServer`; an anti-pattern for tests to manipulate the server
- update class names to match containing files
- use existing `TestApplicationEnvironment`
  - apply some `MvcTestFixture` improvements to the shared `TestApplicationEnvironment` class
- remove unused methods from `TestHelper`

nits:
- touched-up some leftover `_app` &c declarations to be more explicit and minimize `using`s
- moved statements into correct sections of methods in `RoutingTests`
- removed `TestLoggerFactory` and related classes from `TagHelperSampleTest`
This commit is contained in:
Doug Bunting 2015-09-10 19:43:55 -07:00
parent 6459fb0e30
commit d03a851ab3
88 changed files with 2340 additions and 4401 deletions

View File

@ -12,9 +12,9 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ActionResultTests : IClassFixture<MvcFixture<ActionResultsWebSite.Startup>> public class ActionResultTests : IClassFixture<MvcTestFixture<ActionResultsWebSite.Startup>>
{ {
public ActionResultTests(MvcFixture<ActionResultsWebSite.Startup> fixture) public ActionResultTests(MvcTestFixture<ActionResultsWebSite.Startup> fixture)
{ {
Client = fixture.Client; Client = fixture.Client;
} }

View File

@ -8,9 +8,9 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ActivatorTests : IClassFixture<MvcFixture<ActivatorWebSite.Startup>> public class ActivatorTests : IClassFixture<MvcTestFixture<ActivatorWebSite.Startup>>
{ {
public ActivatorTests(MvcFixture<ActivatorWebSite.Startup> fixture) public ActivatorTests(MvcTestFixture<ActivatorWebSite.Startup> fixture)
{ {
Client = fixture.Client; Client = fixture.Client;
} }

View File

@ -1,33 +1,29 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class AntiforgeryTests public class AntiforgeryTests : IClassFixture<MvcTestFixture<AntiforgeryTokenWebSite.Startup>>
{ {
private const string SiteName = nameof(AntiforgeryTokenWebSite); public AntiforgeryTests(MvcTestFixture<AntiforgeryTokenWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new AntiforgeryTokenWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new AntiforgeryTokenWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task MultipleAFTokensWithinTheSamePage_GeneratesASingleCookieToken() public async Task MultipleAFTokensWithinTheSamePage_GeneratesASingleCookieToken()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Account/Login");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Account/Login");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -45,11 +41,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task MultipleFormPostWithingASingleView_AreAllowed() public async Task MultipleFormPostWithingASingleView_AreAllowed()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Do a get request.
var client = server.CreateClient(); var getResponse = await Client.GetAsync("http://localhost/Account/Login");
// do a get response.
var getResponse = await client.GetAsync("http://localhost/Account/Login");
var responseBody = await getResponse.Content.ReadAsStringAsync(); var responseBody = await getResponse.Content.ReadAsStringAsync();
// Get the AF token for the second login. If the cookies are generated twice(i.e are different), // 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); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -80,10 +73,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task InvalidCookieToken_Throws() public async Task InvalidCookieToken_Throws()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var getResponse = await Client.GetAsync("http://localhost/Account/Login");
var client = server.CreateClient();
var getResponse = await client.GetAsync("http://localhost/Account/Login");
var responseBody = await getResponse.Content.ReadAsStringAsync(); var responseBody = await getResponse.Content.ReadAsStringAsync();
var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseBody, "Account/Login"); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseBody, "Account/Login");
@ -101,7 +91,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var exception = response.GetServerException(); var exception = response.GetServerException();
@ -112,10 +102,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task InvalidFormToken_Throws() public async Task InvalidFormToken_Throws()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var getResponse = await Client.GetAsync("http://localhost/Account/Login");
var client = server.CreateClient();
var getResponse = await client.GetAsync("http://localhost/Account/Login");
var responseBody = await getResponse.Content.ReadAsStringAsync(); var responseBody = await getResponse.Content.ReadAsStringAsync();
var cookieToken = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); var cookieToken = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse);
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Account/Login"); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Account/Login");
@ -131,7 +118,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var exception = response.GetServerException(); var exception = response.GetServerException();
@ -142,16 +129,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task IncompatibleCookieToken_Throws() public async Task IncompatibleCookieToken_Throws()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// do a get response. // do a get response.
// We do two requests to get two different sets of antiforgery cookie and token values. // 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 responseBody1 = await getResponse1.Content.ReadAsStringAsync();
var formToken1 = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseBody1, "Account/Login"); 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 responseBody2 = await getResponse2.Content.ReadAsStringAsync();
var cookieToken2 = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse2); var cookieToken2 = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse2);
@ -169,7 +153,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var exception = response.GetServerException(); var exception = response.GetServerException();
@ -180,11 +164,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task MissingCookieToken_Throws() public async Task MissingCookieToken_Throws()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// do a get response. // 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 responseBody = await getResponse.Content.ReadAsStringAsync();
var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseBody, "Account/Login"); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseBody, "Account/Login");
var cookieTokenKey = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse).Key; var cookieTokenKey = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse).Key;
@ -200,7 +181,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var exception = response.GetServerException(); var exception = response.GetServerException();
@ -213,9 +194,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task MissingAFToken_Throws() public async Task MissingAFToken_Throws()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var getResponse = await Client.GetAsync("http://localhost/Account/Login");
var client = server.CreateClient();
var getResponse = await client.GetAsync("http://localhost/Account/Login");
var responseBody = await getResponse.Content.ReadAsStringAsync(); var responseBody = await getResponse.Content.ReadAsStringAsync();
var cookieToken = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse); var cookieToken = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse);
@ -230,7 +209,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var exception = response.GetServerException(); var exception = response.GetServerException();
@ -241,12 +220,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task SetCookieAndHeaderBeforeFlushAsync_GeneratesCookieTokenAndHeader() public async Task SetCookieAndHeaderBeforeFlushAsync_GeneratesCookieTokenAndHeader()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Account/FlushAsyncLogin");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Account/FlushAsyncLogin");
// Assert // Assert
var header = Assert.Single(response.Headers.GetValues("X-Frame-Options")); var header = Assert.Single(response.Headers.GetValues("X-Frame-Options"));
@ -260,11 +235,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task SetCookieAndHeaderBeforeFlushAsync_PostToForm() public async Task SetCookieAndHeaderBeforeFlushAsync_PostToForm()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// do a get response. // 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 responseBody = await getResponse.Content.ReadAsStringAsync();
var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseBody, "Account/FlushAsyncLogin"); var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseBody, "Account/FlushAsyncLogin");
@ -282,7 +254,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -1,35 +1,31 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Formatters; using Microsoft.AspNet.Mvc.Formatters;
using Microsoft.AspNet.Mvc.ModelBinding; using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ApiExplorerTest public class ApiExplorerTest : IClassFixture<MvcTestFixture<ApiExplorerWebSite.Startup>>
{ {
private const string SiteName = nameof(ApiExplorerWebSite); public ApiExplorerTest(MvcTestFixture<ApiExplorerWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new ApiExplorerWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new ApiExplorerWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task ApiExplorer_IsVisible_EnabledWithConvention() public async Task ApiExplorer_IsVisible_EnabledWithConvention()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerVisbilityEnabledByConvention");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerVisbilityEnabledByConvention");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -41,12 +37,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_IsVisible_DisabledWithConvention() public async Task ApiExplorer_IsVisible_DisabledWithConvention()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerVisbilityDisabledByConvention");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerVisbilityDisabledByConvention");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -58,12 +50,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_IsVisible_DisabledWithAttribute() public async Task ApiExplorer_IsVisible_DisabledWithAttribute()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerVisibilitySetExplicitly/Disabled");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerVisibilitySetExplicitly/Disabled");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -75,12 +63,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_IsVisible_EnabledWithAttribute() public async Task ApiExplorer_IsVisible_EnabledWithAttribute()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerVisibilitySetExplicitly/Enabled");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerVisibilitySetExplicitly/Enabled");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -92,12 +76,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_GroupName_SetByConvention() public async Task ApiExplorer_GroupName_SetByConvention()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerNameSetByConvention");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerNameSetByConvention");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -110,12 +90,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_GroupName_SetByAttributeOnController() public async Task ApiExplorer_GroupName_SetByAttributeOnController()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerNameSetExplicitly/SetOnController");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerNameSetExplicitly/SetOnController");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -128,12 +104,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_GroupName_SetByAttributeOnAction() public async Task ApiExplorer_GroupName_SetByAttributeOnAction()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerNameSetExplicitly/SetOnAction");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerNameSetExplicitly/SetOnAction");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -146,12 +118,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_RouteTemplate_DisplaysFixedRoute() public async Task ApiExplorer_RouteTemplate_DisplaysFixedRoute()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerRouteAndPathParametersInformation");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerRouteAndPathParametersInformation");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -164,12 +132,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_RouteTemplate_DisplaysRouteWithParameters() public async Task ApiExplorer_RouteTemplate_DisplaysRouteWithParameters()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerRouteAndPathParametersInformation/5");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerRouteAndPathParametersInformation/5");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -189,12 +153,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiExplorer_RouteTemplate_StripsInlineConstraintsFromThePath() public async Task ApiExplorer_RouteTemplate_StripsInlineConstraintsFromThePath()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/Constraint/5"; var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/Constraint/5";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -214,12 +176,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiExplorer_RouteTemplate_StripsCatchAllsFromThePath() public async Task ApiExplorer_RouteTemplate_StripsCatchAllsFromThePath()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/CatchAll/5"; var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/CatchAll/5";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -238,12 +198,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiExplorer_RouteTemplate_StripsCatchAllsWithConstraintsFromThePath() public async Task ApiExplorer_RouteTemplate_StripsCatchAllsWithConstraintsFromThePath()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/CatchAllAndConstraint/5"; var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/CatchAllAndConstraint/5";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -265,9 +223,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiExplorer_RouteTemplateStripsMultipleConstraints_OnTheSamePathSegment() public async Task ApiExplorer_RouteTemplateStripsMultipleConstraints_OnTheSamePathSegment()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/" var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/"
+ "MultipleParametersInSegment/12-01-1987"; + "MultipleParametersInSegment/12-01-1987";
@ -275,7 +230,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
+ "MultipleParametersInSegment/{month}-{day}-{year}"; + "MultipleParametersInSegment/{month}-{day}-{year}";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -304,8 +259,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiExplorer_RouteTemplateStripsMultipleConstraints_InMultipleSegments() public async Task ApiExplorer_RouteTemplateStripsMultipleConstraints_InMultipleSegments()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/" var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/"
+ "MultipleParametersInMultipleSegments/12/01/1987"; + "MultipleParametersInMultipleSegments/12/01/1987";
@ -313,7 +266,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
+ "MultipleParametersInMultipleSegments/{month}/{day}/{year}"; + "MultipleParametersInMultipleSegments/{month}/{day}/{year}";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -342,15 +295,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiExplorer_DescribeParameters_FromAllSources() public async Task ApiExplorer_DescribeParameters_FromAllSources()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/MultipleTypesOfParameters/1/2/3"; var url = "http://localhost/ApiExplorerRouteAndPathParametersInformation/MultipleTypesOfParameters/1/2/3";
var expectedRelativePath = "ApiExplorerRouteAndPathParametersInformation/" var expectedRelativePath = "ApiExplorerRouteAndPathParametersInformation/"
+ "MultipleTypesOfParameters/{path}/{pathAndQuery}/{pathAndFromBody}"; + "MultipleTypesOfParameters/{path}/{pathAndQuery}/{pathAndFromBody}";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -372,12 +323,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_RouteTemplate_MakesParametersOptional() public async Task ApiExplorer_RouteTemplate_MakesParametersOptional()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient(); "http://localhost/ApiExplorerRouteAndPathParametersInformation/Optional/");
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerRouteAndPathParametersInformation/Optional/");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -394,12 +342,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_HttpMethod_All() public async Task ApiExplorer_HttpMethod_All()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerHttpMethod/All");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerHttpMethod/All");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -412,12 +356,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_HttpMethod_Single() public async Task ApiExplorer_HttpMethod_Single()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerHttpMethod/Get");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerHttpMethod/Get");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -435,15 +375,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiExplorer_HttpMethod_Single(string httpMethod) public async Task ApiExplorer_HttpMethod_Single(string httpMethod)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod(httpMethod), new HttpMethod(httpMethod),
"http://localhost/ApiExplorerHttpMethod/Single"); "http://localhost/ApiExplorerHttpMethod/Single");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -460,12 +397,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("GetTask")] [InlineData("GetTask")]
public async Task ApiExplorer_ResponseType_VoidWithoutAttribute(string action) public async Task ApiExplorer_ResponseType_VoidWithoutAttribute(string action)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithoutAttribute/" + action); "http://localhost/ApiExplorerResponseTypeWithoutAttribute/" + action);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -485,12 +418,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("GetTaskOfDerivedActionResult")] [InlineData("GetTaskOfDerivedActionResult")]
public async Task ApiExplorer_ResponseType_UnknownWithoutAttribute(string action) public async Task ApiExplorer_ResponseType_UnknownWithoutAttribute(string action)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithoutAttribute/" + action); "http://localhost/ApiExplorerResponseTypeWithoutAttribute/" + action);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -508,12 +437,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("GetTaskOfInt", "System.Int32")] [InlineData("GetTaskOfInt", "System.Int32")]
public async Task ApiExplorer_ResponseType_KnownWithoutAttribute(string action, string type) public async Task ApiExplorer_ResponseType_KnownWithoutAttribute(string action, string type)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithoutAttribute/" + action); "http://localhost/ApiExplorerResponseTypeWithoutAttribute/" + action);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -532,12 +457,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("GetTask", "System.Int32")] [InlineData("GetTask", "System.Int32")]
public async Task ApiExplorer_ResponseType_KnownWithAttribute(string action, string type) public async Task ApiExplorer_ResponseType_KnownWithAttribute(string action, string type)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/ApiExplorerResponseTypeWithAttribute/" + action); "http://localhost/ApiExplorerResponseTypeWithAttribute/" + action);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -553,12 +474,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("Action", "ApiExplorerWebSite.Customer")] [InlineData("Action", "ApiExplorerWebSite.Customer")]
public async Task ApiExplorer_ResponseType_OverrideOnAction(string action, string type) public async Task ApiExplorer_ResponseType_OverrideOnAction(string action, string type)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/ApiExplorerResponseTypeOverrideOnAction/" + action); "http://localhost/ApiExplorerResponseTypeOverrideOnAction/" + action);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -574,12 +491,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[FrameworkSkipCondition(RuntimeFrameworks.Mono)] [FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ApiExplorer_ResponseContentType_Unset() public async Task ApiExplorer_ResponseContentType_Unset()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerResponseContentType/Unset");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerResponseContentType/Unset");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -604,12 +517,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_ResponseContentType_Specific() public async Task ApiExplorer_ResponseContentType_Specific()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerResponseContentType/Specific");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerResponseContentType/Specific");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -630,12 +539,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_ResponseContentType_NoMatch() public async Task ApiExplorer_ResponseContentType_NoMatch()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerResponseContentType/NoMatch");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerResponseContentType/NoMatch");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -657,12 +562,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
string contentType, string contentType,
string formatterType) string formatterType)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/ApiExplorerResponseContentTypeOverrideOnAction/" + action); "http://localhost/ApiExplorerResponseContentTypeOverrideOnAction/" + action);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -679,12 +580,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_Parameters_SimpleTypes_Default() public async Task ApiExplorer_Parameters_SimpleTypes_Default()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerParameters/SimpleParameters");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerParameters/SimpleParameters");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -707,12 +604,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_Parameters_SimpleTypes_BinderMetadataOnParameters() public async Task ApiExplorer_Parameters_SimpleTypes_BinderMetadataOnParameters()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient(); "http://localhost/ApiExplorerParameters/SimpleParametersWithBinderMetadata");
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerParameters/SimpleParametersWithBinderMetadata");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -735,12 +629,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_ParametersSimpleModel() public async Task ApiExplorer_ParametersSimpleModel()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerParameters/SimpleModel");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerParameters/SimpleModel");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -763,12 +653,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_Parameters_SimpleTypes_SimpleModel_FromBody() public async Task ApiExplorer_Parameters_SimpleTypes_SimpleModel_FromBody()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerParameters/SimpleModelFromBody/5");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerParameters/SimpleModelFromBody/5");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);
@ -791,12 +677,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiExplorer_Parameters_SimpleTypes_ComplexModel() public async Task ApiExplorer_Parameters_SimpleTypes_ComplexModel()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApiExplorerParameters/ComplexModel");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApiExplorerParameters/ComplexModel");
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body); var result = JsonConvert.DeserializeObject<List<ApiExplorerData>>(body);

View File

@ -1,31 +1,27 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ApplicationModelTest public class ApplicationModelTest : IClassFixture<MvcTestFixture<ApplicationModelWebSite.Startup>>
{ {
private const string SiteName = nameof(ApplicationModelWebSite); public ApplicationModelTest(MvcTestFixture<ApplicationModelWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new ApplicationModelWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new ApplicationModelWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task ControllerModel_CustomizedWithAttribute() public async Task ControllerModel_CustomizedWithAttribute()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/CoolController/GetControllerName");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/CoolController/GetControllerName");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -37,12 +33,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ActionModel_CustomizedWithAttribute() public async Task ActionModel_CustomizedWithAttribute()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ActionModel/ActionName");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ActionModel/ActionName");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -54,12 +46,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ParameterModel_CustomizedWithAttribute() public async Task ParameterModel_CustomizedWithAttribute()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ParameterModel/GetParameterMetadata");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ParameterModel/GetParameterMetadata");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -71,12 +59,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApplicationModel_AddPropertyToActionDescriptor_FromApplicationModel() public async Task ApplicationModel_AddPropertyToActionDescriptor_FromApplicationModel()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/GetCommonDescription");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/GetCommonDescription");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -88,12 +72,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApplicationModel_AddPropertyToActionDescriptor_ControllerModelOverwritesCommonApplicationProperty() public async Task ApplicationModel_AddPropertyToActionDescriptor_ControllerModelOverwritesCommonApplicationProperty()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApplicationModel/GetControllerDescription");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApplicationModel/GetControllerDescription");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -105,12 +85,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApplicationModel_ProvidesMetadataToActionDescriptor_ActionModelOverwritesControllerModelProperty() public async Task ApplicationModel_ProvidesMetadataToActionDescriptor_ActionModelOverwritesControllerModelProperty()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ApplicationModel/GetActionSpecificDescription");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ApplicationModel/GetActionSpecificDescription");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -122,12 +98,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApplicationModelExtensions_AddsConventionToAllControllers() public async Task ApplicationModelExtensions_AddsConventionToAllControllers()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Lisence/GetLisence");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Lisence/GetLisence");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -142,14 +114,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApplicationModelExtensions_AddsConventionToAllActions() public async Task ApplicationModelExtensions_AddsConventionToAllActions()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/GetHelloWorld"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/GetHelloWorld");
request.Headers.Add("helloWorld", "HelloWorld"); request.Headers.Add("helloWorld", "HelloWorld");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -14,7 +14,7 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class BasicTests : IClassFixture<MvcFixture<BasicWebSite.Startup>> public class BasicTests : IClassFixture<MvcTestFixture<BasicWebSite.Startup>>
{ {
// Some tests require comparing the actual response body against an expected response baseline // 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 // 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. // use it on all the rest of the tests.
private static readonly Assembly _resourcesAssembly = typeof(BasicTests).GetTypeInfo().Assembly; private static readonly Assembly _resourcesAssembly = typeof(BasicTests).GetTypeInfo().Assembly;
public BasicTests(MvcFixture<BasicWebSite.Startup> fixture) public BasicTests(MvcTestFixture<BasicWebSite.Startup> fixture)
{ {
Client = fixture.Client; Client = fixture.Client;
} }

View File

@ -1,39 +1,37 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class BestEffortLinkGenerationTest public class BestEffortLinkGenerationTest : IClassFixture<MvcTestFixture<BestEffortLinkGenerationWebSite.Startup>>
{ {
private const string SiteName = nameof(BestEffortLinkGenerationWebSite);
private readonly Action<IApplicationBuilder> _app = new BestEffortLinkGenerationWebSite.Startup().Configure;
private readonly Action<IServiceCollection> _configureServices = new BestEffortLinkGenerationWebSite.Startup().ConfigureServices;
private const string ExpectedOutput = @"<html> private const string ExpectedOutput = @"<html>
<body> <body>
<a href=""/Home/About"">About Us</a> <a href=""/Home/About"">About Us</a>
</body> </body>
</html>"; </html>";
public BestEffortLinkGenerationTest(MvcTestFixture<BestEffortLinkGenerationWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task GenerateLink_NonExistentAction() public async Task GenerateLink_NonExistentAction()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/Home/Index"; var url = "http://localhost/Home/Index";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert

View File

@ -1,22 +1,22 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using RazorWebSite;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Test to verify compilation options from the application are used to compile // Test to verify compilation options from the application are used to compile
// precompiled and dynamically compiled views. // precompiled and dynamically compiled views.
public class CompilationOptionsTests public class CompilationOptionsTests : IClassFixture<MvcTestFixture<RazorWebSite.Startup>>
{ {
private const string SiteName = nameof(RazorWebSite); public CompilationOptionsTests(MvcTestFixture<RazorWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task CompilationOptions_AreUsedByViewsAndPartials() 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 running from DNXCORE50
This method is only defined in DNXCORE50"; This method is only defined in DNXCORE50";
#endif #endif
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/ViewsConsumingCompilationOptions/"); var body = await Client.GetStringAsync("http://localhost/ViewsConsumingCompilationOptions/");
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);

View File

@ -1,29 +1,26 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class CompositeViewEngineTests public class CompositeViewEngineTests : IClassFixture<MvcTestFixture<CompositeViewEngineWebSite.Startup>>
{ {
private const string SiteName = nameof(CompositeViewEngineWebSite); public CompositeViewEngineTests(MvcTestFixture<CompositeViewEngineWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new CompositeViewEngineWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new CompositeViewEngineWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task CompositeViewEngine_FindsPartialViewsAcrossAllEngines() public async Task CompositeViewEngine_FindsPartialViewsAcrossAllEngines()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var body = await Client.GetStringAsync("http://localhost/");
var client = server.CreateClient();
// Act
var body = await client.GetStringAsync("http://localhost/");
// Assert // Assert
Assert.Equal("Hello world", body.Trim()); Assert.Equal("Hello world", body.Trim());
@ -32,12 +29,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task CompositeViewEngine_FindsViewsAcrossAllEngines() public async Task CompositeViewEngine_FindsViewsAcrossAllEngines()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var body = await Client.GetStringAsync("http://localhost/Home/TestView");
var client = server.CreateClient();
// Act
var body = await client.GetStringAsync("http://localhost/Home/TestView");
// Assert // Assert
Assert.Equal("Content from test view", body.Trim()); Assert.Equal("Content from test view", body.Trim());

View File

@ -1,41 +1,39 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ActionConstraintsWebSite; using ActionConstraintsWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Actions; using Microsoft.AspNet.Mvc.Actions;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ConsumesAttributeTests public class ConsumesAttributeTests : IClassFixture<MvcTestFixture<ActionConstraintsWebSite.Startup>>
{ {
private const string SiteName = nameof(ActionConstraintsWebSite); public ConsumesAttributeTests(MvcTestFixture<ActionConstraintsWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task NoRequestContentType_SelectsActionWithoutConstraint() public async Task NoRequestContentType_SelectsActionWithoutConstraint()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Post, HttpMethod.Post,
"http://localhost/ConsumesAttribute_Company/CreateProduct"); "http://localhost/ConsumesAttribute_Company/CreateProduct");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var product = JsonConvert.DeserializeObject<Product>( var product = JsonConvert.DeserializeObject<Product>(await response.Content.ReadAsStringAsync());
await response.Content.ReadAsStringAsync());
// Assert // Assert
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
Assert.Null(product); Assert.Null(product);
@ -45,14 +43,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task NoRequestContentType_Throws_IfMultipleActionsWithConstraints() public async Task NoRequestContentType_Throws_IfMultipleActionsWithConstraints()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Post, HttpMethod.Post,
"http://localhost/ConsumesAttribute_AmbiguousActions/CreateProduct"); "http://localhost/ConsumesAttribute_AmbiguousActions/CreateProduct");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var exception = response.GetServerException(); var exception = response.GetServerException();
// Assert // Assert
@ -72,17 +68,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task NoRequestContentType_Selects_IfASingleActionWithConstraintIsPresent() public async Task NoRequestContentType_Selects_IfASingleActionWithConstraintIsPresent()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Post, HttpMethod.Post,
"http://localhost/ConsumesAttribute_PassThrough/CreateProduct"); "http://localhost/ConsumesAttribute_PassThrough/CreateProduct");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var product = JsonConvert.DeserializeObject<Product>( var product = JsonConvert.DeserializeObject<Product>(await response.Content.ReadAsStringAsync());
await response.Content.ReadAsStringAsync());
// Assert // Assert
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
Assert.Null(product); Assert.Null(product);
@ -94,18 +87,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task Selects_Action_BasedOnRequestContentType(string requestContentType) public async Task Selects_Action_BasedOnRequestContentType(string requestContentType)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{SampleString:\""+requestContentType+"\"}"; var input = "{SampleString:\""+requestContentType+"\"}";
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Post, HttpMethod.Post,
"http://localhost/ConsumesAttribute_AmbiguousActions/CreateProduct"); "http://localhost/ConsumesAttribute_AmbiguousActions/CreateProduct");
request.Content = new StringContent(input, Encoding.UTF8, requestContentType); request.Content = new StringContent(input, Encoding.UTF8, requestContentType);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var product = JsonConvert.DeserializeObject<Product>( var product = JsonConvert.DeserializeObject<Product>(await response.Content.ReadAsStringAsync());
await response.Content.ReadAsStringAsync());
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(requestContentType, product.SampleString); Assert.Equal(requestContentType, product.SampleString);
@ -117,9 +108,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ActionLevelAttribute_OveridesClassLevel(string requestContentType) public async Task ActionLevelAttribute_OveridesClassLevel(string requestContentType)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{SampleString:\"" + requestContentType + "\"}"; var input = "{SampleString:\"" + requestContentType + "\"}";
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Post, HttpMethod.Post,
@ -128,9 +116,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var expectedString = "ConsumesAttribute_OverridesBaseController_" + requestContentType; var expectedString = "ConsumesAttribute_OverridesBaseController_" + requestContentType;
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var product = JsonConvert.DeserializeObject<Product>( var product = JsonConvert.DeserializeObject<Product>(await response.Content.ReadAsStringAsync());
await response.Content.ReadAsStringAsync());
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedString, product.SampleString); Assert.Equal(expectedString, product.SampleString);
@ -142,9 +130,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task DerivedClassLevelAttribute_OveridesBaseClassLevel() public async Task DerivedClassLevelAttribute_OveridesBaseClassLevel()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "<Product xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" " + var input = "<Product xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns=\"http://schemas.datacontract.org/2004/07/ActionConstraintsWebSite\">" + "xmlns=\"http://schemas.datacontract.org/2004/07/ActionConstraintsWebSite\">" +
"<SampleString>application/xml</SampleString></Product>"; "<SampleString>application/xml</SampleString></Product>";
@ -155,9 +140,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var expectedString = "ConsumesAttribute_OverridesController_application/xml"; var expectedString = "ConsumesAttribute_OverridesController_application/xml";
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync(); var responseString = await response.Content.ReadAsStringAsync();
var product = JsonConvert.DeserializeObject<Product>(responseString); var product = JsonConvert.DeserializeObject<Product>(responseString);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedString, product.SampleString); Assert.Equal(expectedString, product.SampleString);

View File

@ -7,34 +7,31 @@ using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ContentNegotiationWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Mvc.Formatters.Xml;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ContentNegotiationTest public class ContentNegotiationTest : IClassFixture<MvcTestFixture<ContentNegotiationWebSite.Startup>>
{ {
private const string SiteName = nameof(ContentNegotiationWebSite); public ContentNegotiationTest(MvcTestFixture<ContentNegotiationWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task ProducesAttribute_SingleContentType_PicksTheFirstSupportedFormatter() public async Task ProducesAttribute_SingleContentType_PicksTheFirstSupportedFormatter()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Selects custom even though it is last in the list. // Selects custom even though it is last in the list.
var expectedContentType = MediaTypeHeaderValue.Parse("application/custom;charset=utf-8"); var expectedContentType = MediaTypeHeaderValue.Parse("application/custom;charset=utf-8");
var expectedBody = "Written using custom format."; var expectedBody = "Written using custom format.";
// Act // Act
var response = await client.GetAsync("http://localhost/Normal/WriteUserUsingCustomFormat"); var response = await Client.GetAsync("http://localhost/Normal/WriteUserUsingCustomFormat");
// Assert // Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
@ -46,14 +43,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ProducesAttribute_MultipleContentTypes_RunsConnegToSelectFormatter() public async Task ProducesAttribute_MultipleContentTypes_RunsConnegToSelectFormatter()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
var expectedBody = $"{{{Environment.NewLine} \"Name\": \"My name\",{Environment.NewLine}" + var expectedBody = $"{{{Environment.NewLine} \"Name\": \"My name\",{Environment.NewLine}" +
$" \"Address\": \"My address\"{Environment.NewLine}}}"; $" \"Address\": \"My address\"{Environment.NewLine}}}";
// Act // Act
var response = await client.GetAsync("http://localhost/Normal/MultipleAllowedContentTypes"); var response = await Client.GetAsync("http://localhost/Normal/MultipleAllowedContentTypes");
// Assert // Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
@ -65,13 +60,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task NoProducesAttribute_ActionReturningString_RunsUsingTextFormatter() public async Task NoProducesAttribute_ActionReturningString_RunsUsingTextFormatter()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse("text/plain;charset=utf-8"); var expectedContentType = MediaTypeHeaderValue.Parse("text/plain;charset=utf-8");
var expectedBody = "NormalController"; var expectedBody = "NormalController";
// Act // Act
var response = await client.GetAsync("http://localhost/Normal/ReturnClassName"); var response = await Client.GetAsync("http://localhost/Normal/ReturnClassName");
// Assert // Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
@ -83,12 +76,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task NoProducesAttribute_ActionReturningAnyObject_RunsUsingDefaultFormatters() public async Task NoProducesAttribute_ActionReturningAnyObject_RunsUsingDefaultFormatters()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
// Act // Act
var response = await client.GetAsync("http://localhost/Normal/ReturnUser"); var response = await Client.GetAsync("http://localhost/Normal/ReturnUser");
// Assert // Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
@ -98,14 +89,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ProducesAttributeWithTypeOnly_RunsRegularContentNegotiation() public async Task ProducesAttributeWithTypeOnly_RunsRegularContentNegotiation()
{ {
// Arrange // 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 expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
var expectedOutput = "{\"Name\":\"John\",\"Address\":\"One Microsoft Way\"}"; 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 // Act
var response = await client.GetAsync("http://localhost/Home/UserInfo_ProducesWithTypeOnly"); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -120,16 +110,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ProducesAttribute_WithTypeAndContentType_UsesContentType() public async Task ProducesAttribute_WithTypeAndContentType_UsesContentType()
{ {
// Arrange // 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 expectedContentType = MediaTypeHeaderValue.Parse("application/xml;charset=utf-8");
var expectedOutput = "<User xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" " + var expectedOutput = "<User xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns=\"http://schemas.datacontract.org/2004/07/ContentNegotiationWebSite\">" + "xmlns=\"http://schemas.datacontract.org/2004/07/ContentNegotiationWebSite\">" +
"<Address>One Microsoft Way</Address><Name>John</Name></User>"; "<Address>One Microsoft Way</Address><Name>John</Name></User>";
var request = new HttpRequestMessage(
HttpMethod.Get,
"http://localhost/Home/UserInfo_ProducesWithTypeAndContentType");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
// Act // Act
var response = await client.GetAsync("http://localhost/Home/UserInfo_ProducesWithTypeAndContentType"); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -144,12 +135,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task NoAcceptAndRequestContentTypeHeaders_UsesFirstFormatterWhichCanWriteType(string url) public async Task NoAcceptAndRequestContentTypeHeaders_UsesFirstFormatterWhichCanWriteType(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
// Act // Act
var response = await client.GetAsync(url + "?input=100"); var response = await Client.GetAsync(url + "?input=100");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -161,12 +150,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task NoMatchingFormatter_ForTheGivenContentType_Returns406() public async Task NoMatchingFormatter_ForTheGivenContentType_Returns406()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Normal/ReturnUser_NoMatchingFormatter");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Normal/ReturnUser_NoMatchingFormatter");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
@ -193,12 +178,8 @@ END:VCARD
string expectedMediaType, string expectedMediaType,
string expectedResponseBody) string expectedResponseBody)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ProducesWithMediaTypeParameters/" + action);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ProducesWithMediaTypeParameters/" + action);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -214,16 +195,14 @@ END:VCARD
[Fact] [Fact]
public async Task ProducesAttribute_OnAction_OverridesTheValueOnClass() public async Task ProducesAttribute_OnAction_OverridesTheValueOnClass()
{ {
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Arrange
var client = server.CreateClient();
// Value on the class is application/json. // Value on the class is application/json.
var expectedContentType = MediaTypeHeaderValue.Parse( var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_ProducesContentBaseController_Action;charset=utf-8"); "application/custom_ProducesContentBaseController_Action;charset=utf-8");
var expectedBody = "ProducesContentBaseController"; var expectedBody = "ProducesContentBaseController";
// Act // Act
var response = await client.GetAsync("http://localhost/ProducesContentBase/ReturnClassName"); var response = await Client.GetAsync("http://localhost/ProducesContentBase/ReturnClassName");
// Assert // Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
@ -234,14 +213,13 @@ END:VCARD
[Fact] [Fact]
public async Task ProducesAttribute_OnDerivedClass_OverridesTheValueOnBaseClass() public async Task ProducesAttribute_OnDerivedClass_OverridesTheValueOnBaseClass()
{ {
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Arrange
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse( var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_ProducesContentOnClassController;charset=utf-8"); "application/custom_ProducesContentOnClassController;charset=utf-8");
var expectedBody = "ProducesContentOnClassController"; var expectedBody = "ProducesContentOnClassController";
// Act // Act
var response = await client.GetAsync( var response = await Client.GetAsync(
"http://localhost/ProducesContentOnClass/ReturnClassNameWithNoContentTypeOnAction"); "http://localhost/ProducesContentOnClass/ReturnClassNameWithNoContentTypeOnAction");
// Assert // Assert
@ -253,14 +231,13 @@ END:VCARD
[Fact] [Fact]
public async Task ProducesAttribute_OnDerivedAction_OverridesTheValueOnBaseClass() public async Task ProducesAttribute_OnDerivedAction_OverridesTheValueOnBaseClass()
{ {
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Arrange
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse( var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_NoProducesContentOnClassController_Action;charset=utf-8"); "application/custom_NoProducesContentOnClassController_Action;charset=utf-8");
var expectedBody = "NoProducesContentOnClassController"; var expectedBody = "NoProducesContentOnClassController";
// Act // Act
var response = await client.GetAsync("http://localhost/NoProducesContentOnClass/ReturnClassName"); var response = await Client.GetAsync("http://localhost/NoProducesContentOnClass/ReturnClassName");
// Assert // Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
@ -271,14 +248,13 @@ END:VCARD
[Fact] [Fact]
public async Task ProducesAttribute_OnDerivedAction_OverridesTheValueOnBaseAction() public async Task ProducesAttribute_OnDerivedAction_OverridesTheValueOnBaseAction()
{ {
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Arange
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse( var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_NoProducesContentOnClassController_Action;charset=utf-8"); "application/custom_NoProducesContentOnClassController_Action;charset=utf-8");
var expectedBody = "NoProducesContentOnClassController"; var expectedBody = "NoProducesContentOnClassController";
// Act // Act
var response = await client.GetAsync("http://localhost/NoProducesContentOnClass/ReturnClassName"); var response = await Client.GetAsync("http://localhost/NoProducesContentOnClass/ReturnClassName");
// Assert // Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
@ -290,14 +266,12 @@ END:VCARD
public async Task ProducesAttribute_OnDerivedClassAndAction_OverridesTheValueOnBaseClass() public async Task ProducesAttribute_OnDerivedClassAndAction_OverridesTheValueOnBaseClass()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse( var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_ProducesContentOnClassController_Action;charset=utf-8"); "application/custom_ProducesContentOnClassController_Action;charset=utf-8");
var expectedBody = "ProducesContentOnClassController"; var expectedBody = "ProducesContentOnClassController";
// Act // Act
var response = await client.GetAsync("http://localhost/ProducesContentOnClass/ReturnClassNameContentTypeOnDerivedAction"); var response = await Client.GetAsync("http://localhost/ProducesContentOnClass/ReturnClassNameContentTypeOnDerivedAction");
// Assert // Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
@ -309,13 +283,11 @@ END:VCARD
public async Task ProducesAttribute_IsNotHonored_ForJsonResult() public async Task ProducesAttribute_IsNotHonored_ForJsonResult()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
var expectedBody = "{\"MethodName\":\"Produces_WithNonObjectResult\"}"; var expectedBody = "{\"MethodName\":\"Produces_WithNonObjectResult\"}";
// Act // Act
var response = await client.GetAsync("http://localhost/JsonResult/Produces_WithNonObjectResult"); var response = await Client.GetAsync("http://localhost/JsonResult/Produces_WithNonObjectResult");
// Assert // Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
@ -329,10 +301,6 @@ END:VCARD
public async Task XmlFormatter_SupportedMediaType_DoesNotChangeAcrossRequests() public async Task XmlFormatter_SupportedMediaType_DoesNotChangeAcrossRequests()
{ {
// Arrange // 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 expectedContentType = MediaTypeHeaderValue.Parse("application/xml;charset=utf-8");
var expectedBody = @"<User xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" " + var expectedBody = @"<User xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" " +
@"xmlns=""http://schemas.datacontract.org/2004/07/ContentNegotiationWebSite""><Address>" @"xmlns=""http://schemas.datacontract.org/2004/07/ContentNegotiationWebSite""><Address>"
@ -340,8 +308,12 @@ END:VCARD
for (int i = 0; i < 5; i++) 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 // 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); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -355,8 +327,6 @@ END:VCARD
public async Task NoMatchOn_RequestContentType_FallsBackOnTypeBasedMatch_MatchFound(string actionName) public async Task NoMatchOn_RequestContentType_FallsBackOnTypeBasedMatch_MatchFound(string actionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
var expectedBody = "1234"; var expectedBody = "1234";
var targetUri = "http://localhost/FallbackOnTypeBasedMatch/" + actionName + "/?input=1234"; var targetUri = "http://localhost/FallbackOnTypeBasedMatch/" + actionName + "/?input=1234";
@ -366,7 +336,7 @@ END:VCARD
request.Content = content; request.Content = content;
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
@ -380,15 +350,13 @@ END:VCARD
public async Task ObjectResult_WithStringReturnType_WritesTextPlainFormat(bool matchFormatterOnObjectType) public async Task ObjectResult_WithStringReturnType_WritesTextPlainFormat(bool matchFormatterOnObjectType)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var targetUri = "http://localhost/FallbackOnTypeBasedMatch/ReturnString?matchFormatterOnObjectType=" + var targetUri = "http://localhost/FallbackOnTypeBasedMatch/ReturnString?matchFormatterOnObjectType=" +
matchFormatterOnObjectType; matchFormatterOnObjectType;
var request = new HttpRequestMessage(HttpMethod.Get, targetUri); var request = new HttpRequestMessage(HttpMethod.Get, targetUri);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -403,8 +371,6 @@ END:VCARD
public async Task NoMatchOn_RequestContentType_SkipTypeMatchByAddingACustomFormatter(string actionName) public async Task NoMatchOn_RequestContentType_SkipTypeMatchByAddingACustomFormatter(string actionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var targetUri = "http://localhost/FallbackOnTypeBasedMatch/" + actionName + "/?input=1234"; var targetUri = "http://localhost/FallbackOnTypeBasedMatch/" + actionName + "/?input=1234";
var content = new StringContent("1234", Encoding.UTF8, "application/custom"); var content = new StringContent("1234", Encoding.UTF8, "application/custom");
var request = new HttpRequestMessage(HttpMethod.Post, targetUri); var request = new HttpRequestMessage(HttpMethod.Post, targetUri);
@ -412,7 +378,7 @@ END:VCARD
request.Content = content; request.Content = content;
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
@ -422,8 +388,6 @@ END:VCARD
public async Task NoMatchOn_RequestContentType_FallsBackOnTypeBasedMatch_NoMatchFound_Returns406() public async Task NoMatchOn_RequestContentType_FallsBackOnTypeBasedMatch_NoMatchFound_Returns406()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var targetUri = "http://localhost/FallbackOnTypeBasedMatch/FallbackGivesNoMatch/?input=1234"; var targetUri = "http://localhost/FallbackOnTypeBasedMatch/FallbackGivesNoMatch/?input=1234";
var content = new StringContent("1234", Encoding.UTF8, "application/custom"); var content = new StringContent("1234", Encoding.UTF8, "application/custom");
var request = new HttpRequestMessage(HttpMethod.Post, targetUri); var request = new HttpRequestMessage(HttpMethod.Post, targetUri);
@ -431,7 +395,7 @@ END:VCARD
request.Content = content; request.Content = content;
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
@ -441,12 +405,10 @@ END:VCARD
public async Task ProducesAttribute_And_FormatFilterAttribute_Conflicting() public async Task ProducesAttribute_And_FormatFilterAttribute_Conflicting()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse("application/json"); var expectedContentType = MediaTypeHeaderValue.Parse("application/json");
// Act // Act
var response = await client.GetAsync("http://localhost/FormatFilter/MethodWithFormatFilter.json"); var response = await Client.GetAsync("http://localhost/FormatFilter/MethodWithFormatFilter.json");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -455,12 +417,8 @@ END:VCARD
[Fact] [Fact]
public async Task ProducesAttribute_And_FormatFilterAttribute_Collaborating() public async Task ProducesAttribute_And_FormatFilterAttribute_Collaborating()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/FormatFilter/MethodWithFormatFilter");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/FormatFilter/MethodWithFormatFilter");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -1,36 +1,34 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net; using System.Net;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using ControllerDiscoveryConventionsWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Dnx.Runtime;
using Xunit; using Xunit;
using Microsoft.AspNet.Mvc.Actions;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ControllerDiscoveryConventionTests public class ControllerDiscoveryConventionTests :
IClassFixture<MvcTestFixture<ControllerDiscoveryConventionsWebSite.Startup>>,
IClassFixture<FilteredDefaultAssemblyProviderFixture<ControllerDiscoveryConventionsWebSite.Startup>>
{ {
private const string SiteName = nameof(ControllerDiscoveryConventionsWebSite); public ControllerDiscoveryConventionTests(
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; MvcTestFixture<ControllerDiscoveryConventionsWebSite.Startup> fixture,
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; FilteredDefaultAssemblyProviderFixture<ControllerDiscoveryConventionsWebSite.Startup> filteredFixture)
{
Client = fixture.Client;
FilteredClient = filteredFixture.Client;
}
public HttpClient Client { get; }
public HttpClient FilteredClient { get; }
[Fact] [Fact]
public async Task AbstractControllers_AreSkipped() public async Task AbstractControllers_AreSkipped()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("Abstract/GetValue");
var client = server.CreateClient();
client.BaseAddress = new Uri("http://localhost/");
// Act
var response = await client.GetAsync("Abstract/GetValue");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -39,13 +37,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task TypesDerivingFromControllerBaseTypesThatDoNotReferenceMvc_AreSkipped() public async Task TypesDerivingFromControllerBaseTypesThatDoNotReferenceMvc_AreSkipped()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("SqlTransactionManager/GetValue");
var client = server.CreateClient();
client.BaseAddress = new Uri("http://localhost/");
// Act
var response = await client.GetAsync("SqlTransactionManager/GetValue");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -54,13 +47,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task TypesMarkedWithNonController_AreSkipped() public async Task TypesMarkedWithNonController_AreSkipped()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("NonController/GetValue");
var client = server.CreateClient();
client.BaseAddress = new Uri("http://localhost/");
// Act
var response = await client.GetAsync("NonController/GetValue");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -69,13 +57,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task PocoTypesWithControllerSuffix_AreDiscovered() public async Task PocoTypesWithControllerSuffix_AreDiscovered()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("Poco/GetValue");
var client = server.CreateClient();
client.BaseAddress = new Uri("http://localhost/");
// Act
var response = await client.GetAsync("Poco/GetValue");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -85,13 +68,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task TypesDerivingFromTypesWithControllerSuffix_AreDiscovered() public async Task TypesDerivingFromTypesWithControllerSuffix_AreDiscovered()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("ChildOfAbstract/GetValue");
var client = server.CreateClient();
client.BaseAddress = new Uri("http://localhost/");
// Act
var response = await client.GetAsync("ChildOfAbstract/GetValue");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -101,45 +79,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task TypesDerivingFromApiController_AreDiscovered() public async Task TypesDerivingFromApiController_AreDiscovered()
{ {
// Arrange // Arrange & Act
// TestHelper.CreateServer normally replaces the DefaultAssemblyProvider with a provider that var response = await FilteredClient.GetAsync("PersonApi/GetValue");
// 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<IAssemblyProvider, FilteredDefaultAssemblyProvider>();
});
var client = server.CreateClient();
client.BaseAddress = new Uri("http://localhost/");
// Act
var response = await client.GetAsync("PersonApi/GetValue");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("PersonApi", await response.Content.ReadAsStringAsync()); Assert.Equal("PersonApi", await response.Content.ReadAsStringAsync());
} }
private class FilteredDefaultAssemblyProvider : DefaultAssemblyProvider
{
public FilteredDefaultAssemblyProvider(ILibraryManager libraryManager)
: base(libraryManager)
{
}
protected override IEnumerable<Library> 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));
}
}
} }
} }

View File

@ -12,26 +12,29 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ControllerFromServicesTest public class ControllerFromServicesTest : IClassFixture<MvcTestFixture<ControllersFromServicesWebSite.Startup>>
{ {
private const string SiteName = nameof(ControllersFromServicesWebSite); public ControllerFromServicesTest(MvcTestFixture<ControllersFromServicesWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Func<IServiceCollection, IServiceProvider> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task ControllersWithConstructorInjectionAreCreatedAndActivated() public async Task ControllersWithConstructorInjectionAreCreatedAndActivated()
{ {
// Arrange // Arrange
var expected = "/constructorinjection 14 test-header-value"; var expected = "/constructorinjection 14 test-header-value";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/constructorinjection?value=14");
var client = server.CreateClient(); request.Headers.TryAddWithoutValidation("Test-Header", "test-header-value");
client.DefaultRequestHeaders.TryAddWithoutValidation("Test-Header", "test-header-value");
// Act // 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
Assert.Equal(expected, response); Assert.Equal(expected, responseText);
} }
[Fact] [Fact]
@ -39,11 +42,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = "No schedules available for 23"; var expected = "No schedules available for 23";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var response = await client.GetStringAsync("http://localhost/schedule/23"); var response = await Client.GetStringAsync("http://localhost/schedule/23");
// Assert // Assert
Assert.Equal(expected, response); Assert.Equal(expected, response);
@ -54,11 +55,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = "4"; var expected = "4";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var response = await client.GetStringAsync("http://localhost/inventory/"); var response = await Client.GetStringAsync("http://localhost/inventory/");
// Assert // Assert
Assert.Equal(expected, response); Assert.Equal(expected, response);
@ -69,11 +68,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = "Updated record employee303"; var expected = "Updated record employee303";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var response = await client.PutAsync("http://localhost/employee/update_records?recordId=employee303", var response = await Client.PutAsync(
"http://localhost/employee/update_records?recordId=employee303",
new StringContent(string.Empty)); new StringContent(string.Empty));
// Assert // Assert
@ -86,11 +84,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = "Saved record employee #211"; var expected = "Saved record employee #211";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var response = await client.PostAsync("http://localhost/employeerecords/save/211", var response = await Client.PostAsync(
"http://localhost/employeerecords/save/211",
new StringContent(string.Empty)); new StringContent(string.Empty));
// Assert // Assert
@ -105,12 +102,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("ClientUIStub/GetClientContent/5")] [InlineData("ClientUIStub/GetClientContent/5")]
public async Task AddControllersFromServices_UsesControllerDiscoveryContentions(string action) public async Task AddControllersFromServices_UsesControllerDiscoveryContentions(string action)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/" + action);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/" + action);
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

View File

@ -4,6 +4,7 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Cors.Core; using Microsoft.AspNet.Cors.Core;
@ -12,11 +13,14 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class CorsMiddlewareTests public class CorsMiddlewareTests : IClassFixture<MvcTestFixture<CorsMiddlewareWebSite.Startup>>
{ {
private const string SiteName = nameof(CorsMiddlewareWebSite); public CorsMiddlewareTests(MvcTestFixture<CorsMiddlewareWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new CorsMiddlewareWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new CorsMiddlewareWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("GET")] [InlineData("GET")]
@ -25,16 +29,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ResourceWithSimpleRequestPolicy_Allows_SimpleRequests(string method) public async Task ResourceWithSimpleRequestPolicy_Allows_SimpleRequests(string method)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var origin = "http://example.com"; var origin = "http://example.com";
var request = new HttpRequestMessage(
var requestBuilder = server new HttpMethod(method),
.CreateRequest("http://localhost/CorsMiddleware/GetExclusiveContent") "http://localhost/CorsMiddleware/GetExclusiveContent");
.AddHeader(CorsConstants.Origin, origin); request.Headers.Add(CorsConstants.Origin, origin);
// Act // Act
var response = await requestBuilder.SendAsync(method); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -54,18 +56,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task PolicyFailed_Disallows_PreFlightRequest(string method) public async Task PolicyFailed_Disallows_PreFlightRequest(string method)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var request = new HttpRequestMessage(
var client = server.CreateClient(); new HttpMethod(CorsConstants.PreflightHttpMethod),
"http://localhost/CorsMiddleware/GetExclusiveContent");
// Adding a custom header makes it a non simple request. // Adding a custom header makes it a non-simple request.
var requestBuilder = server request.Headers.Add(CorsConstants.Origin, "http://example.com");
.CreateRequest("http://localhost/CorsMiddleware/GetExclusiveContent") request.Headers.Add(CorsConstants.AccessControlRequestMethod, method);
.AddHeader(CorsConstants.Origin, "http://example.com") request.Headers.Add(CorsConstants.AccessControlRequestHeaders, "Custom");
.AddHeader(CorsConstants.AccessControlRequestMethod, method)
.AddHeader(CorsConstants.AccessControlRequestHeaders, "Custom");
// Act // Act
var response = await requestBuilder.SendAsync(CorsConstants.PreflightHttpMethod); var response = await Client.SendAsync(request);
// Assert // Assert
// Middleware applied the policy and since that did not pass, there were no access control headers. // 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() public async Task PolicyFailed_Allows_ActualRequest_WithMissingResponseHeaders()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var request = new HttpRequestMessage(HttpMethod.Put, "http://localhost/CorsMiddleware/GetExclusiveContent");
var client = server.CreateClient();
// Adding a custom header makes it a non simple request. // Adding a custom header makes it a non simple request.
var requestBuilder = server request.Headers.Add(CorsConstants.Origin, "http://example2.com");
.CreateRequest("http://localhost/CorsMiddleware/GetExclusiveContent")
.AddHeader(CorsConstants.Origin, "http://example2.com");
// Act // Act
var response = await requestBuilder.SendAsync("PUT"); var response = await Client.SendAsync(request);
// Assert // Assert
// Middleware applied the policy and since that did not pass, there were no access control headers. // Middleware applied the policy and since that did not pass, there were no access control headers.

View File

@ -1,22 +1,23 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Cors.Core; using Microsoft.AspNet.Cors.Core;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class CorsTests public class CorsTests : IClassFixture<MvcTestFixture<CorsWebSite.Startup>>
{ {
private const string SiteName = nameof(CorsWebSite); public CorsTests(MvcTestFixture<CorsWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new CorsWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new CorsWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("GET")] [InlineData("GET")]
@ -25,16 +26,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ResourceWithSimpleRequestPolicy_Allows_SimpleRequests(string method) public async Task ResourceWithSimpleRequestPolicy_Allows_SimpleRequests(string method)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var origin = "http://example.com"; var origin = "http://example.com";
var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Cors/GetBlogComments");
var requestBuilder = server request.Headers.Add(CorsConstants.Origin, origin);
.CreateRequest("http://localhost/Cors/GetBlogComments")
.AddHeader(CorsConstants.Origin, origin);
// Act // Act
var response = await requestBuilder.SendAsync(method); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -54,18 +51,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task PolicyFailed_Disallows_PreFlightRequest(string method) public async Task PolicyFailed_Disallows_PreFlightRequest(string method)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var request = new HttpRequestMessage(
var client = server.CreateClient(); new HttpMethod(CorsConstants.PreflightHttpMethod),
"http://localhost/Cors/GetBlogComments");
// Adding a custom header makes it a non simple request. // Adding a custom header makes it a non-simple request.
var requestBuilder = server request.Headers.Add(CorsConstants.Origin, "http://example.com");
.CreateRequest("http://localhost/Cors/GetBlogComments") request.Headers.Add(CorsConstants.AccessControlRequestMethod, method);
.AddHeader(CorsConstants.Origin, "http://example.com") request.Headers.Add(CorsConstants.AccessControlRequestHeaders, "Custom");
.AddHeader(CorsConstants.AccessControlRequestMethod, method)
.AddHeader(CorsConstants.AccessControlRequestHeaders, "Custom");
// Act // Act
var response = await requestBuilder.SendAsync(CorsConstants.PreflightHttpMethod); var response = await Client.SendAsync(request);
// Assert // Assert
// MVC applied the policy and since that did not pass, there were no access control headers. // 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() public async Task SuccessfulCorsRequest_AllowsCredentials_IfThePolicyAllowsCredentials()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var request = new HttpRequestMessage(
var client = server.CreateClient(); HttpMethod.Put,
"http://localhost/Cors/EditUserComment?userComment=abcd");
// Adding a custom header makes it a non simple request. // Adding a custom header makes it a non-simple request.
var requestBuilder = server request.Headers.Add(CorsConstants.Origin, "http://example.com");
.CreateRequest("http://localhost/Cors/EditUserComment?userComment=abcd") request.Headers.Add(CorsConstants.AccessControlExposeHeaders, "exposed1,exposed2");
.AddHeader(CorsConstants.Origin, "http://example.com")
.AddHeader(CorsConstants.AccessControlExposeHeaders, "exposed1,exposed2");
// Act // Act
var response = await requestBuilder.SendAsync("PUT"); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -114,18 +109,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task SuccessfulPreflightRequest_AllowsCredentials_IfThePolicyAllowsCredentials() public async Task SuccessfulPreflightRequest_AllowsCredentials_IfThePolicyAllowsCredentials()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var request = new HttpRequestMessage(
var client = server.CreateClient(); new HttpMethod(CorsConstants.PreflightHttpMethod),
"http://localhost/Cors/EditUserComment?userComment=abcd");
// Adding a custom header makes it a non simple request. // Adding a custom header makes it a non-simple request.
var requestBuilder = server request.Headers.Add(CorsConstants.Origin, "http://example.com");
.CreateRequest("http://localhost/Cors/EditUserComment?userComment=abcd") request.Headers.Add(CorsConstants.AccessControlRequestMethod, "PUT");
.AddHeader(CorsConstants.Origin, "http://example.com") request.Headers.Add(CorsConstants.AccessControlRequestHeaders, "header1,header2");
.AddHeader(CorsConstants.AccessControlRequestMethod, "PUT")
.AddHeader(CorsConstants.AccessControlRequestHeaders, "header1,header2");
// Act // Act
var response = await requestBuilder.SendAsync(CorsConstants.PreflightHttpMethod); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -151,16 +145,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task PolicyFailed_Allows_ActualRequest_WithMissingResponseHeaders() public async Task PolicyFailed_Allows_ActualRequest_WithMissingResponseHeaders()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var request = new HttpRequestMessage(HttpMethod.Put, "http://localhost/Cors/GetUserComments");
var client = server.CreateClient();
// Adding a custom header makes it a non simple request. // Adding a custom header makes it a non simple request.
var requestBuilder = server request.Headers.Add(CorsConstants.Origin, "http://example2.com");
.CreateRequest("http://localhost/Cors/GetUserComments")
.AddHeader(CorsConstants.Origin, "http://example2.com");
// Act // Act
var response = await requestBuilder.SendAsync("PUT"); var response = await Client.SendAsync(request);
// Assert // Assert
// MVC applied the policy and since that did not pass, there were no access control headers. // 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) public async Task DisableCors_ActionsCanOverride_ControllerLevel(string method)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Cors/GetExclusiveContent");
var client = server.CreateClient();
// Exclusive content is not available on other sites. // Exclusive content is not available on other sites.
var requestBuilder = server request.Headers.Add(CorsConstants.Origin, "http://example.com");
.CreateRequest("http://localhost/Cors/GetExclusiveContent")
.AddHeader(CorsConstants.Origin, "http://example.com");
// Act // Act
var response = await requestBuilder.SendAsync(method); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -206,18 +194,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task DisableCors_PreFlight_ActionsCanOverride_ControllerLevel(string method) public async Task DisableCors_PreFlight_ActionsCanOverride_ControllerLevel(string method)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var request = new HttpRequestMessage(
var client = server.CreateClient(); new HttpMethod(CorsConstants.PreflightHttpMethod),
"http://localhost/Cors/GetExclusiveContent");
// Exclusive content is not available on other sites. // Exclusive content is not available on other sites.
var requestBuilder = server request.Headers.Add(CorsConstants.Origin, "http://example.com");
.CreateRequest("http://localhost/Cors/GetExclusiveContent") request.Headers.Add(CorsConstants.AccessControlRequestMethod, method);
.AddHeader(CorsConstants.Origin, "http://example.com") request.Headers.Add(CorsConstants.AccessControlRequestHeaders, "Custom");
.AddHeader(CorsConstants.AccessControlRequestMethod, method)
.AddHeader(CorsConstants.AccessControlRequestHeaders, "Custom");
// Act // Act
var response = await requestBuilder.SendAsync(CorsConstants.PreflightHttpMethod); var response = await Client.SendAsync(request);
// Assert // Assert
// Since there are no response headers, the client should step in to block the content. // Since there are no response headers, the client should step in to block the content.

View File

@ -1,22 +1,21 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class CustomRouteTest public class CustomRouteTest : IClassFixture<MvcTestFixture<CustomRouteWebSite.Startup>>
{ {
private const string SiteName = nameof(CustomRouteWebSite); public CustomRouteTest(MvcTestFixture<CustomRouteWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new CustomRouteWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new CustomRouteWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("Javier", "Hola from Spain.")] [InlineData("Javier", "Hola from Spain.")]
@ -25,14 +24,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task RouteToLocale_ConventionalRoute_BasedOnUser(string user, string expected) public async Task RouteToLocale_ConventionalRoute_BasedOnUser(string user, string expected)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/CustomRoute_Products/Index"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/CustomRoute_Products/Index");
request.Headers.Add("User", user); request.Headers.Add("User", user);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); 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) public async Task RouteWithAttributeRoute_IncludesLocale_BasedOnUser(string user, string expected)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/CustomRoute_Orders/5"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/CustomRoute_Orders/5");
request.Headers.Add("User", user); request.Headers.Add("User", user);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -1,11 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
@ -17,23 +15,22 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
/// 1. Based on configuration, generate Content urls pointing to local or a CDN server /// 1. Based on configuration, generate Content urls pointing to local or a CDN server
/// 2. Based on configuration, generate lower case urls /// 2. Based on configuration, generate lower case urls
/// </summary> /// </summary>
public class CustomUrlHelperTests public class CustomUrlHelperTests : IClassFixture<MvcTestFixture<UrlHelperWebSite.Startup>>
{ {
private const string SiteName = nameof(UrlHelperWebSite);
private readonly Action<IApplicationBuilder> _app = new UrlHelperWebSite.Startup().Configure;
private readonly Action<IServiceCollection> _configureServices = new UrlHelperWebSite.Startup().ConfigureServices;
private const string _cdnServerBaseUrl = "http://cdn.contoso.com"; private const string _cdnServerBaseUrl = "http://cdn.contoso.com";
public CustomUrlHelperTests(MvcTestFixture<UrlHelperWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task CustomUrlHelper_GeneratesUrlFromController() public async Task CustomUrlHelper_GeneratesUrlFromController()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/UrlContent");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/UrlContent");
var responseData = await response.Content.ReadAsStringAsync(); var responseData = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -44,12 +41,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task CustomUrlHelper_GeneratesUrlFromView() public async Task CustomUrlHelper_GeneratesUrlFromView()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/Index");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/Index");
var responseData = await response.Content.ReadAsStringAsync(); var responseData = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -62,12 +55,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("http://localhost/Home/LinkByUrlAction", "/home/urlcontent")] [InlineData("http://localhost/Home/LinkByUrlAction", "/home/urlcontent")]
public async Task LowercaseUrls_LinkGeneration(string url, string expectedLink) public async Task LowercaseUrls_LinkGeneration(string url, string expectedLink)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(url);
var client = server.CreateClient();
// Act
var response = await client.GetAsync(url);
var responseData = await response.Content.ReadAsStringAsync(); var responseData = await response.Content.ReadAsStringAsync();
// Assert // Assert

View File

@ -3,23 +3,25 @@
using System; using System;
using System.Net; using System.Net;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.ActionConstraints; using Microsoft.AspNet.Mvc.ActionConstraints;
using Microsoft.AspNet.Mvc.Actions; using Microsoft.AspNet.Mvc.Actions;
using Microsoft.AspNet.Mvc.ApiExplorer; using Microsoft.AspNet.Mvc.ApiExplorer;
using Microsoft.AspNet.Mvc.Filters; using Microsoft.AspNet.Mvc.Filters;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Tests that various MVC services have the correct order. // Tests that various MVC services have the correct order.
public class DefaultOrderTest public class DefaultOrderTest : IClassFixture<MvcTestFixture<BasicWebSite.Startup>>
{ {
private const string SiteName = nameof(BasicWebSite); public DefaultOrderTest(MvcTestFixture<BasicWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new BasicWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new BasicWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData(typeof(IActionDescriptorProvider), typeof(ControllerActionDescriptorProvider), -1000)] [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) public async Task ServiceOrder_GetOrder(Type serviceType, Type actualType, int order)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/Order/GetServiceOrder?serviceType=" + serviceType.AssemblyQualifiedName; var url = "http://localhost/Order/GetServiceOrder?serviceType=" + serviceType.AssemblyQualifiedName;
if (actualType != null) if (actualType != null)
@ -41,7 +40,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
} }
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert

View File

@ -1,33 +1,30 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class DefaultValuesTest public class DefaultValuesTest : IClassFixture<MvcTestFixture<BasicWebSite.Startup>>
{ {
private const string SiteName = nameof(BasicWebSite); public DefaultValuesTest(MvcTestFixture<BasicWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new BasicWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new BasicWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task Controller_WithDefaultValueAttribut_ReturnsDefault() public async Task Controller_WithDefaultValueAttribut_ReturnsDefault()
{ {
// Arrange // Arrange
var expected = "hello"; var expected = "hello";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/DefaultValues/EchoValue_DefaultValueAttribute"; var url = "http://localhost/DefaultValues/EchoValue_DefaultValueAttribute";
// Act // Act
var response = await client.GetStringAsync(url); var response = await Client.GetStringAsync(url);
// Assert // Assert
Assert.Equal(expected, response); Assert.Equal(expected, response);
@ -38,14 +35,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = "cool"; var expected = "cool";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/DefaultValues/EchoValue_DefaultValueAttribute?input=cool"; var url = "http://localhost/DefaultValues/EchoValue_DefaultValueAttribute?input=cool";
// Act // Act
var response = await client.GetStringAsync(url); var response = await Client.GetStringAsync(url);
// Assert // Assert
Assert.Equal(expected, response); Assert.Equal(expected, response);
@ -56,14 +49,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = "world"; var expected = "world";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/DefaultValues/EchoValue_DefaultParameterValue"; var url = "http://localhost/DefaultValues/EchoValue_DefaultParameterValue";
// Act // Act
var response = await client.GetStringAsync(url); var response = await Client.GetStringAsync(url);
// Assert // Assert
Assert.Equal(expected, response); Assert.Equal(expected, response);
@ -74,14 +63,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = "cool"; var expected = "cool";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/DefaultValues/EchoValue_DefaultParameterValue?input=cool"; var url = "http://localhost/DefaultValues/EchoValue_DefaultParameterValue?input=cool";
// Act // Act
var response = await client.GetStringAsync(url); var response = await Client.GetStringAsync(url);
// Assert // Assert
Assert.Equal(expected, response); Assert.Equal(expected, response);

View File

@ -1,20 +1,20 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using AutofacWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class DependencyResolverTests public class DependencyResolverTests : IClassFixture<MvcTestFixture<AutofacWebSite.Startup>>
{ {
private const string SiteName = nameof(AutofacWebSite); public DependencyResolverTests(MvcTestFixture<AutofacWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Func<IServiceCollection, IServiceProvider> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("http://localhost/di", "<p>Builder Output: Hello from builder.</p>")] [InlineData("http://localhost/di", "<p>Builder Output: Hello from builder.</p>")]
@ -22,14 +22,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task AutofacDIContainerCanUseMvc(string url, string expectedResponseBody) public async Task AutofacDIContainerCanUseMvc(string url, string expectedResponseBody)
{ {
// Arrange & Act & Assert (does not throw) // 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 // 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, responseText);
Assert.Equal(expectedResponseBody, actualResponseBody);
} }
} }
} }

View File

@ -1,30 +1,30 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using RazorWebSite;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class DirectivesTest public class DirectivesTest : IClassFixture<MvcTestFixture<RazorWebSite.Startup>>
{ {
private const string SiteName = nameof(RazorWebSite); public DirectivesTest(MvcTestFixture<RazorWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task ViewsInheritsUsingsAndInjectDirectivesFromViewStarts() public async Task ViewsInheritsUsingsAndInjectDirectivesFromViewStarts()
{ {
// Arrange
var expected = @"Hello Person1"; var expected = @"Hello Person1";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/Directives/ViewInheritsInjectAndUsingsFromViewImports"); var body = await Client.GetStringAsync(
"http://localhost/Directives/ViewInheritsInjectAndUsingsFromViewImports");
// Assert // Assert
Assert.Equal(expected, body.Trim()); Assert.Equal(expected, body.Trim());
@ -33,12 +33,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ViewInheritsBasePageFromViewStarts() public async Task ViewInheritsBasePageFromViewStarts()
{ {
// Arrange
var expected = @"WriteLiteral says:layout:Write says:Write says:Hello Person2"; var expected = @"WriteLiteral says:layout:Write says:Write says:Hello Person2";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/Directives/ViewInheritsBasePageFromViewImports"); var body = await Client.GetStringAsync("http://localhost/Directives/ViewInheritsBasePageFromViewImports");
// Assert // Assert
Assert.Equal(expected, body.Trim()); Assert.Equal(expected, body.Trim());

View File

@ -1,14 +1,10 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Net; using System.Net;
using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Threading.Tasks; using System.Threading.Tasks;
using ErrorPageMiddlewareWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
@ -16,11 +12,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
/// <summary> /// <summary>
/// Functional test to verify the error reporting of Razor compilation by diagnostic middleware. /// Functional test to verify the error reporting of Razor compilation by diagnostic middleware.
/// </summary> /// </summary>
public class ErrorPageTests public class ErrorPageTests : IClassFixture<MvcTestFixture<ErrorPageMiddlewareWebSite.Startup>>
{ {
private const string SiteName = nameof(ErrorPageMiddlewareWebSite); public ErrorPageTests(MvcTestFixture<ErrorPageMiddlewareWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("CompilationFailure", "Cannot implicitly convert type &#x27;int&#x27; to &#x27;string&#x27;")] [InlineData("CompilationFailure", "Cannot implicitly convert type &#x27;int&#x27; to &#x27;string&#x27;")]
@ -31,12 +30,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CompilationFailuresAreListedByErrorPageMiddleware(string action, string expected) public async Task CompilationFailuresAreListedByErrorPageMiddleware(string action, string expected)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
// Act // Act
var response = await client.GetAsync("http://localhost/" + action); var response = await Client.GetAsync("http://localhost/" + action);
// Assert // Assert
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
@ -52,12 +49,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Arrange // Arrange
var expectedMessage = "The type or namespace name &#x27;NamespaceDoesNotExist&#x27; could not be found (" var expectedMessage = "The type or namespace name &#x27;NamespaceDoesNotExist&#x27; could not be found ("
+ "are you missing a using directive or an assembly reference?)"; + "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"); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
// Act // Act
var response = await client.GetAsync("http://localhost/ErrorFromViewImports"); var response = await Client.GetAsync("http://localhost/ErrorFromViewImports");
// Assert // Assert
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);

View File

@ -1,33 +1,30 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class FileResultTests public class FileResultTests : IClassFixture<MvcTestFixture<FilesWebSite.Startup>>
{ {
private const string SiteName = nameof(FilesWebSite); public FileResultTests(MvcTestFixture<FilesWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new FilesWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new FilesWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[ConditionalFact] [ConditionalFact]
// https://github.com/aspnet/Mvc/issues/2727 // https://github.com/aspnet/Mvc/issues/2727
[FrameworkSkipCondition(RuntimeFrameworks.Mono)] [FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task FileFromDisk_CanBeEnabled_WithMiddleware() public async Task FileFromDisk_CanBeEnabled_WithMiddleware()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/DownloadFiles/DowloadFromDisk");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/DownloadFiles/DowloadFromDisk");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -45,12 +42,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[FrameworkSkipCondition(RuntimeFrameworks.Mono)] [FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task FileFromDisk_ReturnsFileWithFileName() public async Task FileFromDisk_ReturnsFileWithFileName()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/DownloadFiles/DowloadFromDiskWithFileName");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/DownloadFiles/DowloadFromDiskWithFileName");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -70,12 +63,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FileFromStream_ReturnsFile() public async Task FileFromStream_ReturnsFile()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/DownloadFiles/DowloadFromStream");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/DownloadFiles/DowloadFromStream");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -91,12 +80,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FileFromStream_ReturnsFileWithFileName() public async Task FileFromStream_ReturnsFileWithFileName()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/DownloadFiles/DowloadFromStreamWithFileName");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/DownloadFiles/DowloadFromStreamWithFileName");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -116,12 +101,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FileFromBinaryData_ReturnsFile() public async Task FileFromBinaryData_ReturnsFile()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/DownloadFiles/DowloadFromBinaryData");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/DownloadFiles/DowloadFromBinaryData");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -137,12 +118,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FileFromBinaryData_ReturnsFileWithFileName() public async Task FileFromBinaryData_ReturnsFileWithFileName()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/DownloadFiles/DowloadFromBinaryDataWithFileName");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/DownloadFiles/DowloadFromBinaryDataWithFileName");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -163,12 +140,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FileFromEmbeddedResources_ReturnsFileWithFileName() public async Task FileFromEmbeddedResources_ReturnsFileWithFileName()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedBody = "Sample text file as embedded resource."; var expectedBody = "Sample text file as embedded resource.";
// Act // Act
var response = await client.GetAsync("http://localhost/EmbeddedFiles/DownloadFileWithFileName"); var response = await Client.GetAsync("http://localhost/EmbeddedFiles/DownloadFileWithFileName");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -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<TStartup> : MvcTestFixture<TStartup>
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<IAssemblyProvider, FilteredDefaultAssemblyProvider>();
}
private class FilteredDefaultAssemblyProvider : DefaultAssemblyProvider
{
public FilteredDefaultAssemblyProvider(ILibraryManager libraryManager)
: base(libraryManager)
{
}
protected override IEnumerable<Library> 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));
}
}
}
}

View File

@ -7,19 +7,19 @@ using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Mvc.Formatters.Xml;
using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class FiltersTest public class FiltersTest : IClassFixture<MvcTestFixture<FiltersWebSite.Startup>>
{ {
private const string SiteName = nameof(FiltersWebSite); public FiltersTest(MvcTestFixture<FiltersWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new FiltersWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new FiltersWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
// A controller can only be an action filter and result filter, so we don't have entries // 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. // for the other filter types implemented by the controller.
@ -27,9 +27,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ListAllFilters() public async Task ListAllFilters()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = new string[] var expected = new string[]
{ {
"Global Authorization Filter - OnAuthorization", "Global Authorization Filter - OnAuthorization",
@ -61,7 +58,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}; };
// Act // Act
var response = await client.GetAsync("http://localhost/Products/GetPrice/5"); var response = await Client.GetAsync("http://localhost/Products/GetPrice/5");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -82,12 +79,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task AnonymousUsersAreBlocked() public async Task AnonymousUsersAreBlocked()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Anonymous/GetHelloWorld");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Anonymous/GetHelloWorld");
// Assert // Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
@ -96,12 +89,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task AllowsAnonymousUsersToAccessController() public async Task AllowsAnonymousUsersToAccessController()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/RandomNumber/GetRandomNumber");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/RandomNumber/GetRandomNumber");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -115,13 +104,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("ApiManagers")] [InlineData("ApiManagers")]
public async Task CanAuthorize(string testAction) public async Task CanAuthorize(string testAction)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/AuthorizeUser/"+testAction);
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/AuthorizeUser/"+testAction);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -131,13 +115,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task AllowAnonymousOverridesAuthorize() public async Task AllowAnonymousOverridesAuthorize()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/AuthorizeUser/AlwaysCanCallAllowAnonymous");
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/AuthorizeUser/AlwaysCanCallAllowAnonymous");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -147,13 +126,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ImpossiblePolicyFailsAuthorize() public async Task ImpossiblePolicyFailsAuthorize()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/AuthorizeUser/Impossible");
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/AuthorizeUser/Impossible");
// Assert // Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
@ -162,12 +136,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ServiceFilterUsesRegisteredServicesAsFilter() public async Task ServiceFilterUsesRegisteredServicesAsFilter()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/RandomNumber/GetRandomNumber");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/RandomNumber/GetRandomNumber");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -178,12 +148,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ServiceFilterThrowsIfServiceIsNotRegistered() public async Task ServiceFilterThrowsIfServiceIsNotRegistered()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/RandomNumber/GetAuthorizedRandomNumber"; var url = "http://localhost/RandomNumber/GetAuthorizedRandomNumber";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var exception = response.GetServerException(); var exception = response.GetServerException();
@ -194,12 +162,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task TypeFilterInitializesArguments() public async Task TypeFilterInitializesArguments()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/RandomNumber/GetModifiedRandomNumber?randomNumber=10"; var url = "http://localhost/RandomNumber/GetModifiedRandomNumber?randomNumber=10";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -210,12 +176,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task TypeFilterThrowsIfServicesAreNotRegistered() public async Task TypeFilterThrowsIfServicesAreNotRegistered()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/RandomNumber/GetHalfOfModifiedRandomNumber?randomNumber=3"; var url = "http://localhost/RandomNumber/GetHalfOfModifiedRandomNumber?randomNumber=3";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var exception = response.GetServerException(); var exception = response.GetServerException();
@ -225,12 +189,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ActionFilterOverridesActionExecuted() public async Task ActionFilterOverridesActionExecuted()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/XmlSerializer/GetDummyClass?sampleInput=10");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/XmlSerializer/GetDummyClass?sampleInput=10");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -242,12 +202,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResultFilterOverridesOnResultExecuting() public async Task ResultFilterOverridesOnResultExecuting()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/DummyClass/GetDummyClass");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/DummyClass/GetDummyClass");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -259,12 +215,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResultFilterOverridesOnResultExecuted() public async Task ResultFilterOverridesOnResultExecuted()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/DummyClass/GetEmptyActionResult");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/DummyClass/GetEmptyActionResult");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -276,12 +228,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task OrderOfExecutionOfFilters_WhenOrderAttribute_IsNotMentioned() public async Task OrderOfExecutionOfFilters_WhenOrderAttribute_IsNotMentioned()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/GetSampleString");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/GetSampleString");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -294,12 +242,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ExceptionsHandledInActionFilters_WillNotShortCircuitResultFilters() public async Task ExceptionsHandledInActionFilters_WillNotShortCircuitResultFilters()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/ThrowExceptionAndHandleInActionFilter");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/ThrowExceptionAndHandleInActionFilter");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -311,12 +255,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ExceptionFilter_OnAction_ShortCircuitsResultFilters() public async Task ExceptionFilter_OnAction_ShortCircuitsResultFilters()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/ThrowExcpetion");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/ThrowExcpetion");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -330,12 +270,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GlobalExceptionFilter_HandlesAnException() public async Task GlobalExceptionFilter_HandlesAnException()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Exception/GetError?error=RandomError");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Exception/GetError?error=RandomError");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -347,12 +283,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ExceptionFilter_Scope() public async Task ExceptionFilter_Scope()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ExceptionOrder/GetError");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ExceptionOrder/GetError");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -368,12 +300,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ActionFilter_Scope() public async Task ActionFilter_Scope()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ActionFilter/GetHelloWorld");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ActionFilter/GetHelloWorld");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -395,12 +323,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResultFilter_Scope() public async Task ResultFilter_Scope()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ResultFilter/GetHelloWorld");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ResultFilter/GetHelloWorld");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -418,12 +342,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FiltersWithOrder() public async Task FiltersWithOrder()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/RandomNumber/GetOrderedRandomNumber");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/RandomNumber/GetOrderedRandomNumber");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -435,12 +355,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ActionFiltersWithOrder() public async Task ActionFiltersWithOrder()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/ActionFilterOrder");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/ActionFilterOrder");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -456,12 +372,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResultFiltersWithOrder() public async Task ResultFiltersWithOrder()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/ResultFilterOrder");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/ResultFilterOrder");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -475,12 +387,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ActionFilterShortCircuitsAction() public async Task ActionFilterShortCircuitsAction()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/DummyClass/ActionNeverGetsExecuted");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/DummyClass/ActionNeverGetsExecuted");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -492,12 +400,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResultFilterShortCircuitsResult() public async Task ResultFilterShortCircuitsResult()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/DummyClass/ResultNeverGetsExecuted");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/DummyClass/ResultNeverGetsExecuted");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -509,12 +413,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ExceptionFilterShortCircuitsAnotherExceptionFilter() public async Task ExceptionFilterShortCircuitsAnotherExceptionFilter()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/ThrowRandomExcpetion");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/ThrowRandomExcpetion");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -526,12 +426,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ThrowingFilters_ResultFilter_NotHandledByGlobalExceptionFilter() public async Task ThrowingFilters_ResultFilter_NotHandledByGlobalExceptionFilter()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/ThrowingResultFilter");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/ThrowingResultFilter");
// Assert // Assert
var exception = response.GetServerException(); var exception = response.GetServerException();
@ -543,12 +439,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ThrowingFilters_ActionFilter_HandledByGlobalExceptionFilter() public async Task ThrowingFilters_ActionFilter_HandledByGlobalExceptionFilter()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/ThrowingActionFilter");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/ThrowingActionFilter");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -560,12 +452,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ThrowingFilters_AuthFilter_NotHandledByGlobalExceptionFilter() public async Task ThrowingFilters_AuthFilter_NotHandledByGlobalExceptionFilter()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/ThrowingAuthorizationFilter");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/ThrowingAuthorizationFilter");
// Assert // Assert
var exception = response.GetServerException(); var exception = response.GetServerException();
@ -577,12 +465,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ThrowingExceptionFilter_ExceptionFilter_NotHandledByGlobalExceptionFilter() public async Task ThrowingExceptionFilter_ExceptionFilter_NotHandledByGlobalExceptionFilter()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Home/ThrowingExceptionFilter");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/ThrowingExceptionFilter");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -594,15 +478,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var input = "{ sampleInt: 10 }"; 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"); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/ResourceFilter/Post");
request.Content = new StringContent(input, Encoding.UTF8, "application/json"); request.Content = new StringContent(input, Encoding.UTF8, "application/json");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
// Uses formatters from options. // Uses formatters from options.
@ -617,15 +497,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var input = "{ sampleInt: 10 }"; 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"); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/ResourceFilter/Get");
request.Content = new StringContent(input, Encoding.UTF8, "application/json"); request.Content = new StringContent(input, Encoding.UTF8, "application/json");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -638,15 +514,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var input = "{ sampleInt: 10 }"; var input = "{ sampleInt: 10 }";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Json"); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Json");
request.Content = new StringContent(input, Encoding.UTF8, "application/json"); request.Content = new StringContent(input, Encoding.UTF8, "application/json");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -659,15 +531,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var input = "{ sampleInt: 10 }"; var input = "{ sampleInt: 10 }";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Json"); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Json");
request.Content = new StringContent(input, Encoding.UTF8, "application/json"); request.Content = new StringContent(input, Encoding.UTF8, "application/json");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -683,16 +551,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
"<SampleInt>10</SampleInt>" + "<SampleInt>10</SampleInt>" +
"</DummyClass>"; "</DummyClass>";
// There's nothing that can deserialize the body, so the result contains the default // There's nothing that can deserialize the body, so the result contains the default value.
// value.
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Json"); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Json");
request.Content = new StringContent(input, Encoding.UTF8, "application/xml"); request.Content = new StringContent(input, Encoding.UTF8, "application/xml");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -1,30 +1,27 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class FormatFilterTest public class FormatFilterTest : IClassFixture<MvcTestFixture<FormatFilterWebSite.Startup>>
{ {
private const string SiteName = nameof(FormatFilterWebSite); public FormatFilterTest(MvcTestFixture<FormatFilterWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new FormatFilterWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new FormatFilterWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task FormatFilter_NoExtensionInRequest() public async Task FormatFilter_NoExtensionInRequest()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/FormatFilter/GetProduct/5");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/FormatFilter/GetProduct/5");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -34,12 +31,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FormatFilter_ExtensionInRequest_Default() public async Task FormatFilter_ExtensionInRequest_Default()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/FormatFilter/GetProduct/5.json");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/FormatFilter/GetProduct/5.json");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -49,12 +42,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FormatFilter_ExtensionInRequest_Optional() public async Task FormatFilter_ExtensionInRequest_Optional()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/FormatFilter/GetProduct.json");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/FormatFilter/GetProduct.json");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -64,12 +53,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FormatFilter_ExtensionInRequest_Custom() public async Task FormatFilter_ExtensionInRequest_Custom()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/FormatFilter/GetProduct/5.custom");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/FormatFilter/GetProduct/5.custom");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -79,12 +64,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FormatFilter_ExtensionInRequest_CaseInsensitivity() public async Task FormatFilter_ExtensionInRequest_CaseInsensitivity()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/FormatFilter/GetProduct/5.Custom");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/FormatFilter/GetProduct/5.Custom");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -94,12 +75,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FormatFilter_ExtensionInRequest_NonExistant() public async Task FormatFilter_ExtensionInRequest_NonExistant()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/FormatFilter/GetProduct/5.xml");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/FormatFilter/GetProduct/5.xml");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -108,12 +85,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FormatFilter_And_ProducesFilter_Match() public async Task FormatFilter_And_ProducesFilter_Match()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/FormatFilter/ProducesMethod/5.json");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/FormatFilter/ProducesMethod/5.json");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -123,12 +96,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FormatFilter_And_ProducesFilter_Conflict() public async Task FormatFilter_And_ProducesFilter_Conflict()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/FormatFilter/ProducesMethod/5.xml");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/FormatFilter/ProducesMethod/5.xml");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -137,12 +106,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FormatFilter_And_OverrideProducesFilter() public async Task FormatFilter_And_OverrideProducesFilter()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ProducesOverride/ReturnClassName");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ProducesOverride/ReturnClassName");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -9,25 +9,37 @@ using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using HtmlGenerationWebSite;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Internal; using Microsoft.AspNet.Mvc.Internal;
using Microsoft.AspNet.Mvc.TagHelpers; using Microsoft.AspNet.Mvc.TagHelpers;
using Microsoft.AspNet.Testing;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Extensions; using Microsoft.Framework.DependencyInjection.Extensions;
using Microsoft.Framework.WebEncoders;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class HtmlGenerationTest public class HtmlGenerationTest :
IClassFixture<MvcTestFixture<HtmlGenerationWebSite.Startup>>,
IClassFixture<MvcEncodedTestFixture<HtmlGenerationWebSite.Startup>>
{ {
private const string SiteName = nameof(HtmlGenerationWebSite); private const string SiteName = nameof(HtmlGenerationWebSite);
private static readonly Assembly _resourcesAssembly = typeof(HtmlGenerationTest).GetTypeInfo().Assembly; private static readonly Assembly _resourcesAssembly = typeof(HtmlGenerationTest).GetTypeInfo().Assembly;
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; private readonly Action<IApplicationBuilder> _app = new HtmlGenerationWebSite.Startup().Configure;
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; private readonly Action<IServiceCollection> _configureServices =
new HtmlGenerationWebSite.Startup().ConfigureServices;
public HtmlGenerationTest(
MvcTestFixture<HtmlGenerationWebSite.Startup> fixture,
MvcEncodedTestFixture<HtmlGenerationWebSite.Startup> encodedFixture)
{
Client = fixture.Client;
EncodedClient = encodedFixture.Client;
}
public HttpClient Client { get; }
public HttpClient EncodedClient { get; }
[Theory] [Theory]
[InlineData("Index", null)] [InlineData("Index", null)]
@ -60,8 +72,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task HtmlGenerationWebSite_GeneratesExpectedResults(string action, string antiforgeryPath) public async Task HtmlGenerationWebSite_GeneratesExpectedResults(string action, string antiforgeryPath)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".html"; var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".html";
var expectedContent = var expectedContent =
@ -69,7 +79,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act // Act
// The host is not important as everything runs in memory and tests are isolated from each other. // 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(); var responseContent = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -119,14 +129,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task HtmlGenerationWebSite_GenerateEncodedResults(string action, string antiforgeryPath) public async Task HtmlGenerationWebSite_GenerateEncodedResults(string action, string antiforgeryPath)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, services =>
{
_configureServices(services);
services.AddTransient<IHtmlEncoder, TestHtmlEncoder>();
services.AddTransient<IJavaScriptStringEncoder, TestJavaScriptEncoder>();
services.AddTransient<IUrlEncoder, TestUrlEncoder>();
});
var client = server.CreateClient();
var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".Encoded.html"; var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".Encoded.html";
var expectedContent = var expectedContent =
@ -134,7 +136,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act // Act
// The host is not important as everything runs in memory and tests are isolated from each other. // 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(); var responseContent = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -176,8 +178,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ValidationTagHelpers_GeneratesExpectedSpansAndDivs() public async Task ValidationTagHelpers_GeneratesExpectedSpansAndDivs()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Customer.Index.html"; var outputFile = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Customer.Index.html";
var expectedContent = var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
@ -194,7 +194,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync(); var responseContent = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -224,10 +224,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Arrange // Arrange
var assertFile = var assertFile =
"compiler/resources/CacheTagHelper_CanCachePortionsOfViewsPartialViewsAndViewComponents.Assert"; "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 outputFile1 = assertFile + "1.txt";
var expected1 = var expected1 =
@ -242,8 +238,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act - 1 // Act - 1
// Verify that content gets cached based on vary-by-params // Verify that content gets cached based on vary-by-params
var targetUrl = "/catalog?categoryId=1&correlationid=1"; var targetUrl = "/catalog?categoryId=1&correlationid=1";
var response1 = await client.GetStringAsync(targetUrl); var request = RequestWithLocale(targetUrl, "North");
var response2 = await client.GetStringAsync(targetUrl); var response1 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
request = RequestWithLocale(targetUrl, "North");
var response2 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
// Assert - 1 // Assert - 1
#if GENERATE_BASELINES #if GENERATE_BASELINES
@ -256,8 +254,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act - 2 // Act - 2
// Verify content gets changed in partials when one of the vary by parameters is changed // Verify content gets changed in partials when one of the vary by parameters is changed
targetUrl = "/catalog?categoryId=3&correlationid=2"; targetUrl = "/catalog?categoryId=3&correlationid=2";
var response3 = await client.GetStringAsync(targetUrl); request = RequestWithLocale(targetUrl, "North");
var response4 = await client.GetStringAsync(targetUrl); var response3 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
request = RequestWithLocale(targetUrl, "North");
var response4 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
// Assert - 2 // Assert - 2
#if GENERATE_BASELINES #if GENERATE_BASELINES
@ -269,12 +269,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act - 3 // Act - 3
// Verify content gets changed in a View Component when the Vary-by-header parameters is changed // 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"; targetUrl = "/catalog?categoryId=3&correlationid=3";
var response5 = await client.GetStringAsync(targetUrl); request = RequestWithLocale(targetUrl, "East");
var response6 = await client.GetStringAsync(targetUrl); var response5 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
request = RequestWithLocale(targetUrl, "East");
var response6 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
// Assert - 3 // Assert - 3
#if GENERATE_BASELINES #if GENERATE_BASELINES
@ -288,13 +287,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task CacheTagHelper_ExpiresContent_BasedOnExpiresParameter() public async Task CacheTagHelper_ExpiresContent_BasedOnExpiresParameter()
{ {
// Arrange // Arrange & Act - 1
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response1 = await Client.GetStringAsync("/catalog/2");
var client = server.CreateClient();
client.BaseAddress = new Uri("http://localhost");
// Act - 1
var response1 = await client.GetStringAsync("/catalog/2");
// Assert - 1 // Assert - 1
var expected1 = "Cached content for 2"; var expected1 = "Cached content for 2";
@ -302,7 +296,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act - 2 // Act - 2
await Task.Delay(TimeSpan.FromSeconds(1)); await Task.Delay(TimeSpan.FromSeconds(1));
var response2 = await client.GetStringAsync("/catalog/3"); var response2 = await Client.GetStringAsync("/catalog/3");
// Assert - 2 // Assert - 2
var expected2 = "Cached content for 3"; var expected2 = "Cached content for 3";
@ -312,21 +306,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task CacheTagHelper_UsesVaryByCookie_ToVaryContent() public async Task CacheTagHelper_UsesVaryByCookie_ToVaryContent()
{ {
// Arrange // Arrange & Act - 1
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response1 = await Client.GetStringAsync("/catalog/cart?correlationid=1");
var client = server.CreateClient();
client.BaseAddress = new Uri("http://localhost");
// Act - 1
var response1 = await client.GetStringAsync("/catalog/cart?correlationid=1");
// Assert - 1 // Assert - 1
var expected1 = "Cart content for 1"; var expected1 = "Cart content for 1";
Assert.Equal(expected1, response1.Trim()); Assert.Equal(expected1, response1.Trim());
// Act - 2 // Act - 2
client.DefaultRequestHeaders.Add("Cookie", "CartId=10"); var request = new HttpRequestMessage(HttpMethod.Get, "/catalog/cart?correlationid=2");
var response2 = await client.GetStringAsync("/catalog/cart?correlationid=2"); request.Headers.Add("Cookie", "CartId=10");
var response2 = await (await Client.SendAsync(request)).Content.ReadAsStringAsync();
// Assert - 2 // Assert - 2
var expected2 = "Cart content for 2"; var expected2 = "Cart content for 2";
@ -334,8 +324,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act - 3 // Act - 3
// Resend the cookiesless request and cached result from the first response. // 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 - 3
Assert.Equal(expected1, response3.Trim()); Assert.Equal(expected1, response3.Trim());
@ -344,13 +333,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task CacheTagHelper_VariesByRoute() public async Task CacheTagHelper_VariesByRoute()
{ {
// Arrange // Arrange & Act - 1
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response1 = await Client.GetStringAsync(
var client = server.CreateClient();
client.BaseAddress = new Uri("http://localhost");
// Act - 1
var response1 = await client.GetStringAsync(
"/catalog/north-west/confirm-payment?confirmationId=1"); "/catalog/north-west/confirm-payment?confirmationId=1");
// Assert - 1 // Assert - 1
@ -358,7 +342,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Assert.Equal(expected1, response1.Trim()); Assert.Equal(expected1, response1.Trim());
// Act - 2 // Act - 2
var response2 = await client.GetStringAsync( var response2 = await Client.GetStringAsync(
"/catalog/south-central/confirm-payment?confirmationId=2"); "/catalog/south-central/confirm-payment?confirmationId=2");
// Assert - 2 // Assert - 2
@ -366,14 +350,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Assert.Equal(expected2, response2.Trim()); Assert.Equal(expected2, response2.Trim());
// Act 3 // Act 3
var response3 = await client.GetStringAsync( var response3 = await Client.GetStringAsync(
"/catalog/north-west/Silver/confirm-payment?confirmationId=4"); "/catalog/north-west/Silver/confirm-payment?confirmationId=4");
var expected3 = "Welcome Silver member. Your confirmation id is 4. (Region north-west)"; var expected3 = "Welcome Silver member. Your confirmation id is 4. (Region north-west)";
Assert.Equal(expected3, response3.Trim()); Assert.Equal(expected3, response3.Trim());
// Act 4 // Act 4
var response4 = await client.GetStringAsync( var response4 = await Client.GetStringAsync(
"/catalog/north-west/Gold/confirm-payment?confirmationId=5"); "/catalog/north-west/Gold/confirm-payment?confirmationId=5");
var expected4 = "Welcome Gold member. Your confirmation id is 5. (Region north-west)"; var expected4 = "Welcome Gold member. Your confirmation id is 5. (Region north-west)";
@ -381,13 +365,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act - 4 // Act - 4
// Resend the responses and expect cached results. // Resend the responses and expect cached results.
response1 = await client.GetStringAsync( response1 = await Client.GetStringAsync(
"/catalog/north-west/confirm-payment?confirmationId=301"); "/catalog/north-west/confirm-payment?confirmationId=301");
response2 = await client.GetStringAsync( response2 = await Client.GetStringAsync(
"/catalog/south-central/confirm-payment?confirmationId=402"); "/catalog/south-central/confirm-payment?confirmationId=402");
response3 = await client.GetStringAsync( response3 = await Client.GetStringAsync(
"/catalog/north-west/Silver/confirm-payment?confirmationId=503"); "/catalog/north-west/Silver/confirm-payment?confirmationId=503");
response4 = await client.GetStringAsync( response4 = await Client.GetStringAsync(
"/catalog/north-west/Gold/confirm-payment?confirmationId=608"); "/catalog/north-west/Gold/confirm-payment?confirmationId=608");
// Assert - 4 // Assert - 4
@ -400,14 +384,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task CacheTagHelper_VariesByUserId() public async Task CacheTagHelper_VariesByUserId()
{ {
// Arrange // Arrange & Act - 1
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response1 = await Client.GetStringAsync("/catalog/past-purchases/test1?correlationid=1");
var client = server.CreateClient(); var response2 = await Client.GetStringAsync("/catalog/past-purchases/test1?correlationid=2");
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");
// Assert - 1 // Assert - 1
var expected1 = "Past purchases for user test1 (1)"; var expected1 = "Past purchases for user test1 (1)";
@ -415,8 +394,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Assert.Equal(expected1, response2.Trim()); Assert.Equal(expected1, response2.Trim());
// Act - 2 // Act - 2
var response3 = await client.GetStringAsync("/catalog/past-purchases/test2?correlationid=3"); var response3 = await Client.GetStringAsync("/catalog/past-purchases/test2?correlationid=3");
var response4 = await client.GetStringAsync("/catalog/past-purchases/test2?correlationid=4"); var response4 = await Client.GetStringAsync("/catalog/past-purchases/test2?correlationid=4");
// Assert - 2 // Assert - 2
var expected2 = "Past purchases for user test2 (3)"; var expected2 = "Past purchases for user test2 (3)";
@ -427,13 +406,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task CacheTagHelper_BubblesExpirationOfNestedTagHelpers() public async Task CacheTagHelper_BubblesExpirationOfNestedTagHelpers()
{ {
// Arrange // Arrange & Act - 1
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response1 = await Client.GetStringAsync("/categories/Books?correlationId=1");
var client = server.CreateClient();
client.BaseAddress = new Uri("http://localhost");
// Act - 1
var response1 = await client.GetStringAsync("/categories/Books?correlationId=1");
// Assert - 1 // Assert - 1
var expected1 = var expected1 =
@ -442,7 +416,7 @@ Products: Book1, Book2 (1)";
Assert.Equal(expected1, response1.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected1, response1.Trim(), ignoreLineEndingDifferences: true);
// Act - 2 // Act - 2
var response2 = await client.GetStringAsync("/categories/Electronics?correlationId=2"); var response2 = await Client.GetStringAsync("/categories/Electronics?correlationId=2");
// Assert - 2 // Assert - 2
var expected2 = var expected2 =
@ -452,10 +426,10 @@ Products: Book1, Book2 (1)";
// Act - 3 // Act - 3
// Trigger an expiration // 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(); response3.EnsureSuccessStatusCode();
var response4 = await client.GetStringAsync("/categories/Electronics?correlationId=3"); var response4 = await Client.GetStringAsync("/categories/Electronics?correlationId=3");
// Assert - 3 // Assert - 3
var expected3 = var expected3 =
@ -467,15 +441,10 @@ Products: Laptops (3)";
[Fact] [Fact]
public async Task CacheTagHelper_DoesNotCacheIfDisabled() public async Task CacheTagHelper_DoesNotCacheIfDisabled()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response1 = await Client.GetStringAsync("/catalog/GetDealPercentage/20?isEnabled=true");
var client = server.CreateClient(); var response2 = await Client.GetStringAsync("/catalog/GetDealPercentage/40?isEnabled=true");
client.BaseAddress = new Uri("http://localhost"); var response3 = await Client.GetStringAsync("/catalog/GetDealPercentage/30?isEnabled=false");
// 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
Assert.Equal("Deal percentage is 20", response1.Trim()); Assert.Equal("Deal percentage is 20", response1.Trim());
@ -538,8 +507,6 @@ Products: Laptops (3)";
public async Task EditorTemplateWithNoModel_RendersWithCorrectMetadata() public async Task EditorTemplateWithNoModel_RendersWithCorrectMetadata()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = PlatformNormalizer.NormalizeContent( var expected = PlatformNormalizer.NormalizeContent(
"<label class=\"control-label col-md-2\" for=\"Name\">ItemName</label>" + Environment.NewLine + "<label class=\"control-label col-md-2\" for=\"Name\">ItemName</label>" + Environment.NewLine +
"<input id=\"Name\" name=\"Name\" type=\"text\" value=\"\" />" + Environment.NewLine + Environment.NewLine + "<input id=\"Name\" name=\"Name\" type=\"text\" value=\"\" />" + Environment.NewLine + Environment.NewLine +
@ -548,7 +515,7 @@ Products: Laptops (3)";
Environment.NewLine + Environment.NewLine); Environment.NewLine + Environment.NewLine);
// Act // Act
var response = await client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingSharedEditorTemplate"); var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingSharedEditorTemplate");
// Assert // Assert
Assert.Equal(expected, response); Assert.Equal(expected, response);
@ -558,16 +525,22 @@ Products: Laptops (3)";
public async Task EditorTemplateWithSpecificModel_RendersWithCorrectMetadata() public async Task EditorTemplateWithSpecificModel_RendersWithCorrectMetadata()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = "<label for=\"Description\">ItemDesc</label>" + Environment.NewLine + var expected = "<label for=\"Description\">ItemDesc</label>" + Environment.NewLine +
"<input id=\"Description\" name=\"Description\" type=\"text\" value=\"\" />" + Environment.NewLine + Environment.NewLine; "<input id=\"Description\" name=\"Description\" type=\"text\" value=\"\" />" + Environment.NewLine + Environment.NewLine;
// Act // Act
var response = await client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingModelSpecificEditorTemplate"); var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingModelSpecificEditorTemplate");
// Assert // Assert
Assert.Equal(expected, response); 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;
}
} }
} }

View File

@ -1,21 +1,21 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing; using Microsoft.AspNet.Testing;
using Microsoft.Framework.DependencyInjection;
using RazorWebSite;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class HtmlHelperOptionsTest public class HtmlHelperOptionsTest : IClassFixture<MvcTestFixture<RazorWebSite.Startup>>
{ {
private const string SiteName = nameof(RazorWebSite); public HtmlHelperOptionsTest(MvcTestFixture<RazorWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task AppWideDefaultsInViewAndPartialView() public async Task AppWideDefaultsInViewAndPartialView()
@ -40,11 +40,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
False"; False";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/HtmlHelperOptions/HtmlHelperOptionsDefaultsInView"); var body = await Client.GetStringAsync("http://localhost/HtmlHelperOptions/HtmlHelperOptionsDefaultsInView");
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -75,11 +72,8 @@ True
True"; True";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/HtmlHelperOptions/OverrideAppWideDefaultsInView"); var body = await Client.GetStringAsync("http://localhost/HtmlHelperOptions/OverrideAppWideDefaultsInView");
// Assert // Assert
// Mono issue - https://github.com/aspnet/External/issues/19 // Mono issue - https://github.com/aspnet/External/issues/19

View File

@ -6,30 +6,25 @@ using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using InlineConstraints;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class InlineConstraintTests public class InlineConstraintTests : IClassFixture<MvcTestFixture<InlineConstraints.Startup>>
{ {
private const string SiteName = nameof(InlineConstraintsWebSite); public InlineConstraintTests(MvcTestFixture<InlineConstraints.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task RoutingToANonExistantArea_WithExistConstraint_RoutesToCorrectAction() public async Task RoutingToANonExistantArea_WithExistConstraint_RoutesToCorrectAction()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/area-exists/Users");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/area-exists/Users");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -40,12 +35,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task RoutingToANonExistantArea_WithoutExistConstraint_RoutesToIncorrectAction() public async Task RoutingToANonExistantArea_WithoutExistConstraint_RoutesToIncorrectAction()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/area-withoutexists/Users");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/area-withoutexists/Users");
// Assert // Assert
var exception = response.GetServerException(); var exception = response.GetServerException();
@ -62,12 +53,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductById_IntConstraintForOptionalId_IdPresent() public async Task GetProductById_IntConstraintForOptionalId_IdPresent()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductById/5");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductById/5");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -81,12 +68,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductById_IntConstraintForOptionalId_NoId() public async Task GetProductById_IntConstraintForOptionalId_NoId()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductById");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductById");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -98,12 +81,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductById_IntConstraintForOptionalId_NotIntId() public async Task GetProductById_IntConstraintForOptionalId_NotIntId()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductById/asdf");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductById/asdf");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -112,12 +91,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByName_AlphaContraintForMandatoryName_ValidName() public async Task GetProductByName_AlphaContraintForMandatoryName_ValidName()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductByName/asdf");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductByName/asdf");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -130,12 +105,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByName_AlphaContraintForMandatoryName_NonAlphaName() public async Task GetProductByName_AlphaContraintForMandatoryName_NonAlphaName()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductByName/asd123");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductByName/asd123");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -144,12 +115,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByName_AlphaContraintForMandatoryName_NoName() public async Task GetProductByName_AlphaContraintForMandatoryName_NoName()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductByName");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductByName");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -158,13 +125,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByManufacturingDate_DateTimeConstraintForMandatoryDateTime_ValidDateTime() public async Task GetProductByManufacturingDate_DateTimeConstraintForMandatoryDateTime_ValidDateTime()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act
var response = 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -178,12 +141,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByCategoryName_StringLengthConstraint_ForOptionalCategoryName_ValidCatName() public async Task GetProductByCategoryName_StringLengthConstraint_ForOptionalCategoryName_ValidCatName()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductByCategoryName/Sports");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductByCategoryName/Sports");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -196,13 +155,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByCategoryName_StringLengthConstraint_ForOptionalCategoryName_InvalidCatName() public async Task GetProductByCategoryName_StringLengthConstraint_ForOptionalCategoryName_InvalidCatName()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act
var response = var response =
await client.GetAsync("http://localhost/products/GetProductByCategoryName/SportsSportsSportsSports"); await Client.GetAsync("http://localhost/products/GetProductByCategoryName/SportsSportsSportsSports");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -211,12 +166,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByCategoryName_StringLength1To20Constraint_ForOptionalCategoryName_NoCatName() public async Task GetProductByCategoryName_StringLength1To20Constraint_ForOptionalCategoryName_NoCatName()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductByCategoryName");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductByCategoryName");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -228,12 +179,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByCategoryId_Int10To100Constraint_ForMandatoryCatId_ValidId() public async Task GetProductByCategoryId_Int10To100Constraint_ForMandatoryCatId_ValidId()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductByCategoryId/40");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductByCategoryId/40");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -246,12 +193,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByCategoryId_Int10To100Constraint_ForMandatoryCatId_InvalidId() public async Task GetProductByCategoryId_Int10To100Constraint_ForMandatoryCatId_InvalidId()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductByCategoryId/5");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductByCategoryId/5");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -260,12 +203,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByCategoryId_Int10To100Constraint_ForMandatoryCatId_NotIntId() public async Task GetProductByCategoryId_Int10To100Constraint_ForMandatoryCatId_NotIntId()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductByCategoryId/asdf");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductByCategoryId/asdf");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -274,12 +213,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByPrice_FloatContraintForOptionalPrice_Valid() public async Task GetProductByPrice_FloatContraintForOptionalPrice_Valid()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductByPrice/4023.23423");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductByPrice/4023.23423");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -292,12 +227,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByPrice_FloatContraintForOptionalPrice_NoPrice() public async Task GetProductByPrice_FloatContraintForOptionalPrice_NoPrice()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductByPrice");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductByPrice");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -309,12 +240,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByManufacturerId_IntMin10Constraint_ForOptionalManufacturerId_Valid() public async Task GetProductByManufacturerId_IntMin10Constraint_ForOptionalManufacturerId_Valid()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductByManufacturerId/57");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductByManufacturerId/57");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -327,12 +254,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetProductByManufacturerId_IntMin10Cinstraint_ForOptionalManufacturerId_NoId() public async Task GetProductByManufacturerId_IntMin10Cinstraint_ForOptionalManufacturerId_NoId()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetProductByManufacturerId");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetProductByManufacturerId");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -344,12 +267,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetUserByName_RegExConstraint_ForMandatoryName_Valid() public async Task GetUserByName_RegExConstraint_ForMandatoryName_Valid()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetUserByName/abc");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetUserByName/abc");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -362,12 +281,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetUserByName_RegExConstraint_ForMandatoryName_InValid() public async Task GetUserByName_RegExConstraint_ForMandatoryName_InValid()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/products/GetUserByName/abcd");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/products/GetUserByName/abcd");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -376,13 +291,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetStoreById_GuidConstraintForOptionalId_Valid() public async Task GetStoreById_GuidConstraintForOptionalId_Valid()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act
var response = 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -395,12 +306,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetStoreById_GuidConstraintForOptionalId_NoId() public async Task GetStoreById_GuidConstraintForOptionalId_NoId()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Store/GetStoreById");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Store/GetStoreById");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -412,12 +319,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetStoreById_GuidConstraintForOptionalId_NotGuidId() public async Task GetStoreById_GuidConstraintForOptionalId_NotGuidId()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Store/GetStoreById/691cf17a-791b");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Store/GetStoreById/691cf17a-791b");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -426,12 +329,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetStoreByLocation_StringLengthConstraint_AlphaConstraint_ForMandatoryLocation_Valid() public async Task GetStoreByLocation_StringLengthConstraint_AlphaConstraint_ForMandatoryLocation_Valid()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Store/GetStoreByLocation/Bellevue");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Store/GetStoreByLocation/Bellevue");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -444,12 +343,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetStoreByLocation_StringLengthConstraint_AlphaConstraint_ForMandatoryLocation_MoreLength() public async Task GetStoreByLocation_StringLengthConstraint_AlphaConstraint_ForMandatoryLocation_MoreLength()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Store/GetStoreByLocation/BellevueRedmond");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Store/GetStoreByLocation/BellevueRedmond");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -458,12 +353,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetStoreByLocation_StringLengthConstraint_AlphaConstraint_ForMandatoryLocation_LessLength() public async Task GetStoreByLocation_StringLengthConstraint_AlphaConstraint_ForMandatoryLocation_LessLength()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Store/GetStoreByLocation/Be");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Store/GetStoreByLocation/Be");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -472,12 +363,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task GetStoreByLocation_StringLengthConstraint_AlphaConstraint_ForMandatoryLocation_NoAlpha() public async Task GetStoreByLocation_StringLengthConstraint_AlphaConstraint_ForMandatoryLocation_NoAlpha()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Store/GetStoreByLocation/Bell124");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Store/GetStoreByLocation/Bell124");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -490,12 +377,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("1-234-56789-X", "10 Digit ISBN Number")] [InlineData("1-234-56789-X", "10 Digit ISBN Number")]
public async Task CustomInlineConstraint_Add_Update(string isbn, string expectedBody) public async Task CustomInlineConstraint_Add_Update(string isbn, string expectedBody)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/book/index/" + isbn);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/book/index/" + isbn);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -649,13 +532,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
string parameterValue, string parameterValue,
string expectedLink) string expectedLink)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act
string url; string url;
if (parameterName == null) if (parameterName == null)
{ {
url = string.Format( url = string.Format(
@ -675,7 +553,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
parameterValue); parameterValue);
} }
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();

View File

@ -1,26 +1,25 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class InputFormatterTests public class InputFormatterTests : IClassFixture<MvcTestFixture<FormatterWebSite.Startup>>
{ {
private const string SiteName = nameof(FormatterWebSite); public InputFormatterTests(MvcTestFixture<FormatterWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new FormatterWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new FormatterWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[ConditionalFact] [ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18 // Mono issue - https://github.com/aspnet/External/issues/18
@ -28,8 +27,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CheckIfXmlInputFormatterIsBeingCalled() public async Task CheckIfXmlInputFormatterIsBeingCalled()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var sampleInputInt = 10; var sampleInputInt = 10;
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<DummyClass xmlns=\"http://schemas.datacontract.org/2004/07/FormatterWebSite\"><SampleInt>" "<DummyClass xmlns=\"http://schemas.datacontract.org/2004/07/FormatterWebSite\"><SampleInt>"
@ -37,7 +34,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var content = new StringContent(input, Encoding.UTF8, "application/xml"); var content = new StringContent(input, Encoding.UTF8, "application/xml");
// Act // 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(HttpStatusCode.OK, response.StatusCode);
@ -53,14 +50,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonInputFormatter_IsSelectedForJsonRequest(string requestContentType) public async Task JsonInputFormatter_IsSelectedForJsonRequest(string requestContentType)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var sampleInputInt = 10; var sampleInputInt = 10;
var input = "{\"SampleInt\":10}"; var input = "{\"SampleInt\":10}";
var content = new StringContent(input, Encoding.UTF8, requestContentType); var content = new StringContent(input, Encoding.UTF8, requestContentType);
// Act // 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(HttpStatusCode.OK, response.StatusCode);
@ -78,15 +73,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("invalid", false)] [InlineData("invalid", false)]
[InlineData("application/custom", false)] [InlineData("application/custom", false)]
[InlineData("image/jpg", false)] [InlineData("image/jpg", false)]
public async Task ModelStateErrorValidation_NoInputFormatterFound_ForGivenContentType(string requestContentType, public async Task ModelStateErrorValidation_NoInputFormatterFound_ForGivenContentType(
string requestContentType,
bool filterHandlesModelStateError) bool filterHandlesModelStateError)
{ {
// Arrange // Arrange
var actionName = filterHandlesModelStateError ? "ActionFilterHandlesError" : "ActionHandlesError"; var actionName = filterHandlesModelStateError ? "ActionFilterHandlesError" : "ActionHandlesError";
var expectedSource = filterHandlesModelStateError ? "filter" : "action"; var expectedSource = filterHandlesModelStateError ? "filter" : "action";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{\"SampleInt\":10}"; var input = "{\"SampleInt\":10}";
var content = new StringContent(input); var content = new StringContent(input);
content.Headers.Clear(); content.Headers.Clear();
@ -96,7 +89,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/InputFormatter/" + actionName); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/InputFormatter/" + actionName);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
request.Content = content; request.Content = content;
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync(); var responseBody = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<FormatterWebSite.ErrorInfo>(responseBody); var result = JsonConvert.DeserializeObject<FormatterWebSite.ErrorInfo>(responseBody);
@ -113,15 +106,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Theory] [Theory]
[InlineData("application/json", "{\"SampleInt\":10}", 10)] [InlineData("application/json", "{\"SampleInt\":10}", 10)]
[InlineData("application/json", "{}", 0)] [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 // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var content = new StringContent(jsonInput, Encoding.UTF8, requestContentType); var content = new StringContent(jsonInput, Encoding.UTF8, requestContentType);
// Act // 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(); var responseBody = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -136,12 +130,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonInputFormatter_ReturnsDefaultValue_ForValueTypes(string input) public async Task JsonInputFormatter_ReturnsDefaultValue_ForValueTypes(string input)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var content = new StringContent(input, Encoding.UTF8, "application/json"); var content = new StringContent(input, Encoding.UTF8, "application/json");
// Act // 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(); var responseBody = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -154,12 +146,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = "1773"; var expected = "1773";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var content = new StringContent(expected, Encoding.UTF8, "application/json"); var content = new StringContent(expected, Encoding.UTF8, "application/json");
// Act // 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(); var responseBody = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -174,13 +164,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonInputFormatter_IsModelStateInvalid_ForEmptyContentType(string jsonInput) public async Task JsonInputFormatter_IsModelStateInvalid_ForEmptyContentType(string jsonInput)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var content = new StringContent(jsonInput, Encoding.UTF8, "application/json"); var content = new StringContent(jsonInput, Encoding.UTF8, "application/json");
content.Headers.Clear(); content.Headers.Clear();
// Act // 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(); var responseBody = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -190,16 +178,19 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Theory] [Theory]
[InlineData("application/json", "{\"SampleInt\":10}", 10)] [InlineData("application/json", "{\"SampleInt\":10}", 10)]
[InlineData("application/json", "{}", 0)] [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 // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var content = new StringContent(jsonInput, Encoding.UTF8, requestContentType); 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 // Act
var response = await client.PostAsync("http://localhost/JsonFormatter/ReturnInput/", content); var response = await Client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync(); var responseBody = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -213,12 +204,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CustomFormatter_IsSelected_ForSupportedContentTypeAndEncoding(string encoding) public async Task CustomFormatter_IsSelected_ForSupportedContentTypeAndEncoding(string encoding)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var content = new StringContent("Test Content", Encoding.GetEncoding(encoding), "text/plain"); var content = new StringContent("Test Content", Encoding.GetEncoding(encoding), "text/plain");
// Act // 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(); var responseBody = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -232,12 +221,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CustomFormatter_NotSelected_ForUnsupportedContentType(string contentType) public async Task CustomFormatter_NotSelected_ForUnsupportedContentType(string contentType)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var content = new StringContent("Test Content", Encoding.UTF8, contentType); var content = new StringContent("Test Content", Encoding.UTF8, contentType);
// Act // 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(); var responseBody = await response.Content.ReadAsStringAsync();
// Assert // Assert

View File

@ -1,27 +1,27 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Testing; using Microsoft.AspNet.Testing;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class InputObjectValidationTests public class InputObjectValidationTests : IClassFixture<MvcTestFixture<FormatterWebSite.Startup>>
{ {
private const string SiteName = nameof(FormatterWebSite); public InputObjectValidationTests(MvcTestFixture<FormatterWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new FormatterWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new FormatterWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
// Parameters: Request Content, Expected status code, Expected model state error message // Parameters: Request Content, Expected status code, Expected model state error message
public static IEnumerable<object[]> SimpleTypePropertiesModelRequestData public static IEnumerable<object[]> SimpleTypePropertiesModelRequestData
@ -51,8 +51,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CheckIfObjectIsDeserializedWithoutErrors() public async Task CheckIfObjectIsDeserializedWithoutErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var sampleId = 2; var sampleId = 2;
var sampleName = "SampleUser"; var sampleName = "SampleUser";
var sampleAlias = "SampleAlias"; var sampleAlias = "SampleAlias";
@ -66,7 +64,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var content = new StringContent(input, Encoding.UTF8, "application/xml"); var content = new StringContent(input, Encoding.UTF8, "application/xml");
// Act // Act
var response = await client.PostAsync("http://localhost/Validation/Index", content); var response = await Client.PostAsync("http://localhost/Validation/Index", content);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -78,8 +76,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CheckIfObjectIsDeserialized_WithErrors() public async Task CheckIfObjectIsDeserialized_WithErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var sampleId = 0; var sampleId = 0;
var sampleName = "user"; var sampleName = "user";
var sampleAlias = "a"; var sampleAlias = "a";
@ -90,7 +86,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var content = new StringContent(input, Encoding.UTF8, "application/json"); var content = new StringContent(input, Encoding.UTF8, "application/json");
// Act // Act
var response = await client.PostAsync("http://localhost/Validation/Index", content); var response = await Client.PostAsync("http://localhost/Validation/Index", content);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -108,12 +104,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CheckIfExcludedFieldsAreNotValidated() public async Task CheckIfExcludedFieldsAreNotValidated()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var content = new StringContent("{\"Alias\":\"xyz\"}", Encoding.UTF8, "application/json"); var content = new StringContent("{\"Alias\":\"xyz\"}", Encoding.UTF8, "application/json");
// Act // Act
var response = await client.PostAsync("http://localhost/Validation/GetDeveloperName", content); var response = await Client.PostAsync("http://localhost/Validation/GetDeveloperName", content);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -125,8 +119,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ShallowValidation_HappensOnExcluded_ComplexTypeProperties() public async Task ShallowValidation_HappensOnExcluded_ComplexTypeProperties()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var requestData = "{\"Name\":\"Library Manager\", \"Suppliers\": [{\"Name\":\"Contoso Corp\"}]}"; var requestData = "{\"Name\":\"Library Manager\", \"Suppliers\": [{\"Name\":\"Contoso Corp\"}]}";
var content = new StringContent(requestData, Encoding.UTF8, "application/json"); var content = new StringContent(requestData, Encoding.UTF8, "application/json");
var expectedModelStateErrorMessage 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'."; = "The field Name must be a string or array type with a maximum length of '5'.";
// Act // Act
var response = await client.PostAsync("http://localhost/Validation/CreateProject", content); var response = await Client.PostAsync("http://localhost/Validation/CreateProject", content);
// Assert // Assert
Assert.Equal(StatusCodes.Status400BadRequest, (int)response.StatusCode); Assert.Equal(StatusCodes.Status400BadRequest, (int)response.StatusCode);
@ -158,12 +150,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
string expectedModelStateErrorMessage) string expectedModelStateErrorMessage)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var content = new StringContent(requestContent, Encoding.UTF8, "application/json"); var content = new StringContent(requestContent, Encoding.UTF8, "application/json");
// Act // Act
var response = await client.PostAsync( var response = await Client.PostAsync(
"http://localhost/Validation/CreateSimpleTypePropertiesModel", "http://localhost/Validation/CreateSimpleTypePropertiesModel",
content); content);
@ -181,14 +171,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CheckIfExcludedField_IsNotValidatedForNonBodyBoundModels() public async Task CheckIfExcludedField_IsNotValidatedForNonBodyBoundModels()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var kvps = new List<KeyValuePair<string, string>>(); var kvps = new List<KeyValuePair<string, string>>();
kvps.Add(new KeyValuePair<string, string>("Alias", "xyz")); kvps.Add(new KeyValuePair<string, string>("Alias", "xyz"));
var content = new FormUrlEncodedContent(kvps); var content = new FormUrlEncodedContent(kvps);
// Act // Act
var response = await client.PostAsync("http://localhost/Validation/GetDeveloperAlias", content); var response = await Client.PostAsync("http://localhost/Validation/GetDeveloperAlias", content);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -1,27 +1,26 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class JsonOutputFormatterTests public class JsonOutputFormatterTests : IClassFixture<MvcTestFixture<FormatterWebSite.Startup>>
{ {
private const string SiteName = nameof(FormatterWebSite); public JsonOutputFormatterTests(MvcTestFixture<FormatterWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new FormatterWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new FormatterWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task JsonOutputFormatter_ReturnsIndentedJson() public async Task JsonOutputFormatter_ReturnsIndentedJson()
@ -40,11 +39,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
serializerSettings.Formatting = Formatting.Indented; serializerSettings.Formatting = Formatting.Indented;
var expectedBody = JsonConvert.SerializeObject(user, serializerSettings); var expectedBody = JsonConvert.SerializeObject(user, serializerSettings);
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var response = await client.GetAsync("http://localhost/JsonFormatter/ReturnsIndentedJson"); var response = await Client.GetAsync("http://localhost/JsonFormatter/ReturnsIndentedJson");
// Assert // Assert
var actualBody = await response.Content.ReadAsStringAsync(); var actualBody = await response.Content.ReadAsStringAsync();
@ -57,9 +53,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task SerializableErrorIsReturnedInExpectedFormat() public async Task SerializableErrorIsReturnedInExpectedFormat()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<Employee xmlns=\"http://schemas.datacontract.org/2004/07/FormatterWebSite\">" + "<Employee xmlns=\"http://schemas.datacontract.org/2004/07/FormatterWebSite\">" +
"<Id>2</Id><Name>foo</Name></Employee>"; "<Id>2</Id><Name>foo</Name></Employee>";
@ -72,7 +65,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new StringContent(input, Encoding.UTF8, "application/xml"); request.Content = new StringContent(input, Encoding.UTF8, "application/xml");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);

View File

@ -6,21 +6,21 @@ using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using JsonPatchWebSite;
using JsonPatchWebSite.Models; using JsonPatchWebSite.Models;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class JsonPatchTest public class JsonPatchTest : IClassFixture<MvcTestFixture<JsonPatchWebSite.Startup>>
{ {
private const string SiteName = nameof(JsonPatchWebSite); public JsonPatchTest(MvcTestFixture<JsonPatchWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("http://localhost/jsonpatch/JsonPatchWithoutModelState")] [InlineData("http://localhost/jsonpatch/JsonPatchWithoutModelState")]
@ -29,9 +29,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonPatch_ValidAddOperation_Success(string url) public async Task JsonPatch_ValidAddOperation_Success(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "[{ \"op\": \"add\", " + var input = "[{ \"op\": \"add\", " +
"\"path\": \"Orders/2\", " + "\"path\": \"Orders/2\", " +
"\"value\": { \"OrderName\": \"Name2\" }}]"; "\"value\": { \"OrderName\": \"Name2\" }}]";
@ -43,7 +40,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}; };
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -58,9 +55,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonPatch_ValidReplaceOperation_Success(string url) public async Task JsonPatch_ValidReplaceOperation_Success(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "[{ \"op\": \"replace\", " + var input = "[{ \"op\": \"replace\", " +
"\"path\": \"Orders/0/OrderName\", " + "\"path\": \"Orders/0/OrderName\", " +
"\"value\": \"ReplacedOrder\" }]"; "\"value\": \"ReplacedOrder\" }]";
@ -72,7 +66,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}; };
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -87,9 +81,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonPatch_ValidCopyOperation_Success(string url) public async Task JsonPatch_ValidCopyOperation_Success(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "[{ \"op\": \"copy\", " + var input = "[{ \"op\": \"copy\", " +
"\"path\": \"Orders/1/OrderName\", " + "\"path\": \"Orders/1/OrderName\", " +
"\"from\": \"Orders/0/OrderName\"}]"; "\"from\": \"Orders/0/OrderName\"}]";
@ -101,7 +92,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}; };
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -116,9 +107,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonPatch_ValidMoveOperation_Success(string url) public async Task JsonPatch_ValidMoveOperation_Success(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "[{ \"op\": \"move\", " + var input = "[{ \"op\": \"move\", " +
"\"path\": \"Orders/1/OrderName\", " + "\"path\": \"Orders/1/OrderName\", " +
"\"from\": \"Orders/0/OrderName\"}]"; "\"from\": \"Orders/0/OrderName\"}]";
@ -130,7 +118,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}; };
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -147,9 +135,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonPatch_ValidRemoveOperation_Success(string url) public async Task JsonPatch_ValidRemoveOperation_Success(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "[{ \"op\": \"remove\", " + var input = "[{ \"op\": \"remove\", " +
"\"path\": \"Orders/1/OrderName\"}]"; "\"path\": \"Orders/1/OrderName\"}]";
var request = new HttpRequestMessage var request = new HttpRequestMessage
@ -160,7 +145,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}; };
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -175,9 +160,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonPatch_MultipleValidOperations_Success(string url) public async Task JsonPatch_MultipleValidOperations_Success(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "[{ \"op\": \"add\", "+ var input = "[{ \"op\": \"add\", "+
"\"path\": \"Orders/2\", " + "\"path\": \"Orders/2\", " +
"\"value\": { \"OrderName\": \"Name2\" }}, " + "\"value\": { \"OrderName\": \"Name2\" }}, " +
@ -195,7 +177,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}; };
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); 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) public async Task JsonPatch_InvalidOperations_failure(string url, string input, string errorMessage)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage var request = new HttpRequestMessage
{ {
Content = new StringContent(input, Encoding.UTF8, "application/json-patch+json"), Content = new StringContent(input, Encoding.UTF8, "application/json-patch+json"),
@ -273,7 +252,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}; };
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -284,9 +263,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonPatch_InvalidData_FormatterErrorInModelState_Failure() public async Task JsonPatch_InvalidData_FormatterErrorInModelState_Failure()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{ \"op\": \"add\", " + var input = "{ \"op\": \"add\", " +
"\"path\": \"Orders/2\", " + "\"path\": \"Orders/2\", " +
"\"value\": { \"OrderName\": \"Name2\" }}"; "\"value\": { \"OrderName\": \"Name2\" }}";
@ -298,7 +274,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}; };
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -309,9 +285,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonPatch_JsonConverterOnProperty_Success() public async Task JsonPatch_JsonConverterOnProperty_Success()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "[{ \"op\": \"add\", " + var input = "[{ \"op\": \"add\", " +
"\"path\": \"Orders/2\", " + "\"path\": \"Orders/2\", " +
"\"value\": { \"OrderType\": \"Type2\" }}]"; "\"value\": { \"OrderType\": \"Type2\" }}]";
@ -323,7 +296,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}; };
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -335,9 +308,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonPatch_JsonConverterOnClass_Success() public async Task JsonPatch_JsonConverterOnClass_Success()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "[{ \"op\": \"add\", " + var input = "[{ \"op\": \"add\", " +
"\"path\": \"ProductCategory\", " + "\"path\": \"ProductCategory\", " +
"\"value\": { \"CategoryName\": \"Name2\" }}]"; "\"value\": { \"CategoryName\": \"Name2\" }}]";
@ -349,7 +319,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}; };
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();

View File

@ -1,35 +1,31 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class JsonResultTest public class JsonResultTest : IClassFixture<MvcTestFixture<BasicWebSite.Startup>>
{ {
private const string SiteName = nameof(BasicWebSite); public JsonResultTest(MvcTestFixture<BasicWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new BasicWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new BasicWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task JsonResult_UsesDefaultContentType() public async Task JsonResult_UsesDefaultContentType()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/JsonResult/Plain"; var url = "http://localhost/JsonResult/Plain";
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -46,16 +42,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonResult_Conneg_Fails(string mediaType) public async Task JsonResult_Conneg_Fails(string mediaType)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/JsonResult/Plain"; var url = "http://localhost/JsonResult/Plain";
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.TryAddWithoutValidation("Accept", mediaType); request.Headers.TryAddWithoutValidation("Accept", mediaType);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -69,15 +61,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonResult_Null() public async Task JsonResult_Null()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/JsonResult/Null"; var url = "http://localhost/JsonResult/Null";
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -91,15 +79,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonResult_String() public async Task JsonResult_String()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/JsonResult/String"; var url = "http://localhost/JsonResult/String";
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -112,15 +96,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonResult_Uses_CustomSerializerSettings() public async Task JsonResult_Uses_CustomSerializerSettings()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/JsonResult/CustomSerializerSettings"; var url = "http://localhost/JsonResult/CustomSerializerSettings";
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -132,15 +112,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonResult_CustomContentType() public async Task JsonResult_CustomContentType()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/JsonResult/CustomContentType"; var url = "http://localhost/JsonResult/CustomContentType";
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert

View File

@ -12,7 +12,7 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class LinkGenerationTests : IClassFixture<MvcFixture<BasicWebSite.Startup>> public class LinkGenerationTests : IClassFixture<MvcTestFixture<BasicWebSite.Startup>>
{ {
// Some tests require comparing the actual response body against an expected response baseline // 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 // 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. // use it on all the rest of the tests.
private static readonly Assembly _resourcesAssembly = typeof(LinkGenerationTests).GetTypeInfo().Assembly; private static readonly Assembly _resourcesAssembly = typeof(LinkGenerationTests).GetTypeInfo().Assembly;
public LinkGenerationTests(MvcFixture<BasicWebSite.Startup> fixture) public LinkGenerationTests(MvcTestFixture<BasicWebSite.Startup> fixture)
{ {
Client = fixture.Client; Client = fixture.Client;
} }

View File

@ -1,29 +1,30 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Net.Http;
using System.Reflection; using System.Reflection;
using System.Resources; using System.Resources;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
using LocalizationWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing; using Microsoft.AspNet.Testing;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Net.Http.Headers; using Microsoft.Net.Http.Headers;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class LocalizationTest public class LocalizationTest : IClassFixture<MvcTestFixture<LocalizationWebSite.Startup>>
{ {
private const string SiteName = nameof(LocalizationWebSite); private const string SiteName = nameof(LocalizationWebSite);
private static readonly Assembly _assembly = typeof(LocalizationTest).GetTypeInfo().Assembly; private static readonly Assembly _assembly = typeof(LocalizationTest).GetTypeInfo().Assembly;
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; public LocalizationTest(MvcTestFixture<LocalizationWebSite.Startup> fixture)
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; {
Client = fixture.Client;
}
public HttpClient Client { get; }
public static IEnumerable<object[]> LocalizationData public static IEnumerable<object[]> LocalizationData
{ {
@ -62,15 +63,15 @@ mypartial
public async Task Localization_SuffixViewName(string value, string expected) public async Task Localization_SuffixViewName(string value, string expected)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var cultureCookie = "c=" + value + "|uic=" + value; var cultureCookie = "c=" + value + "|uic=" + value;
client.DefaultRequestHeaders.Add( var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/");
request.Headers.Add(
"Cookie", "Cookie",
new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString()); new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString());
// Act // Act
var body = await client.GetStringAsync("http://localhost/"); var response = await Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -112,10 +113,9 @@ Hi";
public async Task Localization_Resources_ReturnExpectedValues(string value, string expected) public async Task Localization_Resources_ReturnExpectedValues(string value, string expected)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var cultureCookie = "c=" + value + "|uic=" + value; var cultureCookie = "c=" + value + "|uic=" + value;
client.DefaultRequestHeaders.Add( var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/Locpage");
request.Headers.Add(
"Cookie", "Cookie",
new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString()); new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString());
@ -128,7 +128,8 @@ Hi";
WriteResourceFile("Views.Home.Locpage.cshtml." + value + ".resx"); WriteResourceFile("Views.Home.Locpage.cshtml." + value + ".resx");
// Act // Act
var body = await client.GetStringAsync("http://localhost/Home/Locpage"); var response = await Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
// Assert // Assert
Assert.Equal(expected, body.Trim()); Assert.Equal(expected, body.Trim());

View File

@ -1,13 +1,10 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using ModelBindingWebSite; using ModelBindingWebSite;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@ -15,19 +12,19 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ModelBindingBindingBehaviorTest public class ModelBindingBindingBehaviorTest : IClassFixture<MvcTestFixture<ModelBindingWebSite.Startup>>
{ {
private const string SiteName = nameof(ModelBindingWebSite); public ModelBindingBindingBehaviorTest(MvcTestFixture<ModelBindingWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task BindingBehavior_MissingRequiredProperties_ValidationErrors() public async Task BindingBehavior_MissingRequiredProperties_ValidationErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/BindingBehavior/EchoModelValues"; var url = "http://localhost/BindingBehavior/EchoModelValues";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
var formData = new List<KeyValuePair<string, string>> var formData = new List<KeyValuePair<string, string>>
@ -38,7 +35,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(formData); request.Content = new FormUrlEncodedContent(formData);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
@ -63,9 +60,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task BindingBehavior_OptionalIsOptional() public async Task BindingBehavior_OptionalIsOptional()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/BindingBehavior/EchoModelValues"; var url = "http://localhost/BindingBehavior/EchoModelValues";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
var formData = new List<KeyValuePair<string, string>> var formData = new List<KeyValuePair<string, string>>
@ -77,7 +71,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(formData); request.Content = new FormUrlEncodedContent(formData);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -96,9 +90,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task BindingBehavior_Never_IsNotBound() public async Task BindingBehavior_Never_IsNotBound()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/BindingBehavior/EchoModelValues"; var url = "http://localhost/BindingBehavior/EchoModelValues";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
var formData = new List<KeyValuePair<string, string>> var formData = new List<KeyValuePair<string, string>>
@ -114,7 +105,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(formData); request.Content = new FormUrlEncodedContent(formData);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -1,13 +1,10 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using ModelBindingWebSite; using ModelBindingWebSite;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@ -15,19 +12,19 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ModelBindingDataMemberRequiredTest public class ModelBindingDataMemberRequiredTest : IClassFixture<MvcTestFixture<ModelBindingWebSite.Startup>>
{ {
private const string SiteName = nameof(ModelBindingWebSite); public ModelBindingDataMemberRequiredTest(MvcTestFixture<ModelBindingWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task DataMember_MissingRequiredProperty_ValidationError() public async Task DataMember_MissingRequiredProperty_ValidationError()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/DataMemberRequired/EchoModelValues"; var url = "http://localhost/DataMemberRequired/EchoModelValues";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
var formData = new List<KeyValuePair<string, string>> var formData = new List<KeyValuePair<string, string>>
@ -38,7 +35,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(formData); request.Content = new FormUrlEncodedContent(formData);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
@ -58,9 +55,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task DataMember_RequiredPropertyProvided_Success() public async Task DataMember_RequiredPropertyProvided_Success()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/DataMemberRequired/EchoModelValues"; var url = "http://localhost/DataMemberRequired/EchoModelValues";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
var formData = new List<KeyValuePair<string, string>> var formData = new List<KeyValuePair<string, string>>
@ -73,7 +67,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(formData); request.Content = new FormUrlEncodedContent(formData);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -1,12 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using ModelBindingWebSite; using ModelBindingWebSite;
using ModelBindingWebSite.Controllers; using ModelBindingWebSite.Controllers;
using ModelBindingWebSite.Models; using ModelBindingWebSite.Models;
@ -15,19 +12,19 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ModelBindingFromFormTest public class ModelBindingFromFormTest : IClassFixture<MvcTestFixture<ModelBindingWebSite.Startup>>
{ {
private const string SiteName = nameof(ModelBindingWebSite); public ModelBindingFromFormTest(MvcTestFixture<ModelBindingWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task FromForm_CustomModelPrefix_ForParameter() public async Task FromForm_CustomModelPrefix_ForParameter()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/FromFormAttribute_Company/CreateCompany"; var url = "http://localhost/FromFormAttribute_Company/CreateCompany";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
var nameValueCollection = new List<KeyValuePair<string, string>> var nameValueCollection = new List<KeyValuePair<string, string>>
@ -38,7 +35,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -53,9 +50,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromForm_CustomModelPrefix_ForCollectionParameter() public async Task FromForm_CustomModelPrefix_ForCollectionParameter()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/FromFormAttribute_Company/CreateCompanyFromEmployees"; var url = "http://localhost/FromFormAttribute_Company/CreateCompanyFromEmployees";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
var nameValueCollection = new List<KeyValuePair<string, string>> var nameValueCollection = new List<KeyValuePair<string, string>>
@ -65,7 +59,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -79,9 +73,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromForm_CustomModelPrefix_ForProperty() public async Task FromForm_CustomModelPrefix_ForProperty()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/FromFormAttribute_Company/CreateCompany"; var url = "http://localhost/FromFormAttribute_Company/CreateCompany";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
var nameValueCollection = new List<KeyValuePair<string, string>> var nameValueCollection = new List<KeyValuePair<string, string>>
@ -91,7 +82,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -105,9 +96,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromForm_CustomModelPrefix_ForCollectionProperty() public async Task FromForm_CustomModelPrefix_ForCollectionProperty()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/FromFormAttribute_Company/CreateDepartment"; var url = "http://localhost/FromFormAttribute_Company/CreateDepartment";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
var nameValueCollection = new List<KeyValuePair<string, string>> var nameValueCollection = new List<KeyValuePair<string, string>>
@ -117,7 +105,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -132,9 +120,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromForm_NonExistingValueAddsValidationErrors_OnProperty_UsingCustomModelPrefix() public async Task FromForm_NonExistingValueAddsValidationErrors_OnProperty_UsingCustomModelPrefix()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/FromFormAttribute_Company/ValidateDepartment"; var url = "http://localhost/FromFormAttribute_Company/ValidateDepartment";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
@ -143,7 +128,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();

View File

@ -12,11 +12,14 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ModelBindingFromHeaderTest public class ModelBindingFromHeaderTest : IClassFixture<MvcTestFixture<ModelBindingWebSite.Startup>>
{ {
private const string SiteName = nameof(ModelBindingWebSite); public ModelBindingFromHeaderTest(MvcTestFixture<ModelBindingWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new ModelBindingWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new ModelBindingWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
// The action that this test hits will echo back the model-bound value // The action that this test hits will echo back the model-bound value
[Theory] [Theory]
@ -27,15 +30,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = headerValue; var expected = headerValue;
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToStringParameter"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToStringParameter");
request.Headers.TryAddWithoutValidation(headerName, headerValue); request.Headers.TryAddWithoutValidation(headerName, headerValue);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -51,16 +50,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Arrange // Arrange
var title = "How to make really really good soup."; var title = "How to make really really good soup.";
var tags = new string[] { "Cooking", "Recipes", "Awesome" }; 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"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToProperty/CustomName");
request.Headers.TryAddWithoutValidation("BlogTitle", title); request.Headers.TryAddWithoutValidation("BlogTitle", title);
request.Headers.TryAddWithoutValidation("BlogTags", string.Join(", ", tags)); request.Headers.TryAddWithoutValidation("BlogTags", string.Join(", ", tags));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -77,15 +72,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var tags = new string[] { "Cooking", "Recipes", "Awesome" }; 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"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToProperty/CustomName");
request.Headers.TryAddWithoutValidation("BlogTags", string.Join(", ", tags)); request.Headers.TryAddWithoutValidation("BlogTags", string.Join(", ", tags));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -101,14 +92,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromHeader_NonExistingHeaderAddsValidationErrors_OnCollectionProperty_CustomName() public async Task FromHeader_NonExistingHeaderAddsValidationErrors_OnCollectionProperty_CustomName()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToProperty/CustomName"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToProperty/CustomName");
request.Headers.TryAddWithoutValidation("BlogTitle", "Cooking Receipes."); request.Headers.TryAddWithoutValidation("BlogTitle", "Cooking Receipes.");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -126,15 +114,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = "1e331f25-0869-4c87-8a94-64e6e40cb5a0"; 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"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToStringParameter/CustomName");
request.Headers.TryAddWithoutValidation("tId", "1e331f25-0869-4c87-8a94-64e6e40cb5a0"); request.Headers.TryAddWithoutValidation("tId", "1e331f25-0869-4c87-8a94-64e6e40cb5a0");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -154,15 +138,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = headerValue; var expected = headerValue;
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToStringParameter"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToStringParameter");
request.Headers.TryAddWithoutValidation(headerName, headerValue); request.Headers.TryAddWithoutValidation(headerName, headerValue);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -183,16 +163,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
string headerValue) string headerValue)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Intentionally not setting a header value
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Get, HttpMethod.Get,
"http://localhost/Blog/BindToStringParameterDefaultValue"); "http://localhost/Blog/BindToStringParameterDefaultValue");
// Intentionally not setting a header value
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -213,15 +190,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = headerValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); 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"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToStringArrayParameter");
request.Headers.TryAddWithoutValidation(headerName, headerValue); request.Headers.TryAddWithoutValidation(headerName, headerValue);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -241,17 +214,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Arrange // Arrange
var title = "How to make really really good soup."; var title = "How to make really really good soup.";
var tags = new string[] { "Cooking", "Recipes", "Awesome" }; 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"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToModel?author=Marvin");
request.Headers.TryAddWithoutValidation("title", title); request.Headers.TryAddWithoutValidation("title", title);
request.Headers.TryAddWithoutValidation("tags", string.Join(", ", tags)); request.Headers.TryAddWithoutValidation("tags", string.Join(", ", tags));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -270,15 +238,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromHeader_BindHeader_ToModel_NoValues_ValidationError() public async Task FromHeader_BindHeader_ToModel_NoValues_ValidationError()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Intentionally not setting a title or tags
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToModel?author=Marvin"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Blog/BindToModel?author=Marvin");
// Intentionally not setting a title or tags
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -300,17 +264,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromHeader_BindHeader_ToModel_NoValues_InitializedValue_NoValidationError() public async Task FromHeader_BindHeader_ToModel_NoValues_InitializedValue_NoValidationError()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Intentionally not setting a title or tags
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Get, HttpMethod.Get,
"http://localhost/Blog/BindToModelWithInitializedValue?author=Marvin"); "http://localhost/Blog/BindToModelWithInitializedValue?author=Marvin");
// Intentionally not setting a title or tags
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -1,10 +1,8 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using ModelBindingWebSite; using ModelBindingWebSite;
using ModelBindingWebSite.Controllers; using ModelBindingWebSite.Controllers;
using ModelBindingWebSite.Models; using ModelBindingWebSite.Models;
@ -13,25 +11,25 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ModelBindingFromQueryTest public class ModelBindingFromQueryTest : IClassFixture<MvcTestFixture<ModelBindingWebSite.Startup>>
{ {
private const string SiteName = nameof(ModelBindingWebSite); public ModelBindingFromQueryTest(MvcTestFixture<ModelBindingWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task FromQuery_CustomModelPrefix_ForParameter() public async Task FromQuery_CustomModelPrefix_ForParameter()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// [FromQuery(Name = "customPrefix")] is used to apply a prefix // [FromQuery(Name = "customPrefix")] is used to apply a prefix
var url = var url =
"http://localhost/FromQueryAttribute_Company/CreateCompany?customPrefix.Employees[0].Name=somename"; "http://localhost/FromQueryAttribute_Company/CreateCompany?customPrefix.Employees[0].Name=somename";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -45,14 +43,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromQuery_CustomModelPrefix_ForCollectionParameter() public async Task FromQuery_CustomModelPrefix_ForCollectionParameter()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = var url =
"http://localhost/FromQueryAttribute_Company/CreateCompanyFromEmployees?customPrefix[0].Name=somename"; "http://localhost/FromQueryAttribute_Company/CreateCompanyFromEmployees?customPrefix[0].Name=somename";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -66,15 +61,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromQuery_CustomModelPrefix_ForProperty() public async Task FromQuery_CustomModelPrefix_ForProperty()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// [FromQuery(Name = "EmployeeId")] is used to apply a prefix // [FromQuery(Name = "EmployeeId")] is used to apply a prefix
var url = var url =
"http://localhost/FromQueryAttribute_Company/CreateCompany?customPrefix.Employees[0].EmployeeId=1234"; "http://localhost/FromQueryAttribute_Company/CreateCompany?customPrefix.Employees[0].EmployeeId=1234";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -89,13 +81,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromQuery_CustomModelPrefix_ForCollectionProperty() public async Task FromQuery_CustomModelPrefix_ForCollectionProperty()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/FromQueryAttribute_Company/CreateDepartment?TestEmployees[0].EmployeeId=1234"; var url = "http://localhost/FromQueryAttribute_Company/CreateDepartment?TestEmployees[0].EmployeeId=1234";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -110,14 +99,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromQuery_NonExistingValueAddsValidationErrors_OnProperty_UsingCustomModelPrefix() public async Task FromQuery_NonExistingValueAddsValidationErrors_OnProperty_UsingCustomModelPrefix()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = var url =
"http://localhost/FromQueryAttribute_Company/ValidateDepartment?TestEmployees[0].Department=contoso"; "http://localhost/FromQueryAttribute_Company/ValidateDepartment?TestEmployees[0].Department=contoso";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();

View File

@ -1,12 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using ModelBindingWebSite; using ModelBindingWebSite;
using ModelBindingWebSite.Models; using ModelBindingWebSite.Models;
using Newtonsoft.Json; using Newtonsoft.Json;
@ -14,25 +11,24 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ModelBindingFromRouteTest public class ModelBindingFromRouteTest : IClassFixture<MvcTestFixture<ModelBindingWebSite.Startup>>
{ {
private const string SiteName = nameof(ModelBindingWebSite); public ModelBindingFromRouteTest(MvcTestFixture<ModelBindingWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task FromRoute_CustomModelPrefix_ForParameter() public async Task FromRoute_CustomModelPrefix_ForParameter()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// [FromRoute(Name = "customPrefix")] is used to apply a prefix // [FromRoute(Name = "customPrefix")] is used to apply a prefix
var url = var url = "http://localhost/FromRouteAttribute_Company/CreateEmployee/somename";
"http://localhost/FromRouteAttribute_Company/CreateEmployee/somename";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -44,15 +40,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromRoute_CustomModelPrefix_ForProperty() public async Task FromRoute_CustomModelPrefix_ForProperty()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// [FromRoute(Name = "EmployeeId")] is used to apply a prefix // [FromRoute(Name = "EmployeeId")] is used to apply a prefix
var url = var url = "http://localhost/FromRouteAttribute_Company/CreateEmployee/somename/1234";
"http://localhost/FromRouteAttribute_Company/CreateEmployee/somename/1234";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -65,12 +57,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FromRoute_NonExistingValueAddsValidationErrors_OnProperty_UsingCustomModelPrefix() public async Task FromRoute_NonExistingValueAddsValidationErrors_OnProperty_UsingCustomModelPrefix()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// [FromRoute(Name = "TestEmployees")] is used to apply a prefix // [FromRoute(Name = "TestEmployees")] is used to apply a prefix
var url = var url = "http://localhost/FromRouteAttribute_Company/ValidateDepartment/contoso";
"http://localhost/FromRouteAttribute_Company/ValidateDepartment/contoso";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
// No values. // No values.
@ -78,7 +66,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new FormUrlEncodedContent(nameValueCollection); request.Content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();

View File

@ -1,36 +1,33 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using ModelBindingWebSite.Models; using ModelBindingWebSite.Models;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ModelBindingModelBinderAttributeTest public class ModelBindingModelBinderAttributeTest : IClassFixture<MvcTestFixture<ModelBindingWebSite.Startup>>
{ {
private const string SiteName = nameof(ModelBindingWebSite); public ModelBindingModelBinderAttributeTest(MvcTestFixture<ModelBindingWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new ModelBindingWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new ModelBindingWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task ModelBinderAttribute_CustomModelPrefix() public async Task ModelBinderAttribute_CustomModelPrefix()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// [ModelBinder(Name = "customPrefix")] is used to apply a prefix // [ModelBinder(Name = "customPrefix")] is used to apply a prefix
var url = var url =
"http://localhost/ModelBinderAttribute_Company/GetCompany?customPrefix.Employees[0].Name=somename"; "http://localhost/ModelBinderAttribute_Company/GetCompany?customPrefix.Employees[0].Name=somename";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -44,14 +41,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ModelBinderAttribute_CustomModelPrefix_OnProperty() public async Task ModelBinderAttribute_CustomModelPrefix_OnProperty()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var url = "http://localhost/ModelBinderAttribute_Company/CreateCompany?employees[0].Alias=somealias";
var client = server.CreateClient();
var url =
"http://localhost/ModelBinderAttribute_Company/CreateCompany?employees[0].Alias=somealias";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -65,16 +58,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ModelBinderAttribute_WithPrefixOnParameter() public async Task ModelBinderAttribute_WithPrefixOnParameter()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// [ModelBinder(Name = "customPrefix")] is used to apply a prefix // [ModelBinder(Name = "customPrefix")] is used to apply a prefix
var url = var url = "http://localhost/ModelBinderAttribute_Product/GetBinderType_UseModelBinderOnType" +
"http://localhost/ModelBinderAttribute_Product/GetBinderType_UseModelBinderOnType" +
"?customPrefix.ProductId=5"; "?customPrefix.ProductId=5";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -87,15 +76,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ModelBinderAttribute_WithBinderOnParameter() public async Task ModelBinderAttribute_WithBinderOnParameter()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var url = "http://localhost/ModelBinderAttribute_Product/GetBinderType_UseModelBinder/" +
var client = server.CreateClient();
var url =
"http://localhost/ModelBinderAttribute_Product/GetBinderType_UseModelBinder/" +
"?model.productId=5"; "?model.productId=5";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -108,16 +93,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ModelBinderAttribute_WithBinderOnEnum() public async Task ModelBinderAttribute_WithBinderOnEnum()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var url = "http://localhost/ModelBinderAttribute_Product/ModelBinderAttribute_UseModelBinderOnEnum" +
var client = server.CreateClient();
var url =
"http://localhost/ModelBinderAttribute_Product/" +
"ModelBinderAttribute_UseModelBinderOnEnum" +
"?status=Shipped"; "?status=Shipped";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();

File diff suppressed because it is too large Load Diff

View File

@ -1,31 +1,28 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ModelMetadataAttributeTest public class ModelMetadataAttributeTest : IClassFixture<MvcTestFixture<ValidationWebSite.Startup>>
{ {
private const string SiteName = nameof(ValidationWebSite); public ModelMetadataAttributeTest(MvcTestFixture<ValidationWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new ValidationWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new ValidationWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task ModelMetaDataTypeAttribute_ValidBaseClass_EmptyResponseBody() public async Task ModelMetaDataTypeAttribute_ValidBaseClass_EmptyResponseBody()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{ \"Name\": \"MVC\", \"Contact\":\"4258959019\", \"Category\":\"Technology\"," + var input = "{ \"Name\": \"MVC\", \"Contact\":\"4258959019\", \"Category\":\"Technology\"," +
"\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 21, \"ProductDetails\": {\"Detail1\": \"d1\"," + "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 21, \"ProductDetails\": {\"Detail1\": \"d1\"," +
" \"Detail2\": \"d2\", \"Detail3\": \"d3\"}}"; " \"Detail2\": \"d2\", \"Detail3\": \"d3\"}}";
@ -34,7 +31,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata"; var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata";
// Act // Act
var response = await client.PostAsync(url, content); var response = await Client.PostAsync(url, content);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -45,15 +42,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ModelMetaDataTypeAttribute_InvalidPropertiesAndSubPropertiesOnBaseClass_ReturnsErrors() public async Task ModelMetaDataTypeAttribute_InvalidPropertiesAndSubPropertiesOnBaseClass_ReturnsErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{ \"Price\": 2, \"ProductDetails\": {\"Detail1\": \"d1\"}}"; var input = "{ \"Price\": 2, \"ProductDetails\": {\"Detail1\": \"d1\"}}";
var content = new StringContent(input, Encoding.UTF8, "application/json"); var content = new StringContent(input, Encoding.UTF8, "application/json");
var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata"; var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata";
// Act // Act
var response = await client.PostAsync(url, content); var response = await Client.PostAsync(url, content);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -76,8 +71,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ModelMetaDataTypeAttribute_InvalidComplexTypePropertyOnBaseClass_ReturnsErrors() public async Task ModelMetaDataTypeAttribute_InvalidComplexTypePropertyOnBaseClass_ReturnsErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{ \"Contact\":\"4255678765\", \"Category\":\"Technology\"," + var input = "{ \"Contact\":\"4255678765\", \"Category\":\"Technology\"," +
"\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 21 }"; "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 21 }";
var content = new StringContent(input, Encoding.UTF8, "application/json"); var content = new StringContent(input, Encoding.UTF8, "application/json");
@ -85,7 +78,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata"; var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata";
// Act // Act
var response = await client.PostAsync(url, content); var response = await Client.PostAsync(url, content);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -101,8 +94,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ModelMetaDataTypeAttribute_InvalidClassAttributeOnBaseClass_ReturnsErrors() public async Task ModelMetaDataTypeAttribute_InvalidClassAttributeOnBaseClass_ReturnsErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{ \"Contact\":\"4258959019\", \"Category\":\"Technology\"," + var input = "{ \"Contact\":\"4258959019\", \"Category\":\"Technology\"," +
"\"CompanyName\":\"Microsoft\", \"Country\":\"UK\",\"Price\": 21, \"ProductDetails\": {\"Detail1\": \"d1\"," + "\"CompanyName\":\"Microsoft\", \"Country\":\"UK\",\"Price\": 21, \"ProductDetails\": {\"Detail1\": \"d1\"," +
" \"Detail2\": \"d2\", \"Detail3\": \"d3\"}}"; " \"Detail2\": \"d2\", \"Detail3\": \"d3\"}}";
@ -112,7 +103,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata"; var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata";
// Act // Act
var response = await client.PostAsync(url, content); var response = await Client.PostAsync(url, content);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -125,8 +116,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ModelMetaDataTypeAttribute_ValidDerivedClass_EmptyResponseBody() public async Task ModelMetaDataTypeAttribute_ValidDerivedClass_EmptyResponseBody()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{ \"Name\": \"MVC\", \"Contact\":\"4258959019\", \"Category\":\"Technology\"," + var input = "{ \"Name\": \"MVC\", \"Contact\":\"4258959019\", \"Category\":\"Technology\"," +
"\"CompanyName\":\"Microsoft\", \"Country\":\"USA\", \"Version\":\"2\"," + "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\", \"Version\":\"2\"," +
"\"DatePurchased\": \"/Date(1297246301973)/\", \"Price\" : \"110\" }"; "\"DatePurchased\": \"/Date(1297246301973)/\", \"Price\" : \"110\" }";
@ -135,7 +124,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var url = "http://localhost/ModelMetadataTypeValidation/ValidateSoftwareViewModelIncludingMetadata"; var url = "http://localhost/ModelMetadataTypeValidation/ValidateSoftwareViewModelIncludingMetadata";
// Act // Act
var response = await client.PostAsync(url, content); var response = await Client.PostAsync(url, content);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -146,8 +135,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ModelMetaDataTypeAttribute_InvalidPropertiesOnDerivedClass_ReturnsErrors() public async Task ModelMetaDataTypeAttribute_InvalidPropertiesOnDerivedClass_ReturnsErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{ \"Name\": \"MVC\", \"Contact\":\"425-895-9019\", \"Category\":\"Technology\"," + var input = "{ \"Name\": \"MVC\", \"Contact\":\"425-895-9019\", \"Category\":\"Technology\"," +
"\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 2}"; "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 2}";
var content = new StringContent(input, Encoding.UTF8, "application/json"); var content = new StringContent(input, Encoding.UTF8, "application/json");
@ -155,7 +142,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var url = "http://localhost/ModelMetadataTypeValidation/ValidateSoftwareViewModelIncludingMetadata"; var url = "http://localhost/ModelMetadataTypeValidation/ValidateSoftwareViewModelIncludingMetadata";
// Act // Act
var response = await client.PostAsync(url, content); var response = await Client.PostAsync(url, content);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -169,8 +156,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ModelMetaDataTypeAttribute_InvalidClassAttributeOnBaseClassProduct_ReturnsErrors() public async Task ModelMetaDataTypeAttribute_InvalidClassAttributeOnBaseClassProduct_ReturnsErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{ \"Contact\":\"4258959019\", \"Category\":\"Technology\"," + var input = "{ \"Contact\":\"4258959019\", \"Category\":\"Technology\"," +
"\"CompanyName\":\"Microsoft\", \"Country\":\"UK\",\"Version\":\"2\"," + "\"CompanyName\":\"Microsoft\", \"Country\":\"UK\",\"Version\":\"2\"," +
"\"DatePurchased\": \"/Date(1297246301973)/\", \"Price\" : \"110\" }"; "\"DatePurchased\": \"/Date(1297246301973)/\", \"Price\" : \"110\" }";
@ -179,7 +164,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var url = "http://localhost/ModelMetadataTypeValidation/ValidateSoftwareViewModelIncludingMetadata"; var url = "http://localhost/ModelMetadataTypeValidation/ValidateSoftwareViewModelIncludingMetadata";
// Act // Act
var response = await client.PostAsync(url, content); var response = await Client.PostAsync(url, content);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();

View File

@ -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<TStartup> : MvcTestFixture<TStartup>
where TStartup : new()
{
protected override void AddAdditionalServices(IServiceCollection services)
{
services.AddTransient<IHtmlEncoder, CommonTestEncoder>();
services.AddTransient<IJavaScriptStringEncoder, CommonTestEncoder>();
services.AddTransient<IUrlEncoder, CommonTestEncoder>();
}
}
}

View File

@ -1,30 +1,25 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Mvc.Formatters.Xml;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class MvcSampleTests public class MvcSampleTests : IClassFixture<MvcTestFixture<MvcSample.Web.Startup>>
{ {
private const string SiteName = nameof(MvcSample) + "." + nameof(MvcSample.Web); public MvcSampleTests(MvcTestFixture<MvcSample.Web.Startup> fixture)
{
Client = fixture.Client;
}
// Path relative to Mvc\\test\Microsoft.AspNet.Mvc.FunctionalTests public HttpClient Client { get; }
private readonly static string SamplesFolder = Path.Combine("..", "..", "samples");
private readonly Action<IApplicationBuilder> _app = new MvcSample.Web.Startup().Configure;
private readonly Func<IServiceCollection, IServiceProvider> _configureServices = new MvcSample.Web.Startup().ConfigureServices;
[Theory] [Theory]
[InlineData("")] // Shared/MyView.cshtml [InlineData("")] // Shared/MyView.cshtml
@ -41,12 +36,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("/Home/ValidationSummary")] // Home/ValidationSummary.cshtml [InlineData("/Home/ValidationSummary")] // Home/ValidationSummary.cshtml
public async Task Home_Pages_ReturnSuccess(string path) public async Task Home_Pages_ReturnSuccess(string path)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices); var response = await Client.GetAsync("http://localhost" + path);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost" + path);
// Assert // Assert
Assert.NotNull(response); Assert.NotNull(response);
@ -69,14 +60,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task FormUrlEncoded_ReturnsAppropriateResults(string input, string expectedOutput) public async Task FormUrlEncoded_ReturnsAppropriateResults(string input, string expectedOutput)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/FormUrlEncoded/IsValidPerson"); var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/FormUrlEncoded/IsValidPerson");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Content = new StringContent(input, Encoding.UTF8, "application/x-www-form-urlencoded"); request.Content = new StringContent(input, Encoding.UTF8, "application/x-www-form-urlencoded");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(expectedOutput, await response.Content.ReadAsStringAsync()); Assert.Equal(expectedOutput, await response.Content.ReadAsStringAsync());
@ -85,12 +74,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FormUrlEncoded_Index_ReturnSuccess() public async Task FormUrlEncoded_Index_ReturnSuccess()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices); var response = await Client.GetAsync("http://localhost/FormUrlEncoded");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/FormUrlEncoded");
// Assert // Assert
Assert.NotNull(response); Assert.NotNull(response);
@ -100,12 +85,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task Home_NotFoundAction_Returns404() public async Task Home_NotFoundAction_Returns404()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices); var response = await Client.GetAsync("http://localhost/Home/NotFound");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/NotFound");
// Assert // Assert
Assert.NotNull(response); Assert.NotNull(response);
@ -118,13 +99,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task Home_CreateUser_ReturnsXmlBasedOnAcceptHeader() public async Task Home_CreateUser_ReturnsXmlBasedOnAcceptHeader()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/ReturnUser"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Home/ReturnUser");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.NotNull(response); Assert.NotNull(response);
@ -145,12 +124,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("http://localhost/Filters/NotGrantedClaim", HttpStatusCode.Unauthorized)] [InlineData("http://localhost/Filters/NotGrantedClaim", HttpStatusCode.Unauthorized)]
public async Task FiltersController_Tests(string url, HttpStatusCode statusCode) public async Task FiltersController_Tests(string url, HttpStatusCode statusCode)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices); var response = await Client.GetAsync(url);
var client = server.CreateClient();
// Act
var response = await client.GetAsync(url);
// Assert // Assert
Assert.NotNull(response); Assert.NotNull(response);
@ -160,12 +135,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task FiltersController_Crash_ThrowsException() public async Task FiltersController_Crash_ThrowsException()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, SamplesFolder, _configureServices); var response = await Client.GetAsync("http://localhost/Filters/Crash?message=HelloWorld");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Filters/Crash?message=HelloWorld");
// Assert // Assert
Assert.NotNull(response); Assert.NotNull(response);

View File

@ -2,62 +2,105 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Reflection; using System.Reflection;
using System.Runtime.Versioning;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Mvc.Actions; using Microsoft.AspNet.Mvc.Actions;
using Microsoft.AspNet.TestHost; using Microsoft.AspNet.TestHost;
using Microsoft.AspNet.Testing;
using Microsoft.Dnx.Runtime; using Microsoft.Dnx.Runtime;
using Microsoft.Dnx.Runtime.Infrastructure; using Microsoft.Dnx.Runtime.Infrastructure;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Microsoft.Framework.Logging.Testing;
namespace Microsoft.AspNet.Mvc.FunctionalTests 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 startupTypeInfo = startupInstance.GetType().GetTypeInfo();
var configureMethod = (Action<IApplicationBuilder>)startupTypeInfo var configureApplication = (Action<IApplicationBuilder>)startupTypeInfo
.DeclaredMethods .DeclaredMethods
.First(m => m.Name == "Configure") .FirstOrDefault(m => m.Name == "Configure" && m.GetParameters().Length == 1)
.CreateDelegate(typeof(Action<IApplicationBuilder>), startupInstance); ?.CreateDelegate(typeof(Action<IApplicationBuilder>), startupInstance);
if (configureApplication == null)
var configureServices = (Action<IServiceCollection>)startupTypeInfo {
var configureWithLogger = (Action<IApplicationBuilder, ILoggerFactory>)startupTypeInfo
.DeclaredMethods .DeclaredMethods
.First(m => m.Name == "ConfigureServices") .FirstOrDefault(m => m.Name == "Configure" && m.GetParameters().Length == 2)
.CreateDelegate(typeof(Action<IServiceCollection>), startupInstance); ?.CreateDelegate(typeof(Action<IApplicationBuilder, ILoggerFactory>), startupInstance);
Debug.Assert(configureWithLogger != null);
Server = TestServer.Create( configureApplication = application => configureWithLogger(application, NullLoggerFactory.Instance);
CallContextServiceLocator.Locator.ServiceProvider,
configureMethod,
configureServices: InitializeServices(startupTypeInfo.Assembly, configureServices));
Client = Server.CreateClient();
Client.BaseAddress = new Uri("http://localhost");
} }
public TestServer Server { get; } var buildServices = (Func<IServiceCollection, IServiceProvider>)startupTypeInfo
.DeclaredMethods
.FirstOrDefault(m => m.Name == "ConfigureServices" && m.ReturnType == typeof(IServiceProvider))
?.CreateDelegate(typeof(Func<IServiceCollection, IServiceProvider>), startupInstance);
if (buildServices == null)
{
var configureServices = (Action<IServiceCollection>)startupTypeInfo
.DeclaredMethods
.FirstOrDefault(m => m.Name == "ConfigureServices" && m.ReturnType == typeof(void))
?.CreateDelegate(typeof(Action<IServiceCollection>), startupInstance);
Debug.Assert(configureServices != null);
buildServices = services =>
{
configureServices(services);
return services.BuildServiceProvider();
};
}
// 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 HttpClient Client { get; } public HttpClient Client { get; }
public void Dispose() public void Dispose()
{ {
Client.Dispose(); Client.Dispose();
Server.Dispose(); _server.Dispose();
} }
public static Func<IServiceCollection, IServiceProvider> InitializeServices( protected virtual void AddAdditionalServices(IServiceCollection services)
{
}
private Func<IServiceCollection, IServiceProvider> InitializeServices(
Assembly startupAssembly, Assembly startupAssembly,
Action<IServiceCollection> configureServices) Func<IServiceCollection, IServiceProvider> buildServices)
{ {
var applicationServices = CallContextServiceLocator.Locator.ServiceProvider; var applicationServices = CallContextServiceLocator.Locator.ServiceProvider;
var libraryManager = applicationServices.GetRequiredService<ILibraryManager>(); var libraryManager = applicationServices.GetRequiredService<ILibraryManager>();
// 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 applicationName = startupAssembly.GetName().Name;
var library = libraryManager.GetLibrary(applicationName); var library = libraryManager.GetLibrary(applicationName);
var applicationRoot = Path.GetDirectoryName(library.Path); var applicationRoot = Path.GetDirectoryName(library.Path);
@ -73,47 +116,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
hostingEnvironment.Initialize(applicationRoot, "Production"); hostingEnvironment.Initialize(applicationRoot, "Production");
services.AddInstance<IHostingEnvironment>(hostingEnvironment); services.AddInstance<IHostingEnvironment>(hostingEnvironment);
// Inject a custom assembly provider. Overrides AddMvc() because that uses TryAdd().
var assemblyProvider = new StaticAssemblyProvider(); var assemblyProvider = new StaticAssemblyProvider();
assemblyProvider.CandidateAssemblies.Add(startupAssembly); assemblyProvider.CandidateAssemblies.Add(startupAssembly);
services.AddInstance<IAssemblyProvider>(assemblyProvider); services.AddInstance<IAssemblyProvider>(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);
}
}
} }
} }

View File

@ -3,10 +3,10 @@
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class MvcFixture<TStartup> : MvcFixture public class MvcTestFixture<TStartup> : MvcTestFixture
where TStartup : new() where TStartup : new()
{ {
public MvcFixture() public MvcTestFixture()
: base(new TStartup()) : base(new TStartup())
{ {
} }

View File

@ -1,22 +1,22 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Threading.Tasks; using System.Threading.Tasks;
using ContentNegotiationWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class OutputFormatterTest public class OutputFormatterTest : IClassFixture<MvcTestFixture<ContentNegotiationWebSite.Startup>>
{ {
private const string SiteName = nameof(ContentNegotiationWebSite); public OutputFormatterTest(MvcTestFixture<ContentNegotiationWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("ReturnTaskOfString")] [InlineData("ReturnTaskOfString")]
@ -26,13 +26,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task StringOutputFormatter_ForStringValues_GetsSelectedReturnsTextPlainContentType(string actionName) public async Task StringOutputFormatter_ForStringValues_GetsSelectedReturnsTextPlainContentType(string actionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse("text/plain;charset=utf-8"); var expectedContentType = MediaTypeHeaderValue.Parse("text/plain;charset=utf-8");
var expectedBody = actionName; var expectedBody = actionName;
// Act // Act
var response = await client.GetAsync("http://localhost/TextPlain/" + actionName); var response = await Client.GetAsync("http://localhost/TextPlain/" + actionName);
// Assert // Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
@ -46,12 +44,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonOutputFormatter_ForNonStringValue_GetsSelected(string actionName) public async Task JsonOutputFormatter_ForNonStringValue_GetsSelected(string actionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8"); var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
// Act // Act
var response = await client.GetAsync("http://localhost/TextPlain/" + actionName); var response = await Client.GetAsync("http://localhost/TextPlain/" + actionName);
// Assert // Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType); Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
@ -62,12 +58,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("ReturnVoid")] [InlineData("ReturnVoid")]
public async Task NoContentFormatter_ForVoidAndTaskReturnType_DoesNotRun(string actionName) public async Task NoContentFormatter_ForVoidAndTaskReturnType_DoesNotRun(string actionName)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/NoContent/" + actionName);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/NoContent/" + actionName);
// Assert // Assert
Assert.Null(response.Content.Headers.ContentType); Assert.Null(response.Content.Headers.ContentType);
@ -84,12 +76,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("ReturnObject_NullValue")] [InlineData("ReturnObject_NullValue")]
public async Task NoContentFormatter_ForNullValue_ByDefault_GetsSelectedAndWritesResponse(string actionName) public async Task NoContentFormatter_ForNullValue_ByDefault_GetsSelectedAndWritesResponse(string actionName)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/NoContent/" + actionName);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/NoContent/" + actionName);
// Assert // Assert
Assert.Null(response.Content.Headers.ContentType); Assert.Null(response.Content.Headers.ContentType);
@ -107,12 +95,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task public async Task
NoContentFormatter_ForNullValue_AndTreatNullAsNoContentFlagSetToFalse_DoesNotGetSelected(string actionName) NoContentFormatter_ForNullValue_AndTreatNullAsNoContentFlagSetToFalse_DoesNotGetSelected(string actionName)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/NoContentDoNotTreatNullValueAsNoContent/" +
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/NoContentDoNotTreatNullValueAsNoContent/" +
actionName); actionName);
// Assert // Assert

View File

@ -5,6 +5,7 @@ using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Http;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
@ -17,13 +18,20 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class PrecompilationTest public class PrecompilationTest : IClassFixture<MvcTestFixture<PrecompilationWebSite.Startup>>
{ {
private const string SiteName = nameof(PrecompilationWebSite); private const string SiteName = nameof(PrecompilationWebSite);
private static readonly TimeSpan _cacheDelayInterval = TimeSpan.FromSeconds(1); private static readonly TimeSpan _cacheDelayInterval = TimeSpan.FromSeconds(1);
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; private readonly Action<IApplicationBuilder> _app = new Startup().Configure;
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices;
public PrecompilationTest(MvcTestFixture<PrecompilationWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[ConditionalFact] [ConditionalFact]
[FrameworkSkipCondition(RuntimeFrameworks.Mono)] [FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task PrecompiledView_RendersCorrectly() public async Task PrecompiledView_RendersCorrectly()
@ -90,11 +98,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
@"Value set inside DNXCORE50 " + assemblyNamePrefix; @"Value set inside DNXCORE50 " + assemblyNamePrefix;
#endif #endif
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // 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(); var responseContent = await response.Content.ReadAsStringAsync();
// Assert // 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=""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."" " + @"data-val-range-min=""10"" data-val-required=""The Age field is required."" " +
@"id=""Age"" name=""Age"" value="""" /><a href="""">Back to List</a></root>"; @"id=""Age"" name=""Age"" value="""" /><a href="""">Back to List</a></root>";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var response = await client.GetStringAsync("http://localhost/TagHelpers/Add"); var response = await Client.GetStringAsync("http://localhost/TagHelpers/Add");
// Assert // Assert
var responseLines = response.Split(new[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); var responseLines = response.Split(new[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
@ -131,11 +134,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Arrange // Arrange
var assemblyNamePrefix = GetAssemblyNamePrefix(); var assemblyNamePrefix = GetAssemblyNamePrefix();
var expected = @"<root>root-content</root>"; var expected = @"<root>root-content</root>";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var response = await client.GetStringAsync("http://localhost/TagHelpers/Remove"); var response = await Client.GetStringAsync("http://localhost/TagHelpers/Remove");
// Assert // Assert
var responseLines = response.Split(new[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); var responseLines = response.Split(new[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);

View File

@ -1,31 +1,29 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using RazorEmbeddedViewsWebSite;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class RazorEmbeddedViewsTest public class RazorEmbeddedViewsTest : IClassFixture<MvcTestFixture<RazorEmbeddedViewsWebSite.Startup>>
{ {
private const string SiteName = nameof(RazorEmbeddedViewsWebSite); public RazorEmbeddedViewsTest(MvcTestFixture<RazorEmbeddedViewsWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task RazorViewEngine_UsesFileProviderOnViewEngineOptionsToLocateViews() public async Task RazorViewEngine_UsesFileProviderOnViewEngineOptionsToLocateViews()
{ {
// Arrange // Arrange
var expectedMessage = "Hello test-user, this is /RazorEmbeddedViews_Home"; var expectedMessage = "Hello test-user, this is /RazorEmbeddedViews_Home";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // 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
Assert.Equal(expectedMessage, response); Assert.Equal(expectedMessage, response);
@ -36,12 +34,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expectedMessage = "Hello admin-user, this is /Restricted/RazorEmbeddedViews_Admin/Login"; 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"; var target = "http://localhost/Restricted/RazorEmbeddedViews_Admin/Login?AdminUser=admin-user";
// Act // Act
var response = await client.GetStringAsync(target); var response = await Client.GetStringAsync(target);
// Assert // Assert
Assert.Equal(expectedMessage, response); Assert.Equal(expectedMessage, response);

View File

@ -1,33 +1,31 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using RazorEmbeddedViewsWebSite;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// The EmbeddedFileSystem used by RazorEmbeddedViewsWebSite performs case sensitive lookups for files. // 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. // These tests verify that we correctly normalize route values when constructing view lookup paths.
public class RazorFileSystemCaseSensitivityTest public class RazorFileSystemCaseSensitivityTest : IClassFixture<MvcTestFixture<RazorEmbeddedViewsWebSite.Startup>>
{ {
private const string SiteName = nameof(RazorEmbeddedViewsWebSite); public RazorFileSystemCaseSensitivityTest(MvcTestFixture<RazorEmbeddedViewsWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task RazorViewEngine_NormalizesActionName_WhenLookingUpViewPaths() public async Task RazorViewEngine_NormalizesActionName_WhenLookingUpViewPaths()
{ {
// Arrange // Arrange
var expectedMessage = "Hello test-user, this is /RazorEmbeddedViews_Home"; var expectedMessage = "Hello test-user, this is /RazorEmbeddedViews_Home";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // 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
Assert.Equal(expectedMessage, response); Assert.Equal(expectedMessage, response);
@ -38,11 +36,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expectedMessage = "Hello test-user, this is /razorembeddedviews_home"; var expectedMessage = "Hello test-user, this is /razorembeddedviews_home";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // 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
Assert.Equal(expectedMessage, response); Assert.Equal(expectedMessage, response);
@ -53,12 +49,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expectedMessage = "Hello admin-user, this is /restricted/razorembeddedviews_admin/login"; 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"; var target = "http://localhost/restricted/razorembeddedviews_admin/login?AdminUser=admin-user";
// Act // Act
var response = await client.GetStringAsync(target); var response = await Client.GetStringAsync(target);
// Assert // Assert
Assert.Equal(expectedMessage, response); Assert.Equal(expectedMessage, response);

View File

@ -1,21 +1,22 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using RazorWebSite;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class RazorViewLocationSpecificationTest public class RazorViewLocationSpecificationTest : IClassFixture<MvcTestFixture<RazorWebSite.Startup>>
{ {
private const string BaseUrl = "http://localhost/ViewNameSpecification_Home/"; private const string BaseUrl = "http://localhost/ViewNameSpecification_Home/";
private const string SiteName = nameof(RazorWebSite);
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; public RazorViewLocationSpecificationTest(MvcTestFixture<RazorWebSite.Startup> fixture)
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; {
Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("LayoutSpecifiedWithPartialPathInViewStart")] [InlineData("LayoutSpecifiedWithPartialPathInViewStart")]
@ -24,15 +25,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("LayoutSpecifiedWithPartialPathInViewStart_ForViewSpecifiedWithAppRelativePathWithExtension")] [InlineData("LayoutSpecifiedWithPartialPathInViewStart_ForViewSpecifiedWithAppRelativePathWithExtension")]
public async Task PartialLayoutPaths_SpecifiedInViewStarts_GetResolvedByViewEngine(string action) public async Task PartialLayoutPaths_SpecifiedInViewStarts_GetResolvedByViewEngine(string action)
{ {
// Arrange
var expected = var expected =
@"<layout> @"<layout>
_ViewStart that specifies partial Layout _ViewStart that specifies partial Layout
</layout>"; </layout>";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync(BaseUrl + action); var body = await Client.GetStringAsync(BaseUrl + action);
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -45,14 +45,13 @@ _ViewStart that specifies partial Layout
[InlineData("LayoutSpecifiedWithPartialPathInPageWithAppRelativePathWithExtension")] [InlineData("LayoutSpecifiedWithPartialPathInPageWithAppRelativePathWithExtension")]
public async Task PartialLayoutPaths_SpecifiedInPage_GetResolvedByViewEngine(string actionName) public async Task PartialLayoutPaths_SpecifiedInPage_GetResolvedByViewEngine(string actionName)
{ {
// Arrange
var expected = var expected =
@"<non-shared>Layout specified in page @"<non-shared>Layout specified in page
</non-shared>"; </non-shared>";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync(BaseUrl + actionName); var body = await Client.GetStringAsync(BaseUrl + actionName);
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -63,14 +62,13 @@ _ViewStart that specifies partial Layout
[InlineData("LayoutSpecifiedWithNonPartialPathWithExtension")] [InlineData("LayoutSpecifiedWithNonPartialPathWithExtension")]
public async Task NonPartialLayoutPaths_GetResolvedByViewEngine(string actionName) public async Task NonPartialLayoutPaths_GetResolvedByViewEngine(string actionName)
{ {
// Arrange
var expected = var expected =
@"<non-shared>Page With Non Partial Layout @"<non-shared>Page With Non Partial Layout
</non-shared>"; </non-shared>";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync(BaseUrl + actionName); var body = await Client.GetStringAsync(BaseUrl + actionName);
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -82,16 +80,15 @@ _ViewStart that specifies partial Layout
[InlineData("ViewWithPartial_SpecifiedWithAbsoluteNameAndExtension")] [InlineData("ViewWithPartial_SpecifiedWithAbsoluteNameAndExtension")]
public async Task PartialsCanBeSpecifiedWithPartialPath(string actionName) public async Task PartialsCanBeSpecifiedWithPartialPath(string actionName)
{ {
// Arrange
var expected = var expected =
@"<layout> @"<layout>
Non Shared Partial Non Shared Partial
</layout>"; </layout>";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync(BaseUrl + actionName); var body = await Client.GetStringAsync(BaseUrl + actionName);
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);

View File

@ -1,26 +1,26 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class RemoteAttributeValidationTest public class RemoteAttributeValidationTest : IClassFixture<MvcTestFixture<ValidationWebSite.Startup>>
{ {
private const string SiteName = nameof(ValidationWebSite);
private static readonly Assembly _resourcesAssembly = private static readonly Assembly _resourcesAssembly =
typeof(RemoteAttributeValidationTest).GetTypeInfo().Assembly; typeof(RemoteAttributeValidationTest).GetTypeInfo().Assembly;
private readonly Action<IApplicationBuilder> _app = new ValidationWebSite.Startup().Configure; public RemoteAttributeValidationTest(MvcTestFixture<ValidationWebSite.Startup> fixture)
private readonly Action<IServiceCollection> _configureServices = new ValidationWebSite.Startup().ConfigureServices; {
Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("Aria", "/Aria")] [InlineData("Aria", "/Aria")]
@ -28,15 +28,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task RemoteAttribute_LeadsToExpectedValidationAttributes(string areaName, string pathSegment) public async Task RemoteAttribute_LeadsToExpectedValidationAttributes(string areaName, string pathSegment)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var outputFile = "compiler/resources/ValidationWebSite." + areaName + ".RemoteAttribute_Home.Create.html"; var outputFile = "compiler/resources/ValidationWebSite." + areaName + ".RemoteAttribute_Home.Create.html";
var expectedContent = var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
var url = "http://localhost" + pathSegment + "/RemoteAttribute_Home/Create"; var url = "http://localhost" + pathSegment + "/RemoteAttribute_Home/Create";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -65,13 +63,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
string expectedContent) string expectedContent)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost" + pathSegment + var url = "http://localhost" + pathSegment +
"/RemoteAttribute_Verify/IsIdAvailable?UserId1=Joe1&UserId2=Joe2&UserId3=Joe3&UserId4=Joe4"; "/RemoteAttribute_Verify/IsIdAvailable?UserId1=Joe1&UserId2=Joe2&UserId3=Joe3&UserId4=Joe4";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -89,8 +85,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
string expectedContent) string expectedContent)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost" + pathSegment + "/RemoteAttribute_Verify/IsIdAvailable"; var url = "http://localhost" + pathSegment + "/RemoteAttribute_Verify/IsIdAvailable";
var contentDictionary = new Dictionary<string, string> var contentDictionary = new Dictionary<string, string>
{ {
@ -102,7 +96,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var content = new FormUrlEncodedContent(contentDictionary); var content = new FormUrlEncodedContent(contentDictionary);
// Act // Act
var response = await client.PostAsync(url, content); var response = await Client.PostAsync(url, content);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -5,19 +5,20 @@ using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Each of these tests makes two requests, because we want each test to verify that the data is // 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. // PER-REQUEST and does not linger around to impact the next request.
public class RequestServicesTest public class RequestServicesTest : IClassFixture<MvcTestFixture<RequestServicesWebSite.Startup>>
{ {
private const string SiteName = nameof(RequestServicesWebSite); public RequestServicesTest(MvcTestFixture<RequestServicesWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new RequestServicesWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new RequestServicesWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("http://localhost/RequestScoped/FromController")] [InlineData("http://localhost/RequestScoped/FromController")]
@ -28,19 +29,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("http://localhost/Other/FromActionArgument")] [InlineData("http://localhost/Other/FromActionArgument")]
public async Task RequestServices(string url) 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++) for (var i = 0; i < 2; i++)
{ {
// Arrange
var requestId = Guid.NewGuid().ToString(); var requestId = Guid.NewGuid().ToString();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.TryAddWithoutValidation("RequestId", requestId); 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(); var body = (await response.Content.ReadAsStringAsync()).Trim();
Assert.Equal(requestId, body); Assert.Equal(requestId, body);
} }
@ -50,9 +49,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task RequestServices_TagHelper() public async Task RequestServices_TagHelper()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/Other/FromTagHelper"; var url = "http://localhost/Other/FromTagHelper";
// Act & Assert // Act & Assert
@ -62,7 +58,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.TryAddWithoutValidation("RequestId", requestId); request.Headers.TryAddWithoutValidation("RequestId", requestId);
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var body = (await response.Content.ReadAsStringAsync()).Trim(); var body = (await response.Content.ReadAsStringAsync()).Trim();
@ -75,9 +71,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task RequestServices_ActionConstraint() public async Task RequestServices_ActionConstraint()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/Other/FromActionConstraint"; var url = "http://localhost/Other/FromActionConstraint";
// Act & Assert // Act & Assert
@ -85,7 +78,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var request1 = new HttpRequestMessage(HttpMethod.Get, url); var request1 = new HttpRequestMessage(HttpMethod.Get, url);
request1.Headers.TryAddWithoutValidation("RequestId", requestId1); request1.Headers.TryAddWithoutValidation("RequestId", requestId1);
var response1 = await client.SendAsync(request1); var response1 = await Client.SendAsync(request1);
var body1 = (await response1.Content.ReadAsStringAsync()).Trim(); var body1 = (await response1.Content.ReadAsStringAsync()).Trim();
Assert.Equal(requestId1, body1); Assert.Equal(requestId1, body1);
@ -94,7 +87,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var request2 = new HttpRequestMessage(HttpMethod.Get, url); var request2 = new HttpRequestMessage(HttpMethod.Get, url);
request2.Headers.TryAddWithoutValidation("RequestId", requestId2); request2.Headers.TryAddWithoutValidation("RequestId", requestId2);
var response2 = await client.SendAsync(request2); var response2 = await Client.SendAsync(request2);
Assert.Equal(HttpStatusCode.NotFound, response2.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response2.StatusCode);
} }
} }

View File

@ -1,24 +1,24 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Mvc.Formatters.Xml;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class RespectBrowserAcceptHeaderTests public class RespectBrowserAcceptHeaderTests : IClassFixture<MvcTestFixture<FormatterWebSite.Startup>>
{ {
private const string SiteName = nameof(FormatterWebSite); public RespectBrowserAcceptHeaderTests(MvcTestFixture<FormatterWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new FormatterWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new FormatterWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("application/xml,*/*;0.2")] [InlineData("application/xml,*/*;0.2")]
@ -26,12 +26,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task AllMediaRangeAcceptHeader_FirstFormatterInListWritesResponse(string acceptHeader) public async Task AllMediaRangeAcceptHeader_FirstFormatterInListWritesResponse(string acceptHeader)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var request = RequestWithAccept("http://localhost/RespectBrowserAcceptHeader/EmployeeInfo", acceptHeader);
var client = server.CreateClient();
client.DefaultRequestHeaders.Add("Accept", acceptHeader);
// Act // Act
var response = await client.GetAsync("http://localhost/RespectBrowserAcceptHeader/EmployeeInfo"); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -50,15 +48,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task AllMediaRangeAcceptHeader_ProducesAttributeIsHonored(string acceptHeader) public async Task AllMediaRangeAcceptHeader_ProducesAttributeIsHonored(string acceptHeader)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var request = RequestWithAccept(
var client = server.CreateClient(); "http://localhost/RespectBrowserAcceptHeader/EmployeeInfoWithProduces",
client.DefaultRequestHeaders.Add("Accept", acceptHeader); acceptHeader);
var expectedResponseData = "<RespectBrowserAcceptHeaderController.Employee xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" + var expectedResponseData =
"<RespectBrowserAcceptHeaderController.Employee xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns=\"http://schemas.datacontract.org/2004/07/FormatterWebSite.Controllers\"><Id>20</Id><Name>Mike" + " xmlns=\"http://schemas.datacontract.org/2004/07/FormatterWebSite.Controllers\"><Id>20</Id><Name>Mike" +
"</Name></RespectBrowserAcceptHeaderController.Employee>"; "</Name></RespectBrowserAcceptHeaderController.Employee>";
// Act // Act
var response = await client.GetAsync("http://localhost/RespectBrowserAcceptHeader/EmployeeInfoWithProduces"); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -77,16 +76,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task AllMediaRangeAcceptHeader_WithContentTypeHeader_ContentTypeIsHonored(string acceptHeader) public async Task AllMediaRangeAcceptHeader_WithContentTypeHeader_ContentTypeIsHonored(string acceptHeader)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var requestData =
var client = server.CreateClient(); "<RespectBrowserAcceptHeaderController.Employee xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" +
client.DefaultRequestHeaders.Add("Accept", acceptHeader);
var requestData = "<RespectBrowserAcceptHeaderController.Employee xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns=\"http://schemas.datacontract.org/2004/07/FormatterWebSite.Controllers\"><Id>35</Id><Name>Jimmy" + " xmlns=\"http://schemas.datacontract.org/2004/07/FormatterWebSite.Controllers\"><Id>35</Id><Name>Jimmy" +
"</Name></RespectBrowserAcceptHeaderController.Employee>"; "</Name></RespectBrowserAcceptHeaderController.Employee>";
var request = RequestWithAccept("http://localhost/RespectBrowserAcceptHeader/CreateEmployee", acceptHeader);
request.Content = new StringContent(requestData, Encoding.UTF8, "application/xml");
request.Method = HttpMethod.Post;
// Act // Act
var response = await client.PostAsync("http://localhost/RespectBrowserAcceptHeader/CreateEmployee", var response = await Client.SendAsync(request);
new StringContent(requestData, Encoding.UTF8, "application/xml"));
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -96,5 +95,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var responseData = await response.Content.ReadAsStringAsync(); var responseData = await response.Content.ReadAsStringAsync();
Assert.Equal(requestData, responseData); 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;
}
} }
} }

View File

@ -4,29 +4,26 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using ResponseCacheWebSite;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ResponseCacheTest public class ResponseCacheTest : IClassFixture<MvcTestFixture<ResponseCacheWebSite.Startup>>
{ {
private const string SiteName = nameof(ResponseCacheWebSite); public ResponseCacheTest(MvcTestFixture<ResponseCacheWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task ResponseCache_SetsAllHeaders() public async Task ResponseCache_SetsAllHeaders()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/CacheHeaders/Index");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/CacheHeaders/Index");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -50,12 +47,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[MemberData(nameof(CacheControlData))] [MemberData(nameof(CacheControlData))]
public async Task ResponseCache_SetsDifferentCacheControlHeaders(string url, string expected) public async Task ResponseCache_SetsDifferentCacheControlHeaders(string url, string expected)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(url);
var client = server.CreateClient();
// Act
var response = await client.GetAsync(url);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -65,13 +58,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task SetsHeadersForAllActionsOfClass() public async Task SetsHeadersForAllActionsOfClass()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response1 = await Client.GetAsync("http://localhost/ClassLevelCache/GetHelloWorld");
var client = server.CreateClient(); var response2 = await Client.GetAsync("http://localhost/ClassLevelCache/GetFooBar");
// Act
var response1 = await client.GetAsync("http://localhost/ClassLevelCache/GetHelloWorld");
var response2 = await client.GetAsync("http://localhost/ClassLevelCache/GetFooBar");
// Assert // Assert
var data = Assert.Single(response1.Headers.GetValues("Cache-control")); var data = Assert.Single(response1.Headers.GetValues("Cache-control"));
@ -88,12 +77,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task HeadersSetInActionOverridesTheOnesInClass() public async Task HeadersSetInActionOverridesTheOnesInClass()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ClassLevelCache/ConflictExistingHeader");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ClassLevelCache/ConflictExistingHeader");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -103,12 +88,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task HeadersToNotCacheAParticularAction() public async Task HeadersToNotCacheAParticularAction()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ClassLevelCache/DoNotCacheThisAction");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ClassLevelCache/DoNotCacheThisAction");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -118,12 +99,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ClassLevelHeadersAreUnsetByActionLevelHeaders() public async Task ClassLevelHeadersAreUnsetByActionLevelHeaders()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ClassLevelNoStore/CacheThisAction");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ClassLevelNoStore/CacheThisAction");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Vary")); var data = Assert.Single(response.Headers.GetValues("Vary"));
@ -138,12 +115,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task SetsCacheControlPublicByDefault() public async Task SetsCacheControlPublicByDefault()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/CacheHeaders/SetsCacheControlPublicByDefault");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/CacheHeaders/SetsCacheControlPublicByDefault");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -153,13 +126,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ThrowsWhenDurationIsNotSet() public async Task ThrowsWhenDurationIsNotSet()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>( var ex = await Assert.ThrowsAsync<InvalidOperationException>(
() => client.GetAsync("http://localhost/CacheHeaders/ThrowsWhenDurationIsNotSet")); () => Client.GetAsync("http://localhost/CacheHeaders/ThrowsWhenDurationIsNotSet"));
Assert.Equal( Assert.Equal(
"If the 'NoStore' property is not set to true, 'Duration' property must be specified.", "If the 'NoStore' property is not set to true, 'Duration' property must be specified.",
ex.Message); ex.Message);
@ -169,12 +138,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResponseCache_SetsAllHeaders_FromCacheProfile() public async Task ResponseCache_SetsAllHeaders_FromCacheProfile()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/CacheProfiles/PublicCache30Sec");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/CacheProfiles/PublicCache30Sec");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -184,12 +149,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResponseCache_SetsAllHeaders_ChosesTheRightProfile() public async Task ResponseCache_SetsAllHeaders_ChosesTheRightProfile()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/CacheProfiles/PrivateCache30Sec");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/CacheProfiles/PrivateCache30Sec");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -199,12 +160,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResponseCache_SetsNoCacheHeaders() public async Task ResponseCache_SetsNoCacheHeaders()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/CacheProfiles/NoCache");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/CacheProfiles/NoCache");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -216,12 +173,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResponseCache_AddsHeaders() public async Task ResponseCache_AddsHeaders()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/CacheProfiles/CacheProfileAddParameter");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/CacheProfiles/CacheProfileAddParameter");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -233,12 +186,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResponseCache_ModifiesHeaders() public async Task ResponseCache_ModifiesHeaders()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/CacheProfiles/CacheProfileOverride");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/CacheProfiles/CacheProfileOverride");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -248,12 +197,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResponseCache_FallbackToFilter_IfNoAttribute() public async Task ResponseCache_FallbackToFilter_IfNoAttribute()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/CacheProfiles/FallbackToFilter");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/CacheProfiles/FallbackToFilter");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -265,12 +210,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResponseCacheAttribute_OnAction_OverridesTheValuesOnClass() public async Task ResponseCacheAttribute_OnAction_OverridesTheValuesOnClass()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/ClassLevelNoStore/CacheThisActionWithProfileSettings");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/ClassLevelNoStore/CacheThisActionWithProfileSettings");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Vary")); var data = Assert.Single(response.Headers.GetValues("Vary"));
@ -286,12 +227,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResponseCacheAttribute_OverridesProfileDuration_FromAttributeProperty() public async Task ResponseCacheAttribute_OverridesProfileDuration_FromAttributeProperty()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecTo15Sec");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecTo15Sec");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -301,12 +238,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResponseCacheAttribute_OverridesProfileLocation_FromAttributeProperty() public async Task ResponseCacheAttribute_OverridesProfileLocation_FromAttributeProperty()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecToPrivateCache");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecToPrivateCache");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -316,12 +249,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResponseCacheAttribute_OverridesProfileNoStore_FromAttributeProperty() public async Task ResponseCacheAttribute_OverridesProfileNoStore_FromAttributeProperty()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecToNoStore");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecToNoStore");
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("Cache-control")); var data = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -331,12 +260,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResponseCacheAttribute_OverridesProfileVaryBy_FromAttributeProperty() public async Task ResponseCacheAttribute_OverridesProfileVaryBy_FromAttributeProperty()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient(); "http://localhost/CacheProfileOverrides/PublicCache30SecWithVaryByAcceptToVaryByTest");
// Act
var response = await client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecWithVaryByAcceptToVaryByTest");
// Assert // Assert
var cacheControl = Assert.Single(response.Headers.GetValues("Cache-control")); var cacheControl = Assert.Single(response.Headers.GetValues("Cache-control"));
@ -348,12 +274,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ResponseCacheAttribute_OverridesProfileVaryBy_FromAttributeProperty_AndRemovesVaryHeader() public async Task ResponseCacheAttribute_OverridesProfileVaryBy_FromAttributeProperty_AndRemovesVaryHeader()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient(); "http://localhost/CacheProfileOverrides/PublicCache30SecWithVaryByAcceptToVaryByNone");
// Act
var response = await client.GetAsync("http://localhost/CacheProfileOverrides/PublicCache30SecWithVaryByAcceptToVaryByNone");
// Assert // Assert
var cacheControl = Assert.Single(response.Headers.GetValues("Cache-control")); var cacheControl = Assert.Single(response.Headers.GetValues("Cache-control"));

View File

@ -1,13 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using ModelBindingWebSite;
using ModelBindingWebSite.Models; using ModelBindingWebSite.Models;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; 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 /// 3) The server returns the bound object. We verify if the property specified by the expression in step 1
/// has the expected value. /// has the expected value.
/// </summary> /// </summary>
public class RoundTripTests public class RoundTripTests : IClassFixture<MvcTestFixture<ModelBindingWebSite.Startup>>
{ {
private const string SiteName = nameof(ModelBindingWebSite); public RoundTripTests(MvcTestFixture<ModelBindingWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
// Uses the expression p => p.Name
[Fact] [Fact]
public async Task RoundTrippedValues_GetsModelBound_ForSimpleExpressions() public async Task RoundTrippedValues_GetsModelBound_ForSimpleExpressions()
{ {
// Arrange // Arrange
var expected = "test-name"; var expected = "test-name";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var expression = await client.GetStringAsync("http://localhost/RoundTrip/GetPerson"); var expression = await Client.GetStringAsync("http://localhost/RoundTrip/GetPerson");
var keyValuePairs = new[] var keyValuePairs = new[]
{ {
new KeyValuePair<string, string>(expression, expected) new KeyValuePair<string, string>(expression, expected)
}; };
var result = await GetPerson(client, keyValuePairs); var result = await GetPerson(Client, keyValuePairs);
// Assert // Assert
Assert.Equal("Name", expression); Assert.Equal("Name", expression);
@ -56,16 +52,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = 40; var expected = 40;
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var expression = await client.GetStringAsync("http://localhost/RoundTrip/GetPersonParentAge"); var expression = await Client.GetStringAsync("http://localhost/RoundTrip/GetPersonParentAge");
var keyValuePairs = new[] var keyValuePairs = new[]
{ {
new KeyValuePair<string, string>(expression, expected.ToString()) new KeyValuePair<string, string>(expression, expected.ToString())
}; };
var result = await GetPerson(client, keyValuePairs); var result = await GetPerson(Client, keyValuePairs);
// Assert // Assert
Assert.Equal("Parent.Age", expression); Assert.Equal("Parent.Age", expression);
@ -78,16 +72,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = 12; var expected = 12;
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var expression = await client.GetStringAsync("http://localhost/RoundTrip/GetPersonDependentAge"); var expression = await Client.GetStringAsync("http://localhost/RoundTrip/GetPersonDependentAge");
var keyValuePairs = new[] var keyValuePairs = new[]
{ {
new KeyValuePair<string, string>(expression, expected.ToString()) new KeyValuePair<string, string>(expression, expected.ToString())
}; };
var result = await GetPerson(client, keyValuePairs); var result = await GetPerson(Client, keyValuePairs);
// Assert // Assert
Assert.Equal("Dependents[0].Age", expression); Assert.Equal("Dependents[0].Age", expression);
@ -99,17 +91,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task RoundTrippedValues_GetsModelBound_ForStringIndexedProperties() public async Task RoundTrippedValues_GetsModelBound_ForStringIndexedProperties()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = "6 feet"; var expected = "6 feet";
// Act // Act
var expression = await client.GetStringAsync("http://localhost/RoundTrip/GetPersonParentHeightAttribute"); var expression = await Client.GetStringAsync("http://localhost/RoundTrip/GetPersonParentHeightAttribute");
var keyValuePairs = new[] var keyValuePairs = new[]
{ {
new KeyValuePair<string, string>(expression, expected), new KeyValuePair<string, string>(expression, expected),
}; };
var result = await GetPerson(client, keyValuePairs); var result = await GetPerson(Client, keyValuePairs);
// Assert // Assert
Assert.Equal("Parent.Attributes[height]", expression); Assert.Equal("Parent.Attributes[height]", expression);
@ -122,16 +112,14 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
// Arrange // Arrange
var expected = "test-nested-name"; var expected = "test-nested-name";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var expression = await client.GetStringAsync("http://localhost/RoundTrip/GetDependentPersonName"); var expression = await Client.GetStringAsync("http://localhost/RoundTrip/GetDependentPersonName");
var keyValuePairs = new[] var keyValuePairs = new[]
{ {
new KeyValuePair<string, string>(expression, expected.ToString()) new KeyValuePair<string, string>(expression, expected.ToString())
}; };
var result = await GetPerson(client, keyValuePairs); var result = await GetPerson(Client, keyValuePairs);
// Assert // Assert
Assert.Equal("Dependents[0].Dependents[0].Name", expression); Assert.Equal("Dependents[0].Dependents[0].Name", expression);

View File

@ -1,36 +1,33 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Actions; using Microsoft.AspNet.Mvc.Actions;
using Microsoft.AspNet.Mvc.Routing; using Microsoft.AspNet.Mvc.Routing;
using Microsoft.AspNet.Routing; using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Routing.Template; using Microsoft.AspNet.Routing.Template;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class RouteDataTest public class RouteDataTest : IClassFixture<MvcTestFixture<BasicWebSite.Startup>>
{ {
private const string SiteName = nameof(BasicWebSite); public RouteDataTest(MvcTestFixture<BasicWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new BasicWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new BasicWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task RouteData_Routers_ConventionalRoute() public async Task RouteData_Routers_ConventionalRoute()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Routing/Conventional");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Routing/Conventional");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -38,7 +35,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<ResultData>(body); var result = JsonConvert.DeserializeObject<ResultData>(body);
Assert.Equal(new string[] Assert.Equal(
new string[]
{ {
typeof(RouteCollection).FullName, typeof(RouteCollection).FullName,
typeof(TemplateRoute).FullName, typeof(TemplateRoute).FullName,
@ -50,12 +48,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task RouteData_Routers_AttributeRoute() public async Task RouteData_Routers_AttributeRoute()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Routing/Attribute");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Routing/Attribute");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -80,10 +74,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task RouteData_DataTokens_FilterCanSetDataTokens() public async Task RouteData_DataTokens_FilterCanSetDataTokens()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Routing/DataTokens");
var client = server.CreateClient();
var response = await client.GetAsync("http://localhost/Routing/DataTokens");
// Guard // Guard
var body = await response.Content.ReadAsStringAsync(); 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"); Assert.Single(result.DataTokens, kvp => kvp.Key == "actionName" && ((string)kvp.Value) == "DataTokens");
// Act // Act
response = await client.GetAsync("http://localhost/Routing/Conventional"); response = await Client.GetAsync("http://localhost/Routing/Conventional");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -1,22 +1,22 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class RoutingLowercaseUrlTest
{
private const string SiteName = nameof(LowercaseUrlsWebSite);
// This website sets the generation of lowercase URLs to true // This website sets the generation of lowercase URLs to true
private readonly Action<IApplicationBuilder> _app = new LowercaseUrlsWebSite.Startup().Configure; public class RoutingLowercaseUrlTest : IClassFixture<MvcTestFixture<LowercaseUrlsWebSite.Startup>>
private readonly Action<IServiceCollection> _configureServices = new LowercaseUrlsWebSite.Startup().ConfigureServices; {
public RoutingLowercaseUrlTest(MvcTestFixture<LowercaseUrlsWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
// Generating lower case URL doesnt lowercase the query parameters // 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")] [InlineData("Api/Employee/GetEmployee/JohnDoe", "/api/employee/getemployee/johndoe")]
public async Task GenerateLowerCaseUrlsTests(string path, string expectedUrl) public async Task GenerateLowerCaseUrlsTests(string path, string expectedUrl)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/" + path);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/" + path);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

File diff suppressed because it is too large Load Diff

View File

@ -1,26 +1,26 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Mvc.Formatters.Xml;
using Microsoft.AspNet.Testing; using Microsoft.AspNet.Testing;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class SerializableErrorTests public class SerializableErrorTests : IClassFixture<MvcTestFixture<XmlFormattersWebSite.Startup>>
{ {
private const string SiteName = nameof(XmlFormattersWebSite); public SerializableErrorTests(MvcTestFixture<XmlFormattersWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new XmlFormattersWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new XmlFormattersWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
public static TheoryData AcceptHeadersData public static TheoryData AcceptHeadersData
{ {
@ -46,13 +46,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ModelStateErrors_AreSerialized(string acceptHeader) public async Task ModelStateErrors_AreSerialized(string acceptHeader)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SerializableError/ModelStateErrors");
var client = server.CreateClient(); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader));
var expectedXml = "<Error><key1>key1-error</key1><key2>The input was not valid.</key2></Error>"; var expectedXml = "<Error><key1>key1-error</key1><key2>The input was not valid.</key2></Error>";
// Act // 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.Equal(HttpStatusCode.OK, response.StatusCode);
@ -73,14 +72,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task PostedSerializableError_IsBound(string acceptHeader) public async Task PostedSerializableError_IsBound(string acceptHeader)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader));
var expectedXml = "<Error><key1>key1-error</key1><key2>The input was not valid.</key2></Error>"; var expectedXml = "<Error><key1>key1-error</key1><key2>The input was not valid.</key2></Error>";
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 // Act
var response = await client.PostAsync("http://localhost/SerializableError/LogErrors", requestContent); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -101,8 +99,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task IsReturnedInExpectedFormat(string acceptHeader) public async Task IsReturnedInExpectedFormat(string acceptHeader)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<Employee xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite.Models\">" + "<Employee xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite.Models\">" +
"<Id>2</Id><Name>foo</Name></Employee>"; "<Id>2</Id><Name>foo</Name></Employee>";
@ -114,7 +110,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content = new StringContent(input, Encoding.UTF8, "application/xml-dcs"); request.Content = new StringContent(input, Encoding.UTF8, "application/xml-dcs");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);

View File

@ -1,20 +1,20 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using FormatterWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class StreamOutputFormatterTest public class StreamOutputFormatterTest : IClassFixture<MvcTestFixture<FormatterWebSite.Startup>>
{ {
private const string SiteName = nameof(FormatterWebSite); public StreamOutputFormatterTest(MvcTestFixture<FormatterWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("SimpleMemoryStream", null)] [InlineData("SimpleMemoryStream", null)]
@ -24,12 +24,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("MemoryStreamOverridesContentTypeWithProduces", "text/plain")] [InlineData("MemoryStreamOverridesContentTypeWithProduces", "text/plain")]
public async Task StreamOutputFormatter_ReturnsAppropriateContentAndContentType(string actionName, string contentType) public async Task StreamOutputFormatter_ReturnsAppropriateContentAndContentType(string actionName, string contentType)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/Stream/" + actionName);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Stream/" + actionName);
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
// Assert // Assert

View File

@ -1,26 +1,27 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net; using System.Net;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class TagHelperSampleTest public class TagHelperSampleTest : IClassFixture<MvcTestFixture<TagHelperSample.Web.Startup>>
{ {
private const string SiteName = nameof(TagHelperSample) + "." + nameof(TagHelperSample.Web); public TagHelperSampleTest(MvcTestFixture<TagHelperSample.Web.Startup> fixture)
{
Client = fixture.Client;
}
// Path relative to Mvc\\test\Microsoft.AspNet.Mvc.FunctionalTests public HttpClient Client { get; }
private readonly static string SamplesFolder = Path.Combine("..", "..", "samples");
private static readonly List<string> Paths = new List<string> public static TheoryData<string> PathData
{
get
{
return new TheoryData<string>
{ {
string.Empty, string.Empty,
"/", "/",
@ -36,71 +37,19 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
"/Home/Edit/0?Name=Bobby&Blurb=howdy&DateOfBirth=1999-11-30&YearsEmployeed=2", "/Home/Edit/0?Name=Bobby&Blurb=howdy&DateOfBirth=1999-11-30&YearsEmployeed=2",
"/Home/Index", "/Home/Index",
}; };
}
}
private readonly ILoggerFactory _loggerFactory = new TestLoggerFactory(); [Theory]
private readonly Action<IApplicationBuilder, ILoggerFactory> _app = new TagHelperSample.Web.Startup().Configure; [MemberData(nameof(PathData))]
private readonly Action<IServiceCollection> _configureServices = new TagHelperSample.Web.Startup().ConfigureServices; public async Task Home_Pages_ReturnSuccess(string path)
[Fact]
public async Task Home_Pages_ReturnSuccess()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(app => _app(app, _loggerFactory), SiteName, SamplesFolder, _configureServices); var response = await Client.GetAsync("http://localhost" + path);
var client = server.CreateClient();
for (var index = 0; index < Paths.Count; index++)
{
// Act
var path = Paths[index];
var response = await client.GetAsync("http://localhost" + path);
// Assert // Assert
Assert.NotNull(response); Assert.NotNull(response);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
} }
} }
private class TestLoggerFactory : ILoggerFactory
{
public LogLevel MinimumLevel { get; set; }
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<object, Exception, string> formatter)
{
}
}
private class TestDisposable : IDisposable
{
public void Dispose()
{
}
}
}
} }

View File

@ -1,33 +1,37 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using BasicWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.WebEncoders;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class TagHelpersTest public class TagHelpersTest :
IClassFixture<MvcTestFixture<TagHelpersWebSite.Startup>>,
IClassFixture<MvcEncodedTestFixture<TagHelpersWebSite.Startup>>
{ {
private const string SiteName = nameof(TagHelpersWebSite);
// Some tests require comparing the actual response body against an expected response baseline // 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 // 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 // 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. // use it on all the rest of the tests.
private static readonly Assembly _resourcesAssembly = typeof(TagHelpersTest).GetTypeInfo().Assembly; private static readonly Assembly _resourcesAssembly = typeof(TagHelpersTest).GetTypeInfo().Assembly;
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; public TagHelpersTest(
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; MvcTestFixture<TagHelpersWebSite.Startup> fixture,
MvcEncodedTestFixture<TagHelpersWebSite.Startup> encodedFixture)
{
Client = fixture.Client;
EncodedClient = encodedFixture.Client;
}
public HttpClient Client { get; }
public HttpClient EncodedClient { get; }
[Theory] [Theory]
[InlineData("Index")] [InlineData("Index")]
@ -37,8 +41,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanRenderViewsWithTagHelpers(string action) public async Task CanRenderViewsWithTagHelpers(string action)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
var outputFile = "compiler/resources/TagHelpersWebSite.Home." + action + ".html"; var outputFile = "compiler/resources/TagHelpersWebSite.Home." + action + ".html";
var expectedContent = var expectedContent =
@ -46,7 +48,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act // Act
// The host is not important as everything runs in memory and tests are isolated from each other. // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -64,12 +66,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanRenderViewsWithTagHelpersAndUnboundDynamicAttributes_Encoded() public async Task CanRenderViewsWithTagHelpersAndUnboundDynamicAttributes_Encoded()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, services =>
{
_configureServices(services);
services.AddTransient<IHtmlEncoder, TestHtmlEncoder>();
});
var client = server.CreateClient();
var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
var outputFile = "compiler/resources/TagHelpersWebSite.Home.UnboundDynamicAttributes.Encoded.html"; var outputFile = "compiler/resources/TagHelpersWebSite.Home.UnboundDynamicAttributes.Encoded.html";
var expectedContent = var expectedContent =
@ -77,7 +73,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act // Act
// The host is not important as everything runs in memory and tests are isolated from each other. // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -146,12 +142,8 @@ page:<root>root-content</root>"
[MemberData(nameof(TagHelpersAreInheritedFromViewImportsPagesData))] [MemberData(nameof(TagHelpersAreInheritedFromViewImportsPagesData))]
public async Task TagHelpersAreInheritedFromViewImportsPages(string action, string expected) public async Task TagHelpersAreInheritedFromViewImportsPages(string action, string expected)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var result = await Client.GetStringAsync("http://localhost/Home/" + action);
var client = server.CreateClient();
// Act
var result = await client.GetStringAsync("http://localhost/Home/" + action);
// Assert // Assert
Assert.Equal(expected, result.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, result.Trim(), ignoreLineEndingDifferences: true);
@ -161,14 +153,12 @@ page:<root>root-content</root>"
public async Task ViewsWithModelMetadataAttributes_CanRenderForm() public async Task ViewsWithModelMetadataAttributes_CanRenderForm()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Create.html"; var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Create.html";
var expectedContent = var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
// Act // Act
var response = await client.GetAsync("http://localhost/Employee/Create"); var response = await Client.GetAsync("http://localhost/Employee/Create");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -189,8 +179,6 @@ page:<root>root-content</root>"
public async Task ViewsWithModelMetadataAttributes_CanRenderPostedValue() public async Task ViewsWithModelMetadataAttributes_CanRenderPostedValue()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Details.AfterCreate.html"; var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Details.AfterCreate.html";
var expectedContent = var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
@ -206,7 +194,7 @@ page:<root>root-content</root>"
var postContent = new FormUrlEncodedContent(validPostValues); var postContent = new FormUrlEncodedContent(validPostValues);
// Act // Act
var response = await client.PostAsync("http://localhost/Employee/Create", postContent); var response = await Client.PostAsync("http://localhost/Employee/Create", postContent);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -223,8 +211,6 @@ page:<root>root-content</root>"
public async Task ViewsWithModelMetadataAttributes_CanHandleInvalidData() public async Task ViewsWithModelMetadataAttributes_CanHandleInvalidData()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Create.Invalid.html"; var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Create.Invalid.html";
var expectedContent = var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
@ -240,7 +226,7 @@ page:<root>root-content</root>"
var postContent = new FormUrlEncodedContent(validPostValues); var postContent = new FormUrlEncodedContent(validPostValues);
// Act // Act
var response = await client.PostAsync("http://localhost/Employee/Create", postContent); var response = await Client.PostAsync("http://localhost/Employee/Create", postContent);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -7,26 +7,25 @@ using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Net.Http.Headers; using Microsoft.Net.Http.Headers;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class TempDataTest public class TempDataTest : IClassFixture<MvcTestFixture<TempDataWebSite.Startup>>
{ {
private const string SiteName = nameof(TempDataWebSite); public TempDataTest(MvcTestFixture<TempDataWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new TempDataWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new TempDataWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task TempData_PersistsJustForNextRequest() public async Task TempData_PersistsJustForNextRequest()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var nameValueCollection = new List<KeyValuePair<string, string>> var nameValueCollection = new List<KeyValuePair<string, string>>
{ {
new KeyValuePair<string, string>("value", "Foo"), new KeyValuePair<string, string>("value", "Foo"),
@ -34,13 +33,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var content = new FormUrlEncodedContent(nameValueCollection); var content = new FormUrlEncodedContent(nameValueCollection);
// Act 1 // Act 1
var response = await client.PostAsync("/Home/SetTempData", content); var response = await Client.PostAsync("/Home/SetTempData", content);
// Assert 1 // Assert 1
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Act 2 // Act 2
response = await client.SendAsync(GetRequest("Home/GetTempData", response)); response = await Client.SendAsync(GetRequest("Home/GetTempData", response));
// Assert 2 // Assert 2
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -48,7 +47,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Assert.Equal("Foo", body); Assert.Equal("Foo", body);
// Act 3 // Act 3
response = await client.SendAsync(GetRequest("Home/GetTempData", response)); response = await Client.SendAsync(GetRequest("Home/GetTempData", response));
// Assert 3 // Assert 3
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
@ -58,8 +57,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ViewRendersTempData() public async Task ViewRendersTempData()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var nameValueCollection = new List<KeyValuePair<string, string>> var nameValueCollection = new List<KeyValuePair<string, string>>
{ {
new KeyValuePair<string, string>("value", "Foo"), new KeyValuePair<string, string>("value", "Foo"),
@ -67,7 +64,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var content = new FormUrlEncodedContent(nameValueCollection); var content = new FormUrlEncodedContent(nameValueCollection);
// Act // Act
var response = await client.PostAsync("http://localhost/Home/DisplayTempData", content); var response = await Client.PostAsync("http://localhost/Home/DisplayTempData", content);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -81,8 +78,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task Redirect_RetainsTempData_EvenIfAccessed() public async Task Redirect_RetainsTempData_EvenIfAccessed()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var nameValueCollection = new List<KeyValuePair<string, string>> var nameValueCollection = new List<KeyValuePair<string, string>>
{ {
new KeyValuePair<string, string>("value", "Foo"), new KeyValuePair<string, string>("value", "Foo"),
@ -90,19 +85,19 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var content = new FormUrlEncodedContent(nameValueCollection); var content = new FormUrlEncodedContent(nameValueCollection);
// Act 1 // Act 1
var response = await client.PostAsync("/Home/SetTempData", content); var response = await Client.PostAsync("/Home/SetTempData", content);
// Assert 1 // Assert 1
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Act 2 // Act 2
var redirectResponse = await client.SendAsync(GetRequest("/Home/GetTempDataAndRedirect", response)); var redirectResponse = await Client.SendAsync(GetRequest("/Home/GetTempDataAndRedirect", response));
// Assert 2 // Assert 2
Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode); Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode);
// Act 3 // 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 3
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -114,8 +109,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task Peek_RetainsTempData() public async Task Peek_RetainsTempData()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var nameValueCollection = new List<KeyValuePair<string, string>> var nameValueCollection = new List<KeyValuePair<string, string>>
{ {
new KeyValuePair<string, string>("value", "Foo"), new KeyValuePair<string, string>("value", "Foo"),
@ -123,13 +116,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var content = new FormUrlEncodedContent(nameValueCollection); var content = new FormUrlEncodedContent(nameValueCollection);
// Act 1 // Act 1
var response = await client.PostAsync("/Home/SetTempData", content); var response = await Client.PostAsync("/Home/SetTempData", content);
// Assert 1 // Assert 1
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Act 2 // Act 2
var peekResponse = await client.SendAsync(GetRequest("/Home/PeekTempData", response)); var peekResponse = await Client.SendAsync(GetRequest("/Home/PeekTempData", response));
// Assert 2 // Assert 2
Assert.Equal(HttpStatusCode.OK, peekResponse.StatusCode); Assert.Equal(HttpStatusCode.OK, peekResponse.StatusCode);
@ -137,7 +130,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Assert.Equal("Foo", body); Assert.Equal("Foo", body);
// Act 3 // Act 3
var getResponse = await client.SendAsync(GetRequest("/Home/GetTempData", response)); var getResponse = await Client.SendAsync(GetRequest("/Home/GetTempData", response));
// Assert 3 // Assert 3
Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
@ -151,8 +144,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task TempData_ValidTypes_RoundTripProperly() public async Task TempData_ValidTypes_RoundTripProperly()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var testGuid = Guid.NewGuid(); var testGuid = Guid.NewGuid();
var nameValueCollection = new List<KeyValuePair<string, string>> var nameValueCollection = new List<KeyValuePair<string, string>>
{ {
@ -167,13 +158,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var content = new FormUrlEncodedContent(nameValueCollection); var content = new FormUrlEncodedContent(nameValueCollection);
// Act 1 // Act 1
var redirectResponse = await client.PostAsync("/Home/SetTempDataMultiple", content); var redirectResponse = await Client.PostAsync("/Home/SetTempDataMultiple", content);
// Assert 1 // Assert 1
Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode); Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode);
// Act 2 // 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 2
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -185,8 +176,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task TempData_InvalidType_Throws() public async Task TempData_InvalidType_Throws()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var nameValueCollection = new List<KeyValuePair<string, string>> var nameValueCollection = new List<KeyValuePair<string, string>>
{ {
new KeyValuePair<string, string>("value", "Foo"), new KeyValuePair<string, string>("value", "Foo"),
@ -196,7 +185,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act & Assert // Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => var exception = await Assert.ThrowsAsync<InvalidOperationException>(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 '" + Assert.Equal("The '" + typeof(SessionStateTempDataProvider).FullName + "' cannot serialize an object of type '" +
typeof(TempDataWebSite.Controllers.HomeController.NonSerializableType).FullName + "' to session state.", exception.Message); typeof(TempDataWebSite.Controllers.HomeController.NonSerializableType).FullName + "' to session state.", exception.Message);

View File

@ -6,59 +6,57 @@ using Microsoft.Dnx.Runtime;
namespace Microsoft.AspNet.Mvc.FunctionalTests 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 // 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. // in a regular context.
public class TestApplicationEnvironment : IApplicationEnvironment public class TestApplicationEnvironment : IApplicationEnvironment
{ {
private readonly IApplicationEnvironment _originalAppEnvironment; private readonly IApplicationEnvironment _original;
private readonly string _applicationBasePath;
private readonly string _applicationName;
public TestApplicationEnvironment(IApplicationEnvironment originalAppEnvironment, string appBasePath, string appName) public TestApplicationEnvironment(IApplicationEnvironment original, string name, string basePath)
{ {
_originalAppEnvironment = originalAppEnvironment; _original = original;
_applicationBasePath = appBasePath; ApplicationName = name;
_applicationName = appName; ApplicationBasePath = basePath;
} }
public string ApplicationName public string ApplicationName { get; }
{
get { return _applicationName; }
}
public string ApplicationVersion public string ApplicationVersion
{ {
get { return _originalAppEnvironment.ApplicationVersion; } get
{
return _original.ApplicationVersion;
}
} }
public string ApplicationBasePath public string ApplicationBasePath { get; }
{
get { return _applicationBasePath; }
}
public string Configuration public string Configuration
{ {
get get
{ {
return _originalAppEnvironment.Configuration; return _original.Configuration;
} }
} }
public FrameworkName RuntimeFramework public FrameworkName RuntimeFramework
{ {
get { return _originalAppEnvironment.RuntimeFramework; } get
{
return _original.RuntimeFramework;
}
} }
public object GetData(string name) public object GetData(string name)
{ {
return _originalAppEnvironment.GetData(name); return _original.GetData(name);
} }
public void SetData(string name, object value) public void SetData(string name, object value)
{ {
_originalAppEnvironment.SetData(name, value); _original.SetData(name, value);
} }
} }
} }

View File

@ -6,11 +6,10 @@ using System.IO;
using System.Reflection; using System.Reflection;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting; 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.Mvc.Actions;
using Microsoft.AspNet.TestHost;
using Microsoft.Dnx.Runtime;
using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
@ -20,19 +19,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
private static readonly string WebsitesDirectoryPath = Path.Combine("..", "WebSites"); private static readonly string WebsitesDirectoryPath = Path.Combine("..", "WebSites");
public static TestServer CreateServer(Action<IApplicationBuilder> builder, string applicationWebSiteName) public static TestServer CreateServer(Action<IApplicationBuilder> builder, string applicationWebSiteName)
{
return CreateServer(builder, applicationWebSiteName, applicationPath: null);
}
public static TestServer CreateServer(
Action<IApplicationBuilder> builder,
string applicationWebSiteName,
string applicationPath)
{ {
return CreateServer( return CreateServer(
builder, builder,
applicationWebSiteName, applicationWebSiteName,
applicationPath, applicationPath: null,
configureServices: (Action<IServiceCollection>)null); configureServices: (Action<IServiceCollection>)null);
} }
@ -48,7 +39,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
configureServices: configureServices); configureServices: configureServices);
} }
public static TestServer CreateServer( private static TestServer CreateServer(
Action<IApplicationBuilder> builder, Action<IApplicationBuilder> builder,
string applicationWebSiteName, string applicationWebSiteName,
string applicationPath, string applicationPath,
@ -59,34 +50,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
services => AddTestServices(services, applicationWebSiteName, applicationPath, configureServices)); services => AddTestServices(services, applicationWebSiteName, applicationPath, configureServices));
} }
public static TestServer CreateServer(
Action<IApplicationBuilder> builder,
string applicationWebSiteName,
Func<IServiceCollection, IServiceProvider> configureServices)
{
return CreateServer(
builder,
applicationWebSiteName,
applicationPath: null,
configureServices: configureServices);
}
public static TestServer CreateServer(
Action<IApplicationBuilder> builder,
string applicationWebSiteName,
string applicationPath,
Func<IServiceCollection, IServiceProvider> 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( private static void AddTestServices(
IServiceCollection services, IServiceCollection services,
string applicationWebSiteName, string applicationWebSiteName,
@ -112,8 +75,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
applicationPath); applicationPath);
var environment = new TestApplicationEnvironment( var environment = new TestApplicationEnvironment(
originalEnvironment, originalEnvironment,
applicationBasePath, applicationWebSiteName,
applicationWebSiteName); applicationBasePath);
services.AddInstance<IApplicationEnvironment>(environment); services.AddInstance<IApplicationEnvironment>(environment);
var hostingEnvironment = new HostingEnvironment(); var hostingEnvironment = new HostingEnvironment();
hostingEnvironment.Initialize(applicationBasePath, environmentName: null); hostingEnvironment.Initialize(applicationBasePath, environmentName: null);

View File

@ -8,26 +8,25 @@ using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing; using Microsoft.AspNet.Testing;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class TryValidateModelTest public class TryValidateModelTest : IClassFixture<MvcTestFixture<ValidationWebSite.Startup>>
{ {
private const string SiteName = nameof(ValidationWebSite); public TryValidateModelTest(MvcTestFixture<ValidationWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new ValidationWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new ValidationWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task TryValidateModel_ClearParameterValidationError_ReturnsErrorsForInvalidProperties() public async Task TryValidateModel_ClearParameterValidationError_ReturnsErrorsForInvalidProperties()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{ \"Price\": 2, \"Contact\": \"acvrdzersaererererfdsfdsfdsfsdf\", " + var input = "{ \"Price\": 2, \"Contact\": \"acvrdzersaererererfdsfdsfdsfsdf\", " +
"\"ProductDetails\": {\"Detail1\": \"d1\", \"Detail2\": \"d2\", \"Detail3\": \"d3\"}}"; "\"ProductDetails\": {\"Detail1\": \"d1\", \"Detail2\": \"d2\", \"Detail3\": \"d3\"}}";
var content = new StringContent(input, Encoding.UTF8, "application/json"); var content = new StringContent(input, Encoding.UTF8, "application/json");
@ -36,7 +35,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
"TryValidateModelAfterClearingValidationErrorInParameter?theImpossibleString=test"; "TryValidateModelAfterClearingValidationErrorInParameter?theImpossibleString=test";
// Act // Act
var response = await client.PostAsync(url, content); var response = await Client.PostAsync(url, content);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -59,13 +58,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task TryValidateModel_InvalidTypeOnDerivedModel_ReturnsErrors() public async Task TryValidateModel_InvalidTypeOnDerivedModel_ReturnsErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var url = "http://localhost/ModelMetadataTypeValidation/TryValidateModelSoftwareViewModelWithPrefix";
var client = server.CreateClient();
var url =
"http://localhost/ModelMetadataTypeValidation/TryValidateModelSoftwareViewModelWithPrefix";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
@ -78,13 +74,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task TryValidateModel_ValidDerivedModel_ReturnsEmptyResponseBody() public async Task TryValidateModel_ValidDerivedModel_ReturnsEmptyResponseBody()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var url = "http://localhost/ModelMetadataTypeValidation/TryValidateModelValidModelNoPrefix";
var client = server.CreateClient();
var url =
"http://localhost/ModelMetadataTypeValidation/TryValidateModelValidModelNoPrefix";
// Act // Act
var response = await client.GetAsync(url); var response = await Client.GetAsync(url);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -96,8 +89,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task TryValidateModel_CollectionsModel_ReturnsErrorsForInvalidProperties() public async Task TryValidateModel_CollectionsModel_ReturnsErrorsForInvalidProperties()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "[ { \"Price\": 2, \"Contact\": \"acvrdzersaererererfdsfdsfdsfsdf\", " + var input = "[ { \"Price\": 2, \"Contact\": \"acvrdzersaererererfdsfdsfdsfsdf\", " +
"\"ProductDetails\": {\"Detail1\": \"d1\", \"Detail2\": \"d2\", \"Detail3\": \"d3\"} }," + "\"ProductDetails\": {\"Detail1\": \"d1\", \"Detail2\": \"d2\", \"Detail3\": \"d3\"} }," +
"{\"Price\": 2, \"Contact\": \"acvrdzersaererererfdsfdsfdsfsdf\", " + "{\"Price\": 2, \"Contact\": \"acvrdzersaererererfdsfdsfdsfsdf\", " +
@ -107,7 +98,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
"http://localhost/ModelMetadataTypeValidation/TryValidateModelWithCollectionsModel"; "http://localhost/ModelMetadataTypeValidation/TryValidateModelWithCollectionsModel";
// Act // Act
var response = await client.PostAsync(url, content); var response = await Client.PostAsync(url, content);
// Assert // Assert
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();

View File

@ -1,36 +1,41 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.WebEncoders;
using RazorWebSite;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class UrlResolutionTest public class UrlResolutionTest :
IClassFixture<MvcTestFixture<RazorWebSite.Startup>>,
IClassFixture<MvcEncodedTestFixture<RazorWebSite.Startup>>
{ {
private const string SiteName = nameof(RazorWebSite);
private readonly Action<IApplicationBuilder> _app = new Startup().Configure;
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices;
private static readonly Assembly _resourcesAssembly = typeof(UrlResolutionTest).GetTypeInfo().Assembly; private static readonly Assembly _resourcesAssembly = typeof(UrlResolutionTest).GetTypeInfo().Assembly;
public UrlResolutionTest(
MvcTestFixture<RazorWebSite.Startup> fixture,
MvcEncodedTestFixture<RazorWebSite.Startup> encodedFixture)
{
Client = fixture.Client;
EncodedClient = encodedFixture.Client;
}
public HttpClient Client { get; }
public HttpClient EncodedClient { get; }
[Fact] [Fact]
public async Task AppRelativeUrlsAreResolvedCorrectly() public async Task AppRelativeUrlsAreResolvedCorrectly()
{ {
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Arrange
var client = server.CreateClient();
var outputFile = "compiler/resources/RazorWebSite.UrlResolution.Index.html"; var outputFile = "compiler/resources/RazorWebSite.UrlResolution.Index.html";
var expectedContent = var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
// Act // 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(); var responseContent = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -45,18 +50,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task AppRelativeUrlsAreResolvedAndEncodedCorrectly() public async Task AppRelativeUrlsAreResolvedAndEncodedCorrectly()
{ {
var server = TestHelper.CreateServer(_app, SiteName, services => // Arrange
{
_configureServices(services);
services.AddTransient<IHtmlEncoder, TestHtmlEncoder>();
});
var client = server.CreateClient();
var outputFile = "compiler/resources/RazorWebSite.UrlResolution.Index.Encoded.html"; var outputFile = "compiler/resources/RazorWebSite.UrlResolution.Index.Encoded.html";
var expectedContent = var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
// Act // 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(); var responseContent = await response.Content.ReadAsStringAsync();
// Assert // Assert

View File

@ -1,30 +1,26 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using ValueProvidersWebSite;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ValueProviderTest public class ValueProviderTest : IClassFixture<MvcTestFixture<ValueProvidersWebSite.Startup>>
{ {
private const string SiteName = nameof(ValueProvidersWebSite); public ValueProviderTest(MvcTestFixture<ValueProvidersWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task ValueProviderFactories_AreVisitedInSequentialOrder_ForValueProviders() public async Task ValueProviderFactories_AreVisitedInSequentialOrder_ForValueProviders()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var body = await Client.GetStringAsync("http://localhost/Home/TestValueProvider?test=not-test-value");
var client = server.CreateClient();
// Act
var body = await client.GetStringAsync("http://localhost/Home/TestValueProvider?test=not-test-value");
// Assert // Assert
Assert.Equal("custom-value-provider-value", body.Trim()); Assert.Equal("custom-value-provider-value", body.Trim());
@ -33,12 +29,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ValueProviderFactories_ReturnsValuesFromQueryValueProvider() public async Task ValueProviderFactories_ReturnsValuesFromQueryValueProvider()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var body = await Client.GetStringAsync("http://localhost/Home/DefaultValueProviders?test=query-value");
var client = server.CreateClient();
// Act
var body = await client.GetStringAsync("http://localhost/Home/DefaultValueProviders?test=query-value");
// Assert // Assert
Assert.Equal("query-value", body.Trim()); Assert.Equal("query-value", body.Trim());
@ -47,12 +39,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ValueProviderFactories_ReturnsValuesFromRouteValueProvider() public async Task ValueProviderFactories_ReturnsValuesFromRouteValueProvider()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var body = await Client.GetStringAsync("http://localhost/RouteTest/route-value");
var client = server.CreateClient();
// Act
var body = await client.GetStringAsync("http://localhost/RouteTest/route-value");
// Assert // Assert
Assert.Equal("route-value", body.Trim()); Assert.Equal("route-value", body.Trim());
@ -67,12 +55,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("http://localhost/Home/GetFlagValuesAsInt?flags=Value1,Value2", "3")] [InlineData("http://localhost/Home/GetFlagValuesAsInt?flags=Value1,Value2", "3")]
public async Task ValueProvider_DeserializesEnumsWithFlags(string url, string expected) public async Task ValueProvider_DeserializesEnumsWithFlags(string url, string expected)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var body = await Client.GetStringAsync(url);
var client = server.CreateClient();
// Act
var body = await client.GetStringAsync(url);
// Assert // Assert
Assert.Equal(expected, body.Trim()); Assert.Equal(expected, body.Trim());

View File

@ -1,23 +1,23 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class VersioningTests public class VersioningTests : IClassFixture<MvcTestFixture<VersioningWebSite.Startup>>
{ {
private const string SiteName = nameof(VersioningWebSite); public VersioningTests(MvcTestFixture<VersioningWebSite.Startup> fixture)
readonly Action<IApplicationBuilder> _app = new VersioningWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new VersioningWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("1")] [InlineData("1")]
@ -25,12 +25,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task AttributeRoutedAction_WithVersionedRoutes_IsNotAmbiguous(string version) public async Task AttributeRoutedAction_WithVersionedRoutes_IsNotAmbiguous(string version)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/Addresses?version=" + version);
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -38,7 +36,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<RoutingResult>(body); var result = JsonConvert.DeserializeObject<RoutingResult>(body);
// Assert
Assert.Contains("api/addresses", result.ExpectedUrls); Assert.Contains("api/addresses", result.ExpectedUrls);
Assert.Equal("Address", result.Controller); Assert.Equal("Address", result.Controller);
Assert.Equal("GetV" + version, result.Action); Assert.Equal("GetV" + version, result.Action);
@ -50,14 +47,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task AttributeRoutedAction_WithAmbiguousVersionedRoutes_CanBeDisambiguatedUsingOrder(string version) public async Task AttributeRoutedAction_WithAmbiguousVersionedRoutes_CanBeDisambiguatedUsingOrder(string version)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var query = "?version=" + version; var query = "?version=" + version;
var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/Addresses/All" + query); var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/Addresses/All" + query);
// Act // Act
var response = await client.SendAsync(message); var response = await Client.SendAsync(message);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -65,7 +60,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var body = await response.Content.ReadAsStringAsync(); var body = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<RoutingResult>(body); var result = JsonConvert.DeserializeObject<RoutingResult>(body);
// Assert
Assert.Contains("/api/addresses/all?version=" + version, result.ExpectedUrls); Assert.Contains("/api/addresses/all?version=" + version, result.ExpectedUrls);
Assert.Equal("Address", result.Controller); Assert.Equal("Address", result.Controller);
Assert.Equal("GetAllV" + version, result.Action); Assert.Equal("GetAllV" + version, result.Action);
@ -75,12 +69,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_CanReachV1Operations_OnTheSameController_WithNoVersionSpecified() public async Task VersionedApi_CanReachV1Operations_OnTheSameController_WithNoVersionSpecified()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets");
var client = server.CreateClient();
// Act // Act
var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets"); var response = await Client.SendAsync(message);
var response = await client.SendAsync(message);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -98,12 +90,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_CanReachV1Operations_OnTheSameController_WithVersionSpecified() public async Task VersionedApi_CanReachV1Operations_OnTheSameController_WithVersionSpecified()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets?version=2");
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -119,12 +109,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_CanReachV1OperationsWithParameters_OnTheSameController() public async Task VersionedApi_CanReachV1OperationsWithParameters_OnTheSameController()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets/5");
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -140,12 +128,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_CanReachV1OperationsWithParameters_OnTheSameController_WithVersionSpecified() public async Task VersionedApi_CanReachV1OperationsWithParameters_OnTheSameController_WithVersionSpecified()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Tickets/5?version=2");
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -169,12 +155,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_CanReachOtherVersionOperations_OnTheSameController(string version) public async Task VersionedApi_CanReachOtherVersionOperations_OnTheSameController(string version)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Tickets?version=" + version);
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -195,12 +179,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_CanNotReachOtherVersionOperations_OnTheSameController_WithNoVersionSpecified() public async Task VersionedApi_CanNotReachOtherVersionOperations_OnTheSameController_WithNoVersionSpecified()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Tickets");
var client = server.CreateClient();
// Act // Act
var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Tickets"); var response = await Client.SendAsync(message);
var response = await client.SendAsync(message);
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -222,12 +204,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
string version) string version)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Tickets/5?version=" + version);
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -250,12 +230,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_CanNotReachOtherVersionOperationsWithParameters_OnTheSameController_WithNoVersionSpecified(string method) public async Task VersionedApi_CanNotReachOtherVersionOperationsWithParameters_OnTheSameController_WithNoVersionSpecified(string method)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Tickets/5");
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -271,12 +249,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_CanUseOrderToDisambiguate_OverlappingVersionRanges(string version) public async Task VersionedApi_CanUseOrderToDisambiguate_OverlappingVersionRanges(string version)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Books?version=" + version);
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -295,12 +271,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_OverlappingVersionRanges_FallsBackToLowerOrderAction(string version) public async Task VersionedApi_OverlappingVersionRanges_FallsBackToLowerOrderAction(string version)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Books?version=" + version);
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); 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) public async Task VersionedApi_CanReachV1Operations_OnTheOriginalController_WithNoVersionSpecified(string method, string action)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Movies");
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); 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) public async Task VersionedApi_CanReachV1Operations_OnTheOriginalController_WithVersionSpecified(string method, string action)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Movies?version=2");
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); 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) public async Task VersionedApi_CanReachV1OperationsWithParameters_OnTheOriginalController(string method, string action)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Movies/5");
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); 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) public async Task VersionedApi_CanReachV1OperationsWithParameters_OnTheOriginalController_WithVersionSpecified(string method, string action)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(new HttpMethod(method), "http://localhost/Movies/5?version=2");
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -410,12 +376,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_CanReachOtherVersionOperationsWithParameters_OnTheV2Controller() public async Task VersionedApi_CanReachOtherVersionOperationsWithParameters_OnTheV2Controller()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Put, "http://localhost/Movies/5?version=2");
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -434,12 +398,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_CanHaveTwoRoutesWithVersionOnTheUrl_OnTheSameAction(string url) public async Task VersionedApi_CanHaveTwoRoutesWithVersionOnTheUrl_OnTheSameAction(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/" + url);
var client = server.CreateClient();
// Act // Act
var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/" + url); var response = await Client.SendAsync(message);
var response = await client.SendAsync(message);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); 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) public async Task VersionedApi_CanHaveTwoRoutesWithVersionOnTheUrl_OnDifferentActions(string url, string version)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/" + url);
var client = server.CreateClient();
// Act // Act
var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/" + url); var response = await Client.SendAsync(message);
var response = await client.SendAsync(message);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); 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) public async Task VersionedApi_CanHaveTwoRoutesWithVersionOnTheUrl_OnDifferentActions_WithInlineConstraint(string url, string version)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/" + url);
var client = server.CreateClient();
// Act // Act
var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/" + url); var response = await Client.SendAsync(message);
var response = await client.SendAsync(message);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); 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) public async Task VersionedApi_CanProvideVersioningInformation_UsingPlainActionConstraint(string url, string query, string actionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost/" + url + query);
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -527,12 +483,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_ConstraintOrder_IsRespected() public async Task VersionedApi_ConstraintOrder_IsRespected()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost/" + "Customers?version=2");
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -548,12 +502,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_CanUseConstraintOrder_ToChangeSelectedAction() public async Task VersionedApi_CanUseConstraintOrder_ToChangeSelectedAction()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var message = new HttpRequestMessage(HttpMethod.Delete, "http://localhost/" + "Customers/5?version=2");
var client = server.CreateClient();
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -571,13 +523,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task VersionedApi_MultipleVersionsUsingAttributeRouting_OnTheSameMethod(string version) public async Task VersionedApi_MultipleVersionsUsingAttributeRouting_OnTheSameMethod(string version)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var path = "/" + version + "/Vouchers?version=" + version; var path = "/" + version + "/Vouchers?version=" + version;
var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost" + path);
// Act // Act
var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost" + path); var response = await Client.SendAsync(message);
var response = await client.SendAsync(message);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -1,21 +1,21 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using ViewComponentWebSite;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ViewComponentTests public class ViewComponentTests : IClassFixture<MvcTestFixture<ViewComponentWebSite.Startup>>
{ {
private const string SiteName = nameof(ViewComponentWebSite); public ViewComponentTests(MvcTestFixture<ViewComponentWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
public static IEnumerable<object[]> ViewViewComponents_AreRenderedCorrectlyData public static IEnumerable<object[]> ViewViewComponents_AreRenderedCorrectlyData
{ {
@ -41,11 +41,8 @@ ViewWithSyncComponents Invoke: hello from viewdatacomponent"
[MemberData(nameof(ViewViewComponents_AreRenderedCorrectlyData))] [MemberData(nameof(ViewViewComponents_AreRenderedCorrectlyData))]
public async Task ViewViewComponents_AreRenderedCorrectly(string actionName, string expected) public async Task ViewViewComponents_AreRenderedCorrectly(string actionName, string expected)
{ {
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Arrange & Act
var client = server.CreateClient(); var body = await Client.GetStringAsync("http://localhost/Home/" + actionName);
// Act
var body = await client.GetStringAsync("http://localhost/Home/" + actionName);
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -54,11 +51,8 @@ ViewWithSyncComponents Invoke: hello from viewdatacomponent"
[Fact] [Fact]
public async Task ViewComponents_SupportsValueType() public async Task ViewComponents_SupportsValueType()
{ {
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Arrange & Act
var client = server.CreateClient(); var body = await Client.GetStringAsync("http://localhost/Home/ViewWithIntegerViewComponent");
// Act
var body = await client.GetStringAsync("http://localhost/Home/ViewWithIntegerViewComponent");
// Assert // Assert
Assert.Equal("10", body.Trim()); Assert.Equal("10", body.Trim());
@ -67,11 +61,8 @@ ViewWithSyncComponents Invoke: hello from viewdatacomponent"
[Fact] [Fact]
public async Task ViewComponents_InvokeWithViewComponentResult() public async Task ViewComponents_InvokeWithViewComponentResult()
{ {
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Arrange & Act
var client = server.CreateClient(); var body = await Client.GetStringAsync("http://localhost/ViewComponentResult/Invoke?number=31");
// Act
var body = await client.GetStringAsync("http://localhost/ViewComponentResult/Invoke?number=31");
// Assert // Assert
Assert.Equal("31", body.Trim()); Assert.Equal("31", body.Trim());
@ -86,14 +77,11 @@ ViewWithSyncComponents Invoke: hello from viewdatacomponent"
[InlineData("http://localhost/Home/ViewComponentWithEnumerableModelUsingUnion", "Union")] [InlineData("http://localhost/Home/ViewComponentWithEnumerableModelUsingUnion", "Union")]
public async Task ViewComponents_SupportsEnumerableModel(string url, string linqQueryType) public async Task ViewComponents_SupportsEnumerableModel(string url, string linqQueryType)
{ {
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Arrange & Act
var client = server.CreateClient();
// Act
// https://github.com/aspnet/Mvc/issues/1354 // https://github.com/aspnet/Mvc/issues/1354
// The invoked ViewComponent/View has a model which is an internal type implementing Enumerable. // The invoked ViewComponent/View has a model which is an internal type implementing Enumerable.
// For ex - TestEnumerableObject.Select(t => t) returns WhereSelectListIterator // For ex - TestEnumerableObject.Select(t => t) returns WhereSelectListIterator
var body = await client.GetStringAsync(url); var body = await Client.GetStringAsync(url);
// Assert // Assert
Assert.Equal("<p>Hello</p><p>World</p><p>Sample</p><p>Test</p>" Assert.Equal("<p>Hello</p><p>World</p><p>Sample</p><p>Test</p>"
@ -105,11 +93,8 @@ ViewWithSyncComponents Invoke: hello from viewdatacomponent"
[InlineData("ViewComponentWebSite.Namespace2.SameName")] [InlineData("ViewComponentWebSite.Namespace2.SameName")]
public async Task ViewComponents_FullName(string name) public async Task ViewComponents_FullName(string name)
{ {
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Arrange & Act
var client = server.CreateClient(); var body = await Client.GetStringAsync("http://localhost/FullName/Invoke?name=" + name);
// Act
var body = await client.GetStringAsync("http://localhost/FullName/Invoke?name=" + name);
// Assert // Assert
Assert.Equal(name, body.Trim()); Assert.Equal(name, body.Trim());
@ -118,13 +103,11 @@ ViewWithSyncComponents Invoke: hello from viewdatacomponent"
[Fact] [Fact]
public async Task ViewComponents_ShortNameUsedForViewLookup() public async Task ViewComponents_ShortNameUsedForViewLookup()
{ {
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Arrange
var client = server.CreateClient();
var name = "ViewComponentWebSite.Integer"; var name = "ViewComponentWebSite.Integer";
// Act // 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
Assert.Equal("17", body.Trim()); Assert.Equal("17", body.Trim());

View File

@ -1,26 +1,26 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing; using Microsoft.AspNet.Testing;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Net.Http.Headers; using Microsoft.Net.Http.Headers;
using RazorWebSite;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class ViewEngineTests public class ViewEngineTests : IClassFixture<MvcTestFixture<RazorWebSite.Startup>>
{ {
private const string SiteName = nameof(RazorWebSite);
private static readonly Assembly _assembly = typeof(ViewEngineTests).GetTypeInfo().Assembly; private static readonly Assembly _assembly = typeof(ViewEngineTests).GetTypeInfo().Assembly;
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; public ViewEngineTests(MvcTestFixture<RazorWebSite.Startup> fixture)
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; {
Client = fixture.Client;
}
public HttpClient Client { get; }
public static IEnumerable<object[]> RazorView_ExecutesPageAndLayoutData public static IEnumerable<object[]> RazorView_ExecutesPageAndLayoutData
{ {
@ -64,11 +64,8 @@ ViewWithNestedLayout-Content
[MemberData(nameof(RazorView_ExecutesPageAndLayoutData))] [MemberData(nameof(RazorView_ExecutesPageAndLayoutData))]
public async Task RazorView_ExecutesPageAndLayout(string actionName, string expected) public async Task RazorView_ExecutesPageAndLayout(string actionName, string expected)
{ {
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); // Arrange & Act
var client = server.CreateClient(); var body = await Client.GetStringAsync("http://localhost/ViewEngine/" + actionName);
// Act
var body = await client.GetStringAsync("http://localhost/ViewEngine/" + actionName);
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -77,6 +74,7 @@ ViewWithNestedLayout-Content
[Fact] [Fact]
public async Task RazorView_ExecutesPartialPagesWithCorrectContext() public async Task RazorView_ExecutesPartialPagesWithCorrectContext()
{ {
// Arrange
var expected = @"<partial>98052 var expected = @"<partial>98052
</partial> </partial>
@ -84,11 +82,9 @@ ViewWithNestedLayout-Content
</partial2> </partial2>
test-value"; test-value";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/ViewEngine/ViewWithPartial"); var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewWithPartial");
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -99,11 +95,9 @@ test-value";
{ {
// Arrange // Arrange
var expected = "HelloWorld"; var expected = "HelloWorld";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync( var body = await Client.GetStringAsync(
"http://localhost/ViewEngine/ViewWithPartialTakingModelFromIEnumerable"); "http://localhost/ViewEngine/ViewWithPartialTakingModelFromIEnumerable");
// Assert // Assert
@ -113,14 +107,13 @@ test-value";
[Fact] [Fact]
public async Task RazorView_PassesViewContextBetweenViewAndLayout() public async Task RazorView_PassesViewContextBetweenViewAndLayout()
{ {
// Arrange
var expected = var expected =
@"<title>Page title</title> @"<title>Page title</title>
partial-contentcomponent-content"; partial-contentcomponent-content";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/ViewEngine/ViewPassesViewDataToLayout"); var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewPassesViewDataToLayout");
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -153,15 +146,13 @@ expander-partial";
public async Task RazorViewEngine_UsesViewExpandersForViewsAndPartials(string value, string expected) public async Task RazorViewEngine_UsesViewExpandersForViewsAndPartials(string value, string expected)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var cultureCookie = "c=" + value + "|uic=" + value; var cultureCookie = "c=" + value + "|uic=" + value;
client.DefaultRequestHeaders.Add( var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/TemplateExpander");
"Cookie", request.Headers.Add("Cookie", new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString());
new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString());
// Act // Act
var body = await client.GetStringAsync("http://localhost/TemplateExpander"); var response = await Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -183,12 +174,8 @@ expander-partial";
[MemberData(nameof(ViewLocationExpanders_PassesInIsPartialToViewLocationExpanderContextData))] [MemberData(nameof(ViewLocationExpanders_PassesInIsPartialToViewLocationExpanderContextData))]
public async Task ViewLocationExpanders_PassesInIsPartialToViewLocationExpanderContext(string action, string expected) public async Task ViewLocationExpanders_PassesInIsPartialToViewLocationExpanderContext(string action, string expected)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var body = await Client.GetStringAsync($"http://localhost/ExpanderViews/{action}");
var client = server.CreateClient();
// Act
var body = await client.GetStringAsync($"http://localhost/ExpanderViews/{action}");
// Assert // Assert
Assert.Equal(expected, body.Trim()); Assert.Equal(expected, body.Trim());
@ -244,12 +231,8 @@ ViewWithNestedLayout-Content
[MemberData(nameof(RazorViewEngine_RendersPartialViewsData))] [MemberData(nameof(RazorViewEngine_RendersPartialViewsData))]
public async Task RazorViewEngine_RendersPartialViews(string actionName, string expected) public async Task RazorViewEngine_RendersPartialViews(string actionName, string expected)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var body = await Client.GetStringAsync("http://localhost/PartialViewEngine/" + actionName);
var client = server.CreateClient();
// Act
var body = await client.GetStringAsync("http://localhost/PartialViewEngine/" + actionName);
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -262,11 +245,9 @@ ViewWithNestedLayout-Content
var expected = @"<title>viewstart-value</title> var expected = @"<title>viewstart-value</title>
~/Views/NestedViewStarts/NestedViewStarts/Layout.cshtml ~/Views/NestedViewStarts/NestedViewStarts/Layout.cshtml
index-content"; index-content";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/NestedViewStarts"); var body = await Client.GetStringAsync("http://localhost/NestedViewStarts");
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -301,15 +282,13 @@ index-content";
public async Task RazorViewEngine_UsesExpandersForLayouts(string value, string expected) public async Task RazorViewEngine_UsesExpandersForLayouts(string value, string expected)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var cultureCookie = "c=" + value + "|uic=" + value; var cultureCookie = "c=" + value + "|uic=" + value;
client.DefaultRequestHeaders.Add( var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/TemplateExpander/ViewWithLayout");
"Cookie", request.Headers.Add("Cookie", new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString());
new CookieHeaderValue("ASPNET_CULTURE", cultureCookie).ToString());
// Act // Act
var body = await client.GetStringAsync("http://localhost/TemplateExpander/ViewWithLayout"); var response = await Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -322,12 +301,10 @@ index-content";
var expected = var expected =
@"<view-start>Hello Controller-Person</view-start> @"<view-start>Hello Controller-Person</view-start>
<page>Hello Controller-Person</page>"; <page>Hello Controller-Person</page>";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var target = "http://localhost/NestedViewImports"; var target = "http://localhost/NestedViewImports";
// Act // Act
var body = await client.GetStringAsync(target); var body = await Client.GetStringAsync(target);
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -342,11 +319,9 @@ index-content";
Page Content Page Content
<component-title>ViewComponent With Title</component-title> <component-title>ViewComponent With Title</component-title>
<component-body>Component With Layout</component-body>"; <component-body>Component With Layout</component-body>";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/ViewEngine/ViewWithComponentThatHasLayout"); var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewWithComponentThatHasLayout");
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -357,11 +332,9 @@ Page Content
{ {
// Arrange // Arrange
var expected = @"<page-content>ViewComponent With ViewStart</page-content>"; var expected = @"<page-content>ViewComponent With ViewStart</page-content>";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/ViewEngine/ViewWithComponentThatHasViewStart"); var body = await Client.GetStringAsync("http://localhost/ViewEngine/ViewWithComponentThatHasViewStart");
// Assert // Assert
Assert.Equal(expected, body.Trim()); Assert.Equal(expected, body.Trim());
@ -372,11 +345,9 @@ Page Content
{ {
// Arrange // Arrange
var expected = "Partial that does not specify Layout"; var expected = "Partial that does not specify Layout";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/PartialsWithLayout/PartialDoesNotExecuteViewStarts"); var body = await Client.GetStringAsync("http://localhost/PartialsWithLayout/PartialDoesNotExecuteViewStarts");
// Assert // Assert
Assert.Equal(expected, body.Trim()); Assert.Equal(expected, body.Trim());
@ -389,11 +360,9 @@ Page Content
var expected = var expected =
@"<layout-for-viewstart-with-layout><layout-for-viewstart-with-layout>Partial that specifies Layout @"<layout-for-viewstart-with-layout><layout-for-viewstart-with-layout>Partial that specifies Layout
</layout-for-viewstart-with-layout>Partial that does not specify Layout</layout-for-viewstart-with-layout>"; </layout-for-viewstart-with-layout>Partial that does not specify Layout</layout-for-viewstart-with-layout>";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/PartialsWithLayout/PartialsRenderedViaRenderPartial"); var body = await Client.GetStringAsync("http://localhost/PartialsWithLayout/PartialsRenderedViaRenderPartial");
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -408,11 +377,9 @@ Page Content
</layout-for-viewstart-with-layout> </layout-for-viewstart-with-layout>
Partial that does not specify Layout Partial that does not specify Layout
</layout-for-viewstart-with-layout>"; </layout-for-viewstart-with-layout>";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/PartialsWithLayout/PartialsRenderedViaPartialAsync"); var body = await Client.GetStringAsync("http://localhost/PartialsWithLayout/PartialsRenderedViaPartialAsync");
// Assert // Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
@ -422,13 +389,11 @@ Partial that does not specify Layout
public async Task RazorView_SetsViewPathAndExecutingPagePath() public async Task RazorView_SetsViewPathAndExecutingPagePath()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var outputFile = "compiler/resources/ViewEngineController.ViewWithPaths.txt"; var outputFile = "compiler/resources/ViewEngineController.ViewWithPaths.txt";
var expectedContent = await ResourceFile.ReadResourceAsync(_assembly, outputFile, sourceFile: false); var expectedContent = await ResourceFile.ReadResourceAsync(_assembly, outputFile, sourceFile: false);
// Act // Act
var responseContent = await client.GetStringAsync("http://localhost/ViewWithPaths"); var responseContent = await Client.GetStringAsync("http://localhost/ViewWithPaths");
// Assert // Assert
responseContent = responseContent.Trim(); responseContent = responseContent.Trim();

View File

@ -3,28 +3,26 @@
using System; using System;
using System.Net; using System.Net;
using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class WebApiCompatShimActionResultTest public class WebApiCompatShimActionResultTest : IClassFixture<MvcTestFixture<WebApiCompatShimWebSite.Startup>>
{ {
private const string SiteName = nameof(WebApiCompatShimWebSite); public WebApiCompatShimActionResultTest(MvcTestFixture<WebApiCompatShimWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new WebApiCompatShimWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new WebApiCompatShimWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task ApiController_BadRequest() public async Task ApiController_BadRequest()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetBadRequest");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetBadRequest");
// Assert // Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
@ -33,12 +31,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_BadRequestMessage() public async Task ApiController_BadRequestMessage()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetBadRequestMessage");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetBadRequestMessage");
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -50,13 +44,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_BadRequestModelState() public async Task ApiController_BadRequestModelState()
{ {
// Arrange // 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.\"]}}"; var expected = "{\"Message\":\"The request is invalid.\",\"ModelState\":{\"product.Name\":[\"Name is required.\"]}}";
// Act // 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(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -67,12 +58,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_Conflict() public async Task ApiController_Conflict()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetConflict");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetConflict");
// Assert // Assert
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
@ -81,12 +68,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_Content() public async Task ApiController_Content()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetContent");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetContent");
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -97,12 +80,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_CreatedRelative() public async Task ApiController_CreatedRelative()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedRelative");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedRelative");
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -114,12 +93,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_CreatedAbsolute() public async Task ApiController_CreatedAbsolute()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedAbsolute");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedAbsolute");
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -131,12 +106,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_CreatedQualified() public async Task ApiController_CreatedQualified()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedQualified");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedQualified");
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -148,12 +119,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_CreatedUri() public async Task ApiController_CreatedUri()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedUri");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedUri");
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -165,12 +132,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_CreatedAtRoute() public async Task ApiController_CreatedAtRoute()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedAtRoute");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetCreatedAtRoute");
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -182,12 +145,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_InternalServerError() public async Task ApiController_InternalServerError()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetInternalServerError");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetInternalServerError");
// Assert // Assert
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
@ -196,12 +155,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_InternalServerErrorException() public async Task ApiController_InternalServerErrorException()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetInternalServerErrorException");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetInternalServerErrorException");
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -212,12 +167,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_Json() public async Task ApiController_Json()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetJson");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetJson");
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -229,16 +180,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_JsonSettings() public async Task ApiController_JsonSettings()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = var expected =
"{" + Environment.NewLine + "{" + Environment.NewLine +
" \"Name\": \"Test User\"" + Environment.NewLine + " \"Name\": \"Test User\"" + Environment.NewLine +
"}"; "}";
// Act // 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(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -250,16 +198,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_JsonSettingsEncoding() public async Task ApiController_JsonSettingsEncoding()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = var expected =
"{" + Environment.NewLine + "{" + Environment.NewLine +
" \"Name\": \"Test User\"" + Environment.NewLine + " \"Name\": \"Test User\"" + Environment.NewLine +
"}"; "}";
// Act // 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(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -271,12 +216,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_NotFound() public async Task ApiController_NotFound()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetNotFound");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetNotFound");
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -285,12 +226,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_Ok() public async Task ApiController_Ok()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetOk");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetOk");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -299,12 +236,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_OkContent() public async Task ApiController_OkContent()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetOkContent");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetOkContent");
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -315,12 +248,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_RedirectString() public async Task ApiController_RedirectString()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetRedirectString");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetRedirectString");
// Assert // Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
@ -334,12 +263,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
"/api/Blog/BasicApi/WriteToHttpContext")] "/api/Blog/BasicApi/WriteToHttpContext")]
public async Task ApiController_RedirectUri(string url, string expected) public async Task ApiController_RedirectUri(string url, string expected)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(url);
var client = server.CreateClient();
// Act
var response = await client.GetAsync(url);
// Assert // Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
@ -349,12 +274,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_ResponseMessage() public async Task ApiController_ResponseMessage()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetResponseMessage");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetResponseMessage");
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -364,12 +285,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_StatusCode() public async Task ApiController_StatusCode()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/ActionResult/GetStatusCode");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/ActionResult/GetStatusCode");
// Assert // Assert
Assert.Equal(HttpStatusCode.PaymentRequired, response.StatusCode); Assert.Equal(HttpStatusCode.PaymentRequired, response.StatusCode);

View File

@ -1,23 +1,23 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Actions; using Microsoft.AspNet.Mvc.Actions;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class WebApiCompatShimActionSelectionTest public class WebApiCompatShimActionSelectionTest : IClassFixture<MvcTestFixture<WebApiCompatShimWebSite.Startup>>
{ {
private const string SiteName = nameof(WebApiCompatShimWebSite); public WebApiCompatShimActionSelectionTest(MvcTestFixture<WebApiCompatShimWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new WebApiCompatShimWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new WebApiCompatShimWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("GET", "GetItems")] [InlineData("GET", "GetItems")]
@ -30,20 +30,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_TakesHttpMethodFromPrefix_UnnamedAction(string httpMethod, string actionName) public async Task WebAPIConvention_TakesHttpMethodFromPrefix_UnnamedAction(string httpMethod, string actionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod(httpMethod), new HttpMethod(httpMethod),
"http://localhost/api/Admin/WebAPIActionConventions"); "http://localhost/api/Admin/WebAPIActionConventions");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(actionName, result.ActionName); Assert.Equal(actionName, result.ActionName);
} }
@ -59,20 +55,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_TakesHttpMethodFromPrefix_NamedAction(string httpMethod, string actionName) public async Task WebAPIConvention_TakesHttpMethodFromPrefix_NamedAction(string httpMethod, string actionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod(httpMethod), new HttpMethod(httpMethod),
"http://localhost/api/Blog/WebAPIActionConventions/" + actionName); "http://localhost/api/Blog/WebAPIActionConventions/" + actionName);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(actionName, result.ActionName); Assert.Equal(actionName, result.ActionName);
} }
@ -81,15 +73,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_TakesHttpMethodFromPrefix_NamedAction_MismatchedVerb() public async Task WebAPIConvention_TakesHttpMethodFromPrefix_NamedAction_MismatchedVerb()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("POST"), new HttpMethod("POST"),
"http://localhost/api/Blog/WebAPIActionConventions/GetItems"); "http://localhost/api/Blog/WebAPIActionConventions/GetItems");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -99,20 +88,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_TakesHttpMethodFromPrefix_UnnamedAction_DefaultVerbIsPost_Success() public async Task WebAPIConvention_TakesHttpMethodFromPrefix_UnnamedAction_DefaultVerbIsPost_Success()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("POST"), new HttpMethod("POST"),
"http://localhost/api/Admin/WebApiActionConventionsDefaultPost"); "http://localhost/api/Admin/WebApiActionConventionsDefaultPost");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("DefaultVerbIsPost", result.ActionName); Assert.Equal("DefaultVerbIsPost", result.ActionName);
} }
@ -121,20 +106,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_TakesHttpMethodFromPrefix_NamedAction_DefaultVerbIsPost_Success() public async Task WebAPIConvention_TakesHttpMethodFromPrefix_NamedAction_DefaultVerbIsPost_Success()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("POST"), new HttpMethod("POST"),
"http://localhost/api/Blog/WebAPIActionConventionsDefaultPost/DefaultVerbIsPost"); "http://localhost/api/Blog/WebAPIActionConventionsDefaultPost/DefaultVerbIsPost");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("DefaultVerbIsPost", result.ActionName); Assert.Equal("DefaultVerbIsPost", result.ActionName);
} }
@ -143,15 +124,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_TakesHttpMethodFromPrefix_UnnamedAction_DefaultVerbIsPost_VerbMismatch() public async Task WebAPIConvention_TakesHttpMethodFromPrefix_UnnamedAction_DefaultVerbIsPost_VerbMismatch()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("GET"), new HttpMethod("GET"),
"http://localhost/api/Admin/WebApiActionConventionsDefaultPost"); "http://localhost/api/Admin/WebApiActionConventionsDefaultPost");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -161,15 +139,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_TakesHttpMethodFromPrefix_NamedAction_DefaultVerbIsPost_VerbMismatch() public async Task WebAPIConvention_TakesHttpMethodFromPrefix_NamedAction_DefaultVerbIsPost_VerbMismatch()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("PUT"), new HttpMethod("PUT"),
"http://localhost/api/Blog/WebApiActionConventionsDefaultPost/DefaultVerbIsPost"); "http://localhost/api/Blog/WebApiActionConventionsDefaultPost/DefaultVerbIsPost");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -179,20 +154,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_TakesHttpMethodFromMethodName_NotActionName_UnnamedAction_Success() public async Task WebAPIConvention_TakesHttpMethodFromMethodName_NotActionName_UnnamedAction_Success()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("POST"), new HttpMethod("POST"),
"http://localhost/api/Admin/WebAPIActionConventionsActionName"); "http://localhost/api/Admin/WebAPIActionConventionsActionName");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("GetItems", result.ActionName); Assert.Equal("GetItems", result.ActionName);
} }
@ -201,20 +172,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_TakesHttpMethodFromMethodName_NotActionName_NamedAction_Success() public async Task WebAPIConvention_TakesHttpMethodFromMethodName_NotActionName_NamedAction_Success()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("POST"), new HttpMethod("POST"),
"http://localhost/api/Blog/WebAPIActionConventionsActionName/GetItems"); "http://localhost/api/Blog/WebAPIActionConventionsActionName/GetItems");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("GetItems", result.ActionName); Assert.Equal("GetItems", result.ActionName);
} }
@ -223,15 +190,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_TakesHttpMethodFromMethodName_NotActionName_UnnamedAction_VerbMismatch() public async Task WebAPIConvention_TakesHttpMethodFromMethodName_NotActionName_UnnamedAction_VerbMismatch()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("Get"), new HttpMethod("Get"),
"http://localhost/api/Admin/WebAPIActionConventionsActionName"); "http://localhost/api/Admin/WebAPIActionConventionsActionName");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -241,15 +205,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_TakesHttpMethodFromMethodName_NotActionName_NamedAction_VerbMismatch() public async Task WebAPIConvention_TakesHttpMethodFromMethodName_NotActionName_NamedAction_VerbMismatch()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("GET"), new HttpMethod("GET"),
"http://localhost/api/Blog/WebAPIActionConventionsActionName/GetItems"); "http://localhost/api/Blog/WebAPIActionConventionsActionName/GetItems");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -259,20 +220,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_HttpMethodOverride_UnnamedAction_Success() public async Task WebAPIConvention_HttpMethodOverride_UnnamedAction_Success()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("GET"), new HttpMethod("GET"),
"http://localhost/api/Admin/WebAPIActionConventionsVerbOverride"); "http://localhost/api/Admin/WebAPIActionConventionsVerbOverride");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("PostItems", result.ActionName); Assert.Equal("PostItems", result.ActionName);
} }
@ -281,20 +238,16 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_HttpMethodOverride_NamedAction_Success() public async Task WebAPIConvention_HttpMethodOverride_NamedAction_Success()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("GET"), new HttpMethod("GET"),
"http://localhost/api/Blog/WebAPIActionConventionsVerbOverride/PostItems"); "http://localhost/api/Blog/WebAPIActionConventionsVerbOverride/PostItems");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("PostItems", result.ActionName); Assert.Equal("PostItems", result.ActionName);
} }
@ -303,15 +256,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_HttpMethodOverride_UnnamedAction_VerbMismatch() public async Task WebAPIConvention_HttpMethodOverride_UnnamedAction_VerbMismatch()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("POST"), new HttpMethod("POST"),
"http://localhost/api/Admin/WebAPIActionConventionsVerbOverride"); "http://localhost/api/Admin/WebAPIActionConventionsVerbOverride");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -321,21 +271,18 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebAPIConvention_HttpMethodOverride_NamedAction_VerbMismatch() public async Task WebAPIConvention_HttpMethodOverride_NamedAction_VerbMismatch()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
new HttpMethod("POST"), new HttpMethod("POST"),
"http://localhost/api/Blog/WebAPIActionConventionsVerbOverride/PostItems"); "http://localhost/api/Blog/WebAPIActionConventionsVerbOverride/PostItems");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); 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] [Theory]
[InlineData("GET", "api/Admin/Test", "GetUsers")] [InlineData("GET", "api/Admin/Test", "GetUsers")]
[InlineData("GET", "api/Admin/Test/2", "GetUser")] [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) public async Task LegacyActionSelection_OverloadedAction_WithUnnamedAction(string httpMethod, string requestUrl, string expectedActionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedActionName, result.ActionName); 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) public async Task LegacyActionSelection_OverloadedAction_NonIdRouteParameter(string httpMethod, string requestUrl, string expectedActionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedActionName, result.ActionName); 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) public async Task LegacyActionSelection_OverloadedAction_Parameter_Casing(string httpMethod, string requestUrl, string expectedActionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedActionName, result.ActionName); 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) public async Task LegacyActionSelection_RouteWithActionName(string httpMethod, string requestUrl, string expectedActionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedActionName, result.ActionName); 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) public async Task LegacyActionSelection_RouteWithActionName_Casing(string httpMethod, string requestUrl, string expectedActionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedActionName, result.ActionName); 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) public async Task LegacyActionSelection_RouteWithoutActionName(string httpMethod, string requestUrl, string expectedActionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedActionName, result.ActionName); 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) public async Task LegacyActionSelection_ModelBindingParameterAttribute_AreAppliedWhenSelectingActions(string httpMethod, string requestUrl, string expectedActionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedActionName, result.ActionName); 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) public async Task LegacyActionSelection_ActionsThatHaveSubsetOfRouteParameters_AreConsideredForSelection(string httpMethod, string requestUrl, string expectedActionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedActionName, result.ActionName); Assert.Equal(expectedActionName, result.ActionName);
} }
@ -574,13 +489,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task LegacyActionSelection_RequestToAmbiguousAction_OnDefaultRoute() public async Task LegacyActionSelection_RequestToAmbiguousAction_OnDefaultRoute()
{ {
// Arrange // 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"); var request = new HttpRequestMessage(new HttpMethod("POST"), "http://localhost/api/Admin/Test?name=mario");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
var exception = response.GetServerException(); 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) public async Task LegacyActionSelection_SelectAction_ReturnsActionDescriptor_ForEnumParameterOverloads(string httpMethod, string requestUrl, string expectedActionName)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl); var request = new HttpRequestMessage(new HttpMethod(httpMethod), "http://localhost/" + requestUrl);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
// Assert // Assert
var data = Assert.Single(response.Headers.GetValues("ActionSelection"));
var result = JsonConvert.DeserializeObject<ActionSelectionResult>(data);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedActionName, result.ActionName); Assert.Equal(expectedActionName, result.ActionName);
} }

View File

@ -19,21 +19,25 @@ using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class WebApiCompatShimBasicTest public class WebApiCompatShimBasicTest : IClassFixture<MvcTestFixture<WebApiCompatShimWebSite.Startup>>
{ {
private const string SiteName = nameof(WebApiCompatShimWebSite); private const string SiteName = nameof(WebApiCompatShimWebSite);
private readonly Action<IApplicationBuilder> _app = new WebApiCompatShimWebSite.Startup().Configure; private readonly Action<IApplicationBuilder> _app = new WebApiCompatShimWebSite.Startup().Configure;
private readonly Action<IServiceCollection> _configureServices = new WebApiCompatShimWebSite.Startup().ConfigureServices; private readonly Action<IServiceCollection> _configureServices =
new WebApiCompatShimWebSite.Startup().ConfigureServices;
public WebApiCompatShimBasicTest(MvcTestFixture<WebApiCompatShimWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task ApiController_Activates_HttpContextAndUser() public async Task ApiController_Activates_HttpContextAndUser()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/BasicApi/WriteToHttpContext");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/BasicApi/WriteToHttpContext");
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -46,12 +50,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_Activates_UrlHelper() public async Task ApiController_Activates_UrlHelper()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/BasicApi/GenerateUrl");
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/BasicApi/GenerateUrl");
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -61,24 +61,21 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
content); content);
} }
#if !DNXCORE50
[Fact] [Fact]
public async Task Options_SetsDefaultFormatters() public async Task Options_SetsDefaultFormatters()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = new string[] var expected = new string[]
{ {
typeof(JsonMediaTypeFormatter).FullName, typeof(JsonMediaTypeFormatter).FullName,
typeof(XmlMediaTypeFormatter).FullName, typeof(XmlMediaTypeFormatter).FullName,
#if !DNXCORE50
typeof(FormUrlEncodedMediaTypeFormatter).FullName, typeof(FormUrlEncodedMediaTypeFormatter).FullName,
#endif
}; };
// Act // 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 content = await response.Content.ReadAsStringAsync();
var formatters = JsonConvert.DeserializeObject<string[]>(content); var formatters = JsonConvert.DeserializeObject<string[]>(content);
@ -88,17 +85,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Assert.Equal(expected, formatters); Assert.Equal(expected, formatters);
} }
#endif
[Fact] [Fact]
public async Task ActionThrowsHttpResponseException_WithStatusCode() public async Task ActionThrowsHttpResponseException_WithStatusCode()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/api/Blog/HttpResponseException/ThrowsHttpResponseExceptionWithHttpStatusCode"); "http://localhost/api/Blog/HttpResponseException/ThrowsHttpResponseExceptionWithHttpStatusCode");
// Assert // Assert
@ -110,12 +101,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ActionThrowsHttpResponseException_WithResponse() public async Task ActionThrowsHttpResponseException_WithResponse()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/api/Blog/HttpResponseException" + "http://localhost/api/Blog/HttpResponseException" +
"/ThrowsHttpResponseExceptionWithHttpResponseMessage?message=send some message"); "/ThrowsHttpResponseExceptionWithHttpResponseMessage?message=send some message");
@ -128,12 +115,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ActionThrowsHttpResponseException_EnsureGlobalHttpresponseExceptionActionFilter_IsInvoked() public async Task ActionThrowsHttpResponseException_EnsureGlobalHttpresponseExceptionActionFilter_IsInvoked()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/api/Blog/HttpResponseException/ThrowsHttpResponseExceptionEnsureGlobalFilterRunsLast"); "http://localhost/api/Blog/HttpResponseException/ThrowsHttpResponseExceptionEnsureGlobalFilterRunsLast");
// Assert // Assert
@ -146,12 +129,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ActionThrowsHttpResponseException_EnsureGlobalFilterConvention_IsApplied() public async Task ActionThrowsHttpResponseException_EnsureGlobalFilterConvention_IsApplied()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync(
var client = server.CreateClient();
// Act
var response = await client.GetAsync(
"http://localhost/api/Blog/" + "http://localhost/api/Blog/" +
"HttpResponseException/ThrowsHttpResponseExceptionInjectAFilterToHandleHttpResponseException"); "HttpResponseException/ThrowsHttpResponseExceptionInjectAFilterToHandleHttpResponseException");
@ -165,12 +144,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_CanValidateCustomObjectWithPrefix_Fails() public async Task ApiController_CanValidateCustomObjectWithPrefix_Fails()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetStringAsync(
var client = server.CreateClient();
// Act
var response = await client.GetStringAsync(
"http://localhost/api/Blog/BasicApi/ValidateObjectWithPrefixFails?prefix=prefix"); "http://localhost/api/Blog/BasicApi/ValidateObjectWithPrefixFails?prefix=prefix");
// Assert // Assert
@ -182,12 +157,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_CanValidateCustomObject_IsSuccessFul() public async Task ApiController_CanValidateCustomObject_IsSuccessFul()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetStringAsync("http://localhost/api/Blog/BasicApi/ValidateObject_Passes");
var client = server.CreateClient();
// Act
var response = await client.GetStringAsync("http://localhost/api/Blog/BasicApi/ValidateObject_Passes");
// Assert // Assert
Assert.Equal("true", response); Assert.Equal("true", response);
@ -196,12 +167,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact] [Fact]
public async Task ApiController_CanValidateCustomObject_Fails() public async Task ApiController_CanValidateCustomObject_Fails()
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetStringAsync("http://localhost/api/Blog/BasicApi/ValidateObjectFails");
var client = server.CreateClient();
// Act
var response = await client.GetStringAsync("http://localhost/api/Blog/BasicApi/ValidateObjectFails");
// Assert // Assert
var json = JsonConvert.DeserializeObject<Dictionary<string, string>>(response); var json = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
@ -215,15 +182,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_RequestProperty() public async Task ApiController_RequestProperty()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var expected = "POST http://localhost/api/Blog/HttpRequestMessage/EchoProperty localhost " +
var client = server.CreateClient();
var expected =
"POST http://localhost/api/Blog/HttpRequestMessage/EchoProperty localhost " +
"13 Hello, world!"; "13 Hello, world!";
// Act // Act
var response = await client.PostAsync( var response = await Client.PostAsync(
"http://localhost/api/Blog/HttpRequestMessage/EchoProperty", "http://localhost/api/Blog/HttpRequestMessage/EchoProperty",
new StringContent("Hello, world!")); new StringContent("Hello, world!"));
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
@ -239,15 +202,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_RequestParameter() public async Task ApiController_RequestParameter()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = var expected =
"POST http://localhost/api/Blog/HttpRequestMessage/EchoParameter localhost " + "POST http://localhost/api/Blog/HttpRequestMessage/EchoParameter localhost " +
"17 Hello, the world!"; "17 Hello, the world!";
// Act // Act
var response = await client.PostAsync( var response = await Client.PostAsync(
"http://localhost/api/Blog/HttpRequestMessage/EchoParameter", "http://localhost/api/Blog/HttpRequestMessage/EchoParameter",
new StringContent("Hello, the world!")); new StringContent("Hello, the world!"));
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
@ -261,14 +221,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_ResponseReturned() public async Task ApiController_ResponseReturned()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var expected = "POST Hello, HttpResponseMessage world!";
var client = server.CreateClient();
var expected =
"POST Hello, HttpResponseMessage world!";
// Act // Act
var response = await client.PostAsync( var response = await Client.PostAsync(
"http://localhost/api/Blog/HttpRequestMessage/EchoWithResponseMessage", "http://localhost/api/Blog/HttpRequestMessage/EchoWithResponseMessage",
new StringContent("Hello, HttpResponseMessage world!")); new StringContent("Hello, HttpResponseMessage world!"));
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
@ -287,22 +243,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_ExplicitChunkedEncoding_IsIgnored() public async Task ApiController_ExplicitChunkedEncoding_IsIgnored()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var expected = "POST Hello, HttpResponseMessage world!";
var client = server.CreateClient();
var expected =
"POST Hello, HttpResponseMessage world!";
// Act
var request = new HttpRequestMessage(); var request = new HttpRequestMessage();
request.Method = HttpMethod.Post; request.Method = HttpMethod.Post;
request.RequestUri = new Uri("http://localhost/api/Blog/HttpRequestMessage/EchoWithResponseMessageChunked"); request.RequestUri = new Uri("http://localhost/api/Blog/HttpRequestMessage/EchoWithResponseMessageChunked");
request.Content = new StringContent("Hello, HttpResponseMessage world!"); request.Content = new StringContent("Hello, HttpResponseMessage world!");
// Act
// HttpClient buffers the response by default and this would set the Content-Length header and so // 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 // 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. // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -315,7 +266,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Assert.Null(response.Headers.TransferEncodingChunked); 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 // response stream for us. But since we are reading the content explicitly, we need
// to close it. // to close it.
var responseStream = await response.Content.ReadAsStreamAsync(); var responseStream = await response.Content.ReadAsStreamAsync();
@ -343,7 +294,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Get, HttpMethod.Get,
"http://localhost/api/Blog/HttpRequestMessage/GetUser"); "http://localhost/api/Blog/HttpRequestMessage/GetUser");
request.Headers.Accept.ParseAdd(accept); request.Headers.Accept.ParseAdd(accept);
// Act // Act
@ -393,7 +343,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Get, HttpMethod.Get,
"http://localhost/api/Blog/HttpRequestMessage/Fail"); "http://localhost/api/Blog/HttpRequestMessage/Fail");
request.Headers.Accept.ParseAdd(accept); request.Headers.Accept.ParseAdd(accept);
// Act // Act
@ -410,9 +359,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_CreateResponse_HardcodedFormatter() public async Task ApiController_CreateResponse_HardcodedFormatter()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Get, HttpMethod.Get,
"http://localhost/api/Blog/HttpRequestMessage/GetUserJson"); "http://localhost/api/Blog/HttpRequestMessage/GetUserJson");
@ -421,7 +367,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml")); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var user = await response.Content.ReadAsAsync<WebApiCompatShimWebSite.User>(); var user = await response.Content.ReadAsAsync<WebApiCompatShimWebSite.User>();
// Assert // Assert
@ -436,13 +382,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebApiRouting_AccessMvcController(string url, HttpStatusCode expected) public async Task WebApiRouting_AccessMvcController(string url, HttpStatusCode expected)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(expected, response.StatusCode); Assert.Equal(expected, response.StatusCode);
@ -454,13 +397,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task WebApiRouting_AccessWebApiController(string url, HttpStatusCode expected) public async Task WebApiRouting_AccessWebApiController(string url, HttpStatusCode expected)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(expected, response.StatusCode); Assert.Equal(expected, response.StatusCode);
@ -470,12 +410,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_Returns_ByteArrayContent() public async Task ApiController_Returns_ByteArrayContent()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedBody = "Hello from ByteArrayContent!!"; var expectedBody = "Hello from ByteArrayContent!!";
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -490,12 +428,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_Returns_StreamContent() public async Task ApiController_Returns_StreamContent()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedBody = "This content is from a file"; var expectedBody = "This content is from a file";
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -513,12 +449,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("ReturnPushStreamContentSync", "Hello from PushStreamContent Sync!!")] [InlineData("ReturnPushStreamContentSync", "Hello from PushStreamContent Sync!!")]
public async Task ApiController_Returns_PushStreamContent(string action, string expectedBody) public async Task ApiController_Returns_PushStreamContent(string action, string expectedBody)
{ {
// Arrange // Arrange & Act
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var response = await Client.GetAsync("http://localhost/api/Blog/HttpRequestMessage/" + action);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/api/Blog/HttpRequestMessage/" + action);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -533,13 +465,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_Returns_PushStreamContentWithCustomHeaders() public async Task ApiController_Returns_PushStreamContentWithCustomHeaders()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedBody = "Hello from PushStreamContent with custom headers!!"; var expectedBody = "Hello from PushStreamContent with custom headers!!";
var multipleValues = new[] { "value1", "value2" }; var multipleValues = new[] { "value1", "value2" };
// Act // 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
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -1,24 +1,24 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class WebApiCompatShimParameterBindingTest public class WebApiCompatShimParameterBindingTest : IClassFixture<MvcTestFixture<WebApiCompatShimWebSite.Startup>>
{ {
private const string SiteName = nameof(WebApiCompatShimWebSite); public WebApiCompatShimParameterBindingTest(MvcTestFixture<WebApiCompatShimWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new WebApiCompatShimWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new WebApiCompatShimWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("http://localhost/api/Blog/Employees/PostByIdDefault/5")] [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) public async Task ApiController_SimpleParameter_Default_ReadsFromUrl(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -44,9 +41,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_SimpleParameter_Default_DoesNotReadFormData() public async Task ApiController_SimpleParameter_Default_DoesNotReadFormData()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/api/Blog/Employees/PostByIdDefault"; var url = "http://localhost/api/Blog/Employees/PostByIdDefault";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = new FormUrlEncodedContent(new Dictionary<string, string>() request.Content = new FormUrlEncodedContent(new Dictionary<string, string>()
@ -55,7 +49,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}); });
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -69,13 +63,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_SimpleParameter_ModelBinder_ReadsFromUrl(string url) public async Task ApiController_SimpleParameter_ModelBinder_ReadsFromUrl(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -87,9 +78,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_SimpleParameter_ModelBinder_ReadsFromFormData() public async Task ApiController_SimpleParameter_ModelBinder_ReadsFromFormData()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/api/Blog/Employees/PostByIdModelBinder"; var url = "http://localhost/api/Blog/Employees/PostByIdModelBinder";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = new FormUrlEncodedContent(new Dictionary<string, string>() request.Content = new FormUrlEncodedContent(new Dictionary<string, string>()
@ -98,7 +86,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}); });
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -112,13 +100,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_SimpleParameter_FromQuery_ReadsFromQueryNotRouteData(string url, string expected) public async Task ApiController_SimpleParameter_FromQuery_ReadsFromQueryNotRouteData(string url, string expected)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -130,9 +115,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_SimpleParameter_FromQuery_DoesNotReadFormData() public async Task ApiController_SimpleParameter_FromQuery_DoesNotReadFormData()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/api/Blog/Employees/PostByIdFromQuery"; var url = "http://localhost/api/Blog/Employees/PostByIdFromQuery";
var request = new HttpRequestMessage(HttpMethod.Post, url); var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = new FormUrlEncodedContent(new Dictionary<string, string>() request.Content = new FormUrlEncodedContent(new Dictionary<string, string>()
@ -141,7 +123,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}); });
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -153,9 +135,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_ComplexParameter_Default_ReadsFromBody() public async Task ApiController_ComplexParameter_Default_ReadsFromBody()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/api/Blog/Employees/PutEmployeeDefault"; var url = "http://localhost/api/Blog/Employees/PutEmployeeDefault";
var request = new HttpRequestMessage(HttpMethod.Put, url); var request = new HttpRequestMessage(HttpMethod.Put, url);
request.Content = new StringContent(JsonConvert.SerializeObject(new request.Content = new StringContent(JsonConvert.SerializeObject(new
@ -166,7 +145,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -178,9 +157,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_ComplexParameter_ModelBinder_ReadsFormAndUrl() public async Task ApiController_ComplexParameter_ModelBinder_ReadsFormAndUrl()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/api/Blog/Employees/PutEmployeeModelBinder/5"; var url = "http://localhost/api/Blog/Employees/PutEmployeeModelBinder/5";
var request = new HttpRequestMessage(HttpMethod.Put, url); var request = new HttpRequestMessage(HttpMethod.Put, url);
request.Content = new FormUrlEncodedContent(new Dictionary<string, string>() request.Content = new FormUrlEncodedContent(new Dictionary<string, string>()
@ -189,7 +165,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
}); });
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert
@ -202,9 +178,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ApiController_TwoParameters_DefaultSources() public async Task ApiController_TwoParameters_DefaultSources()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var url = "http://localhost/api/Blog/Employees/PutEmployeeBothDefault?name=Name_Override"; var url = "http://localhost/api/Blog/Employees/PutEmployeeBothDefault?name=Name_Override";
var request = new HttpRequestMessage(HttpMethod.Put, url); var request = new HttpRequestMessage(HttpMethod.Put, url);
request.Content = new StringContent(JsonConvert.SerializeObject(new request.Content = new StringContent(JsonConvert.SerializeObject(new
@ -215,7 +188,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
// Assert // Assert

View File

@ -1,24 +1,24 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Mvc.Formatters.Xml;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class XmlDataContractSerializerFormattersWrappingTest public class XmlDataContractSerializerFormattersWrappingTest : IClassFixture<MvcTestFixture<XmlFormattersWebSite.Startup>>
{ {
private const string SiteName = nameof(XmlFormattersWebSite); public XmlDataContractSerializerFormattersWrappingTest(MvcTestFixture<XmlFormattersWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new XmlFormattersWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new XmlFormattersWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[ConditionalTheory] [ConditionalTheory]
// Mono issue - https://github.com/aspnet/External/issues/18 // Mono issue - https://github.com/aspnet/External/issues/18
@ -28,18 +28,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_ValueTypes(string url) public async Task CanWrite_ValueTypes(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync(); var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfint xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" + XmlAssert.Equal(
"<ArrayOfint xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">" + " xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">" +
"<int>10</int><int>20</int></ArrayOfint>", "<int>10</int><int>20</int></ArrayOfint>",
result); result);
@ -53,18 +52,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_NonWrappedTypes(string url) public async Task CanWrite_NonWrappedTypes(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync(); var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfstring xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" + XmlAssert.Equal(
"<ArrayOfstring xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">" + " xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">" +
"<string>value1</string><string>value2</string></ArrayOfstring>", "<string>value1</string><string>value2</string></ArrayOfstring>",
result); result);
@ -78,18 +76,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_NonWrappedTypes_Empty(string url) public async Task CanWrite_NonWrappedTypes_Empty(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync(); var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfstring xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" + XmlAssert.Equal(
"<ArrayOfstring xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" />", " xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" />",
result); result);
} }
@ -102,18 +99,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_NonWrappedTypes_NullInstance(string url) public async Task CanWrite_NonWrappedTypes_NullInstance(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync(); var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfstring i:nil=\"true\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" + XmlAssert.Equal(
"<ArrayOfstring i:nil=\"true\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" />", " xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" />",
result); result);
} }
@ -126,18 +122,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_WrappedTypes(string url) public async Task CanWrite_WrappedTypes(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync(); var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfPersonWrapper xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" + XmlAssert.Equal(
"<ArrayOfPersonWrapper xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite\"><PersonWrapper>" + " xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite\"><PersonWrapper>" +
"<Age>35</Age><Id>10</Id><Name>Mike</Name></PersonWrapper><PersonWrapper><Age>35</Age><Id>" + "<Age>35</Age><Id>10</Id><Name>Mike</Name></PersonWrapper><PersonWrapper><Age>35</Age><Id>" +
"11</Id><Name>Jimmy</Name></PersonWrapper></ArrayOfPersonWrapper>", "11</Id><Name>Jimmy</Name></PersonWrapper></ArrayOfPersonWrapper>",
@ -152,18 +147,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_WrappedTypes_Empty(string url) public async Task CanWrite_WrappedTypes_Empty(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync(); var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfPersonWrapper xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" + XmlAssert.Equal(
"<ArrayOfPersonWrapper xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite\" />", " xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite\" />",
result); result);
} }
@ -176,18 +170,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_WrappedTypes_NullInstance(string url) public async Task CanWrite_WrappedTypes_NullInstance(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync(); var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfPersonWrapper i:nil=\"true\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" + XmlAssert.Equal(
"<ArrayOfPersonWrapper i:nil=\"true\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite\" />", " xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite\" />",
result); result);
} }
@ -198,18 +191,17 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_IEnumerableOf_SerializableErrors() public async Task CanWrite_IEnumerableOf_SerializableErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/IEnumerable/SerializableErrors"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/IEnumerable/SerializableErrors");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-dcs"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var result = await response.Content.ReadAsStringAsync(); var result = await response.Content.ReadAsStringAsync();
XmlAssert.Equal("<ArrayOfSerializableErrorWrapper xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" + XmlAssert.Equal(
"<ArrayOfSerializableErrorWrapper xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.AspNet.Mvc.Formatters.Xml\"><SerializableErrorWrapper>" + " xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.AspNet.Mvc.Formatters.Xml\"><SerializableErrorWrapper>" +
"<key1>key1-error</key1><key2>key2-error</key2></SerializableErrorWrapper><SerializableErrorWrapper>" + "<key1>key1-error</key1><key2>key2-error</key2></SerializableErrorWrapper><SerializableErrorWrapper>" +
"<key3>key1-error</key3><key4>key2-error</key4></SerializableErrorWrapper>" + "<key3>key1-error</key3><key4>key2-error</key4></SerializableErrorWrapper>" +

View File

@ -1,7 +1,6 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
@ -11,19 +10,14 @@ using System.Net.Http.Headers;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using XmlFormattersWebSite; using XmlFormattersWebSite;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class XmlDataContractSerializerInputFormatterTest public class XmlDataContractSerializerInputFormatterTest : IClassFixture<MvcTestFixture<XmlFormattersWebSite.Startup>>
{ {
private const string SiteName = nameof(XmlFormattersWebSite);
private readonly Action<IApplicationBuilder> _app = new Startup().Configure;
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices;
private readonly string errorMessageFormat = string.Format( private readonly string errorMessageFormat = string.Format(
"{{1}}:{0} does not recognize '{1}', so instead use '{2}' with '{3}' set to '{4}' for value " + "{{1}}:{0} does not recognize '{1}', so instead use '{2}' with '{3}' set to '{4}' for value " +
"type property '{{0}}' on type '{{1}}'.", "type property '{{0}}' on type '{{1}}'.",
@ -33,19 +27,24 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
nameof(DataMemberAttribute.IsRequired), nameof(DataMemberAttribute.IsRequired),
bool.TrueString); bool.TrueString);
public XmlDataContractSerializerInputFormatterTest(MvcTestFixture<XmlFormattersWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[ConditionalFact] [ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18 // Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)] [FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ThrowsOnInvalidInput_AndAddsToModelState() public async Task ThrowsOnInvalidInput_AndAddsToModelState()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "Not a valid xml document"; var input = "Not a valid xml document";
var content = new StringContent(input, Encoding.UTF8, "application/xml-dcs"); var content = new StringContent(input, Encoding.UTF8, "application/xml-dcs");
// Act // 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.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
@ -63,16 +62,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task RequiredDataIsProvided_AndModelIsBound_NoValidationErrors() public async Task RequiredDataIsProvided_AndModelIsBound_NoValidationErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml-dcs"));
var input = "<Store xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite\" " + var input = "<Store xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite\" " +
"xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Address><State>WA</State><Zipcode>" + "xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Address><State>WA</State><Zipcode>" +
"98052</Zipcode></Address><Id>10</Id></Store>"; "98052</Zipcode></Address><Id>10</Id></Store>";
var content = new StringContent(input, Encoding.UTF8, "application/xml-dcs"); 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 // 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 dcsSerializer = new DataContractSerializer(typeof(ModelBindingInfo));
@ -94,19 +92,18 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task DataMissingForRefereneceTypeProperties_AndModelIsBound_AndHasMixedValidationErrors() public async Task DataMissingForRefereneceTypeProperties_AndModelIsBound_AndHasMixedValidationErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml-dcs"));
var input = "<Store xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite\"" + var input = "<Store xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite\"" +
" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" + " xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<Address i:nil=\"true\"/><Id>10</Id></Store>"; "<Address i:nil=\"true\"/><Id>10</Id></Store>";
var content = new StringContent(input, Encoding.UTF8, "application/xml-dcs"); 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<string>(); var expectedErrorMessages = new List<string>();
expectedErrorMessages.Add("Address:The Address field is required."); expectedErrorMessages.Add("Address:The Address field is required.");
// Act // 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 dcsSerializer = new DataContractSerializer(typeof(ModelBindingInfo));

View File

@ -1,25 +1,24 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Threading.Tasks; using System.Threading.Tasks;
using FormatterWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Mvc.Formatters.Xml;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class XmlOutputFormatterTests public class XmlOutputFormatterTests : IClassFixture<MvcTestFixture<FormatterWebSite.Startup>>
{ {
private const string SiteName = nameof(FormatterWebSite); public XmlOutputFormatterTests(MvcTestFixture<FormatterWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[ConditionalFact] [ConditionalFact]
// Mono.Xml2.XmlTextReader.ReadText is unable to read the XML. This is fixed in mono 4.3.0. // Mono.Xml2.XmlTextReader.ReadText is unable to read the XML. This is fixed in mono 4.3.0.
@ -27,15 +26,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task XmlDataContractSerializerOutputFormatterIsCalled() public async Task XmlDataContractSerializerOutputFormatterIsCalled()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Post, HttpMethod.Post,
"http://localhost/Home/GetDummyClass?sampleInput=10"); "http://localhost/Home/GetDummyClass?sampleInput=10");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -50,15 +47,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task XmlSerializerOutputFormatterIsCalled() public async Task XmlSerializerOutputFormatterIsCalled()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Post, HttpMethod.Post,
"http://localhost/XmlSerializer/GetDummyClass?sampleInput=10"); "http://localhost/XmlSerializer/GetDummyClass?sampleInput=10");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -74,15 +69,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task XmlSerializerFailsAndDataContractSerializerIsCalled() public async Task XmlSerializerFailsAndDataContractSerializerIsCalled()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Post, HttpMethod.Post,
"http://localhost/DataContractSerializer/GetPerson?name=HelloWorld"); "http://localhost/DataContractSerializer/GetPerson?name=HelloWorld");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -97,15 +90,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task XmlSerializerOutputFormatter_WhenDerivedClassIsReturned() public async Task XmlSerializerOutputFormatter_WhenDerivedClassIsReturned()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Post, HttpMethod.Post,
"http://localhost/XmlSerializer/GetDerivedDummyClass?sampleInput=10"); "http://localhost/XmlSerializer/GetDerivedDummyClass?sampleInput=10");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -122,15 +113,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task XmlDataContractSerializerOutputFormatter_WhenDerivedClassIsReturned() public async Task XmlDataContractSerializerOutputFormatter_WhenDerivedClassIsReturned()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Post, HttpMethod.Post,
"http://localhost/Home/GetDerivedDummyClass?sampleInput=10"); "http://localhost/Home/GetDerivedDummyClass?sampleInput=10");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -145,15 +134,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task XmlSerializerFormatter_DoesNotWriteDictionaryObjects() public async Task XmlSerializerFormatter_DoesNotWriteDictionaryObjects()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage( var request = new HttpRequestMessage(
HttpMethod.Post, HttpMethod.Post,
"http://localhost/XmlSerializer/GetDictionary"); "http://localhost/XmlSerializer/GetDictionary");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml;charset=utf-8"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);

View File

@ -1,23 +1,23 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc.Formatters.Xml; using Microsoft.AspNet.Mvc.Formatters.Xml;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class XmlSerializerFormattersWrappingTest public class XmlSerializerFormattersWrappingTest : IClassFixture<MvcTestFixture<XmlFormattersWebSite.Startup>>
{ {
private const string SiteName = nameof(XmlFormattersWebSite); public XmlSerializerFormattersWrappingTest(MvcTestFixture<XmlFormattersWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new XmlFormattersWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new XmlFormattersWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory] [Theory]
[InlineData("http://localhost/IEnumerable/ValueTypes")] [InlineData("http://localhost/IEnumerable/ValueTypes")]
@ -25,13 +25,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_ValueTypes(string url) public async Task CanWrite_ValueTypes(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -48,13 +46,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_NonWrappedTypes(string url) public async Task CanWrite_NonWrappedTypes(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -71,13 +67,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_NonWrappedTypes_NullInstance(string url) public async Task CanWrite_NonWrappedTypes_NullInstance(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -93,13 +87,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_NonWrappedTypes_Empty(string url) public async Task CanWrite_NonWrappedTypes_Empty(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -115,13 +107,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_WrappedTypes(string url) public async Task CanWrite_WrappedTypes(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -139,13 +129,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_WrappedTypes_Empty(string url) public async Task CanWrite_WrappedTypes_Empty(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -162,13 +150,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_WrappedTypes_NullInstance(string url) public async Task CanWrite_WrappedTypes_NullInstance(string url)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url); var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -182,13 +168,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanWrite_IEnumerableOf_SerializableErrors() public async Task CanWrite_IEnumerableOf_SerializableErrors()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/IEnumerable/SerializableErrors"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/IEnumerable/SerializableErrors");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser")); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml-xmlser"));
// Act // Act
var response = await client.SendAsync(request); var response = await Client.SendAsync(request);
// Assert // Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);

View File

@ -1,30 +1,28 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing.xunit; using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.DependencyInjection;
using Xunit; using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests namespace Microsoft.AspNet.Mvc.FunctionalTests
{ {
public class XmlSerializerInputFormatterTests public class XmlSerializerInputFormatterTests : IClassFixture<MvcTestFixture<XmlFormattersWebSite.Startup>>
{ {
private const string SiteName = nameof(XmlFormattersWebSite); public XmlSerializerInputFormatterTests(MvcTestFixture<XmlFormattersWebSite.Startup> fixture)
private readonly Action<IApplicationBuilder> _app = new XmlFormattersWebSite.Startup().Configure; {
private readonly Action<IServiceCollection> _configureServices = new XmlFormattersWebSite.Startup().ConfigureServices; Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact] [Fact]
public async Task CheckIfXmlSerializerInputFormatterIsCalled() public async Task CheckIfXmlSerializerInputFormatterIsCalled()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var sampleInputInt = 10; var sampleInputInt = 10;
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<DummyClass><SampleInt>" "<DummyClass><SampleInt>"
@ -32,7 +30,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var content = new StringContent(input, Encoding.UTF8, "application/xml-xmlser"); var content = new StringContent(input, Encoding.UTF8, "application/xml-xmlser");
// Act // 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(HttpStatusCode.OK, response.StatusCode);
@ -45,13 +43,11 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ThrowsOnInvalidInput_AndAddsToModelState() public async Task ThrowsOnInvalidInput_AndAddsToModelState()
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "Not a valid xml document"; var input = "Not a valid xml document";
var content = new StringContent(input, Encoding.UTF8, "application/xml-xmlser"); var content = new StringContent(input, Encoding.UTF8, "application/xml-xmlser");
// Act // 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.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);

View File

@ -1,4 +1,4 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
@ -39,63 +39,63 @@
<!-- Fallback to static href --> <!-- Fallback to static href -->
<link href="HtmlEncode[[/styles/site.min.css?a=b&c=d]]" rel="stylesheet" data-extra="test" title="&quot;the&quot; title" /> <link href="HtmlEncode[[/styles/site.min.css?a=b&c=d]]" rel="stylesheet" data-extra="test" title="&quot;the&quot; title" />
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css?a=b&c=d]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css?a=b&c=d]]"]);</script>
<!-- Fallback from globbed href to static href --> <!-- Fallback from globbed href to static href -->
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]"]);</script>
<!-- Fallback from globbed href with exclude to static href --> <!-- Fallback from globbed href with exclude to static href -->
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]"]);</script>
<!-- Fallback from globbed and static href to static href --> <!-- Fallback from globbed and static href to static href -->
<link href="HtmlEncode[[styles/site.min.css]]" rel="stylesheet" data-extra="test" /><link href="HtmlEncode[[/styles/site.css]]" rel="stylesheet" data-extra="test" /> <link href="HtmlEncode[[styles/site.min.css]]" rel="stylesheet" data-extra="test" /><link href="HtmlEncode[[/styles/site.css]]" rel="stylesheet" data-extra="test" />
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]"]);</script>
<!-- Fallback from globbed and static href with exclude to static href --> <!-- Fallback from globbed and static href with exclude to static href -->
<link href="HtmlEncode[[styles/site.min.css]]" rel="stylesheet" data-extra="test" /> <link href="HtmlEncode[[styles/site.min.css]]" rel="stylesheet" data-extra="test" />
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]"]);</script>
<!-- Fallback to static href with no primary href --> <!-- Fallback to static href with no primary href -->
<link rel="stylesheet" data-extra="test"> <link rel="stylesheet" data-extra="test">
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]"]);</script>
<!-- Fallback to globbed href --> <!-- Fallback to globbed href -->
<link href="HtmlEncode[[/styles/site.min.css]]" rel="stylesheet" data-extra="test" /> <link href="HtmlEncode[[/styles/site.min.css]]" rel="stylesheet" data-extra="test" />
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]"]);</script>
<!-- Fallback to static and globbed href --> <!-- Fallback to static and globbed href -->
<link href="HtmlEncode[[/styles/site.min.css]]" rel="stylesheet" data-extra="test" /> <link href="HtmlEncode[[/styles/site.min.css]]" rel="stylesheet" data-extra="test" />
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]","JavaScriptEncode[[/styles/sub/site2.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]","JavaScriptStringEncode[[/styles/sub/site2.css]]"]);</script>
<!-- Fallback to static and globbed href should dedupe --> <!-- Fallback to static and globbed href should dedupe -->
<link href="HtmlEncode[[/styles/site.min.css]]" rel="stylesheet" data-extra="test" /> <link href="HtmlEncode[[/styles/site.min.css]]" rel="stylesheet" data-extra="test" />
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]"]);</script>
<!-- Fallback to static and globbed href with exclude --> <!-- Fallback to static and globbed href with exclude -->
<link href="HtmlEncode[[/styles/site.min.css]]" rel="stylesheet" data-extra="test" /> <link href="HtmlEncode[[/styles/site.min.css]]" rel="stylesheet" data-extra="test" />
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]","JavaScriptEncode[[/styles/sub/site2.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]","JavaScriptStringEncode[[/styles/sub/site2.css]]"]);</script>
<!-- Fallback from globbed href to glbobed href --> <!-- Fallback from globbed href to glbobed href -->
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]"]);</script>
<!-- Fallback from globbed href with exclude to globbed href --> <!-- Fallback from globbed href with exclude to globbed href -->
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]"]);</script>
<!-- Fallback from globbed and static href to globbed href --> <!-- Fallback from globbed and static href to globbed href -->
<link href="HtmlEncode[[styles/site.min.css]]" rel="stylesheet" data-extra="test" /><link href="HtmlEncode[[/styles/site.css]]" rel="stylesheet" data-extra="test" /> <link href="HtmlEncode[[styles/site.min.css]]" rel="stylesheet" data-extra="test" /><link href="HtmlEncode[[/styles/site.css]]" rel="stylesheet" data-extra="test" />
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]"]);</script>
<!-- Fallback from globbed and static href with exclude to globbed href --> <!-- Fallback from globbed and static href with exclude to globbed href -->
<link href="HtmlEncode[[styles/site.min.css]]" rel="stylesheet" data-extra="test"> <link href="HtmlEncode[[styles/site.min.css]]" rel="stylesheet" data-extra="test">
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]"]);</script>
<!-- Kitchen sink, all the attributes --> <!-- Kitchen sink, all the attributes -->
<link href="HtmlEncode[[styles/site.min.css]]" rel="stylesheet" data-extra="test" /> <link href="HtmlEncode[[styles/site.min.css]]" rel="stylesheet" data-extra="test" />
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css]]","JavaScriptEncode[[/styles/sub/site2.css]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css]]","JavaScriptStringEncode[[/styles/sub/site2.css]]"]);</script>
<!-- Fallback to globbed href that doesn't exist --> <!-- Fallback to globbed href that doesn't exist -->
<link href="HtmlEncode[[/styles/site.min.css]]" rel="stylesheet" data-extra="test" /> <link href="HtmlEncode[[/styles/site.min.css]]" rel="stylesheet" data-extra="test" />
@ -120,7 +120,7 @@
<!-- Fallback with file version --> <!-- Fallback with file version -->
<link href="HtmlEncode[[/styles/site.min.css]]" rel="stylesheet" data-extra="test"> <link href="HtmlEncode[[/styles/site.min.css]]" rel="stylesheet" data-extra="test">
<meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptEncode[[visibility]]","JavaScriptEncode[[hidden]]",["JavaScriptEncode[[/styles/site.css?v=XY7YsMemPf8AGU4SIX9ED9eOjK1LOQWu2dmCNmh-pQc]]"]);</script> <meta name="x-stylesheet-fallback-test" class="HtmlEncode[[hidden]]" /><script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName("SCRIPT"),g=f[f.length-1].previousElementSibling,h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel="stylesheet" href="'+c[d]+'"/>')}("JavaScriptStringEncode[[visibility]]","JavaScriptStringEncode[[hidden]]",["JavaScriptStringEncode[[/styles/site.css?v=XY7YsMemPf8AGU4SIX9ED9eOjK1LOQWu2dmCNmh-pQc]]"]);</script>
<!-- Globbed link tag with existing file, static href and file version --> <!-- Globbed link tag with existing file, static href and file version -->
<link href="HtmlEncode[[/styles/site.css?v=XY7YsMemPf8AGU4SIX9ED9eOjK1LOQWu2dmCNmh-pQc]]" rel="stylesheet" /><link href="HtmlEncode[[/styles/sub/site2.css?v=30cxPex0tA9xEatW7f1Qhnn8tVLAHgE6xwIZhESq0y0]]" rel="stylesheet" /><link href="HtmlEncode[[/styles/sub/site3.css?v=fSxxOr1Q4Dq2uPuzlju5UYGuK0SKABI-ghvaIGEsZDc]]" rel="stylesheet" /><link href="HtmlEncode[[/styles/sub/site3.min.css?v=s8JMmAZxBn0dzuhRtQ0wgOvNBK4XRJRWEC2wfzsVF9M]]" rel="stylesheet" /> <link href="HtmlEncode[[/styles/site.css?v=XY7YsMemPf8AGU4SIX9ED9eOjK1LOQWu2dmCNmh-pQc]]" rel="stylesheet" /><link href="HtmlEncode[[/styles/sub/site2.css?v=30cxPex0tA9xEatW7f1Qhnn8tVLAHgE6xwIZhESq0y0]]" rel="stylesheet" /><link href="HtmlEncode[[/styles/sub/site3.css?v=fSxxOr1Q4Dq2uPuzlju5UYGuK0SKABI-ghvaIGEsZDc]]" rel="stylesheet" /><link href="HtmlEncode[[/styles/sub/site3.min.css?v=s8JMmAZxBn0dzuhRtQ0wgOvNBK4XRJRWEC2wfzsVF9M]]" rel="stylesheet" />

View File

@ -1,4 +1,4 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
@ -13,27 +13,27 @@
<script src="HtmlEncode[[/blank.js?a=b&c=d]]" data-foo="foo-data2" title="&lt;the title>"> <script src="HtmlEncode[[/blank.js?a=b&c=d]]" data-foo="foo-data2" title="&lt;the title>">
// TagHelper script with comment in body, and extra properties. // TagHelper script with comment in body, and extra properties.
</script> </script>
<script>(false||document.write("<script src=\"JavaScriptEncode[[/styles/site.js?a=b&c=d]]\" JavaScriptEncode[[data-foo]]=\"JavaScriptEncode[[foo-data2]]\" JavaScriptEncode[[title]]=\"JavaScriptEncode[[&lt;the title>]]\"><\/script>"));</script> <script>(false||document.write("<script src=\"JavaScriptStringEncode[[/styles/site.js?a=b&c=d]]\" JavaScriptStringEncode[[data-foo]]=\"JavaScriptStringEncode[[foo-data2]]\" JavaScriptStringEncode[[title]]=\"JavaScriptStringEncode[[&lt;the title>]]\"><\/script>"));</script>
<script src="HtmlEncode[[/blank.js]]" title="&quot;the&quot; title"> <script src="HtmlEncode[[/blank.js]]" title="&quot;the&quot; title">
// Fallback to globbed src // Fallback to globbed src
</script> </script>
<script>(false||document.write("<script src=\"JavaScriptEncode[[/styles/site.js]]\" JavaScriptEncode[[title]]=\"JavaScriptEncode[["the" title]]\"><\/script>"));</script> <script>(false||document.write("<script src=\"JavaScriptStringEncode[[/styles/site.js]]\" JavaScriptStringEncode[[title]]=\"JavaScriptStringEncode[["the" title]]\"><\/script>"));</script>
<script src="HtmlEncode[[/blank.js]]"> <script src="HtmlEncode[[/blank.js]]">
// Fallback to globbed src with exclude // Fallback to globbed src with exclude
</script> </script>
<script>(false||document.write("<script src=\"JavaScriptEncode[[/styles/site.js]]\"><\/script><script src=\"JavaScriptEncode[[/styles/sub/site2.js]]\"><\/script>"));</script> <script>(false||document.write("<script src=\"JavaScriptStringEncode[[/styles/site.js]]\"><\/script><script src=\"JavaScriptStringEncode[[/styles/sub/site2.js]]\"><\/script>"));</script>
<script src="HtmlEncode[[/blank.js]]"> <script src="HtmlEncode[[/blank.js]]">
// Fallback to globbed and static src // Fallback to globbed and static src
</script> </script>
<script>(false||document.write("<script src=\"JavaScriptEncode[[/styles/site.js]]\"><\/script><script src=\"JavaScriptEncode[[/styles/sub/site2.js]]\"><\/script>"));</script> <script>(false||document.write("<script src=\"JavaScriptStringEncode[[/styles/site.js]]\"><\/script><script src=\"JavaScriptStringEncode[[/styles/sub/site2.js]]\"><\/script>"));</script>
<script src="HtmlEncode[[/blank.js]]"> <script src="HtmlEncode[[/blank.js]]">
// Fallback to globbed and static src should de-dupe // Fallback to globbed and static src should de-dupe
</script> </script>
<script>(false||document.write("<script src=\"JavaScriptEncode[[/styles/site.js]]\"><\/script>"));</script> <script>(false||document.write("<script src=\"JavaScriptStringEncode[[/styles/site.js]]\"><\/script>"));</script>
<script src="HtmlEncode[[/blank.js]]"> <script src="HtmlEncode[[/blank.js]]">
// Fallback to globbed src with missing include // Fallback to globbed src with missing include
@ -42,7 +42,7 @@
<script src="HtmlEncode[[/blank.js]]"> <script src="HtmlEncode[[/blank.js]]">
// Fallback to static and globbed src with missing include // Fallback to static and globbed src with missing include
</script> </script>
<script>(false||document.write("<script src=\"JavaScriptEncode[[/styles/site.js]]\"><\/script>"));</script> <script>(false||document.write("<script src=\"JavaScriptStringEncode[[/styles/site.js]]\"><\/script>"));</script>
<script src="HtmlEncode[[/blank.js]]"> <script src="HtmlEncode[[/blank.js]]">
// Fallback to globbed src outside of webroot // Fallback to globbed src outside of webroot
@ -55,7 +55,7 @@
<script data-foo="foo-data3"> <script data-foo="foo-data3">
// Valid TagHelper (although no src is provided) script with comment in body, and extra properties. // Valid TagHelper (although no src is provided) script with comment in body, and extra properties.
</script> </script>
<script>(false||document.write("<script JavaScriptEncode[[data-foo]]=\"JavaScriptEncode[[foo-data3]]\" src=\"JavaScriptEncode[[/styles/site.js]]\"><\/script>"));</script> <script>(false||document.write("<script JavaScriptStringEncode[[data-foo]]=\"JavaScriptStringEncode[[foo-data3]]\" src=\"JavaScriptStringEncode[[/styles/site.js]]\"><\/script>"));</script>
<script src="HtmlEncode[[/blank.js]]"> <script src="HtmlEncode[[/blank.js]]">
// Invalid TagHelper script with comment in body. // Invalid TagHelper script with comment in body.
@ -98,12 +98,12 @@
<script src="HtmlEncode[[/blank.js]]"> <script src="HtmlEncode[[/blank.js]]">
// TagHelper script with comment in body, and file version. // TagHelper script with comment in body, and file version.
</script> </script>
<script>(false||document.write("<script src=\"JavaScriptEncode[[/styles/site.js?v=jx1PJjLX32-xgQQx2BxnckU9QH9DVKkm4-M5bSK869I]]\"><\/script>"));</script> <script>(false||document.write("<script src=\"JavaScriptStringEncode[[/styles/site.js?v=jx1PJjLX32-xgQQx2BxnckU9QH9DVKkm4-M5bSK869I]]\"><\/script>"));</script>
<script src="HtmlEncode[[/blank.js]]"> <script src="HtmlEncode[[/blank.js]]">
// Fallback to globbed src with file version. // Fallback to globbed src with file version.
</script> </script>
<script>(false||document.write("<script src=\"JavaScriptEncode[[/styles/site.js?v=jx1PJjLX32-xgQQx2BxnckU9QH9DVKkm4-M5bSK869I]]\"><\/script>"));</script> <script>(false||document.write("<script src=\"JavaScriptStringEncode[[/styles/site.js?v=jx1PJjLX32-xgQQx2BxnckU9QH9DVKkm4-M5bSK869I]]\"><\/script>"));</script>
<script src="HtmlEncode[[/styles/site.js?v=jx1PJjLX32-xgQQx2BxnckU9QH9DVKkm4-M5bSK869I]]"> <script src="HtmlEncode[[/styles/site.js?v=jx1PJjLX32-xgQQx2BxnckU9QH9DVKkm4-M5bSK869I]]">
// Regular script with comment in body, and file version. // Regular script with comment in body, and file version.

View File

@ -36,15 +36,16 @@
"LoggingWebSite": "1.0.0", "LoggingWebSite": "1.0.0",
"LowercaseUrlsWebSite": "1.0.0-*", "LowercaseUrlsWebSite": "1.0.0-*",
"Microsoft.AspNet.Mvc": "6.0.0-*", "Microsoft.AspNet.Mvc": "6.0.0-*",
"Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-*",
"Microsoft.AspNet.Mvc.TestCommon": { "Microsoft.AspNet.Mvc.TestCommon": {
"version": "6.0.0-*", "version": "6.0.0-*",
"type": "build" "type": "build"
}, },
"Microsoft.AspNet.Mvc.TestConfiguration": "1.0.0", "Microsoft.AspNet.Mvc.TestConfiguration": "1.0.0",
"Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-*",
"Microsoft.AspNet.TestHost": "1.0.0-*", "Microsoft.AspNet.TestHost": "1.0.0-*",
"Microsoft.AspNet.WebUtilities": "1.0.0-*", "Microsoft.AspNet.WebUtilities": "1.0.0-*",
"Microsoft.Framework.Configuration.Json": "1.0.0-*", "Microsoft.Framework.Configuration.Json": "1.0.0-*",
"Microsoft.Framework.Logging.Testing": "1.0.0-*",
"Microsoft.Framework.WebEncoders.Testing": "1.0.0-*", "Microsoft.Framework.WebEncoders.Testing": "1.0.0-*",
"ModelBindingWebSite": "1.0.0", "ModelBindingWebSite": "1.0.0",
"MvcSample.Web": "1.0.0", "MvcSample.Web": "1.0.0",
@ -72,8 +73,7 @@
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "dnx451": { },
"dnxcore50": { "dnxcore50": { }
}
}, },
"exclude": [ "exclude": [
"wwwroot", "wwwroot",