Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@@ -0,0 +1,258 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.IO;
using System.Web.Mvc.Properties;
using System.Web.Routing;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Mvc.Html.Test
{
public class ChildActionExtensionsTest
{
Mock<HtmlHelper> htmlHelper;
Mock<HttpContextBase> httpContext;
Mock<RouteBase> route;
Mock<IViewDataContainer> viewDataContainer;
RouteData originalRouteData;
RouteCollection routes;
ViewContext viewContext;
VirtualPathData virtualPathData;
public ChildActionExtensionsTest()
{
route = new Mock<RouteBase>();
route.Setup(r => r.GetVirtualPath(It.IsAny<RequestContext>(), It.IsAny<RouteValueDictionary>()))
.Returns(() => virtualPathData);
virtualPathData = new VirtualPathData(route.Object, "~/VirtualPath");
routes = new RouteCollection();
routes.Add(route.Object);
originalRouteData = new RouteData();
string returnValue = "";
httpContext = new Mock<HttpContextBase>();
httpContext.Setup(hc => hc.Request.ApplicationPath).Returns("~");
httpContext.Setup(hc => hc.Response.ApplyAppPathModifier(It.IsAny<string>()))
.Callback<string>(s => returnValue = s)
.Returns(() => returnValue);
httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()));
viewContext = new ViewContext
{
RequestContext = new RequestContext(httpContext.Object, originalRouteData)
};
viewDataContainer = new Mock<IViewDataContainer>();
htmlHelper = new Mock<HtmlHelper>(viewContext, viewDataContainer.Object, routes);
}
[Fact]
public void GuardClauses()
{
// Act & Assert
Assert.ThrowsArgumentNull(
() => ChildActionExtensions.ActionHelper(null /* htmlHelper */, "abc", null /* controllerName */, null /* routeValues */, null /* textWriter */),
"htmlHelper"
);
Assert.ThrowsArgumentNullOrEmpty(
() => ChildActionExtensions.ActionHelper(htmlHelper.Object, null /* actionName */, null /* controllerName */, null /* routeValues */, null /* textWriter */),
"actionName"
);
Assert.ThrowsArgumentNullOrEmpty(
() => ChildActionExtensions.ActionHelper(htmlHelper.Object, String.Empty /* actionName */, null /* controllerName */, null /* routeValues */, null /* textWriter */),
"actionName"
);
}
[Fact]
public void ServerExecuteCalledWithWrappedChildActionMvcHandler()
{
// Arrange
IHttpHandler callbackHandler = null;
TextWriter callbackTextWriter = null;
bool callbackPreserveForm = false;
httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))
.Callback<IHttpHandler, TextWriter, bool>(
(handler, textWriter, preserveForm) =>
{
callbackHandler = handler;
callbackTextWriter = textWriter;
callbackPreserveForm = preserveForm;
});
TextWriter stringWriter = new StringWriter();
// Act
ChildActionExtensions.ActionHelper(htmlHelper.Object, "actionName", null /* controllerName */, null /* routeValues */, stringWriter);
// Assert
Assert.NotNull(callbackHandler);
HttpHandlerUtil.ServerExecuteHttpHandlerWrapper wrapper = callbackHandler as HttpHandlerUtil.ServerExecuteHttpHandlerWrapper;
Assert.NotNull(wrapper);
Assert.NotNull(wrapper.InnerHandler);
ChildActionExtensions.ChildActionMvcHandler childHandler = wrapper.InnerHandler as ChildActionExtensions.ChildActionMvcHandler;
Assert.NotNull(childHandler);
Assert.Same(stringWriter, callbackTextWriter);
Assert.True(callbackPreserveForm);
}
[Fact]
public void RouteDataTokensIncludesParentActionViewContext()
{
// Arrange
MvcHandler mvcHandler = null;
httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))
.Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);
// Act
ChildActionExtensions.ActionHelper(htmlHelper.Object, "actionName", null /* controllerName */, null /* routeValues */, null /* textWriter */);
// Assert
Assert.Same(viewContext, mvcHandler.RequestContext.RouteData.DataTokens[ControllerContext.ParentActionViewContextToken]);
}
[Fact]
public void RouteValuesIncludeNewActionName()
{
// Arrange
MvcHandler mvcHandler = null;
httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))
.Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);
// Act
ChildActionExtensions.ActionHelper(htmlHelper.Object, "actionName", null /* controllerName */, null /* routeValues */, null /* textWriter */);
// Assert
RouteData routeData = mvcHandler.RequestContext.RouteData;
Assert.Equal("actionName", routeData.Values["action"]);
}
[Fact]
public void RouteValuesIncludeOldControllerNameWhenControllerNameIsNullOrEmpty()
{
// Arrange
originalRouteData.Values["controller"] = "oldController";
MvcHandler mvcHandler = null;
httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))
.Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);
// Act
ChildActionExtensions.ActionHelper(htmlHelper.Object, "actionName", null /* controllerName */, null /* routeValues */, null /* textWriter */);
// Assert
RouteData routeData = mvcHandler.RequestContext.RouteData;
Assert.Equal("oldController", routeData.Values["controller"]);
}
[Fact]
public void RouteValuesIncludeNewControllerNameWhenControllNameIsNotEmpty()
{
// Arrange
originalRouteData.Values["controller"] = "oldController";
MvcHandler mvcHandler = null;
httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))
.Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);
// Act
ChildActionExtensions.ActionHelper(htmlHelper.Object, "actionName", "newController", null /* routeValues */, null /* textWriter */);
// Assert
RouteData routeData = mvcHandler.RequestContext.RouteData;
Assert.Equal("newController", routeData.Values["controller"]);
}
[Fact]
public void PassedRouteValuesOverrideParentRequestRouteValues()
{
// Arrange
originalRouteData.Values["name1"] = "value1";
originalRouteData.Values["name2"] = "value2";
MvcHandler mvcHandler = null;
httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))
.Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);
// Act
ChildActionExtensions.ActionHelper(htmlHelper.Object, "actionName", null /* controllerName */, new RouteValueDictionary { { "name2", "newValue2" } }, null /* textWriter */);
// Assert
RouteData routeData = mvcHandler.RequestContext.RouteData;
Assert.Equal("value1", routeData.Values["name1"]);
Assert.Equal("newValue2", routeData.Values["name2"]);
Assert.Equal("newValue2", (routeData.Values[ChildActionValueProvider.ChildActionValuesKey] as DictionaryValueProvider<object>).GetValue("name2").RawValue);
}
[Fact]
public void NoChildActionValuesDictionaryCreatedIfNoRouteValuesPassed()
{
// Arrange
MvcHandler mvcHandler = null;
httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))
.Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);
// Act
ChildActionExtensions.ActionHelper(htmlHelper.Object, "actionName", null /* controllerName */, null, null /* textWriter */);
// Assert
RouteData routeData = mvcHandler.RequestContext.RouteData;
Assert.Null(routeData.Values[ChildActionValueProvider.ChildActionValuesKey]);
}
[Fact]
public void RouteValuesDoesNotIncludeExplicitlyPassedAreaName()
{
// Arrange
Route route = routes.MapRoute("my-area", "my-area");
route.DataTokens["area"] = "myArea";
MvcHandler mvcHandler = null;
httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))
.Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);
// Act
ChildActionExtensions.ActionHelper(htmlHelper.Object, "actionName", null /* controllerName */, new RouteValueDictionary { { "area", "myArea" } }, null /* textWriter */);
// Assert
RouteData routeData = mvcHandler.RequestContext.RouteData;
Assert.False(routeData.Values.ContainsKey("area"));
Assert.Null((routeData.Values[ChildActionValueProvider.ChildActionValuesKey] as DictionaryValueProvider<object>).GetValue("area"));
}
[Fact]
public void RouteValuesIncludeExplicitlyPassedAreaNameIfAreasNotInUse()
{
// Arrange
Route route = routes.MapRoute("my-area", "my-area");
MvcHandler mvcHandler = null;
httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))
.Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);
// Act
ChildActionExtensions.ActionHelper(htmlHelper.Object, "actionName", null /* controllerName */, new RouteValueDictionary { { "area", "myArea" } }, null /* textWriter */);
// Assert
RouteData routeData = mvcHandler.RequestContext.RouteData;
Assert.True(routeData.Values.ContainsKey("area"));
Assert.Equal("myArea", (routeData.Values[ChildActionValueProvider.ChildActionValuesKey] as DictionaryValueProvider<object>).GetValue("area").RawValue);
}
[Fact]
public void NoMatchingRouteThrows()
{
// Arrange
routes.Clear();
// Act & Assert
Assert.Throws<InvalidOperationException>(
() => ChildActionExtensions.ActionHelper(htmlHelper.Object, "actionName", null /* controllerName */, null /* routeValues */, null /* textWriter */),
MvcResources.Common_NoRouteMatched
);
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,257 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq.Expressions;
using Microsoft.Web.UnitTestUtil;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Mvc.Html.Test
{
public class DisplayNameExtensionsTest
{
[Fact]
public void DisplayNameNullExpressionThrows()
{
// Act & Assert
Assert.ThrowsArgumentNull(
() => MvcHelper.GetHtmlHelper().Display(null),
"expression");
}
[Fact]
public void DisplayNameWithNoModelMetadataDisplayNameOverride()
{
// Act
MvcHtmlString result = MvcHelper.GetHtmlHelper().DisplayNameInternal("PropertyName", new MetadataHelper().MetadataProvider.Object);
// Assert
Assert.Equal("PropertyName", result.ToHtmlString());
}
[Fact]
public void DisplayNameUsesMetadataForDisplayText()
{
// Arrange
MetadataHelper metadataHelper = new MetadataHelper();
metadataHelper.Metadata.Setup(m => m.DisplayName).Returns("Custom display name from metadata");
// Act
MvcHtmlString result = MvcHelper.GetHtmlHelper().DisplayNameInternal("PropertyName", metadataHelper.MetadataProvider.Object);
// Assert
Assert.Equal("Custom display name from metadata", result.ToHtmlString());
}
private sealed class Model
{
public string PropertyName { get; set; }
}
[Fact]
public void DisplayNameConsultsMetadataProviderForMetadataAboutProperty()
{
// Arrange
Model model = new Model { PropertyName = "propertyValue" };
ViewDataDictionary viewData = new ViewDataDictionary();
Mock<ViewContext> viewContext = new Mock<ViewContext>();
viewContext.Setup(c => c.ViewData).Returns(viewData);
Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();
viewDataContainer.Setup(c => c.ViewData).Returns(viewData);
HtmlHelper<Model> html = new HtmlHelper<Model>(viewContext.Object, viewDataContainer.Object);
viewData.Model = model;
MetadataHelper metadataHelper = new MetadataHelper();
metadataHelper.MetadataProvider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), typeof(Model), "PropertyName"))
.Returns(metadataHelper.Metadata.Object)
.Verifiable();
// Act
html.DisplayNameInternal("PropertyName", metadataHelper.MetadataProvider.Object);
// Assert
metadataHelper.MetadataProvider.Verify();
}
[Fact]
public void DisplayNameUsesMetadataForPropertyName()
{
// Arrange
MetadataHelper metadataHelper = new MetadataHelper();
metadataHelper.Metadata = new Mock<ModelMetadata>(metadataHelper.MetadataProvider.Object, null, null, typeof(object), "Custom property name from metadata");
metadataHelper.MetadataProvider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))
.Returns(metadataHelper.Metadata.Object);
// Act
MvcHtmlString result = MvcHelper.GetHtmlHelper().DisplayNameInternal("PropertyName", metadataHelper.MetadataProvider.Object);
// Assert
Assert.Equal("Custom property name from metadata", result.ToHtmlString());
}
[Fact]
public void DisplayNameForNullExpressionThrows()
{
// Act & Assert
Assert.ThrowsArgumentNull(
() => MvcHelper.GetHtmlHelper().DisplayNameFor((Expression<Func<Object, Object>>)null),
"expression");
Assert.ThrowsArgumentNull(
() => GetEnumerableHtmlHelper().DisplayNameFor((Expression<Func<Foo, Object>>)null),
"expression");
}
[Fact]
public void DisplayNameForNonMemberExpressionThrows()
{
// Act & Assert
Assert.Throws<InvalidOperationException>(
() => MvcHelper.GetHtmlHelper().DisplayNameFor(model => new { foo = "Bar" }),
"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.");
Assert.Throws<InvalidOperationException>(
() => GetEnumerableHtmlHelper().DisplayNameFor((Expression<Func<IEnumerable<Foo>, object>>)(model => new { foo = "Bar" })),
"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.");
}
[Fact]
public void DisplayNameForWithNoModelMetadataDisplayNameOverride()
{
// Arrange
string unknownKey = "this is a dummy parameter value";
// Act
MvcHtmlString result = MvcHelper.GetHtmlHelper().DisplayNameFor(model => unknownKey);
MvcHtmlString enumerableResult = GetEnumerableHtmlHelper().DisplayNameFor((Expression<Func<IEnumerable<Foo>, string>>)(model => unknownKey));
// Assert
Assert.Equal("unknownKey", result.ToHtmlString());
Assert.Equal("unknownKey", enumerableResult.ToHtmlString());
}
[Fact]
public void DisplayNameForUsesModelMetadata()
{
// Arrange
MetadataHelper metadataHelper = new MetadataHelper();
metadataHelper.Metadata.Setup(m => m.DisplayName).Returns("Custom display name from metadata");
string unknownKey = "this is a dummy parameter value";
// Act
MvcHtmlString result = MvcHelper.GetHtmlHelper().DisplayNameForInternal(model => unknownKey, metadataHelper.MetadataProvider.Object);
MvcHtmlString enumerableResult = GetEnumerableHtmlHelper().DisplayNameForInternal(model => model.Bar, metadataHelper.MetadataProvider.Object);
// Assert
Assert.Equal("Custom display name from metadata", result.ToHtmlString());
Assert.Equal("Custom display name from metadata", enumerableResult.ToHtmlString());
}
[Fact]
public void DisplayNameForEmptyDisplayNameReturnsEmptyName()
{
// Arrange
MetadataHelper metadataHelper = new MetadataHelper();
metadataHelper.Metadata.Setup(m => m.DisplayName).Returns(String.Empty);
string unknownKey = "this is a dummy parameter value";
// Act
MvcHtmlString result = MvcHelper.GetHtmlHelper().DisplayNameForInternal(model => unknownKey, metadataHelper.MetadataProvider.Object);
MvcHtmlString enumerableResult = GetEnumerableHtmlHelper().DisplayNameForInternal(model => model.Bar, metadataHelper.MetadataProvider.Object);
// Assert
Assert.Equal(String.Empty, result.ToHtmlString());
Assert.Equal(String.Empty, enumerableResult.ToHtmlString());
}
[Fact]
public void DisplayNameForModelUsesModelMetadata()
{
// Arrange
ViewDataDictionary viewData = new ViewDataDictionary();
Mock<ModelMetadata> metadata = new MetadataHelper().Metadata;
metadata.Setup(m => m.DisplayName).Returns("Custom display name from metadata");
viewData.ModelMetadata = metadata.Object;
viewData.TemplateInfo.HtmlFieldPrefix = "Prefix";
// Act
MvcHtmlString result = MvcHelper.GetHtmlHelper(viewData).DisplayNameForModel();
// Assert
Assert.Equal("Custom display name from metadata", result.ToHtmlString());
}
[Fact]
public void DisplayNameForWithNestedClass()
{
// Arrange
ViewDataDictionary viewData = new ViewDataDictionary();
Mock<ViewContext> viewContext = new Mock<ViewContext>();
viewContext.Setup(c => c.ViewData).Returns(viewData);
Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();
viewDataContainer.Setup(c => c.ViewData).Returns(viewData);
HtmlHelper<NestedProduct> html = new HtmlHelper<NestedProduct>(viewContext.Object, viewDataContainer.Object);
// Act
MvcHtmlString result = html.DisplayNameForInternal(nested => nested.product.Id, new MetadataHelper().MetadataProvider.Object);
//Assert
Assert.Equal("Id", result.ToHtmlString());
}
private class Product
{
public int Id { get; set; }
}
private class Cart
{
public Product[] Products { get; set; }
}
private class NestedProduct
{
public Product product = new Product();
}
private sealed class Foo
{
public string Bar { get; set; }
}
private static HtmlHelper<IEnumerable<Foo>> GetEnumerableHtmlHelper()
{
return MvcHelper.GetHtmlHelper(new ViewDataDictionary<IEnumerable<Foo>>());
}
private sealed class MetadataHelper
{
public Mock<ModelMetadata> Metadata { get; set; }
public Mock<ModelMetadataProvider> MetadataProvider { get; set; }
public MetadataHelper()
{
MetadataProvider = new Mock<ModelMetadataProvider>();
Metadata = new Mock<ModelMetadata>(MetadataProvider.Object, null, null, typeof(object), null);
MetadataProvider.Setup(p => p.GetMetadataForProperties(It.IsAny<object>(), It.IsAny<Type>()))
.Returns(new ModelMetadata[0]);
MetadataProvider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>()))
.Returns(Metadata.Object);
MetadataProvider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))
.Returns(Metadata.Object);
}
}
}
}

