public RecordingRuleBuilder(RecordedCallRule rule, RuleBuilder wrappedBuilder) { this.rule = rule; this.wrappedBuilder = wrappedBuilder; rule.Applicator = x => { }; }
public void Test_RuleBuilder_NoProperty() { var v = new RuleBuilder<ValidateFailure, ValidateFailure>(_Validation); v.SetValueGetter(i => i); Assert.Equal(string.Empty, v.ValueName); var result = new ValidateFailure(); Assert.Equal(result, v.ValueGetter((object)result)); }
public void Setup() { Fake.InitializeFixture(this); this.fakeManager = A.Fake<FakeManager>(o => o.CallsBaseMethods()); this.builder = this.CreateBuilder(); }
public void Setup() { this.wrappedBuilder = A.Fake<RuleBuilder>(x => x.WithArgumentsForConstructor(() => new RuleBuilder(A.Fake<BuildableCallRule>(), A.Fake<FakeManager>(), c => A.Fake<IFakeAsserter>()))); this.rule = A.Fake<RecordedCallRule>(); this.builder = new RecordingRuleBuilder(this.rule, this.wrappedBuilder); }
public void Test_RuleBuilder_OverrideName() { var v = new RuleBuilder<TestRuleBuilderClass, string>(_Validation); v.SetValueGetter(i => i.Failure.Error); Assert.Equal("Failure.Error", v.ValueName); var name = "go"; v.ValueName = name; Assert.Equal(name, v.ValueName); }
public void Test_RuleBuilder_OverrideError() { var v = new RuleBuilder<TestRuleBuilderClass, string>(_Validation); v.SetValueGetter(i => i.Failure.Error); Assert.Equal(null, v.Error); var error = "go"; v.Error = error; Assert.Equal(error, v.Error); }
public void FlagReturnsInExperimentForRuleMatchWhenInExperimentVariationButNonExperimentRollout() { var user = User.WithKey("userkey"); var rollout = BuildRollout(RolloutKind.Rollout, false); var rule = new RuleBuilder().Id("id").Rollout(rollout).Clauses(ClauseBuilder.ShouldMatchUser(user)).Build(); var f = FeatureFlagWithRules(rule); var result = BasicEvaluator.Evaluate(f, baseUser, EventFactory.Default); Assert.Equal(EvaluationReasonKind.RuleMatch, result.Result.Reason.Kind); Assert.False(result.Result.Reason.InExperiment); }
// see https://httpd.apache.org/docs/2.4/rewrite/advanced.html#setenvvars public void AddAction_Throws_ChangeEnvNotSupported() { var builder = new RuleBuilder(); var flags = new Flags(); flags.SetFlag(FlagType.Env, "rewritten:1"); var ex = Assert.Throws <NotSupportedException>(() => builder.AddAction(null, flags)); Assert.Equal(Resources.Error_ChangeEnvironmentNotSupported, ex.Message); }
public void Test_RuleBuilder_ThenRuleFor() { var v = new RuleBuilder<TestRuleBuilderClass, string>(_Validation); var next = v.ThenRuleFor(i => i.Failure); Assert.NotNull(next); Assert.NotSame(v, next); Assert.NotNull((next as IRuleBuilder<TestRuleBuilderClass, ValidateFailure>).ValueGetter); var builder = next as IRuleMessageBuilder<TestRuleBuilderClass, ValidateFailure>; Assert.NotNull(builder); Assert.Equal("Failure", (builder as IValidateRuleBuilder).ValueName); }
public void Test_RuleBuilder_OneLevelProperty() { var v = new RuleBuilder<ValidateFailure, string>(_Validation); v.SetValueGetter(i => i.Error); Assert.Equal("Error", v.ValueName); var result = new ValidateFailure() { Error = "a" }; Assert.Equal(result.Error, v.ValueGetter(result)); }
/// <summary> /// Gets an Expression which calls the binding target if the method binding succeeded. /// /// Throws InvalidOperationException if the binding failed. /// /// OBSOLETE /// </summary> public Expression MakeExpression(RuleBuilder rule, IList <Expression> parameters) { ContractUtils.RequiresNotNull(rule, "rule"); if (_target == null) { throw new InvalidOperationException("An expression cannot be produced because the method binding was unsuccessful."); } return(MakeExpression(new ParameterBinderWithCodeContext(_target.Binder._binder, rule.Context), parameters)); }
public void Rule_Composite_With_Not_IsNumeric_And_IsBetween_Builder_Test() { var builder = new RuleBuilder() .If( n => n.Not( c => c.Field("Age").IsNumeric() .And( c.Field("Age").IsBetween("01", "62") .InputFilter(f => f.ToInteger()) .Or( c.Field("Age").IsBetween("67", "90") ) ) ) ) .Then( a => a.Message("Incorrect age range") ); var rule = builder.Build(); Assert.IsInstanceOfType(rule, typeof(Rule)); var condition = (NotCondition)rule.Condition; var innerCondition = (AndCondition)condition.Condition; var andLeftCondition = (FieldIsNumeric)innerCondition.Conditions.First(); Assert.AreEqual("Age", andLeftCondition.FieldName); var andRightCondition = (OrCondition)innerCondition.Conditions.Last(); var orLeftCondition = (FieldIsBetween <string>)andRightCondition.Conditions.First(); Assert.AreEqual("Age", orLeftCondition.FieldName); Assert.AreEqual("01", orLeftCondition.MinValue); Assert.AreEqual("62", orLeftCondition.MaxValue); var orRightCondition = (FieldIsBetween <string>)andRightCondition.Conditions.Last(); Assert.AreEqual("Age", orRightCondition.FieldName); Assert.AreEqual("67", orRightCondition.MinValue); Assert.AreEqual("90", orRightCondition.MaxValue); var task = (RuleMessageTask)rule.Tasks.Single(); Assert.AreEqual("Incorrect age range", task.Message); }
public void Required_SetsPropertyValidatorRequiredToTrue_ReturnsRuleBuilder() { // Create Dependancies PropertyValidator <Customer, string> validator = PropertyValidatorFactory.DefaultCustomerNameValidator(); // Test var actionOptionBuilder = new ActionOptionBuilder <Customer, string>(validator); RuleBuilder <Customer, string> requiredResult = actionOptionBuilder.Required(); // Assert Assert.That(requiredResult, Is.InstanceOf <RuleBuilder <Customer, string> >()); }
public void OperationTypeExceptionTest() { LinguisticVariable outputVariable = new LinguisticVariable("outputVar1", 1, 10); Term outputTerm = TermsFactory.Instance.CreateTermForVariable("outputVar", outputVariable, new TrapezoidalFunction()); // TODO : Variable input/output checking RuleBuilder builder = RuleBuilder.CreateBuilder(); Rule rule = builder .OutputTerm(outputTerm) .Build(); }
public void Rule_test() { var rule = new RuleBuilder().Builder(); _ruleRepository.Add(rule); _unitOfWork.Commit(); var result = _ruleRepository.GetById(rule.Id); result.Should().NotBeNull(); result.Should().Be(rule); }
public void WhenRuleIsDefault_GetRuleVersionShouldReturnValidVersion() { var rule = new RuleDescription { Name = "$Default", Filter = new SqlFilter("1=0") }; var ruleVersion = RuleBuilder.GetRuleVersion(rule); Assert.Equal(new Version(1, 0), ruleVersion.Version); }
public Rule <TContentType, TConditionType> CreateRule(RuleDataModel <TContentType, TConditionType> ruleDataModel) { if (ruleDataModel is null) { throw new ArgumentNullException(nameof(ruleDataModel)); } ContentContainer <TContentType> contentContainer = new ContentContainer <TContentType>(ruleDataModel.ContentType, (t) => (object)ruleDataModel.Content); RuleBuilderResult <TContentType, TConditionType> ruleBuilderResult = RuleBuilder.NewRule <TContentType, TConditionType>() .WithName(ruleDataModel.Name) .WithDatesInterval(ruleDataModel.DateBegin, ruleDataModel.DateEnd) .WithCondition(cnb => ruleDataModel.RootCondition is { } ? this.ConvertConditionNode(cnb, ruleDataModel.RootCondition) : null)
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}» اجباری است."); }
/// <summary> /// Adds a new validation rule to check whether a string is not null or empty. /// </summary> /// <typeparam name="TObject">The type of the object under validation.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="ruleBuilder">Current rule builder to add the rule to.</param> /// <param name="errorCreator">Function to create new objects of type <typeparamref name="TError"/></param> /// <param name="terminateValidationOnError">Specifies whether to stop the validation for current object if it does not pass the rule.</param> /// <returns>The same <see cref="RuleBuilder{TObject, string, TError}"/> instance so that multiple calls can be chained.</returns> /// <remarks> /// Does not allow empty strings. /// Stops the validation for current selector if the object does not pass this rule. /// </remarks> public static RuleBuilder <TObject, string, TError> IsRequired <TObject, TError>( this RuleBuilder <TObject, string, TError> ruleBuilder, Func <TError> errorCreator, bool terminateValidationOnError = false) { ruleBuilder.HasRule( x => x != null && x.Trim().Length != 0, errorCreator, stopValidationOnError: true, terminateValidationOnError: terminateValidationOnError); return(ruleBuilder); }
public void AddAction_DefaultRedirectStatusCode() { var builder = new RuleBuilder(); var flags = new Flags(); var pattern = new Pattern(new List <PatternSegment>()); flags.SetFlag(FlagType.Redirect, string.Empty); builder.AddAction(pattern, flags); var redirectAction = (RedirectAction)builder._actions[0]; Assert.Equal(StatusCodes.Status302Found, redirectAction.StatusCode); }
/// <summary> /// Provides functionality for defining a rule to check whether a selected property of type <typeparamref name="TSelectorResult"/> does not equal to its default value. /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <typeparam name="TSelectorResult">The type of the selector result.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="ruleBuilder">Current rule builder to add the rule to.</param> /// <param name="errorCreator">Function to create new objects of type <typeparamref name="TError"/></param> /// <param name="terminateValidationOnError">Specifies whether to stop the validation for current object if it does not pass the rule.</param> /// <returns>The same <see cref="RuleBuilder{TObject, TSelectorResult, TError}"/> instance so that multiple calls can be chained.</returns> /// <remarks> /// Rule uses default <see cref="EqualityComparer{T}"/> to check for equality with the default value of type <typeparamref name="TSelectorResult"/>. /// Stops the validation for current selector if the object does not pass this rule. /// </remarks> public static RuleBuilder <TObject, TSelectorResult, TError> IsRequired <TObject, TSelectorResult, TError>( this RuleBuilder <TObject, TSelectorResult, TError> ruleBuilder, Func <TError> errorCreator, bool terminateValidationOnError = false) { ruleBuilder.HasRule( x => !EqualityComparer <TSelectorResult> .Default.Equals(x, default), errorCreator, stopValidationOnError: true, terminateValidationOnError: terminateValidationOnError); return(ruleBuilder); }
protected override void Init() { SetValidator(nameof(Email), x => x.Email, RuleBuilder.Create() .AddRule(new IsEmail()) .Build()); SetValidator(nameof(Age), x => x.Age, RuleBuilder.Create() .AddRule(new IsNumber()) .AddRule(new LargerThan(18)) .Build()); }
public void RuleApplicationService_Remove() { var rule = new RuleBuilder().Builder(); _ruleRepository.Add(rule); _unitOfWork.Commit(); _ruleApplicationService.Remove(rule.Id); var result = _ruleRepository.Get(new Filter()); result.entities.Should().HaveCount(0); }
public void DoNotRunIfHasRuleViolation_ShouldRunClauseAdded() { var rule = new Rule ( "Rule1" ); var ruleBuilder = new RuleBuilder<RuleEngineContext<Customer>, Customer> ( rule ); ruleBuilder.DoNotRunIfHasRuleViolation (); var ruleEngineContext = new RuleEngineContext ( new Customer () ); ruleEngineContext.RuleViolationReporter.Report ( new RuleViolation ( rule, null, null ) ); var shouldRunResult = rule.ShouldRunRule ( ruleEngineContext ); Assert.IsFalse ( shouldRunResult ); }
public void RuleApplicationService_Enable() { var rule = new RuleBuilder().Disable().Builder(); _ruleRepository.Add(rule); _unitOfWork.Commit(); _ruleApplicationService.Enable(rule.Id); var entity = _ruleRepository.GetById(rule.Id); entity.Active.Should().BeTrue(); }
public void Test_RuleBuilder_OneLevelProperty() { var v = new RuleBuilder <ValidateFailure, string>(_Validation); v.SetValueGetter(i => i.Error); Assert.Equal("Error", v.ValueName); var result = new ValidateFailure() { Error = "a" }; Assert.Equal(result.Error, v.ValueGetter(result)); }
public void Test_RuleBuilder_ThenRuleFor() { var v = new RuleBuilder <TestRuleBuilderClass, string>(_Validation); var next = v.ThenRuleFor(i => i.Failure); Assert.NotNull(next); Assert.NotSame(v, next); Assert.NotNull((next as IRuleBuilder <TestRuleBuilderClass, ValidateFailure>).ValueGetter); var builder = next as IRuleMessageBuilder <TestRuleBuilderClass, ValidateFailure>; Assert.NotNull(builder); Assert.Equal("Failure", (builder as IValidateRuleBuilder).ValueName); }
public void TestRulesCheck() { var api = new TfsApi("https://msk-tfs1.securitycode.ru/tfs/Endpoint%20Security"); var builder = new RuleBuilder(); var rules = new List <IRule> { builder.BuildPresets(StaticRules.CheckTasksAreapath, new AreaPathParameter(@"SNES\Secret Net Server")) }; var inconsisant = builder.CheckInconsistant(rules, api); }
public void ReplaceTcpMatch() { var tcpMatch = new TcpMatchBuilder().SetSrcPort(200, 300) .SetFlags(new[] { "syn", "fin", "ack" }, new[] { "syn" }) .SetOption(16, true).Build(); var rule = new RuleBuilder() .SetIp4Src("192.168.5.2/23") .SetIp4Dst("192.168.5/24") .SetInInterface("eno8") .SetOutInterface("eno45", true, true) .SetProto("tCp") .AddMatch(tcpMatch) .Accept(); var tcpMatch2 = new TcpMatchBuilder().SetSrcPort(500, 600) .SetFlags(new[] { "syn", "fin", "ack" }, new[] { "syn" }) .SetOption(16, true).Build(); var rule2 = new RuleBuilder() .SetIp4Src("192.168.7.2/23") .SetIp4Dst("192.168.3/24") .SetInInterface("eno8") .SetOutInterface("eno45", true, true) .SetProto("tCp") .AddMatch(tcpMatch2) .Accept(); using (var wr = new IptTransaction(Tables.NAT)) { wr.AppendRule(Chains.POSTROUTING, rule); wr.Commit(); var rules = wr.GetRules(Chains.POSTROUTING); rule = rules.First(); var match = rule.Matches.First(); Assert.Equal("200:300", match[TcpMatchBuilder.SPORT_OPT]); var target = rule.Target; Assert.NotEmpty(rules); Assert.Equal(TargetTypes.ACCEPT, target.Name); } using (var wr = new IptTransaction(Tables.NAT)) { wr.ReplaceRule(Chains.POSTROUTING, 1, rule2); wr.Commit(); var rules = wr.GetRules(Chains.POSTROUTING); rule2 = rules.First(); var match = rule2.Matches.First(); Assert.Equal("500:600", match[TcpMatchBuilder.SPORT_OPT]); var target = rule.Target; Assert.NotEmpty(rules); Assert.Equal(TargetTypes.ACCEPT, target.Name); } }
public void Account_test() { var rule = new RuleBuilder().Builder(); var account = new AccountBuilder().WithRule(rule).Builder(); _ruleRepository.Add(rule); _accountRepository.Add(account); _unitOfWork.Commit(); var result = _accountRepository.GetById(account.Id); result.Should().NotBeNull(); result.Should().Be(account); }
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 Test_RuleBuilder_TwoLevelProperty() { var v = new RuleBuilder<TestRuleBuilderClass, string>(_Validation); v.SetValueGetter(i => i.Failure.Error); Assert.Equal("Failure.Error", v.ValueName); var result = new TestRuleBuilderClass() { Failure = new ValidateFailure() { Error = "ab" } }; Assert.Equal(result.Failure.Error, v.ValueGetter(result)); }
public void WriteSNatTarget() { var snatTarget = new SNatTargetBuilder().SetSource("192.168.1.1", "192.168.1.10", 200, 300).Build(); var rule = new RuleBuilder() .SetIp4Src("192.168.3.2/23") .SetIp4Dst("192.168.3/24") .SetInInterface("eno8") .SetOutInterface("eno45", true, true) .SetProto("tCp") .SetTarget(snatTarget) .Build(); System.Console.WriteLine(rule); using (var wr = new IptTransaction(Tables.NAT)) { wr.AppendRule(Chains.POSTROUTING, rule); wr.Commit(); var rules = wr.GetRules(Chains.POSTROUTING); rule = rules.First(); var target = rule.Target; System.Console.WriteLine(rule); Assert.NotEmpty(rules); Assert.Equal("192.168.1.1-192.168.1.10:200-300", target[SNatTargetBuilder.TO_SOURCE_OPT]); Assert.Equal(TargetTypes.SNAT, target.Name); } "iptables -t nat -F POSTROUTING".Bash(); snatTarget = new SNatTargetBuilder().SetSource("192.168.10.1", "192.168.10.1", 200, 300).Build(); rule = new RuleBuilder() .SetIp4Src("192.168.3.2/23") .SetIp4Dst("192.168.3/24") .SetInInterface("eno8") .SetOutInterface("eno45", true, true) .SetProto("tCp") .SetTarget(snatTarget) .Build(); System.Console.WriteLine(rule); using (var wr = new IptTransaction(Tables.NAT)) { wr.AppendRule(Chains.POSTROUTING, rule); wr.Commit(); var rules = wr.GetRules(Chains.POSTROUTING); rule = rules.First(); var target = rule.Target; System.Console.WriteLine(rule); Assert.NotEmpty(rules); Assert.Equal("192.168.10.1:200-300", target[SNatTargetBuilder.TO_SOURCE_OPT]); Assert.Equal(TargetTypes.SNAT, target.Name); } }
public void DoNotRunIfHasRuleViolation_ShouldRunClauseAdded() { var rule = new Rule("Rule1"); var ruleBuilder = new RuleBuilder <RuleEngineContext <Customer>, Customer> (rule); ruleBuilder.DoNotRunIfHasRuleViolation(); var ruleEngineContext = new RuleEngineContext(new Customer()); ruleEngineContext.RuleViolationReporter.Report(new RuleViolation(rule, null, null)); var shouldRunResult = rule.ShouldRunRule(ruleEngineContext); Assert.IsFalse(shouldRunResult); }
public override void EnterRule_definition(Rule_definitionContext context) { var builder = new RuleBuilder(); using (_parserContext.PushScope()) { var expressionListener = new RuleParserListener(_parserContext, builder); var walker = new ParseTreeWalker(); walker.Walk(expressionListener, context); } var rule = builder.Build(); _ruleSet.Add(Enumerable.Repeat(rule, 1)); }
public void RuleWithNoVariationOrRolloutReturnsMalformedFlagError() { var user = User.WithKey("userkey"); var clause = ClauseBuilder.ShouldMatchUser(user); var rule = new RuleBuilder().Id("ruleid").Clauses(clause).Build(); var f = FeatureFlagWithRules(rule); var result = BasicEvaluator.Evaluate(f, user, EventFactory.Default); var expected = new EvaluationDetail <LdValue>(LdValue.Null, null, EvaluationReason.ErrorReason(EvaluationErrorKind.MalformedFlag)); Assert.Equal(expected, result.Result); Assert.Equal(0, result.PrerequisiteEvents.Count); }
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 async Task ProcessOrderAsync() { var rule = RuleBuilder.CreateRuleImp(SampleRules.GetOrCreateSampleRule()); if (rule == null) { throw new InvalidOperationException("Rule object is not defined."); } var context = new OrderDiscountContext(Order.Model); await context.ExecuteAsync(rule); Discounts = context.GetOrderDiscounts(); Total = DiscountLogic.GetOrderTotalAmount(Order.Model, Discounts); LogInfo("Order has been processed successfully."); }
public void AccountApplicationService_Remove() { var rule = new RuleBuilder().WithDays(3).WithType(RuleType.UpUntil).WithPenalty(2).WithInterestPerDay(0.2m).Builder(); var account = new AccountBuilder().WithRule(rule).Builder(); _ruleRepository.Add(rule); _accountRepository.Add(account); _unitOfWork.Commit(); _accountApplicationService.Remove(account.Id); var result = _accountRepository.Get(new Filter()); result.entities.Should().HaveCount(0); }
private async Task BuildSubscription(string connectionString, string[] messagesTypes, string handlerFullName) { var topicName = _config.EffectiveTopicName; var client = new SubscriptionClient(connectionString, topicName, _config.SubscriberName); var ruleApplier = new RuleApplier(_ruleApplierLog, client); var ruleBuilder = new RuleBuilder(ruleApplier, _subscriptionRuleVersionResolver, _config.SubscriberName); var rulesForCurrentSoftwareVersion = ruleBuilder.GenerateSubscriptionRules(messagesTypes, handlerFullName, _config.OmitSpecificSubscriberFilter).ToArray(); var rulesCurrentlyDefinedInServiceBus = await client.GetRulesAsync().ConfigureAwait(false); _log.LogInformation($"Validating subscription '{_config.SubscriberName}' rules on topic '{topicName}'..."); await ruleBuilder.ApplyRuleChanges(rulesForCurrentSoftwareVersion, rulesCurrentlyDefinedInServiceBus.ToArray(), messagesTypes).ConfigureAwait(false); }
public void Then_ProvidingAThenClauseOverrideToTheBuilder_RuleShouldHaveAThenClauseOverride() { var rule = new Rule ( "Rule1" ); var ruleBuilder = new RuleBuilder<RuleEngineContext<Customer>, Customer> ( rule ); ruleBuilder.When ( ( cust, ctxt ) => true ).Then ( ( cust, ctxt ) => cust.Age++ ); var customer = new Customer { Age = 10 }; var context = new RuleEngineContext<Customer> ( customer ); foreach ( var clause in rule.ThenClauses ) { clause ( context ); } Assert.AreEqual ( 11, customer.Age ); }
public void ExecuteRules_WithDisabledRule_DisabledRuleIsNotRun() { var patient = new Patient { Name = new Name () }; var patientRuleCollection = new PatientRuleCollection (); patientRuleCollection.FirstNameCannotBeNull.Disable (); var ruleRun = false; var ruleBuilder = new RuleBuilder<RuleEngineContext<Patient>, Patient> ( patientRuleCollection.FirstNameCannotBeNull as Rule ); ruleBuilder.Then ( p => ruleRun = true ).ElseThen ( p => ruleRun = true ); var ruleEngine = new RuleEngine<Patient> ( patientRuleCollection ); var ruleEngineContext = new RuleEngineContext<Patient> ( patient ); ruleEngineContext.WorkingMemory.AddContextObject ( new Name () ); ruleEngine.ExecuteRules ( ruleEngineContext ); Assert.IsFalse ( ruleRun ); }
public void ExecuteRules_GivenPatientRuleCollection_AllRulesRun() { var patient = new Patient { Name = new Name () }; var patientRuleCollection = new PatientRuleCollection (); var runRuleCount = 0; foreach ( var patientRule in patientRuleCollection ) { var ruleBuilder = new RuleBuilder<RuleEngineContext<Patient>, Patient> ( patientRule as Rule ); ruleBuilder.Then ( p => runRuleCount++ ).ElseThen ( p => runRuleCount++ ); } var ruleEngine = new RuleEngine<Patient> ( patientRuleCollection ); var ruleEngineContext = new RuleEngineContext<Patient> ( patient ); ruleEngineContext.WorkingMemory.AddContextObject ( new Name () ); ruleEngine.ExecuteRules ( ruleEngineContext ); Assert.AreEqual ( patientRuleCollection.Count (), runRuleCount ); }
public void When_GivenAThenClauseWithoutAWhenClause_ThrowsInvalidRuleException() { var rule = new Rule ( "Rule1" ); var ruleBuilder = new RuleBuilder<RuleEngineContext<Customer>, Customer> ( rule ); ruleBuilder.Then ( c => c.Age++ ); }
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())); builder.Rule.GetDisplayName().ShouldBeNull(); builder.Rule.PropertyName.ShouldBeNull(); }
public void When_WithAWhenFunction_AssignsWhenFunctionToRule() { var rule = new Rule ( "Rule1" ); var ruleBuilder = new RuleBuilder<RuleEngineContext<Customer>, Customer> ( rule ); ruleBuilder.When ( ( cust, ctxt ) => cust.Age < 20 ); var customer = new Customer { Age = 10 }; var context = new RuleEngineContext<Customer> ( customer ); var lessThan20 = rule.WhenClause ( context ); Assert.IsTrue ( lessThan20 ); }
public void When_GivenAWhenPredicate_AssignsWhenPredicateToRule() { var rule = new Rule ( "Rule1" ); var ruleBuilder = new RuleBuilder<RuleEngineContext<Customer>, Customer> ( rule ); ruleBuilder.When ( c => c.Age < 20 ); var customer = new Customer { Age = 10 }; var context = new RuleEngineContext<Customer> ( customer ); var lessThan20 = rule.WhenClause ( context ); Assert.IsTrue ( lessThan20 ); }
public void Test_RuleBuilder_Build() { var v = new RuleBuilder<TestRuleBuilderClass, string>(_Validation); v.ValidateAsyncFunc = (e, o, s) => { return null; }; v.SetValueGetter(i => i.Failure.Error); v.Condition = (d) => { return false; }; v.Error = "ok"; var next = v.ThenRuleFor(i => i.Failure); var r = v.Build(); Assert.NotNull(r); Assert.NotNull(r.NextRuleList); Assert.NotNull(r.ValidateAsyncFunc); Assert.NotNull(r.Condition); Assert.Equal(v.ValidateAsyncFunc, r.ValidateAsyncFunc); Assert.Equal(v.Condition, r.Condition); Assert.Equal("Failure.Error", r.ValueName); Assert.Equal("ok", r.Error); }
public void WithPrioroty_RulePriorityIsSet() { var rule = new Rule ( "Rule1" ); var ruleBuilder = new RuleBuilder<RuleEngineContext<Customer>, Customer> ( rule ); ruleBuilder.WithPriority ( 5 ); Assert.AreEqual ( 5, rule.Priority ); }
public void Nullable_object_with_condition_should_not_throw() { var builder = new RuleBuilder<Person, int>(PropertyRule.Create<Person, int>(x => x.NullableInt.Value)); builder.GreaterThanOrEqualTo(3).When(x => x.NullableInt != null); builder.Rule.Validate(new ValidationContext<Person>(new Person(), new PropertyChain(), new DefaultValidatorSelector())); }
public void PropertyDescription_should_return_custom_property_name() { var builder = new RuleBuilder<Person, DateTime>(x => x.DateOfBirth); builder.NotEqual(default(DateTime)).WithName("Foo"); builder.Model.PropertyDescription.ShouldEqual("Foo"); }
public void PropertyDescription_should_return_custom_property_name() { var builder = new RuleBuilder<Person, DateTime>(PropertyRule.Create<Person, DateTime>(x => x.DateOfBirth)); builder.NotEqual(default(DateTime)).WithName("Foo"); builder.Rule.GetDisplayName().ShouldEqual("Foo"); }
public void PropertyDescription_should_return_property_name_split() { var builder = new RuleBuilder<Person, DateTime>(PropertyRule.Create<Person, DateTime>(x => x.DateOfBirth)); builder.Rule.GetDisplayName().ShouldEqual("Date Of Birth"); }
public RecordingRuleBuilder(RecordedCallRule rule, RuleBuilder wrappedBuilder) { this.rule = rule; this.wrappedBuilder = wrappedBuilder; }
public void Property_should_return_null_when_it_is_not_a_property_being_validated() { builder = new RuleBuilder<Person, string>(PropertyRule.Create<Person, string>(x => "Foo")); builder.Rule.Member.ShouldBeNull(); }
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())); 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 void Setup() { var rule = PropertyRule.Create<Person,string>(x => x.Surname); builder = new RuleBuilder<Person, string>(rule); }
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'."); }
private PropertyRule<TestObject, object> CreateRule(Expression<Func<TestObject, object>> expression) { var builder = new RuleBuilder<TestObject, object>(expression); builder.SetValidator(new NotNullValidator()); return (PropertyRule<TestObject, object>)builder.Single(); }
void Awake() { rb = GameObject.FindGameObjectWithTag("RuleBuilder").GetComponent<RuleBuilder>(); }