Make tests resilient to Localization (#5011)

This commit is contained in:
Ryan Brandenburg 2016-07-14 09:28:01 -07:00 committed by GitHub
parent 95796744c1
commit 310ab25347
37 changed files with 352 additions and 494 deletions

View File

@ -104,7 +104,9 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
{ {
if (contentType.Type == "*" || contentType.SubType == "*") if (contentType.Type == "*" || contentType.SubType == "*")
{ {
throw new ArgumentException(string.Format(Resources.FormatterMappings_NotValidMediaType, contentType)); throw new ArgumentException(
string.Format(Resources.FormatterMappings_NotValidMediaType, contentType),
nameof(contentType));
} }
} }
@ -119,7 +121,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
{ {
if (format == ".") if (format == ".")
{ {
throw new ArgumentException(string.Format(Resources.Format_NotValid, format)); throw new ArgumentException(string.Format(Resources.Format_NotValid, format), nameof(format));
} }
format = format.Substring(1); format = format.Substring(1);

View File

@ -68,12 +68,12 @@ namespace System.Net.Http
/// <summary> /// <summary>
/// HTTP X-Requested-With header field name /// HTTP X-Requested-With header field name
/// </summary> /// </summary>
public const string HttpRequestedWithHeader = @"x-requested-with"; public const string HttpRequestedWithHeader = "x-requested-with";
/// <summary> /// <summary>
/// HTTP X-Requested-With header field value /// HTTP X-Requested-With header field value
/// </summary> /// </summary>
public const string HttpRequestedWithHeaderValue = @"XMLHttpRequest"; public const string HttpRequestedWithHeaderValue = "XMLHttpRequest";
/// <summary> /// <summary>
/// HTTP Host header field name /// HTTP Host header field name

View File

@ -1,7 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using Microsoft.AspNetCore.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Mvc.Filters namespace Microsoft.AspNetCore.Mvc.Filters
@ -42,16 +42,13 @@ namespace Microsoft.AspNetCore.Mvc.Filters
// Arrange // Arrange
var collection = new FilterCollection(); var collection = new FilterCollection();
var expectedMessage = var expectedMessage = $"The type '{typeof(NonFilter).FullName}' must derive from " + $"'{typeof(IFilterMetadata).FullName}'.";
$"The type '{typeof(NonFilter).FullName}' must derive from " +
$"'{typeof(IFilterMetadata).FullName}'." + Environment.NewLine +
"Parameter name: filterType";
// Act & Assert // Act & Assert
var ex = Assert.Throws<ArgumentException>(() => { collection.Add(typeof(NonFilter)); }); ExceptionAssert.ThrowsArgument(
() => collection.Add(typeof(NonFilter)),
// Assert "filterType",
Assert.Equal(expectedMessage, ex.Message); expectedMessage);
} }
[Fact] [Fact]
@ -88,16 +85,13 @@ namespace Microsoft.AspNetCore.Mvc.Filters
// Arrange // Arrange
var collection = new FilterCollection(); var collection = new FilterCollection();
var expectedMessage = var expectedMessage = $"The type '{typeof(NonFilter).FullName}' must derive from '{typeof(IFilterMetadata).FullName}'.";
$"The type '{typeof(NonFilter).FullName}' must derive from " +
$"'{typeof(IFilterMetadata).FullName}'." + Environment.NewLine +
"Parameter name: filterType";
// Act & Assert // Act & Assert
var ex = Assert.Throws<ArgumentException>(() => { collection.AddService(typeof(NonFilter)); }); ExceptionAssert.ThrowsArgument(
() => { collection.AddService(typeof(NonFilter)); },
// Assert "filterType",
Assert.Equal(expectedMessage, ex.Message); expectedMessage);
} }
private class MyFilter : IFilterMetadata, IOrderedFilter private class MyFilter : IFilterMetadata, IOrderedFilter

View File

@ -3,11 +3,10 @@
using System; using System;
using Microsoft.AspNetCore.Mvc.TestCommon; using Microsoft.AspNetCore.Mvc.TestCommon;
using Microsoft.Extensions.Primitives; using Microsoft.AspNetCore.Testing;
using Microsoft.Net.Http.Headers; using Microsoft.Net.Http.Headers;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Mvc.Formatters namespace Microsoft.AspNetCore.Mvc.Formatters
{ {
public class FormatterMappingsTest public class FormatterMappingsTest
@ -49,14 +48,16 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
// Arrange // Arrange
var options = new FormatterMappings(); var options = new FormatterMappings();
var format = "."; var format = ".";
var expected = string.Format(@"The format provided is invalid '{0}'. A format must be a non-empty file-" + var expected = $"The format provided is invalid '{format}'. A format must be a non-empty file-" +
"extension, optionally prefixed with a '.' character.", format); "extension, optionally prefixed with a '.' character.";
// Act and assert // Act and assert
var exception = Assert.Throws<ArgumentException>(() => options.SetMediaTypeMappingForFormat( ExceptionAssert.ThrowsArgument(
format, () => options.SetMediaTypeMappingForFormat(
MediaTypeHeaderValue.Parse("application/xml"))); format,
Assert.Equal(expected, exception.Message); MediaTypeHeaderValue.Parse("application/xml")),
"format",
expected);
} }
[Fact] [Fact]
@ -65,16 +66,15 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
// Arrange // Arrange
var options = new FormatterMappings(); var options = new FormatterMappings();
var format = ""; var format = "";
var expected = "Value cannot be null or empty." + Environment.NewLine + "Parameter name: format";
// Act and assert // Act and Assert
var exception = Assert.Throws<ArgumentException>(() => options.SetMediaTypeMappingForFormat( ExceptionAssert.ThrowsArgumentNullOrEmpty(
format, () => options.SetMediaTypeMappingForFormat(
MediaTypeHeaderValue.Parse("application/xml"))); format,
Assert.Equal(expected, exception.Message); MediaTypeHeaderValue.Parse("application/xml")),
"format");
} }
[Theory] [Theory]
[InlineData("application/*")] [InlineData("application/*")]
[InlineData("*/json")] [InlineData("*/json")]
@ -83,14 +83,16 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
{ {
// Arrange // Arrange
var options = new FormatterMappings(); var options = new FormatterMappings();
var expected = string.Format(@"The media type ""{0}"" is not valid. MediaTypes containing wildcards (*) " + var expected = $@"The media type ""{format}"" is not valid. MediaTypes containing wildcards (*) " +
"are not allowed in formatter mappings.", format); "are not allowed in formatter mappings.";
// Act and assert // Act and assert
var exception = Assert.Throws<ArgumentException>(() => options.SetMediaTypeMappingForFormat( ExceptionAssert.ThrowsArgument(
"star", () => options.SetMediaTypeMappingForFormat(
MediaTypeHeaderValue.Parse(format))); "star",
Assert.Equal(expected, exception.Message); MediaTypeHeaderValue.Parse(format)),
"contentType",
expected);
} }
[Theory] [Theory]

View File

@ -14,6 +14,7 @@ using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Logging.Testing;
@ -28,10 +29,12 @@ namespace Microsoft.AspNetCore.Mvc.Internal
public class AttributeRoutingTest public class AttributeRoutingTest
{ {
[Fact] [Fact]
[ReplaceCulture]
public async Task AttributeRouting_SyntaxErrorInTemplate() public async Task AttributeRouting_SyntaxErrorInTemplate()
{ {
// Arrange // Arrange
var action = CreateAction("InvalidTemplate", "{a/dkfk}"); var value = "a/dkfk";
var action = CreateAction("InvalidTemplate", "{" + value + "}");
var expectedMessage = var expectedMessage =
"The following errors occurred with attribute routing information:" + Environment.NewLine + "The following errors occurred with attribute routing information:" + Environment.NewLine +
@ -46,12 +49,10 @@ namespace Microsoft.AspNetCore.Mvc.Internal
var services = CreateServices(action); var services = CreateServices(action);
var route = AttributeRouting.CreateAttributeMegaRoute(services); var route = AttributeRouting.CreateAttributeMegaRoute(services);
var routeContext = new RouteContext(new DefaultHttpContext());
// Act & Assert // Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => route.RouteAsync(routeContext));
{
await route.RouteAsync(new RouteContext(new DefaultHttpContext()));
});
Assert.Equal(expectedMessage, ex.Message); Assert.Equal(expectedMessage, ex.Message);
} }

View File

@ -2469,9 +2469,7 @@ namespace Microsoft.AspNetCore.Mvc.Internal
// Act & Assert // Act & Assert
await ExceptionAssert.ThrowsAsync<InvalidOperationException>( await ExceptionAssert.ThrowsAsync<InvalidOperationException>(
() => invoker.InvokeAsync(), () => invoker.InvokeAsync(),
"Cannot return null from an action method with a return type of '" $"Cannot return null from an action method with a return type of '{resultType}'.");
+ resultType
+ "'.");
} }
[Fact] [Fact]

View File

