File: token_bucket_test.go

package info (click to toggle)
golang-github-go-kit-kit 0.6.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 4,820 kB
  • sloc: sh: 65; makefile: 14
file content (63 lines) | stat: -rw-r--r-- 1,627 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package ratelimit_test

import (
	"context"
	"strings"
	"testing"
	"time"

	jujuratelimit "github.com/juju/ratelimit"
	"golang.org/x/time/rate"

	"github.com/go-kit/kit/endpoint"
	"github.com/go-kit/kit/ratelimit"
)

var nopEndpoint = func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil }

func TestTokenBucketLimiter(t *testing.T) {
	tb := jujuratelimit.NewBucket(time.Minute, 1)
	testSuccessThenFailure(
		t,
		ratelimit.NewTokenBucketLimiter(tb)(nopEndpoint),
		ratelimit.ErrLimited.Error())
}

func TestTokenBucketThrottler(t *testing.T) {
	tb := jujuratelimit.NewBucket(time.Minute, 1)
	testSuccessThenFailure(
		t,
		ratelimit.NewTokenBucketThrottler(tb, nil)(nopEndpoint),
		"context deadline exceeded")
}

func TestXRateErroring(t *testing.T) {
	limit := rate.NewLimiter(rate.Every(time.Minute), 1)
	testSuccessThenFailure(
		t,
		ratelimit.NewErroringLimiter(limit)(nopEndpoint),
		ratelimit.ErrLimited.Error())
}

func TestXRateDelaying(t *testing.T) {
	limit := rate.NewLimiter(rate.Every(time.Minute), 1)
	testSuccessThenFailure(
		t,
		ratelimit.NewDelayingLimiter(limit)(nopEndpoint),
		"exceed context deadline")
}

func testSuccessThenFailure(t *testing.T, e endpoint.Endpoint, failContains string) {
	ctx, cxl := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer cxl()

	// First request should succeed.
	if _, err := e(ctx, struct{}{}); err != nil {
		t.Errorf("unexpected: %v\n", err)
	}

	// Next request should fail.
	if _, err := e(ctx, struct{}{}); !strings.Contains(err.Error(), failContains) {
		t.Errorf("expected `%s`: %v\n", failContains, err)
	}
}