Added more tests and error handling for construction of middleware classes #236

This commit is contained in:
Mikael Mengistu 2015-06-19 12:32:53 -07:00
parent c83ff60275
commit 12b78a31bf
5 changed files with 388 additions and 7 deletions

View File

@ -6,12 +6,14 @@ using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Abstractions;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Builder
{
public static class UseMiddlewareExtensions
{
const string InvokeMethodName = "Invoke";
public static IApplicationBuilder UseMiddleware<T>(this IApplicationBuilder builder, params object[] args)
{
return builder.UseMiddleware(typeof(T), args);
@ -22,24 +24,44 @@ namespace Microsoft.AspNet.Builder
var applicationServices = builder.ApplicationServices;
return builder.Use(next =>
{
var instance = ActivatorUtilities.CreateInstance(builder.ApplicationServices, middleware, new[] { next }.Concat(args).ToArray());
var methodinfo = middleware.GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public);
var parameters = methodinfo.GetParameters();
if (parameters[0].ParameterType != typeof(HttpContext))
var methods = middleware.GetMethods(BindingFlags.Instance | BindingFlags.Public);
var invokeMethods = methods.Where(m => string.Equals(m.Name, InvokeMethodName, StringComparison.Ordinal)).ToArray();
if (invokeMethods.Length > 1)
{
throw new Exception("Middleware Invoke method must take first argument of HttpContext");
throw new InvalidOperationException(Resources.FormatException_UseMiddleMutlipleInvokes(InvokeMethodName));
}
if (invokeMethods.Length == 0)
{
throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoInvokeMethod(InvokeMethodName));
}
var methodinfo = invokeMethods[0];
if (!typeof(Task).IsAssignableFrom(methodinfo.ReturnType))
{
throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNonTaskReturnType(InvokeMethodName, nameof(Task)));
}
var parameters = methodinfo.GetParameters();
if (parameters.Length == 0 || parameters[0].ParameterType != typeof(HttpContext))
{
throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoParameters(InvokeMethodName,nameof(HttpContext)));
}
var instance = ActivatorUtilities.CreateInstance(builder.ApplicationServices, middleware, new[] { next }.Concat(args).ToArray());
if (parameters.Length == 1)
{
return (RequestDelegate)methodinfo.CreateDelegate(typeof(RequestDelegate), instance);
}
return context =>
{
var serviceProvider = context.RequestServices ?? context.ApplicationServices ?? applicationServices;
if (serviceProvider == null)
{
throw new Exception("IServiceProvider is not available");
throw new InvalidOperationException(Resources.FormatException_UseMiddlewareIServiceProviderNotAvailable(nameof(IServiceProvider)));
}
var arguments = new object[parameters.Length];
arguments[0] = context;
for(var index = 1; index != parameters.Length; ++index)

View File

@ -2,5 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: InternalsVisibleTo("Microsoft.AspNet.Http.Abstractions.Tests")]

View File

@ -0,0 +1,110 @@
// <auto-generated />
namespace Microsoft.AspNet.Http.Abstractions
{
using System.Globalization;
using System.Reflection;
using System.Resources;
internal static class Resources
{
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.AspNet.Http.Abstractions.Resources", typeof(Resources).GetTypeInfo().Assembly);
/// <summary>
/// '{0}' is not available.
/// </summary>
internal static string Exception_UseMiddlewareIServiceProviderNotAvailable
{
get { return GetString("Exception_UseMiddlewareIServiceProviderNotAvailable"); }
}
/// <summary>
/// '{0}' is not available.
/// </summary>
internal static string FormatException_UseMiddlewareIServiceProviderNotAvailable(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("Exception_UseMiddlewareIServiceProviderNotAvailable"), p0);
}
/// <summary>
/// No public '{0}' method found.
/// </summary>
internal static string Exception_UseMiddlewareNoInvokeMethod
{
get { return GetString("Exception_UseMiddlewareNoInvokeMethod"); }
}
/// <summary>
/// No public '{0}' method found.
/// </summary>
internal static string FormatException_UseMiddlewareNoInvokeMethod(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("Exception_UseMiddlewareNoInvokeMethod"), p0);
}
/// <summary>
/// '{0}' does not return an object of type '{1}'.
/// </summary>
internal static string Exception_UseMiddlewareNonTaskReturnType
{
get { return GetString("Exception_UseMiddlewareNonTaskReturnType"); }
}
/// <summary>
/// '{0}' does not return an object of type '{1}'.
/// </summary>
internal static string FormatException_UseMiddlewareNonTaskReturnType(object p0, object p1)
{
return string.Format(CultureInfo.CurrentCulture, GetString("Exception_UseMiddlewareNonTaskReturnType"), p0, p1);
}
/// <summary>
/// The '{0}' method's first argument must be of type '{1}'.
/// </summary>
internal static string Exception_UseMiddlewareNoParameters
{
get { return GetString("Exception_UseMiddlewareNoParameters"); }
}
/// <summary>
/// The '{0}' method's first argument must be of type '{1}'.
/// </summary>
internal static string FormatException_UseMiddlewareNoParameters(object p0, object p1)
{
return string.Format(CultureInfo.CurrentCulture, GetString("Exception_UseMiddlewareNoParameters"), p0, p1);
}
/// <summary>
/// Multiple public '{0}' methods are available.
/// </summary>
internal static string Exception_UseMiddleMutlipleInvokes
{
get { return GetString("Exception_UseMiddleMutlipleInvokes"); }
}
/// <summary>
/// Multiple public '{0}' methods are available.
/// </summary>
internal static string FormatException_UseMiddleMutlipleInvokes(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("Exception_UseMiddleMutlipleInvokes"), p0);
}
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);
System.Diagnostics.Debug.Assert(value != null);
if (formatterNames != null)
{
for (var i = 0; i < formatterNames.Length; i++)
{
value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}");
}
}
return value;
}
}
}

