BlueGit

timfa bluegit

Files

bluegit / internal / backupserver / throttle / throttle_test.go

throttle_test.go

throttle_test.go 1.6 KiB Download Raw
1package throttle
2
3import (
4 "bytes"
5 "context"
6 "io"
7 "testing"
8 "time"
9)
10
11func TestLimiterAverage(t *testing.T) {
12 now := time.Unix(0, 0)
13 slept := time.Duration(0)
14 l := New(100 << 10) // 100 KiB/s
15 l.now = func() time.Time { return now }
16 l.last = now
17 l.sleep = func(_ context.Context, d time.Duration) error {
18 slept += d
19 now = now.Add(d)
20 return nil
21 }
22 data := bytes.Repeat([]byte("x"), 1<<20) // 1 MiB
23 n, err := io.Copy(io.Discard, l.Reader(context.Background(), bytes.NewReader(data)))
24 if err != nil || n != 1<<20 {
25 t.Fatal(n, err)
26 }
27 // 1 MiB tegen 100 KiB/s is ruim 10 s, min de eerste burst van 25 KiB.
28 if slept < 9500*time.Millisecond || slept > 10500*time.Millisecond {
29 t.Fatalf("geslapen %v, verwacht ~10s", slept)
30 }
31}
32
33func TestUnlimited(t *testing.T) {
34 l := New(0)
35 r := bytes.NewReader([]byte("abc"))
36 if b, _ := io.ReadAll(l.Reader(context.Background(), r)); string(b) != "abc" {
37 t.Fatal(string(b))
38 }
39 if err := l.Wait(context.Background(), 1<<30); err != nil {
40 t.Fatal(err)
41 }
42}
43
44func TestCancel(t *testing.T) {
45 l := New(1024)
46 ctx, cancel := context.WithCancel(context.Background())
47 cancel()
48 _ = l.Wait(ctx, 16<<10)
49 if err := l.Wait(ctx, 16<<10); err == nil {
50 t.Fatal("geen fout na annuleren")
51 }
52}
53
54func TestSetRate(t *testing.T) {
55 l := New(0)
56 l.SetRate(2048)
57 if l.Rate() != 2048 {
58 t.Fatal(l.Rate())
59 }
60 var slept time.Duration
61 l.sleep = func(_ context.Context, d time.Duration) error { slept += d; return nil }
62 now := time.Unix(0, 0)
63 l.now = func() time.Time { return now }
64 l.last = now
65 l.tokens = 0
66 _ = l.Wait(context.Background(), 4096)
67 if slept != 2*time.Second {
68 t.Fatal(slept)
69 }
70}