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 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 134 135 136 137 138 139 140 141 142
|
package pubsub
import (
"fmt"
"testing"
"time"
)
func TestSendToOneSub(t *testing.T) {
p := NewPublisher(100*time.Millisecond, 10)
c := p.Subscribe()
p.Publish("hi")
msg := <-c
if msg.(string) != "hi" {
t.Fatalf("expected message hi but received %v", msg)
}
}
func TestSendToMultipleSubs(t *testing.T) {
p := NewPublisher(100*time.Millisecond, 10)
var subs []chan interface{}
subs = append(subs, p.Subscribe(), p.Subscribe(), p.Subscribe())
p.Publish("hi")
for _, c := range subs {
msg := <-c
if msg.(string) != "hi" {
t.Fatalf("expected message hi but received %v", msg)
}
}
}
func TestEvictOneSub(t *testing.T) {
p := NewPublisher(100*time.Millisecond, 10)
s1 := p.Subscribe()
s2 := p.Subscribe()
p.Evict(s1)
p.Publish("hi")
if _, ok := <-s1; ok {
t.Fatal("expected s1 to not receive the published message")
}
msg := <-s2
if msg.(string) != "hi" {
t.Fatalf("expected message hi but received %v", msg)
}
}
func TestClosePublisher(t *testing.T) {
p := NewPublisher(100*time.Millisecond, 10)
var subs []chan interface{}
subs = append(subs, p.Subscribe(), p.Subscribe(), p.Subscribe())
p.Close()
for _, c := range subs {
if _, ok := <-c; ok {
t.Fatal("expected all subscriber channels to be closed")
}
}
}
const sampleText = "test"
type testSubscriber struct {
dataCh chan interface{}
ch chan error
}
func (s *testSubscriber) Wait() error {
return <-s.ch
}
func newTestSubscriber(p *Publisher) *testSubscriber {
ts := &testSubscriber{
dataCh: p.Subscribe(),
ch: make(chan error),
}
go func() {
for data := range ts.dataCh {
s, ok := data.(string)
if !ok {
ts.ch <- fmt.Errorf("Unexpected type %T", data)
break
}
if s != sampleText {
ts.ch <- fmt.Errorf("Unexpected text %s", s)
break
}
}
close(ts.ch)
}()
return ts
}
// for testing with -race
func TestPubSubRace(t *testing.T) {
p := NewPublisher(0, 1024)
var subs []*testSubscriber
for j := 0; j < 50; j++ {
subs = append(subs, newTestSubscriber(p))
}
for j := 0; j < 1000; j++ {
p.Publish(sampleText)
}
time.AfterFunc(1*time.Second, func() {
for _, s := range subs {
p.Evict(s.dataCh)
}
})
for _, s := range subs {
_ = s.Wait()
}
}
func BenchmarkPubSub(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer()
p := NewPublisher(0, 1024)
var subs []*testSubscriber
for j := 0; j < 50; j++ {
subs = append(subs, newTestSubscriber(p))
}
b.StartTimer()
for j := 0; j < 1000; j++ {
p.Publish(sampleText)
}
time.AfterFunc(1*time.Second, func() {
for _, s := range subs {
p.Evict(s.dataCh)
}
})
for _, s := range subs {
if err := s.Wait(); err != nil {
b.Fatal(err)
}
}
}
}
|