@ -2,7 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Threading.Tasks; using Microsoft.AspNetCore.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Mvc.ModelBinding namespace Microsoft.AspNetCore.Mvc.ModelBinding
@ -15,8 +15,7 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding
// Arrange // Arrange
var expected = var expected =
"The provided binding source 'Test Source' is a greedy data source. " + "The provided binding source 'Test Source' is a greedy data source. " +
"'BindingSourceValueProvider' does not support greedy data sources." + Environment.NewLine + $"'{nameof(BindingSourceValueProvider)}' does not support greedy data sources.";
"Parameter name: bindingSource";
var bindingSource = new BindingSource( var bindingSource = new BindingSource(
"Test", "Test",
@ -25,29 +24,28 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding
isFromRequest: true); isFromRequest: true);
// Act & Assert // Act & Assert
var exception = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
() => new TestableBindingSourceValueProvider(bindingSource)); () => new TestableBindingSourceValueProvider(bindingSource),
Assert.Equal(expected, exception.Message); "bindingSource",
expected);
} }
[Fact] [Fact]
public void BindingSourceValueProvider_ThrowsOnCompositeSource() public void BindingSourceValueProvider_ThrowsOnCompositeSource()
{ {
// Arrange // Arrange
var expected = var expected = $"The provided binding source 'Test Source' is a composite. '{nameof(BindingSourceValueProvider)}' " +
"The provided binding source 'Test Source' is a composite. " + "requires that the source must represent a single type of input.";
"'BindingSourceValueProvider' requires that the source must represent a single type of input." +
Environment.NewLine +
"Parameter name: bindingSource";
var bindingSource = CompositeBindingSource.Create( var bindingSource = CompositeBindingSource.Create(
bindingSources: new BindingSource[] { BindingSource.Query, BindingSource.Form }, bindingSources: new BindingSource[] { BindingSource.Query, BindingSource.Form },
displayName: "Test Source"); displayName: "Test Source");
// Act & Assert // Act & Assert
var exception = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
() => new TestableBindingSourceValueProvider(bindingSource)); () => new TestableBindingSourceValueProvider(bindingSource),
Assert.Equal(expected, exception.Message); "bindingSource",
expected);
} }
[Fact] [Fact]

View File

@ -1,7 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using Microsoft.AspNetCore.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Mvc.ModelBinding namespace Microsoft.AspNetCore.Mvc.ModelBinding
@ -12,20 +12,18 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding
public void BindingSource_CanAcceptDataFrom_ThrowsOnComposite() public void BindingSource_CanAcceptDataFrom_ThrowsOnComposite()
{ {
// Arrange // Arrange
var expected = var expected = "The provided binding source 'Test Source' is a composite. " +
"The provided binding source 'Test Source' is a composite. " + $"'{nameof(BindingSource.CanAcceptDataFrom)}' requires that the source must represent a single type of input.";
"'CanAcceptDataFrom' requires that the source must represent a single type of input." +
Environment.NewLine +
"Parameter name: bindingSource";
var bindingSource = CompositeBindingSource.Create( var bindingSource = CompositeBindingSource.Create(
bindingSources: new BindingSource[] { BindingSource.Query, BindingSource.Form }, bindingSources: new BindingSource[] { BindingSource.Query, BindingSource.Form },
displayName: "Test Source"); displayName: "Test Source");
// Act & Assert // Act & Assert
var exception = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
() => BindingSource.Query.CanAcceptDataFrom(bindingSource)); () => BindingSource.Query.CanAcceptDataFrom(bindingSource),
Assert.Equal(expected, exception.Message); "bindingSource",
expected);
} }
[Fact] [Fact]

View File

@ -1,7 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using Microsoft.AspNetCore.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Mvc.ModelBinding namespace Microsoft.AspNetCore.Mvc.ModelBinding
@ -12,12 +12,6 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding
public void CompositeBindingSourceTest_CanAcceptDataFrom_ThrowsOnComposite() public void CompositeBindingSourceTest_CanAcceptDataFrom_ThrowsOnComposite()
{ {
// Arrange // Arrange
var expected =
"The provided binding source 'Test Source2' is a composite. " +
"'CanAcceptDataFrom' requires that the source must represent a single type of input." +
Environment.NewLine +
"Parameter name: bindingSource";
var composite1 = CompositeBindingSource.Create( var composite1 = CompositeBindingSource.Create(
bindingSources: new BindingSource[] { BindingSource.Query, BindingSource.Form }, bindingSources: new BindingSource[] { BindingSource.Query, BindingSource.Form },
displayName: "Test Source1"); displayName: "Test Source1");
@ -26,11 +20,15 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding
bindingSources: new BindingSource[] { BindingSource.Query, BindingSource.Form }, bindingSources: new BindingSource[] { BindingSource.Query, BindingSource.Form },
displayName: "Test Source2"); displayName: "Test Source2");
var expected = "The provided binding source 'Test Source2' is a composite. " +
$"'{nameof(composite1.CanAcceptDataFrom)}' requires that the source must represent a single type of input.";
// Act & Assert // Act & Assert
var exception = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
() => composite1.CanAcceptDataFrom(composite2)); () => composite1.CanAcceptDataFrom(composite2),
Assert.Equal(expected, exception.Message); "bindingSource",
expected);
} }
[Fact] [Fact]

View File

@ -15,6 +15,7 @@ using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.AspNetCore.Mvc.ModelBinding.Internal; using Microsoft.AspNetCore.Mvc.ModelBinding.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Testing;
using Moq; using Moq;
using Xunit; using Xunit;
@ -49,8 +50,6 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding
public async Task TryUpdateModel_ReturnsFalse_IfModelValidationFails() public async Task TryUpdateModel_ReturnsFalse_IfModelValidationFails()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19
var expectedMessage = PlatformNormalizer.NormalizeContent("The MyProperty field is required.");
var binderProviders = new IModelBinderProvider[] var binderProviders = new IModelBinderProvider[]
{ {
new SimpleTypeModelBinderProvider(), new SimpleTypeModelBinderProvider(),
@ -86,7 +85,7 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding
// Assert // Assert
Assert.False(result); Assert.False(result);
var error = Assert.Single(modelState["MyProperty"].Errors); var error = Assert.Single(modelState["MyProperty"].Errors);
Assert.Equal(expectedMessage, error.ErrorMessage); Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("MyProperty"), error.ErrorMessage);
} }
[Fact] [Fact]
@ -613,8 +612,12 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding
var model = new MyModel(); var model = new MyModel();
Func<ModelMetadata, bool> propertyFilter = (m) => true; Func<ModelMetadata, bool> propertyFilter = (m) => true;
var modelName = model.GetType().FullName;
var userName = typeof(User).FullName;
var expectedMessage = $"The model's runtime type '{modelName}' is not assignable to the type '{userName}'.";
// Act & Assert // Act & Assert
var exception = await Assert.ThrowsAsync<ArgumentException>( var exception = await ExceptionAssert.ThrowsArgumentAsync(
() => ModelBindingHelper.TryUpdateModelAsync( () => ModelBindingHelper.TryUpdateModelAsync(
model, model,
typeof(User), typeof(User),
@ -624,14 +627,9 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding
GetModelBinderFactory(binder.Object), GetModelBinderFactory(binder.Object),
Mock.Of<IValueProvider>(), Mock.Of<IValueProvider>(),
new Mock<IObjectModelValidator>(MockBehavior.Strict).Object, new Mock<IObjectModelValidator>(MockBehavior.Strict).Object,
propertyFilter)); propertyFilter),
"modelType",
var expectedMessage = string.Format("The model's runtime type '{0}' is not assignable to the type '{1}'." + expectedMessage);
Environment.NewLine +
"Parameter name: modelType",
model.GetType().FullName,
typeof(User).FullName);
Assert.Equal(expectedMessage, exception.Message);
} }
[Theory] [Theory]

View File

@ -2,8 +2,9 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Linq;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Mvc.Formatters.Xml.Internal namespace Microsoft.AspNetCore.Mvc.Formatters.Xml.Internal
@ -80,16 +81,14 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml.Internal
public void ThrowsArugmentExceptionFor_ConcreteEnumerableOfT(Type declaredType) public void ThrowsArugmentExceptionFor_ConcreteEnumerableOfT(Type declaredType)
{ {
// Arrange // Arrange
var expectedMessage = var expectedMessage = "The type must be an interface and must be or derive from 'IEnumerable`1'.";
"The type must be an interface and must be or derive from 'IEnumerable`1'." +
$"{Environment.NewLine}Parameter name: sourceEnumerableOfT";
// Act and Assert // Act and Assert
var ex = Assert.Throws<ArgumentException>(() => new EnumerableWrapperProvider( ExceptionAssert.ThrowsArgument(() => new EnumerableWrapperProvider(
declaredType, declaredType,
elementWrapperProvider: null)); elementWrapperProvider: null),
"sourceEnumerableOfT",
Assert.Equal(expectedMessage, ex.Message); expectedMessage);
} }
} }
} }

View File

@ -1,7 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using Microsoft.AspNetCore.Testing;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Mvc.Formatters.Xml.Internal namespace Microsoft.AspNetCore.Mvc.Formatters.Xml.Internal
@ -43,13 +43,15 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml.Internal
// Arrange // Arrange
var wrapperProvider = new SerializableErrorWrapperProvider(); var wrapperProvider = new SerializableErrorWrapperProvider();
var person = new Person() { Id = 10, Name = "John" }; var person = new Person() { Id = 10, Name = "John" };
var expectedMessage = string.Format("The object to be wrapped must be of type '{0}'" +
$" but was of type 'Person'.{Environment.NewLine}Parameter name: original", var expectedMessage = "The object to be wrapped must be of type " +
typeof(SerializableErrorWrapper).Name); $"'{nameof(SerializableErrorWrapper)}' but was of type 'Person'.";
// Act and Assert // Act and Assert
var exception = Assert.Throws<ArgumentException>(() => wrapperProvider.Wrap(person)); ExceptionAssert.ThrowsArgument(
Assert.Equal(expectedMessage, exception.Message); () => wrapperProvider.Wrap(person),
"original",
expectedMessage);
} }
} }
} }

View File

