node_test.go 2.13 KB
Newer Older
1
package merkledag_test
2 3

import (
Jeromy's avatar
Jeromy committed
4
	"context"
5
	"testing"
6 7 8 9

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

Jeromy's avatar
Jeromy committed
10
	node "gx/ipfs/QmRSU5EqqWVZSNdbU51yXmVoF1uNw3JgTNB6RaiL7DZM16/go-ipld-node"
11 12 13
)

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

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

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

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

37
	if nd.Links()[1].Name != "c" {
38 39 40 41 42 43 44 45 46 47
		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
48
	if len(nd.Links()) != 2 {
49 50 51
		t.Fatal("number of links incorrect")
	}

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

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

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

68
	nd := &ProtoNode{}
Jeromy's avatar
Jeromy committed
69 70 71 72
	nd.SetLinks([]*node.Link{
		{Name: "a", Cid: k},
		{Name: "c", Cid: k},
		{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 108

	_, 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)
	}

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

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

122 123
	nd.SetData([]byte("testing"))

124
	ond := nd.Copy().(*ProtoNode)
125 126 127 128 129 130
	ond.SetData(nil)

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