View File

@@ -0,0 +1,425 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Web.Routing;
using Microsoft.Web.UnitTestUtil;
using Moq;
using Xunit;
namespace System.Web.Mvc.Html.Test
{
public class FormExtensionsTest
{
private static void BeginFormHelper(Func<HtmlHelper, MvcForm> beginForm, string expectedFormTag)
{
// Arrange
StringWriter writer;
HtmlHelper htmlHelper = GetFormHelper(out writer);
// Act
IDisposable formDisposable = beginForm(htmlHelper);
formDisposable.Dispose();
// Assert
Assert.Equal(expectedFormTag + "</form>", writer.ToString());
}
[Fact]
public void BeginFormParameterDictionaryMerging()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("bar", "foo", FormMethod.Get, new RouteValueDictionary(new { method = "post" })),
@"<form action=""" + MvcHelper.AppPathModifier + @"/foo/bar"" method=""get"">");
}
[Fact]
public void BeginFormSetsAndRestoresToDefault()
{
// Arrange
StringWriter writer;
HtmlHelper htmlHelper = GetFormHelper(out writer);
htmlHelper.ViewContext.FormContext = null;
FormContext defaultFormContext = htmlHelper.ViewContext.FormContext;
// Act & assert - push
MvcForm theForm = htmlHelper.BeginForm();
Assert.NotNull(htmlHelper.ViewContext.FormContext);
Assert.NotEqual(defaultFormContext, htmlHelper.ViewContext.FormContext);
// Act & assert - pop
theForm.Dispose();
Assert.Equal(defaultFormContext, htmlHelper.ViewContext.FormContext);
Assert.Equal(@"<form action=""/some/path"" method=""post""></form>", writer.ToString());
}
[Fact]
public void BeginFormWithClientValidationEnabled()
{
// Arrange
StringWriter writer;
HtmlHelper htmlHelper = GetFormHelper(out writer);
htmlHelper.ViewContext.ClientValidationEnabled = true;
htmlHelper.ViewContext.FormContext = null;
FormContext defaultFormContext = htmlHelper.ViewContext.FormContext;
// Act & assert - push
MvcForm theForm = htmlHelper.BeginForm();
Assert.NotNull(htmlHelper.ViewContext.FormContext);
Assert.NotEqual(defaultFormContext, htmlHelper.ViewContext.FormContext);
Assert.Equal("form_id", htmlHelper.ViewContext.FormContext.FormId);
// Act & assert - pop
theForm.Dispose();
Assert.Equal(defaultFormContext, htmlHelper.ViewContext.FormContext);
Assert.Equal(@"<form action=""/some/path"" id=""form_id"" method=""post""></form><script type=""text/javascript"">
//<![CDATA[
if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
window.mvcClientValidationMetadata.push({""Fields"":[],""FormId"":""form_id"",""ReplaceValidationSummary"":false});
//]]>
</script>", writer.ToString());
}
[Fact]
public void BeginFormWithClientValidationAndUnobtrusiveJavaScriptEnabled()
{
// Arrange
StringWriter writer;
HtmlHelper htmlHelper = GetFormHelper(out writer);
htmlHelper.ViewContext.ClientValidationEnabled = true;
htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled = true;
// Act & assert - push
MvcForm theForm = htmlHelper.BeginForm();
Assert.Null(htmlHelper.ViewContext.FormContext.FormId);
// Act & assert - pop
theForm.Dispose();
Assert.Equal(@"<form action=""/some/path"" method=""post""></form>", writer.ToString());
}
[Fact]
public void BeginFormWithActionControllerInvalidFormMethodHtmlValues()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("bar", "foo", (FormMethod)2, new RouteValueDictionary(new { baz = "baz" })),
@"<form action=""" + MvcHelper.AppPathModifier + @"/foo/bar"" baz=""baz"" method=""post"">");
}
[Fact]
public void BeginFormWithActionController()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("bar", "foo"),
@"<form action=""" + MvcHelper.AppPathModifier + @"/foo/bar"" method=""post"">");
}
[Fact]
public void BeginFormWithActionControllerFormMethodHtmlDictionary()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("bar", "foo", FormMethod.Get, new RouteValueDictionary(new { baz = "baz" })),
@"<form action=""" + MvcHelper.AppPathModifier + @"/foo/bar"" baz=""baz"" method=""get"">");
}
[Fact]
public void BeginFormWithActionControllerFormMethodHtmlValues()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("bar", "foo", FormMethod.Get, new { baz = "baz" }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/foo/bar"" baz=""baz"" method=""get"">");
}
[Fact]
public void BeginFormWithActionControllerFormMethodHtmlValuesWithUnderscores()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("bar", "foo", FormMethod.Get, new { data_test = "value" }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/foo/bar"" data-test=""value"" method=""get"">");
}
[Fact]
public void BeginFormWithActionControllerRouteDictionaryFormMethodHtmlDictionary()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("bar", "foo", new RouteValueDictionary(new { id = "id" }), FormMethod.Get, new RouteValueDictionary(new { baz = "baz" })),
@"<form action=""" + MvcHelper.AppPathModifier + @"/foo/bar/id"" baz=""baz"" method=""get"">");
}
[Fact]
public void BeginFormWithActionControllerRouteValuesFormMethodHtmlValues()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("bar", "foo", new { id = "id" }, FormMethod.Get, new { baz = "baz" }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/foo/bar/id"" baz=""baz"" method=""get"">");
}
[Fact]
public void BeginFormWithActionControllerRouteValuesFormMethodHtmlValuesWithUnderscores()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("bar", "foo", new { id = "id" }, FormMethod.Get, new { foo_baz = "baz" }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/foo/bar/id"" foo-baz=""baz"" method=""get"">");
}
[Fact]
public void BeginFormWithActionControllerNullRouteValuesFormMethodNullHtmlValues()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("bar", "foo", null, FormMethod.Get, null),
@"<form action=""" + MvcHelper.AppPathModifier + @"/foo/bar"" method=""get"">");
}
[Fact]
public void BeginFormWithRouteValues()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm(new { action = "someOtherAction", id = "id" }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/home/someOtherAction/id"" method=""post"">");
}
[Fact]
public void BeginFormWithRouteDictionary()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm(new RouteValueDictionary { { "action", "someOtherAction" }, { "id", "id" } }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/home/someOtherAction/id"" method=""post"">");
}
[Fact]
public void BeginFormWithActionControllerRouteValues()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("myAction", "myController", new { id = "id", pageNum = "123" }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/myController/myAction/id?pageNum=123"" method=""post"">");
}
[Fact]
public void BeginFormWithActionControllerRouteDictionary()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("myAction", "myController", new RouteValueDictionary { { "pageNum", "123" }, { "id", "id" } }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/myController/myAction/id?pageNum=123"" method=""post"">");
}
[Fact]
public void BeginFormWithActionControllerMethod()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("myAction", "myController", FormMethod.Get),
@"<form action=""" + MvcHelper.AppPathModifier + @"/myController/myAction"" method=""get"">");
}
[Fact]
public void BeginFormWithActionControllerRouteValuesMethod()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("myAction", "myController", new { id = "id", pageNum = "123" }, FormMethod.Get),
@"<form action=""" + MvcHelper.AppPathModifier + @"/myController/myAction/id?pageNum=123"" method=""get"">");
}
[Fact]
public void BeginFormWithActionControllerRouteDictionaryMethod()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm("myAction", "myController", new RouteValueDictionary { { "pageNum", "123" }, { "id", "id" } }, FormMethod.Get),
@"<form action=""" + MvcHelper.AppPathModifier + @"/myController/myAction/id?pageNum=123"" method=""get"">");
}
[Fact]
public void BeginFormWithNoParams()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginForm(),
@"<form action=""/some/path"" method=""post"">");
}
[Fact]
public void BeginRouteFormWithRouteNameInvalidFormMethodHtmlValues()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", (FormMethod)2, new RouteValueDictionary(new { baz = "baz" })),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction"" baz=""baz"" method=""post"">");
}
[Fact]
public void BeginRouteFormWithRouteName()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute"),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction"" method=""post"">");
}
[Fact]
public void BeginRouteFormWithRouteNameFormMethodHtmlDictionary()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", FormMethod.Get, new RouteValueDictionary(new { baz = "baz" })),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction"" baz=""baz"" method=""get"">");
}
[Fact]
public void BeginRouteFormWithRouteNameFormMethodHtmlValues()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", FormMethod.Get, new { baz = "baz" }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction"" baz=""baz"" method=""get"">");
}
[Fact]
public void BeginRouteFormWithRouteNameFormMethodHtmlValuesWithUnderscores()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", FormMethod.Get, new { foo_baz = "baz" }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction"" foo-baz=""baz"" method=""get"">");
}
[Fact]
public void BeginRouteFormWithRouteNameRouteDictionaryFormMethodHtmlDictionary()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", new RouteValueDictionary(new { id = "id" }), FormMethod.Get, new RouteValueDictionary(new { baz = "baz" })),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction/id"" baz=""baz"" method=""get"">");
}
[Fact]
public void BeginRouteFormWithRouteNameRouteValuesFormMethodHtmlValues()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", new { id = "id" }, FormMethod.Get, new { baz = "baz" }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction/id"" baz=""baz"" method=""get"">");
}
[Fact]
public void BeginRouteFormWithRouteNameRouteValuesFormMethodHtmlValuesWithUnderscores()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", new { id = "id" }, FormMethod.Get, new { foo_baz = "baz" }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction/id"" foo-baz=""baz"" method=""get"">");
}
[Fact]
public void BeginRouteFormWithRouteNameNullRouteValuesFormMethodNullHtmlValues()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", null, FormMethod.Get, null),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction"" method=""get"">");
}
[Fact]
public void BeginRouteFormWithRouteValues()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm(new { action = "someOtherAction", id = "id" }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/home/someOtherAction/id"" method=""post"">");
}
[Fact]
public void BeginRouteFormWithRouteDictionary()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm(new RouteValueDictionary { { "action", "someOtherAction" }, { "id", "id" } }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/home/someOtherAction/id"" method=""post"">");
}
[Fact]
public void BeginRouteFormWithRouteNameRouteValues()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", new { id = "id", pageNum = "123" }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction/id?pageNum=123"" method=""post"">");
}
[Fact]
public void BeginRouteFormWithActionControllerRouteDictionary()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", new RouteValueDictionary { { "pageNum", "123" }, { "id", "id" } }),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction/id?pageNum=123"" method=""post"">");
}
[Fact]
public void BeginRouteFormCanUseNamedRouteWithoutSpecifyingDefaults()
{
// DevDiv 217072: Non-mvc specific helpers should not give default values for controller and action
BeginFormHelper(
htmlHelper =>
{
htmlHelper.RouteCollection.MapRoute("MyRouteName", "any/url", new { controller = "Charlie" });
return htmlHelper.BeginRouteForm("MyRouteName");
}, @"<form action=""" + MvcHelper.AppPathModifier + @"/any/url"" method=""post"">");
}
[Fact]
public void BeginRouteFormWithActionControllerMethod()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", FormMethod.Get),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction"" method=""get"">");
}
[Fact]
public void BeginRouteFormWithActionControllerRouteValuesMethod()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", new { id = "id", pageNum = "123" }, FormMethod.Get),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction/id?pageNum=123"" method=""get"">");
}
[Fact]
public void BeginRouteFormWithActionControllerRouteDictionaryMethod()
{
BeginFormHelper(
htmlHelper => htmlHelper.BeginRouteForm("namedroute", new RouteValueDictionary { { "pageNum", "123" }, { "id", "id" } }, FormMethod.Get),
@"<form action=""" + MvcHelper.AppPathModifier + @"/named/home/oldaction/id?pageNum=123"" method=""get"">");
}
[Fact]
public void EndFormWritesCloseTag()
{
// Arrange
StringWriter writer;
HtmlHelper htmlHelper = GetFormHelper(out writer);
// Act
htmlHelper.EndForm();
// Assert
Assert.Equal("</form>", writer.ToString());
}
private static HtmlHelper GetFormHelper(out StringWriter writer)
{
Mock<ViewContext> mockViewContext = new Mock<ViewContext>() { CallBase = true };
mockViewContext.Setup(c => c.HttpContext.Request.Url).Returns(new Uri("http://www.contoso.com/some/path"));
mockViewContext.Setup(c => c.HttpContext.Request.RawUrl).Returns("/some/path");
mockViewContext.Setup(c => c.HttpContext.Request.ApplicationPath).Returns("/");
mockViewContext.Setup(c => c.HttpContext.Request.Path).Returns("/");
mockViewContext.Setup(c => c.HttpContext.Request.ServerVariables).Returns((NameValueCollection)null);
mockViewContext.Setup(c => c.HttpContext.Response.Write(It.IsAny<string>())).Throws(new Exception("Should not be called"));
mockViewContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());
writer = new StringWriter();
mockViewContext.Setup(c => c.Writer).Returns(writer);
mockViewContext.Setup(c => c.HttpContext.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(r => MvcHelper.AppPathModifier + r);
RouteCollection rt = new RouteCollection();
rt.Add(new Route("{controller}/{action}/{id}", null) { Defaults = new RouteValueDictionary(new { id = "defaultid" }) });
rt.Add("namedroute", new Route("named/{controller}/{action}/{id}", null) { Defaults = new RouteValueDictionary(new { id = "defaultid" }) });
RouteData rd = new RouteData();
rd.Values.Add("controller", "home");
rd.Values.Add("action", "oldaction");
mockViewContext.Setup(c => c.RouteData).Returns(rd);
HtmlHelper helper = new HtmlHelper(mockViewContext.Object, new Mock<IViewDataContainer>().Object, rt);
helper.ViewContext.FormIdGenerator = () => "form_id";
return helper;
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,99 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.IO;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Mvc.Html.Test
{
public class MvcFormTest
{
[Fact]
public void ConstructorWithNullViewContextThrows()
{
Assert.ThrowsArgumentNull(
delegate { new MvcForm((ViewContext)null); },
"viewContext");
}
[Fact]
public void DisposeRendersCloseFormTag()
{
// Arrange
StringWriter writer = new StringWriter();
ViewContext viewContext = GetViewContext(writer);
MvcForm form = new MvcForm(viewContext);
// Act
form.Dispose();
// Assert
Assert.Equal("</form>", writer.ToString());
}
[Fact]
public void EndFormRendersCloseFormTag()
{
// Arrange
StringWriter writer = new StringWriter();
ViewContext viewContext = GetViewContext(writer);
MvcForm form = new MvcForm(viewContext);
// Act
form.EndForm();
// Assert
Assert.Equal("</form>", writer.ToString());
}
[Fact]
public void DisposeTwiceRendersCloseFormTagOnce()
{
// Arrange
StringWriter writer = new StringWriter();
ViewContext viewContext = GetViewContext(writer);
MvcForm form = new MvcForm(viewContext);
// Act
form.Dispose();
form.Dispose();
// Assert
Assert.Equal("</form>", writer.ToString());
}
[Fact]
public void EndFormTwiceRendersCloseFormTagOnce()
{
// Arrange
StringWriter writer = new StringWriter();
ViewContext viewContext = GetViewContext(writer);
MvcForm form = new MvcForm(viewContext);
// Act
form.EndForm();
form.EndForm();
// Assert
Assert.Equal("</form>", writer.ToString());
}
private static ViewContext GetViewContext(TextWriter writer)
{
Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(o => o.Items).Returns(new Hashtable());
return new ViewContext()
{
HttpContext = mockHttpContext.Object,
Writer = writer
};
}
}
}

View File

@@ -0,0 +1,85 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using Microsoft.Web.UnitTestUtil;
using Xunit;
namespace System.Web.Mvc.Html.Test
{
public class NameExtensionsTest
{
[Fact]
public void NonStronglyTypedWithNoPrefix()
{
// Arrange
HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());
// Act & Assert
Assert.Equal("", html.IdForModel().ToHtmlString());
Assert.Equal("foo", html.Id("foo").ToHtmlString());
Assert.Equal("foo_bar", html.Id("foo.bar").ToHtmlString());
Assert.Equal(String.Empty, html.Id("<script>alert(\"XSS!\")</script>").ToHtmlString());
Assert.Equal("", html.NameForModel().ToHtmlString());
Assert.Equal("foo", html.Name("foo").ToHtmlString());
Assert.Equal("foo.bar", html.Name("foo.bar").ToHtmlString());
Assert.Equal("&lt;script>alert(&quot;XSS!&quot;)&lt;/script>", html.Name("<script>alert(\"XSS!\")</script>").ToHtmlString());
}
[Fact]
public void NonStronglyTypedWithPrefix()
{
// Arrange
HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());
html.ViewData.TemplateInfo.HtmlFieldPrefix = "prefix";
// Act & Assert
Assert.Equal("prefix", html.IdForModel().ToHtmlString());
Assert.Equal("prefix_foo", html.Id("foo").ToHtmlString());
Assert.Equal("prefix_foo_bar", html.Id("foo.bar").ToHtmlString());
Assert.Equal("prefix", html.NameForModel().ToHtmlString());
Assert.Equal("prefix.foo", html.Name("foo").ToHtmlString());
Assert.Equal("prefix.foo.bar", html.Name("foo.bar").ToHtmlString());
}
[Fact]
public void StronglyTypedWithNoPrefix()
{
// Arrange
HtmlHelper<OuterClass> html = MvcHelper.GetHtmlHelper(new ViewDataDictionary<OuterClass>());
// Act & Assert
Assert.Equal("IntValue", html.IdFor(m => m.IntValue).ToHtmlString());
Assert.Equal("Inner_StringValue", html.IdFor(m => m.Inner.StringValue).ToHtmlString());
Assert.Equal("IntValue", html.NameFor(m => m.IntValue).ToHtmlString());
Assert.Equal("Inner.StringValue", html.NameFor(m => m.Inner.StringValue).ToHtmlString());
}
[Fact]
public void StronglyTypedWithPrefix()
{
// Arrange
HtmlHelper<OuterClass> html = MvcHelper.GetHtmlHelper(new ViewDataDictionary<OuterClass>());
html.ViewData.TemplateInfo.HtmlFieldPrefix = "prefix";
// Act & Assert
Assert.Equal("prefix_IntValue", html.IdFor(m => m.IntValue).ToHtmlString());
Assert.Equal("prefix_Inner_StringValue", html.IdFor(m => m.Inner.StringValue).ToHtmlString());
Assert.Equal("prefix.IntValue", html.NameFor(m => m.IntValue).ToHtmlString());
Assert.Equal("prefix.Inner.StringValue", html.NameFor(m => m.Inner.StringValue).ToHtmlString());
}
private sealed class OuterClass
{
public InnerClass Inner { get; set; }
public int IntValue { get; set; }
}
private sealed class InnerClass
{
public string StringValue { get; set; }
}
}
}

