/
stress.go
114 lines (94 loc) · 2.62 KB
/
stress.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
104
105
106
107
108
109
110
111
112
113
114
package test
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"sync"
"github.com/pion/transport/connctx"
)
var errByteSequenceChanged = errors.New("byte sequence changed")
// Options represents the configuration of the stress test
type Options struct {
MsgSize int
MsgCount int
}
// Stress enables stress testing of a io.ReadWriter.
// It checks that packets are received correctly and in order.
func Stress(ca io.Writer, cb io.Reader, opt Options) error {
return StressContext(context.Background(), &wrappedWriter{ca}, &wrappedReader{cb}, opt)
}
// StressContext enables stress testing of a io.ReadWriter.
// It checks that packets are received correctly and in order.
func StressContext(ctx context.Context, ca connctx.Writer, cb connctx.Reader, opt Options) error {
bufs := make(chan []byte, opt.MsgCount)
errCh := make(chan error)
// Write
go func() {
err := write(ctx, ca, bufs, opt)
errCh <- err
close(bufs)
}()
// Read
go func() {
result := make([]byte, opt.MsgSize)
for original := range bufs {
err := read(ctx, cb, original, result)
if err != nil {
errCh <- err
}
}
close(errCh)
}()
return FlattenErrs(GatherErrs(errCh))
}
func read(ctx context.Context, r connctx.Reader, original, result []byte) error {
n, err := r.ReadContext(ctx, result)
if err != nil {
return err
}
if !bytes.Equal(original, result[:n]) {
return fmt.Errorf("%w %#v != %#v", errByteSequenceChanged, original, result)
}
return nil
}
// StressDuplex enables duplex stress testing of a io.ReadWriter.
// It checks that packets are received correctly and in order.
func StressDuplex(ca io.ReadWriter, cb io.ReadWriter, opt Options) error {
return StressDuplexContext(context.Background(), &wrappedReadWriter{ca}, &wrappedReadWriter{cb}, opt)
}
// StressDuplexContext enables duplex stress testing of a io.ReadWriter.
// It checks that packets are received correctly and in order.
func StressDuplexContext(ctx context.Context, ca connctx.ReadWriter, cb connctx.ReadWriter, opt Options) error {
errCh := make(chan error)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
errCh <- StressContext(ctx, ca, cb, opt)
}()
go func() {
defer wg.Done()
errCh <- StressContext(ctx, cb, ca, opt)
}()
go func() {
wg.Wait()
close(errCh)
}()
return FlattenErrs(GatherErrs(errCh))
}
func write(ctx context.Context, c connctx.Writer, bufs chan []byte, opt Options) error {
randomizer := initRand()
for i := 0; i < opt.MsgCount; i++ {
buf, err := randomizer.randBuf(opt.MsgSize)
if err != nil {
return err
}
bufs <- buf
if _, err = c.WriteContext(ctx, buf); err != nil {
return err
}
}
return nil
}