Using test setup pattern from aspnet/Stress.

This commit is contained in:
Pranav K 2015-09-09 00:38:18 -07:00
parent 87c15bb6dc
commit d25d9704f7
6 changed files with 230 additions and 217 deletions

View File

@ -8,35 +8,33 @@ using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using ActionResultsWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests
{
public class ActionResultTests
public class ActionResultTests : IClassFixture<MvcFixture<ActionResultsWebSite.Startup>>
{
private const string SiteName = nameof(ActionResultsWebSite);
private readonly Action<IApplicationBuilder> _app = new Startup().Configure;
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices;
public ActionResultTests(MvcFixture<ActionResultsWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact]
public async Task BadRequestResult_CanBeReturned()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "{\"SampleInt\":10}";
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ActionResultsVerification/GetBadResult");
"ActionResultsVerification/GetBadResult");
request.Content = new StringContent(input, Encoding.UTF8, "application/json");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
@ -47,15 +45,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CreatedResult_SetsRelativePathInLocationHeader()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ActionResultsVerification/GetCreatedRelative");
"ActionResultsVerification/GetCreatedRelative");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
@ -67,15 +62,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CreatedResult_SetsAbsolutePathInLocationHeader()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ActionResultsVerification/GetCreatedAbsolute");
"ActionResultsVerification/GetCreatedAbsolute");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
@ -87,15 +79,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CreatedResult_SetsQualifiedPathInLocationHeader()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ActionResultsVerification/GetCreatedQualified");
"ActionResultsVerification/GetCreatedQualified");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
@ -109,15 +98,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CreatedResult_SetsUriInLocationHeader()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ActionResultsVerification/GetCreatedUri");
"ActionResultsVerification/GetCreatedUri");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
@ -129,15 +115,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CreatedAtActionResult_GeneratesUri_WithActionAndController()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ActionResultsVerification/GetCreatedAtAction");
"ActionResultsVerification/GetCreatedAtAction");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
@ -149,15 +132,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CreatedAtRouteResult_GeneratesUri_WithRouteValues()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ActionResultsVerification/GetCreatedAtRoute");
"ActionResultsVerification/GetCreatedAtRoute");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
@ -169,15 +149,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CreatedAtRouteResult_GeneratesUri_WithRouteName()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ActionResultsVerification/GetCreatedAtRouteWithRouteName");
"ActionResultsVerification/GetCreatedAtRouteWithRouteName");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
@ -189,18 +166,15 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task SerializableError_CanSerializeNormalObjects()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<DummyClass xmlns=\"http://schemas.datacontract.org/2004/07/ActionResultsWebSite\">" +
"<SampleInt>2</SampleInt><SampleString>foo</SampleString></DummyClass>";
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Home/GetCustomErrorObject");
var request = new HttpRequestMessage(HttpMethod.Post, "Home/GetCustomErrorObject");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;charset=utf-8"));
request.Content = new StringContent(input, Encoding.UTF8, "application/xml");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
@ -212,14 +186,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ContentResult_WritesContent_SetsDefaultContentTypeAndEncoding()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ActionResultsVerification/GetContentResult");
HttpMethod.Post,
"ActionResultsVerification/GetContentResult");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -232,14 +204,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ContentResult_WritesContent_SetsContentTypeWithDefaultEncoding()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ActionResultsVerification/GetContentResultWithContentType");
HttpMethod.Post,
"ActionResultsVerification/GetContentResultWithContentType");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -252,14 +222,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ContentResult_WritesContent_SetsContentTypeAndEncoding()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ActionResultsVerification/GetContentResultWithContentTypeAndEncoding");
HttpMethod.Post,
"ActionResultsVerification/GetContentResultWithContentTypeAndEncoding");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -272,14 +240,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ObjectResult_WithStatusCodeAndNoContent_SetsSameStatusCode()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Get,
"http://localhost/ActionResultsVerification/GetObjectResultWithNoContent");
HttpMethod.Get,
"ActionResultsVerification/GetObjectResultWithNoContent");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
@ -289,15 +255,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task HttpNotFoundObjectResult_NoResponseContent()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Get,
"http://localhost/ActionResultsVerification/GetNotFoundObjectResult");
"ActionResultsVerification/GetNotFoundObjectResult");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -308,15 +271,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task HttpNotFoundObjectResult_WithResponseContent()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ActionResultsVerification/GetNotFoundObjectResultWithContent");
"ActionResultsVerification/GetNotFoundObjectResultWithContent");
// Act
var response = await client.SendAsync(request);
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -327,23 +287,21 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task HttpNotFoundObjectResult_WithDisposableObject()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var nameValueCollection = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("guid", Guid.NewGuid().ToString()),
};
// Act
var response1 = await client.PostAsync(
var response1 = await Client.PostAsync(
"/ActionResultsVerification/GetDisposeCalled",
new FormUrlEncodedContent(nameValueCollection));
await client.PostAsync(
await Client.PostAsync(
"/ActionResultsVerification/GetNotFoundObjectResultWithDisposableObject",
new FormUrlEncodedContent(nameValueCollection));
var response2 = await client.PostAsync(
var response2 = await Client.PostAsync(
"/ActionResultsVerification/GetDisposeCalled",
new FormUrlEncodedContent(nameValueCollection));

View File

@ -2,33 +2,31 @@
// 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 ActivatorWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests
{
public class ActivatorTests
public class ActivatorTests : IClassFixture<MvcFixture<ActivatorWebSite.Startup>>
{
private const string SiteName = nameof(ActivatorWebSite);
private readonly Action<IApplicationBuilder> _app = new Startup().Configure;
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices;
public ActivatorTests(MvcFixture<ActivatorWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[Fact]
public async Task ControllerThatCannotBeActivated_ThrowsWhenAttemptedToBeInvoked()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedMessage =
"Unable to resolve service for type 'ActivatorWebSite.CannotBeActivatedController+FakeType' while " +
"attempting to activate 'ActivatorWebSite.CannotBeActivatedController'.";
// Act & Assert
var response = await client.GetAsync("http://localhost/CannotBeActivated/Index");
var response = await Client.GetAsync("CannotBeActivated/Index");
var exception = response.GetServerException();
Assert.Equal(typeof(InvalidOperationException).FullName, exception.ExceptionType);
@ -39,12 +37,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task PropertiesForPocoControllersAreInitialized()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = "4|some-text";
// Act
var response = await client.GetAsync("http://localhost/Plain?foo=some-text");
var response = await Client.GetAsync("Plain?foo=some-text");
// Assert
var headerValue = Assert.Single(response.Headers.GetValues("X-Fake-Header"));
@ -57,12 +53,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task PropertiesForTypesDerivingFromControllerAreInitialized()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = "Hello world";
// Act
var body = await client.GetStringAsync("http://localhost/Regular");
var body = await Client.GetStringAsync("Regular");
// Assert
Assert.Equal(expected, body);
@ -72,12 +66,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ViewActivator_ActivatesDefaultInjectedProperties()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = @"<label for=""Hello"">Hello</label> world! /View/ConsumeServicesFromBaseType";
// Act
var body = await client.GetStringAsync("http://localhost/View/ConsumeDefaultProperties");
var body = await Client.GetStringAsync("View/ConsumeDefaultProperties");
// Assert
Assert.Equal(expected, body.Trim());
@ -87,12 +79,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ViewActivator_ActivatesAndContextualizesInjectedServices()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = "4 test-value";
// Act
var body = await client.GetStringAsync("http://localhost/View/ConsumeInjectedService?test=test-value");
var body = await Client.GetStringAsync("View/ConsumeInjectedService?test=test-value");
// Assert
Assert.Equal(expected, body.Trim());
@ -102,12 +92,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ViewActivator_ActivatesServicesFromBaseType()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = @"/content/scripts/test.js";
// Act
var body = await client.GetStringAsync("http://localhost/View/ConsumeServicesFromBaseType");
var body = await Client.GetStringAsync("View/ConsumeServicesFromBaseType");
// Assert
Assert.Equal(expected, body.Trim());
@ -117,12 +105,10 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ViewComponentActivator_Activates()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = @"Random Number:4";
// Act
var body = await client.GetStringAsync("http://localhost/View/ConsumeViewComponent");
var body = await Client.GetStringAsync("View/ConsumeViewComponent");
// Assert
Assert.Equal(expected, body.Trim());
@ -133,14 +119,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ViewComponentThatCannotBeActivated_ThrowsWhenAttemptedToBeInvoked()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedMessage =
"Unable to resolve service for type 'ActivatorWebSite.CannotBeActivatedComponent+FakeType' " +
"while attempting to activate 'ActivatorWebSite.CannotBeActivatedComponent'.";
// Act & Assert
var response = await client.GetAsync("http://localhost/View/ConsumeCannotBeActivatedComponent");
var response = await Client.GetAsync("View/ConsumeCannotBeActivatedComponent");
var exception = response.GetServerException();
Assert.Equal(typeof(InvalidOperationException).FullName, exception.ExceptionType);
@ -151,8 +135,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task TagHelperActivation_ConstructorInjection_RendersProperly()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expected = "<body><h2>Activation Test</h2>" +
Environment.NewLine +
"<div>FakeFakeFake</div>" +
@ -165,7 +147,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
"</body>";
// Act
var body = await client.GetStringAsync("http://localhost/View/UseTagHelper");
var body = await Client.GetStringAsync("View/UseTagHelper");
// Assert
Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);

View File

@ -8,37 +8,34 @@ using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
using BasicWebSite;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests
{
public class BasicTests
public class BasicTests : IClassFixture<MvcFixture<BasicWebSite.Startup>>
{
private const string SiteName = nameof(BasicWebSite);
// Some tests require comparing the actual response body against an expected response baseline
// so they require a reference to the assembly on which the resources are located, in order to
// make the tests less verbose, we get a reference to the assembly with the resources and we
// use it on all the rest of the tests.
private static readonly Assembly _resourcesAssembly = typeof(BasicTests).GetTypeInfo().Assembly;
private readonly Action<IApplicationBuilder> _app = new Startup().Configure;
private readonly Action<IServiceCollection> _configureServices = new Startup().ConfigureServices;
public BasicTests(MvcFixture<BasicWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory]
[InlineData("http://localhost/")]
[InlineData("http://localhost/Home")]
[InlineData("http://localhost/Home/Index")]
[InlineData("")]
[InlineData("Home")]
[InlineData("Home/Index")]
public async Task CanRender_ViewsWithLayout(string url)
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
var outputFile = "compiler/resources/BasicWebSite.Home.Index.html";
var expectedContent =
@ -46,7 +43,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act
// The host is not important as everything runs in memory and tests are isolated from each other.
var response = await client.GetAsync(url);
var response = await Client.GetAsync(url);
var responseContent = await response.Content.ReadAsStringAsync();
// Assert
@ -64,15 +61,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task CanRender_SimpleViews()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
var outputFile = "compiler/resources/BasicWebSite.Home.PlainView.html";
var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
// Act
var response = await client.GetAsync("http://localhost/Home/PlainView");
var response = await Client.GetAsync("http://localhost/Home/PlainView");
var responseContent = await response.Content.ReadAsStringAsync();
// Assert
@ -90,14 +85,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ViewWithAttributePrefix_RendersWithoutIgnoringPrefix()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var outputFile = "compiler/resources/BasicWebSite.Home.ViewWithPrefixedAttributeValue.html";
var expectedContent =
await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false);
// Act
var response = await client.GetAsync("http://localhost/Home/ViewWithPrefixedAttributeValue");
var response = await Client.GetAsync("Home/ViewWithPrefixedAttributeValue");
var responseContent = await response.Content.ReadAsStringAsync();
// Assert
@ -113,12 +106,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact]
public async Task CanReturn_ResultsWithoutContent()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/NoContentResult");
var response = await Client.GetAsync("Home/NoContentResult");
var responseContent = await response.Content.ReadAsStringAsync();
// Assert
@ -131,12 +120,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact]
public async Task ReturningTaskFromAction_ProducesEmptyResult()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/ActionReturningTask");
var response = await Client.GetAsync("Home/ActionReturningTask");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -148,15 +133,12 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task ActionDescriptors_CreatedOncePerRequest()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedContent = "1";
// Act and Assert
for (var i = 0; i < 3; i++)
{
var result = await client.GetAsync("http://localhost/Monitor/CountActionDescriptorInvocations");
var result = await Client.GetAsync("Monitor/CountActionDescriptorInvocations");
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
var responseContent = await result.Content.ReadAsStringAsync();
@ -167,12 +149,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact]
public async Task ActionWithRequireHttps_RedirectsToSecureUrl_ForNonHttpsGetRequests()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act
var response = await client.GetAsync("http://localhost/Home/HttpsOnlyAction");
var response = await Client.GetAsync("Home/HttpsOnlyAction");
// Assert
Assert.Equal(HttpStatusCode.MovedPermanently, response.StatusCode);
@ -187,12 +165,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact]
public async Task ActionWithRequireHttps_ReturnsBadRequestResponse_ForNonHttpsNonGetRequests()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act
var response = await client.SendAsync(new HttpRequestMessage(
var response = await Client.SendAsync(new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/Home/HttpsOnlyAction"));
@ -209,12 +183,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[InlineData("POST")]
public async Task ActionWithRequireHttps_AllowsHttpsRequests(string method)
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = new HttpClient(server.CreateHandler(), false);
// Act
var response = await client.SendAsync(new HttpRequestMessage(
var response = await Client.SendAsync(new HttpRequestMessage(
new HttpMethod(method),
"https://localhost/Home/HttpsOnlyAction"));
@ -226,8 +196,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonViewComponent_RendersJson()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = new HttpClient(server.CreateHandler(), false);
var expectedBody = JsonConvert.SerializeObject(new BasicWebSite.Models.Person()
{
Id = 10,
@ -235,7 +203,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
});
// Act
var response = await client.GetAsync("https://localhost/Home/JsonTextInView");
var response = await Client.GetAsync("Home/JsonTextInView");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -249,9 +217,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonHelper_RendersJson()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = new HttpClient(server.CreateHandler(), false);
var json = JsonConvert.SerializeObject(new BasicWebSite.Models.Person()
{
Id = 9000,
@ -265,7 +230,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
json);
// Act
var response = await client.GetAsync("https://localhost/Home/JsonHelperInView");
var response = await Client.GetAsync("Home/JsonHelperInView");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -279,9 +244,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task JsonHelperWithSettings_RendersJson()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = new HttpClient(server.CreateHandler(), false);
var json = JsonConvert.SerializeObject(new BasicWebSite.Models.Person()
{
Id = 9000,
@ -295,7 +257,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
json);
// Act
var response = await client.GetAsync("https://localhost/Home/JsonHelperWithSettingsInView");
var response = await Client.GetAsync("Home/JsonHelperWithSettingsInView");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -344,12 +306,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[MemberData(nameof(HtmlHelperLinkGenerationData))]
public async Task HtmlHelperLinkGeneration(string viewName, string expectedLink)
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = new HttpClient(server.CreateHandler(), false);
// Act
var response = await client.GetAsync("http://localhost/Links/Index?view=" + viewName);
var response = await Client.GetAsync("Links/Index?view=" + viewName);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -360,12 +318,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact]
public async Task ConfigureMvc_AddsOptionsProperly()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = new HttpClient(server.CreateHandler(), false);
// Act
var response = await client.GetAsync("http://localhost/Home/GetApplicationDescription");
var response = await Client.GetAsync("Home/GetApplicationDescription");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -376,12 +330,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact]
public async Task TypesWithoutControllerSuffix_DerivingFromTypesWithControllerSuffix_CanBeAccessed()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = new HttpClient(server.CreateHandler(), false);
// Act
var response = await client.GetStringAsync("http://localhost/appointments");
var response = await Client.GetStringAsync("appointments");
// Assert
Assert.Equal("2 appointments available.", response);
@ -390,12 +340,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
[Fact]
public async Task TypesMarkedAsNonAction_AreInaccessible()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = new HttpClient(server.CreateHandler(), false);
// Act
var response = await client.GetAsync("http://localhost/SqlData/TruncateAllDbRecords");
var response = await Client.GetAsync("SqlData/TruncateAllDbRecords");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

View File

@ -3,28 +3,29 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Testing;
using Microsoft.Framework.DependencyInjection;
using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests
{
public class LinkGenerationTests
public class LinkGenerationTests : IClassFixture<MvcFixture<BasicWebSite.Startup>>
{
private const string SiteName = nameof(BasicWebSite);
// Some tests require comparing the actual response body against an expected response baseline
// so they require a reference to the assembly on which the resources are located, in order to
// make the tests less verbose, we get a reference to the assembly with the resources and we
// use it on all the rest of the tests.
private static readonly Assembly _resourcesAssembly = typeof(LinkGenerationTests).GetTypeInfo().Assembly;
private readonly Action<IApplicationBuilder> _app = new BasicWebSite.Startup().Configure;
private readonly Action<IServiceCollection> _configureServices = new BasicWebSite.Startup().ConfigureServices;
public LinkGenerationTests(MvcFixture<BasicWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory]
[InlineData("http://pingüino/Home/RedirectToActionReturningTaskAction", "/Home/ActionReturningTask")]
@ -34,14 +35,9 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
string url,
string expected)
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
// Act
// The host is not important as everything runs in memory and tests are isolated from each other.
var response = await client.GetAsync(url);
var response = await Client.GetAsync(url);
var responseContent = await response.Content.ReadAsStringAsync();
// Assert
@ -56,8 +52,6 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
public async Task GeneratedLinks_AreNotPunyEncoded_WhenGeneratedOnViews()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
var outputFile = "compiler/resources/BasicWebSite.Home.ActionLinkView.html";
var expectedContent =
@ -65,7 +59,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
// Act
// The host is not important as everything runs in memory and tests are isolated from each other.
var response = await client.GetAsync("http://localhost/Home/ActionLinkView");
var response = await Client.GetAsync("http://localhost/Home/ActionLinkView");
var responseContent = await response.Content.ReadAsStringAsync();
// Assert

View File

@ -0,0 +1,119 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.Versioning;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Mvc.Actions;
using Microsoft.AspNet.TestHost;
using Microsoft.Dnx.Runtime;
using Microsoft.Dnx.Runtime.Infrastructure;
using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.Mvc.FunctionalTests
{
public class MvcFixture : IDisposable
{
public MvcFixture(object startupInstance)
{
var startupTypeInfo = startupInstance.GetType().GetTypeInfo();
var configureMethod = (Action<IApplicationBuilder>)startupTypeInfo
.DeclaredMethods
.First(m => m.Name == "Configure")
.CreateDelegate(typeof(Action<IApplicationBuilder>), startupInstance);
var configureServices = (Action<IServiceCollection>)startupTypeInfo
.DeclaredMethods
.First(m => m.Name == "ConfigureServices")
.CreateDelegate(typeof(Action<IServiceCollection>), startupInstance);
Server = TestServer.Create(
CallContextServiceLocator.Locator.ServiceProvider,
configureMethod,
configureServices: InitializeServices(startupTypeInfo.Assembly, configureServices));
Client = Server.CreateClient();
Client.BaseAddress = new Uri("http://localhost");
}
public TestServer Server { get; }
public HttpClient Client { get; }
public void Dispose()
{
Client.Dispose();
Server.Dispose();
}
public static Func<IServiceCollection, IServiceProvider> InitializeServices(
Assembly startupAssembly,
Action<IServiceCollection> configureServices)
{
var applicationServices = CallContextServiceLocator.Locator.ServiceProvider;
var libraryManager = applicationServices.GetRequiredService<ILibraryManager>();
var applicationName = startupAssembly.GetName().Name;
var library = libraryManager.GetLibrary(applicationName);
var applicationRoot = Path.GetDirectoryName(library.Path);
var applicationEnvironment = applicationServices.GetRequiredService<IApplicationEnvironment>();
return (services) =>
{
services.AddInstance<IApplicationEnvironment>(
new TestApplicationEnvironment(applicationEnvironment, applicationName, applicationRoot));
var hostingEnvironment = new HostingEnvironment();
hostingEnvironment.Initialize(applicationRoot, "Production");
services.AddInstance<IHostingEnvironment>(hostingEnvironment);
var assemblyProvider = new StaticAssemblyProvider();
assemblyProvider.CandidateAssemblies.Add(startupAssembly);
services.AddInstance<IAssemblyProvider>(assemblyProvider);
configureServices(services);
return services.BuildServiceProvider();
};
}
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

@ -0,0 +1,14 @@
// 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.
namespace Microsoft.AspNet.Mvc.FunctionalTests
{
public class MvcFixture<TStartup> : MvcFixture
where TStartup : new()
{
public MvcFixture()
: base(new TStartup())
{
}
}
}