Exemplo n.º 1
0
        public void ViewLocalizer_UseIndexerWithArguments_ReturnsLocalizedString()
        {
            // Arrange
            var applicationEnvironment = new Mock<IApplicationEnvironment>();
            applicationEnvironment.Setup(a => a.ApplicationName).Returns("TestApplication");

            var localizedString = new LocalizedString("Hello", "Bonjour test");

            var htmlLocalizer = new Mock<IHtmlLocalizer>();
            htmlLocalizer.Setup(h => h["Hello", "test"]).Returns(localizedString);

            var htmlLocalizerFactory = new Mock<IHtmlLocalizerFactory>();
            htmlLocalizerFactory.Setup(
                h => h.Create("example", "TestApplication")).Returns(htmlLocalizer.Object);

            var viewLocalizer = new ViewLocalizer(htmlLocalizerFactory.Object, applicationEnvironment.Object);

            var view = new Mock<IView>();
            view.Setup(v => v.Path).Returns("example");
            var viewContext = new ViewContext();
            viewContext.View = view.Object;

            viewLocalizer.Contextualize(viewContext);

            // Act
            var actualLocalizedString = viewLocalizer["Hello", "test"];

            // Assert
            Assert.Equal(localizedString, actualLocalizedString);
        }
        //[TestMethod]
        public void Should_Read_MissingResource_FallbackToResourceName()
        {
            InitLocalizer("en-AU");
            LocalizedString result = localizer.GetString("No resource string");

            Assert.AreEqual("No resource string", result);
            Assert.IsTrue(result.ResourceNotFound);
        }
        //[TestMethod]
        public void Should_Read_ResourceMissingCulture_FallbackToResourceName()
        {
            InitLocalizer("zh-CN");
            LocalizedString result = localizer.GetString("Empty");

            Assert.AreEqual("Empty", result);
            Assert.IsTrue(result.ResourceNotFound);
        }
Exemplo n.º 4
0
        public MenuItemBuilder Add(LocalizedString caption, Action<MenuItemBuilder> builderAction)
        {
            _addActions.Add(item =>
            {
                var menuItem = new MenuItemDefinition { Id = caption.Name };
                var itemBuilder = new MenuItemBuilder(menuItem);
                itemBuilder.Caption(caption);
                builderAction(itemBuilder);
                item.Items.Add(menuItem);
            });

            return this;
        }
Exemplo n.º 5
0
        public void HtmlLocalizer_UseIndexer_ReturnsLocalizedString()
        {
            // Arrange
            var localizedString = new LocalizedString("Hello", "Bonjour");
            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s["Hello"]).Returns(localizedString);

            var htmlLocalizer = new HtmlLocalizer(stringLocalizer.Object, new CommonTestEncoder());

            // Act
            var actualLocalizedString = htmlLocalizer["Hello"];

            // Assert
            Assert.Equal(localizedString, actualLocalizedString);
        }
        //[TestMethod]
        public void Should_Read_Color_NoFallback()
        {
            InitLocalizer("en-AU");
            LocalizedString result = localizer.GetString("Color");

            Assert.AreEqual("Colour (specific)", result);

            InitLocalizer("fr");
            result = localizer.GetString("Color");
            Assert.AreEqual("Couleur (neutre)", result);

            InitLocalizer(CultureInfo.InvariantCulture.ThreeLetterISOLanguageName);
            result = localizer.GetString("Color");
            Assert.AreEqual("Color (invariant)", result);
        }
Exemplo n.º 7
0
        public void HtmlLocalizer_UseIndexer_ReturnsLocalizedHtmlString()
        {
            // Arrange
            var localizedString = new LocalizedString("Hello", "Bonjour");
            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s["Hello"]).Returns(localizedString);

            var htmlLocalizer = new HtmlLocalizer(stringLocalizer.Object);

            // Act
            var actualLocalizedHtmlString = htmlLocalizer["Hello"];

            // Assert
            Assert.Equal(localizedString.Name, actualLocalizedHtmlString.Name);
            Assert.Equal(localizedString.Value, actualLocalizedHtmlString.Value);
        }