@ -10,7 +10,6 @@ using System.Threading.Tasks;
using System.Xml; using System.Xml;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing;
using Microsoft.AspNetCore.Testing.xunit; using Microsoft.AspNetCore.Testing.xunit;
using Moq; using Moq;
@ -53,9 +52,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
public TestLevelOne TestOne { get; set; } public TestLevelOne TestOne { get; set; }
} }
[ConditionalTheory]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
[InlineData("application/xml", true)] [InlineData("application/xml", true)]
[InlineData("application/*", false)] [InlineData("application/*", false)]
[InlineData("*/*", false)] [InlineData("*/*", false)]
@ -90,9 +86,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
Assert.Equal(expectedCanRead, result); Assert.Equal(expectedCanRead, result);
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public void XmlDataContractSerializer_CachesSerializerForType() public void XmlDataContractSerializer_CachesSerializerForType()
{ {
// Arrange // Arrange
@ -136,9 +129,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
Assert.True(formatter.SupportedEncodings.Any(i => i.WebName == "utf-16")); Assert.True(formatter.SupportedEncodings.Any(i => i.WebName == "utf-16"));
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_ReadsSimpleTypes() public async Task ReadAsync_ReadsSimpleTypes()
{ {
// Arrange // Arrange
@ -165,9 +155,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
Assert.Equal(expectedString, model.sampleString); Assert.Equal(expectedString, model.sampleString);
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_ReadsComplexTypes() public async Task ReadAsync_ReadsComplexTypes()
{ {
// Arrange // Arrange
@ -197,9 +184,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
Assert.Equal(expectedString, model.TestOne.sampleString); Assert.Equal(expectedString, model.TestOne.sampleString);
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_ReadsWhenMaxDepthIsModified() public async Task ReadAsync_ReadsWhenMaxDepthIsModified()
{ {
// Arrange // Arrange
@ -223,9 +207,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedInt, model.SampleInt);
} }
[ConditionalFact]
[FrameworkSkipCondition(RuntimeFrameworks.Mono,
SkipReason = "Mono issue - https://github.com/aspnet/External/issues/18")]
public async Task ReadAsync_ThrowsOnExceededMaxDepth() public async Task ReadAsync_ThrowsOnExceededMaxDepth()
{ {
// Arrange // Arrange
@ -242,9 +223,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
await Assert.ThrowsAsync(typeof(SerializationException), async () => await formatter.ReadAsync(context)); await Assert.ThrowsAsync(typeof(SerializationException), async () => await formatter.ReadAsync(context));
} }
[ConditionalFact]
[FrameworkSkipCondition(RuntimeFrameworks.Mono,
SkipReason = "Mono issue - https://github.com/aspnet/External/issues/18")]
public async Task ReadAsync_ThrowsWhenReaderQuotasAreChanged() public async Task ReadAsync_ThrowsWhenReaderQuotasAreChanged()
{ {
// Arrange // Arrange
@ -271,9 +249,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
Assert.Throws(typeof(ArgumentException), () => formatter.MaxDepth = 0); Assert.Throws(typeof(ArgumentException), () => formatter.MaxDepth = 0);
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_VerifyStreamIsOpenAfterRead() public async Task ReadAsync_VerifyStreamIsOpenAfterRead()
{ {
// Arrange // Arrange
@ -293,17 +268,10 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
Assert.True(context.HttpContext.Request.Body.CanRead); Assert.True(context.HttpContext.Request.Body.CanRead);
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_FallsbackToUTF8_WhenCharSet_NotInContentType() public async Task ReadAsync_FallsbackToUTF8_WhenCharSet_NotInContentType()
{ {
// Arrange // Arrange
var expectedException = TestPlatformHelper.IsMono ? typeof(SerializationException) : var expectedException = typeof(XmlException);
typeof(XmlException);
var expectedMessage = TestPlatformHelper.IsMono ?
"Expected element 'TestLevelTwo' in namespace '', but found Element node 'DummyClass' in namespace ''" :
"The expected encoding 'utf-8' does not match the actual encoding 'utf-16LE'.";
var inpStart = Encoding.Unicode.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + var inpStart = Encoding.Unicode.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-16\"?>" +
"<DummyClass><SampleInt>"); "<DummyClass><SampleInt>");
byte[] inp = { 192, 193 }; byte[] inp = { 192, 193 };
@ -319,20 +287,15 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
// Act // Act
var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context)); var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context));
Assert.Equal(expectedMessage, ex.Message); Assert.Contains("utf-8", ex.Message);
Assert.Contains("utf-16LE", ex.Message);
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream() public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream()
{ {
// Arrange // Arrange
var expectedException = TestPlatformHelper.IsMono ? typeof(SerializationException) : var expectedException = typeof(XmlException);
typeof(XmlException);
var expectedMessage = TestPlatformHelper.IsMono ?
"Expected element 'TestLevelTwo' in namespace '', but found Element node 'DummyClass' in namespace ''" :
"The expected encoding 'utf-16LE' does not match the actual encoding 'utf-8'.";
var inputBytes = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + var inputBytes = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<DummyClass><SampleInt>1000</SampleInt></DummyClass>"); "<DummyClass><SampleInt>1000</SampleInt></DummyClass>");
@ -352,12 +315,10 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
// Act // Act
var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context)); var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context));
Assert.Equal(expectedMessage, ex.Message); Assert.Contains("utf-16LE", ex.Message);
Assert.Contains("utf-8", ex.Message);
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_IgnoresBOMCharacters() public async Task ReadAsync_IgnoresBOMCharacters()
{ {
// Arrange // Arrange
@ -389,9 +350,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
Assert.Equal(expectedBytes, Encoding.UTF8.GetBytes(model.SampleString)); Assert.Equal(expectedBytes, Encoding.UTF8.GetBytes(model.SampleString));
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_AcceptsUTF16Characters() public async Task ReadAsync_AcceptsUTF16Characters()
{ {
// Arrange // Arrange
@ -429,9 +387,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
Assert.Equal(expectedString, model.sampleString); Assert.Equal(expectedString, model.sampleString);
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_ThrowsWhenNotConfiguredWithRootName() public async Task ReadAsync_ThrowsWhenNotConfiguredWithRootName()
{ {
// Arrange // Arrange
@ -450,9 +405,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
await Assert.ThrowsAsync(typeof(SerializationException), async () => await formatter.ReadAsync(context)); await Assert.ThrowsAsync(typeof(SerializationException), async () => await formatter.ReadAsync(context));
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_ReadsWhenConfiguredWithRootName() public async Task ReadAsync_ReadsWhenConfiguredWithRootName()
{ {
// Arrange // Arrange
@ -489,9 +441,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedInt, model.SampleInt);
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_ThrowsWhenNotConfiguredWithKnownTypes() public async Task ReadAsync_ThrowsWhenNotConfiguredWithKnownTypes()
{ {
// Arrange // Arrange
@ -511,9 +460,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
await Assert.ThrowsAsync(typeof(SerializationException), async () => await formatter.ReadAsync(context)); await Assert.ThrowsAsync(typeof(SerializationException), async () => await formatter.ReadAsync(context));
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ReadAsync_ReadsWhenConfiguredWithKnownTypes() public async Task ReadAsync_ReadsWhenConfiguredWithKnownTypes()
{ {
// Arrange // Arrange

View File

@ -300,15 +300,13 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
Assert.True(context.HttpContext.Request.Body.CanRead); Assert.True(context.HttpContext.Request.Body.CanRead);
} }
[ReplaceCulture]
[Fact] [Fact]
public async Task ReadAsync_FallsbackToUTF8_WhenCharSet_NotInContentType() public async Task ReadAsync_FallsbackToUTF8_WhenCharSet_NotInContentType()
{ {
// Arrange // Arrange
var expectedException = TestPlatformHelper.IsMono ? typeof(InvalidOperationException) : var expectedException = typeof(XmlException);
typeof(XmlException); var expectedMessage = "The expected encoding 'utf-8' does not match the actual encoding 'utf-16LE'.";
var expectedMessage = TestPlatformHelper.IsMono ?
"There is an error in XML document." :
"The expected encoding 'utf-8' does not match the actual encoding 'utf-16LE'.";
var inpStart = Encoding.Unicode.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + var inpStart = Encoding.Unicode.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-16\"?>" +
"<DummyClass><SampleInt>"); "<DummyClass><SampleInt>");
@ -329,14 +327,12 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
} }
[Fact] [Fact]
[ReplaceCulture]
public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream() public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream()
{ {
// Arrange // Arrange
var expectedException = TestPlatformHelper.IsMono ? typeof(InvalidOperationException) : var expectedException = typeof(XmlException);
typeof(XmlException); var expectedMessage = "The expected encoding 'utf-16LE' does not match the actual encoding 'utf-8'.";
var expectedMessage = TestPlatformHelper.IsMono ?
"There is an error in XML document." :
"The expected encoding 'utf-16LE' does not match the actual encoding 'utf-8'.";
var inputBytes = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + var inputBytes = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<DummyClass><SampleInt>1000</SampleInt></DummyClass>"); "<DummyClass><SampleInt>1000</SampleInt></DummyClass>");

View File

@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
public async Task ViewsInheritsUsingsAndInjectDirectivesFromViewStarts() public async Task ViewsInheritsUsingsAndInjectDirectivesFromViewStarts()
{ {
// Arrange // Arrange
var expected = @"Hello Person1"; var expected = "Hello Person1";
// Act // Act
var body = await Client.GetStringAsync( var body = await Client.GetStringAsync(
@ -34,7 +34,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
public async Task ViewInheritsBasePageFromViewStarts() public async Task ViewInheritsBasePageFromViewStarts()
{ {
// Arrange // Arrange
var expected = @"WriteLiteral says:layout:Write says:Write says:Hello Person2"; var expected = "WriteLiteral says:layout:Write says:Write says:Hello Person2";
// Act // Act
var body = await Client.GetStringAsync("http://localhost/Directives/ViewInheritsBasePageFromViewImports"); var body = await Client.GetStringAsync("http://localhost/Directives/ViewInheritsBasePageFromViewImports");

View File

@ -96,11 +96,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
#if GENERATE_BASELINES #if GENERATE_BASELINES
ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else #else
// Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal(expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true);
Assert.Equal(
PlatformNormalizer.NormalizeContent(expectedContent.Trim()),
responseContent,
ignoreLineEndingDifferences: true);
#endif #endif
} }
else else
@ -112,11 +108,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else #else
expectedContent = string.Format(expectedContent, forgeryToken); expectedContent = string.Format(expectedContent, forgeryToken);
// Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal(expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true);
Assert.Equal(
PlatformNormalizer.NormalizeContent(expectedContent.Trim()),
responseContent,
ignoreLineEndingDifferences: true);
#endif #endif
} }
} }
@ -164,9 +156,8 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
#if GENERATE_BASELINES #if GENERATE_BASELINES
ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else #else
// Mono issue - https://github.com/aspnet/External/issues/19
Assert.Equal( Assert.Equal(
PlatformNormalizer.NormalizeContent(expectedContent.Trim()), expectedContent.Trim(),
responseContent, responseContent,
ignoreLineEndingDifferences: true); ignoreLineEndingDifferences: true);
#endif #endif
@ -180,11 +171,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else #else
expectedContent = string.Format(expectedContent, forgeryToken); expectedContent = string.Format(expectedContent, forgeryToken);
// Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal(expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true);
Assert.Equal(
PlatformNormalizer.NormalizeContent(expectedContent.Trim()),
responseContent,
ignoreLineEndingDifferences: true);
#endif #endif
} }
} }
@ -254,11 +241,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else #else
expectedContent = string.Format(expectedContent, forgeryToken); expectedContent = string.Format(expectedContent, forgeryToken);
// Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal(expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true);
Assert.Equal(
PlatformNormalizer.NormalizeContent(expectedContent.Trim()),
responseContent,
ignoreLineEndingDifferences: true);
#endif #endif
} }
@ -502,12 +485,12 @@ Products: Music Systems, Televisions (3)";
public async Task EditorTemplateWithNoModel_RendersWithCorrectMetadata() public async Task EditorTemplateWithNoModel_RendersWithCorrectMetadata()
{ {
// Arrange // Arrange
var expected = PlatformNormalizer.NormalizeContent( var expected =
"<label class=\"control-label col-md-2\" for=\"Name\">ItemName</label>" + Environment.NewLine + "<label class=\"control-label col-md-2\" for=\"Name\">ItemName</label>" + Environment.NewLine +
"<input id=\"Name\" name=\"Name\" type=\"text\" value=\"\" />" + Environment.NewLine + Environment.NewLine + "<input id=\"Name\" name=\"Name\" type=\"text\" value=\"\" />" + Environment.NewLine + Environment.NewLine +
"<label class=\"control-label col-md-2\" for=\"Id\">ItemNo</label>" + Environment.NewLine + "<label class=\"control-label col-md-2\" for=\"Id\">ItemNo</label>" + Environment.NewLine +
"<input data-val=\"true\" data-val-required=\"The ItemNo field is required.\" id=\"Id\" name=\"Id\" type=\"text\" value=\"\" />" + "<input data-val=\"true\" data-val-required=\"The ItemNo field is required.\" id=\"Id\" name=\"Id\" type=\"text\" value=\"\" />" +
Environment.NewLine + Environment.NewLine); Environment.NewLine + Environment.NewLine;
// Act // Act
var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingSharedEditorTemplate"); var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingSharedEditorTemplate");

View File

@ -76,11 +76,7 @@ True";
var body = await Client.GetStringAsync("http://localhost/HtmlHelperOptions/OverrideAppWideDefaultsInView"); var body = await Client.GetStringAsync("http://localhost/HtmlHelperOptions/OverrideAppWideDefaultsInView");
// Assert // Assert
// Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true);
Assert.Equal(
PlatformNormalizer.NormalizeContent(expected),
body.Trim(),
ignoreLineEndingDifferences: true);
} }
} }
} }

View File

@ -16,7 +16,7 @@ using Xunit;
namespace Microsoft.AspNetCore.Mvc.FunctionalTests namespace Microsoft.AspNetCore.Mvc.FunctionalTests
{ {
public class XmlDataContractSerializerInputFormatterTest : IClassFixture<MvcTestFixture<XmlFormattersWebSite.Startup>> public class XmlDataContractSerializerInputFormatterTest : IClassFixture<MvcTestFixture<Startup>>
{ {
private readonly string errorMessageFormat = string.Format( private readonly string errorMessageFormat = string.Format(
"{{1}}:{0} does not recognize '{1}', so instead use '{2}' with '{3}' set to '{4}' for value " + "{{1}}:{0} does not recognize '{1}', so instead use '{2}' with '{3}' set to '{4}' for value " +
@ -27,16 +27,13 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
nameof(DataMemberAttribute.IsRequired), nameof(DataMemberAttribute.IsRequired),
bool.TrueString); bool.TrueString);
public XmlDataContractSerializerInputFormatterTest(MvcTestFixture<XmlFormattersWebSite.Startup> fixture) public XmlDataContractSerializerInputFormatterTest(MvcTestFixture<Startup> fixture)
{ {
Client = fixture.Client; Client = fixture.Client;
} }
public HttpClient Client { get; } public HttpClient Client { get; }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ThrowsOnInvalidInput_AndAddsToModelState() public async Task ThrowsOnInvalidInput_AndAddsToModelState()
{ {
// Arrange // Arrange
@ -56,9 +53,6 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
data); data);
} }
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task RequiredDataIsProvided_AndModelIsBound_NoValidationErrors() public async Task RequiredDataIsProvided_AndModelIsBound_NoValidationErrors()
{ {
// Arrange // Arrange
@ -85,10 +79,6 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
Assert.Empty(modelBindingInfo.ModelStateErrorMessages); Assert.Empty(modelBindingInfo.ModelStateErrorMessages);
} }
// Verifies that the model state has errors related to body model validation.
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task DataMissingForRefereneceTypeProperties_AndModelIsBound_AndHasMixedValidationErrors() public async Task DataMissingForRefereneceTypeProperties_AndModelIsBound_AndHasMixedValidationErrors()
{ {
// Arrange // Arrange

View File

@ -118,6 +118,12 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
var modelState = testContext.ModelState; var modelState = testContext.ModelState;
var priceRange = ValidationAttributeUtil.GetRangeErrorMessage(20, 100, "Price");
var categoryRequired = ValidationAttributeUtil.GetRequiredErrorMessage("Category");
var contactUsRequired = ValidationAttributeUtil.GetRequiredErrorMessage("Contact Us");
var detail2Required = ValidationAttributeUtil.GetRequiredErrorMessage("Detail2");
var detail3Required = ValidationAttributeUtil.GetRequiredErrorMessage("Detail3");
// Act // Act
var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext); var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext);
@ -127,21 +133,13 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
Assert.NotNull(boundPerson); Assert.NotNull(boundPerson);
Assert.False(modelState.IsValid); Assert.False(modelState.IsValid);
var modelStateErrors = CreateValidationDictionary(modelState); var modelStateErrors = CreateValidationDictionary(modelState);
Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["CompanyName"]); Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["CompanyName"]);
Assert.Equal("The field Price must be between 20 and 100.", modelStateErrors["Price"]); Assert.Equal(priceRange, modelStateErrors["Price"]);
// Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal(categoryRequired, modelStateErrors["Category"]);
Assert.Equal( Assert.Equal(contactUsRequired, modelStateErrors["Contact"]);
PlatformNormalizer.NormalizeContent("The Category field is required."), Assert.Equal(detail2Required, modelStateErrors["ProductDetails.Detail2"]);
modelStateErrors["Category"]); Assert.Equal(detail3Required, modelStateErrors["ProductDetails.Detail3"]);
Assert.Equal(
PlatformNormalizer.NormalizeContent("The Contact Us field is required."),
modelStateErrors["Contact"]);
Assert.Equal(
PlatformNormalizer.NormalizeContent("The Detail2 field is required."),
modelStateErrors["ProductDetails.Detail2"]);
Assert.Equal(
PlatformNormalizer.NormalizeContent("The Detail3 field is required."),
modelStateErrors["ProductDetails.Detail3"]);
} }
[Fact] [Fact]
@ -170,6 +168,8 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
var modelState = testContext.ModelState; var modelState = testContext.ModelState;
var productDetailsRequired = ValidationAttributeUtil.GetRequiredErrorMessage("ProductDetails");
// Act // Act
var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext); var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext);
@ -179,9 +179,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
Assert.NotNull(boundPerson); Assert.NotNull(boundPerson);
Assert.False(modelState.IsValid); Assert.False(modelState.IsValid);
var modelStateErrors = CreateValidationDictionary(modelState); var modelStateErrors = CreateValidationDictionary(modelState);
Assert.Equal( Assert.Equal(productDetailsRequired, modelStateErrors["ProductDetails"]);
PlatformNormalizer.NormalizeContent("The ProductDetails field is required."),
modelStateErrors["ProductDetails"]);
} }
[Fact] [Fact]
@ -287,6 +285,9 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
var modelState = testContext.ModelState; var modelState = testContext.ModelState;
var priceRange = ValidationAttributeUtil.GetRangeErrorMessage(100, 200, "Price");
var contactLength = ValidationAttributeUtil.GetStringLengthErrorMessage(null, 10, "Contact");
// Act // Act
var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext); var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext);
@ -297,10 +298,9 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
Assert.False(modelState.IsValid); Assert.False(modelState.IsValid);
var modelStateErrors = CreateValidationDictionary(modelState); var modelStateErrors = CreateValidationDictionary(modelState);
Assert.Equal(2, modelStateErrors.Count); Assert.Equal(2, modelStateErrors.Count);
Assert.Equal("The field Price must be between 100 and 200.", modelStateErrors["Price"]);
Assert.Equal( Assert.Equal(priceRange, modelStateErrors["Price"]);
"The field Contact must be a string with a maximum length of 10.", Assert.Equal(contactLength, modelStateErrors["Contact"]);
modelStateErrors["Contact"]);
} }
[Fact] [Fact]
@ -379,6 +379,8 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
var modelState = testContext.ModelState; var modelState = testContext.ModelState;
var addressRequired = ValidationAttributeUtil.GetRequiredErrorMessage("Address");
// Act // Act
var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext); var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext);
@ -390,8 +392,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
Assert.Equal("CustomParameter.Address", key); Assert.Equal("CustomParameter.Address", key);
Assert.False(modelState.IsValid); Assert.False(modelState.IsValid);
var error = Assert.Single(modelState[key].Errors); var error = Assert.Single(modelState[key].Errors);
// Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal(addressRequired, error.ErrorMessage);
Assert.Equal(PlatformNormalizer.NormalizeContent("The Address field is required."), error.ErrorMessage);
} }
[Fact] [Fact]
@ -623,6 +624,8 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
var httpContext = testContext.HttpContext; var httpContext = testContext.HttpContext;
var modelState = testContext.ModelState; var modelState = testContext.ModelState;
var streetRequired = ValidationAttributeUtil.GetRequiredErrorMessage("Street");
// Act // Act
var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext); var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext);
@ -637,8 +640,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
var street = entry.Value; var street = entry.Value;
Assert.Equal(ModelValidationState.Invalid, street.ValidationState); Assert.Equal(ModelValidationState.Invalid, street.ValidationState);
var error = Assert.Single(street.Errors); var error = Assert.Single(street.Errors);
// Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal(streetRequired, error.ErrorMessage);
Assert.Equal(PlatformNormalizer.NormalizeContent("The Street field is required."), error.ErrorMessage);
} }
private class Person3 private class Person3

