-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecaying_average_test.go
74 lines (58 loc) · 2.32 KB
/
decaying_average_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package lrc
import (
"math"
"testing"
"time"
"github.com/lightningnetwork/lnd/clock"
"github.com/stretchr/testify/require"
)
var testTime = time.Date(2024, time.January, 5, 0, 0, 0, 0, time.UTC)
func setupTest(period time.Duration) (*clock.TestClock, *decayingAverage) {
testClock := clock.NewTestClock(testTime)
return testClock, newDecayingAverage(testClock, period, nil)
}
// TestDecayingAverage tests basic operation of our decaying average
// calculations.
func TestDecayingAverage(t *testing.T) {
period := time.Hour * 10
testClock, decayingAverage := setupTest(period)
// Assert that we begin with a zero value and timestamp.
require.EqualValues(t, time.Time{}, decayingAverage.lastUpdate)
require.EqualValues(t, 0, decayingAverage.value)
// Once we access our value, assert that timestamp is updated.
require.EqualValues(t, 0, decayingAverage.getValue())
require.EqualValues(t, testTime, decayingAverage.lastUpdate)
// Add a value to the decaying average and assert that the average
// has the same value, because our mock clock's time is the same as
// the last update time of the average.
value := 10.0
decayingAverage.add(value)
require.EqualValues(t, value, decayingAverage.getValue())
// Advance our clock and assert that our value has been discounted by
// time.
testClock.SetTime(testTime.Add(time.Hour))
require.Less(t, decayingAverage.getValue(), value)
}
// TestDecayingAverageValues tests updating of decaying average values against
// independently calculated expected values.
func TestDecayingAverageValues(t *testing.T) {
period := time.Second * 100
testClock, decayingAverage := setupTest(period)
// Progress to non-zero time
decayingAverage.add(1000)
require.EqualValues(t, 1000, decayingAverage.getValue())
// Progress time a few times and assert we hit our (rounded) expected
// values.
testClock.SetTime(testTime.Add(time.Second * 25))
require.EqualValues(t, 707.11,
math.Round(decayingAverage.getValue()*100)/100)
testClock.SetTime(testTime.Add(time.Second * 28))
require.EqualValues(t, 678.30,
math.Round(decayingAverage.getValue()*100)/100)
decayingAverage.add(2300)
require.EqualValues(t, 2978.30,
math.Round(decayingAverage.getValue()*100)/100)
testClock.SetTime(testTime.Add(time.Second * 78))
require.EqualValues(t, 1489.15,
math.Round(decayingAverage.getValue()*100)/100)
}