Skip to content

Instantly share code, notes, and snippets.

@suzujun
Last active February 6, 2020 00:02
Show Gist options
  • Save suzujun/2fcb15c1a922500c7fdecb25149db4d0 to your computer and use it in GitHub Desktop.
Save suzujun/2fcb15c1a922500c7fdecb25149db4d0 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"golang.org/x/time/rate"
)
func TestLimitter(t *testing.T) {
const maxCount = 10
var mu sync.Mutex
var wg sync.WaitGroup
ctx := context.Background()
r := time.Millisecond * 100
limit := rate.Every(r)
limiter := rate.NewLimiter(limit, 1)
res := make([]time.Duration, 0, maxCount)
now := time.Now()
for i := 0; i < maxCount; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if err := limiter.Wait(ctx); err != nil {
return
}
mu.Lock()
elapsed := time.Since(now)
now = time.Now()
res = append(res, elapsed)
// do something...
mu.Unlock()
}()
}
wg.Wait()
for i, d := range res[1:] {
assert.True(t, d >= r, fmt.Sprintf("%02d: %d >= %d", i, d, r))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment