コード例 #1
0
        public void Validate_Collection_Using_Specified_Specification_WithoutValidateObjectGraph()
        {
            //Build test data
            var validContact = new Contact()
            {
                FirstName = "Johnny B", LastName = "Good"
            };
            var invalidContact = new Contact()
            {
                FirstName = "Baddy"
            };

            var contacts = new List <Contact>()
            {
                validContact, invalidContact
            };

            //Create specification
            ValidationCatalog.AddSpecification <Contact>(spec =>
            {
                spec.Check(c => c.FirstName).Required();
                spec.Check(c => c.LastName).Required();
            });

            //Validate
            var results = ValidationCatalog.Validate(contacts);

            Assert.That(results.Errors.Count, Is.AtLeast(1));
        }
コード例 #2
0
        public void ValidateConcurrently()
        {
            ValidationCatalog.AddSpecification <Customer>(s => s.Check(c => c.Name).Required().MaxLength(50));
            Customer customer1 = new Customer()
            {
                Name = string.Empty.PadLeft(55, 'X')
            };
            Customer customer2 = new Customer()
            {
                Name = string.Empty.PadLeft(45, 'X')
            };

            var childThread = new Thread(() =>
            {
                var customer1Notification = ValidationCatalog.Validate(customer1);
                Assert.IsFalse(customer1Notification.IsValid);
            });

            childThread.Start();

            var customer2Notification = ValidationCatalog.Validate(customer2);

            Assert.IsTrue(customer2Notification.IsValid);

            childThread.Join();
        }
コード例 #3
0
        public void ValidateMethodCallPropertyOnClass_IsSuccessful()
        {
            ValidationCatalog.AddSpecification <StubClass>(validates => validates.Check(x => x.GetCollection()).Required().CountGreaterThan(1));
            var c = new StubClass();

            Assert.DoesNotThrow(() => ValidationCatalog.Validate(c));
        }
コード例 #4
0
        public void SpecificationAbstract_OnObject_WithSpecification_IsValid()
        {
            ValidationCatalog.AddSpecification <BaseClassSpecification>();
            ValidationCatalog.AddSpecification <DerivedClassASpecification>();
            ValidationCatalog.AddSpecification <DerivedClassBSpecification>();
            ValidationCatalog.AddSpecification <ClassWithAbstractPropertySpecification>();

            var t = new DerivedClassA();
            var a = new ClassWithAbstractProperty {
                BaseClassProperty = t
            };

            //collection
            a.BaseClassCollectionProperty = new List <BaseClass>();
            //a.BaseClassCollectionProperty.Add(new DerivedClassA());
            a.BaseClassCollectionProperty.Add(new DerivedClassB()
            {
                BaseName = "Valid"
            });


            var n = ValidationCatalog.Validate(a);

            Assert.That(n.IsValid, Is.False);
            Assert.That(n.All().Count(), Is.EqualTo(3));
        }
コード例 #5
0
ファイル: MessageTests.cs プロジェクト: ne4ta/SpecExpress
        public void When_WithMessageIsSuppliedWithCustomPropetyValueFormat()
        {
            var customMessage = "Dope! It's required!";

            //Add a rule
            ValidationCatalog.AddSpecification <Contact>(
                spec => spec.Check(c => c.DateOfBirth).Required()
                .IsInPast().With(m =>
            {
                m.Message =
                    "Date must be in the past. You entered {PropertyValue}.";
                m.FormatProperty = s => s.ToShortDateString();
            }));



            //String.Format("{0} must be less than {1}", m.PropertyName, m.PropertyValue.ToString("mm/dd/yyyy"))));

            //dummy data
            var contact = new Contact()
            {
                FirstName = "Joesph", LastName = "Smith", DateOfBirth = System.DateTime.Now.AddYears(1)
            };

            //Validate
            var valNot = ValidationCatalog.Validate(contact);

            Assert.That(valNot.Errors, Is.Not.Empty);
            Assert.That(valNot.Errors.First().Message, Is.EqualTo("Too long 5"));
        }
