notifications_test.go 2.34 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
package notifications

import (
	"bytes"
	"testing"
	"time"

	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
	blocks "github.com/jbenet/go-ipfs/blocks"
)

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
func TestDuplicates(t *testing.T) {
	b1 := blocks.NewBlock([]byte("1"))
	b2 := blocks.NewBlock([]byte("2"))

	n := New()
	defer n.Shutdown()
	ch := n.Subscribe(context.Background(), b1.Key(), b2.Key())

	n.Publish(b1)
	blockRecvd, ok := <-ch
	if !ok {
		t.Fail()
	}
	assertBlocksEqual(t, b1, blockRecvd)

	n.Publish(b1) // ignored duplicate

	n.Publish(b2)
	blockRecvd, ok = <-ch
	if !ok {
		t.Fail()
	}
	assertBlocksEqual(t, b2, blockRecvd)
}

37
func TestPublishSubscribe(t *testing.T) {
38
	blockSent := blocks.NewBlock([]byte("Greetings from The Interval"))
39 40 41 42 43

	n := New()
	defer n.Shutdown()
	ch := n.Subscribe(context.Background(), blockSent.Key())

Jeromy's avatar
Jeromy committed
44
	n.Publish(blockSent)
45 46 47 48 49
	blockRecvd, ok := <-ch
	if !ok {
		t.Fail()
	}

Jeromy's avatar
Jeromy committed
50
	assertBlocksEqual(t, blockRecvd, blockSent)
51 52 53

}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
func TestSubscribeMany(t *testing.T) {
	e1 := blocks.NewBlock([]byte("Greetings from The Interval"))
	e2 := blocks.NewBlock([]byte("Greetings from The Interval"))

	n := New()
	defer n.Shutdown()
	ch := n.Subscribe(context.Background(), e1.Key(), e2.Key())

	n.Publish(e1)
	r1, ok := <-ch
	if !ok {
		t.Fatal("didn't receive first expected block")
	}
	assertBlocksEqual(t, e1, r1)

	n.Publish(e2)
	r2, ok := <-ch
	if !ok {
		t.Fatal("didn't receive second expected block")
	}
	assertBlocksEqual(t, e2, r2)
}

77 78 79 80 81 82 83 84 85
func TestSubscribeIsANoopWhenCalledWithNoKeys(t *testing.T) {
	n := New()
	defer n.Shutdown()
	ch := n.Subscribe(context.TODO()) // no keys provided
	if _, ok := <-ch; ok {
		t.Fatal("should be closed if no keys provided")
	}
}

86 87 88 89 90 91 92
func TestCarryOnWhenDeadlineExpires(t *testing.T) {

	impossibleDeadline := time.Nanosecond
	fastExpiringCtx, _ := context.WithTimeout(context.Background(), impossibleDeadline)

	n := New()
	defer n.Shutdown()
93
	block := blocks.NewBlock([]byte("A Missed Connection"))
94 95 96 97 98
	blockChannel := n.Subscribe(fastExpiringCtx, block.Key())

	assertBlockChannelNil(t, blockChannel)
}

Jeromy's avatar
Jeromy committed
99
func assertBlockChannelNil(t *testing.T, blockChannel <-chan *blocks.Block) {
100 101 102 103 104 105
	_, ok := <-blockChannel
	if ok {
		t.Fail()
	}
}

Jeromy's avatar
Jeromy committed
106
func assertBlocksEqual(t *testing.T, a, b *blocks.Block) {
107
	if !bytes.Equal(a.Data, b.Data) {
108
		t.Fatal("blocks aren't equal")
109 110
	}
	if a.Key() != b.Key() {
111
		t.Fatal("block keys aren't equal")
112 113
	}
}