|
| 1 | +package examples |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/hyperjumptech/grule-rule-engine/ast" |
| 7 | + "github.com/hyperjumptech/grule-rule-engine/builder" |
| 8 | + "github.com/hyperjumptech/grule-rule-engine/engine" |
| 9 | + "github.com/hyperjumptech/grule-rule-engine/pkg" |
| 10 | + "github.com/stretchr/testify/assert" |
| 11 | +) |
| 12 | + |
| 13 | +const ( |
| 14 | + SliceOORRule = ` |
| 15 | + rule SliceOORRule { |
| 16 | + when |
| 17 | + PriceSlice.Prices[4] > 10 // will cause panic |
| 18 | + then |
| 19 | + Log("Price number 4 is greater than 10"); |
| 20 | + Retract("SliceOORRule"); |
| 21 | + }` |
| 22 | +) |
| 23 | + |
| 24 | +type AUserSliceIssue struct { |
| 25 | + Prices []int |
| 26 | +} |
| 27 | + |
| 28 | +func TestMethodCall_SliceOOR(t *testing.T) { |
| 29 | + ps := &AUserSliceIssue{ |
| 30 | + Prices: []int{1, 2, 3}, |
| 31 | + } |
| 32 | + |
| 33 | + dataContext := ast.NewDataContext() |
| 34 | + err := dataContext.Add("PriceSlice", ps) |
| 35 | + assert.NoError(t, err) |
| 36 | + |
| 37 | + // Prepare knowledgebase library and load it with our rule. |
| 38 | + lib := ast.NewKnowledgeLibrary() |
| 39 | + rb := builder.NewRuleBuilder(lib) |
| 40 | + err = rb.BuildRuleFromResource("Test", "0.1.1", pkg.NewBytesResource([]byte(SliceOORRule))) |
| 41 | + assert.NoError(t, err) |
| 42 | + |
| 43 | + // expect no panic and no error (ReturnErrOnFailedRuleEvaluation = false) |
| 44 | + eng1 := &engine.GruleEngine{MaxCycle: 5} |
| 45 | + kb := lib.NewKnowledgeBaseInstance("Test", "0.1.1") |
| 46 | + err = eng1.Execute(dataContext, kb) |
| 47 | + assert.NoError(t, err) |
| 48 | + |
| 49 | + // expect no panic and execute to return an error here |
| 50 | + eng1 = &engine.GruleEngine{MaxCycle: 5, ReturnErrOnFailedRuleEvaluation: true} |
| 51 | + kb = lib.NewKnowledgeBaseInstance("Test", "0.1.1") |
| 52 | + err = eng1.Execute(dataContext, kb) |
| 53 | + assert.Error(t, err) |
| 54 | +} |
0 commit comments