diff --git a/src/Microsoft.AspNetCore.Mvc.Core/Formatters/FormatterMappings.cs b/src/Microsoft.AspNetCore.Mvc.Core/Formatters/FormatterMappings.cs index 03ed3065a5..3d66ecf5ca 100644 --- a/src/Microsoft.AspNetCore.Mvc.Core/Formatters/FormatterMappings.cs +++ b/src/Microsoft.AspNetCore.Mvc.Core/Formatters/FormatterMappings.cs @@ -104,7 +104,9 @@ namespace Microsoft.AspNetCore.Mvc.Formatters { 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 == ".") { - throw new ArgumentException(string.Format(Resources.Format_NotValid, format)); + throw new ArgumentException(string.Format(Resources.Format_NotValid, format), nameof(format)); } format = format.Substring(1); diff --git a/src/Microsoft.AspNetCore.Mvc.WebApiCompatShim/ContentNegotiator/FormattingUtilities.cs b/src/Microsoft.AspNetCore.Mvc.WebApiCompatShim/ContentNegotiator/FormattingUtilities.cs index 1a9921221f..fbf5b80d35 100644 --- a/src/Microsoft.AspNetCore.Mvc.WebApiCompatShim/ContentNegotiator/FormattingUtilities.cs +++ b/src/Microsoft.AspNetCore.Mvc.WebApiCompatShim/ContentNegotiator/FormattingUtilities.cs @@ -68,12 +68,12 @@ namespace System.Net.Http /// /// HTTP X-Requested-With header field name /// - public const string HttpRequestedWithHeader = @"x-requested-with"; + public const string HttpRequestedWithHeader = "x-requested-with"; /// /// HTTP X-Requested-With header field value /// - public const string HttpRequestedWithHeaderValue = @"XMLHttpRequest"; + public const string HttpRequestedWithHeaderValue = "XMLHttpRequest"; /// /// HTTP Host header field name diff --git a/test/Microsoft.AspNetCore.Mvc.Core.Test/Filters/FilterCollectionTest.cs b/test/Microsoft.AspNetCore.Mvc.Core.Test/Filters/FilterCollectionTest.cs index 43afe1610b..095ee2dd8e 100644 --- a/test/Microsoft.AspNetCore.Mvc.Core.Test/Filters/FilterCollectionTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Core.Test/Filters/FilterCollectionTest.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; +using Microsoft.AspNetCore.Testing; using Xunit; namespace Microsoft.AspNetCore.Mvc.Filters @@ -42,16 +42,13 @@ namespace Microsoft.AspNetCore.Mvc.Filters // Arrange var collection = new FilterCollection(); - var expectedMessage = - $"The type '{typeof(NonFilter).FullName}' must derive from " + - $"'{typeof(IFilterMetadata).FullName}'." + Environment.NewLine + - "Parameter name: filterType"; + var expectedMessage = $"The type '{typeof(NonFilter).FullName}' must derive from " + $"'{typeof(IFilterMetadata).FullName}'."; // Act & Assert - var ex = Assert.Throws(() => { collection.Add(typeof(NonFilter)); }); - - // Assert - Assert.Equal(expectedMessage, ex.Message); + ExceptionAssert.ThrowsArgument( + () => collection.Add(typeof(NonFilter)), + "filterType", + expectedMessage); } [Fact] @@ -88,16 +85,13 @@ namespace Microsoft.AspNetCore.Mvc.Filters // Arrange var collection = new FilterCollection(); - var expectedMessage = - $"The type '{typeof(NonFilter).FullName}' must derive from " + - $"'{typeof(IFilterMetadata).FullName}'." + Environment.NewLine + - "Parameter name: filterType"; + var expectedMessage = $"The type '{typeof(NonFilter).FullName}' must derive from '{typeof(IFilterMetadata).FullName}'."; // Act & Assert - var ex = Assert.Throws(() => { collection.AddService(typeof(NonFilter)); }); - - // Assert - Assert.Equal(expectedMessage, ex.Message); + ExceptionAssert.ThrowsArgument( + () => { collection.AddService(typeof(NonFilter)); }, + "filterType", + expectedMessage); } private class MyFilter : IFilterMetadata, IOrderedFilter diff --git a/test/Microsoft.AspNetCore.Mvc.Core.Test/Formatters/FormatterMappingsTest.cs b/test/Microsoft.AspNetCore.Mvc.Core.Test/Formatters/FormatterMappingsTest.cs index da94275264..d5428abc3f 100644 --- a/test/Microsoft.AspNetCore.Mvc.Core.Test/Formatters/FormatterMappingsTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Core.Test/Formatters/FormatterMappingsTest.cs @@ -3,11 +3,10 @@ using System; using Microsoft.AspNetCore.Mvc.TestCommon; -using Microsoft.Extensions.Primitives; +using Microsoft.AspNetCore.Testing; using Microsoft.Net.Http.Headers; using Xunit; - namespace Microsoft.AspNetCore.Mvc.Formatters { public class FormatterMappingsTest @@ -49,14 +48,16 @@ namespace Microsoft.AspNetCore.Mvc.Formatters // Arrange var options = new FormatterMappings(); var format = "."; - var expected = string.Format(@"The format provided is invalid '{0}'. A format must be a non-empty file-" + - "extension, optionally prefixed with a '.' character.", format); + var expected = $"The format provided is invalid '{format}'. A format must be a non-empty file-" + + "extension, optionally prefixed with a '.' character."; // Act and assert - var exception = Assert.Throws(() => options.SetMediaTypeMappingForFormat( - format, - MediaTypeHeaderValue.Parse("application/xml"))); - Assert.Equal(expected, exception.Message); + ExceptionAssert.ThrowsArgument( + () => options.SetMediaTypeMappingForFormat( + format, + MediaTypeHeaderValue.Parse("application/xml")), + "format", + expected); } [Fact] @@ -65,16 +66,15 @@ namespace Microsoft.AspNetCore.Mvc.Formatters // Arrange var options = new FormatterMappings(); var format = ""; - var expected = "Value cannot be null or empty." + Environment.NewLine + "Parameter name: format"; - // Act and assert - var exception = Assert.Throws(() => options.SetMediaTypeMappingForFormat( - format, - MediaTypeHeaderValue.Parse("application/xml"))); - Assert.Equal(expected, exception.Message); + // Act and Assert + ExceptionAssert.ThrowsArgumentNullOrEmpty( + () => options.SetMediaTypeMappingForFormat( + format, + MediaTypeHeaderValue.Parse("application/xml")), + "format"); } - [Theory] [InlineData("application/*")] [InlineData("*/json")] @@ -83,14 +83,16 @@ namespace Microsoft.AspNetCore.Mvc.Formatters { // Arrange var options = new FormatterMappings(); - var expected = string.Format(@"The media type ""{0}"" is not valid. MediaTypes containing wildcards (*) " + - "are not allowed in formatter mappings.", format); + var expected = $@"The media type ""{format}"" is not valid. MediaTypes containing wildcards (*) " + + "are not allowed in formatter mappings."; // Act and assert - var exception = Assert.Throws(() => options.SetMediaTypeMappingForFormat( - "star", - MediaTypeHeaderValue.Parse(format))); - Assert.Equal(expected, exception.Message); + ExceptionAssert.ThrowsArgument( + () => options.SetMediaTypeMappingForFormat( + "star", + MediaTypeHeaderValue.Parse(format)), + "contentType", + expected); } [Theory] diff --git a/test/Microsoft.AspNetCore.Mvc.Core.Test/Internal/AttributeRoutingTest.cs b/test/Microsoft.AspNetCore.Mvc.Core.Test/Internal/AttributeRoutingTest.cs index 2dc8531835..5b77c4d995 100644 --- a/test/Microsoft.AspNetCore.Mvc.Core.Test/Internal/AttributeRoutingTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Core.Test/Internal/AttributeRoutingTest.cs @@ -14,6 +14,7 @@ using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; @@ -28,10 +29,12 @@ namespace Microsoft.AspNetCore.Mvc.Internal public class AttributeRoutingTest { [Fact] + [ReplaceCulture] public async Task AttributeRouting_SyntaxErrorInTemplate() { // Arrange - var action = CreateAction("InvalidTemplate", "{a/dkfk}"); + var value = "a/dkfk"; + var action = CreateAction("InvalidTemplate", "{" + value + "}"); var expectedMessage = "The following errors occurred with attribute routing information:" + Environment.NewLine + @@ -42,16 +45,14 @@ namespace Microsoft.AspNetCore.Mvc.Internal "and can occur only at the end of the parameter. The '*' character marks a parameter as catch-all, " + "and can occur only at the start of the parameter." + Environment.NewLine + "Parameter name: routeTemplate"; - + var services = CreateServices(action); var route = AttributeRouting.CreateAttributeMegaRoute(services); + var routeContext = new RouteContext(new DefaultHttpContext()); // Act & Assert - var ex = await Assert.ThrowsAsync(async () => - { - await route.RouteAsync(new RouteContext(new DefaultHttpContext())); - }); + var ex = await Assert.ThrowsAsync(() => route.RouteAsync(routeContext)); Assert.Equal(expectedMessage, ex.Message); } @@ -69,7 +70,7 @@ namespace Microsoft.AspNetCore.Mvc.Internal "For action: 'DisallowedParameter'" + Environment.NewLine + "Error: The attribute route '{foo}/{action}' cannot contain a parameter named '{foo}'. " + "Use '[foo]' in the route template to insert the value 'bleh'."; - + var services = CreateServices(action); var route = AttributeRouting.CreateAttributeMegaRoute(services); @@ -103,7 +104,7 @@ namespace Microsoft.AspNetCore.Mvc.Internal "For action: 'DisallowedParameter2'" + Environment.NewLine + "Error: The attribute route 'cool/{action}' cannot contain a parameter named '{action}'. " + "Use '[action]' in the route template to insert the value 'hey'."; - + var services = CreateServices(action1, action2); var route = AttributeRouting.CreateAttributeMegaRoute(services); diff --git a/test/Microsoft.AspNetCore.Mvc.Core.Test/Internal/ControllerActionInvokerTest.cs b/test/Microsoft.AspNetCore.Mvc.Core.Test/Internal/ControllerActionInvokerTest.cs index c695754142..f54da94908 100644 --- a/test/Microsoft.AspNetCore.Mvc.Core.Test/Internal/ControllerActionInvokerTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Core.Test/Internal/ControllerActionInvokerTest.cs @@ -2469,9 +2469,7 @@ namespace Microsoft.AspNetCore.Mvc.Internal // Act & Assert await ExceptionAssert.ThrowsAsync( () => invoker.InvokeAsync(), - "Cannot return null from an action method with a return type of '" - + resultType - + "'."); + $"Cannot return null from an action method with a return type of '{resultType}'."); } [Fact] diff --git a/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/BindingSourceValueProviderTest.cs b/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/BindingSourceValueProviderTest.cs index b28b6bfe20..ea699e183a 100644 --- a/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/BindingSourceValueProviderTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/BindingSourceValueProviderTest.cs @@ -2,7 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Threading.Tasks; +using Microsoft.AspNetCore.Testing; using Xunit; namespace Microsoft.AspNetCore.Mvc.ModelBinding @@ -15,8 +15,7 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding // Arrange var expected = "The provided binding source 'Test Source' is a greedy data source. " + - "'BindingSourceValueProvider' does not support greedy data sources." + Environment.NewLine + - "Parameter name: bindingSource"; + $"'{nameof(BindingSourceValueProvider)}' does not support greedy data sources."; var bindingSource = new BindingSource( "Test", @@ -25,29 +24,28 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding isFromRequest: true); // Act & Assert - var exception = Assert.Throws( - () => new TestableBindingSourceValueProvider(bindingSource)); - Assert.Equal(expected, exception.Message); + ExceptionAssert.ThrowsArgument( + () => new TestableBindingSourceValueProvider(bindingSource), + "bindingSource", + expected); } [Fact] public void BindingSourceValueProvider_ThrowsOnCompositeSource() { // Arrange - var expected = - "The provided binding source 'Test Source' is a composite. " + - "'BindingSourceValueProvider' requires that the source must represent a single type of input." + - Environment.NewLine + - "Parameter name: bindingSource"; + var expected = $"The provided binding source 'Test Source' is a composite. '{nameof(BindingSourceValueProvider)}' " + + "requires that the source must represent a single type of input."; var bindingSource = CompositeBindingSource.Create( bindingSources: new BindingSource[] { BindingSource.Query, BindingSource.Form }, displayName: "Test Source"); // Act & Assert - var exception = Assert.Throws( - () => new TestableBindingSourceValueProvider(bindingSource)); - Assert.Equal(expected, exception.Message); + ExceptionAssert.ThrowsArgument( + () => new TestableBindingSourceValueProvider(bindingSource), + "bindingSource", + expected); } [Fact] diff --git a/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/Metadata/BindingSourceTest.cs b/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/Metadata/BindingSourceTest.cs index 680844a652..8e2367c121 100644 --- a/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/Metadata/BindingSourceTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/Metadata/BindingSourceTest.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; +using Microsoft.AspNetCore.Testing; using Xunit; namespace Microsoft.AspNetCore.Mvc.ModelBinding @@ -12,20 +12,18 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding public void BindingSource_CanAcceptDataFrom_ThrowsOnComposite() { // Arrange - var expected = - "The provided binding source 'Test Source' is a composite. " + - "'CanAcceptDataFrom' requires that the source must represent a single type of input." + - Environment.NewLine + - "Parameter name: bindingSource"; + var expected = "The provided binding source 'Test Source' is a composite. " + + $"'{nameof(BindingSource.CanAcceptDataFrom)}' requires that the source must represent a single type of input."; var bindingSource = CompositeBindingSource.Create( bindingSources: new BindingSource[] { BindingSource.Query, BindingSource.Form }, displayName: "Test Source"); // Act & Assert - var exception = Assert.Throws( - () => BindingSource.Query.CanAcceptDataFrom(bindingSource)); - Assert.Equal(expected, exception.Message); + ExceptionAssert.ThrowsArgument( + () => BindingSource.Query.CanAcceptDataFrom(bindingSource), + "bindingSource", + expected); } [Fact] diff --git a/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/Metadata/CompositeBindingSourceTest.cs b/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/Metadata/CompositeBindingSourceTest.cs index 96470e7ab9..b5ee0c57ea 100644 --- a/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/Metadata/CompositeBindingSourceTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/Metadata/CompositeBindingSourceTest.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; +using Microsoft.AspNetCore.Testing; using Xunit; namespace Microsoft.AspNetCore.Mvc.ModelBinding @@ -12,12 +12,6 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding public void CompositeBindingSourceTest_CanAcceptDataFrom_ThrowsOnComposite() { // 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( bindingSources: new BindingSource[] { BindingSource.Query, BindingSource.Form }, displayName: "Test Source1"); @@ -26,11 +20,15 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding bindingSources: new BindingSource[] { BindingSource.Query, BindingSource.Form }, 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 - var exception = Assert.Throws( - () => composite1.CanAcceptDataFrom(composite2)); - Assert.Equal(expected, exception.Message); + ExceptionAssert.ThrowsArgument( + () => composite1.CanAcceptDataFrom(composite2), + "bindingSource", + expected); } [Fact] diff --git a/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/ModelBindingHelperTest.cs b/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/ModelBindingHelperTest.cs index 2bc310189f..94d0084146 100644 --- a/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/ModelBindingHelperTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Core.Test/ModelBinding/ModelBindingHelperTest.cs @@ -15,6 +15,7 @@ using Microsoft.AspNetCore.Mvc.Internal; using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; using Microsoft.AspNetCore.Mvc.ModelBinding.Internal; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; +using Microsoft.AspNetCore.Testing; using Moq; using Xunit; @@ -49,8 +50,6 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding public async Task TryUpdateModel_ReturnsFalse_IfModelValidationFails() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expectedMessage = PlatformNormalizer.NormalizeContent("The MyProperty field is required."); var binderProviders = new IModelBinderProvider[] { new SimpleTypeModelBinderProvider(), @@ -86,7 +85,7 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding // Assert Assert.False(result); var error = Assert.Single(modelState["MyProperty"].Errors); - Assert.Equal(expectedMessage, error.ErrorMessage); + Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("MyProperty"), error.ErrorMessage); } [Fact] @@ -613,8 +612,12 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding var model = new MyModel(); Func 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 - var exception = await Assert.ThrowsAsync( + var exception = await ExceptionAssert.ThrowsArgumentAsync( () => ModelBindingHelper.TryUpdateModelAsync( model, typeof(User), @@ -624,14 +627,9 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding GetModelBinderFactory(binder.Object), Mock.Of(), new Mock(MockBehavior.Strict).Object, - propertyFilter)); - - var expectedMessage = string.Format("The model's runtime type '{0}' is not assignable to the type '{1}'." + - Environment.NewLine + - "Parameter name: modelType", - model.GetType().FullName, - typeof(User).FullName); - Assert.Equal(expectedMessage, exception.Message); + propertyFilter), + "modelType", + expectedMessage); } [Theory] diff --git a/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/Internal/EnumerableWrapperProviderTest.cs b/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/Internal/EnumerableWrapperProviderTest.cs index 8a40b19bf9..0b594890c6 100644 --- a/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/Internal/EnumerableWrapperProviderTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/Internal/EnumerableWrapperProviderTest.cs @@ -2,8 +2,9 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; +using Microsoft.AspNetCore.Testing; using Xunit; namespace Microsoft.AspNetCore.Mvc.Formatters.Xml.Internal @@ -80,16 +81,14 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml.Internal public void ThrowsArugmentExceptionFor_ConcreteEnumerableOfT(Type declaredType) { // Arrange - var expectedMessage = - "The type must be an interface and must be or derive from 'IEnumerable`1'." + - $"{Environment.NewLine}Parameter name: sourceEnumerableOfT"; + var expectedMessage = "The type must be an interface and must be or derive from 'IEnumerable`1'."; // Act and Assert - var ex = Assert.Throws(() => new EnumerableWrapperProvider( - declaredType, - elementWrapperProvider: null)); - - Assert.Equal(expectedMessage, ex.Message); + ExceptionAssert.ThrowsArgument(() => new EnumerableWrapperProvider( + declaredType, + elementWrapperProvider: null), + "sourceEnumerableOfT", + expectedMessage); } } } \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/Internal/SerializableErrorWrapperProviderTest.cs b/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/Internal/SerializableErrorWrapperProviderTest.cs index 9311be16fd..fbf779a0aa 100644 --- a/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/Internal/SerializableErrorWrapperProviderTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/Internal/SerializableErrorWrapperProviderTest.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; +using Microsoft.AspNetCore.Testing; using Xunit; namespace Microsoft.AspNetCore.Mvc.Formatters.Xml.Internal @@ -43,13 +43,15 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml.Internal // Arrange var wrapperProvider = new SerializableErrorWrapperProvider(); 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", - typeof(SerializableErrorWrapper).Name); + + var expectedMessage = "The object to be wrapped must be of type " + + $"'{nameof(SerializableErrorWrapper)}' but was of type 'Person'."; // Act and Assert - var exception = Assert.Throws(() => wrapperProvider.Wrap(person)); - Assert.Equal(expectedMessage, exception.Message); + ExceptionAssert.ThrowsArgument( + () => wrapperProvider.Wrap(person), + "original", + expectedMessage); } } } \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/XmlDataContractSerializerInputFormatterTest.cs b/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/XmlDataContractSerializerInputFormatterTest.cs index 9a79c2d9f1..7626fd15a8 100644 --- a/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/XmlDataContractSerializerInputFormatterTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/XmlDataContractSerializerInputFormatterTest.cs @@ -10,7 +10,6 @@ using System.Threading.Tasks; using System.Xml; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Testing.xunit; using Moq; @@ -53,9 +52,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml public TestLevelOne TestOne { get; set; } } - [ConditionalTheory] - // Mono issue - https://github.com/aspnet/External/issues/18 - [FrameworkSkipCondition(RuntimeFrameworks.Mono)] [InlineData("application/xml", true)] [InlineData("application/*", false)] [InlineData("*/*", false)] @@ -90,9 +86,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml Assert.Equal(expectedCanRead, result); } - [ConditionalFact] - // Mono issue - https://github.com/aspnet/External/issues/18 - [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public void XmlDataContractSerializer_CachesSerializerForType() { // Arrange @@ -136,9 +129,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml 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() { // Arrange @@ -165,9 +155,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml Assert.Equal(expectedString, model.sampleString); } - [ConditionalFact] - // Mono issue - https://github.com/aspnet/External/issues/18 - [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task ReadAsync_ReadsComplexTypes() { // Arrange @@ -197,9 +184,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml Assert.Equal(expectedString, model.TestOne.sampleString); } - [ConditionalFact] - // Mono issue - https://github.com/aspnet/External/issues/18 - [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task ReadAsync_ReadsWhenMaxDepthIsModified() { // Arrange @@ -223,9 +207,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml Assert.Equal(expectedInt, model.SampleInt); } - [ConditionalFact] - [FrameworkSkipCondition(RuntimeFrameworks.Mono, - SkipReason = "Mono issue - https://github.com/aspnet/External/issues/18")] public async Task ReadAsync_ThrowsOnExceededMaxDepth() { // Arrange @@ -242,9 +223,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml 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() { // Arrange @@ -271,9 +249,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml 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() { // Arrange @@ -293,17 +268,10 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml 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() { // Arrange - var expectedException = TestPlatformHelper.IsMono ? typeof(SerializationException) : - 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 expectedException = typeof(XmlException); var inpStart = Encoding.Unicode.GetBytes("" + ""); byte[] inp = { 192, 193 }; @@ -319,20 +287,15 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml // Act 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() { // Arrange - var expectedException = TestPlatformHelper.IsMono ? typeof(SerializationException) : - 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 expectedException = typeof(XmlException); + var inputBytes = Encoding.UTF8.GetBytes("" + "1000"); @@ -352,12 +315,10 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml // Act 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() { // Arrange @@ -389,9 +350,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml 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() { // Arrange @@ -429,9 +387,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml Assert.Equal(expectedString, model.sampleString); } - [ConditionalFact] - // Mono issue - https://github.com/aspnet/External/issues/18 - [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task ReadAsync_ThrowsWhenNotConfiguredWithRootName() { // Arrange @@ -450,9 +405,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml 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() { // Arrange @@ -489,9 +441,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml Assert.Equal(expectedInt, model.SampleInt); } - [ConditionalFact] - // Mono issue - https://github.com/aspnet/External/issues/18 - [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task ReadAsync_ThrowsWhenNotConfiguredWithKnownTypes() { // Arrange @@ -511,9 +460,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml 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() { // Arrange diff --git a/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/XmlSerializerInputFormatterTest.cs b/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/XmlSerializerInputFormatterTest.cs index 459a32c906..f9630eb0a2 100644 --- a/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/XmlSerializerInputFormatterTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Formatters.Xml.Test/XmlSerializerInputFormatterTest.cs @@ -300,15 +300,13 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml Assert.True(context.HttpContext.Request.Body.CanRead); } + [ReplaceCulture] [Fact] public async Task ReadAsync_FallsbackToUTF8_WhenCharSet_NotInContentType() { // Arrange - var expectedException = TestPlatformHelper.IsMono ? typeof(InvalidOperationException) : - typeof(XmlException); - 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 expectedException = typeof(XmlException); + var expectedMessage = "The expected encoding 'utf-8' does not match the actual encoding 'utf-16LE'."; var inpStart = Encoding.Unicode.GetBytes("" + ""); @@ -329,14 +327,12 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml } [Fact] + [ReplaceCulture] public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream() { // Arrange - var expectedException = TestPlatformHelper.IsMono ? typeof(InvalidOperationException) : - typeof(XmlException); - 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 expectedException = typeof(XmlException); + var expectedMessage = "The expected encoding 'utf-16LE' does not match the actual encoding 'utf-8'."; var inputBytes = Encoding.UTF8.GetBytes("" + "1000"); diff --git a/test/Microsoft.AspNetCore.Mvc.FunctionalTests/DirectivesTest.cs b/test/Microsoft.AspNetCore.Mvc.FunctionalTests/DirectivesTest.cs index f4a00ec334..e6226ab171 100644 --- a/test/Microsoft.AspNetCore.Mvc.FunctionalTests/DirectivesTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.FunctionalTests/DirectivesTest.cs @@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests public async Task ViewsInheritsUsingsAndInjectDirectivesFromViewStarts() { // Arrange - var expected = @"Hello Person1"; + var expected = "Hello Person1"; // Act var body = await Client.GetStringAsync( @@ -34,7 +34,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests public async Task ViewInheritsBasePageFromViewStarts() { // Arrange - var expected = @"WriteLiteral says:layout:Write says:Write says:Hello Person2"; + var expected = "WriteLiteral says:layout:Write says:Write says:Hello Person2"; // Act var body = await Client.GetStringAsync("http://localhost/Directives/ViewInheritsBasePageFromViewImports"); diff --git a/test/Microsoft.AspNetCore.Mvc.FunctionalTests/HtmlGenerationTest.cs b/test/Microsoft.AspNetCore.Mvc.FunctionalTests/HtmlGenerationTest.cs index 6b3a17f940..16426ce2d6 100644 --- a/test/Microsoft.AspNetCore.Mvc.FunctionalTests/HtmlGenerationTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.FunctionalTests/HtmlGenerationTest.cs @@ -96,11 +96,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests #if GENERATE_BASELINES ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); #else - // Mono issue - https://github.com/aspnet/External/issues/19 - Assert.Equal( - PlatformNormalizer.NormalizeContent(expectedContent.Trim()), - responseContent, - ignoreLineEndingDifferences: true); + Assert.Equal(expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true); #endif } else @@ -112,11 +108,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); #else expectedContent = string.Format(expectedContent, forgeryToken); - // Mono issue - https://github.com/aspnet/External/issues/19 - Assert.Equal( - PlatformNormalizer.NormalizeContent(expectedContent.Trim()), - responseContent, - ignoreLineEndingDifferences: true); + Assert.Equal(expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true); #endif } } @@ -164,9 +156,8 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests #if GENERATE_BASELINES ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); #else - // Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal( - PlatformNormalizer.NormalizeContent(expectedContent.Trim()), + expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true); #endif @@ -180,11 +171,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); #else expectedContent = string.Format(expectedContent, forgeryToken); - // Mono issue - https://github.com/aspnet/External/issues/19 - Assert.Equal( - PlatformNormalizer.NormalizeContent(expectedContent.Trim()), - responseContent, - ignoreLineEndingDifferences: true); + Assert.Equal(expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true); #endif } } @@ -254,11 +241,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); #else expectedContent = string.Format(expectedContent, forgeryToken); - // Mono issue - https://github.com/aspnet/External/issues/19 - Assert.Equal( - PlatformNormalizer.NormalizeContent(expectedContent.Trim()), - responseContent, - ignoreLineEndingDifferences: true); + Assert.Equal(expectedContent.Trim(), responseContent, ignoreLineEndingDifferences: true); #endif } @@ -502,12 +485,12 @@ Products: Music Systems, Televisions (3)"; public async Task EditorTemplateWithNoModel_RendersWithCorrectMetadata() { // Arrange - var expected = PlatformNormalizer.NormalizeContent( + var expected = "" + Environment.NewLine + "" + Environment.NewLine + Environment.NewLine + "" + Environment.NewLine + "" + - Environment.NewLine + Environment.NewLine); + Environment.NewLine + Environment.NewLine; // Act var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingSharedEditorTemplate"); diff --git a/test/Microsoft.AspNetCore.Mvc.FunctionalTests/HtmlHelperOptionsTest.cs b/test/Microsoft.AspNetCore.Mvc.FunctionalTests/HtmlHelperOptionsTest.cs index ba2a59e1fb..d2bab1e71f 100644 --- a/test/Microsoft.AspNetCore.Mvc.FunctionalTests/HtmlHelperOptionsTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.FunctionalTests/HtmlHelperOptionsTest.cs @@ -76,11 +76,7 @@ True"; var body = await Client.GetStringAsync("http://localhost/HtmlHelperOptions/OverrideAppWideDefaultsInView"); // Assert - // Mono issue - https://github.com/aspnet/External/issues/19 - Assert.Equal( - PlatformNormalizer.NormalizeContent(expected), - body.Trim(), - ignoreLineEndingDifferences: true); + Assert.Equal(expected, body.Trim(), ignoreLineEndingDifferences: true); } } } diff --git a/test/Microsoft.AspNetCore.Mvc.FunctionalTests/XmlDataContractSerializerInputFormatterTest.cs b/test/Microsoft.AspNetCore.Mvc.FunctionalTests/XmlDataContractSerializerInputFormatterTest.cs index eec000aabf..7794702beb 100644 --- a/test/Microsoft.AspNetCore.Mvc.FunctionalTests/XmlDataContractSerializerInputFormatterTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.FunctionalTests/XmlDataContractSerializerInputFormatterTest.cs @@ -16,7 +16,7 @@ using Xunit; namespace Microsoft.AspNetCore.Mvc.FunctionalTests { - public class XmlDataContractSerializerInputFormatterTest : IClassFixture> + public class XmlDataContractSerializerInputFormatterTest : IClassFixture> { private readonly string errorMessageFormat = string.Format( "{{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), bool.TrueString); - public XmlDataContractSerializerInputFormatterTest(MvcTestFixture fixture) + public XmlDataContractSerializerInputFormatterTest(MvcTestFixture fixture) { Client = fixture.Client; } public HttpClient Client { get; } - [ConditionalFact] - // Mono issue - https://github.com/aspnet/External/issues/18 - [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task ThrowsOnInvalidInput_AndAddsToModelState() { // Arrange @@ -56,9 +53,6 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests data); } - [ConditionalFact] - // Mono issue - https://github.com/aspnet/External/issues/18 - [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task RequiredDataIsProvided_AndModelIsBound_NoValidationErrors() { // Arrange @@ -85,10 +79,6 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests 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() { // Arrange diff --git a/test/Microsoft.AspNetCore.Mvc.IntegrationTests/BodyValidationIntegrationTests.cs b/test/Microsoft.AspNetCore.Mvc.IntegrationTests/BodyValidationIntegrationTests.cs index 236ad49635..bf830a830e 100644 --- a/test/Microsoft.AspNetCore.Mvc.IntegrationTests/BodyValidationIntegrationTests.cs +++ b/test/Microsoft.AspNetCore.Mvc.IntegrationTests/BodyValidationIntegrationTests.cs @@ -118,6 +118,12 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests 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 var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext); @@ -127,21 +133,13 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests Assert.NotNull(boundPerson); Assert.False(modelState.IsValid); var modelStateErrors = CreateValidationDictionary(modelState); + Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["CompanyName"]); - Assert.Equal("The field Price must be between 20 and 100.", modelStateErrors["Price"]); - // Mono issue - https://github.com/aspnet/External/issues/19 - Assert.Equal( - PlatformNormalizer.NormalizeContent("The Category field is required."), - modelStateErrors["Category"]); - 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"]); + Assert.Equal(priceRange, modelStateErrors["Price"]); + Assert.Equal(categoryRequired, modelStateErrors["Category"]); + Assert.Equal(contactUsRequired, modelStateErrors["Contact"]); + Assert.Equal(detail2Required, modelStateErrors["ProductDetails.Detail2"]); + Assert.Equal(detail3Required, modelStateErrors["ProductDetails.Detail3"]); } [Fact] @@ -170,6 +168,8 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests var modelState = testContext.ModelState; + var productDetailsRequired = ValidationAttributeUtil.GetRequiredErrorMessage("ProductDetails"); + // Act var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext); @@ -179,9 +179,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests Assert.NotNull(boundPerson); Assert.False(modelState.IsValid); var modelStateErrors = CreateValidationDictionary(modelState); - Assert.Equal( - PlatformNormalizer.NormalizeContent("The ProductDetails field is required."), - modelStateErrors["ProductDetails"]); + Assert.Equal(productDetailsRequired, modelStateErrors["ProductDetails"]); } [Fact] @@ -287,6 +285,9 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests var modelState = testContext.ModelState; + var priceRange = ValidationAttributeUtil.GetRangeErrorMessage(100, 200, "Price"); + var contactLength = ValidationAttributeUtil.GetStringLengthErrorMessage(null, 10, "Contact"); + // Act var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext); @@ -297,10 +298,9 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests Assert.False(modelState.IsValid); var modelStateErrors = CreateValidationDictionary(modelState); Assert.Equal(2, modelStateErrors.Count); - Assert.Equal("The field Price must be between 100 and 200.", modelStateErrors["Price"]); - Assert.Equal( - "The field Contact must be a string with a maximum length of 10.", - modelStateErrors["Contact"]); + + Assert.Equal(priceRange, modelStateErrors["Price"]); + Assert.Equal(contactLength, modelStateErrors["Contact"]); } [Fact] @@ -379,6 +379,8 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests var modelState = testContext.ModelState; + var addressRequired = ValidationAttributeUtil.GetRequiredErrorMessage("Address"); + // Act var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext); @@ -390,8 +392,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests Assert.Equal("CustomParameter.Address", key); Assert.False(modelState.IsValid); var error = Assert.Single(modelState[key].Errors); - // Mono issue - https://github.com/aspnet/External/issues/19 - Assert.Equal(PlatformNormalizer.NormalizeContent("The Address field is required."), error.ErrorMessage); + Assert.Equal(addressRequired, error.ErrorMessage); } [Fact] @@ -623,6 +624,8 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests var httpContext = testContext.HttpContext; var modelState = testContext.ModelState; + var streetRequired = ValidationAttributeUtil.GetRequiredErrorMessage("Street"); + // Act var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext); @@ -637,8 +640,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests var street = entry.Value; Assert.Equal(ModelValidationState.Invalid, street.ValidationState); var error = Assert.Single(street.Errors); - // Mono issue - https://github.com/aspnet/External/issues/19 - Assert.Equal(PlatformNormalizer.NormalizeContent("The Street field is required."), error.ErrorMessage); + Assert.Equal(streetRequired, error.ErrorMessage); } private class Person3 diff --git a/test/Microsoft.AspNetCore.Mvc.IntegrationTests/CollectionModelBinderIntegrationTest.cs b/test/Microsoft.AspNetCore.Mvc.IntegrationTests/CollectionModelBinderIntegrationTest.cs index 2409df4a6c..067d73a8e9 100644 --- a/test/Microsoft.AspNetCore.Mvc.IntegrationTests/CollectionModelBinderIntegrationTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.IntegrationTests/CollectionModelBinderIntegrationTest.cs @@ -675,7 +675,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests Assert.Equal("Addresses[Key1].Street", kvp.Key); var entry = kvp.Value; 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] @@ -714,7 +714,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests var entry = Assert.Single(modelState).Value; 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 diff --git a/test/Microsoft.AspNetCore.Mvc.IntegrationTests/HeaderModelBinderIntegrationTest.cs b/test/Microsoft.AspNetCore.Mvc.IntegrationTests/HeaderModelBinderIntegrationTest.cs index daa19c1103..edeb35591a 100644 --- a/test/Microsoft.AspNetCore.Mvc.IntegrationTests/HeaderModelBinderIntegrationTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.IntegrationTests/HeaderModelBinderIntegrationTest.cs @@ -63,8 +63,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests var key = Assert.Single(modelState.Keys); Assert.Equal("CustomParameter.Address.Header", key); var error = Assert.Single(modelState[key].Errors); - // Mono issue - https://github.com/aspnet/External/issues/19 - Assert.Equal(PlatformNormalizer.NormalizeContent("The Street field is required."), error.ErrorMessage); + Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Street"), error.ErrorMessage); } [Fact] diff --git a/test/Microsoft.AspNetCore.Mvc.IntegrationTests/TryValidateModelIntegrationTest.cs b/test/Microsoft.AspNetCore.Mvc.IntegrationTests/TryValidateModelIntegrationTest.cs index 4be21f1089..2d505f5420 100644 --- a/test/Microsoft.AspNetCore.Mvc.IntegrationTests/TryValidateModelIntegrationTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.IntegrationTests/TryValidateModelIntegrationTest.cs @@ -76,6 +76,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests } [Fact] + [ReplaceCulture] public void TryValidateModel_CollectionsModel_ReturnsErrorsForInvalidProperties() { // Arrange @@ -107,6 +108,12 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests 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 var result = controller.TryValidateModel(model); @@ -114,26 +121,23 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests Assert.False(result); Assert.False(modelState.IsValid); var modelStateErrors = GetModelStateErrors(modelState); + 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( - PlatformNormalizer.NormalizeContent("The Category field is required."), - 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(priceRange, modelStateErrors["[0].Price"]); + Assert.Equal(categoryRequired, modelStateErrors["[0].Category"]); + AssertErrorEquals(contactUsMax + contactusRegEx, modelStateErrors["[0].Contact"]); 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( - PlatformNormalizer.NormalizeContent("The Category field is required."), - modelStateErrors["[1].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["[1].Contact"]); + expected.Split('.').OrderBy(item => item, StringComparer.Ordinal), + actual.Split('.').OrderBy(item => item, StringComparer.Ordinal)); } private TestController CreateController( @@ -150,14 +154,6 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests 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 GetModelStateErrors(ModelStateDictionary modelState) { var result = new Dictionary(); diff --git a/test/Microsoft.AspNetCore.Mvc.IntegrationTests/ValidationIntegrationTests.cs b/test/Microsoft.AspNetCore.Mvc.IntegrationTests/ValidationIntegrationTests.cs index 2ed7bd361f..d55d09496b 100644 --- a/test/Microsoft.AspNetCore.Mvc.IntegrationTests/ValidationIntegrationTests.cs +++ b/test/Microsoft.AspNetCore.Mvc.IntegrationTests/ValidationIntegrationTests.cs @@ -12,7 +12,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Newtonsoft.Json.Linq; using Xunit; @@ -112,7 +111,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests modelState, e => string.Equals(e.Key, "AccountId", StringComparison.OrdinalIgnoreCase)).Value; 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] @@ -1494,9 +1493,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests private static void AssertRequiredError(string key, ModelError error) { - // Mono issue - https://github.com/aspnet/External/issues/19 - Assert.Equal(PlatformNormalizer.NormalizeContent( - string.Format("The {0} field is required.", key)), error.ErrorMessage); + Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage(key), error.ErrorMessage); Assert.Null(error.Exception); } } diff --git a/test/Microsoft.AspNetCore.Mvc.Localization.Test/HtmlLocalizerTest.cs b/test/Microsoft.AspNetCore.Mvc.Localization.Test/HtmlLocalizerTest.cs index af908bc111..b78a0b3ed5 100644 --- a/test/Microsoft.AspNetCore.Mvc.Localization.Test/HtmlLocalizerTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Localization.Test/HtmlLocalizerTest.cs @@ -86,16 +86,12 @@ namespace Microsoft.AspNetCore.Mvc.Localization.Test new object[] { 10, new DateTime(2015, 10, 10) }, "Bonjour HtmlEncode[[10]] Bienvenue {1:yyyy}" }; - if (!TestPlatformHelper.IsMono) - { - // 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[] { + yield return new object[] { "{0:{{000}}}", new object[] { 10 }, "HtmlEncode[[{010}]]" }; + yield return new object[] { "Bonjour {0:'{{characters that should be escaped}}b'###'b'}", new object[] { 10 }, "Bonjour HtmlEncode[[{characters that should be escaped}b10b]]" - }; - } + }; } } @@ -131,22 +127,16 @@ namespace Microsoft.AspNetCore.Mvc.Localization.Test { get { - var data = new TheoryData + return new TheoryData { "{0", + "{" }; - - // Mono doesn't like { in an underlying string.Format on Mac. - if (!TestPlatformHelper.IsMac || !TestPlatformHelper.IsMono) - { - data.Add("{"); - } - - return data; } } [Theory] + [ReplaceCulture] [MemberData(nameof(InvalidResourceStringData))] public void HtmlLocalizer_HtmlWithInvalidResourceString_ContentThrowsException(string format) { diff --git a/test/Microsoft.AspNetCore.Mvc.Razor.Host.Test/InjectChunkVisitorTest.cs b/test/Microsoft.AspNetCore.Mvc.Razor.Host.Test/InjectChunkVisitorTest.cs index 366b2b6fe8..461000d75a 100644 --- a/test/Microsoft.AspNetCore.Mvc.Razor.Host.Test/InjectChunkVisitorTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Razor.Host.Test/InjectChunkVisitorTest.cs @@ -72,22 +72,22 @@ public MyType2 @MyPropertyName2 { get; private set; } { // Arrange var expected = string.Join(Environment.NewLine, -@"[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]", -@"public", +"[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]", +"public", @"#line 1 """"", -@"MyType1 MyPropertyName1", +"MyType1 MyPropertyName1", "", -@"#line default", -@"#line hidden", -@"{ get; private set; }", -@"[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]", -@"public", +"#line default", +"#line hidden", +"{ get; private set; }", +"[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]", +"public", @"#line 1 """"", -@"MyType2 @MyPropertyName2", +"MyType2 @MyPropertyName2", "", -@"#line default", -@"#line hidden", -@"{ get; private set; }", +"#line default", +"#line hidden", +"{ get; private set; }", ""); var writer = new CSharpCodeWriter(); var context = CreateContext(); diff --git a/test/Microsoft.AspNetCore.Mvc.Razor.Test/Internal/DefaultRoslynCompilationServiceTest.cs b/test/Microsoft.AspNetCore.Mvc.Razor.Test/Internal/DefaultRoslynCompilationServiceTest.cs index 6a320d51ad..b880459544 100644 --- a/test/Microsoft.AspNetCore.Mvc.Razor.Test/Internal/DefaultRoslynCompilationServiceTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.Razor.Test/Internal/DefaultRoslynCompilationServiceTest.cs @@ -69,7 +69,7 @@ this should fail"; { // Arrange var fileContent = "file content"; - var content = @"this should fail"; + var content = "this should fail"; var compilationService = GetRoslynCompilationService(); var relativeFileInfo = new RelativeFileInfo( diff --git a/test/Microsoft.AspNetCore.Mvc.TagHelpers.Test/ValidationSummaryTagHelperTest.cs b/test/Microsoft.AspNetCore.Mvc.TagHelpers.Test/ValidationSummaryTagHelperTest.cs index 064b248246..cd5c74a2df 100644 --- a/test/Microsoft.AspNetCore.Mvc.TagHelpers.Test/ValidationSummaryTagHelperTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.TagHelpers.Test/ValidationSummaryTagHelperTest.cs @@ -311,15 +311,13 @@ namespace Microsoft.AspNetCore.Mvc.TagHelpers var validationSummaryTagHelper = new ValidationSummaryTagHelper(generator); var validationTypeName = typeof(ValidationSummary).FullName; - var expectedMessage = - $@"The value of argument 'value' ({validationSummary}) is invalid for Enum type '{validationTypeName}'. -Parameter name: value"; + var expectedMessage = $"The value of argument 'value' ({validationSummary}) is invalid for Enum type '{validationTypeName}'."; // Act & Assert - var ex = Assert.Throws( + ExceptionAssert.ThrowsArgument( + () => validationSummaryTagHelper.ValidationSummary = validationSummary, "value", - () => { validationSummaryTagHelper.ValidationSummary = validationSummary; }); - Assert.Equal(expectedMessage, ex.Message); + expectedMessage); } private static ViewContext CreateViewContext() diff --git a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Internal/DefaultDisplayTemplatesTest.cs b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Internal/DefaultDisplayTemplatesTest.cs index 5fc82e8bdb..bf9c3446ca 100644 --- a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Internal/DefaultDisplayTemplatesTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Internal/DefaultDisplayTemplatesTest.cs @@ -122,9 +122,9 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Internal { // Arrange var expected = "
HtmlEncode[[Property1]]
" + Environment.NewLine + - "
"+ Environment.NewLine + - "
HtmlEncode[[Property3]]
"+ Environment.NewLine + - "
"+ Environment.NewLine; + "
" + Environment.NewLine + + "
HtmlEncode[[Property3]]
" + Environment.NewLine + + "
" + Environment.NewLine; var model = new DefaultTemplatesUtilities.ObjectWithScaffoldColumn(); var viewEngine = new Mock(MockBehavior.Strict); diff --git a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Internal/DefaultEditorTemplatesTest.cs b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Internal/DefaultEditorTemplatesTest.cs index d00679cb0c..10d6eb53d2 100644 --- a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Internal/DefaultEditorTemplatesTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Internal/DefaultEditorTemplatesTest.cs @@ -15,7 +15,6 @@ using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.TestCommon; using Microsoft.AspNetCore.Mvc.ViewEngines; -using Microsoft.AspNetCore.Testing; using Moq; using Xunit; @@ -610,17 +609,15 @@ Environment.NewLine; [InlineData("datetime", null, "2000-01-02T03:04:05.006+00:00")] [InlineData("datetime-local", null, "2000-01-02T03:04:05.006")] [InlineData("time", "{0:t}", "03:04:05.006")] - [ReplaceCulture] public void Editor_FindsCorrectDateOrTimeTemplate(string dataTypeName, string editFormatString, string expected) { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expectedInput = PlatformNormalizer.NormalizeContent( - ""); + "]]\" value=\"HtmlEncode[[" + expected + "]]\" />"; var offset = TimeSpan.FromHours(0); var model = new DateTimeOffset( @@ -666,17 +663,16 @@ Environment.NewLine; [InlineData("datetime", null, "2000-01-02T03:04:05.060+00:00")] [InlineData("datetime-local", null, "2000-01-02T03:04:05.060")] [InlineData("time", "{0:t}", "03:04:05.060")] - [ReplaceCulture] public void Editor_AppliesRfc3339(string dataTypeName, string editFormatString, string expected) { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expectedInput = PlatformNormalizer.NormalizeContent( + var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("DateTimeOffset"); + var expectedInput = ""); + "]]\" value=\"HtmlEncode[[" + expected + "]]\" />"; // Place DateTime-local value in current timezone. 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) { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expectedInput = PlatformNormalizer.NormalizeContent( - ""); + "]]\" value=\"HtmlEncode[[Formatted as 2000-01-02T03:04:05.0600000+00:00]]\" />"; var offset = TimeSpan.FromHours(0); var model = new DateTimeOffset( diff --git a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/RemoteAttributeTest.cs b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/RemoteAttributeTest.cs index 4526ddc46e..bde6e7b5c7 100644 --- a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/RemoteAttributeTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/RemoteAttributeTest.cs @@ -230,13 +230,13 @@ namespace Microsoft.AspNetCore.Mvc { // Arrange 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 - var exception = Assert.Throws( + ExceptionAssert.ThrowsArgument( + () => attribute.FormatAdditionalFieldsForClientValidation(property), "property", - () => attribute.FormatAdditionalFieldsForClientValidation(property)); - Assert.Equal(expected, exception.Message); + expectedMessage); } [Theory] @@ -244,13 +244,13 @@ namespace Microsoft.AspNetCore.Mvc public void FormatPropertyForClientValidation_WithInvalidPropertyName_Throws(string property) { // Arrange - var expected = "Value cannot be null or empty." + Environment.NewLine + "Parameter name: property"; + var expected = "Value cannot be null or empty."; // Act & Assert - var exception = Assert.Throws( + ExceptionAssert.ThrowsArgument( + () => RemoteAttribute.FormatPropertyForClientValidation(property), "property", - () => RemoteAttribute.FormatPropertyForClientValidation(property)); - Assert.Equal(expected, exception.Message); + expected); } [Fact] diff --git a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperCheckboxTest.cs b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperCheckboxTest.cs index 71a527ec72..2c050dd206 100644 --- a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperCheckboxTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperCheckboxTest.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.TestCommon; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.WebEncoders.Testing; using Xunit; @@ -20,12 +21,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxOverridesCalculatedValuesWithValuesFromHtmlAttributes() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + @"value=""HtmlEncode[[false]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); // Act @@ -41,12 +41,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxExplicitParametersOverrideDictionary_ForValueInModel() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + @"value=""HtmlEncode[[false]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); @@ -80,13 +79,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxWithInvalidBooleanThrows() { // Arrange - var expected = "String was not recognized as a valid Boolean."; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); // Act & Assert var ex = Assert.Throws( () => helper.CheckBox("Property2", isChecked: null, htmlAttributes: null)); - Assert.Equal(expected, ex.Message); + Assert.Contains("Boolean", ex.Message); } [Fact] @@ -95,29 +93,26 @@ namespace Microsoft.AspNetCore.Mvc.Rendering // Arrange 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." + - "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + - Environment.NewLine + "Parameter name: expression"; + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value."; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); // Act & Assert - var ex = Assert.Throws( + ExceptionAssert.ThrowsArgument( + () => helper.CheckBox(null, isChecked: true, htmlAttributes: null), "expression", - () => helper.CheckBox(null, isChecked: true, htmlAttributes: null)); - - Assert.Equal(expected, ex.Message); + expected); } [Fact] public void CheckBoxCheckedWithOnlyName_GeneratesExpectedValue() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + @"value=""HtmlEncode[[true]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); // Act @@ -131,12 +126,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBox_WithCanRenderAtEndOfFormSet_DoesNotGenerateInlineHiddenTag() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + @"value=""HtmlEncode[[true]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); helper.ViewContext.FormContext.CanRenderAtEndOfForm = true; @@ -157,11 +151,10 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxUsesAttemptedValueFromModelState() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @"" + - @""); + @""; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); helper.ViewData.ModelState.SetModelValue("Property1", new string[] { "false" }, "false"); @@ -341,11 +334,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxGeneratesUnobtrusiveValidationAttributes() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @"" + - @""); + @""; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData()); // Act @@ -359,13 +352,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxReplacesUnderscoresInHtmlAttributesWithDashes() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var htmlAttributes = new { Property1_Property3 = "Property3ObjValue" }; @@ -418,12 +410,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxInTemplate_WithEmptyExpression_GeneratesExpectedValue() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + @"value=""HtmlEncode[[false]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(model: false); var attributes = new Dictionary { { "Property3", "Property3Value" } }; helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix"; @@ -439,13 +431,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxWithComplexExpressionsEvaluatesValuesInViewDataDictionary() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + @" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData()); // Act @@ -459,11 +450,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxForWithNullContainer_TreatsBooleanAsFalse() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @"" + - @""); + @""; var viewData = GetTestModelViewData(); var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData); 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) { // Arrange + var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1"); // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @"" + - @""); + @""; expected = string.Format(expected, expectedChecked); var viewData = GetTestModelViewData(); @@ -507,12 +499,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxForOverridesCalculatedParametersWithValuesFromHtmlAttributes() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( + var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property3"); + var expected = @""); + @"value=""HtmlEncode[[false]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); // Act @@ -526,11 +518,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxForGeneratesUnobtrusiveValidationAttributes() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @"" + - @""); + @""; var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider(); var viewDataDictionary = new ViewDataDictionary(metadataProvider) { @@ -551,11 +543,11 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxFor_UsesModelStateAttemptedValue(string attemptedValue, string expectedChecked) { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @"" + - @""); + @""; expected = string.Format(expected, expectedChecked); var viewData = GetTestModelViewData(); @@ -573,12 +565,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxFor_WithObjectAttribute_MapsUnderscoresInNamesToDashes() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var htmlAttributes = new { Property1_Property3 = "Property3ObjValue" }; @@ -593,12 +585,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxFor_WithAttributeDictionary_GeneratesExpectedAttributes() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); var attributes = new Dictionary { { "Property3", "Property3Value" } }; @@ -613,12 +605,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxForInTemplate_GeneratesExpectedValue() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + @"value=""HtmlEncode[[false]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix"; var attributes = new Dictionary { { "Property3", "PropValue" } }; @@ -634,12 +626,12 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void CheckBoxFor_WithComplexExpressions_DoesNotUseValuesFromViewDataDictionary() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + @"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData()); // Act diff --git a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperHiddenTest.cs b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperHiddenTest.cs index 8c2946c47e..43566e6ffb 100644 --- a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperHiddenTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperHiddenTest.cs @@ -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 " + "Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." + - "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + - Environment.NewLine + "Parameter name: expression"; + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value."; // Act and Assert ExceptionAssert.ThrowsArgument( @@ -449,10 +448,10 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void HiddenGeneratesUnobtrusiveValidation() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + var requiredMessage = new RequiredAttribute().FormatErrorMessage("Property2"); + var expected = + $@""; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues()); // Act @@ -713,10 +712,10 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void HiddenFor_GeneratesUnobtrusiveValidationAttributes() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property2"); + var expected = + $@""; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithErrors()); // Act diff --git a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperPasswordTest.cs b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperPasswordTest.cs index 96a3e2edc9..192b50e282 100644 --- a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperPasswordTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperPasswordTest.cs @@ -131,16 +131,15 @@ namespace Microsoft.AspNetCore.Mvc.Rendering var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues()); var name = 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." + - "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + - Environment.NewLine + "Parameter name: expression"; + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value."; // Act and Assert ExceptionAssert.ThrowsArgument( () => helper.Password(name, value, htmlAttributes: null), "expression", - expected); + expectedMessage); } [Fact] @@ -169,10 +168,10 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void PasswordGeneratesUnobtrusiveValidation() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property2"); + var expected = + $@""; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues()); // Act @@ -278,10 +277,10 @@ namespace Microsoft.AspNetCore.Mvc.Rendering public void PasswordFor_GeneratesUnobtrusiveValidationAttributes() { // Arrange - // Mono issue - https://github.com/aspnet/External/issues/19 - var expected = PlatformNormalizer.NormalizeContent( - @""); + var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property2"); + var expected = + $@""; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithErrors()); // Act diff --git a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperSelectTest.cs b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperSelectTest.cs index bb9b443164..969cb70c38 100644 --- a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperSelectTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/Rendering/HtmlHelperSelectTest.cs @@ -375,15 +375,14 @@ namespace Microsoft.AspNetCore.Mvc.Rendering // Arrange 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." + - "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + - Environment.NewLine + "Parameter name: expression"; + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value."; var helper = DefaultTemplatesUtilities.GetHtmlHelper(); // Act & Assert - var ex = Assert.Throws( + ExceptionAssert.ThrowsArgument( + () => helper.DropDownList(null, selectList: null, optionLabel: null, htmlAttributes: null), "expression", - () => helper.DropDownList(null, selectList: null, optionLabel: null, htmlAttributes: null)); - Assert.Equal(expected, ex.Message); + expected); } [Theory] diff --git a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/ViewFeatures/DefaultHtmlGeneratorTest.cs b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/ViewFeatures/DefaultHtmlGeneratorTest.cs index 90ab2aaf10..933623f246 100644 --- a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/ViewFeatures/DefaultHtmlGeneratorTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/ViewFeatures/DefaultHtmlGeneratorTest.cs @@ -16,6 +16,7 @@ using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Mvc.TestCommon; using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Options; using Moq; using Xunit; @@ -76,21 +77,19 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures var viewContext = GetViewContext(model: null, metadataProvider: metadataProvider); var modelExplorer = metadataProvider.GetModelExplorerForType(typeof(string), model: null); - 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." + - "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + - Environment.NewLine + "Parameter name: expression"; + 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." + + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value."; // Act and assert - var ex = Assert.Throws( - "expression", + ExceptionAssert.ThrowsArgument( () => htmlGenerator.GetCurrentValues( viewContext, modelExplorer, expression: null, - allowMultiple: true)); - - Assert.Equal(expected, ex.Message); + allowMultiple: true), + "expression", + expected); } [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 " + "Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." + - "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + - Environment.NewLine + "Parameter name: expression"; + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value."; // Act and assert - var ex = Assert.Throws( - "expression", + ExceptionAssert.ThrowsArgument( () => htmlGenerator.GenerateSelect( viewContext, modelExplorer, @@ -117,9 +114,9 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures null, new List(), true, - null)); - - Assert.Equal(expected, ex.Message); + null), + "expression", + expected); } [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 " + "Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." + - "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + - Environment.NewLine + "Parameter name: expression"; + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value."; // Act and assert - var ex = Assert.Throws( - "expression", + ExceptionAssert.ThrowsArgument( () => htmlGenerator.GenerateTextArea( viewContext, modelExplorer, null, 1, 1, - null)); - - Assert.Equal(expected, ex.Message); + null), + "expression", + expected); } [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 " + "Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." + - "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value." + - Environment.NewLine + "Parameter name: expression"; + "IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value."; // Act and assert - var ex = Assert.Throws( + ExceptionAssert.ThrowsArgument( + () => htmlGenerator.GenerateValidationMessage(viewContext, null, null, "Message", "tag", null), "expression", - () => htmlGenerator.GenerateValidationMessage(viewContext, null, null, "Message", "tag", null)); - - Assert.Equal(expected, ex.Message); + expected); } [Theory] diff --git a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/project.json b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/project.json index 611da03eaf..e44deb8bc8 100644 --- a/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/project.json +++ b/test/Microsoft.AspNetCore.Mvc.ViewFeatures.Test/project.json @@ -16,6 +16,7 @@ "version": "1.1.0-*", "type": "build" }, + "Microsoft.AspNetCore.Mvc.ViewFeatures": "1.1.0-*", "Microsoft.AspNetCore.Testing": "1.1.0-*", "Microsoft.Extensions.DependencyInjection": "1.1.0-*", "Microsoft.Extensions.DiagnosticAdapter": "1.1.0-*", diff --git a/test/Microsoft.AspNetCore.Mvc.WebApiCompatShimTest/HttpRequestMessage/HttpRequestMessageExtensionsTest.cs b/test/Microsoft.AspNetCore.Mvc.WebApiCompatShimTest/HttpRequestMessage/HttpRequestMessageExtensionsTest.cs index d2c6aed02c..90f1cdfa9f 100644 --- a/test/Microsoft.AspNetCore.Mvc.WebApiCompatShimTest/HttpRequestMessage/HttpRequestMessageExtensionsTest.cs +++ b/test/Microsoft.AspNetCore.Mvc.WebApiCompatShimTest/HttpRequestMessage/HttpRequestMessageExtensionsTest.cs @@ -23,10 +23,7 @@ namespace System.Net.Http var ex = Assert.Throws( () => request.CreateResponse(HttpStatusCode.OK, CreateValue(), "foo/bar; param=value")); - Assert.Equal( - TestPlatformHelper.IsMono ? - "Invalid format." : - "The format of value 'foo/bar; param=value' is invalid.", ex.Message); + Assert.Contains("foo/bar; param=value", ex.Message); } [Fact]