github.com/iotexproject/iotex-core@v1.14.1-rc1/pkg/util/blockutil/block_time_calculator_test.go (about) 1 package blockutil 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/stretchr/testify/require" 8 ) 9 10 func TestBlockTimeCalculator_CalculateBlockTime(t *testing.T) { 11 r := require.New(t) 12 interval := 5 * time.Second 13 intervalFn := func(h uint64) time.Duration { 14 return 5 * time.Second 15 } 16 tipHeight := uint64(100) 17 tipHeightF := func() uint64 { return tipHeight } 18 baseTime, err := time.Parse("2006-01-02T15:04:05.000Z", "2022-01-01T00:00:00.000Z") 19 r.NoError(err) 20 historyBlockTimeF := func(height uint64) (time.Time, error) { return baseTime.Add(time.Hour * time.Duration(height)), nil } 21 btc, err := NewBlockTimeCalculator(intervalFn, tipHeightF, historyBlockTimeF) 22 r.NoError(err) 23 24 historyWrapper := func(height uint64) time.Time { 25 t, err := historyBlockTimeF(height) 26 r.NoError(err) 27 return t 28 } 29 cases := []struct { 30 name string 31 height uint64 32 want time.Time 33 errMsg string 34 }{ 35 {"height is in the past", tipHeight - 1, historyWrapper(tipHeight - 1), ""}, 36 {"height is in the past I", tipHeight, historyWrapper(tipHeight), ""}, 37 {"height is in the future", tipHeight + 1, historyWrapper(tipHeight).Add(interval), ""}, 38 {"height is in the future I", tipHeight + 2, historyWrapper(tipHeight).Add(2 * interval), ""}, 39 {"height is not overflow", tipHeight + (1<<63-1)/uint64(interval), historyWrapper(tipHeight).Add((1<<63 - 1) / interval * interval), ""}, 40 {"height is overflow", tipHeight + (1<<63-1)/uint64(interval) + 1, time.Time{}, "height overflow"}, 41 } 42 43 for _, c := range cases { 44 t.Run(c.name, func(t *testing.T) { 45 got, err := btc.CalculateBlockTime(c.height) 46 if c.errMsg != "" { 47 r.ErrorContains(err, c.errMsg) 48 return 49 } 50 r.NoError(err) 51 r.Equal(c.want, got) 52 }) 53 } 54 }