Skip to content

Commit

Permalink
Added err detection for io.EOF and more sample for save/load RuleSet …
Browse files Browse the repository at this point in the history
…binary (#185)
  • Loading branch information
newm4n authored Apr 14, 2021
1 parent 8c7b275 commit b407409
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
2 changes: 1 addition & 1 deletion ast/KnowledgeBase.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func (lib *KnowledgeLibrary) LoadKnowledgeBaseFromReader(reader io.Reader, overw

catalog := &Catalog{}
err := catalog.ReadCatalogFromReader(reader)
if err != nil {
if err != nil && err != io.EOF {
return nil, err
}
kb := catalog.BuildKnowledgeBase()
Expand Down
46 changes: 45 additions & 1 deletion examples/Serialization_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"github.com/hyperjumptech/grule-rule-engine/builder"
"github.com/hyperjumptech/grule-rule-engine/pkg"
"github.com/stretchr/testify/assert"
"io"
"os"
"testing"
)

Expand All @@ -39,8 +41,50 @@ func TestSerialization(t *testing.T) {
buff2 := bytes.NewBuffer(buff1.Bytes())
cat2 := &ast.Catalog{}
err = cat2.ReadCatalogFromReader(buff2)
assert.Nil(t, err)
if err != nil && err != io.EOF {
assert.Nil(t, err)
}

kb2 := cat2.BuildKnowledgeBase()
assert.True(t, kb.IsIdentical(kb2))
}

func TestSerializationOnFile(t *testing.T) {
testFile := "Test.GRB"

// SAFING INTO FILE
// First prepare our library for loading the orignal GRL
lib := ast.NewKnowledgeLibrary()
rb := builder.NewRuleBuilder(lib)
err := rb.BuildRuleFromResource("Purchase Calculator", "0.0.1", pkg.NewFileResource("CashFlowRule.grl"))
assert.NoError(t, err)

// Lets create the file to write into
f, err := os.OpenFile(testFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
assert.Nil(t, err)

// Save the knowledge base into the file and close it.
err = lib.StoreKnowledgeBaseToWriter(f, "load_rules_test", "0.1.1")
assert.Nil(t, err)
_ = f.Close()

// LOADING FROM FILE
// Lets assume we are using different library, so create a new one
lib2 := ast.NewKnowledgeLibrary()

// Open the existing safe file
f2, err := os.Open(testFile)
assert.Nil(t, err)

// Load the file directly into the library and close the file
kb2, err := lib2.LoadKnowledgeBaseFromReader(f2, true)
assert.Nil(t, err)
_ = f2.Close()

// Delete the test file
err = os.Remove(testFile)
assert.Nil(t, err)

// compare that the original knowledgebase is exacly the same to the loaded one.
assert.True(t, lib.GetKnowledgeBase("load_rules_test", "0.1.1").IsIdentical(kb2))
}

0 comments on commit b407409

Please sign in to comment.