View File

@ -0,0 +1,135 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Exception_UseMiddlewareIServiceProviderNotAvailable" xml:space="preserve">
<value>'{0}' is not available.</value>
</data>
<data name="Exception_UseMiddlewareNoInvokeMethod" xml:space="preserve">
<value>No public '{0}' method found.</value>
</data>
<data name="Exception_UseMiddlewareNonTaskReturnType" xml:space="preserve">
<value>'{0}' does not return an object of type '{1}'.</value>
</data>
<data name="Exception_UseMiddlewareNoParameters" xml:space="preserve">
<value>The '{0}' method's first argument must be of type '{1}'.</value>
</data>
<data name="Exception_UseMiddleMutlipleInvokes" xml:space="preserve">
<value>Multiple public '{0}' methods are available.</value>
</data>
</root>

View File

@ -0,0 +1,112 @@
// 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.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Builder.Internal;
using Microsoft.AspNet.Http.Abstractions;
using Xunit;
namespace Microsoft.AspNet.Http
{
public class UseMiddlewareTest
{
[Fact]
public void UseMiddleware_WithNoParameters_ThrowsException()
{
var mockServiceProvider = new DummyServiceProvider();
var builder = new ApplicationBuilder(mockServiceProvider);
builder.UseMiddleware(typeof(MiddlewareNoParametersStub));
var exception = Assert.Throws<InvalidOperationException>(() => builder.Build());
Assert.Equal(Resources.FormatException_UseMiddlewareNoParameters("Invoke",nameof(HttpContext)), exception.Message);
}
[Fact]
public void UseMiddleware_NonTaskReturnType_ThrowsException()
{
var mockServiceProvider = new DummyServiceProvider();
var builder = new ApplicationBuilder(mockServiceProvider);
builder.UseMiddleware(typeof(MiddlewareNonTaskReturnStub));
var exception = Assert.Throws<InvalidOperationException>(() => builder.Build());
Assert.Equal(Resources.FormatException_UseMiddlewareNonTaskReturnType("Invoke", nameof(Task)), exception.Message);
}
[Fact]
public void UseMiddleware_NoInvokeMethod_ThrowsException()
{
var mockServiceProvider = new DummyServiceProvider();
var builder = new ApplicationBuilder(mockServiceProvider);
builder.UseMiddleware(typeof(MiddlewareNoInvokeStub));
var exception = Assert.Throws<InvalidOperationException>(() => builder.Build());
Assert.Equal(Resources.FormatException_UseMiddlewareNoInvokeMethod("Invoke"), exception.Message);
}
[Fact]
public void UseMiddleware_MutlipleInvokeMethods_ThrowsException()
{
var mockServiceProvider = new DummyServiceProvider();
var builder = new ApplicationBuilder(mockServiceProvider);
builder.UseMiddleware(typeof(MiddlewareMultipleInvokesStub));
var exception = Assert.Throws<InvalidOperationException>(() => builder.Build());
Assert.Equal(Resources.FormatException_UseMiddleMutlipleInvokes("Invoke"), exception.Message);
}
private class DummyServiceProvider : IServiceProvider
{
public object GetService(Type serviceType)
{
return null;
}
}
private class MiddlewareNoParametersStub
{
public MiddlewareNoParametersStub(RequestDelegate next)
{
}
public Task Invoke()
{
return Task.FromResult(0);
}
}
private class MiddlewareNonTaskReturnStub
{
public MiddlewareNonTaskReturnStub(RequestDelegate next)
{
}
public int Invoke()
{
return 0;
}
}
private class MiddlewareNoInvokeStub
{
public MiddlewareNoInvokeStub(RequestDelegate next)
{
}
}
private class MiddlewareMultipleInvokesStub
{
public MiddlewareMultipleInvokesStub(RequestDelegate next)
{
}
public Task Invoke(HttpContext context)
{
return Task.FromResult(0);
}
public Task Invoke(HttpContext context, int i)
{
return Task.FromResult(0);
}
}
}
}