Improve: fix go test race detect

This commit is contained in:
Dreamacro
2020-07-18 20:56:13 +08:00
parent 6c7a8fffe0
commit cf9e1545a4
3 changed files with 19 additions and 12 deletions

View File

@ -1,8 +1,8 @@
package observable
import (
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
@ -38,20 +38,20 @@ func TestObservable_MutilSubscribe(t *testing.T) {
src := NewObservable(iter)
ch1, _ := src.Subscribe()
ch2, _ := src.Subscribe()
count := 0
var count int32
var wg sync.WaitGroup
wg.Add(2)
waitCh := func(ch <-chan interface{}) {
for range ch {
count++
atomic.AddInt32(&count, 1)
}
wg.Done()
}
go waitCh(ch1)
go waitCh(ch2)
wg.Wait()
assert.Equal(t, count, 10)
assert.Equal(t, int32(10), count)
}
func TestObservable_UnSubscribe(t *testing.T) {
@ -82,9 +82,6 @@ func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
}
func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
// waiting for other goroutine recycle
time.Sleep(120 * time.Millisecond)
init := runtime.NumGoroutine()
iter := iterator([]interface{}{1, 2, 3, 4, 5})
src := NewObservable(iter)
max := 100
@ -107,6 +104,12 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
go waitCh(ch)
}
wg.Wait()
now := runtime.NumGoroutine()
assert.Equal(t, init, now)
for _, sub := range list {
_, more := <-sub
assert.False(t, more)
}
_, more := <-list[0]
assert.False(t, more)
}