github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/merkledag/utils/utils_test.go (about) 1 package dagutils 2 3 import ( 4 "strings" 5 "testing" 6 7 key "github.com/ipfs/go-ipfs/blocks/key" 8 dag "github.com/ipfs/go-ipfs/merkledag" 9 mdtest "github.com/ipfs/go-ipfs/merkledag/test" 10 11 context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context" 12 ) 13 14 func TestAddLink(t *testing.T) { 15 ds := mdtest.Mock() 16 fishnode := &dag.Node{ 17 Data: []byte("fishcakes!"), 18 } 19 20 fk, err := ds.Add(fishnode) 21 if err != nil { 22 t.Fatal(err) 23 } 24 25 nd := new(dag.Node) 26 nnode, err := addLink(context.Background(), ds, nd, "fish", fishnode) 27 if err != nil { 28 t.Fatal(err) 29 } 30 31 fnprime, err := nnode.GetLinkedNode(context.Background(), ds, "fish") 32 if err != nil { 33 t.Fatal(err) 34 } 35 36 fnpkey, err := fnprime.Key() 37 if err != nil { 38 t.Fatal(err) 39 } 40 41 if fnpkey != fk { 42 t.Fatal("wrong child node found!") 43 } 44 } 45 46 func assertNodeAtPath(t *testing.T, ds dag.DAGService, root *dag.Node, path string, exp key.Key) { 47 parts := strings.Split(path, "/") 48 cur := root 49 for _, e := range parts { 50 nxt, err := cur.GetLinkedNode(context.Background(), ds, e) 51 if err != nil { 52 t.Fatal(err) 53 } 54 55 cur = nxt 56 } 57 58 curk, err := cur.Key() 59 if err != nil { 60 t.Fatal(err) 61 } 62 63 if curk != exp { 64 t.Fatal("node not as expected at end of path") 65 } 66 } 67 68 func TestInsertNode(t *testing.T) { 69 ds := mdtest.Mock() 70 root := new(dag.Node) 71 e := NewDagEditor(ds, root) 72 73 testInsert(t, e, "a", "anodefortesting", false, "") 74 testInsert(t, e, "a/b", "data", false, "") 75 testInsert(t, e, "a/b/c/d/e", "blah", false, "merkledag: not found") 76 testInsert(t, e, "a/b/c/d/e", "foo", true, "") 77 testInsert(t, e, "a/b/c/d/f", "baz", true, "") 78 testInsert(t, e, "a/b/c/d/f", "bar", true, "") 79 80 testInsert(t, e, "", "bar", true, "cannot create link with no name!") 81 testInsert(t, e, "////", "slashes", true, "cannot create link with no name!") 82 83 k, err := e.GetNode().Key() 84 if err != nil { 85 t.Fatal(err) 86 } 87 88 if k.B58String() != "QmThorWojP6YzLJwDukxiYCoKQSwyrMCvdt4WZ6rPm221t" { 89 t.Fatal("output was different than expected") 90 } 91 } 92 93 func testInsert(t *testing.T, e *Editor, path, data string, create bool, experr string) { 94 child := &dag.Node{Data: []byte(data)} 95 ck, err := e.ds.Add(child) 96 if err != nil { 97 t.Fatal(err) 98 } 99 100 var c func() *dag.Node 101 if create { 102 c = func() *dag.Node { 103 return &dag.Node{} 104 } 105 } 106 107 err = e.InsertNodeAtPath(context.Background(), path, child, c) 108 if experr != "" { 109 var got string 110 if err != nil { 111 got = err.Error() 112 } 113 if got != experr { 114 t.Fatalf("expected '%s' but got '%s'", experr, got) 115 } 116 return 117 } 118 119 if err != nil { 120 t.Fatal(err) 121 } 122 123 assertNodeAtPath(t, e.ds, e.root, path, ck) 124 }