diff --git a/ast/KnowledgeBase.go b/ast/KnowledgeBase.go index 902d16a1..a312ce93 100755 --- a/ast/KnowledgeBase.go +++ b/ast/KnowledgeBase.go @@ -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() diff --git a/examples/Serialization_test.go b/examples/Serialization_test.go index 151fd077..0c012a21 100755 --- a/examples/Serialization_test.go +++ b/examples/Serialization_test.go @@ -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" ) @@ -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)) +}