pin_test.go 2.2 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4 5
package pin

import (
	"testing"

Jeromy's avatar
Jeromy committed
6
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
Jeromy's avatar
Jeromy committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
	bs "github.com/jbenet/go-ipfs/blockservice"
	mdag "github.com/jbenet/go-ipfs/merkledag"
	"github.com/jbenet/go-ipfs/util"
)

func randNode() (*mdag.Node, util.Key) {
	nd := new(mdag.Node)
	nd.Data = make([]byte, 32)
	util.NewFastRand().Read(nd.Data)
	k, _ := nd.Key()
	return nd, k
}

func TestPinnerBasic(t *testing.T) {
	dstore := datastore.NewMapDatastore()
	bserv, err := bs.NewBlockService(dstore, nil)
	if err != nil {
		t.Fatal(err)
	}

	dserv := &mdag.DAGService{bserv}

	p := NewPinner(dstore, dserv)

	a, ak := randNode()

	// Pin A{}
	err = p.Pin(a, false)
	if err != nil {
		t.Fatal(err)
	}

	if !p.IsPinned(ak) {
		t.Fatal("Failed to find key")
	}

	b, _ := randNode()
	err = b.AddNodeLink("child", a)
	if err != nil {
		t.Fatal(err)
	}

	c, ck := randNode()
	err = b.AddNodeLink("otherchild", c)
	if err != nil {
		t.Fatal(err)
	}

	// recursively pin B{A,C}
	err = p.Pin(b, true)
	if err != nil {
		t.Fatal(err)
	}

	if !p.IsPinned(ck) {
		t.Fatal("Child of recursively pinned node not found")
	}

	bk, _ := b.Key()
	if !p.IsPinned(bk) {
		t.Fatal("Recursively pinned node not found..")
	}

	d, _ := randNode()
	d.AddNodeLink("a", a)
	d.AddNodeLink("c", c)

	e, ek := randNode()
	d.AddNodeLink("e", e)

	// Must be in dagserv for unpin to work
	err = dserv.AddRecursive(d)
	if err != nil {
		t.Fatal(err)
	}

	// Add D{A,C,E}
	err = p.Pin(d, true)
	if err != nil {
		t.Fatal(err)
	}

	if !p.IsPinned(ek) {
		t.Fatal(err)
	}

	dk, _ := d.Key()
	if !p.IsPinned(dk) {
		t.Fatal("pinned node not found.")
	}

	// Test recursive unpin
	err = p.Unpin(dk, true)
	if err != nil {
		t.Fatal(err)
	}

	// c should still be pinned under b
	if !p.IsPinned(ck) {
		t.Fatal("Recursive unpin fail.")
	}

	err = p.Flush()
	if err != nil {
		t.Fatal(err)
	}

	np, err := LoadPinner(dstore, dserv)
	if err != nil {
		t.Fatal(err)
	}

	// Test directly pinned
	if !np.IsPinned(ak) {
		t.Fatal("Could not find pinned node!")
	}

	// Test indirectly pinned
	if !np.IsPinned(ck) {
		t.Fatal("could not find indirectly pinned node")
	}

	// Test recursively pinned
	if !np.IsPinned(bk) {
		t.Fatal("could not find recursively pinned node")
	}
}