View File

@ -675,7 +675,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
Assert.Equal("Addresses[Key1].Street", kvp.Key); Assert.Equal("Addresses[Key1].Street", kvp.Key);
var entry = kvp.Value; var entry = kvp.Value;
var error = Assert.Single(entry.Errors); var error = Assert.Single(entry.Errors);
Assert.Equal("The field Street must be a string with a maximum length of 3.", error.ErrorMessage); Assert.Equal(ValidationAttributeUtil.GetStringLengthErrorMessage(null, 3, "Street"), error.ErrorMessage);
} }
[Theory] [Theory]
@ -714,7 +714,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
var entry = Assert.Single(modelState).Value; var entry = Assert.Single(modelState).Value;
var error = Assert.Single(entry.Errors); var error = Assert.Single(entry.Errors);
Assert.Equal("The field Street must be a string with a maximum length of 3.", error.ErrorMessage); Assert.Equal(ValidationAttributeUtil.GetStringLengthErrorMessage(null, 3, "Street"), error.ErrorMessage);
} }
// parameter type, form content, expected type // parameter type, form content, expected type

View File

@ -63,8 +63,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
var key = Assert.Single(modelState.Keys); var key = Assert.Single(modelState.Keys);
Assert.Equal("CustomParameter.Address.Header", key); Assert.Equal("CustomParameter.Address.Header", key);
var error = Assert.Single(modelState[key].Errors); var error = Assert.Single(modelState[key].Errors);
// Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Street"), error.ErrorMessage);
Assert.Equal(PlatformNormalizer.NormalizeContent("The Street field is required."), error.ErrorMessage);
} }
[Fact] [Fact]

