Skip to content

Commit

Permalink
Improve: fix go test race detect
Browse files Browse the repository at this point in the history
  • Loading branch information
Dreamacro committed Jul 18, 2020
1 parent 6c7a8ff commit cf9e154
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 12 deletions.
21 changes: 12 additions & 9 deletions common/observable/observable_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package observable

import (
"runtime"
"sync"
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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
Expand All @@ -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)
}
3 changes: 3 additions & 0 deletions common/singledo/singledo.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,12 @@ func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, err error, s
s.mux.Unlock()
call.val, call.err = fn()
call.wg.Done()

s.mux.Lock()
s.call = nil
s.result = &Result{call.val, call.err}
s.last = now
s.mux.Unlock()
return call.val, call.err, false
}

Expand Down
7 changes: 4 additions & 3 deletions common/singledo/singledo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package singledo

import (
"sync"
"sync/atomic"
"testing"
"time"

Expand All @@ -11,7 +12,7 @@ import (
func TestBasic(t *testing.T) {
single := NewSingle(time.Millisecond * 30)
foo := 0
shardCount := 0
var shardCount int32 = 0
call := func() (interface{}, error) {
foo++
time.Sleep(time.Millisecond * 5)
Expand All @@ -25,15 +26,15 @@ func TestBasic(t *testing.T) {
go func() {
_, _, shard := single.Do(call)
if shard {
shardCount++
atomic.AddInt32(&shardCount, 1)
}
wg.Done()
}()
}

wg.Wait()
assert.Equal(t, 1, foo)
assert.Equal(t, 4, shardCount)
assert.Equal(t, int32(4), shardCount)
}

func TestTimer(t *testing.T) {
Expand Down

0 comments on commit cf9e154

Please sign in to comment.