Exemplo n.º 1
0
        public void WithPortugueseTranslation_Should_AddTranslation()
        {
            var settings = new ValidatorSettings();

            settings.WithPortugueseTranslation();
            TranslationTestHelpers.ShouldContainSingleTranslation(settings.Translations, "Portuguese", Translation.Portuguese);
        }
            public void Should_PassAllEntries()
            {
                var validatorSettings = new ValidatorSettings();

                var dictionary = new Dictionary <string, string>()
                {
                    ["k1"] = "v1",
                    ["k2"] = "v2",
                    ["k3"] = "v3",
                    ["k4"] = "v4",
                };

                validatorSettings.WithTranslation("name", dictionary);

                validatorSettings.Translations.ShouldBeLikeTranslations(
                    new Dictionary <string, IReadOnlyDictionary <string, string> >()
                {
                    ["name"] = new Dictionary <string, string>()
                    {
                        ["k1"] = "v1",
                        ["k2"] = "v2",
                        ["k3"] = "v3",
                        ["k4"] = "v4",
                    },
                });
            }
Exemplo n.º 3
0
        public Validator(ValidatorSettings settings = null)
        {
            _expressionValidator = new ClassValidatorExpression();
            _errors = new Dictionary <string, List <string> >();

            _settings = settings ?? new ValidatorSettings();
        }
            public void Should_ThrowException_When_NullEntryInDictionary()
            {
                var validatorSettings = new ValidatorSettings();

                var dictionary = new Dictionary <string, IReadOnlyDictionary <string, string> >()
                {
                    ["name1"] = new Dictionary <string, string>()
                    {
                        ["k11"] = "v11",
                        ["k12"] = "v12",
                        ["k13"] = null,
                        ["k14"] = "v14",
                    },
                    ["name2"] = new Dictionary <string, string>()
                    {
                        ["k21"] = "v21",
                        ["k22"] = "v22",
                        ["k23"] = "v23",
                        ["k24"] = "v24",
                    }
                };

                Action action = () => validatorSettings.WithTranslation(dictionary);

                action.Should().ThrowExactly <ArgumentNullException>();
            }
Exemplo n.º 5
0
            public void WithEnglishTranslation_Should_AddTranslation()
            {
                var settings = new ValidatorSettings();

                settings.WithEnglishTranslation();
                ShouldAddSingleTranslation(settings.Translations, "English", Translation.English);
            }
