forked from BitBoxSwiss/bitbox-wallet-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhistory_test.go
283 lines (256 loc) · 9.98 KB
/
history_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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package rates
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strconv"
"testing"
"time"
"github.com/BitBoxSwiss/bitbox-wallet-app/util/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPriceAt(t *testing.T) {
updater := NewRateUpdater(nil, "/dev/null") // don't need to make HTTP requests or load DB
defer updater.Stop()
updater.history = map[string][]exchangeRate{
"btcUSD": {
{value: 2, timestamp: time.Date(2020, 9, 1, 0, 0, 0, 0, time.UTC)},
{value: 3, timestamp: time.Date(2020, 9, 2, 0, 0, 0, 0, time.UTC)},
{value: 5, timestamp: time.Date(2020, 9, 3, 0, 0, 0, 0, time.UTC)},
{value: 8, timestamp: time.Date(2020, 9, 4, 0, 0, 0, 0, time.UTC)},
},
}
tt := []struct {
wantValue float64
at time.Time
}{
{0, time.Date(2020, 8, 31, 0, 0, 0, 0, time.UTC)}, // before first point
{2, time.Date(2020, 9, 1, 0, 0, 0, 0, time.UTC)}, // exactly at first point
{0, time.Date(2020, 9, 10, 0, 0, 0, 0, time.UTC)}, // no data; way in the future
{5, time.Date(2020, 9, 3, 0, 0, 0, 0, time.UTC)}, // exact match
{8, time.Date(2020, 9, 4, 0, 0, 0, 0, time.UTC)}, // exact match
// The following are all interpolated.
{2.5, time.Date(2020, 9, 1, 12, 0, 0, 0, time.UTC)},
{4, time.Date(2020, 9, 2, 12, 0, 0, 0, time.UTC)},
{6.5, time.Date(2020, 9, 3, 12, 0, 0, 0, time.UTC)},
{7.25, time.Date(2020, 9, 3, 18, 0, 0, 0, time.UTC)},
}
for _, test := range tt {
assert.Equal(t,
test.wantValue,
updater.HistoricalPriceAt("btc", "USD", test.at), "at = %s", test.at)
}
}
func TestUpdateHistory(t *testing.T) {
const wantStartUnix = 1598918462 // 2020-09-01 00:01:02
const wantEndUnix = 1599004862 // 2020-09-02 00:01:02
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "GET", r.Method, "request method")
assert.Equal(t, "/coins/bitcoin/market_chart/range", r.URL.Path, "URL path")
assert.Equal(t, strconv.Itoa(wantStartUnix), r.URL.Query().Get("from"), "from query arg")
assert.Equal(t, strconv.Itoa(wantEndUnix), r.URL.Query().Get("to"), "to query arg")
assert.Equal(t, "usd", r.URL.Query().Get("vs_currency"), "vs_currency query arg")
// Composed after a real response like this one:
// https://api.coingecko.com/api/v3/coins/bitcoin/market_chart/range?vs_currency=usd&from=1598918400&to=1600128000
// - 2020-09-01 00:05:00 UTC
// - 2020-09-01 01:08:21 UTC
fmt.Fprintln(w, `{
"prices": [
[
1598918700000,
10000.0
],
[
1598922501000,
10001.0
]
]
}`)
}))
defer ts.Close()
dbdir := test.TstTempDir("TestUpdateHistory")
defer os.RemoveAll(dbdir)
updater := NewRateUpdater(http.DefaultClient, dbdir)
updater.coingeckoURL = ts.URL
updater.history = map[string][]exchangeRate{
"btcUSD": {
{value: 1.0, timestamp: time.Unix(1598832062, 0)}, // 2020-08-31 00:01:02
{value: 2.0, timestamp: time.Unix(1599091262, 0)}, // 2020-09-03 00:01:02
},
}
g := fixedTimeRange(time.Unix(wantStartUnix, 0), time.Unix(wantEndUnix, 0))
n, err := updater.updateHistory(context.Background(), "btc", "USD", g)
require.NoError(t, err, "updater.updateHistory err")
assert.Equal(t, 2, n, "updater.updateHistory n")
wantHistory := map[string][]exchangeRate{
"btcUSD": {
{value: 1.0, timestamp: time.Unix(1598832062, 0)}, // preexisting point
{value: 10000.0, timestamp: time.Unix(1598918700, 0)},
{value: 10001.0, timestamp: time.Unix(1598922501, 0)},
{value: 2.0, timestamp: time.Unix(1599091262, 0)}, // preexisting point
},
}
assert.Equal(t, wantHistory, updater.history, "updater.history")
updater.Stop() // closes dbdir so updater2 can load it
updater2 := NewRateUpdater(http.DefaultClient, dbdir)
defer updater2.Stop()
updater2.coingeckoURL = "unused"
updater2.loadHistoryBucket("btcUSD")
assert.Equal(t, wantHistory, updater.history, "updater2.history")
}
func TestFetchGeckoMarketRangeInvalidCoinFiat(t *testing.T) {
tt := []struct{ coin, fiat string }{
{"BTC", "invalid"},
{"BTC", ""},
{"unsupported", "USD"},
{"", "USD"},
}
for _, test := range tt {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
var updater RateUpdater
g := fixedTimeRange(time.Now().Add(-time.Hour), time.Now())
_, err := updater.fetchGeckoMarketRange(ctx, test.coin, test.fiat, g)
require.Error(t, err, "fetchGeckoMarketRange(%q, %q) returned nil error", test.coin, test.fiat)
cancel()
}
}
func TestHistoryEarliestLatest(t *testing.T) {
updater := NewRateUpdater(nil, "/dev/null")
defer updater.Stop()
updater.history = map[string][]exchangeRate{
"btcUSD": {
{value: 1, timestamp: time.Unix(1598832062, 0)}, // 2020-08-31 00:01:02
{value: 2, timestamp: time.Unix(1598918700, 0)},
{value: 3, timestamp: time.Unix(1598922501, 0)},
{value: 4, timestamp: time.Unix(1599091262, 0)}, // 2020-09-03 00:01:02
},
"ltcUSD": {
{value: 4, timestamp: time.Date(2020, 8, 02, 23, 0, 0, 0, time.UTC)},
{value: 4, timestamp: time.Date(2020, 9, 02, 23, 0, 0, 0, time.UTC)},
},
}
earliest := updater.HistoryEarliestTimestamp("btc", "USD")
assert.Equal(t, updater.history["btcUSD"][0].timestamp, earliest, "earliest")
latest := updater.HistoryLatestTimestamp("btc", "USD")
assert.Equal(t, updater.history["btcUSD"][3].timestamp, latest, "latest")
assert.Zero(t, updater.HistoryEarliestTimestamp("foo", "bar"), "zero earliest")
assert.Zero(t, updater.HistoryLatestTimestamp("foo", "bar"), "zero latest")
assert.Equal(t,
updater.history["ltcUSD"][1].timestamp,
updater.HistoryLatestTimestampFiat([]string{"btc", "ltc"}, "USD"))
assert.Zero(t, updater.HistoryLatestTimestampFiat([]string{"btc", "foo"}, "USD"))
assert.Zero(t, updater.HistoryLatestTimestampFiat([]string{"foo", "btc"}, "USD"))
}
// TestLoadDumpBucketUnusableDB ensures no panic when the RateUpdater.historyDB is unusable.
func TestLoadDumpBucketUnusableDB(t *testing.T) {
updater := NewRateUpdater(nil, "/dev/null")
defer updater.Stop()
_, err1 := updater.loadHistoryBucket("foo")
require.Error(t, err1, "loadHistoryBucket")
err2 := updater.dumpHistoryBucket("bar", nil)
require.Error(t, err2, "dumpHistoryBucket")
}
func TestDumpLoadHistoryBucket(t *testing.T) {
wantRates := []exchangeRate{
{value: 1, timestamp: time.Unix(1598832062, 0)},
{value: 2, timestamp: time.Unix(1598918700, 0)},
{value: 3, timestamp: time.Unix(1598922501, 0)},
{value: 4, timestamp: time.Unix(1599091262, 0)},
}
dbdir := test.TstTempDir("TestLoadDumpHistoryBucket")
defer os.RemoveAll(dbdir)
updater1 := NewRateUpdater(nil, dbdir)
require.NoError(t, updater1.dumpHistoryBucket("btcUSD", wantRates), "dumpHistoryBucket")
updater1.Stop() // close dbdir so updater2 can load
updater2 := NewRateUpdater(nil, dbdir)
defer updater2.Stop()
rates, err := updater2.loadHistoryBucket("btcUSD")
require.NoError(t, err, "updater2.loadHistoryBucket")
assert.Len(t, rates, 4, "len(rates)")
}
func TestReconfigureHistoryLoadsFromDB(t *testing.T) {
sampleRates := []exchangeRate{
{value: 1, timestamp: time.Unix(1598832062, 0)},
{value: 2, timestamp: time.Unix(1598918700, 0)},
{value: 3, timestamp: time.Unix(1598922501, 0)},
{value: 4, timestamp: time.Unix(1599091262, 0)},
}
dbdir := test.TstTempDir("TestReconfigureHistoryLoadsFromDB")
defer os.RemoveAll(dbdir)
updater1 := NewRateUpdater(nil, dbdir)
require.NoError(t, updater1.dumpHistoryBucket("btcUSD", sampleRates), "dumpHistoryBucket")
updater1.Stop() // close dbdir so updater2 can load
updater2 := NewRateUpdater(http.DefaultClient, dbdir)
updater2.coingeckoURL = "unused" // avoid hitting real API
defer updater2.Stop()
updater2.ReconfigureHistory([]string{"btc"}, []string{"USD"})
// Loading from bbolt DB may result in unsorted slice.
// To test this manually, comment out sortRatesByTimestamp in
// RateUpdater.loadHistoryBucket and add the following here:
// assert.Equal(t, nil, updater2.history["btcUSD"])
for _, rate := range sampleRates {
v := updater2.HistoricalPriceAt("btc", "USD", rate.timestamp)
assert.Equal(t, rate.value, v, "PriceAt(btc, USD, %d)", rate.timestamp.Unix())
}
}
func BenchmarkDumpHistoryBucket(b *testing.B) {
var rates []exchangeRate
for i := 0; i < 5000; i++ {
rates = append(rates, exchangeRate{
value: float64(i),
timestamp: time.Unix(int64(i), 0),
})
}
updater := NewRateUpdater(nil, test.TstTempDir("BenchmarkDumpHistoryBucket"))
defer updater.Stop()
b.ResetTimer()
for i := 0; i < b.N; i++ {
err := updater.dumpHistoryBucket("btcUSD", rates)
require.NoError(b, err, "updater.dumpHistoryBucket")
}
}
func BenchmarkLoadHistoryBucket(b *testing.B) {
var rates []exchangeRate
for i := 0; i < 5000; i++ {
rates = append(rates, exchangeRate{
value: float64(i),
timestamp: time.Unix(int64(i), 0),
})
}
dbdir := test.TstTempDir("BenchmarkLoadHistoryBucket")
updater := NewRateUpdater(nil, dbdir)
updater.dumpHistoryBucket("btcUSD", rates)
updater.Stop()
updater2 := NewRateUpdater(nil, dbdir)
defer updater2.Stop()
b.ResetTimer()
for i := 0; i < b.N; i++ {
rates, err := updater2.loadHistoryBucket("btcUSD")
require.NoError(b, err, "updater.loadHistoryBucket")
require.Len(b, rates, 5000, "len(rates)")
}
}
func TestHistoryLatestTimestampCoin(t *testing.T) {
updater := NewRateUpdater(nil, "/dev/null") // don't need to make HTTP requests or load DB
defer updater.Stop()
updater.history = map[string][]exchangeRate{
"btcUSD": {
{value: 2, timestamp: time.Date(2020, 9, 1, 0, 0, 0, 0, time.UTC)},
{value: 3, timestamp: time.Date(2020, 9, 2, 0, 0, 0, 0, time.UTC)},
{value: 5, timestamp: time.Date(2020, 9, 3, 0, 0, 0, 0, time.UTC)},
{value: 8, timestamp: time.Date(2020, 9, 4, 0, 0, 0, 0, time.UTC)},
},
"btcEUR": {
{value: 2, timestamp: time.Date(2020, 9, 1, 0, 0, 0, 0, time.UTC)},
{value: 3, timestamp: time.Date(2020, 9, 2, 0, 0, 0, 0, time.UTC)},
{value: 5, timestamp: time.Date(2020, 9, 3, 0, 0, 0, 0, time.UTC)},
},
}
assert.Equal(t, time.Time{}, updater.HistoryLatestTimestampCoin("eth"))
assert.Equal(t,
time.Date(2020, 9, 3, 0, 0, 0, 0, time.UTC),
updater.HistoryLatestTimestampCoin("btc"))
}