go.etcd.io/etcd@v3.3.27+incompatible/raft/rafttest/network_test.go (about)

     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  
    15  package rafttest
    16  
    17  import (
    18  	"testing"
    19  	"time"
    20  
    21  	"github.com/coreos/etcd/raft/raftpb"
    22  )
    23  
    24  func TestNetworkDrop(t *testing.T) {
    25  	// drop around 10% messages
    26  	sent := 1000
    27  	droprate := 0.1
    28  	nt := newRaftNetwork(1, 2)
    29  	nt.drop(1, 2, droprate)
    30  	for i := 0; i < sent; i++ {
    31  		nt.send(raftpb.Message{From: 1, To: 2})
    32  	}
    33  
    34  	c := nt.recvFrom(2)
    35  
    36  	received := 0
    37  	done := false
    38  	for !done {
    39  		select {
    40  		case <-c:
    41  			received++
    42  		default:
    43  			done = true
    44  		}
    45  	}
    46  
    47  	drop := sent - received
    48  	if drop > int((droprate+0.1)*float64(sent)) || drop < int((droprate-0.1)*float64(sent)) {
    49  		t.Errorf("drop = %d, want around %.2f", drop, droprate*float64(sent))
    50  	}
    51  }
    52  
    53  func TestNetworkDelay(t *testing.T) {
    54  	sent := 1000
    55  	delay := time.Millisecond
    56  	delayrate := 0.1
    57  	nt := newRaftNetwork(1, 2)
    58  
    59  	nt.delay(1, 2, delay, delayrate)
    60  	var total time.Duration
    61  	for i := 0; i < sent; i++ {
    62  		s := time.Now()
    63  		nt.send(raftpb.Message{From: 1, To: 2})
    64  		total += time.Since(s)
    65  	}
    66  
    67  	w := time.Duration(float64(sent)*delayrate/2) * delay
    68  	// there is some overhead in the send call since it generates random numbers.
    69  	if total < w {
    70  		t.Errorf("total = %v, want > %v", total, w)
    71  	}
    72  }