Exemplo n.º 8
0
        public NavigationBuilder Add(LocalizedString caption, string position, Action<NavigationItemBuilder> itemBuilder, IEnumerable<string> classes = null)
        {
            var childBuilder = new NavigationItemBuilder();

            childBuilder.Caption(caption);
            childBuilder.Position(position);
            itemBuilder(childBuilder);
            Contained.AddRange(childBuilder.Build());

            if (classes != null)
            {
                foreach (var className in classes)
                    childBuilder.AddClass(className);
            }

            return this;
        }
        public void Should_Read_Color_FallbackToParent()
        {
            InitLocalizer("fr-FR");
            LocalizedString result = localizer.GetString("Color");

            Assert.AreEqual("Couleur (neutre)", result);
            Assert.IsFalse(result.ResourceNotFound);

            InitLocalizer("en-NZ");
            result = localizer.GetString("Color");
            Assert.AreEqual("Color (neutral)", result);
            Assert.IsFalse(result.ResourceNotFound);

            InitLocalizer("zh-CN");
            result = localizer.GetString("Color");
            Assert.AreEqual("Color (invariant)", result);
            Assert.IsFalse(result.ResourceNotFound);
        }
Exemplo n.º 10
0
        public void HtmlLocalizerOfTTest_UseIndexer_ReturnsLocalizedString()
        {
            // Arrange
            var localizedString = new LocalizedString("Hello", "Bonjour");

            var htmlLocalizer = new Mock<IHtmlLocalizer>();
            htmlLocalizer.Setup(h => h["Hello"]).Returns(localizedString);

            var htmlLocalizerFactory = new Mock<IHtmlLocalizerFactory>();
            htmlLocalizerFactory.Setup(h => h.Create(typeof(TestClass)))
                .Returns(htmlLocalizer.Object);

            var htmlLocalizerOfT = new HtmlLocalizer<TestClass>(htmlLocalizerFactory.Object);

            // Act
            var actualLocalizedString = htmlLocalizerOfT["Hello"];

            // Assert
            Assert.Equal(localizedString, actualLocalizedString);
        }
            public int Compare(object x, object y)
            {
                LocalizedString lsX = (LocalizedString)x;
                LocalizedString lsY = (LocalizedString)y;

                if (ReferenceEquals(lsX, lsY))
                {
                    return(0);
                }
                if (lsX.Name == lsY.Name && lsX.Value == lsY.Value && lsX.ResourceNotFound == lsY.ResourceNotFound)
                {
                    return(0);
                }
                int result = StringComparer.CurrentCulture.Compare(lsX.Name, lsY.Name);

                if (result != 0)
                {
                    return(result);
                }
                result = StringComparer.CurrentCulture.Compare(lsX.Value, lsY.Value);
                return(result != 0 ? result : lsX.ResourceNotFound.CompareTo(lsY.ResourceNotFound));
            }
Exemplo n.º 12
0
        public void HtmlLocalizerOfTTest_UseIndexerWithArguments_ReturnsLocalizedString()
        {
            // Arrange
            var applicationEnvironment = new Mock<IApplicationEnvironment>();
            applicationEnvironment.Setup(a => a.ApplicationName).Returns("TestApplication");

            var localizedString = new LocalizedString("Hello", "Bonjour test");

            var htmlLocalizer = new Mock<IHtmlLocalizer>();
            htmlLocalizer.Setup(h => h["Hello", "test"]).Returns(localizedString);

            var htmlLocalizerFactory = new Mock<IHtmlLocalizerFactory>();
            htmlLocalizerFactory.Setup(h => h.Create(typeof(TestClass)))
                .Returns(htmlLocalizer.Object);

            var htmlLocalizerOfT = new HtmlLocalizer<TestClass>(htmlLocalizerFactory.Object);

            // Act
            var actualLocalizedString = htmlLocalizerOfT["Hello", "test"];

            // Assert
            Assert.Equal(localizedString, actualLocalizedString);
        }
Exemplo n.º 13
0
 protected virtual LocalizedHtmlString ToHtmlString(LocalizedString result, object[] arguments) =>
     new LocalizedHtmlString(result.Name, result.Value, result.ResourceNotFound, arguments);
