public void Test_ValidatorBuilder_Build()
 {
     var builder = new ValidatorBuilder<ValidateContext>(_Validation);
     var rule = builder.RuleFor(i => i.RuleSelector);
     var v = builder.Build();
     Assert.NotNull(v);
 }
 public ValidatorBuilderTest()
 {
     _validators = ValidatorBuilder <Validable>
                   .Create()
                   .AddValidator(new DescriptionIsEmptyValidator())
                   .AddValidator(new DescriptionIsNullValidator())
                   .AddValidator(new CountIsNullValidator())
                   .AddValidator(new CountIsZeroValidator())
                   .Build();
 }
 public void Test_ValidatorBuilder_RuleFor()
 {
     var builder = new ValidatorBuilder<ValidateContext>(_Validation);
     var rule = builder.RuleFor(i => i.RuleSelector);
     Assert.NotNull(rule);
     Assert.NotNull((rule as IRuleBuilder<ValidateContext, IRuleSelector>).ValueGetter);
     var setter = rule as IRuleMessageBuilder<ValidateContext, IRuleSelector>;
     Assert.NotNull(setter);
     Assert.Equal("RuleSelector", (setter as IValidateRuleBuilder).ValueName);
 }
        public void Test_ValidatorBuilder_RuleFor()
        {
            var builder = new ValidatorBuilder <ValidateContext>(_Validation);
            var rule    = builder.RuleFor(i => i.RuleSelector);

            Assert.NotNull(rule);
            Assert.NotNull((rule as IRuleBuilder <ValidateContext, IRuleSelector>).ValueGetter);
            var setter = rule as IRuleMessageBuilder <ValidateContext, IRuleSelector>;

            Assert.NotNull(setter);
            Assert.Equal("RuleSelector", (setter as IValidateRuleBuilder).ValueName);
        }
Ejemplo n.º 5
0
        public static void ScaffoldEntities(string srcDirectory,
                                            string testDirectory,
                                            string projectBaseName,
                                            List <Entity> entities,
                                            string dbContextName,
                                            bool addSwaggerComments,
                                            List <Policy> policies,
                                            IFileSystem fileSystem,
                                            Verbosity verbosity)
        {
            foreach (var entity in entities)
            {
                EntityBuilder.CreateEntity(srcDirectory, entity, projectBaseName, fileSystem);
                DtoBuilder.CreateDtos(srcDirectory, entity, projectBaseName);

                ValidatorBuilder.CreateValidators(srcDirectory, projectBaseName, entity);
                ProfileBuilder.CreateProfile(srcDirectory, entity, projectBaseName);

                QueryGetRecordBuilder.CreateQuery(srcDirectory, entity, dbContextName, projectBaseName);
                QueryGetListBuilder.CreateQuery(srcDirectory, entity, dbContextName, projectBaseName);
                CommandAddRecordBuilder.CreateCommand(srcDirectory, entity, dbContextName, projectBaseName);
                CommandDeleteRecordBuilder.CreateCommand(srcDirectory, entity, dbContextName, projectBaseName);
                CommandUpdateRecordBuilder.CreateCommand(srcDirectory, entity, dbContextName, projectBaseName);
                CommandPatchRecordBuilder.CreateCommand(srcDirectory, entity, dbContextName, projectBaseName);

                ControllerBuilder.CreateController(srcDirectory, entity, addSwaggerComments, policies, projectBaseName);

                // Shared Tests
                FakesBuilder.CreateFakes(testDirectory, projectBaseName, entity);

                // Integration Tests
                AddCommandTestBuilder.CreateTests(testDirectory, entity, projectBaseName);
                DeleteCommandTestBuilder.CreateTests(testDirectory, entity, projectBaseName);
                PatchCommandTestBuilder.CreateTests(testDirectory, entity, projectBaseName);
                GetRecordQueryTestBuilder.CreateTests(testDirectory, entity, projectBaseName);
                GetListQueryTestBuilder.CreateTests(testDirectory, entity, projectBaseName);
                PutCommandTestBuilder.CreateTests(testDirectory, entity, projectBaseName);

                // Functional Tests
                CreateEntityTestBuilder.CreateTests(testDirectory, entity, policies, projectBaseName);
                DeleteEntityTestBuilder.CreateTests(testDirectory, entity, policies, projectBaseName);
                GetEntityRecordTestBuilder.CreateTests(testDirectory, entity, policies, projectBaseName);
                GetEntityListTestBuilder.CreateTests(testDirectory, entity, policies, projectBaseName);
                PatchEntityTestBuilder.CreateTests(testDirectory, entity, policies, projectBaseName);
                PutEntityTestBuilder.CreateTests(testDirectory, entity, policies, projectBaseName);

                if (verbosity == Verbosity.More)
                {
                    WriteHelpText($"{projectBaseName} '{entity.Name}' entity was scaffolded successfully.");
                }
            }
        }
