/
tbf_test.go
120 lines (94 loc) · 2.64 KB
/
tbf_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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package vnet
import (
"context"
"sync"
"testing"
"time"
"github.com/pion/logging"
"github.com/stretchr/testify/assert"
)
func TestTokenBucketFilter(t *testing.T) {
t.Run("bitrateBelowCapacity", func(t *testing.T) {
mnic := newMockNIC(t)
tbf, err := NewTokenBucketFilter(mnic, TBFRate(10*MBit), TBFMaxBurst(10*MBit))
assert.NoError(t, err)
received := 0
mnic.mockOnInboundChunk = func(Chunk) {
received++
}
time.Sleep(1 * time.Second)
sent := 100
for i := 0; i < sent; i++ {
tbf.onInboundChunk(&chunkUDP{
userData: make([]byte, 1200),
})
}
assert.NoError(t, tbf.Close())
assert.Equal(t, sent, received)
})
subTest := func(t *testing.T, capacity int, duration time.Duration) {
log := logging.NewDefaultLoggerFactory().NewLogger("test")
mnic := newMockNIC(t)
tbf, err := NewTokenBucketFilter(mnic, TBFRate(capacity))
assert.NoError(t, err)
chunkChan := make(chan Chunk)
mnic.mockOnInboundChunk = func(c Chunk) {
chunkChan <- c
}
var wg sync.WaitGroup
wg.Add(1)
ctx, cancel := context.WithCancel(context.Background())
go func() {
defer wg.Done()
bytesReceived := 0
packetsReceived := 0
start := time.Now()
for {
select {
case <-ctx.Done():
bits := float64(bytesReceived) * 8.0
rate := bits / time.Since(start).Seconds()
mBitPerSecond := rate / float64(MBit)
// Allow 5% more than capacity due to max bursts
assert.Less(t, rate, 1.05*float64(capacity))
assert.Greater(t, rate, float64(0))
log.Infof("duration=%v, bytesReceived=%v, packetsReceived=%v throughput=%.2f Mb/s", time.Since(start), bytesReceived, packetsReceived, mBitPerSecond)
return
case c := <-chunkChan:
bytesReceived += len(c.UserData())
packetsReceived++
}
}
}()
go func() {
defer cancel()
bytesSent := 0
packetsSent := 0
var start time.Time
for start = time.Now(); time.Since(start) < duration; {
c := &chunkUDP{
userData: make([]byte, 1200),
}
tbf.onInboundChunk(c)
bytesSent += len(c.UserData())
packetsSent++
time.Sleep(1 * time.Millisecond)
}
bits := float64(bytesSent) * 8.0
rate := bits / time.Since(start).Seconds()
mBitPerSecond := rate / float64(MBit)
log.Infof("duration=%v, bytesSent=%v, packetsSent=%v throughput=%.2f Mb/s", time.Since(start), bytesSent, packetsSent, mBitPerSecond)
assert.NoError(t, tbf.Close())
}()
wg.Wait()
}
t.Run("500Kbit-s", func(t *testing.T) {
subTest(t, 500*KBit, 10*time.Second)
})
t.Run("1Mbit-s", func(t *testing.T) {
subTest(t, 1*MBit, 10*time.Second)
})
t.Run("2Mbit-s", func(t *testing.T) {
subTest(t, 2*MBit, 10*time.Second)
})
}