github.com/iotexproject/iotex-core@v1.14.1-rc1/p2p/qos_test.go (about) 1 // Copyright (c) 2021 IoTeX Foundation 2 // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability 3 // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed. 4 // This source code is governed by Apache License 2.0 that can be found in the LICENSE file. 5 6 package p2p 7 8 import ( 9 "testing" 10 "time" 11 12 "github.com/stretchr/testify/require" 13 ) 14 15 func TestQos(t *testing.T) { 16 r := require.New(t) 17 18 now := time.Now() 19 q := NewQoS(now, time.Second) 20 21 for _, test := range []struct { 22 send, broadcast, success bool 23 }{ 24 {true, true, false}, 25 {false, false, true}, 26 {false, true, false}, 27 {true, true, true}, 28 {false, false, false}, 29 {true, false, true}, 30 {false, true, true}, 31 {true, false, false}, 32 } { 33 t := time.Now() 34 if test.send { 35 if test.broadcast { 36 q.updateSendBroadcast(t, test.success) 37 } else { 38 q.updateSendUnicast("test", t, test.success) 39 } 40 } else { 41 if test.broadcast { 42 q.updateRecvBroadcast(t) 43 } else { 44 q.updateRecvUnicast("test", t) 45 } 46 } 47 } 48 49 r.EqualValues(2, q.BroadcastSendTotal()) 50 r.EqualValues(1, q.broadcastSendSuccess) 51 r.EqualValues(2, q.BroadcastRecvTotal()) 52 c, ok := q.UnicastSendTotal("test") 53 r.True(ok) 54 r.EqualValues(2, c) 55 c, ok = q.UnicastRecvTotal("test") 56 r.True(ok) 57 r.EqualValues(2, c) 58 rate, ok := q.UnicastSendSuccessRate("test") 59 r.True(ok) 60 r.EqualValues(0.5, rate) 61 r.EqualValues(0.5, q.BroadcastSendSuccessRate()) 62 _, ok = q.UnicastSendTotal("noname") 63 r.False(ok) 64 _, ok = q.UnicastRecvTotal("noname") 65 r.False(ok) 66 _, ok = q.UnicastSendSuccessRate("noname") 67 r.False(ok) 68 r.True(q.lastBroadcastTime().After(now)) 69 r.True(q.lastUnicastTime().After(now)) 70 71 r.False(q.lostConnection()) 72 time.Sleep(750 * time.Millisecond) 73 r.False(q.lostConnection()) 74 q.updateRecvUnicast("test", time.Now()) 75 time.Sleep(750 * time.Millisecond) 76 r.False(q.lostConnection()) 77 time.Sleep(250 * time.Millisecond) 78 r.True(q.lostConnection()) 79 }