Example #1
0
 public override ValidationRuleResult Execute()
 {
     return(double.IsNaN(value) || double.IsInfinity(value)
                ? ValidationRuleResult.CreateInvalidResult(
                string.Format(Resources.NumberParameterRuleBase_Value_0_must_be_a_concrete_number, ParameterName))
                : ValidationRuleResult.ValidResult);
 }
Example #2
0
        public void GetCandidateMessageProviderTypesShouldReturnCorrectInfoForARule([Frozen] IGetsRuleMatchingInfoForMessageProviderType matchingInfoProvider,
                                                                                    IGetsMessageProviderTypeMatchingInfoForRule info1,
                                                                                    IGetsMessageProviderTypeMatchingInfoForRule info2,
                                                                                    IGetsMessageProviderTypeMatchingInfoForRule info3,
                                                                                    IGetsMessageProviderTypeMatchingInfoForRule info4,
                                                                                    IGetsMessageProviderTypeMatchingInfoForRule info5,
                                                                                    [RuleResult] ValidationRuleResult ruleResult)
        {
            // These have to be three different types, to avoid a no-dupes exception
            var providerType1 = typeof(object);
            var providerType2 = typeof(string);
            var providerType3 = typeof(int);

            Mock.Get(matchingInfoProvider).Setup(x => x.GetMatchingInfo(providerType1)).Returns(new[] { info1 });
            Mock.Get(matchingInfoProvider).Setup(x => x.GetMatchingInfo(providerType2)).Returns(new[] { info2, info3 });
            Mock.Get(matchingInfoProvider).Setup(x => x.GetMatchingInfo(providerType3)).Returns(new[] { info4, info5 });
            Mock.Get(info1).Setup(x => x.IsMatch(ruleResult)).Returns(true);
            Mock.Get(info1).Setup(x => x.GetPriority()).Returns(1);
            Mock.Get(info2).Setup(x => x.IsMatch(ruleResult)).Returns(false);
            Mock.Get(info2).Setup(x => x.GetPriority()).Returns(2);
            Mock.Get(info3).Setup(x => x.IsMatch(ruleResult)).Returns(false);
            Mock.Get(info3).Setup(x => x.GetPriority()).Returns(3);
            Mock.Get(info4).Setup(x => x.IsMatch(ruleResult)).Returns(true);
            Mock.Get(info4).Setup(x => x.GetPriority()).Returns(4);
            Mock.Get(info5).Setup(x => x.IsMatch(ruleResult)).Returns(true);
            Mock.Get(info5).Setup(x => x.GetPriority()).Returns(5);
            var options = Mock.Of <IOptions <MessageProviderTypeOptions> >(x => x.Value == new MessageProviderTypeOptions {
                MessageProviderTypes = new[] { providerType1, providerType2, providerType3 }
            });

            var sut = new MessageProviderRegistry(matchingInfoProvider, options);

            var expected = new[] {
        public void ExecuteAllRulesAsyncShouldReturnResultsForAllRules([Frozen] IExeucutesSingleRule ruleExecutor,
                                                                       SerialRuleExecutor sut,
                                                                       [ExecutableModel] ExecutableRuleAndDependencies rule1,
                                                                       [ExecutableModel] ExecutableRuleAndDependencies rule2,
                                                                       [ExecutableModel] ExecutableRuleAndDependencies rule3,
                                                                       IRuleExecutionContext executionContext,
                                                                       [RuleResult] ValidationRuleResult result1,
                                                                       [RuleResult] ValidationRuleResult result2,
                                                                       [RuleResult] ValidationRuleResult result3)
        {
            var allRules = new[] { rule1, rule2, rule3 };
            var sequence = new MockSequence();

            Mock.Get(executionContext).InSequence(sequence).Setup(x => x.GetRulesWhichMayBeExecuted()).Returns(() => allRules.Select(r => r.ExecutableRule));
            Mock.Get(executionContext).InSequence(sequence).Setup(x => x.GetRulesWhichMayBeExecuted()).Returns(() => Enumerable.Empty <ExecutableRule>());
            Mock.Get(ruleExecutor)
            .Setup(x => x.ExecuteRuleAsync(rule1.ExecutableRule, It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult(result1));
            Mock.Get(ruleExecutor)
            .Setup(x => x.ExecuteRuleAsync(rule2.ExecutableRule, It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult(result2));
            Mock.Get(ruleExecutor)
            .Setup(x => x.ExecuteRuleAsync(rule3.ExecutableRule, It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult(result3));

            Assert.That(async() => await sut.ExecuteAllRulesAsync(executionContext, default),
                        Is.EquivalentTo(new[] { result1, result2, result3 }));
        }
        public void Given_invalid_value_when_validating_it_should_return_error()
        {
            const string testValue = "XX";
            var          country   = new IbanCountry("NL")
            {
                Iban =
                {
                    Structure = "my-structure"
                }
            };

            _structureValidatorMock
            .Setup(m => m.Validate(testValue))
            .Returns(false)
            .Verifiable();

            // Act
            ValidationRuleResult actual = _sut.Validate(new ValidationRuleContext(testValue)
            {
                Country = country
            });

            // Assert
            actual.Should().BeOfType <InvalidStructureResult>();
            _structureValidatorMock.Verify();
            _structureValidationFactoryMock.Verify(m => m.CreateValidator(country.TwoLetterISORegionName, country.Iban.Structure), Times.Once);
        }
 /// <inheritdoc/>
 public IEnumerable <MessageProviderInfo> GetMessageProviderInfo(ValidationRuleResult ruleResult)
 {
     return((from providerInfo in wrapped.GetMessageProviderInfo(ruleResult)
             where !(providerInfo.MessageProvider is null)
             select providerInfo)
            .ToList());
 }
Example #6
0
 public override ValidationRuleResult Execute()
 {
     return(!value.IsConcreteAngle()
                ? ValidationRuleResult.CreateInvalidResult(
                string.Format(Resources.NumberParameterRuleBase_Value_0_must_be_a_concrete_number, ParameterName))
                : ValidationRuleResult.ValidResult);
 }
        public void Given_no_country_when_validating_it_should_return_error()
        {
            ValidationRuleResult actual = _sut.Validate(new ValidationRuleContext(string.Empty));

            // Assert
            actual.Should().BeOfType <InvalidStructureResult>();
            _structureValidationFactoryMock.Verify(m => m.CreateValidator(It.IsAny <string>(), It.IsAny <string>()), Times.Never);
        }
 /// <inheritdoc/>
 public IEnumerable <MessageProviderInfo> GetMessageProviderInfo(ValidationRuleResult ruleResult)
 {
     return((from typeInfo in typeRegistry.GetCandidateMessageProviderTypes(ruleResult)
             let factoryStrategy = factoryStrategySelector.GetMessageProviderFactory(typeInfo, ruleResult.RuleInterface)
                                   where !(factoryStrategy is null)
                                   select GetMessageProviderInfo(factoryStrategy, typeInfo, ruleResult))
            .ToList());
 }
Example #9
0
 public override ValidationRuleResult Execute()
 {
     return(lowerLimit.CompareTo(value) >= 0
                ? ValidationRuleResult.CreateInvalidResult(
                string.Format(Resources.NumericRule_Value_0_must_be_greater_or_equal_to_LowerLimit_1_Current_value_2,
                              ParameterName, lowerLimit, value))
                : ValidationRuleResult.ValidResult);
 }
 /// <inheritdoc/>
 public IEnumerable <MessageProviderInfo> GetMessageProviderInfo(ValidationRuleResult ruleResult)
 {
     return((from providerInfo in wrapped.GetMessageProviderInfo(ruleResult)
             let criteria = criteriaFactory.GetNonGenericMessageCriteria(providerInfo, ruleResult.RuleInterface)
                            where criteria.CanGetFailureMessage(ruleResult)
                            select GetMessageProviderInfo(providerInfo, criteria))
            .ToList());
 }
Example #11
0
        /// <summary>
        /// Gets the most appropriate message provider implementation for getting a feedback message for the
        /// specified <see cref="ValidationRuleResult"/>.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This method uses an instance of <see cref="IGetsMessageProviderInfo"/> to get a collection of candidate
        /// <see cref="MessageProviderInfo"/> instances which could provide a message for the specified rule result.
        /// Once the message provider infos are retrieved, the provider with the highest numeric
        /// <see cref="MessageProviderTypeInfo.Priority"/> is selected and its <see cref="MessageProviderInfo.MessageProvider"/>
        /// implementation is returned as the result of this method.
        /// </para>
        /// <para>
        /// If this method returns a <see langword="null" /> reference then this indicates that there is no message provider
        /// suitable for providing the message for the specified rule result.
        /// If the <see cref="IGetsMessageProviderInfo"/> returned more than one <see cref="MessageProviderInfo"/>
        /// which are tied for the highest priority then any of these may be returned by this method, and results might not
        /// be stable.  Developers are encouraged to avoid message providers with tied priorities.
        /// </para>
        /// <para>
        /// The instance of <see cref="IGetsMessageProviderInfo"/> used is retrieved using a <see cref="IGetsMessageProviderInfoFactory"/>.
        /// </para>
        /// </remarks>
        /// <seealso cref="IGetsMessageProviderInfoFactory"/>
        /// <seealso cref="IGetsMessageProviderInfo"/>
        /// <seealso cref="MessageProviderInfo"/>
        /// <seealso cref="MessageProviderTypeInfo"/>
        /// <seealso cref="MessageProviderInfoFactory"/>
        /// <seealso cref="NullExcludingMessageProviderInfoDecorator"/>
        /// <seealso cref="CriteriaApplyingMessageProviderInfoDecorator"/>
        /// <param name="ruleResult">The validation rule result for which to get a message provider.</param>
        /// <returns>Either an implementation of <see cref="IGetsFailureMessage"/>, or a <see langword="null" />
        /// reference, if no message provider is suitable for the result.</returns>
        public IGetsFailureMessage GetProvider(ValidationRuleResult ruleResult)
        {
            var providerInfoFactory = providerInfoFactoryFactory.GetProviderInfoFactory();

            return((from providerInfo in providerInfoFactory.GetMessageProviderInfo(ruleResult)
                    orderby providerInfo.Priority descending
                    select providerInfo.MessageProvider)
                   .FirstOrDefault());
        }
Example #12
0
        public void ValidResult_Always_ReturnsExpectedValidationRuleResult()
        {
            // Call
            ValidationRuleResult result = ValidationRuleResult.ValidResult;

            // Assert
            Assert.That(result.IsValid, Is.True);
            Assert.That(result.ValidationMessage, Is.Empty);
        }
Example #13
0
        /// <summary>
        /// Gets a value that indicates whether this attribute is a match for the specified validation rule result.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This method is used to determine whether a class decorated with this attribute is eligible to be used to
        /// provide a message for the specified result.
        /// </para>
        /// </remarks>
        /// <param name="result">A validation rule result.</param>
        /// <returns><see langword="true" /> if this attribute matches the specified result; <see langword="false" /> otherwise.</returns>
        /// <exception cref="ArgumentNullException">If the <paramref name="result"/> is <see langword="null" />.</exception>
        public bool IsMatch(ValidationRuleResult result)
        {
            if (result is null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            return(ValidationFunctions.All(func => func(result)));
        }
Example #14
0
        public void CreateInvalidResult_WithInvalidMessage_ThrowsArgumentException(string invalidMessage)
        {
            // Call
            TestDelegate call = () => ValidationRuleResult.CreateInvalidResult(invalidMessage);

            // Assert
            const string expectedMessage = "Value cannot be null or whitespace.";

            TestHelper.AssertThrowsArgumentException <ArgumentException>(call, expectedMessage);
        }
Example #15
0
        bool DoesParentValidatedTypeMatch(ValidationRuleResult result)
        {
            if (ParentValidatedType is null)
            {
                return(true);
            }
            var parentContext = result.RuleContext.AncestorContexts.FirstOrDefault();

            return(!(parentContext is null) && ParentValidatedType.GetTypeInfo().IsAssignableFrom(parentContext.ValueInfo.ValidatedType.GetTypeInfo()));
        }
Example #16
0
        /// <inheritdoc/>
        public bool Validate()
        {
            ValidationRuleResult validationRuleResult = GetValidationRuleResult();

            if (validationRuleResult.Status == ValidationRuleResult.SUCCESS)
            {
                return(true);
            }
            return(false);
        }
 public void GetCandidateMessageProviderTypesShouldAlwaysReturnWrappedResults([Frozen] IGetsCandidateMessageTypes wrapped,
                                                                              RuleWithMessageCandidateTypeDecorator sut,
                                                                              MessageProviderTypeInfo typeInfo1,
                                                                              MessageProviderTypeInfo typeInfo2,
                                                                              MessageProviderTypeInfo typeInfo3,
                                                                              [RuleResult] ValidationRuleResult result)
 {
     Mock.Get(wrapped).Setup(x => x.GetCandidateMessageProviderTypes(result)).Returns(new[] { typeInfo1, typeInfo2, typeInfo3 });
     Assert.That(() => sut.GetCandidateMessageProviderTypes(result), Is.SupersetOf(new[] { typeInfo1, typeInfo2, typeInfo3 }));
 }
Example #18
0
        public void Validate_WithTwoInvalidModels_ExecutesAllRulesAndReturnsInvalidResult()
        {
            // Setup
            var validationRuleOne = Substitute.For <IDataModelValidationRule>();

            validationRuleOne.Execute().Returns(ValidationRuleResult.ValidResult);

            const string validationErrorOne       = "Validation Error One";
            var          invalidValidationRuleOne = Substitute.For <IDataModelValidationRule>();

            invalidValidationRuleOne.Execute().Returns(ValidationRuleResult.CreateInvalidResult(validationErrorOne));

            var invalidProviderOne = Substitute.For <IDataModelRuleProvider>();

            invalidProviderOne.GetDataModelValidationRules().Returns(new[]
            {
                validationRuleOne,
                invalidValidationRuleOne
            });

            var validationRuleTwo = Substitute.For <IDataModelValidationRule>();

            validationRuleTwo.Execute().Returns(ValidationRuleResult.ValidResult);

            const string validationErrorTwo       = "Validation Error Two";
            var          invalidValidationRuleTwo = Substitute.For <IDataModelValidationRule>();

            invalidValidationRuleTwo.Execute().Returns(ValidationRuleResult.CreateInvalidResult(validationErrorTwo));

            var invalidProviderTwo = Substitute.For <IDataModelRuleProvider>();

            invalidProviderTwo.GetDataModelValidationRules().Returns(new[]
            {
                validationRuleTwo,
                invalidValidationRuleTwo
            });

            IDataModelRuleProvider[] models =
            {
                invalidProviderOne,
                invalidProviderTwo
            };

            // Call
            DataModelValidatorResult result = DataModelValidator.Validate(models);

            // Assert
            Assert.That(result.IsValid, Is.False);
            CollectionAssert.AreEquivalent(new[]
            {
                validationErrorOne,
                validationErrorTwo
            }, result.ValidationMessages);
        }
        public void Given_that_no_validator_matches_iban_country_when_validating_it_should_pass()
        {
            var context = new ValidationRuleContext("XX000000", new IbanCountry("XX"));

            // Act
            ValidationRuleResult actual = _sut.Validate(context);

            // Assert
            actual.Should().BeSameAs(ValidationRuleResult.Success);
            _checkDigitsValidatorMock.Verify(m => m.Validate(It.IsAny <string>()), Times.Never);
        }
Example #20
0
        public void CreateInvalidResult_WithValidMessage_ReturnsExpectedValidationRuleResult()
        {
            // Setup
            const string message = "ValidationMessage";

            // Call
            ValidationRuleResult result = ValidationRuleResult.CreateInvalidResult(message);

            // Assert
            Assert.That(result.IsValid, Is.False);
            Assert.That(result.ValidationMessage, Is.EqualTo(message));
        }
        public void Given_country_info_is_null_when_validating_it_should_return_error()
        {
            var context = new ValidationRuleContext(string.Empty)
            {
                Country = null
            };

            // Act
            ValidationRuleResult actual = _sut.Validate(context);

            // Assert
            actual.Should().BeOfType <InvalidLengthResult>();
        }
Example #22
0
        public ValidationRuleResult IsValid(FM36Global global)
        {
            if (global.UKPRN == 0)
            {
                return(ValidationRuleResult.Failure("Invalid ukprn"));
            }

            if (string.IsNullOrWhiteSpace(global.Year))
            {
                return(ValidationRuleResult.Failure("Empty collection year."));
            }

            return(ValidationRuleResult.Ok());
        }
        public void Given_that_bban_structure_length_is_zero_when_validating_it_should_fail()
        {
            var context = new ValidationRuleContext("ZZ000000", new IbanCountry("ZZ")
            {
                Bban = new BbanStructure(new TestPattern(Enumerable.Empty <PatternToken>()))
            });

            // Act
            ValidationRuleResult actual = _sut.Validate(context);

            // Assert
            actual.Should().BeOfType <InvalidNationalCheckDigitsResult>();
            _checkDigitsValidatorMock.Verify(m => m.Validate(It.IsAny <string>()), Times.Never);
        }
        public void IsMatchShouldReturnFalseIfTheRuleInterfaceIsSpecifiedButDoesNotMatch([RuleResult] RuleResult result,
                                                                                         [ManifestModel] ManifestRule rule,
                                                                                         RuleIdentifier id,
                                                                                         object actualValue,
                                                                                         IValidationLogic validationLogic)
        {
            var context    = new RuleContext(rule, id, actualValue, Enumerable.Empty <ValueContext>(), typeof(string));
            var ruleResult = new ValidationRuleResult(result, context, validationLogic);
            var sut        = new FailureMessageStrategyAttribute
            {
                RuleInterface = typeof(int),
            };

            Assert.That(() => sut.IsMatch(ruleResult), Is.False);
        }
Example #25
0
 public ValidationRuleResult IsValid(FM36Learner learner)
 {
     foreach (var priceEpisode in learner.PriceEpisodes)
     {
         var overlappingPriceEpisode = learner.PriceEpisodes
                                       .Where(pe => pe != priceEpisode)
                                       .FirstOrDefault(pe =>
                                                       (priceEpisode.PriceEpisodeValues.PriceEpisodeActualEndDate ?? priceEpisode.PriceEpisodeValues.PriceEpisodePlannedEndDate) > pe.PriceEpisodeValues?.EpisodeStartDate &&
                                                       priceEpisode.PriceEpisodeValues.EpisodeStartDate < (pe.PriceEpisodeValues.PriceEpisodeActualEndDate ?? pe.PriceEpisodeValues?.PriceEpisodePlannedEndDate));
         if (overlappingPriceEpisode != null)
         {
             return(ValidationRuleResult.Failure($"Found overlapping price episodes.  Price Episode {priceEpisode.PriceEpisodeIdentifier} overlapped with price episode {overlappingPriceEpisode.PriceEpisodeIdentifier}."));
         }
     }
     return(ValidationRuleResult.Ok());
 }
        async Task <string> GetMessageAsync(ValidationRuleResult ruleResult, CancellationToken cancellationToken)
        {
            if (outcomesWhichDontGetMessages.Contains(ruleResult.Outcome))
            {
                return(null);
            }

            var messageProvider = messageProviderFactory.GetProvider(ruleResult);

            if (messageProvider is null)
            {
                return(null);
            }

            return(await messageProvider.GetFailureMessageAsync(ruleResult, cancellationToken).ConfigureAwait(false));
        }
Example #27
0
        public void Execute_WithNonConcreteValues_ReturnsExpectedValidationResult(double invalidValue)
        {
            // Setup
            const string parameterName = "ParameterName";
            var          rule          = new DoubleParameterConcreteValueRule(parameterName, invalidValue);

            // Call
            ValidationRuleResult result = rule.Execute();

            // Assert
            Assert.That(result.IsValid, Is.False);

            var expectedMessage = $"{parameterName} must be a concrete number.";

            Assert.That(result.ValidationMessage, Is.EqualTo(expectedMessage));
        }
Example #28
0
        public void Execute_WithValidValue_ReturnsValidResult()
        {
            // Setup
            const string parameterName = "ParameterName";

            var    random = new Random(21);
            double value  = random.NextDouble();

            var rule = new DoubleParameterConcreteValueRule(parameterName, value);

            // Call
            ValidationRuleResult result = rule.Execute();

            // Assert
            Assert.That(result, Is.SameAs(ValidationRuleResult.ValidResult));
        }
        public void GetFailureMessageAsyncShouldCallWrappedServiceWithOneGenericType([Frozen] IGetsFailureMessage <string> wrapped,
                                                                                     FailureMessageProviderAdapter <string> sut,
                                                                                     [RuleResult] RuleResult ruleResult,
                                                                                     [ManifestModel] ManifestRule rule,
                                                                                     Type ruleInterface,
                                                                                     RuleIdentifier id,
                                                                                     string actualValue,
                                                                                     string expectedResult,
                                                                                     IValidationLogic validationLogic)
        {
            var context = new RuleContext(rule, id, actualValue, Enumerable.Empty <ValueContext>(), ruleInterface);
            var validationRuleResult = new ValidationRuleResult(ruleResult, context, validationLogic);

            Mock.Get(wrapped).Setup(x => x.GetFailureMessageAsync(actualValue, validationRuleResult, default)).Returns(Task.FromResult(expectedResult));
            Assert.That(async() => await sut.GetFailureMessageAsync(validationRuleResult), Is.EqualTo(expectedResult));
        }
Example #30
0
        public void Validate_WithOneValidAndOneInvalidDataModel_ExecutesAllRulesAndReturnsInvalidResult()
        {
            // Setup
            var validationRuleOne = Substitute.For <IDataModelValidationRule>();

            validationRuleOne.Execute().Returns(ValidationRuleResult.ValidResult);

            var validProvider = Substitute.For <IDataModelRuleProvider>();

            validProvider.GetDataModelValidationRules().Returns(new[]
            {
                validationRuleOne
            });

            var validationRuleTwo = Substitute.For <IDataModelValidationRule>();

            validationRuleTwo.Execute().Returns(ValidationRuleResult.ValidResult);

            const string validationError       = "Validation Error";
            var          invalidValidationRule = Substitute.For <IDataModelValidationRule>();

            invalidValidationRule.Execute().Returns(ValidationRuleResult.CreateInvalidResult(validationError));

            var invalidProvider = Substitute.For <IDataModelRuleProvider>();

            invalidProvider.GetDataModelValidationRules().Returns(new[]
            {
                validationRuleTwo,
                invalidValidationRule
            });

            IDataModelRuleProvider[] models =
            {
                validProvider,
                invalidProvider
            };

            // Call
            DataModelValidatorResult result = DataModelValidator.Validate(models);

            // Assert
            Assert.That(result.IsValid, Is.False);
            CollectionAssert.AreEqual(new[]
            {
                validationError
            }, result.ValidationMessages);
        }