View File

@@ -0,0 +1,86 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.IO;
using Xunit;
namespace System.Web.Mvc.Html.Test
{
public class PartialExtensionsTest
{
[Fact]
public void PartialWithViewName()
{
// Arrange
RenderPartialExtensionsTest.SpyHtmlHelper helper = RenderPartialExtensionsTest.SpyHtmlHelper.Create();
// Act
MvcHtmlString result = helper.Partial("partial-view");
// Assert
Assert.Equal("partial-view", helper.RenderPartialInternal_PartialViewName);
Assert.Same(helper.ViewData, helper.RenderPartialInternal_ViewData);
Assert.Null(helper.RenderPartialInternal_Model);
Assert.IsType<StringWriter>(helper.RenderPartialInternal_Writer);
Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);
Assert.Equal("This is the result of the view", result.ToHtmlString());
}
[Fact]
public void PartialWithViewNameAndViewData()
{
// Arrange
RenderPartialExtensionsTest.SpyHtmlHelper helper = RenderPartialExtensionsTest.SpyHtmlHelper.Create();
ViewDataDictionary viewData = new ViewDataDictionary();
// Act
MvcHtmlString result = helper.Partial("partial-view", viewData);
// Assert
Assert.Equal("partial-view", helper.RenderPartialInternal_PartialViewName);
Assert.Same(viewData, helper.RenderPartialInternal_ViewData);
Assert.Null(helper.RenderPartialInternal_Model);
Assert.IsType<StringWriter>(helper.RenderPartialInternal_Writer);
Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);
Assert.Equal("This is the result of the view", result.ToHtmlString());
}
[Fact]
public void PartialWithViewNameAndModel()
{
// Arrange
RenderPartialExtensionsTest.SpyHtmlHelper helper = RenderPartialExtensionsTest.SpyHtmlHelper.Create();
object model = new object();
// Act
MvcHtmlString result = helper.Partial("partial-view", model);
// Assert
Assert.Equal("partial-view", helper.RenderPartialInternal_PartialViewName);
Assert.Same(helper.ViewData, helper.RenderPartialInternal_ViewData);
Assert.Same(model, helper.RenderPartialInternal_Model);
Assert.IsType<StringWriter>(helper.RenderPartialInternal_Writer);
Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);
Assert.Equal("This is the result of the view", result.ToHtmlString());
}
[Fact]
public void PartialWithViewNameAndModelAndViewData()
{
// Arrange
RenderPartialExtensionsTest.SpyHtmlHelper helper = RenderPartialExtensionsTest.SpyHtmlHelper.Create();
object model = new object();
ViewDataDictionary viewData = new ViewDataDictionary();
// Act
MvcHtmlString result = helper.Partial("partial-view", model, viewData);
// Assert
Assert.Equal("partial-view", helper.RenderPartialInternal_PartialViewName);
Assert.Same(viewData, helper.RenderPartialInternal_ViewData);
Assert.Same(model, helper.RenderPartialInternal_Model);
Assert.IsType<StringWriter>(helper.RenderPartialInternal_Writer);
Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);
Assert.Equal("This is the result of the view", result.ToHtmlString());
}
}
}

