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
binary-reference-assemblies
bockbuild
boringssl
cecil
cecil-legacy
corefx
corert
ikdasm
ikvm
linker
nuget-buildtasks
nunit-lite
roslyn-binaries
rx
xunit-binaries
ikvm-native
libgc
llvm
m4
man
mcs
mono
msvc
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/ModelStateDictionaryTest.cs

312 lines
10 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.Globalization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.TestUtil;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Mvc.Test
{
public class ModelStateDictionaryTest
{
[Fact]
public void AddModelErrorCreatesModelStateIfNotPresent()
{
// Arrange
ModelStateDictionary dictionary = new ModelStateDictionary();
// Act
dictionary.AddModelError("some key", "some error");
// Assert
KeyValuePair<string, ModelState> kvp = Assert.Single(dictionary);
Assert.Equal("some key", kvp.Key);
ModelError error = Assert.Single(kvp.Value.Errors);
Assert.Equal("some error", error.ErrorMessage);
}
[Fact]
public void AddModelErrorThrowsIfKeyIsNull()
{
// Arrange
ModelStateDictionary dictionary = new ModelStateDictionary();
// Act & Assert
Assert.ThrowsArgumentNull(
delegate { dictionary.AddModelError(null, (string)null); }, "key");
}
[Fact]
public void AddModelErrorUsesExistingModelStateIfPresent()
{
// Arrange
ModelStateDictionary dictionary = new ModelStateDictionary();
dictionary.AddModelError("some key", "some error");
Exception ex = new Exception();
// Act
dictionary.AddModelError("some key", ex);
// Assert
KeyValuePair<string, ModelState> kvp = Assert.Single(dictionary);
Assert.Equal("some key", kvp.Key);
Assert.Equal(2, kvp.Value.Errors.Count);
Assert.Equal("some error", kvp.Value.Errors[0].ErrorMessage);
Assert.Same(ex, kvp.Value.Errors[1].Exception);
}
[Fact]
public void ConstructorThrowsIfDictionaryIsNull()
{
// Act & assert
Assert.ThrowsArgumentNull(
delegate { new ModelStateDictionary((ModelStateDictionary)null); }, "dictionary");
}
[Fact]
public void ConstructorWithDictionaryParameter()
{
// Arrange
ModelStateDictionary oldDictionary = new ModelStateDictionary()
{
{ "foo", new ModelState() { Value = HtmlHelperTest.GetValueProviderResult("bar", "bar") } }
};
// Act
ModelStateDictionary newDictionary = new ModelStateDictionary(oldDictionary);
// Assert
Assert.Single(newDictionary);
Assert.Equal("bar", newDictionary["foo"].Value.ConvertTo(typeof(string)));
}
[Fact]
public void DictionaryInterface()
{
// Arrange
DictionaryHelper<string, ModelState> helper = new DictionaryHelper<string, ModelState>()
{
Creator = () => new ModelStateDictionary(),
Comparer = StringComparer.OrdinalIgnoreCase,
SampleKeys = new string[] { "foo", "bar", "baz", "quux", "QUUX" },
SampleValues = new ModelState[] { new ModelState(), new ModelState(), new ModelState(), new ModelState(), new ModelState() },
ThrowOnKeyNotFound = false
};
// Act & assert
helper.Execute();
}
[Fact]
public void DictionaryIsSerializable()
{
// Arrange
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
ModelStateDictionary originalDict = new ModelStateDictionary();
originalDict.AddModelError("foo", new InvalidOperationException("Some invalid operation."));
originalDict.AddModelError("foo", new InvalidOperationException("Some other invalid operation."));
originalDict.AddModelError("bar", "Some exception text.");
originalDict.SetModelValue("baz", new ValueProviderResult("rawValue", "attemptedValue", CultureInfo.GetCultureInfo("fr-FR")));
// Act
formatter.Serialize(stream, originalDict);
stream.Position = 0;
ModelStateDictionary deserializedDict = formatter.Deserialize(stream) as ModelStateDictionary;
// Assert
Assert.NotNull(deserializedDict);
Assert.Equal(3, deserializedDict.Count);
ModelState foo = deserializedDict["FOO"];
Assert.IsType<InvalidOperationException>(foo.Errors[0].Exception);
Assert.Equal("Some invalid operation.", foo.Errors[0].Exception.Message);
Assert.IsType<InvalidOperationException>(foo.Errors[1].Exception);
Assert.Equal("Some other invalid operation.", foo.Errors[1].Exception.Message);
ModelState bar = deserializedDict["BAR"];
Assert.Equal("Some exception text.", bar.Errors[0].ErrorMessage);
ModelState baz = deserializedDict["BAZ"];
Assert.Equal("rawValue", baz.Value.RawValue);
Assert.Equal("attemptedValue", baz.Value.AttemptedValue);
Assert.Equal(CultureInfo.GetCultureInfo("fr-FR"), baz.Value.Culture);
}
[Fact]
public void IsValidFieldReturnsFalseIfDictionaryDoesNotContainKey()
{
// Arrange
ModelStateDictionary msd = new ModelStateDictionary();
// Act
bool isValid = msd.IsValidField("foo");
// Assert
Assert.True(isValid);
}
[Fact]
public void IsValidFieldReturnsFalseIfKeyChildContainsErrors()
{
// Arrange
ModelStateDictionary msd = new ModelStateDictionary();
msd.AddModelError("foo.bar", "error text");
// Act
bool isValid = msd.IsValidField("foo");
// Assert
Assert.False(isValid);
}
[Fact]
public void IsValidFieldReturnsFalseIfKeyContainsErrors()
{
// Arrange
ModelStateDictionary msd = new ModelStateDictionary();
msd.AddModelError("foo", "error text");
// Act
bool isValid = msd.IsValidField("foo");
// Assert
Assert.False(isValid);
}
[Fact]
public void IsValidFieldReturnsTrueIfModelStateDoesNotContainErrors()
{
// Arrange
ModelStateDictionary msd = new ModelStateDictionary()
{
{ "foo", new ModelState() { Value = new ValueProviderResult(null, null, null) } }
};
// Act
bool isValid = msd.IsValidField("foo");
// Assert
Assert.True(isValid);
}
[Fact]
public void IsValidFieldThrowsIfKeyIsNull()
{
// Arrange
ModelStateDictionary msd = new ModelStateDictionary();
// Act & assert
Assert.ThrowsArgumentNull(
delegate { msd.IsValidField(null); }, "key");
}
[Fact]
public void IsValidPropertyReturnsFalseIfErrors()
{
// Arrange
ModelState errorState = new ModelState() { Value = HtmlHelperTest.GetValueProviderResult("quux", "quux") };
errorState.Errors.Add("some error");
ModelStateDictionary dictionary = new ModelStateDictionary()
{
{ "foo", new ModelState() { Value = HtmlHelperTest.GetValueProviderResult("bar", "bar") } },
{ "baz", errorState }
};
// Act
bool isValid = dictionary.IsValid;
// Assert
Assert.False(isValid);
}
[Fact]
public void IsValidPropertyReturnsTrueIfNoErrors()
{
// Arrange
ModelStateDictionary dictionary = new ModelStateDictionary()
{
{ "foo", new ModelState() { Value = HtmlHelperTest.GetValueProviderResult("bar", "bar") } },
{ "baz", new ModelState() { Value = HtmlHelperTest.GetValueProviderResult("quux", "bar") } }
};
// Act
bool isValid = dictionary.IsValid;
// Assert
Assert.True(isValid);
}
[Fact]
public void MergeCopiesDictionaryEntries()
{
// Arrange
ModelStateDictionary fooDict = new ModelStateDictionary() { { "foo", new ModelState() } };
ModelStateDictionary barDict = new ModelStateDictionary() { { "bar", new ModelState() } };
// Act
fooDict.Merge(barDict);
// Assert
Assert.Equal(2, fooDict.Count);
Assert.Equal(barDict["bar"], fooDict["bar"]);
}
[Fact]
public void MergeDoesNothingIfParameterIsNull()
{
// Arrange
ModelStateDictionary fooDict = new ModelStateDictionary() { { "foo", new ModelState() } };
// Act
fooDict.Merge(null);
// Assert
Assert.Single(fooDict);
Assert.True(fooDict.ContainsKey("foo"));
}
[Fact]
public void SetAttemptedValueCreatesModelStateIfNotPresent()
{
// Arrange
ModelStateDictionary dictionary = new ModelStateDictionary();
// Act
dictionary.SetModelValue("some key", HtmlHelperTest.GetValueProviderResult("some value", "some value"));
// Assert
Assert.Single(dictionary);
ModelState modelState = dictionary["some key"];
Assert.Empty(modelState.Errors);
Assert.Equal("some value", modelState.Value.ConvertTo(typeof(string)));
}
[Fact]
public void SetAttemptedValueUsesExistingModelStateIfPresent()
{
// Arrange
ModelStateDictionary dictionary = new ModelStateDictionary();
dictionary.AddModelError("some key", "some error");
Exception ex = new Exception();
// Act
dictionary.SetModelValue("some key", HtmlHelperTest.GetValueProviderResult("some value", "some value"));
// Assert
Assert.Single(dictionary);
ModelState modelState = dictionary["some key"];
Assert.Single(modelState.Errors);
Assert.Equal("some error", modelState.Errors[0].ErrorMessage);
Assert.Equal("some value", modelState.Value.ConvertTo(typeof(string)));
}
}
}