Exemplo n.º 14
0
        public void HtmlLocalizer_HtmlWithArguments_ReturnsLocalizedHtml(
            string format,
            object[] arguments,
            string expectedText)
        {
            // Arrange
            var localizedString = new LocalizedString("Hello", format);

            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s["Hello"]).Returns(localizedString);

            var htmlLocalizer = new HtmlLocalizer(stringLocalizer.Object, new CommonTestEncoder());

            // Act
            var localizedHtmlString = htmlLocalizer.Html("Hello", arguments);

            // Assert
            Assert.NotNull(localizedHtmlString);
            Assert.Equal(expectedText, localizedHtmlString.Value);
        }
 public OrchardCommandHostRetryException(LocalizedString message)
     : base(message)
 {
 }
Exemplo n.º 16
0
        public void HtmlLocalizer_HtmlWithInvalidResourcestring_ThrowsException(string format)
        {
            // Arrange
            var localizedString = new LocalizedString("Hello", format);

            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s["Hello"]).Returns(localizedString);

            var htmlLocalizer = new HtmlLocalizer(stringLocalizer.Object, new CommonTestEncoder());

            // Act
            var exception = Assert.Throws<FormatException>(() => htmlLocalizer.Html("Hello", new object[] { }));

            // Assert
            Assert.NotNull(exception);
            Assert.Equal("Input string was not in a correct format.", exception.Message);
        }
Exemplo n.º 17
0
 public NavigationBuilder Add(LocalizedString caption, IEnumerable<string> classes = null)
 {
     return Add(caption, null, x => { }, classes);
 }
Exemplo n.º 18
0
        public void AddValidation_WithErrorMessageLocalizerFactoryLocalizerProviderAndDisplayName_SetsAttributesAsExpected()
        {
            // Arrange
            var expected = "Error about 'Length' from localizer.";
            var attribute = new RemoteAttribute("Action", "Controller")
            {
                HttpMethod = "POST",
                ErrorMessage = "Error about '{0}' from override.",
            };

            var url = "/Controller/Action";
            var metadataProvider = new TestModelMetadataProvider();
            metadataProvider
                .ForProperty(typeof(string), nameof(string.Length))
                .DisplayDetails(d => d.DisplayName = () => "Display Length");
            var context = GetValidationContextWithLocalizerFactory(url, metadataProvider);

            var localizedString = new LocalizedString("Fred", expected);
            var localizer = new Mock<IStringLocalizer>(MockBehavior.Strict);
            localizer
                .Setup(l => l["Error about '{0}' from override.", "Display Length"])
                .Returns(localizedString)
                .Verifiable();
            var options = context.ActionContext.HttpContext.RequestServices
                .GetRequiredService<IOptions<MvcDataAnnotationsLocalizationOptions>>();
            options.Value.DataAnnotationLocalizerProvider = (type, factory) => localizer.Object;

            // Act
            attribute.AddValidation(context);

            // Assert
            localizer.VerifyAll();

            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
                kvp =>
                {
                    Assert.Equal("data-val-remote", kvp.Key);
                    Assert.Equal(expected, kvp.Value);
                },
                kvp =>
                {
                    Assert.Equal("data-val-remote-additionalfields", kvp.Key);
                    Assert.Equal("*.Length", kvp.Value);
                },
                kvp => { Assert.Equal("data-val-remote-type", kvp.Key); Assert.Equal("POST", kvp.Value); },
                kvp => { Assert.Equal("data-val-remote-url", kvp.Key); Assert.Equal(url, kvp.Value); });
        }
 public OrchardCommandHostRetryException(LocalizedString message, Exception innerException)
     : base(message, innerException)
 {
 }
Exemplo n.º 20
0
 public OrchardSecurityException(LocalizedString message) : base(message) { }
Exemplo n.º 21
0
        public void MaxLengthAttribute_AddValidation_StringLocalizer_ReturnsLocalizedErrorString()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var errorKey = metadata.GetDisplayName();
            var attribute = new MaxLengthAttribute(10);
            attribute.ErrorMessage = errorKey;
            var localizedString = new LocalizedString(errorKey, "Longueur est invalide");
            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s[errorKey, metadata.GetDisplayName(), attribute.Length]).Returns(localizedString);

            var expectedMessage = "Longueur est invalide";

            var adapter = new MaxLengthAttributeAdapter(attribute, stringLocalizer.Object);

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());

            // Act
            adapter.AddValidation(context);

            // Assert
            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
                kvp => { Assert.Equal("data-val-maxlength", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
                kvp => { Assert.Equal("data-val-maxlength-max", kvp.Key); Assert.Equal("10", kvp.Value); });
        }