View File

@ -76,6 +76,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
} }
[Fact] [Fact]
[ReplaceCulture]
public void TryValidateModel_CollectionsModel_ReturnsErrorsForInvalidProperties() public void TryValidateModel_CollectionsModel_ReturnsErrorsForInvalidProperties()
{ {
// Arrange // Arrange
@ -107,6 +108,12 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
var controller = CreateController(testContext, testContext.MetadataProvider); var controller = CreateController(testContext, testContext.MetadataProvider);
// We define the "CompanyName null" message locally, so we should manually check its value.
var categoryRequired = ValidationAttributeUtil.GetRequiredErrorMessage("Category");
var priceRange = ValidationAttributeUtil.GetRangeErrorMessage(20, 100, "Price");
var contactUsMax = ValidationAttributeUtil.GetStringLengthErrorMessage(null, 20, "Contact Us");
var contactusRegEx = ValidationAttributeUtil.GetRegExErrorMessage("^[0-9]*$", "Contact Us");
// Act // Act
var result = controller.TryValidateModel(model); var result = controller.TryValidateModel(model);
@ -114,26 +121,23 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
Assert.False(result); Assert.False(result);
Assert.False(modelState.IsValid); Assert.False(modelState.IsValid);
var modelStateErrors = GetModelStateErrors(modelState); var modelStateErrors = GetModelStateErrors(modelState);
Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["[0].CompanyName"]); Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["[0].CompanyName"]);
Assert.Equal("The field Price must be between 20 and 100.", modelStateErrors["[0].Price"]); Assert.Equal(priceRange, modelStateErrors["[0].Price"]);
Assert.Equal( Assert.Equal(categoryRequired, modelStateErrors["[0].Category"]);
PlatformNormalizer.NormalizeContent("The Category field is required."), AssertErrorEquals(contactUsMax + contactusRegEx, modelStateErrors["[0].Contact"]);
modelStateErrors["[0].Category"]);
AssertErrorEquals(
"The field Contact Us must be a string with a maximum length of 20." +
"The field Contact Us must match the regular expression " +
(TestPlatformHelper.IsMono ? "^[0-9]*$." : "'^[0-9]*$'."),
modelStateErrors["[0].Contact"]);
Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["[1].CompanyName"]); Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["[1].CompanyName"]);
Assert.Equal("The field Price must be between 20 and 100.", modelStateErrors["[1].Price"]); Assert.Equal(priceRange, modelStateErrors["[1].Price"]);
Assert.Equal(categoryRequired, modelStateErrors["[1].Category"]);
AssertErrorEquals(contactUsMax + contactusRegEx, modelStateErrors["[1].Contact"]);
}
private void AssertErrorEquals(string expected, string actual)
{
// OrderBy is used because the order of the results may very depending on the platform / client.
Assert.Equal( Assert.Equal(
PlatformNormalizer.NormalizeContent("The Category field is required."), expected.Split('.').OrderBy(item => item, StringComparer.Ordinal),
modelStateErrors["[1].Category"]); actual.Split('.').OrderBy(item => item, StringComparer.Ordinal));
AssertErrorEquals(
"The field Contact Us must be a string with a maximum length of 20." +
"The field Contact Us must match the regular expression " +
(TestPlatformHelper.IsMono ? "^[0-9]*$." : "'^[0-9]*$'."),
modelStateErrors["[1].Contact"]);
} }
private TestController CreateController( private TestController CreateController(
@ -150,14 +154,6 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
return controller; return controller;
} }
private void AssertErrorEquals(string expected, string actual)
{
// OrderBy is used because the order of the results may very depending on the platform / client.
Assert.Equal(
expected.Split('.').OrderBy(item => item, StringComparer.Ordinal),
actual.Split('.').OrderBy(item => item, StringComparer.Ordinal));
}
private Dictionary<string, string> GetModelStateErrors(ModelStateDictionary modelState) private Dictionary<string, string> GetModelStateErrors(ModelStateDictionary modelState)
{ {
var result = new Dictionary<string, string>(); var result = new Dictionary<string, string>();

View File

@ -12,7 +12,6 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Xunit; using Xunit;
@ -112,7 +111,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
modelState, modelState,
e => string.Equals(e.Key, "AccountId", StringComparison.OrdinalIgnoreCase)).Value; e => string.Equals(e.Key, "AccountId", StringComparison.OrdinalIgnoreCase)).Value;
var error = Assert.Single(entry.Errors); var error = Assert.Single(entry.Errors);
Assert.Equal("The field AccountId must be between 25 and 50.", error.ErrorMessage); Assert.Equal(ValidationAttributeUtil.GetRangeErrorMessage(25, 50, "AccountId"), error.ErrorMessage);
} }
[Theory] [Theory]
@ -1494,9 +1493,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
private static void AssertRequiredError(string key, ModelError error) private static void AssertRequiredError(string key, ModelError error)
{ {
// Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage(key), error.ErrorMessage);
Assert.Equal(PlatformNormalizer.NormalizeContent(
string.Format("The {0} field is required.", key)), error.ErrorMessage);
Assert.Null(error.Exception); Assert.Null(error.Exception);
} }
} }

View File