Exemplo n.º 6
0
        public static ValidatorSettings WithTranslation(this ValidatorSettings @this, ITranslationHolder translationHolder)
        {
            ThrowHelper.NullArgument(@this, nameof(@this));
            ThrowHelper.NullArgument(translationHolder, nameof(translationHolder));

            return(@this.WithTranslation(translationHolder.Translations));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates instance of <see cref="IValidator{T}"/> that can validate objects of type <typeparamref name="T"/> against the specification provided in the <paramref name="specificationHolder"/>.
        /// </summary>
        /// <param name="specificationHolder">Object that provides specification used to validate models (its member <see cref="ISpecificationHolder{T}.Specification"/>) and, optionally, settings (<see cref="ISettingsHolder.Settings"/>, if it implements also <see cref="ISettingsHolder"/>.</param>
        /// <param name="settings">Settings builder that helps adjust the created <see cref="IValidator{T}"/>'s settings. If not present, the default values are provided. Overrides translations delivered by <paramref name="specificationHolder"/>, if it implements also <see cref="ISettingsHolder"/>.</param>
        /// <typeparam name="T">Type of the models that this instance of <see cref="IValidator{T}"/> can validate.</typeparam>
        /// <returns>Instance of <see cref="IValidator{T}"/>, fully initialized and ready to work.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="specificationHolder"/> is null.</exception>
        /// <exception cref="InvalidOperationException">Thrown if <paramref name="specificationHolder"/>'s <see cref="ISettingsHolder.Settings"/> is null.</exception>
        public IValidator <T> Create <T>(ISpecificationHolder <T> specificationHolder, Func <ValidatorSettings, ValidatorSettings> settings = null)
        {
            if (specificationHolder is null)
            {
                throw new ArgumentNullException(nameof(specificationHolder));
            }

            var validatorSettings = ValidatorSettings.GetDefault();

            if (specificationHolder is ISettingsHolder validatorSettingsHolder)
            {
                if (validatorSettingsHolder.Settings is null)
                {
                    throw new ArgumentException($"{nameof(ISettingsHolder)} can't have null {nameof(ISettingsHolder.Settings)}", nameof(specificationHolder));
                }

                validatorSettings = GetResolvedSettings(validatorSettings, validatorSettingsHolder.Settings);
            }

            validatorSettings = GetResolvedSettings(validatorSettings, settings);

            var modelScheme = ModelSchemeFactory.Create(specificationHolder.Specification);

            SetReferenceLoopProtection(validatorSettings, modelScheme.IsReferenceLoopPossible);

            return(Create(specificationHolder.Specification, validatorSettings));
        }
Exemplo n.º 8
0
 private static void AddRule(ValidatorSettings settings, string filePath)
 => settings.rules.Add(new RuleItem
 {
     Name     = RuleUtility.FilePath2RuleName(filePath),
     Enabled  = true,
     FilePath = filePath,
 });
Exemplo n.º 9
0
        public void WithRussianTranslation_Should_AddTranslation()
        {
            var settings = new ValidatorSettings();

            settings.WithRussianTranslation();
            TranslationTestHelpers.ShouldContainSingleTranslation(settings.Translations, "Russian", Translation.Russian);
        }
Exemplo n.º 10
0
        private static void FetchRules(ValidatorSettings settings = null)
        {
            if (settings == null)
            {
                settings = GetOrCreateSettings();
            }
            var currentRuleFilePaths = RuleUtility.GetRuleFilePaths().ToArray();
            var settingsFilePaths    = settings.rules.Select(rule => rule.FilePath).ToArray();

            // 現在の設定にないものを追加する
            foreach (var filePath in currentRuleFilePaths)
            {
                if (!settingsFilePaths.Contains(filePath))
                {
                    AddRule(settings, filePath);
                }
            }

            // 現在の設定に余分にあるものを削除する
            var deleteRuleIndices = new List <int>();

            foreach (var filePath in settingsFilePaths)
            {
                if (!currentRuleFilePaths.Contains(filePath))
                {
                    var index = Array.IndexOf(currentRuleFilePaths, filePath);
                    deleteRuleIndices.Add(index);
                }
            }

            foreach (int index in deleteRuleIndices.OrderByDescending(x => x))
            {
                settings.rules.RemoveAt(index);
            }
        }
Exemplo n.º 11
0
            public void Should_PassAllEntries()
            {
                var validatorSettings = new ValidatorSettings();

                var holder = new ValidatorSettingsTests.WithTranslation.TestTranslationHolder()
                {
                    Translations = new Dictionary <string, IReadOnlyDictionary <string, string> >()
                    {
                        ["name"] = new Dictionary <string, string>()
                        {
                            ["k1"] = "v1",
                            ["k2"] = "v2",
                            ["k3"] = "v3",
                            ["k4"] = "v4",
                        }
                    }
                };

                validatorSettings.WithTranslation(holder);

                validatorSettings.Translations.ShouldBeLikeTranslations(
                    new Dictionary <string, IReadOnlyDictionary <string, string> >()
                {
                    ["name"] = new Dictionary <string, string>()
                    {
                        ["k1"] = "v1",
                        ["k2"] = "v2",
                        ["k3"] = "v3",
                        ["k4"] = "v4",
                    },
                });
            }
Exemplo n.º 12
0
        private static IInputValidator CreateValidator(string validatorType)
        {
            if (validatorType.Equals("custom", StringComparison.InvariantCultureIgnoreCase))
            {
                validatorSettings = Config.GetSection("custom").Get <ValidatorSettings>();
            }
            else
            {
                validatorSettings = Config.GetSection("default").Get <ValidatorSettings>();
            }

            validator = new InputValidator();
            validator.FirstNameMinLength = validatorSettings.FirstName.Min;
            validator.FirstNameMaxLength = validatorSettings.FirstName.Max;
            validator.LastNameMinLength  = validatorSettings.LastName.Min;
            validator.LastNameMaxLength  = validatorSettings.LastName.Max;
            validator.MinDate            = validatorSettings.DateOfBirth.From;
            validator.MaxDate            = validatorSettings.DateOfBirth.To;
            validator.Gender             = validatorSettings.Gender.ToList();
            validator.MinOffice          = validatorSettings.Office.Min;
            validator.MaxOffice          = validatorSettings.Office.Max;
            validator.MinSalary          = validatorSettings.Salary.Min;
            validator.MaxSalary          = validatorSettings.Salary.Max;

            return(validator);
        }
        public void WithSpanishTranslation_Should_AddTranslation()
        {
            var settings = new ValidatorSettings();

            settings.WithSpanishTranslation();
            TranslationTestHelpers.ShouldContainSingleTranslation(settings.Translations, "Spanish", Translation.Spanish);
        }
            public void Should_ThrowException_When_NullName()
            {
                var validatorSettings = new ValidatorSettings();

                Action action = () => validatorSettings.WithTranslation(null, new Dictionary <string, string>());

                action.Should().ThrowExactly <ArgumentNullException>();
            }
            public void Should_ReturnSelf()
            {
                var validatorSettings = new ValidatorSettings();

                var result = validatorSettings.WithTranslation("name", new Dictionary <string, string>());

                result.Should().BeSameAs(validatorSettings);
            }
Exemplo n.º 16
0
            public void Should_ThrowException_When_NullHolder()
            {
                var validatorSettings = new ValidatorSettings();

                Action action = () => validatorSettings.WithTranslation(null as ITranslationHolder);

                action.Should().ThrowExactly <ArgumentNullException>();
            }
            public void Should_ThrowException_When_NullDictionary()
            {
                var validatorSettings = new ValidatorSettings();

                Action action = () => validatorSettings.WithTranslation("name", null);

                action.Should().ThrowExactly <ArgumentNullException>();
            }
Exemplo n.º 18
0
        public void Should_Initialize_WithDefaultValues()
        {
            var validatorSettings = new ValidatorSettings();

            validatorSettings.Translations.Should().BeEmpty();
            validatorSettings.ReferenceLoopProtectionEnabled.Should().BeNull();
            validatorSettings.IsLocked.Should().BeFalse();
        }
            public void Should_WithReferenceLoopProtectionDisabled_Set_ReferenceLoopProtection_To_False()
            {
                var validatorSettings = new ValidatorSettings();

                validatorSettings.WithReferenceLoopProtectionDisabled();

                validatorSettings.ReferenceLoopProtection.Should().BeFalse();
            }
            public void Should_WithReferenceLoopProtection_Set_ReferenceLoopProtection_To_True()
            {
                var validatorSettings = new ValidatorSettings();

                validatorSettings.WithReferenceLoopProtection();

                validatorSettings.ReferenceLoopProtection.Should().BeTrue();
            }
            public void Should_WithReferenceLoopProtectionDisabled_ReturnSelf()
            {
                var validatorSettings = new ValidatorSettings();

                var result = validatorSettings.WithReferenceLoopProtectionDisabled();

                result.Should().BeSameAs(validatorSettings);
            }
            public void Should_ReturnSelf()
            {
                var validatorSettings = new ValidatorSettings();

                var result = validatorSettings.WithTranslation("name", "key", "translation");

                result.Should().BeSameAs(validatorSettings);
            }
            public void Should_ThrowException_When_NullArgument(string name, string key, string translation)
            {
                var validatorSettings = new ValidatorSettings();

                Action action = () => validatorSettings.WithTranslation(name, key, translation);

                action.Should().ThrowExactly <ArgumentNullException>();
            }
Exemplo n.º 24
0
 private static void SetReferenceLoopProtection(ValidatorSettings settings, bool isReferenceLoopPossible)
 {
     if (!settings.ReferenceLoopProtectionEnabled.HasValue)
     {
         _ = isReferenceLoopPossible
             ? settings.WithReferenceLoopProtection()
             : settings.WithReferenceLoopProtectionDisabled();
     }
 }
Exemplo n.º 25
0
        public void CreateValidatorNoDefaultPhaseSpecified()
        {
            XDocument         xSchema  = Resources.Provider.LoadXmlDocument("GoodSchemas.no_default_phase.xml");
            ValidatorSettings settings = new ValidatorSettings()
            {
                Phase = "#DEFAULT"
            };

            Assert.Throws <ArgumentException>(() => Validator.Create(xSchema, settings));
        }
Exemplo n.º 26
0
        public void CreateValidatorGoodSchemaWithBadSettings()
        {
            XDocument         xSchema  = Resources.Provider.LoadXmlDocument(PHASES_SCHEMA);
            ValidatorSettings settings = new ValidatorSettings()
            {
                Phase = null
            };

            Assert.Throws <ArgumentNullException>(() => Validator.Create(xSchema, settings));
        }
Exemplo n.º 27
0
        public void Settings_ModificationViaMethod()
        {
            var settings = new ValidatorSettings();

            settings.ReferenceLoopProtection.Should().BeNull();

            settings.WithReferenceLoopProtection();

            settings.ReferenceLoopProtection.Should().BeTrue();
        }
Exemplo n.º 28
0
            public static ValidatorSettings WithYodaEnglish(this ValidatorSettings @this)
            {
                var dictionary = new Dictionary <string, string>()
                {
                    ["Global.Required"]  = "Exist, it must.",
                    ["Numbers.LessThan"] = "Greater than {max}, the number must, be not."
                };

                return(@this.WithTranslation("YodaEnglish", dictionary));
            }
Exemplo n.º 29
0
            public void Should_LockSettingsAfterPassingToValidator()
            {
                var settings = new ValidatorSettings();

                settings.IsLocked.Should().BeFalse();

                _ = new Validator <object>(_ => _, settings);

                settings.IsLocked.Should().BeTrue();
            }
Exemplo n.º 30
0
        public void Should_LockSettingsAfterPassingToFactory_ExternalSettings()
        {
            var settings = new ValidatorSettings();

            settings.IsLocked.Should().BeFalse();

            _ = Validator.Factory.Create <object>(s => s, s => settings);

            settings.IsLocked.Should().BeTrue();
        }
Exemplo n.º 31
0
 private Validator CreateValidator(string phase, XDocument schema)
 {
     ValidatorSettings validatorSettings = new ValidatorSettings();
     if (!string.IsNullOrWhiteSpace(phase))
     {
         validatorSettings.Phase = phase;
     }
     if (isProcessingVerbose)
     {
         System.Console.WriteLine(string.Format(
             "Creating the validator with phase '{0}'.",
             validatorSettings.Phase));
     }
     Validator validator = Validator.Create(schema, validatorSettings);
     return validator;
 }