network_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package rafttest
  15. import (
  16. "testing"
  17. "time"
  18. "go.etcd.io/etcd/raft/raftpb"
  19. )
  20. func TestNetworkDrop(t *testing.T) {
  21. // drop around 10% messages
  22. sent := 1000
  23. droprate := 0.1
  24. nt := newRaftNetwork(1, 2)
  25. nt.drop(1, 2, droprate)
  26. for i := 0; i < sent; i++ {
  27. nt.send(raftpb.Message{From: 1, To: 2})
  28. }
  29. c := nt.recvFrom(2)
  30. received := 0
  31. done := false
  32. for !done {
  33. select {
  34. case <-c:
  35. received++
  36. default:
  37. done = true
  38. }
  39. }
  40. drop := sent - received
  41. if drop > int((droprate+0.1)*float64(sent)) || drop < int((droprate-0.1)*float64(sent)) {
  42. t.Errorf("drop = %d, want around %.2f", drop, droprate*float64(sent))
  43. }
  44. }
  45. func TestNetworkDelay(t *testing.T) {
  46. sent := 1000
  47. delay := time.Millisecond
  48. delayrate := 0.1
  49. nt := newRaftNetwork(1, 2)
  50. nt.delay(1, 2, delay, delayrate)
  51. var total time.Duration
  52. for i := 0; i < sent; i++ {
  53. s := time.Now()
  54. nt.send(raftpb.Message{From: 1, To: 2})
  55. total += time.Since(s)
  56. }
  57. w := time.Duration(float64(sent)*delayrate/2) * delay
  58. // there is some overhead in the send call since it generates random numbers.
  59. if total < w {
  60. t.Errorf("total = %v, want > %v", total, w)
  61. }
  62. }