github.com/MetalBlockchain/metalgo@v1.11.9/utils/math/continuous_averager_test.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package math 5 6 import ( 7 "testing" 8 "time" 9 10 "github.com/stretchr/testify/require" 11 ) 12 13 func TestAverager(t *testing.T) { 14 require := require.New(t) 15 16 halflife := time.Second 17 currentTime := time.Now() 18 19 a := NewSyncAverager(NewAverager(0, halflife, currentTime)) 20 require.Zero(a.Read()) 21 22 currentTime = currentTime.Add(halflife) 23 a.Observe(1, currentTime) 24 require.Equal(1.0/1.5, a.Read()) 25 } 26 27 func TestAveragerTimeTravel(t *testing.T) { 28 require := require.New(t) 29 30 halflife := time.Second 31 currentTime := time.Now() 32 33 a := NewSyncAverager(NewAverager(1, halflife, currentTime)) 34 require.Equal(float64(1), a.Read()) 35 36 currentTime = currentTime.Add(-halflife) 37 a.Observe(0, currentTime) 38 require.Equal(1.0/1.5, a.Read()) 39 } 40 41 func TestUninitializedAverager(t *testing.T) { 42 require := require.New(t) 43 44 halfLife := time.Second 45 currentTime := time.Now() 46 47 firstObservation := float64(10) 48 49 a := NewUninitializedAverager(halfLife) 50 require.Zero(a.Read()) 51 52 a.Observe(firstObservation, currentTime) 53 require.Equal(firstObservation, a.Read()) 54 }