Ejemplo n.º 6
0
        public static Task ValidateAsync(this IField field, object?value, IList <string> errors,
                                         Schema?schema              = null,
                                         ValidationMode mode        = ValidationMode.Default,
                                         ValidationUpdater?updater  = null,
                                         IValidatorsFactory?factory = null,
                                         ValidationAction action    = ValidationAction.Upsert)
        {
            var context = CreateContext(schema, mode, updater, action);

            var validator = new ValidatorBuilder(factory, context).ValueValidator(field);

            return(validator.ValidateAsync(value, context, CreateFormatter(errors)));
        }
Ejemplo n.º 7
0
        private static void RunTemplateBuilders(string solutionDirectory, ApiTemplate template, IFileSystem fileSystem)
        {
            // dbcontext
            DbContextBuilder.CreateDbContext(solutionDirectory, template);

            //entities
            foreach (var entity in template.Entities)
            {
                EntityBuilder.CreateEntity(solutionDirectory, entity, fileSystem);
                DtoBuilder.CreateDtos(solutionDirectory, entity);

                RepositoryBuilder.AddRepository(solutionDirectory, entity, template.DbContext);
                ValidatorBuilder.CreateValidators(solutionDirectory, entity);
                ProfileBuilder.CreateProfile(solutionDirectory, entity);

                ControllerBuilder.CreateController(solutionDirectory, entity);

                FakesBuilder.CreateFakes(solutionDirectory, template, entity);
                ReadTestBuilder.CreateEntityReadTests(solutionDirectory, template, entity);
                GetTestBuilder.CreateEntityGetTests(solutionDirectory, template, entity);
                PostTestBuilder.CreateEntityWriteTests(solutionDirectory, template, entity);
                UpdateTestBuilder.CreateEntityUpdateTests(solutionDirectory, template, entity);
                DeleteTestBuilder.DeleteEntityWriteTests(solutionDirectory, template, entity);
                WebAppFactoryBuilder.CreateWebAppFactory(solutionDirectory, template, entity);
            }

            // environments
            AddStartupEnvironmentsWithServices(solutionDirectory, template);

            //seeders
            SeederBuilder.AddSeeders(solutionDirectory, template);

            //services
            SwaggerBuilder.AddSwagger(solutionDirectory, template);

            if (template.AuthSetup.AuthMethod == "JWT")
            {
                IdentityServicesModifier.SetIdentityOptions(solutionDirectory, template.AuthSetup);
                IdentitySeederBuilder.AddSeeders(solutionDirectory, template);
                IdentityRoleBuilder.CreateRoles(solutionDirectory, template.AuthSetup.Roles);
                RoleSeedBuilder.SeedRoles(solutionDirectory, template);
            }

            //final
            ReadmeBuilder.CreateReadme(solutionDirectory, template, fileSystem);

            if (template.AddGit)
            {
                GitSetup(solutionDirectory);
            }
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            var triangleValidator = new ValidatorBuilder <Triangle>()
                                    .AddRule(t => t.Name == "Triangle", t => $"Name {t.Name} is not correct")
                                    .AddRule(t => t.GetArea() > 20, t => $"Area value {t.GetArea()} is not correct. Should be more than 30")
                                    .Build();

            var validationResult = triangleValidator.Validate(new Triangle(3, 6));

            if (!validationResult.IsValid)
            {
                Console.WriteLine(string.Join(Environment.NewLine, validationResult.ErrorMessages));
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates File Cabinet.
        /// </summary>
        private static void CreateFileCabinet()
        {
            IRecordValidator validator = new ValidatorBuilder().CreateDefault();

            if (SettingsApp.FileCabinetType.Equals(typeof(FileCabinetMemoryService)))
            {
                fileCabinetService = new FileCabinetMemoryService(validator, SettingsApp.StartId);
            }
            else if (SettingsApp.FileCabinetType.Equals(typeof(FileCabinetFilesystemService)))
            {
                FileStream fileStream = new FileStream(Settings.FileNameStorage, FileMode.Create, FileAccess.ReadWrite);
                fileCabinetService = new FileCabinetFilesystemService(validator, fileStream, SettingsApp.StartId);
            }
        }
Ejemplo n.º 10
0
        public void Configure(ValidatorBuilder <T> builder)
        {
            var elementBuilder = new TypeValidatorBuilder <TElement>();

            _configurator.Configure(elementBuilder);

            Validator <TElement> elementValidator = elementBuilder.Build("");

            var nestedValidator = new NestedValidator <TElement>(elementValidator);

            var validator = new EnumerableValidator <T, TElement>(nestedValidator);

            builder.AddValidator(validator);
        }
Ejemplo n.º 11
0
 /// <summary>
 ///   Adds an explicit view model-level validation error (with the given
 ///   <paramref name="errorMessage"/> to the current VM if any of its
 ///   properties are invalid (see remarks).
 /// </summary>
 /// <remarks>
 ///   This rule is useful if a VM is displayed in a grid where not all
 ///   properties are visible in the grid. If any of the properites of a
 ///   VM (visible or not) become invalid, a view model-level (row level)
 ///   validation error is added to the VM (which is for example visualized
 ///   by a red cross to the left of the grid row). This indicates to the
 ///   user that something currently not visible may be invalid and that he
 ///   or she should open the details of the current record to correct the
 ///   validation error.
 /// </remarks>
 public static void ValidateProperties <TOwnerVM, TTargetVM, TDescriptor>(
     this ValidatorBuilder <TOwnerVM, TTargetVM, TDescriptor> builder,
     string errorMessage
     )
     where TOwnerVM : IViewModel
     where TTargetVM : IViewModel
     where TDescriptor : class, IVMDescriptor
 {
     builder.CheckViewModel((args) => {
         if (!args.Owner.Kernel.GetValidationResult(ValidationResultScope.PropertiesOnly).IsValid)
         {
             args.AddError(errorMessage);
         }
     });
 }
        public void Validate_NoFields_Strings_Pattern_Invalid()
        {
            // Arrange
            var form      = new QueryCollection(new Dictionary <string, StringValues>());
            var validator = ValidatorBuilder
                            .New()
                            .RequiresStringWithPattern("email", new Regex("\\w+@\\w+\\.\\w+"))
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.IsFalse(valid);
        }
Ejemplo n.º 13
0
        public void File_QueryCollection_Invalid()
        {
            // Arrange
            var form      = new QueryCollection(new Dictionary <string, StringValues>());
            var validator = ValidatorBuilder
                            .New()
                            .RequiresFile("file", f => true)
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.IsFalse(valid);
        }
Ejemplo n.º 14
0
 /// <summary>
 ///   Adds an expli1cit view model-level validation error (with the given
 ///   <paramref name="errorMessage"/>) to the current VM if any of its
 ///   descendants are invalid (see remarks).
 /// </summary>
 /// <remarks>
 ///   <para>Beware that the validation state is always propagated to to the
 ///      parent (meaning that <see cref="ViewModel{TDescriptor}.IsValid"/> returns false
 ///      if any descendant is invalid) but <see cref="ViewModel{TDescriptor}.GetValidationResult(ValidationResultScope)"/>
 ///      with <see cref="ValidationResultScope.Self"/> does not return an error
 ///      by default unless you add this validation rule.</para>
 ///   <para>This validation rule is most useful in hierarchical data structures
 ///      (e.g. an employee has projects which have tasks which have records) to
 ///      guide the user to the (probably not visible) record that is actually
 ///      invalid.</para>
 /// </remarks>
 public static void PropagateChildErrors <TOwnerVM, TTargetVM, TDescriptor>(
     this ValidatorBuilder <TOwnerVM, TTargetVM, TDescriptor> builder,
     string errorMessage
     )
     where TOwnerVM : IViewModel
     where TTargetVM : IViewModel
     where TDescriptor : class, IVMDescriptor
 {
     builder.CheckViewModel((args) => {
         // TODO: Write test to verify that target is used instead of owner.
         if (!args.Target.Kernel.GetValidationResult(ValidationResultScope.Descendants).IsValid)
         {
             args.AddError(errorMessage);
         }
     });
 }
        public void Validate_TwoFields_Strings_MultipleValues_Bounded_NoFields_Valid()
        {
            // Arrange
            var form      = new QueryCollection(new Dictionary <string, StringValues>());
            var validator = ValidatorBuilder
                            .New()
                            .CanHaveStrings("vowels", 2, 5, vowel => vowel.Length == 1)
                            .CanHaveStrings("consonants", 4, 5, consonant => consonant.Length == 1)
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.IsTrue(valid);
        }
Ejemplo n.º 16
0
        public void Configure(ValidatorBuilder <T> builder)
        {
            var propertyValidatorBuilder = new TypeValidatorBuilder <TProperty>();

            foreach (var configurator in _configurators)
            {
                configurator.Configure(propertyValidatorBuilder);
            }

            Validator <TProperty> propertyValueValidator =
                propertyValidatorBuilder.Build("." + GetPropertyName(_propertyExpression));

            var validator = new PropertyValidator <T, TProperty>(_propertyExpression, propertyValueValidator);

            builder.AddValidator(validator);
        }
        public void Validate_NullForm_Invalid()
        {
            // Arrange
            IFormCollection form = null;

            var validator = ValidatorBuilder
                            .New()
                            .RequiresStringWithPattern("email", new Regex("[^@]+@[^.]+(\\.[^.]+)+", RegexOptions.Compiled))
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.IsFalse(valid);
        }
        public void Validate_NullForm_Invalid()
        {
            // Arrange
            IQueryCollection form = null;

            var validator = ValidatorBuilder
                            .New()
                            .RequiresRational("flops")
                            .WithCultureInfo(CultureInfo.InvariantCulture)
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.IsFalse(valid);
        }
Ejemplo n.º 19
0
 public void Test_ValidatorBuilder_RuleSet()
 {
     var builder = new ValidatorBuilder<ValidateContext>(_Validation);
     builder.RuleSet("a", b =>
      {
          builder.RuleFor(i => i.Option);
          builder.RuleFor(i => i.RuleSelector);
          builder.RuleFor(i => i.RuleSelector);
          builder.Builders.RemoveAt(2);
      });
     Assert.NotNull(builder.Builders);
     Assert.Equal(2, builder.Builders.Count);
     Assert.NotNull(builder.Builders[0]);
     Assert.NotNull(builder.Builders[1]);
     Assert.Equal("A", builder.Builders[0].RuleSet);
     Assert.Equal("A", builder.Builders[1].RuleSet);
 }
        /// <summary>
        /// Creates custom validator.
        /// </summary>
        /// <param name="validatorBuilder">The instance of ValidatorBuilder class.</param>
        /// <returns>The instance of IRecordValidator class.</returns>
        public static IRecordValidator CreateСustom(this ValidatorBuilder validatorBuilder)
        {
            var rulesets = GetRulesets();

            ValidationRuleset ruleset = rulesets.Custom;

            return(new CompositeValidator(new List <IRecordValidator>
            {
                new FirstNameValidator(ruleset.FirstName.MinLength, ruleset.FirstName.MaxLength),
                new LastNameValidator(ruleset.LastName.MinLength, ruleset.LastName.MaxLength),
                new DateOfBirthValidator(ruleset.DateOfBirth.From, ruleset.DateOfBirth.To),
                new FavouriteNumberValidator(ruleset.FavNumber.MinValue, ruleset.FavNumber.MaxValue),
                new FavouriteCharacterValidator(ruleset.FavCharacter.SymbolCase),
                new FavouriteGameValidator(ruleset.FavGame.MinLength, ruleset.FavGame.MaxLength),
                new DonationsValidator(ruleset.Donations.MinValue),
            }));
        }
        public void Validate_Rational_Bounded_NoFields_Invalid()
        {
            // Arrange
            var form      = new FormCollection(new Dictionary <string, StringValues>());
            var validator = ValidatorBuilder
                            .New()
                            .RequiresRational("height", height => height > 10 && height < 300)
                            .RequiresRational("weight", weigth => weigth > 10 && weigth < 300)
                            .WithCultureInfo(CultureInfo.InvariantCulture)
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.IsFalse(valid);
        }
Ejemplo n.º 22
0
    static void Main()
    {
        Validator <Student> validator = ValidatorBuilder
                                        .Build <Student>()
                                        // .AddValidation("Age", new Above18())
                                        .AddValidation("Name", new NotNull())
                                        .AddValidation <String>("Name", val => val.Length < 10);

        Student s1 = new Student(76135, "Anacleto", 20);

        validator.Validate(s1);
        s1.Print();
        Student s2 = new Student(654354, "Maria Jose Catita", 25);

        validator.Validate(s2);
        s2.Print();
    }
        public void Validate_OneField_MultipleIntegers_Predicate_DataTest(int min, int max, bool expected, params string[] values)
        {
            // Arrange
            var form = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "blah", new StringValues(values) }
            });
            var validator = ValidatorBuilder
                            .New()
                            .RequiresIntegers("blah", min, max, i => i > 0 && i < 10)
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.AreEqual(valid, expected);
        }
        public void Validate_OneField_MultipleString_Pattern_DataTest(int min, int max, bool expected, params string[] values)
        {
            // Arrange
            var form = new FormCollection(new Dictionary <string, StringValues>
            {
                { "blah", new StringValues(values) }
            });
            var validator = ValidatorBuilder
                            .New()
                            .RequiresStringsWithPattern("blah", min, max, new Regex("[1-5]"))
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.AreEqual(valid, expected);
        }
        public void Test_ValidatorBuilder_RuleSet()
        {
            var builder = new ValidatorBuilder <ValidateContext>(_Validation);

            builder.RuleSet("a", b =>
            {
                builder.RuleFor(i => i.Option);
                builder.RuleFor(i => i.RuleSelector);
                builder.RuleFor(i => i.RuleSelector);
                builder.Builders.RemoveAt(2);
            });
            Assert.NotNull(builder.Builders);
            Assert.Equal(2, builder.Builders.Count);
            Assert.NotNull(builder.Builders[0]);
            Assert.NotNull(builder.Builders[1]);
            Assert.Equal("A", builder.Builders[0].RuleSet);
            Assert.Equal("A", builder.Builders[1].RuleSet);
        }
