forked from pion/transport
/
stress.go
97 lines (79 loc) · 1.7 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
package test
import (
"bytes"
"fmt"
"io"
"sync"
)
// 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 {
bufs := make(chan []byte, opt.MsgCount)
errCh := make(chan error)
// Write
go func() {
err := write(ca, bufs, opt)
errCh <- err
close(bufs)
}()
// Read
go func() {
result := make([]byte, opt.MsgSize)
for original := range bufs {
err := read(cb, original, result)
if err != nil {
errCh <- err
}
}
close(errCh)
}()
return FlattenErrs(GatherErrs(errCh))
}
func read(r io.Reader, original, result []byte) error {
n, err := r.Read(result)
if err != nil {
return err
}
if !bytes.Equal(original, result[:n]) {
return fmt.Errorf("byte sequence changed %#v != %#v", 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 {
errCh := make(chan error)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
errCh <- Stress(ca, cb, opt)
}()
go func() {
defer wg.Done()
errCh <- Stress(cb, ca, opt)
}()
go func() {
wg.Wait()
close(errCh)
}()
return FlattenErrs(GatherErrs(errCh))
}
func write(c io.Writer, bufs chan []byte, opt Options) error {
for i := 0; i < opt.MsgCount; i++ {
buf, err := randBuf(opt.MsgSize)
if err != nil {
return err
}
bufs <- buf
if _, err = c.Write(buf); err != nil {
return err
}
}
return nil
}