public void GivenAnInvalidNarrative_WhenProcessingABundle_ThenAValidationMessageWithAFhirPathIsCreated(string maliciousNarrative) { var defaultObservation = Samples.GetDefaultObservation().ToPoco <Observation>(); defaultObservation.Text.Div = maliciousNarrative; var defaultPatient = Samples.GetDefaultPatient().ToPoco <Patient>(); defaultPatient.Text.Div = maliciousNarrative; var bundle = new Bundle(); bundle.Entry.Add(new Bundle.EntryComponent { Resource = defaultObservation }); bundle.Entry.Add(new Bundle.EntryComponent { Resource = defaultPatient }); var result = _validator.Validate( new PropertyValidatorContext( new ValidationContext(bundle.ToResourceElement()), PropertyRule.Create <ResourceElement, ResourceElement>(x => x), "Resource")); List <ValidationFailure> validationFailures = result as List <ValidationFailure> ?? result.ToList(); Assert.NotEmpty(validationFailures); var expectedObservationFhirPath = defaultObservation.TypeName + "." + KnownFhirPaths.ResourceNarrative; var expectedPatientFhirPath = defaultPatient.TypeName + "." + KnownFhirPaths.ResourceNarrative; Assert.Equal(expectedObservationFhirPath, validationFailures[0].PropertyName); Assert.Equal(expectedPatientFhirPath, validationFailures[1].PropertyName); }
private PropertyRule CreateRule(Expression <Func <TestObject, object> > expression) { var rule = PropertyRule.Create(expression); rule.AddValidator(new NotNullValidator()); return(rule); }
public void PropertyDescription_should_return_custom_property_name() { var builder = new RuleBuilder <Person, DateTime>(PropertyRule.Create <Person, DateTime>(x => x.DateOfBirth), null); builder.NotEqual(default(DateTime)).WithName("Foo"); builder.Rule.GetDisplayName().ShouldEqual("Foo"); }
public void GivenAnInvalidNarrative_WhenProcessingABundle_ThenAValidationMessageIsCreated(string maliciousNarrative) { Observation defaultObservation = Samples.GetDefaultObservation(); defaultObservation.Text.Div = maliciousNarrative; Patient defaultPatient = Samples.GetDefaultPatient(); defaultPatient.Text.Div = maliciousNarrative; var bundle = new Bundle(); bundle.Entry.Add(new Bundle.EntryComponent { Resource = defaultObservation }); bundle.Entry.Add(new Bundle.EntryComponent { Resource = defaultPatient }); var result = _validator.Validate( new PropertyValidatorContext( new ValidationContext(bundle), PropertyRule.Create <Bundle, Resource>(x => x), "Resource")); Assert.NotEmpty(result); }
public void Nullable_object_with_async_condition_should_not_throw() { var builder = new RuleBuilder <Person, int>(PropertyRule.Create <Person, int>(x => x.NullableInt.Value), null); builder.GreaterThanOrEqualTo(3).WhenAsync(async(x, c) => x.NullableInt != null); builder.Rule.Validate(new ValidationContext <Person>(new Person(), new PropertyChain(), new DefaultValidatorSelector())); }
public IRuleBuilder <ElementWrapper <T>, T> CreateRule() { var rule = PropertyRule.Create <ElementWrapper <T>, T>(x => x.Element, () => this.itemValidator.CascadeMode); this.itemValidator.AddRule(rule); return(new RuleBuilder <ElementWrapper <T>, T>(rule)); }
public void Rule_for_a_non_memberexpression_should_not_generate_property_name() { var builder = new RuleBuilder <Person, int>(PropertyRule.Create <Person, int>(x => x.CalculateSalary()), null); builder.Rule.GetDisplayName().ShouldBeNull(); builder.Rule.PropertyName.ShouldBeNull(); }
public IRuleBuilder <T, TProp> CreatePropertyRule <TProp>(System.Linq.Expressions.Expression <Func <T, TProp> > property) { var rule = PropertyRule.Create(property, () => this.propertyValidator.CascadeMode); this.propertyValidator.AddRule(rule); return(new RuleBuilder <T, TProp>(rule)); }
public void Result_should_use_custom_property_name_when_no_property_name_can_be_determined() { var builder = new RuleBuilder<Person, int>(PropertyRule.Create<Person, int>(x => x.CalculateSalary()),null); builder.GreaterThan(100).WithName("Foo"); var results = builder.Rule.Validate(new ValidationContext<Person>(new Person(), new PropertyChain(), new DefaultValidatorSelector())); results.Single().PropertyName.ShouldEqual("Foo"); }
public When_validating_an_invalid_iban() { var rule = PropertyRule.Create <TestModel, string>(x => x.BankAccountNumber); var validationContext = new ValidationContext <TestModel>(new TestModel()); _propertyValidatorContext = new PropertyValidatorContext(validationContext, rule, null, AttemptedIbanValue); }
/* Note: * > ValidationFailure.ErrorMessage displays a user-friendly property name (generated by PropertyRule.GetDisplayName) * > ValidationFailure.PropertyName represents the technical property name (generated by PropertyRule.BuildPropertyName) */ public override void SetUp() { base.SetUp(); _propertyRule = PropertyRule.Create(ExpressionHelper.GetTypedMemberExpression <Customer, string> (c => c.LastName)); _propertyRule.AddValidator(new NotNullValidator()); _customer = new Customer(); }
public void Conditional_child_validator_should_register_with_validator_type_not_property() { var builder = new RuleBuilder <Person, Address>(PropertyRule.Create <Person, Address>(x => x.Address), null); builder.SetValidator((Person person) => new NoopAddressValidator()); builder.Rule.Validators.OfType <ChildValidatorAdaptor>().Single().ValidatorType.ShouldEqual(typeof(NoopAddressValidator)); }
public override void SetUp() { base.SetUp(); PropertyRule rule = PropertyRule.Create <TestModel, string>(x => x.BankAccountNumber); _propertyValidatorContext = new PropertyValidatorContext(null, rule, null, AttemptedIbanValue); }
public void SetUp() { _memberInformationGlobalizationServiceMock = MockRepository.GenerateStrictMock <IMemberInformationGlobalizationService>(); _validationRule = MockRepository.GenerateStub <IValidationRule>(); _propertyRule = PropertyRule.Create(ExpressionHelper.GetTypedMemberExpression <Customer, string> (c => c.LastName)); _service = new PropertyDisplayNameGlobalizationService(_memberInformationGlobalizationServiceMock); }
/// <summary> /// Defines a validation rule for a specify property. /// </summary> /// <example> /// RuleFor(x => x.Surname)... /// </example> /// <typeparam name="TProperty">The type of property being validated</typeparam> /// <param name="expression">The expression representing the property to validate</param> /// <returns>an IRuleBuilder instance on which validators can be defined</returns> public IRuleBuilderInitial <T, TProperty> RuleFor <TProperty>(Expression <Func <T, TProperty> > expression) { expression.Guard("Cannot pass null to RuleFor"); var rule = PropertyRule.Create(expression, () => CascadeMode); AddRule(rule); var ruleBuilder = new RuleBuilder <T, TProperty>(rule); return(ruleBuilder); }
public void Should_throw_when_property_name_is_null() { var builder = new RuleBuilder <Person, int>(PropertyRule.Create <Person, int>(x => x.CalculateSalary())); builder.GreaterThan(4); var ex = typeof(InvalidOperationException).ShouldBeThrownBy(() => builder.Rule.Validate(new ValidationContext <Person>(new Person(), new PropertyChain(), new DefaultValidatorSelector())).ToList()); ex.Message.ShouldEqual("Property name could not be automatically determined for expression x => x.CalculateSalary(). Please specify either a custom property name by calling 'WithName'."); }
/// <summary> /// Defines a concept validation rule for a specify property. /// </summary> /// <typeparam name="T">Type to add validation rules for.</typeparam> /// <typeparam name="TProperty">The type of property being validated.</typeparam> /// <param name="validator">The validator to apply the validation rule to.</param> /// <param name="expression">The expression representing the property to validate.</param> /// <returns>an IRuleBuilder instance on which validators can be defined.</returns> public static IRuleBuilderInitial <T, TProperty> AddRuleForConcept <T, TProperty>( this AbstractValidator <T> validator, Expression <Func <T, TProperty> > expression) { var rule = PropertyRule.Create(expression, () => validator.CascadeMode); rule.PropertyName = FromExpression(expression) ?? typeof(TProperty).Name; validator.AddRule(rule); return(new RuleBuilder <T, TProperty>(rule)); }
public void SetUp() { _validationCollectorProviderMock = MockRepository.GenerateStrictMock <IValidationCollectorProvider>(); _validationCollectorMergerMock = MockRepository.GenerateStrictMock <IValidationCollectorMerger>(); _metaRulesValidatorFactoryStub = MockRepository.GenerateStub <IMetaRulesValidatorFactory>(); _metaRuleValidatorMock = MockRepository.GenerateStrictMock <IMetaRuleValidator>(); _validationRuleGlobalizationServiceMock = MockRepository.GenerateStrictMock <IValidationRuleMetadataService>(); _memberInformationNameResolverMock = MockRepository.GenerateStrictMock <IMemberInformationNameResolver>(); _collectorValidatorMock = MockRepository.GenerateStrictMock <ICollectorValidator> (); _metaValidationRule1Stub = MockRepository.GenerateStub <IAddingComponentPropertyMetaValidationRule>(); _metaValidationRule2Stub = MockRepository.GenerateStub <IAddingComponentPropertyMetaValidationRule>(); _metaValidationRule3Stub = MockRepository.GenerateStub <IAddingComponentPropertyMetaValidationRule>(); _componenValidationCollectorStub1 = MockRepository.GenerateStub <IComponentValidationCollector>(); _componenValidationCollectorStub1.Stub(stub => stub.AddedPropertyMetaValidationRules).Return(new[] { _metaValidationRule1Stub }); _componenValidationCollectorStub2 = MockRepository.GenerateStub <IComponentValidationCollector>(); _componenValidationCollectorStub2.Stub(stub => stub.AddedPropertyMetaValidationRules) .Return(new[] { _metaValidationRule2Stub, _metaValidationRule3Stub }); _componenValidationCollectorStub3 = MockRepository.GenerateStub <IComponentValidationCollector>(); _componenValidationCollectorStub3.Stub(stub => stub.AddedPropertyMetaValidationRules) .Return(new IAddingComponentPropertyMetaValidationRule[0]); _validationCollectorInfo1 = new ValidationCollectorInfo( _componenValidationCollectorStub1, typeof(ApiBasedComponentValidationCollectorProvider)); _validationCollectorInfo2 = new ValidationCollectorInfo( _componenValidationCollectorStub2, typeof(ApiBasedComponentValidationCollectorProvider)); _validationCollectorInfo3 = new ValidationCollectorInfo( _componenValidationCollectorStub3, typeof(ApiBasedComponentValidationCollectorProvider)); _validationRuleStub1 = MockRepository.GenerateStub <IValidationRule>(); _validationRuleStub2 = MockRepository.GenerateStub <IValidationRule>(); _validationRuleStub3 = PropertyRule.Create(ExpressionHelper.GetTypedMemberExpression <Customer, string> (c => c.FirstName)); _validationRuleStub4 = PropertyRule.Create(ExpressionHelper.GetTypedMemberExpression <Customer, string> (c => c.LastName)); _fakeValidationRuleResult = new[] { _validationRuleStub1, _validationRuleStub2, _validationRuleStub3, _validationRuleStub4 }; _fakeValidationCollectorMergeResult = new ValidationCollectorMergeResult(_fakeValidationRuleResult, MockRepository.GenerateStub <ILogContext>()); _fluentValidationBuilder = new FluentValidatorBuilder( _validationCollectorProviderMock, _validationCollectorMergerMock, _metaRulesValidatorFactoryStub, _validationRuleGlobalizationServiceMock, _memberInformationNameResolverMock, _collectorValidatorMock); _validMetaValidationResult1 = MetaValidationRuleValidationResult.CreateValidResult(); _validMetaValidationResult2 = MetaValidationRuleValidationResult.CreateValidResult(); _invalidMetaValidationResult1 = MetaValidationRuleValidationResult.CreateInvalidResult("Error1"); _invalidMetaValidationResult2 = MetaValidationRuleValidationResult.CreateInvalidResult("Error2"); }
/// <summary> /// Defines a validation rule for a specify property. /// </summary> /// <example> /// RuleFor(x => x.Surname)... /// </example> /// <typeparam name="TProperty">The type of property being validated</typeparam> /// <param name="expression">The expression representing the property to validate</param> /// <returns>an IRuleBuilder instance on which validators can be defined</returns> public IRuleBuilder <T, TProperty> RuleFor <TProperty>( Expression <Func <T, TProperty> > expression) { expression.NotNull(nameof(expression)); var rule = PropertyRule.Create(expression); AddRule(rule); return(new RuleBuilder <T, TProperty>(rule)); }
/// <summary> /// Defines a validation rule for a specify property. /// </summary> /// <example> /// RuleFor(x => x.Surname)... /// </example> /// <typeparam name="TProperty">The type of property being validated</typeparam> /// <param name="expression">The expression representing the property to validate</param> /// <returns>an IRuleBuilder instance on which validators can be defined</returns> public IRuleBuilderInitial <T, TProperty> RuleForConcept <TProperty>(Expression <Func <T, TProperty> > expression) { if (expression == null) { throw new ArgumentException("Cannot pass null to RuleForConcept"); } var rule = PropertyRule.Create <T, TProperty>(expression, (Func <CascadeMode>)(() => this.CascadeMode)); rule.PropertyName = FromExpression(expression) ?? typeof(TProperty).Name; this.AddRule((IValidationRule)rule); return((IRuleBuilderInitial <T, TProperty>) new RuleBuilder <T, TProperty>(rule)); }
protected IEnumerable <ValidationError> Validate(object value) { var sut = CreateSubjectUnderTest(); return(sut.Validate(new PropertyValidatorContext( new ValidationContext(new TestClass { TestProperty = value, }), PropertyRule.Create <TestClass, object>((x) => x.TestProperty), "TestProperty"))); }
private void AddRequiredValidation <PropType>(string propName) { var expression = Common.Helpers.DynamicExpression.ParseLambda <T, PropType>(propName); var rule = PropertyRule.Create(expression, () => CascadeMode); dataAnnotationValidatiors.Add(rule); var ruleBuilder = new RuleBuilder <T, PropType>(rule, this); ruleBuilder.NotEmpty().WithMessage("وارد کردن «{PropertyName}» اجباری است."); }
private static IEnumerable <ValidationFailure> GetValidationFailures(ResourceElement defaultObservation) { var validator = new IdValidator(); var result = validator.Validate( new PropertyValidatorContext( new ValidationContext <ResourceElement>(defaultObservation), PropertyRule.Create <ResourceElement, string>(x => x.Id), "Id", defaultObservation.Id)); return(result); }
/// <summary> /// Defines a concept validation rule for a specify property. /// </summary> /// <typeparam name="T">Type to add validation rules for</typeparam> /// <typeparam name="TProperty">The type of property being validated</typeparam> /// <param name="validator">The validator to apply the validation rule to.</param> /// <param name="expression">The expression representing the property to validate</param> /// <returns>an IRuleBuilder instance on which validators can be defined</returns> public static IRuleBuilderInitial <T, TProperty> AddRuleForConcept <T, TProperty>( this AbstractValidator <T> validator, Expression <Func <T, TProperty> > expression) { if (expression == null) { throw new ArgumentException("Cannot pass null to RuleForConcept"); } var rule = PropertyRule.Create(expression, () => validator.CascadeMode); rule.PropertyName = FromExpression(expression) ?? typeof(TProperty).Name; validator.AddRule(rule); return(new RuleBuilder <T, TProperty>(rule)); }
public void GivenAnInvalidNarrative_WhenProcessingAResource_ThenAValidationMessageIsCreated(string maliciousNarrative) { Observation defaultObservation = Samples.GetDefaultObservation(); defaultObservation.Text.Div = maliciousNarrative; var result = _validator.Validate( new PropertyValidatorContext( new ValidationContext(defaultObservation), PropertyRule.Create <Observation, Resource>(x => x), "Resource")); Assert.NotEmpty(result); }
private RuleBuilder <T, TProperty> RuleForInternal <TProperty>(PropertyInfo propertyInfo) { var ruleBuilder = GetRuleBuilder <TProperty>(propertyInfo); if (ruleBuilder == null) { PropertyRule rule = PropertyRule.Create <T, TProperty>(propertyInfo, () => CascadeMode, LoadDisplayName); AddRule(rule); ruleBuilder = new RuleBuilder <T, TProperty>(rule); AddRuleBuilder(propertyInfo, ruleBuilder);//添加RuleBuilder return(ruleBuilder); } return(ruleBuilder); }
public void Valdiator_succeeds_when_item_is_valid() { var instance = new TestRequest { Value = 42 }; var validator = new ValueForValidator <int>(TestInteger.Validator); var selector = ValidatorOptions.ValidatorSelectors.DefaultValidatorSelectorFactory(); var context = new ValidationContext(instance, new PropertyChain(), selector); var propertyValidatorContext = new PropertyValidatorContext(context, PropertyRule.Create <TestRequest, int>(t => t.Value), nameof(TestRequest.Value)); var result = validator.Validate(propertyValidatorContext).ToList(); Assert.Empty(result); }
public IRuleBuilderInitial <T, TProperty> AddRule <TProperty>(Expression <Func <T, TProperty> > expression) { if (expression == null) { throw new ArgumentNullException("Cannot pass null to AddRule"); } var rule = PropertyRule.Create(expression, () => CascadeMode); NestedValidators.Add(rule); var ruleBuilder = new RuleBuilder <T, TProperty>(rule, this); return(ruleBuilder); }
public void when_Get_request_arrives_and_no_customerskey_provided_in_customerKeys_ReturnMe_message_should_be_sent() { var getParameters = new GetParameters(); getParameters.IwillSend = "KeyValuePair"; getParameters.ReturnMe = new ReturnMe(); getParameters.ReturnMe.CustomerKeys = new System.Collections.Generic.List <string>(); var expectedMessage = "Customer keys cannot be null or empty."; var context = new ValidationContext(getParameters, new PropertyChain(), ValidatorOptions.ValidatorSelectors.DefaultValidatorSelectorFactory()); var propertyValidatorContext = new PropertyValidatorContext(context, PropertyRule.Create <GetParameters, ReturnMe>(t => t.ReturnMe), "ReturnMe"); var validator = new ReturnMeValidator.CustomerKeysCannotBeEmpty(); var output = validator.Validate(propertyValidatorContext); var actualMessage = output.Select(x => x.ErrorMessage).ToList().Count > 0 ? output.Select(x => x.ErrorMessage).ToList()[0] : ""; Assert.AreEqual(expectedMessage, actualMessage); }
public void Valdiator_sets_proper_validation_message_when_item_is_invalid() { var instance = new TestRequest { Value = -42 }; var validator = new ValueForValidator <int>(TestInteger.Validator); var selector = ValidatorOptions.ValidatorSelectors.DefaultValidatorSelectorFactory(); var context = new ValidationContext(instance, new PropertyChain(), selector); var propertyValidatorContext = new PropertyValidatorContext(context, PropertyRule.Create <TestRequest, int>(t => t.Value), nameof(TestRequest.Value)); var result = validator.Validate(propertyValidatorContext).ToList(); Assert.NotEmpty(result); Assert.Equal("Value must be above zero", result.First().ErrorMessage); }