コード例 #6
0
        public void When_validated_with_ExplicitSpecification()
        {
            //Don't implicitly validate object graph
            ValidationCatalog.ValidateObjectGraph = false;

            var customer = new Customer {
                Name = "SampleCustomer", Address = new Address()
                {
                    Country = new Country()
                    {
                        Id = "DE", Name = "Germany"
                    }, Street = "1234 Offenbacher Strasse"
                }
            };

            //Add Specification for Customer for international addresses
            ValidationCatalog.SpecificationContainer.Add(new InternationalAddressSpecification());
            ValidationCatalog.AddSpecification <Customer>(spec => spec.Check(c => c.Address).Required().Specification <InternationalAddressSpecification>());

            //Validate Customer
            var results = ValidationCatalog.Validate(customer);

            Assert.That(results.Errors, Is.Not.Empty);

            Assert.That(results.Errors.First().NestedValidationResults, Is.Not.Empty);
        }
コード例 #7
0
        public void Validate_Property_With_NullCondition_IsValid()
        {
            // String.IsNullOrEmpty(c.Addresses[0].City) should throw an exception
            ValidationCatalog.AddSpecification <Contact>(spec => spec.Check(c => c.FirstName).If(c => String.IsNullOrEmpty(c.Addresses[0].City)).Required());
            var vn = ValidationCatalog.Validate(new Contact());

            Assert.That(vn.IsValid, Is.True);
        }
コード例 #8
0
        public void SpecificationInheritance_OnObject_WithSpecification_IsValid()
        {
            ValidationCatalog.AddSpecification <BaseClassSpecification>();
            ValidationCatalog.AddSpecification <DerivedClassASpecification>();

            var a = new DerivedClassA();
            var n = ValidationCatalog.Validate(a);

            Assert.That(n.IsValid, Is.False);
            Assert.That(n.All().Count(), Is.EqualTo(2));
        }
コード例 #9
0
        public void Validate_OptionalNestedProperty_WithNullValue_IsValid()
        {
            var customer = new Customer();

            ValidationCatalog.AddSpecification <Customer>(spec => spec.Check(cust => cust.Address.Street).Optional()
                                                          .MaxLength(255));

            var results = ValidationCatalog.Validate(customer);

            Assert.That(results.Errors, Is.Empty);
        }
コード例 #10
0
        public void InvalidExpression_IsInvalid()
        {
            ValidationCatalog.AddSpecification <Contact>(x => x.Check(c => c.NumberOfDependents).Required().
                                                         GreaterThan(z => new BadWolf().Max(z.NumberOfDependents)));

            var contact = new Contact()
            {
                LastName = "Bill"
            };

            var results = ValidationCatalog.Validate(contact);

            Assert.That(results.Errors, Is.Not.True);
        }
コード例 #11
0
        public void Enum_ValueIsFirstValue_IsRequired()
        {
            ValidationCatalog.AddSpecification <Person>(spec =>
                                                        spec.Check(p => p.PersonGender).Required());

            var person = new Person()
            {
                PersonGender = Gender.Male
            };

            var vn = ValidationCatalog.Validate(person);

            Assert.That(vn.IsValid, Is.True);
        }
コード例 #12
0
        public bool IsValid()
        {
            ValidationCatalog.AddSpecification <Contact>(x =>
            {
                x.Check(contact => contact.LastName).Required();
                x.Check(contact => contact.FirstName).Required();
                x.Check(contact => contact.DateOfBirth).Optional().
                GreaterThan(new DateTime(1950, 1, 1));
            });

            //Validate
            Errors = ValidationCatalog.Validate(this);
            return(Errors.IsValid);
        }
コード例 #13
0
        public void ForEachSpecification_Warn_IsValid()
        {
            //Don't implicitly validate object graph
            ValidationCatalog.ValidateObjectGraph = false;

            //create list of contacts to validate
            var contacts = new List <Contact>
            {
                new Contact()
                {
                    FirstName = String.Empty, LastName = "Smith"
                },
                new Contact()
                {
                    FirstName = String.Empty, LastName = String.Empty
                },
                new Contact()
                {
                    FirstName = "Joe", LastName = "Smith"
                }
            };

            var customer = new Customer()
            {
                Name = "Smith Industries", Contacts = contacts
            };


            //Add Specification for Customer and Address
            ValidationCatalog.AddSpecification <Customer>(spec =>
            {
                spec.Check(c => c.Contacts).Required();
                spec.Warn(c => c.Contacts).Optional().ForEachSpecification <Contact>(
                    cspec =>
                {
                    cspec.Warn(c => c.LastName).Required();
                    cspec.Warn(c => c.FirstName).Required();
                });
            });

            //Validate Customer
            var results = ValidationCatalog.Validate(customer);

            Assert.That(results.Errors, Is.Not.Empty);
            Assert.IsTrue(results.IsValid);

            var allerrors = results.Errors.First().AllErrorMessages().ToList();

            Assert.That(results.Errors.First().NestedValidationResults, Is.Not.Empty);
        }
