2019-12-10 15:04:22 +08:00
|
|
|
package singledo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestBasic(t *testing.T) {
|
|
|
|
single := NewSingle(time.Millisecond * 30)
|
|
|
|
foo := 0
|
|
|
|
shardCount := 0
|
|
|
|
call := func() (interface{}, error) {
|
|
|
|
foo++
|
2019-12-10 16:26:15 +08:00
|
|
|
time.Sleep(time.Millisecond * 5)
|
2019-12-10 15:04:22 +08:00
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var wg sync.WaitGroup
|
2020-04-30 20:13:27 +08:00
|
|
|
const n = 5
|
2019-12-10 15:04:22 +08:00
|
|
|
wg.Add(n)
|
|
|
|
for i := 0; i < n; i++ {
|
|
|
|
go func() {
|
|
|
|
_, _, shard := single.Do(call)
|
|
|
|
if shard {
|
|
|
|
shardCount++
|
|
|
|
}
|
|
|
|
wg.Done()
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
wg.Wait()
|
|
|
|
assert.Equal(t, 1, foo)
|
2020-04-30 20:13:27 +08:00
|
|
|
assert.Equal(t, 4, shardCount)
|
2019-12-10 15:04:22 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestTimer(t *testing.T) {
|
|
|
|
single := NewSingle(time.Millisecond * 30)
|
|
|
|
foo := 0
|
|
|
|
call := func() (interface{}, error) {
|
|
|
|
foo++
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
single.Do(call)
|
|
|
|
time.Sleep(10 * time.Millisecond)
|
|
|
|
_, _, shard := single.Do(call)
|
|
|
|
|
|
|
|
assert.Equal(t, 1, foo)
|
|
|
|
assert.True(t, shard)
|
|
|
|
}
|
2020-04-30 20:13:27 +08:00
|
|
|
|
|
|
|
func TestReset(t *testing.T) {
|
|
|
|
single := NewSingle(time.Millisecond * 30)
|
|
|
|
foo := 0
|
|
|
|
call := func() (interface{}, error) {
|
|
|
|
foo++
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
single.Do(call)
|
|
|
|
single.Reset()
|
|
|
|
single.Do(call)
|
|
|
|
|
|
|
|
assert.Equal(t, 2, foo)
|
|
|
|
}
|