View File

@@ -0,0 +1,124 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.IO;
using Moq;
using Xunit;
namespace System.Web.Mvc.Html.Test
{
public class RenderPartialExtensionsTest
{
[Fact]
public void RenderPartialWithViewName()
{
// Arrange
SpyHtmlHelper helper = SpyHtmlHelper.Create();
// Act
helper.RenderPartial("partial-view");
// Assert
Assert.Equal("partial-view", helper.RenderPartialInternal_PartialViewName);
Assert.Same(helper.ViewData, helper.RenderPartialInternal_ViewData);
Assert.Null(helper.RenderPartialInternal_Model);
Assert.Same(helper.ViewContext.Writer, helper.RenderPartialInternal_Writer);
Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);
}
[Fact]
public void RenderPartialWithViewNameAndViewData()
{
// Arrange
SpyHtmlHelper helper = SpyHtmlHelper.Create();
ViewDataDictionary viewData = new ViewDataDictionary();
// Act
helper.RenderPartial("partial-view", viewData);
// Assert
Assert.Equal("partial-view", helper.RenderPartialInternal_PartialViewName);
Assert.Same(viewData, helper.RenderPartialInternal_ViewData);
Assert.Null(helper.RenderPartialInternal_Model);
Assert.Same(helper.ViewContext.Writer, helper.RenderPartialInternal_Writer);
Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);
}
[Fact]
public void RenderPartialWithViewNameAndModel()
{
// Arrange
SpyHtmlHelper helper = SpyHtmlHelper.Create();
object model = new object();
// Act
helper.RenderPartial("partial-view", model);
// Assert
Assert.Equal("partial-view", helper.RenderPartialInternal_PartialViewName);
Assert.Same(helper.ViewData, helper.RenderPartialInternal_ViewData);
Assert.Same(model, helper.RenderPartialInternal_Model);
Assert.Same(helper.ViewContext.Writer, helper.RenderPartialInternal_Writer);
Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);
}
[Fact]
public void RenderPartialWithViewNameAndModelAndViewData()
{
// Arrange
SpyHtmlHelper helper = SpyHtmlHelper.Create();
object model = new object();
ViewDataDictionary viewData = new ViewDataDictionary();
// Act
helper.RenderPartial("partial-view", model, viewData);
// Assert
Assert.Equal("partial-view", helper.RenderPartialInternal_PartialViewName);
Assert.Same(viewData, helper.RenderPartialInternal_ViewData);
Assert.Same(model, helper.RenderPartialInternal_Model);
Assert.Same(helper.ViewContext.Writer, helper.RenderPartialInternal_Writer);
Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);
}
internal class SpyHtmlHelper : HtmlHelper
{
public string RenderPartialInternal_PartialViewName;
public ViewDataDictionary RenderPartialInternal_ViewData;
public object RenderPartialInternal_Model;
public TextWriter RenderPartialInternal_Writer;
public ViewEngineCollection RenderPartialInternal_ViewEngineCollection;
SpyHtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)
: base(viewContext, viewDataContainer)
{
}
public static SpyHtmlHelper Create()
{
ViewDataDictionary viewData = new ViewDataDictionary();
Mock<ViewContext> mockViewContext = new Mock<ViewContext>() { DefaultValue = DefaultValue.Mock };
mockViewContext.Setup(c => c.HttpContext.Response.Output).Throws(new Exception("Response.Output should never be called."));
mockViewContext.Setup(c => c.ViewData).Returns(viewData);
mockViewContext.Setup(c => c.Writer).Returns(new StringWriter());
Mock<IViewDataContainer> container = new Mock<IViewDataContainer>();
container.Setup(c => c.ViewData).Returns(viewData);
return new SpyHtmlHelper(mockViewContext.Object, container.Object);
}
internal override void RenderPartialInternal(string partialViewName, ViewDataDictionary viewData, object model,
TextWriter writer, ViewEngineCollection viewEngineCollection)
{
RenderPartialInternal_PartialViewName = partialViewName;
RenderPartialInternal_ViewData = viewData;
RenderPartialInternal_Model = model;
RenderPartialInternal_Writer = writer;
RenderPartialInternal_ViewEngineCollection = viewEngineCollection;
writer.Write("This is the result of the view");
}
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,166 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Web.Mvc.Test;
using Microsoft.Web.UnitTestUtil;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Mvc.Html.Test
{
public class ValueExtensionsTest
{
// Value
[Fact]
public void ValueWithNullNameThrows()
{
// Arrange
HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetValueViewData());
// Act & Assert
Assert.ThrowsArgumentNull(
() => helper.Value(name: null),
"name"
);
}
[Fact]
public void ValueGetsValueFromViewData()
{
// Arrange
HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetValueViewData());
// Act
MvcHtmlString html = helper.Value("foo");
// Assert
Assert.Equal("ViewDataFoo", html.ToHtmlString());
}
// ValueFor
[Fact]
public void ValueForWithNullExpressionThrows()
{
// Arrange
HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetValueViewData());
// Act & Assert
Assert.ThrowsArgumentNull(
() => helper.ValueFor<FooBarModel, object>(expression: null),
"expression"
);
}
[Fact]
public void ValueForGetsExpressionValueFromViewDataModel()
{
// Arrange
HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetValueViewData());
// Act
MvcHtmlString html = helper.ValueFor(m => m.foo);
// Assert
Assert.Equal("ViewItemFoo", html.ToHtmlString());
}
// All Value Helpers including ValueForModel
[Fact]
public void ValueHelpersWithErrorsGetValueFromModelState()
{
// Arrange
ViewDataDictionary<FooBarModel> viewDataWithErrors = new ViewDataDictionary<FooBarModel> { { "foo", "ViewDataFoo" } };
viewDataWithErrors.Model = new FooBarModel() { foo = "ViewItemFoo", bar = "ViewItemBar" };
viewDataWithErrors.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";
ModelState modelStateFoo = new ModelState();
modelStateFoo.Value = HtmlHelperTest.GetValueProviderResult(new string[] { "AttemptedValueFoo" }, "AttemptedValueFoo");
viewDataWithErrors.ModelState["FieldPrefix.foo"] = modelStateFoo;
ModelState modelStateFooBar = new ModelState();
modelStateFooBar.Value = HtmlHelperTest.GetValueProviderResult(new string[] { "AttemptedValueFooBar" }, "AttemptedValueFooBar");
viewDataWithErrors.ModelState["FieldPrefix"] = modelStateFooBar;
HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(viewDataWithErrors);
// Act & Assert
Assert.Equal("AttemptedValueFoo", helper.Value("foo").ToHtmlString());
Assert.Equal("AttemptedValueFoo", helper.ValueFor(m => m.foo).ToHtmlString());
Assert.Equal("AttemptedValueFooBar", helper.ValueForModel().ToHtmlString());
}
[Fact]
public void ValueHelpersWithEmptyNameConvertModelValueUsingCurrentCulture()
{
// Arrange
HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetValueViewData());
string expectedModelValue = "{ foo = ViewItemFoo, bar = 1900/01/01 12:00:00 AM }";
// Act & Assert
using (HtmlHelperTest.ReplaceCulture("en-ZA", "en-US"))
{
Assert.Equal(expectedModelValue, helper.Value(name: String.Empty).ToHtmlString());
Assert.Equal(expectedModelValue, helper.ValueFor(m => m).ToHtmlString());
Assert.Equal(expectedModelValue, helper.ValueForModel().ToHtmlString());
}
}
[Fact]
public void ValueHelpersFormatValue()
{
// Arrange
HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetValueViewData());
string expectedModelValue = "-{ foo = ViewItemFoo, bar = 1900/01/01 12:00:00 AM }-";
string expectedBarValue = "-1900/01/01 12:00:00 AM-";
// Act & Assert
using (HtmlHelperTest.ReplaceCulture("en-ZA", "en-US"))
{
Assert.Equal(expectedModelValue, helper.ValueForModel("-{0}-").ToHtmlString());
Assert.Equal(expectedBarValue, helper.Value("bar", "-{0}-").ToHtmlString());
Assert.Equal(expectedBarValue, helper.ValueFor(m => m.bar, "-{0}-").ToHtmlString());
}
}
[Fact]
public void ValueHelpersEncodeValue()
{
// Arrange
ViewDataDictionary<FooBarModel> viewData = new ViewDataDictionary<FooBarModel> { { "foo", @"ViewDataFoo <"">" } };
viewData.Model = new FooBarModel { foo = @"ViewItemFoo <"">" };
ModelState modelStateFoo = new ModelState();
modelStateFoo.Value = HtmlHelperTest.GetValueProviderResult(new string[] { @"AttemptedValueBar <"">" }, @"AttemptedValueBar <"">");
viewData.ModelState["bar"] = modelStateFoo;
HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(viewData);
// Act & Assert
Assert.Equal("&lt;{ foo = ViewItemFoo &lt;&quot;>, bar = (null) }", helper.ValueForModel("<{0}").ToHtmlString());
Assert.Equal("&lt;ViewDataFoo &lt;&quot;>", helper.Value("foo", "<{0}").ToHtmlString());
Assert.Equal("&lt;ViewItemFoo &lt;&quot;>", helper.ValueFor(m => m.foo, "<{0}").ToHtmlString());
Assert.Equal("AttemptedValueBar &lt;&quot;>", helper.ValueFor(m => m.bar).ToHtmlString());
}
private sealed class FooBarModel
{
public string foo { get; set; }
public object bar { get; set; }
public override string ToString()
{
return String.Format("{{ foo = {0}, bar = {1} }}", foo ?? "(null)", bar ?? "(null)");
}
}
private static ViewDataDictionary<FooBarModel> GetValueViewData()
{
ViewDataDictionary<FooBarModel> viewData = new ViewDataDictionary<FooBarModel> { { "foo", "ViewDataFoo" } };
viewData.Model = new FooBarModel { foo = "ViewItemFoo", bar = new DateTime(1900, 1, 1, 0, 0, 0) };
return viewData;
}
}
}