コード例 #14
0
        public void ValidationNotification_WithOneError_IsValid()
        {
            ValidationCatalog.AddSpecification <Customer>(spec =>
            {
                spec.Check(c => c.Name).Required();
                spec.Warn(c => c.Address).Required().Specification <AddressSpecification>();
            });


            var customer = new Customer();

            var vn = ValidationCatalog.Validate(customer);

            Assert.That(vn.IsValid, Is.False);
        }
コード例 #15
0
        public void Validate_Property_Label_Is_Available_On_Error_When_Invalid()
        {
            const string expected = "This is a custom rule label";

            ValidationCatalog.AddSpecification <Contact>(spec =>
                                                         spec.Check(c => c.FirstName).WithLabel(expected).Required());

            var contact = new Contact();
            var vn      = ValidationCatalog.Validate(contact);

            Assert.That(vn.IsValid, Is.False);

            var error = vn.Errors.Single();

            Assert.AreEqual(expected, error.Label);
        }
コード例 #16
0
        public void Validate_Property_With_CustomName_IsValid_And_Label_Is_Set()
        {
            const string expected = "This is a custom rule label";

            ValidationCatalog.AddSpecification <Contact>(spec =>
                                                         spec.Check(c => c.FirstName).WithLabel(expected)
                                                         .If(c => String.IsNullOrEmpty(c.Addresses[0].City)).Required());

            var vn = ValidationCatalog.Validate(new Contact());

            Assert.That(vn.IsValid, Is.True);

            var actual = ValidationCatalog.SpecificationContainer.GetAllSpecifications().Single().PropertyValidators.Single().Label;

            Assert.AreEqual(expected, actual);
        }
コード例 #17
0
ファイル: MessageTests.cs プロジェクト: ne4ta/SpecExpress
        public void When_MessageContainsParameters()
        {
            ValidationCatalog.AddSpecification <Contact>(
                spec => spec.Check(c => c.LastName).Required().EqualTo("Johnson"));

            //dummy data
            var contact = new Contact()
            {
                FirstName = "Joesph", LastName = "Smith"
            };

            //Validate
            var valNot = ValidationCatalog.Validate(contact);

            Assert.That(valNot.Errors, Is.Not.Empty);
            Assert.That(valNot.Errors.First().Message, Is.EqualTo("Last Name must equal Johnson."));
        }
コード例 #18
0
ファイル: MessageTests.cs プロジェクト: ne4ta/SpecExpress
        public void When_WithMessageKeyIsSupplied_DefaultMessageIsOverridden()
        {
            //Add a rule
            ValidationCatalog.AddSpecification <Contact>(spec => spec.Check(c => c.LastName).Required().
                                                         LengthBetween(1, 3).With(m => m.MessageKey = "Alpha"));

            //dummy data
            var contact = new Contact()
            {
                FirstName = "Joesph", LastName = "Smith"
            };

            //Validate
            var valNot = ValidationCatalog.Validate(contact);

            Assert.That(valNot.Errors, Is.Not.Empty);
            Assert.That(valNot.Errors.First().Message, Is.EqualTo("Last Name should only contain letters."));
        }
コード例 #19
0
        public void ValidateProperty_NoValidationForProperty_ThrowsArgumentException()
        {
            //Create Rules Adhoc
            ValidationCatalog.AddSpecification <Contact>(x =>
            {
                x.Check(c => c.FirstName).Required();
            });

            var contact = new Contact();

            // Validation contact.LastName should result with only one error.


            Assert.Throws <ArgumentException>(
                () =>
            {
                var propertyNotification = ValidationCatalog.ValidateProperty(contact, c => c.LastName);
            });
        }
コード例 #20
0
        public void NullableEnum_ValueIsSecondValue_IsRequired()
        {
            ValidationCatalog.AddSpecification <Person>(spec =>
            {
                spec.Check(p => p.PersonGender).Required();
                spec.Check(p => p.NullablePersonGender).Required();
            }
                                                        );

            var person = new Person()
            {
                PersonGender = Gender.Female
            };

            var vn = ValidationCatalog.Validate(person);

            Assert.That(vn.IsValid, Is.False);
            Assert.That(vn.Errors.First().Message, Is.EqualTo("Nullable Person Gender is required."));
        }
