package main import ( "encoding/json" "fmt" "path" "testing" ) func TestTreeDel(t *testing.T) { tree := NewTree(t.TempDir()) if err := tree.Put([]string{"id"}, Leaf{}); err != nil { t.Fatal(err) } if err := tree.Put([]string{"id", "subid"}, Leaf{}); err != nil { t.Fatal(err) } if err := tree.Del([]string{"id"}); err != nil { t.Fatal(err) } else if got, err := tree.Get([]string{"id"}); err != nil { t.Fatal(err) } else if !got.Deleted { t.Fatal(got) } if root, err := tree.GetRoot(); err != nil { t.Fatal(err) } else if len(root.Branches) > 0 { t.Fatal(root.Branches) } } func TestTreeCrud(t *testing.T) { tree := NewTree(t.TempDir()) if m, err := tree.GetRoot(); err != nil { t.Fatal(err) } else if m.Branches == nil { t.Fatal(m) } if err := tree.Del([]string{"id"}); err != nil { t.Fatal(err) } want := Leaf{ Title: "leaf title", Deleted: false, Content: "leaf content", } if err := tree.Put([]string{"id"}, want); err != nil { t.Fatal(err) } else if l, err := tree.Get([]string{"id"}); err != nil { t.Fatal(err) } else if l != want { t.Fatal(want, l) } if withContent, err := tree.GetRoot(); err != nil { t.Fatal(err) } else if withoutContent, err := tree.GetRootMeta(); err != nil { t.Fatal(err) } else if fmt.Sprint(withContent) == fmt.Sprint(withoutContent) { with, _ := json.MarshalIndent(withContent, "", " ") without, _ := json.MarshalIndent(withoutContent, "", " ") t.Fatalf("without content == with content: \n\twith=%s\n\twout=%s", with, without) } } func TestBranchFind(t *testing.T) { cases := map[string]struct { input string want []string found bool branch Branch }{ "empty": { input: "id", want: nil, found: false, branch: Branch{}, }, "yes top level": { input: "id", want: []string{"id"}, found: true, branch: Branch{ Branches: map[string]Branch{"id": Branch{}}, }, }, "yes deep level": { input: "subsubid", want: []string{"id", "subid", "subsubid"}, found: true, branch: Branch{ Branches: map[string]Branch{"id": Branch{ Branches: map[string]Branch{"subid": Branch{ Branches: map[string]Branch{"subsubid": Branch{}}}}, }}, }, }, "no but has deep levels": { input: "notsubsubid", want: nil, found: false, branch: Branch{ Branches: map[string]Branch{"id": Branch{ Branches: map[string]Branch{"subid": Branch{ Branches: map[string]Branch{"subsubid": Branch{}}}}, }}, }, }, } for name, d := range cases { c := d t.Run(name, func(t *testing.T) { got, found := c.branch.Find(c.input) if found != c.found { t.Error(c.found, found) } if path.Join(got...) != path.Join(c.want...) { t.Error(c.want, got) } }) } }