Files
acceptance-tests
data
debian
docs
external
Newtonsoft.Json
api-doc-tools
api-snapshot
aspnetwebstack
packages
src
test
Microsoft.TestCommon
Microsoft.Web.Helpers.Test
Microsoft.Web.Http.Data.Test
Microsoft.Web.Mvc.Test
Microsoft.Web.WebPages.OAuth.Test
SPA.Test
System.Json.Test.Integration
System.Json.Test.Unit
System.Net.Http.Formatting.Test.Integration
System.Net.Http.Formatting.Test.Unit
System.Web.Helpers.Test
System.Web.Http.Integration.Test
System.Web.Http.SelfHost.Test
System.Web.Http.Test
System.Web.Http.WebHost.Test
System.Web.Mvc.Test
Ajax
Async
ExpressionUtil
Html
Properties
Razor
Test
AcceptVerbsAttributeTest.cs
ActionDescriptorTest.cs
ActionExecutedContextTest.cs
ActionExecutingContextTest.cs
ActionFilterAttributeTest.cs
ActionMethodDispatcherCacheTest.cs
ActionMethodDispatcherTest.cs
ActionMethodSelectorTest.cs
ActionNameAttributeTest.cs
AdditionalMetadataAttributeTest.cs
AjaxHelperTest.cs
AjaxHelper`1Test.cs
AjaxRequestExtensionsTest.cs
AllowHtmlAttributeTest.cs
AreaHelpersTest.cs
AreaRegistrationContextTest.cs
AreaRegistrationTest.cs
AssociatedMetadataProviderTest.cs
AssociatedValidatorProviderTest.cs
AsyncControllerTest.cs
AsyncTimeoutAttributeTest.cs
AuthorizationContextTest.cs
AuthorizeAttributeTest.cs
BindAttributeTest.cs
BuildManagerCompiledViewTest.cs
BuildManagerViewEngineTest.cs
ByteArrayModelBinderTest.cs
CachedAssociatedMetadataProviderTest.cs
CachedDataAnnotationsModelMetadataProviderTest.cs
CancellationTokenModelBinderTest.cs
ChildActionOnlyAttributeTest.cs
ChildActionValueProviderFactoryTest.cs
ClientDataTypeModelValidatorProviderTest.cs
CompareAttributeTest.cs
ContentResultTest.cs
ControllerActionInvokerTest.cs.REMOVED.git-id
ControllerBaseTest.cs
ControllerBuilderTest.cs
ControllerContextTest.cs
ControllerDescriptorCacheTest.cs
ControllerDescriptorTest.cs
ControllerInstanceFilterProviderTest.cs
ControllerTest.cs
DataAnnotationsModelMetadataProviderTest.cs
DataAnnotationsModelMetadataProviderTestBase.cs
DataAnnotationsModelValidatorProviderTest.cs
DataAnnotationsModelValidatorTest.cs
DataErrorInfoModelValidatorProviderTest.cs
DataTypeUtilTest.cs
DefaultControllerFactoryTest.cs
DefaultModelBinderTest.cs.REMOVED.git-id
DefaultViewLocationCacheTest.cs
DependencyResolverTest.cs
DescriptorUtilTest.cs
DictionaryHelpersTest.cs
DictionaryValueProviderTest.cs
DynamicViewDataDictionaryTest.cs
EmptyModelValidatorProviderTest.cs
ExceptionContextTest.cs
ExpressionHelperTest.cs
FieldValidationMetadataTest.cs
FileContentResultTest.cs
FilePathResultTest.cs
FileResultTest.cs
FileStreamResultTest.cs
FilterAttributeFilterProviderTest.cs
FilterInfoTest.cs
FilterProviderCollectionTest.cs
FilterProvidersTest.cs
FilterTest.cs
FormCollectionTest.cs
FormContextTest.cs
FormValueProviderFactoryTest.cs
GlobalFilterCollectionTest.cs
HandleErrorAttributeTest.cs
HandleErrorInfoTest.cs
HtmlHelperTest.cs
HtmlHelper`1Test.cs
HttpDeleteAttributeTest.cs
HttpFileCollectionValueProviderFactoryTest.cs
HttpFileCollectionValueProviderTest.cs
HttpGetAttributeTest.cs
HttpHandlerUtilTest.cs
HttpHeadAttributeTest.cs
HttpNotFoundResultTest.cs
HttpOptionsAttributeTest.cs
HttpPatchAttributeTest.cs
HttpPostAttributeTest.cs
HttpPostedFileBaseModelBinderTest.cs
HttpPutAttributeTest.cs
HttpRequestExtensionsTest.cs
HttpStatusCodeResultTest.cs
HttpUnauthorizedResultTest.cs
HttpVerbAttributeHelper.cs
JavaScriptResultTest.cs
JsonResultTest.cs
JsonValueProviderFactoryTest.cs
LinqBinaryModelBinderTest.cs
MockBuildManager.cs
MockHelpers.cs
MockableUnvalidatedRequestValues.cs
ModelBinderAttributeTest.cs
ModelBinderDictionaryTest.cs
ModelBinderProviderCollectionTest.cs
ModelBinderProvidersTest.cs
ModelBindersTest.cs
ModelBindingContextTest.cs
ModelClientValidationRuleTest.cs
ModelErrorCollectionTest.cs
ModelErrorTest.cs
ModelMetadataProvidersTest.cs
ModelMetadataTest.cs
ModelStateDictionaryTest.cs
ModelStateTest.cs
ModelValidationResultTest.cs
ModelValidatorProviderCollectionTest.cs
ModelValidatorProvidersTest.cs
ModelValidatorTest.cs
MultiSelectListTest.cs
MultiServiceResolverTest.cs
MvcHandlerTest.cs
MvcHtmlStringTest.cs
MvcHttpHandlerTest.cs
MvcRouteHandlerTest.cs
MvcTestHelper.cs
MvcWebRazorHostFactoryTest.cs
NameValueCollectionExtensionsTest.cs
NameValueCollectionValueProviderTest.cs
NoAsyncTimeoutAttributeTest.cs
NonActionAttributeTest.cs
OutputCacheAttributeTest.cs
ParameterBindingInfoTest.cs
ParameterDescriptorTest.cs
ParameterInfoUtilTest.cs
PartialViewResultTest.cs
PathHelpersTest.cs
PreApplicationStartCodeTest.cs
QueryStringValueProviderFactoryTest.cs
RangeAttributeAdapterTest.cs
RazorViewEngineTest.cs
RazorViewTest.cs
ReaderWriterCacheTest.cs
RedirectResultTest.cs
RedirectToRouteResultTest.cs
ReflectedActionDescriptorTest.cs
ReflectedControllerDescriptorTest.cs
ReflectedParameterBindingInfoTest.cs
ReflectedParameterDescriptorTest.cs
RegularExpressionAttributeAdapterTest.cs
RemoteAttributeTest.cs
RequireHttpsAttributeTest.cs
RequiredAttributeAdapterTest.cs
ResultExecutedContextTest.cs
ResultExecutingContextTest.cs
RouteCollectionExtensionsTest.cs
RouteDataValueProviderFactoryTest.cs
SelectListTest.cs
SessionStateTempDataProviderTest.cs
SingleServiceResolverTest.cs
StringLengthAttributeAdapterTest.cs
TempDataDictionaryTest.cs
TypeCacheSerializerTest.cs
TypeCacheUtilTest.cs
TypeHelpersTest.cs
UrlHelperTest.cs
UrlParameterTest.cs
UrlRewriterHelperTest.cs
ValidatableObjectAdapterTest.cs
ValidateAntiForgeryTokenAttributeTest.cs
ValidateInputAttributeTest.cs
ValueProviderCollectionTest.cs
ValueProviderDictionaryTest.cs
ValueProviderFactoriesTest.cs
ValueProviderFactoryCollectionTest.cs
ValueProviderResultTest.cs
ValueProviderUtilTest.cs
ViewContextTest.cs
ViewDataDictionaryTest.cs
ViewDataInfoTest.cs
ViewEngineCollectionTest.cs
ViewEngineResultTest.cs
ViewEnginesTest.cs
ViewMasterPageControlBuilderTest.cs
ViewMasterPageTest.cs
ViewPageControlBuilderTest.cs
ViewPageTest.cs
ViewResultBaseTest.cs
ViewResultTest.cs
ViewStartPageTest.cs
ViewTypeParserFilterTest.cs
ViewUserControlControlBuilderTest.cs
ViewUserControlTest.cs
VirtualPathProviderViewEngineTest.cs
WebFormViewEngineTest.cs
WebFormViewTest.cs
Util
System.Web.Mvc.Test.csproj
packages.config
System.Web.Razor.Test
System.Web.WebPages.Administration.Test
System.Web.WebPages.Deployment.Test
System.Web.WebPages.Razor.Test
System.Web.WebPages.Test
WebMatrix.Data.Test
WebMatrix.WebData.Test
Settings.StyleCop
tools
.gitattributes
.gitignore
License.txt
README.md
Runtime.msbuild
Runtime.sln
Runtime.xunit
Settings.StyleCop
build.cmd
bdwgc
binary-reference-assemblies
bockbuild
boringssl
cecil
cecil-legacy
corefx
corert
helix-binaries
ikdasm
ikvm
illinker-test-assets
linker
llvm-project
nuget-buildtasks
nunit-lite
roslyn-binaries
rx
xunit-binaries
how-to-bump-roslyn-binaries.md
ikvm-native
llvm
m4
man
mcs
mono
msvc
netcore
po
runtime
samples
scripts
support
tools
COPYING.LIB
LICENSE
Makefile.am
Makefile.in
NEWS
README.md
acinclude.m4
aclocal.m4
autogen.sh
code_of_conduct.md
compile
config.guess
config.h.in
config.rpath
config.sub
configure.REMOVED.git-id
configure.ac.REMOVED.git-id
depcomp
install-sh
ltmain.sh.REMOVED.git-id
missing
mkinstalldirs
mono-uninstalled.pc.in
test-driver
winconfig.h
linux-packaging-mono/external/aspnetwebstack/test/System.Web.Mvc.Test/Test/AcceptVerbsAttributeTest.cs

