notifications_test.go 1.64 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
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"
)

func TestPublishSubscribe(t *testing.T) {
13
	blockSent := blocks.NewBlock([]byte("Greetings from The Interval"))
14 15 16 17 18

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

Jeromy's avatar
Jeromy committed
19
	n.Publish(blockSent)
20 21 22 23 24
	blockRecvd, ok := <-ch
	if !ok {
		t.Fail()
	}

Jeromy's avatar
Jeromy committed
25
	assertBlocksEqual(t, blockRecvd, blockSent)
26 27 28

}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
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)
}

52 53 54 55 56 57 58
func TestCarryOnWhenDeadlineExpires(t *testing.T) {

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

	n := New()
	defer n.Shutdown()
59
	block := blocks.NewBlock([]byte("A Missed Connection"))
60 61 62 63 64
	blockChannel := n.Subscribe(fastExpiringCtx, block.Key())

	assertBlockChannelNil(t, blockChannel)
}

Jeromy's avatar
Jeromy committed
65
func assertBlockChannelNil(t *testing.T, blockChannel <-chan *blocks.Block) {
66 67 68 69 70 71
	_, ok := <-blockChannel
	if ok {
		t.Fail()
	}
}

Jeromy's avatar
Jeromy committed
72
func assertBlocksEqual(t *testing.T, a, b *blocks.Block) {
73 74 75 76 77 78 79
	if !bytes.Equal(a.Data, b.Data) {
		t.Fail()
	}
	if a.Key() != b.Key() {
		t.Fail()
	}
}