wantlist_test.go 2.03 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4 5 6 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
package wantlist

import (
	"testing"

	cid "gx/ipfs/QmYhQaCYEcaPPjxJX7YcPcVKkQfRy6sJ7B3XmGFk82XYdQ/go-cid"
)

var testcids []*cid.Cid

func init() {
	strs := []string{
		"QmQL8LqkEgYXaDHdNYCG2mmpow7Sp8Z8Kt3QS688vyBeC7",
		"QmcBDsdjgSXU7BP4A4V8LJCXENE5xVwnhrhRGVTJr9YCVj",
		"QmQakgd2wDxc3uUF4orGdEm28zUT9Mmimp5pyPG2SFS9Gj",
	}
	for _, s := range strs {
		c, err := cid.Decode(s)
		if err != nil {
			panic(err)
		}
		testcids = append(testcids, c)
	}

}

type wli interface {
	Contains(*cid.Cid) (*Entry, bool)
}

func assertHasCid(t *testing.T, w wli, c *cid.Cid) {
	e, ok := w.Contains(c)
	if !ok {
		t.Fatal("expected to have ", c)
	}
	if !e.Cid.Equals(c) {
		t.Fatal("returned entry had wrong cid value")
	}
}

func assertNotHasCid(t *testing.T, w wli, c *cid.Cid) {
	_, ok := w.Contains(c)
	if ok {
		t.Fatal("expected not to have ", c)
	}
}

func TestBasicWantlist(t *testing.T) {
	wl := New()

51 52 53
	if !wl.Add(testcids[0], 5) {
		t.Fatal("expected true")
	}
Jeromy's avatar
Jeromy committed
54
	assertHasCid(t, wl, testcids[0])
55 56 57
	if !wl.Add(testcids[1], 4) {
		t.Fatal("expected true")
	}
Jeromy's avatar
Jeromy committed
58 59 60 61 62 63 64
	assertHasCid(t, wl, testcids[0])
	assertHasCid(t, wl, testcids[1])

	if wl.Len() != 2 {
		t.Fatal("should have had two items")
	}

65 66 67
	if wl.Add(testcids[1], 4) {
		t.Fatal("add shouldnt report success on second add")
	}
Jeromy's avatar
Jeromy committed
68 69 70 71 72 73 74
	assertHasCid(t, wl, testcids[0])
	assertHasCid(t, wl, testcids[1])

	if wl.Len() != 2 {
		t.Fatal("should have had two items")
	}

75 76 77 78
	if !wl.Remove(testcids[0]) {
		t.Fatal("should have gotten true")
	}

Jeromy's avatar
Jeromy committed
79 80 81 82 83 84 85 86 87
	assertHasCid(t, wl, testcids[1])
	if _, has := wl.Contains(testcids[0]); has {
		t.Fatal("shouldnt have this cid")
	}
}

func TestSesRefWantlist(t *testing.T) {
	wl := NewThreadSafe()

88 89 90
	if !wl.Add(testcids[0], 5, 1) {
		t.Fatal("should have added")
	}
Jeromy's avatar
Jeromy committed
91
	assertHasCid(t, wl, testcids[0])
92 93 94
	if wl.Remove(testcids[0], 2) {
		t.Fatal("shouldnt have removed")
	}
Jeromy's avatar
Jeromy committed
95
	assertHasCid(t, wl, testcids[0])
96 97 98
	if wl.Add(testcids[0], 5, 1) {
		t.Fatal("shouldnt have added")
	}
Jeromy's avatar
Jeromy committed
99
	assertHasCid(t, wl, testcids[0])
100 101 102
	if !wl.Remove(testcids[0], 1) {
		t.Fatal("should have removed")
	}
Jeromy's avatar
Jeromy committed
103 104
	assertNotHasCid(t, wl, testcids[0])
}