-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathratelimit_handler_test.go
54 lines (46 loc) · 1.14 KB
/
ratelimit_handler_test.go
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
package logging_test
import (
"bytes"
"context"
"fmt"
"io"
"log/slog"
"os"
"testing"
"time"
"github.com/castai/logging"
"golang.org/x/time/rate"
)
func TestRateLimiterHandler(t *testing.T) {
rateLimitHandler := logging.NewRateLimitHandler(logging.RateLimiterHandlerConfig{
Limit: rate.Every(10 * time.Millisecond),
Burst: 1,
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go logging.PrintDroppedLogs(ctx, 1*time.Millisecond, rateLimitHandler, func(level slog.Level, count uint64) {
fmt.Println("dropped", level, count)
})
var buf bytes.Buffer
log := logging.New(
logging.NewTextHandler(logging.TextHandlerConfig{Output: io.MultiWriter(&buf, os.Stdout)}),
rateLimitHandler,
)
for i := 0; i < 10; i++ {
log.WithField("component", "test").Info("test")
time.Sleep(8 * time.Millisecond)
}
actualLinesCount := countLogLines(&buf)
if actualLinesCount > 9 || actualLinesCount < 1 {
t.Errorf("got %d lines, want at least 1 but no more than 10", actualLinesCount)
}
}
func countLogLines(buf *bytes.Buffer) int {
var n int
for _, b := range buf.Bytes() {
if b == '\n' {
n++
}
}
return n
}