ytui/pubsub/pt_test.go
2022-06-27 13:05:00 -04:00

83 lines
1.4 KiB
Go

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