github.com/aergoio/aergo@v1.3.1/consensus/impl/dpos/slot/slot_test.go (about)

     1  /**
     2   *  @file
     3   *  @copyright defined in aergo/LICENSE.txt
     4   */
     5  package slot
     6  
     7  import (
     8  	"fmt"
     9  	"testing"
    10  	"time"
    11  
    12  	"github.com/stretchr/testify/assert"
    13  )
    14  
    15  const (
    16  	nSlots     = 5
    17  	bpInterval = 1
    18  )
    19  
    20  func TestSlotRotation(t *testing.T) {
    21  	Init(bpInterval)
    22  
    23  	ticker := time.NewTicker(time.Second)
    24  	slots := make(map[int64]interface{}, nSlots)
    25  	i := 0
    26  	for now := range ticker.C {
    27  		idx := Time(now).NextBpIndex(nSlots)
    28  		slots[idx] = struct{}{}
    29  		fmt.Printf("[%v]", idx)
    30  		if i > nSlots {
    31  			break
    32  		}
    33  		i++
    34  	}
    35  	fmt.Println()
    36  	assert.True(t, nSlots <= len(slots), "invalid slot index")
    37  }
    38  
    39  func TestSlotConversion(t *testing.T) {
    40  	Init(bpInterval)
    41  
    42  	slot := Now()
    43  	assert.Equal(t, nsToMs(slot.timeNs), slot.timeMs, "inconsistent slot members")
    44  	fmt.Println(slot.timeNs, slot.timeMs)
    45  }
    46  
    47  func TestSlotValidNow(t *testing.T) {
    48  	Init(bpInterval)
    49  
    50  	assert.True(t, Now().IsValidNow(), "invalid slot")
    51  }
    52  
    53  func TestSlotFuture(t *testing.T) {
    54  	Init(bpInterval)
    55  
    56  	assert.True(t, !Time(time.Now().Add(-time.Second)).IsFuture(), "must not be a future slot")
    57  	assert.True(t, !Now().IsFuture(), "must not be a future slot")
    58  	assert.True(t, !Time(time.Now().Add(time.Second)).IsFuture(), "must not be a future slot")
    59  	assert.True(t, Time(time.Now().Add(2*time.Second)).IsFuture(), "must be a future slot")
    60  	assert.True(t, Time(time.Now().Add(3*time.Second)).IsFuture(), "must be a future slot")
    61  }