2022-06-26 19:30:26 -04:00
|
|
|
package pubsub
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"testing"
|
2022-06-26 23:37:08 -04:00
|
|
|
"time"
|
2022-06-26 19:30:26 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestDupePublisher(t *testing.T) {
|
|
|
|
pt := NewProgressTracker()
|
|
|
|
|
2022-06-27 13:05:00 -04:00
|
|
|
if _, err := pt.Publish(); err != nil {
|
2022-06-26 19:30:26 -04:00
|
|
|
t.Fatalf("First publisher should not give error, err:%v", err)
|
|
|
|
}
|
|
|
|
|
2022-06-27 13:05:00 -04:00
|
|
|
if _, err := pt.Publish(); err == nil {
|
2022-06-26 19:30:26 -04:00
|
|
|
t.Fatal("Dupe publisher should give error but got nil")
|
2022-06-26 22:34:53 -04:00
|
|
|
} else {
|
|
|
|
t.Logf("Got err: %v", err)
|
2022-06-26 19:30:26 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestSubSub(t *testing.T) {
|
|
|
|
pt := NewProgressTracker()
|
2022-06-27 13:05:00 -04:00
|
|
|
c1 := pt.Subscribe()
|
2022-06-26 19:30:26 -04:00
|
|
|
select {
|
|
|
|
case <-c1:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
if c1 == nil {
|
2022-06-27 13:05:00 -04:00
|
|
|
t.Fatal("Subscriber should not get a nil channel")
|
2022-06-26 19:30:26 -04:00
|
|
|
}
|
2022-06-27 13:05:00 -04:00
|
|
|
c2 := pt.Subscribe()
|
2022-06-26 19:30:26 -04:00
|
|
|
if c2 == nil {
|
2022-06-27 13:05:00 -04:00
|
|
|
t.Fatal("Subscriber should not get a nil channel")
|
2022-06-26 19:30:26 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestPubSub(t *testing.T) {
|
|
|
|
pt := NewProgressTracker()
|
2022-06-27 13:05:00 -04:00
|
|
|
pc, err := pt.Publish()
|
2022-06-26 22:34:53 -04:00
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("Unexpected err: %v", err)
|
|
|
|
}
|
2022-06-26 19:30:26 -04:00
|
|
|
if pc == nil {
|
|
|
|
t.Fatal("Should not get nil channel")
|
|
|
|
}
|
2022-06-27 13:05:00 -04:00
|
|
|
sc := pt.Subscribe()
|
2022-06-26 19:30:26 -04:00
|
|
|
if sc == nil {
|
|
|
|
t.Fatal("Should not get nil channel")
|
|
|
|
}
|
|
|
|
wg := sync.WaitGroup{}
|
|
|
|
wg.Add(1)
|
2022-06-26 23:13:57 -04:00
|
|
|
c := 0
|
|
|
|
testc := make(chan int)
|
2022-06-26 19:30:26 -04:00
|
|
|
go func() {
|
|
|
|
for range sc {
|
2022-06-26 23:13:57 -04:00
|
|
|
if c == 0 {
|
|
|
|
close(testc)
|
|
|
|
}
|
|
|
|
c++
|
2022-06-26 19:30:26 -04:00
|
|
|
}
|
|
|
|
wg.Done()
|
|
|
|
}()
|
|
|
|
for i := 0; i < 10; i++ {
|
|
|
|
pc <- "blah"
|
2022-06-26 23:37:08 -04:00
|
|
|
time.Sleep(166 * time.Millisecond)
|
2022-06-26 23:13:57 -04:00
|
|
|
if i == 5 {
|
|
|
|
<-testc
|
2022-06-26 22:34:53 -04:00
|
|
|
}
|
2022-06-26 19:30:26 -04:00
|
|
|
}
|
|
|
|
close(pc)
|
|
|
|
wg.Wait()
|
2022-06-26 23:13:57 -04:00
|
|
|
if c == 0 {
|
|
|
|
t.Fatal("There should be atleast one update")
|
|
|
|
}
|
|
|
|
t.Logf("c is :%d", c)
|
2022-06-27 13:05:00 -04:00
|
|
|
sc2 := pt.Subscribe()
|
2022-06-26 22:34:53 -04:00
|
|
|
if sc2 != nil {
|
|
|
|
t.Fatal("Subscriber after publisher done should return nil")
|
|
|
|
}
|
2022-06-26 19:30:26 -04:00
|
|
|
}
|