コード例 #21
0
        public void Validate_OptionalCollection_Using_Registered_Specification()
        {
            //Build test data
            var customer = new Customer()
            {
                Name = "TestCustomer"
            };
            var validContact = new Contact()
            {
                FirstName = "Johnny B", LastName = "Good"
            };
            var invalidContact = new Contact()
            {
                FirstName = "Baddy"
            };

            customer.Contacts = new List <Contact>()
            {
                validContact, invalidContact
            };

            //Build specifications
            ValidationCatalog.AddSpecification <Customer>(spec =>
            {
                spec.Check(cust => cust.Name).Required();
                spec.Check(cust => cust.Contacts).Required();
            });

            ValidationCatalog.AddSpecification <Contact>(spec =>
            {
                spec.Check(c => c.FirstName).Required();
                spec.Check(c => c.LastName).Required();
            });


            ValidationCatalog.ValidateObjectGraph = true;

            //Validate
            var results = ValidationCatalog.Validate(customer);

            Assert.That(results.Errors.Count, Is.AtLeast(1));
        }
コード例 #22
0
        public void TryGetSpecification_WithMock_ReturnsSpecification()
        {
            //Add the target specification to the container
            ValidationCatalog.AddSpecification <Contact>(x => new ContactSpecification());

            //create the mock object which is proxy type
            var mockRepository = new MockRepository();

            mockRepository.Record();
            Contact contact = mockRepository.DynamicMock <Contact>();

            SetupResult.For(contact.FirstName).Return("Something");
            SetupResult.For(contact.LastName).Return("Else");
            mockRepository.ReplayAll();

            //Get a specification that matches the underlying type for the proxy
            var specification = ValidationCatalog.SpecificationContainer.TryGetSpecification(contact.GetType());

            Assert.That(specification, Is.Not.Null);
        }
コード例 #23
0
        public void GetMessageForRuleWithMessageOverrrideAndMessageKey()
        {
            ValidationCatalog.Configure(x => x.AddMessageStore(new ResourceMessageStore(TestRuleErrorMessages.ResourceManager), "OverrideMessages"));

            ValidationCatalog.AddSpecification <Contact>(c =>
            {
                c.Check(x => x.LastName).Required().IsAlpha().With(m => m.MessageKey = "TestRule");
            }
                                                         );

            //Create an Entity
            var contact = new Contact();

            contact.FirstName = null;
            contact.LastName  = "1111";

            var results = ValidationCatalog.ValidateProperty(contact, c => c.LastName);

            Assert.That(results.Errors.ToList().First().Message == "Last Name is invalid!");
        }
コード例 #24
0
ファイル: MessageTests.cs プロジェクト: ne4ta/SpecExpress
        public void When_WithMessageIsSupplied_DefaultMessageIsOverridden()
        {
            var customMessage = "Dope! It's required!";

            //Add a rule
            ValidationCatalog.AddSpecification <Contact>(spec => spec.Check(c => c.LastName).Required().
                                                         LengthBetween(1, 3).With(m => m.Message = "Too long {PropertyValue}"));

            //dummy data
            var contact = new Contact()
            {
                FirstName = "Joesph", LastName = "Smith"
            };

            //Validate
            var valNot = ValidationCatalog.Validate(contact);

            Assert.That(valNot.Errors, Is.Not.Empty);
            Assert.That(valNot.Errors.First().Message, Is.EqualTo("Too long 5"));
        }
コード例 #25
0
        public void Specification_WithForEachSpecification_UsingValidationCatalog_Assert_ThrowsException()
        {
            //Add spec to catalog
            ValidationCatalog.AddSpecification <PersonSpecification>();

            //Setup test data
            _persons.Add(new Person()
            {
                FirstName = "First", LastName = "Last"
            });
            _persons.Add(new Person()
            {
                FirstName = "First"
            });                                                 //Missing Last Name


            Assert.Throws <ValidationException>(() =>
            {
                Specification.Assert(sp => sp.Check(s => _persons).Required().ForEachSpecification());
            });
        }
