Skip to content

Commit

Permalink
Feat/resiliency Fixing #270 (#271)
Browse files Browse the repository at this point in the history
* Better make file

* Fixes issue #270, where in JSON DOM, evaluating non-existent field in map interface yield a zero value, thus caling val.elem() causes a panic. Now the zero is evaluated and returned a normal error
  • Loading branch information
newm4n authored Dec 1, 2021
1 parent 072b2a2 commit 206f2da
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
6 changes: 5 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ build: fix-antlr4-bug
go build ./...

lint: build
${GOBIN}/golint -set_exit_status builder/... engine/... examples/... ast/... pkg/... antlr/. model/...
ifndef GOBIN
"${GOPATH}/bin/golint" -set_exit_status builder/... engine/... examples/... ast/... pkg/... antlr/. model/...
else
"${GOBIN}/golint" -set_exit_status builder/... engine/... examples/... ast/... pkg/... antlr/. model/...
endif

test-short: build
go test ./... -v -covermode=count -coverprofile=coverage.out -short
Expand Down
51 changes: 51 additions & 0 deletions examples/EvaluateMissingDataContext_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package examples

import (
"fmt"
"github.com/hyperjumptech/grule-rule-engine/ast"
"github.com/hyperjumptech/grule-rule-engine/builder"
"github.com/hyperjumptech/grule-rule-engine/engine"
"github.com/hyperjumptech/grule-rule-engine/pkg"
"testing"
)

const (
input_rule = `
rule TestRule "" {
when
R.Result == 'NoResult' &&
inputs.i_am_missing == 'abc' &&
inputs.name.first == 'john'
then
R.Result = "ok";
}
`
)


func TestDataContextMissingFact(t *testing.T) {

oresult := &ObjectResult{
Result: "NoResult",
}

// build rules
lib := ast.NewKnowledgeLibrary()
rb := builder.NewRuleBuilder(lib)
err := rb.BuildRuleFromResource("Test", "0.0.1", pkg.NewBytesResource([]byte(input_rule)))

// add JSON fact
json := []byte(`{"blabla":"bla","name":{"first":"john","last":"doe"}}`)
kb := lib.NewKnowledgeBaseInstance("Test", "0.0.1")
dcx := ast.NewDataContext()

err = dcx.Add("R", oresult)
err = dcx.AddJSON("inputs", json)
if err != nil {
fmt.Println(err.Error())
}

// results in panic
engine.NewGruleEngine().Execute(dcx, kb)

}
3 changes: 3 additions & 0 deletions model/JsonDataAccessLayer.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,9 @@ func (vn *JSONValueNode) GetObjectValueByField(field string) (reflect.Value, err
return reflect.ValueOf(nil), fmt.Errorf("not an object or map")
}
tmap := vn.data.MapIndex(reflect.ValueOf(field))
if tmap == reflect.ValueOf(nil) {
return reflect.ValueOf(nil), fmt.Errorf("json field '%s' is undefined", field)
}
return tmap.Elem(), nil
}

Expand Down

0 comments on commit 206f2da

Please sign in to comment.