Ejemplo n.º 26
0
        public void File_OneFile_Invalid()
        {
            // Arrange
            var form = new FormCollection(new Dictionary <string, StringValues>(), new FormFileCollection
            {
                new FormFile(Stream.Null, 0, 0, "file", "adwdaw")
            });
            var validator = ValidatorBuilder
                            .New()
                            .CanHaveFile("file", f => false)
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.IsFalse(valid);
        }
Ejemplo n.º 27
0
        public static async Task ValidateAsync(this ContentData data, PartitionResolver partitionResolver, IList <ValidationError> errors,
                                               Schema?schema              = null,
                                               ValidationMode mode        = ValidationMode.Default,
                                               ValidationUpdater?updater  = null,
                                               IValidatorsFactory?factory = null,
                                               ValidationAction action    = ValidationAction.Upsert)
        {
            var context = CreateContext(schema, mode, updater, action);

            var validator = new ValidatorBuilder(factory, context).ContentValidator(partitionResolver);

            await validator.ValidateInputAsync(data);

            foreach (var error in validator.Errors)
            {
                errors.Add(error);
            }
        }
        public void Validate_OneField_String_Predicate_FieldsExists_Invalid()
        {
            // Arrange
            var form = new FormCollection(new Dictionary <string, StringValues>
            {
                { "type", "rum" }
            });
            var validator = ValidatorBuilder
                            .New()
                            .RequiresString("type", s => s == "petrol" || s == "diesel")
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.IsFalse(valid);
        }
        public void Validate_OneField_Integer_Unbounded_FieldExists_Valid()
        {
            // Arrange
            var form = new FormCollection(new Dictionary <string, StringValues>
            {
                { "number", "32423" },
            });
            var validator = ValidatorBuilder
                            .New()
                            .RequiresInteger("number")
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.IsTrue(valid);
        }
        public void Validate_TwoFields_Integer_Unbounded_NoFields_Invalid()
        {
            // Arrange
            var form = new FormCollection(new Dictionary <string, StringValues>
            {
            });
            var validator = ValidatorBuilder
                            .New()
                            .RequiresInteger("zip")
                            .RequiresInteger("age")
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.IsFalse(valid);
        }
        public void Validate_OneField_Integer_AllBounded_FieldExists_Valid()
        {
            // Arrange
            var form = new FormCollection(new Dictionary <string, StringValues>
            {
                { "zip", "9000" },
            });
            var validator = ValidatorBuilder
                            .New()
                            .RequiresInteger("zip", zip => zip > 1000 && zip < 9999)
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.IsTrue(valid);
        }
        public void Validate_Builder_Throws()
        {
            // Arrange
            var form = new QueryCollection(new Dictionary <string, StringValues>
            {
                { "flops", "" }
            });

            // Act and Assert
            Assert.Throws <ArgumentException>(() =>
            {
                var validator = ValidatorBuilder
                                .New()
                                .RequiresInteger("flops")
                                .RequiresInteger("flops")
                                .Build();
            });
        }
        public void Validate_EmptyField_Optional_Valid()
        {
            // Arrange
            var form = new FormCollection(new Dictionary <string, StringValues>
            {
                { "flops", "" }
            });
            var validator = ValidatorBuilder
                            .New()
                            .CanHaveInteger("flops")
                            .Build();

            // Act
            var valid = validator.Validate(form);

            // Assert
            Assert.IsTrue(valid);
        }
        public override void Configure(ValidatorBuilder<DateTime> builder)
        {
            var validator = new WithinPastDateTimeValidator(_period);

            builder.AddValidator(validator);
        }