コード例 #26
0
        public void SpecificationInheritance_OnObject_WithSpecification_IsValid()
        {
            //Base Class
            ValidationCatalog.SpecificationContainer.Add(new CustomerRequiredNameSpecification());
            //Inherited class
            ValidationCatalog.AddSpecification <ExtendedCustomer>(spec =>
            {
                spec.Using <Customer, CustomerRequiredNameSpecification>();
                spec.Check(c => c.SpecialGreeting).Required();
            });

            var customer = new ExtendedCustomer();
            var results  = ValidationCatalog.Validate(customer);


            Assert.That(results.Errors.Count, Is.EqualTo(2));
            var errorMessages = results.Errors.Select(x => x.ToString());

            Assert.That(errorMessages.Contains("Cust Name is required."));
            Assert.That(errorMessages.Contains("Special Greeting is required."));
        }
コード例 #27
0
        public void ValidateProperty_SimpleProperty_OverridePropertyNameReturnsValidationNotification()
        {
            //Create Rules Adhoc
            ValidationCatalog.AddSpecification <Contact>(x =>
            {
                x.Check(c => c.LastName, "Contact Last Name").Required();
                x.Check(c => c.FirstName).Required();
            });

            var contact = new Contact();

            // Validating contact as a whole should result in two errors.
            var objectNotification = ValidationCatalog.Validate(contact);

            Assert.IsFalse(objectNotification.IsValid);
            Assert.AreNotEqual(2, objectNotification.Errors);

            // Validation contact.LastName should result with only one error.
            var propertyNotification = ValidationCatalog.ValidateProperty(contact, c => c.LastName);

            Assert.IsFalse(propertyNotification.IsValid);
            Assert.AreNotEqual(1, propertyNotification.Errors);
        }
コード例 #28
0
        public void ValidationContainer_Initialize()
        {
            //Create Rules Adhoc
            ValidationCatalog.AddSpecification <Contact>(x =>
            {
                x.Check(contact => contact.LastName).Required();
                x.Check(contact => contact.FirstName).Required();
                x.Check(contact => contact.DateOfBirth).Optional()
                .GreaterThan(
                    new DateTime(1950, 1, 1));
            });

            //Dummy Contact
            var emptyContact = new Contact();

            emptyContact.FirstName = null;
            emptyContact.LastName  = null;

            //Validate
            ValidationNotification notification = ValidationCatalog.Validate(emptyContact);

            Assert.That(notification.Errors, Is.Not.Empty);
        }
コード例 #29
0
        public void When_multiple_specifications_defined_with_default_spec_defined_return_default()
        {
            Assembly assembly = Assembly.LoadFrom("SpecExpress.Test.Domain.dll");

            ValidationCatalog.Scan(x => x.AddAssembly(assembly));

            //Add Default specification with optional last name
            ValidationCatalog.AddSpecification <SpecExpress.Test.Domain.Entities.Contact>(spec =>
            {
                spec.IsDefaultForType();
                spec.Check(c => c.LastName).Optional();
            });

            //Add Secondary specification with required last name
            ValidationCatalog.AddSpecification <SpecExpress.Test.Domain.Entities.Contact>(spec => spec.Check(c => c.LastName).Required());

            //Create valid object, with null Last Name
            var contact = new SpecExpress.Test.Domain.Entities.Contact();

            var vn = ValidationCatalog.Validate(contact);

            Assert.That(vn.IsValid, Is.True);
        }
コード例 #30
0
        public void ValidateProperty_CollectionProperty_ReturnsValidationNotification()
        {
            //Create Rules Adhoc
            ValidationCatalog.AddSpecification <Address>(x =>
            {
                x.Check(a => a.Street)
                .Required()
                .MaxLength(50);
            });

            ValidationCatalog.AddSpecification <Contact>(x =>
            {
                x.Check(c => c.Addresses).Required()
                .ForEachSpecification <Address>();
                x.Check(c => c.FirstName).Required().MaxLength(100);
            });

            var contact = new Contact();

            contact.Addresses = new List <Address>()
            {
                new Address()
            };

            // Validating contact as a whole should result in two errors.
            var objectNotification = ValidationCatalog.Validate(contact);

            Assert.IsFalse(objectNotification.IsValid);
            Assert.AreEqual(2, objectNotification.Errors.Count);

            // Validation contact.LastName should result with only one error.
            var propertyNotification = ValidationCatalog.ValidateProperty(contact, c => c.Addresses);

            Assert.IsFalse(propertyNotification.IsValid);
            Assert.AreEqual(1, propertyNotification.Errors.Count);
        }