-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlimiter_test.go
103 lines (90 loc) · 1.8 KB
/
limiter_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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Tideland Go Together - Limiter - Unit Tests
//
// Copyright (C) 2019 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.
package limiter_test
//--------------------
// IMPORTS
//--------------------
import (
"context"
"errors"
"sync"
"testing"
"time"
"tideland.dev/go/audit/asserts"
"tideland.dev/go/together/limiter"
)
//--------------------
// TESTS
//--------------------
// TestLimitOK tests the limiting of a number of function calls
// in multiple goroutines without an error.
func TestLimitOK(t *testing.T) {
// Init.
assert := asserts.NewTesting(t, asserts.FailStop)
runs := 100
startedC := make(chan struct{}, 1)
stoppedC := make(chan struct{}, 1)
resultC := make(chan int, 1)
go func() {
max := 0
act := 0
count := 0
for count < runs {
select {
case <-startedC:
act++
if act > max {
max = act
}
case <-stoppedC:
act--
}
count++
}
resultC <- max
}()
job := func() error {
startedC <- struct{}{}
time.Sleep(50 * time.Millisecond)
stoppedC <- struct{}{}
return nil
}
l := limiter.New(10)
ctx := context.Background()
// Test.
for i := 0; i < runs; i++ {
go func() {
err := l.Do(ctx, job)
assert.NoError(err)
}()
}
assert.True(<-resultC <= 11)
}
// TestLimitError tests the returning of en error by an
// executed function.
func TestLimitError(t *testing.T) {
// Init.
assert := asserts.NewTesting(t, asserts.FailStop)
job := func() error {
time.Sleep(25 * time.Millisecond)
return errors.New("ouch")
}
l := limiter.New(5)
ctx := context.Background()
var wg sync.WaitGroup
wg.Add(25)
// Test.
for i := 0; i < 25; i++ {
go func() {
err := l.Do(ctx, job)
assert.ErrorMatch(err, "ouch")
wg.Done()
}()
}
wg.Wait()
}
// EOF