github.com/aergoio/aergo@v1.3.1/p2p/raftsupport/status_test.go (about)

     1  /*
     2   * @file
     3   * @copyright defined in aergo/LICENSE.txt
     4   */
     5  
     6  package raftsupport
     7  
     8  import (
     9  	"math/rand"
    10  	"strconv"
    11  	"sync"
    12  	"testing"
    13  	"time"
    14  
    15  	"github.com/aergoio/aergo-lib/log"
    16  	"github.com/aergoio/aergo/types"
    17  	rtypes "github.com/aergoio/etcd/pkg/types"
    18  )
    19  
    20  func Test_rPeerStatus_activate(t *testing.T) {
    21  	logger := log.NewLogger("raft.support.test")
    22  	id := rtypes.ID(111)
    23  	pid,_ := types.IDB58Decode("16Uiu2HAmFqptXPfcdaCdwipB2fhHATgKGVFVPehDAPZsDKSU7jRm")
    24  
    25  	tests := []struct {
    26  		name   string
    27  		lastAct bool
    28  
    29  		wantActive bool
    30  	}{
    31  		{"TActive",true, true},
    32  		{"TInactive",false, false},
    33  	}
    34  	for _, tt := range tests {
    35  		t.Run(tt.name, func(t *testing.T) {
    36  			s := newPeerStatus(id, pid, logger)
    37  
    38  			barrier := sync.WaitGroup{}
    39  			barrier.Add(2)
    40  			allFin := make(chan bool)
    41  			startTime := time.Now()
    42  			go func() {
    43  				barrier.Wait()
    44  				if tt.lastAct {
    45  					s.activate()
    46  				} else {
    47  					s.deactivate("final")
    48  				}
    49  				close(allFin)
    50  			}()
    51  			// do activate
    52  			go func() {
    53  				for i:=0;i<100;i++ {
    54  					s.activate()
    55  					time.Sleep(time.Microsecond*time.Duration(rand.Intn(10)))
    56  				}
    57  				barrier.Done()
    58  			}()
    59  			// do deactivate
    60  			go func() {
    61  				for i:=0;i<100;i++ {
    62  					s.deactivate("p "+strconv.Itoa(i))
    63  					time.Sleep(time.Microsecond*time.Duration(rand.Intn(10)))
    64  				}
    65  				barrier.Done()
    66  			}()
    67  
    68  			<- allFin
    69  			if s.isActive() != tt.wantActive {
    70  				t.Errorf("rPeerStatus.isActive() = %v , want %v",s.isActive(), tt.wantActive)
    71  			}
    72  			if s.isActive() != (s.activeSince().After(startTime)) {
    73  				t.Errorf("rPeerStatus.ActiveSince() = %v , want not ",s.activeSince() )
    74  			}
    75  		})
    76  	}
    77  }