grafana/pkg/services/screenshot/ratelimit_test.go
George Robinson bad4f7fec5
Alerting: Change screenshots to use components (#55156)
* Alerting: Change screenshots to use components

This commit changes screenshots to use a number of components instead of a set of functional wrappers.

It moves the uploading of screenshots from the screenshot package to the image package so we can re-use the same code for both uploading screenshots and server-side images; SingleFlight from the screenshot package to the image package so we can use it for both taking and uploading the screenshot, where as before it was used just for taking the screenshot; and it also removes the use of a cache because we know that screenshots can be taken at most once per tick of the scheduler.
2022-09-21 10:25:07 +01:00

55 lines
1.1 KiB
Go

package screenshot
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTokenRateLimiter(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
r := NewTokenRateLimiter(1)
ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second)
defer cancelFunc()
var (
v int64
wg sync.WaitGroup
)
testScreenshotFunc := func(ctx context.Context, opts ScreenshotOptions) (*Screenshot, error) {
// v should be 1 to show that no other goroutines acquired the token
atomic.AddInt64(&v, 1)
assert.Equal(t, int64(1), atomic.LoadInt64(&v))
// interrupt so other goroutines can attempt to acquire the token
<-time.After(time.Microsecond)
// v should be 0
atomic.AddInt64(&v, -1)
assert.Equal(t, int64(0), atomic.LoadInt64(&v))
return &Screenshot{}, nil
}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
screenshot, err := r.Do(ctx, ScreenshotOptions{}, testScreenshotFunc)
require.NoError(t, err)
assert.NotNil(t, screenshot)
}()
}
wg.Wait()
}