node_test.go 2.09 KB
Newer Older
1
package merkledag_test
2 3 4

import (
	"testing"
5 6 7 8

	. "github.com/ipfs/go-ipfs/merkledag"
	mdtest "github.com/ipfs/go-ipfs/merkledag/test"

9
	"context"
10 11 12
)

func TestRemoveLink(t *testing.T) {
13 14 15 16 17 18 19 20 21
	nd := &ProtoNode{}
	nd.SetLinks([]*Link{
		&Link{Name: "a"},
		&Link{Name: "b"},
		&Link{Name: "a"},
		&Link{Name: "a"},
		&Link{Name: "c"},
		&Link{Name: "a"},
	})
22 23 24 25 26 27

	err := nd.RemoveNodeLink("a")
	if err != nil {
		t.Fatal(err)
	}

28
	if len(nd.Links()) != 2 {
29 30 31
		t.Fatal("number of links incorrect")
	}

32
	if nd.Links()[0].Name != "b" {
33 34 35
		t.Fatal("link order wrong")
	}

36
	if nd.Links()[1].Name != "c" {
37 38 39 40 41 42 43 44 45 46
		t.Fatal("link order wrong")
	}

	// should fail
	err = nd.RemoveNodeLink("a")
	if err != ErrNotFound {
		t.Fatal("should have failed to remove link")
	}

	// ensure nothing else got touched
47
	if len(nd.Links()) != 2 {
48 49 50
		t.Fatal("number of links incorrect")
	}

51
	if nd.Links()[0].Name != "b" {
52 53 54
		t.Fatal("link order wrong")
	}

55
	if nd.Links()[1].Name != "c" {
56 57 58
		t.Fatal("link order wrong")
	}
}
59 60 61

func TestFindLink(t *testing.T) {
	ds := mdtest.Mock()
62
	k, err := ds.Add(new(ProtoNode))
63 64 65 66
	if err != nil {
		t.Fatal(err)
	}

67 68 69 70 71 72
	nd := &ProtoNode{}
	nd.SetLinks([]*Link{
		&Link{Name: "a", Cid: k},
		&Link{Name: "c", Cid: k},
		&Link{Name: "b", Cid: k},
	})
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

	_, err = ds.Add(nd)
	if err != nil {
		t.Fatal(err)
	}

	lnk, err := nd.GetNodeLink("b")
	if err != nil {
		t.Fatal(err)
	}

	if lnk.Name != "b" {
		t.Fatal("got wrong link back")
	}

	_, err = nd.GetNodeLink("f")
	if err != ErrLinkNotFound {
		t.Fatal("shouldnt have found link")
	}

	_, err = nd.GetLinkedNode(context.Background(), ds, "b")
	if err != nil {
		t.Fatal(err)
	}

	outnd, err := nd.UpdateNodeLink("b", nd)
	if err != nil {
		t.Fatal(err)
	}

	olnk, err := outnd.GetNodeLink("b")
	if err != nil {
		t.Fatal(err)
	}

108
	if olnk.Cid.String() == k.String() {
109 110 111 112 113
		t.Fatal("new link should have different hash")
	}
}

func TestNodeCopy(t *testing.T) {
114 115 116 117 118 119 120
	nd := &ProtoNode{}
	nd.SetLinks([]*Link{
		&Link{Name: "a"},
		&Link{Name: "c"},
		&Link{Name: "b"},
	})

121 122 123 124 125 126 127 128 129
	nd.SetData([]byte("testing"))

	ond := nd.Copy()
	ond.SetData(nil)

	if nd.Data() == nil {
		t.Fatal("should be different objects")
	}
}