@ -86,16 +86,12 @@ namespace Microsoft.AspNetCore.Mvc.Localization.Test
new object[] { 10, new DateTime(2015, 10, 10) }, new object[] { 10, new DateTime(2015, 10, 10) },
"Bonjour HtmlEncode[[10]] Bienvenue {1:yyyy}" "Bonjour HtmlEncode[[10]] Bienvenue {1:yyyy}"
}; };
if (!TestPlatformHelper.IsMono) yield return new object[] { "{0:{{000}}}", new object[] { 10 }, "HtmlEncode[[{010}]]" };
{ yield return new object[] {
// Mono doesn't deal well with custom format strings, even valid ones
yield return new object[] { "{0:{{000}}}", new object[] { 10 }, "HtmlEncode[[{010}]]" };
yield return new object[] {
"Bonjour {0:'{{characters that should be escaped}}b'###'b'}", "Bonjour {0:'{{characters that should be escaped}}b'###'b'}",
new object[] { 10 }, new object[] { 10 },
"Bonjour HtmlEncode[[{characters that should be escaped}b10b]]" "Bonjour HtmlEncode[[{characters that should be escaped}b10b]]"
}; };
}
} }
} }
@ -131,22 +127,16 @@ namespace Microsoft.AspNetCore.Mvc.Localization.Test
{ {
get get
{ {
var data = new TheoryData<string> return new TheoryData<string>
{ {
"{0", "{0",
"{"
}; };
// Mono doesn't like { in an underlying string.Format on Mac.
if (!TestPlatformHelper.IsMac || !TestPlatformHelper.IsMono)
{
data.Add("{");
}
return data;
} }
} }
[Theory] [Theory]
[ReplaceCulture]
[MemberData(nameof(InvalidResourceStringData))] [MemberData(nameof(InvalidResourceStringData))]
public void HtmlLocalizer_HtmlWithInvalidResourceString_ContentThrowsException(string format) public void HtmlLocalizer_HtmlWithInvalidResourceString_ContentThrowsException(string format)
{ {

View File

@ -72,22 +72,22 @@ public MyType2 @MyPropertyName2 { get; private set; }
{ {
// Arrange // Arrange
var expected = string.Join(Environment.NewLine, var expected = string.Join(Environment.NewLine,
@"[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]", "[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]",
@"public", "public",
@"#line 1 """"", @"#line 1 """"",
@"MyType1 MyPropertyName1", "MyType1 MyPropertyName1",
"", "",
@"#line default", "#line default",
@"#line hidden", "#line hidden",
@"{ get; private set; }", "{ get; private set; }",
@"[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]", "[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]",
@"public", "public",
@"#line 1 """"", @"#line 1 """"",
@"MyType2 @MyPropertyName2", "MyType2 @MyPropertyName2",
"", "",
@"#line default", "#line default",
@"#line hidden", "#line hidden",
@"{ get; private set; }", "{ get; private set; }",
""); "");
var writer = new CSharpCodeWriter(); var writer = new CSharpCodeWriter();
var context = CreateContext(); var context = CreateContext();

View File

@ -69,7 +69,7 @@ this should fail";
{ {
// Arrange // Arrange
var fileContent = "file content"; var fileContent = "file content";
var content = @"this should fail"; var content = "this should fail";
var compilationService = GetRoslynCompilationService(); var compilationService = GetRoslynCompilationService();
var relativeFileInfo = new RelativeFileInfo( var relativeFileInfo = new RelativeFileInfo(

View File

@ -311,15 +311,13 @@ namespace Microsoft.AspNetCore.Mvc.TagHelpers
var validationSummaryTagHelper = new ValidationSummaryTagHelper(generator); var validationSummaryTagHelper = new ValidationSummaryTagHelper(generator);
var validationTypeName = typeof(ValidationSummary).FullName; var validationTypeName = typeof(ValidationSummary).FullName;
var expectedMessage = var expectedMessage = $"The value of argument 'value' ({validationSummary}) is invalid for Enum type '{validationTypeName}'.";
$@"The value of argument 'value' ({validationSummary}) is invalid for Enum type '{validationTypeName}'.
Parameter name: value";
// Act & Assert // Act & Assert
var ex = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
() => validationSummaryTagHelper.ValidationSummary = validationSummary,
"value", "value",
() => { validationSummaryTagHelper.ValidationSummary = validationSummary; }); expectedMessage);
Assert.Equal(expectedMessage, ex.Message);
} }
private static ViewContext CreateViewContext() private static ViewContext CreateViewContext()

View File

@ -122,9 +122,9 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Internal
{ {
// Arrange // Arrange
var expected = "<div class=\"HtmlEncode[[display-label]]\">HtmlEncode[[Property1]]</div>" + Environment.NewLine + var expected = "<div class=\"HtmlEncode[[display-label]]\">HtmlEncode[[Property1]]</div>" + Environment.NewLine +
"<div class=\"HtmlEncode[[display-field]]\"></div>"+ Environment.NewLine + "<div class=\"HtmlEncode[[display-field]]\"></div>" + Environment.NewLine +
"<div class=\"HtmlEncode[[display-label]]\">HtmlEncode[[Property3]]</div>"+ Environment.NewLine + "<div class=\"HtmlEncode[[display-label]]\">HtmlEncode[[Property3]]</div>" + Environment.NewLine +
"<div class=\"HtmlEncode[[display-field]]\"></div>"+ Environment.NewLine; "<div class=\"HtmlEncode[[display-field]]\"></div>" + Environment.NewLine;
var model = new DefaultTemplatesUtilities.ObjectWithScaffoldColumn(); var model = new DefaultTemplatesUtilities.ObjectWithScaffoldColumn();
var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict); var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict);

View File

@ -15,7 +15,6 @@ using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.TestCommon; using Microsoft.AspNetCore.Mvc.TestCommon;
using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Testing;
using Moq; using Moq;
using Xunit; using Xunit;
@ -610,17 +609,15 @@ Environment.NewLine;
[InlineData("datetime", null, "2000-01-02T03:04:05.006+00:00")] [InlineData("datetime", null, "2000-01-02T03:04:05.006+00:00")]
[InlineData("datetime-local", null, "2000-01-02T03:04:05.006")] [InlineData("datetime-local", null, "2000-01-02T03:04:05.006")]
[InlineData("time", "{0:t}", "03:04:05.006")] [InlineData("time", "{0:t}", "03:04:05.006")]
[ReplaceCulture]
public void Editor_FindsCorrectDateOrTimeTemplate(string dataTypeName, string editFormatString, string expected) public void Editor_FindsCorrectDateOrTimeTemplate(string dataTypeName, string editFormatString, string expected)
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("DateTimeOffset");
var expectedInput = PlatformNormalizer.NormalizeContent( var expectedInput = "<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " +
"<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " + $"data-val-required=\"HtmlEncode[[{requiredMessage}]]\" id=\"HtmlEncode[[FieldPrefix]]\" " +
"data-val-required=\"HtmlEncode[[The DateTimeOffset field is required.]]\" id=\"HtmlEncode[[FieldPrefix]]\" " +
"name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[" + "name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[" +
dataTypeName + dataTypeName +
"]]\" value=\"HtmlEncode[[" + expected + "]]\" />"); "]]\" value=\"HtmlEncode[[" + expected + "]]\" />";
var offset = TimeSpan.FromHours(0); var offset = TimeSpan.FromHours(0);
var model = new DateTimeOffset( var model = new DateTimeOffset(
@ -666,17 +663,16 @@ Environment.NewLine;
[InlineData("datetime", null, "2000-01-02T03:04:05.060+00:00")] [InlineData("datetime", null, "2000-01-02T03:04:05.060+00:00")]
[InlineData("datetime-local", null, "2000-01-02T03:04:05.060")] [InlineData("datetime-local", null, "2000-01-02T03:04:05.060")]
[InlineData("time", "{0:t}", "03:04:05.060")] [InlineData("time", "{0:t}", "03:04:05.060")]
[ReplaceCulture]
public void Editor_AppliesRfc3339(string dataTypeName, string editFormatString, string expected) public void Editor_AppliesRfc3339(string dataTypeName, string editFormatString, string expected)
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("DateTimeOffset");
var expectedInput = PlatformNormalizer.NormalizeContent( var expectedInput =
"<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " + "<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " +
"data-val-required=\"HtmlEncode[[The DateTimeOffset field is required.]]\" id=\"HtmlEncode[[FieldPrefix]]\" " + $"data-val-required=\"HtmlEncode[[{requiredMessage}]]\" id=\"HtmlEncode[[FieldPrefix]]\" " +
"name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[" + "name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[" +
dataTypeName + dataTypeName +
"]]\" value=\"HtmlEncode[[" + expected + "]]\" />"); "]]\" value=\"HtmlEncode[[" + expected + "]]\" />";
// Place DateTime-local value in current timezone. // Place DateTime-local value in current timezone.
var offset = string.Equals(string.Empty, dataTypeName) ? DateTimeOffset.Now.Offset : TimeSpan.FromHours(0); var offset = string.Equals(string.Empty, dataTypeName) ? DateTimeOffset.Now.Offset : TimeSpan.FromHours(0);
@ -731,13 +727,12 @@ Environment.NewLine;
public void Editor_AppliesNonDefaultEditFormat(string dataTypeName, Html5DateRenderingMode renderingMode) public void Editor_AppliesNonDefaultEditFormat(string dataTypeName, Html5DateRenderingMode renderingMode)
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("DateTimeOffset");
var expectedInput = PlatformNormalizer.NormalizeContent( var expectedInput = "<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " +
"<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " + $"data-val-required=\"HtmlEncode[[{requiredMessage}]]\" id=\"HtmlEncode[[FieldPrefix]]\" " +
"data-val-required=\"HtmlEncode[[The DateTimeOffset field is required.]]\" id=\"HtmlEncode[[FieldPrefix]]\" " +
"name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[" + "name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[" +
dataTypeName + dataTypeName +
"]]\" value=\"HtmlEncode[[Formatted as 2000-01-02T03:04:05.0600000+00:00]]\" />"); "]]\" value=\"HtmlEncode[[Formatted as 2000-01-02T03:04:05.0600000+00:00]]\" />";
var offset = TimeSpan.FromHours(0); var offset = TimeSpan.FromHours(0);
var model = new DateTimeOffset( var model = new DateTimeOffset(

View File

@ -230,13 +230,13 @@ namespace Microsoft.AspNetCore.Mvc
{ {
// Arrange // Arrange
var attribute = new RemoteAttribute(routeName: "default"); var attribute = new RemoteAttribute(routeName: "default");
var expected = "Value cannot be null or empty." + Environment.NewLine + "Parameter name: property"; var expectedMessage = "Value cannot be null or empty.";
// Act & Assert // Act & Assert
var exception = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
() => attribute.FormatAdditionalFieldsForClientValidation(property),
"property", "property",
() => attribute.FormatAdditionalFieldsForClientValidation(property)); expectedMessage);
Assert.Equal(expected, exception.Message);
} }
[Theory] [Theory]
@ -244,13 +244,13 @@ namespace Microsoft.AspNetCore.Mvc
public void FormatPropertyForClientValidation_WithInvalidPropertyName_Throws(string property) public void FormatPropertyForClientValidation_WithInvalidPropertyName_Throws(string property)
{ {
// Arrange // Arrange
var expected = "Value cannot be null or empty." + Environment.NewLine + "Parameter name: property"; var expected = "Value cannot be null or empty.";
// Act & Assert // Act & Assert
var exception = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
() => RemoteAttribute.FormatPropertyForClientValidation(property),
"property", "property",
() => RemoteAttribute.FormatPropertyForClientValidation(property)); expected);
Assert.Equal(expected, exception.Message);
} }
[Fact] [Fact]

View File

@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.TestCommon; using Microsoft.AspNetCore.Mvc.TestCommon;
using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.WebEncoders.Testing; using Microsoft.Extensions.WebEncoders.Testing;
using Xunit; using Xunit;
@ -20,12 +21,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxOverridesCalculatedValuesWithValuesFromHtmlAttributes() public void CheckBoxOverridesCalculatedValuesWithValuesFromHtmlAttributes()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = PlatformNormalizer.NormalizeContent( var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
@"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " + $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property3]]"" " +
@"data-val-required=""HtmlEncode[[The Boolean field is required.]]"" id=""HtmlEncode[[Property3]]"" " +
@"name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " + @"name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
// Act // Act
@ -41,12 +41,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxExplicitParametersOverrideDictionary_ForValueInModel() public void CheckBoxExplicitParametersOverrideDictionary_ForValueInModel()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = PlatformNormalizer.NormalizeContent( var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
@"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " + $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property3]]"" " +
@"data-val-required=""HtmlEncode[[The Boolean field is required.]]"" id=""HtmlEncode[[Property3]]"" " +
@"name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " + @"name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
@ -80,13 +79,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxWithInvalidBooleanThrows() public void CheckBoxWithInvalidBooleanThrows()
{ {
// Arrange // Arrange
var expected = "String was not recognized as a valid Boolean.";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
// Act & Assert // Act & Assert
var ex = Assert.Throws<FormatException>( var ex = Assert.Throws<FormatException>(
() => helper.CheckBox("Property2", isChecked: null, htmlAttributes: null)); () => helper.CheckBox("Property2", isChecked: null, htmlAttributes: null));
Assert.Equal(expected, ex.Message); Assert.Contains("Boolean", ex.Message);
} }
[Fact] [Fact]
@ -95,29 +93,26 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
// Arrange // Arrange
var expected = "The name of an HTML field cannot be null or empty. Instead use methods " + var expected = "The name of an HTML field cannot be null or empty. Instead use methods " +
"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." + "Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
"IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
Environment.NewLine + "Parameter name: expression";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
// Act & Assert // Act & Assert
var ex = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
() => helper.CheckBox(null, isChecked: true, htmlAttributes: null),
"expression", "expression",
() => helper.CheckBox(null, isChecked: true, htmlAttributes: null)); expected);
Assert.Equal(expected, ex.Message);
} }
[Fact] [Fact]
public void CheckBoxCheckedWithOnlyName_GeneratesExpectedValue() public void CheckBoxCheckedWithOnlyName_GeneratesExpectedValue()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = PlatformNormalizer.NormalizeContent( var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
@"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " + $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
@"data-val-required=""HtmlEncode[[The Boolean field is required.]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " + @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
// Act // Act
@ -131,12 +126,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBox_WithCanRenderAtEndOfFormSet_DoesNotGenerateInlineHiddenTag() public void CheckBox_WithCanRenderAtEndOfFormSet_DoesNotGenerateInlineHiddenTag()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = PlatformNormalizer.NormalizeContent( var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
@"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " + $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
@"data-val-required=""HtmlEncode[[The Boolean field is required.]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " + @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[true]]"" />"); @"value=""HtmlEncode[[true]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewContext.FormContext.CanRenderAtEndOfForm = true; helper.ViewContext.FormContext.CanRenderAtEndOfForm = true;
@ -157,11 +151,10 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxUsesAttemptedValueFromModelState() public void CheckBoxUsesAttemptedValueFromModelState()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = PlatformNormalizer.NormalizeContent( var expected = $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Boolean field is required.]]"" " +
@"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" + @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewData.ModelState.SetModelValue("Property1", new string[] { "false" }, "false"); helper.ViewData.ModelState.SetModelValue("Property1", new string[] { "false" }, "false");
@ -341,11 +334,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxGeneratesUnobtrusiveValidationAttributes() public void CheckBoxGeneratesUnobtrusiveValidationAttributes()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Name");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Name field is required.]]"" id=""HtmlEncode[[Name]]""" + $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Name]]""" +
@" name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" + @" name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"<input name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData());
// Act // Act
@ -359,13 +352,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxReplacesUnderscoresInHtmlAttributesWithDashes() public void CheckBoxReplacesUnderscoresInHtmlAttributesWithDashes()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = PlatformNormalizer.NormalizeContent( var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
@"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " + $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
@"data-val-required=""HtmlEncode[[The Boolean field is required.]]"" id=""HtmlEncode[[Property1]]"" " +
@"name=""HtmlEncode[[Property1]]"" Property1-Property3=""HtmlEncode[[Property3ObjValue]]"" " + @"name=""HtmlEncode[[Property1]]"" Property1-Property3=""HtmlEncode[[Property3ObjValue]]"" " +
@"type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " + @"type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
var htmlAttributes = new { Property1_Property3 = "Property3ObjValue" }; var htmlAttributes = new { Property1_Property3 = "Property3ObjValue" };
@ -418,12 +410,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxInTemplate_WithEmptyExpression_GeneratesExpectedValue() public void CheckBoxInTemplate_WithEmptyExpression_GeneratesExpectedValue()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Boolean field is required.]]"" " + $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[MyPrefix]]"" name=""HtmlEncode[[MyPrefix]]"" Property3=""HtmlEncode[[Property3Value]]"" " + @"id=""HtmlEncode[[MyPrefix]]"" name=""HtmlEncode[[MyPrefix]]"" Property3=""HtmlEncode[[Property3Value]]"" " +
@"type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[MyPrefix]]"" type=""HtmlEncode[[hidden]]"" " + @"type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[MyPrefix]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[false]]"" />"); @"value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model: false); var helper = DefaultTemplatesUtilities.GetHtmlHelper(model: false);
var attributes = new Dictionary<string, object> { { "Property3", "Property3Value" } }; var attributes = new Dictionary<string, object> { { "Property3", "Property3Value" } };
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix"; helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
@ -439,13 +431,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxWithComplexExpressionsEvaluatesValuesInViewDataDictionary() public void CheckBoxWithComplexExpressionsEvaluatesValuesInViewDataDictionary()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
var expected = PlatformNormalizer.NormalizeContent( var expected = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
@"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " + $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[ComplexProperty_Property1]]"" " +
@"data-val-required=""HtmlEncode[[The Boolean field is required.]]"" id=""HtmlEncode[[ComplexProperty_Property1]]"" " +
@"name=""HtmlEncode[[ComplexProperty." + @"name=""HtmlEncode[[ComplexProperty." +
@"Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[ComplexProperty.Property1]]""" + @"Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[ComplexProperty.Property1]]""" +
@" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData());
// Act // Act
@ -459,11 +450,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxForWithNullContainer_TreatsBooleanAsFalse() public void CheckBoxForWithNullContainer_TreatsBooleanAsFalse()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " + $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" + @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var viewData = GetTestModelViewData(); var viewData = GetTestModelViewData();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData); var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);
viewData.ModelState.SetModelValue("Property1", new string[] { "false" }, "false"); viewData.ModelState.SetModelValue("Property1", new string[] { "false" }, "false");
@ -481,11 +472,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxForWithNonNullContainer_UsesPropertyValue(bool value, string expectedChecked) public void CheckBoxForWithNonNullContainer_UsesPropertyValue(bool value, string expectedChecked)
{ {
// Arrange // Arrange
var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
// Mono issue - https://github.com/aspnet/External/issues/19 // Mono issue - https://github.com/aspnet/External/issues/19
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input {0}data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " + $@"<input {{0}}data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" + @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
expected = string.Format(expected, expectedChecked); expected = string.Format(expected, expectedChecked);
var viewData = GetTestModelViewData(); var viewData = GetTestModelViewData();
@ -507,12 +499,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxForOverridesCalculatedParametersWithValuesFromHtmlAttributes() public void CheckBoxForOverridesCalculatedParametersWithValuesFromHtmlAttributes()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property3");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " + @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
@"data-val-required=""HtmlEncode[[The Property3 field is required.]]"" " + $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property3]]"" name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " + @"id=""HtmlEncode[[Property3]]"" name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " +
@"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
// Act // Act
@ -526,11 +518,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxForGeneratesUnobtrusiveValidationAttributes() public void CheckBoxForGeneratesUnobtrusiveValidationAttributes()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Name");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Name field is required.]]"" id=""HtmlEncode[[Name]]""" + $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Name]]""" +
@" name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" + @" name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"<input name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider(); var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var viewDataDictionary = new ViewDataDictionary<ModelWithValidation>(metadataProvider) var viewDataDictionary = new ViewDataDictionary<ModelWithValidation>(metadataProvider)
{ {
@ -551,11 +543,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxFor_UsesModelStateAttemptedValue(string attemptedValue, string expectedChecked) public void CheckBoxFor_UsesModelStateAttemptedValue(string attemptedValue, string expectedChecked)
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input {0}data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " + $@"<input {{0}}data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" + @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
@"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
expected = string.Format(expected, expectedChecked); expected = string.Format(expected, expectedChecked);
var viewData = GetTestModelViewData(); var viewData = GetTestModelViewData();
@ -573,12 +565,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxFor_WithObjectAttribute_MapsUnderscoresInNamesToDashes() public void CheckBoxFor_WithObjectAttribute_MapsUnderscoresInNamesToDashes()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " + $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " + @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " +
@"Property1-Property3=""HtmlEncode[[Property3ObjValue]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " + @"Property1-Property3=""HtmlEncode[[Property3ObjValue]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
var htmlAttributes = new { Property1_Property3 = "Property3ObjValue" }; var htmlAttributes = new { Property1_Property3 = "Property3ObjValue" };
@ -593,12 +585,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxFor_WithAttributeDictionary_GeneratesExpectedAttributes() public void CheckBoxFor_WithAttributeDictionary_GeneratesExpectedAttributes()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " + $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " + @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " +
@"Property3=""HtmlEncode[[Property3Value]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " + @"Property3=""HtmlEncode[[Property3Value]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
@"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
var attributes = new Dictionary<string, object> { { "Property3", "Property3Value" } }; var attributes = new Dictionary<string, object> { { "Property3", "Property3Value" } };
@ -613,12 +605,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxForInTemplate_GeneratesExpectedValue() public void CheckBoxForInTemplate_GeneratesExpectedValue()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " + $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[MyPrefix_Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" Property3=""HtmlEncode[[PropValue]]"" " + @"id=""HtmlEncode[[MyPrefix_Property1]]"" name=""HtmlEncode[[MyPrefix.Property1]]"" Property3=""HtmlEncode[[PropValue]]"" " +
@"type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[hidden]]"" " + @"type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[MyPrefix.Property1]]"" type=""HtmlEncode[[hidden]]"" " +
@"value=""HtmlEncode[[false]]"" />"); @"value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix"; helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
var attributes = new Dictionary<string, object> { { "Property3", "PropValue" } }; var attributes = new Dictionary<string, object> { { "Property3", "PropValue" } };
@ -634,12 +626,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void CheckBoxFor_WithComplexExpressions_DoesNotUseValuesFromViewDataDictionary() public void CheckBoxFor_WithComplexExpressions_DoesNotUseValuesFromViewDataDictionary()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " + $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[ComplexProperty_Property1]]"" name=""HtmlEncode[[ComplexProperty." + @"id=""HtmlEncode[[ComplexProperty_Property1]]"" name=""HtmlEncode[[ComplexProperty." +
@"Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[ComplexProperty.Property1]]"" " + @"Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[ComplexProperty.Property1]]"" " +
@"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"); @"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData());
// Act // Act

View File

@ -415,8 +415,7 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
}; };
var expected = "The name of an HTML field cannot be null or empty. Instead use methods " + var expected = "The name of an HTML field cannot be null or empty. Instead use methods " +
"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." + "Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
"IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
Environment.NewLine + "Parameter name: expression";
// Act and Assert // Act and Assert
ExceptionAssert.ThrowsArgument( ExceptionAssert.ThrowsArgument(
@ -449,10 +448,10 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void HiddenGeneratesUnobtrusiveValidation() public void HiddenGeneratesUnobtrusiveValidation()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = new RequiredAttribute().FormatErrorMessage("Property2");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property2 field is required.]]"" " + $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[hidden]]"" value="""" />"); @"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[hidden]]"" value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
// Act // Act
@ -713,10 +712,10 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void HiddenFor_GeneratesUnobtrusiveValidationAttributes() public void HiddenFor_GeneratesUnobtrusiveValidationAttributes()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property2");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property2 field is required.]]"" " + $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[hidden]]"" value="""" />"); @"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[hidden]]"" value="""" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithErrors()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithErrors());
// Act // Act