Exemplo n.º 22
0
 public MenuItemBuilder Caption(LocalizedString caption)
 {
     _item.Caption = caption;
     return this;
 }
        public void Validate_IsValidFalse_StringLocalizerReturnsLocalizerErrorMessage()
        {
            // Arrange
            var metadata = _metadataProvider.GetMetadataForType(typeof(string));
            var container = "Hello";
            var model = container.Length;

            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Setup(a => a.IsValid(model)).Returns(false);

            attribute.Object.ErrorMessage = "Length";

            var localizedString = new LocalizedString("Length", "Longueur est invalide");
            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s["Length"]).Returns(localizedString);

            var validator = new DataAnnotationsModelValidator(attribute.Object, stringLocalizer.Object);
            var validationContext = new ModelValidationContext()
            {
                Metadata = metadata,
                Container = container,
                Model = model,
            };

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            var validationResult = result.Single();
            Assert.Equal("", validationResult.MemberName);
            Assert.Equal("Longueur est invalide", validationResult.Message);
        }
Exemplo n.º 24
0
 public OrchardSecurityException(LocalizedString message, Exception innerException) : base(message, innerException) { }
Exemplo n.º 25
0
 public GroupInfo(LocalizedString name)
 {
     Id = name.Name;
     Name = name;
 }
Exemplo n.º 26
0
 /// <summary>
 /// Creates a new <see cref="LocalizedHtmlString"/> for a <see cref="LocalizedString"/>.
 /// </summary>
 /// <param name="result">The <see cref="LocalizedString"/>.</param>
 protected virtual LocalizedHtmlString ToHtmlString(LocalizedString result) =>
     new LocalizedHtmlString(result.Name, result.Value, result.ResourceNotFound);
        public void Validate_IsValidFalse_StringLocalizerReturnsLocalizerErrorMessage()
        {
            // Arrange
            var metadata = _metadataProvider.GetMetadataForType(typeof(string));
            var container = "Hello";

            var attribute = new MaxLengthAttribute(4);
            attribute.ErrorMessage = "{0} should have no more than {1} characters.";

            var localizedString = new LocalizedString(attribute.ErrorMessage, "Longueur est invalide : 4");
            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s[attribute.ErrorMessage, It.IsAny<object[]>()]).Returns(localizedString);

            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute,
                stringLocalizer.Object);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: container,
                model: "abcde");

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            var validationResult = result.Single();
            Assert.Equal("", validationResult.MemberName);
            Assert.Equal("Longueur est invalide : 4", validationResult.Message);
        }
Exemplo n.º 28
0
 public static LocalizedString OrDefault(this string text, LocalizedString defaultValue)
 {
     return string.IsNullOrEmpty(text)
         ? defaultValue
         : new LocalizedString(null, text);
 }
Exemplo n.º 29
0
 public NavigationBuilder Add(LocalizedString caption, Action<NavigationItemBuilder> itemBuilder, IEnumerable<string> classes = null)
 {
     return Add(caption, null, itemBuilder, classes);
 }
Exemplo n.º 30
0
 public OrchardException(LocalizedString message, Exception innerException)
     : base(message, innerException)
 {
     _localizedMessage = message;
 }
Exemplo n.º 31
0
 public NavigationItemBuilder Caption(LocalizedString caption)
 {
     _item.Text = caption;
     return this;
 }
Exemplo n.º 32
0
 public OrchardException(LocalizedString message)
     : base(message)
 {
     _localizedMessage = message;
 }
        public void ClientRulesWithMaxLengthAttribute_StringLocalizer_ReturnsLocalizedErrorString()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");
            var errorKey = metadata.GetDisplayName();
            var attribute = new MaxLengthAttribute(10);
            attribute.ErrorMessage = errorKey;

            var localizedString = new LocalizedString(errorKey, "Longueur est invalide");
            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s[errorKey]).Returns(localizedString);

            var adapter = new MaxLengthAttributeAdapter(attribute, stringLocalizer.Object);
            var serviceCollection = new ServiceCollection();
            var requestServices = serviceCollection.BuildServiceProvider();
            var context = new ClientModelValidationContext(metadata, provider, requestServices);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("maxlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(10, rule.ValidationParameters["max"]);
            Assert.Equal("Longueur est invalide", rule.ErrorMessage);
        }