Debian Codegraph @

vnet/tbf_test.go

raw symbols SCIP
1 package vnet
2
3 import (
4 "context"
5 "sync"
6 "testing"
7 "time"
8
9 "github.com/pion/logging"
10 "github.com/stretchr/testify/assert"
11 )
12
13 func TestTokenBucketFilter(t *testing.T) {
14 t.Run("bitrateBelowCapacity", func(t *testing.T) {
15 mnic := newMockNIC(t)
16
17 tbf, err := NewTokenBucketFilter(mnic, TBFRate(10*MBit), TBFMaxBurst(10*MBit))
18 assert.NoError(t, err, "should succeed")
19
20 received := 0
21 mnic.mockOnInboundChunk = func(Chunk) {
22 received++
23 }
24
25 time.Sleep(1 * time.Second)
26
27 sent := 100
28 for i := 0; i < sent; i++ {
29 tbf.onInboundChunk(&chunkUDP{
30 userData: make([]byte, 1200),
31 })
32 }
33
34 assert.NoError(t, tbf.Close())
35
36 assert.Equal(t, sent, received)
37 })
38
39 subTest := func(t *testing.T, capacity int, duration time.Duration) {
40 log := logging.NewDefaultLoggerFactory().NewLogger("test")
41
42 mnic := newMockNIC(t)
43
44 tbf, err := NewTokenBucketFilter(mnic, TBFRate(capacity))
45 assert.NoError(t, err, "should succeed")
46
47 chunkChan := make(chan Chunk)
48 mnic.mockOnInboundChunk = func(c Chunk) {
49 chunkChan <- c
50 }
51
52 var wg sync.WaitGroup
53 wg.Add(1)
54
55 ctx, cancel := context.WithCancel(context.Background())
56
57 go func() {
58 defer wg.Done()
59
60 bytesReceived := 0
61 packetsReceived := 0
62 start := time.Now()
63 for {
64 select {
65 case <-ctx.Done():
66 bits := float64(bytesReceived) * 8.0
67 rate := bits / time.Since(start).Seconds()
68 mBitPerSecond := rate / float64(MBit)
69
70 // Allow 5% more than capacity due to max bursts
71 assert.Less(t, rate, 1.05*float64(capacity))
72 assert.Greater(t, rate, float64(0))
73
74 log.Infof("duration=%v, bytesReceived=%v, packetsReceived=%v throughput=%.2f Mb/s", time.Since(start), bytesReceived, packetsReceived, mBitPerSecond)
75 return
76
77 case c := <-chunkChan:
78 bytesReceived += len(c.UserData())
79 packetsReceived++
80 }
81 }
82 }()
83
84 go func() {
85 defer cancel()
86 bytesSent := 0
87 packetsSent := 0
88 var start time.Time
89 for start = time.Now(); time.Since(start) < duration; {
90 c := &chunkUDP{
91 userData: make([]byte, 1200),
92 }
93 tbf.onInboundChunk(c)
94 bytesSent += len(c.UserData())
95 packetsSent++
96 time.Sleep(1 * time.Millisecond)
97 }
98 bits := float64(bytesSent) * 8.0
99 rate := bits / time.Since(start).Seconds()
100 mBitPerSecond := rate / float64(MBit)
101 log.Infof("duration=%v, bytesSent=%v, packetsSent=%v throughput=%.2f Mb/s", time.Since(start), bytesSent, packetsSent, mBitPerSecond)
102
103 assert.NoError(t, tbf.Close())
104 }()
105
106 wg.Wait()
107 }
108
109 t.Run("500Kbit-s", func(t *testing.T) {
110 subTest(t, 500*KBit, 10*time.Second)
111 })
112
113 t.Run("1Mbit-s", func(t *testing.T) {
114 subTest(t, 1*MBit, 10*time.Second)
115 })
116
117 t.Run("2Mbit-s", func(t *testing.T) {
118 subTest(t, 2*MBit, 10*time.Second)
119 })
120 }