View File

@ -131,16 +131,15 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
var name = string.Empty; var name = string.Empty;
var value = string.Empty; var value = string.Empty;
var expected = "The name of an HTML field cannot be null or empty. Instead use methods " + var expectedMessage = "The name of an HTML field cannot be null or empty. Instead use methods " +
"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." + "Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
"IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
Environment.NewLine + "Parameter name: expression";
// Act and Assert // Act and Assert
ExceptionAssert.ThrowsArgument( ExceptionAssert.ThrowsArgument(
() => helper.Password(name, value, htmlAttributes: null), () => helper.Password(name, value, htmlAttributes: null),
"expression", "expression",
expected); expectedMessage);
} }
[Fact] [Fact]
@ -169,10 +168,10 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void PasswordGeneratesUnobtrusiveValidation() public void PasswordGeneratesUnobtrusiveValidation()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property2");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property2 field is required.]]"" " + $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[password]]"" />"); @"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[password]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());
// Act // Act
@ -278,10 +277,10 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
public void PasswordFor_GeneratesUnobtrusiveValidationAttributes() public void PasswordFor_GeneratesUnobtrusiveValidationAttributes()
{ {
// Arrange // Arrange
// Mono issue - https://github.com/aspnet/External/issues/19 var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property2");
var expected = PlatformNormalizer.NormalizeContent( var expected =
@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property2 field is required.]]"" " + $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
@"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[password]]"" />"); @"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[password]]"" />";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithErrors()); var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithErrors());
// Act // Act

