ytui/pubsub/pt_test.go

76 lines
1.4 KiB
Go
Raw Normal View History

2022-06-26 19:30:26 -04:00
package pubsub
import (
"sync"
"testing"
2022-06-26 22:34:53 -04:00
"time"
2022-06-26 19:30:26 -04:00
)
func TestDupePublisher(t *testing.T) {
pt := NewProgressTracker()
if _, err := pt.Publish("foo"); err != nil {
t.Fatalf("First publisher should not give error, err:%v", err)
}
if _, err := pt.Publish("foo"); err == nil {
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
}
if _, err := pt.Publish("bar"); err != nil {
t.Fatalf("Different publisher should not give error, err:%v", err)
}
}
func TestSubSub(t *testing.T) {
pt := NewProgressTracker()
c1 := pt.Subscribe("foo")
select {
case <-c1:
default:
}
if c1 == nil {
t.Fatal("Subscriber should not get a closed channel")
}
c2 := pt.Subscribe("foo")
if c2 == nil {
t.Fatal("Subscriber should not get a closed channel")
}
}
func TestPubSub(t *testing.T) {
pt := NewProgressTracker()
2022-06-26 22:34:53 -04:00
pc, err := pt.Publish("foo")
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")
}
sc := pt.Subscribe("foo")
if sc == nil {
t.Fatal("Should not get nil channel")
}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
for range sc {
}
wg.Done()
}()
for i := 0; i < 10; i++ {
pc <- "blah"
2022-06-26 22:34:53 -04:00
if i == 4 || i == 5 {
time.Sleep(100 * time.Millisecond)
}
2022-06-26 19:30:26 -04:00
}
close(pc)
wg.Wait()
2022-06-26 22:34:53 -04:00
sc2 := pt.Subscribe("foo")
if sc2 != nil {
t.Fatal("Subscriber after publisher done should return nil")
}
2022-06-26 19:30:26 -04:00
}