217 lines
7.9 KiB
C#
Raw Normal View History

// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Mvc.Test
{
public class AcceptVerbsAttributeTest
{
private const string _invalidEnumFormatString = @"The enum '{0}' did not produce the correct array.
Expected: {1}
Actual: {2}";
[Fact]
public void ConstructorThrowsIfVerbsIsEmpty()
{
// Act & Assert
Assert.ThrowsArgumentNullOrEmpty(
delegate { new AcceptVerbsAttribute(new string[0]); }, "verbs");
}
[Fact]
public void ConstructorThrowsIfVerbsIsNull()
{
// Act & Assert
Assert.ThrowsArgumentNullOrEmpty(
delegate { new AcceptVerbsAttribute((string[])null); }, "verbs");
}
[Fact]
public void EnumToArray()
{
// Arrange
IDictionary<string, HttpVerbs> enumValues = EnumToDictionary<HttpVerbs>();
var allCombinations = EnumerableToCombinations(enumValues);
// Act & assert
foreach (var combination in allCombinations)
{
// generate all the names + values in this combination
List<string> aggrNames = new List<string>();
HttpVerbs aggrValues = (HttpVerbs)0;
foreach (var entry in combination)
{
aggrNames.Add(entry.Key);
aggrValues |= entry.Value;
}
// get the resulting array
string[] array = AcceptVerbsAttribute.EnumToArray(aggrValues);
var aggrNamesOrdered = aggrNames.OrderBy(name => name, StringComparer.OrdinalIgnoreCase);
var arrayOrdered = array.OrderBy(name => name, StringComparer.OrdinalIgnoreCase);
bool match = aggrNamesOrdered.SequenceEqual(arrayOrdered, StringComparer.OrdinalIgnoreCase);
if (!match)
{
string message = String.Format(_invalidEnumFormatString, aggrValues,
aggrNames.Aggregate((a, b) => a + ", " + b),
array.Aggregate((a, b) => a + ", " + b));
Assert.True(false, message);
}
}
}
[Fact]
public void IsValidForRequestReturnsFalseIfHttpVerbIsNotInVerbsCollection()
{
// Arrange
AcceptVerbsAttribute attr = new AcceptVerbsAttribute("get", "post");
ControllerContext context = GetControllerContextWithHttpVerb("HEAD");
// Act
bool result = attr.IsValidForRequest(context, null);
// Assert
Assert.False(result);
}
[Fact]
public void IsValidForRequestReturnsTrueIfHttpVerbIsInVerbsCollection()
{
// Arrange
AcceptVerbsAttribute attr = new AcceptVerbsAttribute("get", "post");
ControllerContext context = GetControllerContextWithHttpVerb("POST");
// Act
bool result = attr.IsValidForRequest(context, null);
// Assert
Assert.True(result);
}
[Fact]
public void IsValidForRequestReturnsTrueIfHttpVerbIsOverridden()
{
// Arrange
AcceptVerbsAttribute attr = new AcceptVerbsAttribute("put");
ControllerContext context = GetControllerContextWithHttpVerb("POST", "PUT", null, null);
// Act
bool result = attr.IsValidForRequest(context, null);
// Assert
Assert.True(result);
}
[Fact]
public void IsValidForRequestThrowsIfControllerContextIsNull()
{
// Arrange
AcceptVerbsAttribute attr = new AcceptVerbsAttribute("get", "post");
// Act & Assert
Assert.ThrowsArgumentNull(
delegate { attr.IsValidForRequest(null, null); }, "controllerContext");
}
[Fact]
public void VerbsPropertyFromEnumConstructor()
{
// Arrange
AcceptVerbsAttribute attr = new AcceptVerbsAttribute(HttpVerbs.Get | HttpVerbs.Post);
// Act
ReadOnlyCollection<string> collection = attr.Verbs as ReadOnlyCollection<string>;
// Assert
Assert.NotNull(collection);
Assert.Equal(2, collection.Count);
Assert.Equal("GET", collection[0]);
Assert.Equal("POST", collection[1]);
}
[Fact]
public void VerbsPropertyFromStringArrayConstructor()
{
// Arrange
AcceptVerbsAttribute attr = new AcceptVerbsAttribute("get", "post");
// Act
ReadOnlyCollection<string> collection = attr.Verbs as ReadOnlyCollection<string>;
// Assert
Assert.NotNull(collection);
Assert.Equal(2, collection.Count);
Assert.Equal("get", collection[0]);
Assert.Equal("post", collection[1]);
}
internal static ControllerContext GetControllerContextWithHttpVerb(string httpRequestVerb)
{
return GetControllerContextWithHttpVerb(httpRequestVerb, null, null, null);
}
internal static ControllerContext GetControllerContextWithHttpVerb(string httpRequestVerb, string httpHeaderVerb, string httpFormVerb, string httpQueryStringVerb)
{
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(c => c.HttpContext.Request.HttpMethod).Returns(httpRequestVerb);
NameValueCollection headers = new NameValueCollection();
if (!String.IsNullOrEmpty(httpHeaderVerb))
{
headers.Add(HttpRequestExtensions.XHttpMethodOverrideKey, httpHeaderVerb);
}
mockControllerContext.Setup(c => c.HttpContext.Request.Headers).Returns(headers);
NameValueCollection form = new NameValueCollection();
if (!String.IsNullOrEmpty(httpFormVerb))
{
form.Add(HttpRequestExtensions.XHttpMethodOverrideKey, httpFormVerb);
}
mockControllerContext.Setup(c => c.HttpContext.Request.Form).Returns(form);
NameValueCollection queryString = new NameValueCollection();
if (!String.IsNullOrEmpty(httpQueryStringVerb))
{
queryString.Add(HttpRequestExtensions.XHttpMethodOverrideKey, httpQueryStringVerb);
}
mockControllerContext.Setup(c => c.HttpContext.Request.QueryString).Returns(queryString);
return mockControllerContext.Object;
}
private static IDictionary<string, TEnum> EnumToDictionary<TEnum>()
{
// Arrange
var values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
return values.ToDictionary(value => Enum.GetName(typeof(TEnum), value), value => value);
}
private static IEnumerable<ICollection<T>> EnumerableToCombinations<T>(IEnumerable<T> elements)
{
List<T> allElements = elements.ToList();
int maxCount = 1 << allElements.Count;
for (int idxCombination = 0; idxCombination < maxCount; idxCombination++)
{
List<T> thisCollection = new List<T>();
for (int idxBit = 0; idxBit < 32; idxBit++)
{
bool bitActive = (((uint)idxCombination >> idxBit) & 1) != 0;
if (bitActive)
{
thisCollection.Add(allElements[idxBit]);
}
}
yield return thisCollection;
}
}
}
}