View File

@ -375,15 +375,14 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
// Arrange // Arrange
var expected = "The name of an HTML field cannot be null or empty. Instead use methods " + var expected = "The name of an HTML field cannot be null or empty. Instead use methods " +
"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." + "Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
"IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
Environment.NewLine + "Parameter name: expression";
var helper = DefaultTemplatesUtilities.GetHtmlHelper(); var helper = DefaultTemplatesUtilities.GetHtmlHelper();
// Act & Assert // Act & Assert
var ex = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
() => helper.DropDownList(null, selectList: null, optionLabel: null, htmlAttributes: null),
"expression", "expression",
() => helper.DropDownList(null, selectList: null, optionLabel: null, htmlAttributes: null)); expected);
Assert.Equal(expected, ex.Message);
} }
[Theory] [Theory]

View File

@ -16,6 +16,7 @@ using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.TestCommon; using Microsoft.AspNetCore.Mvc.TestCommon;
using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Moq; using Moq;
using Xunit; using Xunit;
@ -76,21 +77,19 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
var viewContext = GetViewContext<Model>(model: null, metadataProvider: metadataProvider); var viewContext = GetViewContext<Model>(model: null, metadataProvider: metadataProvider);
var modelExplorer = metadataProvider.GetModelExplorerForType(typeof(string), model: null); var modelExplorer = metadataProvider.GetModelExplorerForType(typeof(string), model: null);
var expected = "The name of an HTML field cannot be null or empty. Instead use methods " + var expected = "The name of an HTML field cannot be null or empty. Instead use " +
"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." + "methods Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
"IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
Environment.NewLine + "Parameter name: expression";
// Act and assert // Act and assert
var ex = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
"expression",
() => htmlGenerator.GetCurrentValues( () => htmlGenerator.GetCurrentValues(
viewContext, viewContext,
modelExplorer, modelExplorer,
expression: null, expression: null,
allowMultiple: true)); allowMultiple: true),
"expression",
Assert.Equal(expected, ex.Message); expected);
} }
[Fact] [Fact]
@ -104,12 +103,10 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
var expected = "The name of an HTML field cannot be null or empty. Instead use methods " + var expected = "The name of an HTML field cannot be null or empty. Instead use methods " +
"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." + "Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
"IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
Environment.NewLine + "Parameter name: expression";
// Act and assert // Act and assert
var ex = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
"expression",
() => htmlGenerator.GenerateSelect( () => htmlGenerator.GenerateSelect(
viewContext, viewContext,
modelExplorer, modelExplorer,
@ -117,9 +114,9 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
null, null,
new List<SelectListItem>(), new List<SelectListItem>(),
true, true,
null)); null),
"expression",
Assert.Equal(expected, ex.Message); expected);
} }
[Fact] [Fact]
@ -133,21 +130,19 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
var expected = "The name of an HTML field cannot be null or empty. Instead use methods " + var expected = "The name of an HTML field cannot be null or empty. Instead use methods " +
"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." + "Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
"IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
Environment.NewLine + "Parameter name: expression";
// Act and assert // Act and assert
var ex = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
"expression",
() => htmlGenerator.GenerateTextArea( () => htmlGenerator.GenerateTextArea(
viewContext, viewContext,
modelExplorer, modelExplorer,
null, null,
1, 1,
1, 1,
null)); null),
"expression",
Assert.Equal(expected, ex.Message); expected);
} }
[Fact] [Fact]
@ -161,15 +156,13 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
var expected = "The name of an HTML field cannot be null or empty. Instead use methods " + var expected = "The name of an HTML field cannot be null or empty. Instead use methods " +
"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." + "Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
"IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
Environment.NewLine + "Parameter name: expression";
// Act and assert // Act and assert
var ex = Assert.Throws<ArgumentException>( ExceptionAssert.ThrowsArgument(
() => htmlGenerator.GenerateValidationMessage(viewContext, null, null, "Message", "tag", null),
"expression", "expression",
() => htmlGenerator.GenerateValidationMessage(viewContext, null, null, "Message", "tag", null)); expected);
Assert.Equal(expected, ex.Message);
} }
[Theory] [Theory]

View File

@ -16,6 +16,7 @@
"version": "1.1.0-*", "version": "1.1.0-*",
"type": "build" "type": "build"
}, },
"Microsoft.AspNetCore.Mvc.ViewFeatures": "1.1.0-*",
"Microsoft.AspNetCore.Testing": "1.1.0-*", "Microsoft.AspNetCore.Testing": "1.1.0-*",
"Microsoft.Extensions.DependencyInjection": "1.1.0-*", "Microsoft.Extensions.DependencyInjection": "1.1.0-*",
"Microsoft.Extensions.DiagnosticAdapter": "1.1.0-*", "Microsoft.Extensions.DiagnosticAdapter": "1.1.0-*",

View File

@ -23,10 +23,7 @@ namespace System.Net.Http
var ex = Assert.Throws<FormatException>( var ex = Assert.Throws<FormatException>(
() => request.CreateResponse(HttpStatusCode.OK, CreateValue(), "foo/bar; param=value")); () => request.CreateResponse(HttpStatusCode.OK, CreateValue(), "foo/bar; param=value"));
Assert.Equal( Assert.Contains("foo/bar; param=value", ex.Message);
TestPlatformHelper.IsMono ?
"Invalid format." :
"The format of value 'foo/bar; param=value' is invalid.", ex.Message);
} }
[Fact] [Fact]