Improve log.testConcurrency to check errors and control total event count.
Chris Hines
7 years ago
0 | 0 |
package log_test
|
1 | 1 |
|
2 | 2 |
import (
|
3 | |
"strconv"
|
4 | |
"sync"
|
|
3 |
"math"
|
5 | 4 |
"testing"
|
6 | 5 |
|
7 | 6 |
"github.com/go-kit/kit/log"
|
|
9 | 8 |
|
10 | 9 |
// These test are designed to be run with the race detector.
|
11 | 10 |
|
12 | |
func testConcurrency(t *testing.T, logger log.Logger) {
|
13 | |
for _, n := range []int{10, 100, 500} {
|
14 | |
wg := sync.WaitGroup{}
|
15 | |
wg.Add(n)
|
16 | |
for i := 0; i < n; i++ {
|
17 | |
go func() { spam(logger); wg.Done() }()
|
|
11 |
func testConcurrency(t *testing.T, logger log.Logger, total int) {
|
|
12 |
n := int(math.Sqrt(float64(total)))
|
|
13 |
share := total / n
|
|
14 |
|
|
15 |
errC := make(chan error, n)
|
|
16 |
|
|
17 |
for i := 0; i < n; i++ {
|
|
18 |
go func() {
|
|
19 |
errC <- spam(logger, share)
|
|
20 |
}()
|
|
21 |
}
|
|
22 |
|
|
23 |
for i := 0; i < n; i++ {
|
|
24 |
err := <-errC
|
|
25 |
if err != nil {
|
|
26 |
t.Fatalf("concurrent logging error: %v", err)
|
18 | 27 |
}
|
19 | |
wg.Wait()
|
20 | 28 |
}
|
21 | 29 |
}
|
22 | 30 |
|
23 | |
func spam(logger log.Logger) {
|
24 | |
for i := 0; i < 100; i++ {
|
25 | |
logger.Log("key", strconv.FormatInt(int64(i), 10))
|
|
31 |
func spam(logger log.Logger, count int) error {
|
|
32 |
for i := 0; i < count; i++ {
|
|
33 |
err := logger.Log("key", i)
|
|
34 |
if err != nil {
|
|
35 |
return err
|
|
36 |
}
|
26 | 37 |
}
|
|
38 |
return nil
|
27 | 39 |
}
|
152 | 152 |
}
|
153 | 153 |
|
154 | 154 |
func TestJSONLoggerConcurrency(t *testing.T) {
|
155 | |
testConcurrency(t, log.NewJSONLogger(ioutil.Discard))
|
|
155 |
t.Parallel()
|
|
156 |
testConcurrency(t, log.NewJSONLogger(ioutil.Discard), 10000)
|
156 | 157 |
}
|
47 | 47 |
}
|
48 | 48 |
|
49 | 49 |
func TestLogfmtLoggerConcurrency(t *testing.T) {
|
50 | |
testConcurrency(t, log.NewLogfmtLogger(ioutil.Discard))
|
|
50 |
t.Parallel()
|
|
51 |
testConcurrency(t, log.NewLogfmtLogger(ioutil.Discard), 10000)
|
51 | 52 |
}
|
52 | 53 |
|
53 | 54 |
type mymap map[int]int
|
51 | 51 |
}
|
52 | 52 |
|
53 | 53 |
func TestSwapLoggerConcurrency(t *testing.T) {
|
54 | |
testConcurrency(t, &log.SwapLogger{})
|
|
54 |
t.Parallel()
|
|
55 |
testConcurrency(t, &log.SwapLogger{}, 10000)
|
55 | 56 |
}
|
56 | 57 |
|
57 | 58 |
func TestSyncLoggerConcurrency(t *testing.T) {
|
|
59 | 60 |
w = &bytes.Buffer{}
|
60 | 61 |
logger := log.NewLogfmtLogger(w)
|
61 | 62 |
logger = log.NewSyncLogger(logger)
|
62 | |
testConcurrency(t, logger)
|
|
63 |
testConcurrency(t, logger, 10000)
|
63 | 64 |
}
|
64 | 65 |
|
65 | 66 |
func TestSyncWriterConcurrency(t *testing.T) {
|
66 | 67 |
var w io.Writer
|
67 | 68 |
w = &bytes.Buffer{}
|
68 | 69 |
w = log.NewSyncWriter(w)
|
69 | |
testConcurrency(t, log.NewLogfmtLogger(w))
|
|
70 |
testConcurrency(t, log.NewLogfmtLogger(w), 10000)
|
70 | 71 |
}
|