forked from syscoin/blockbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiat_rates_test.go
176 lines (156 loc) · 4.84 KB
/
fiat_rates_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
//go:build unittest
package fiat
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"github.com/golang/glog"
"github.com/martinboehm/btcutil/chaincfg"
"github.com/syscoin/blockbook/bchain"
"github.com/syscoin/blockbook/bchain/coins/btc"
"github.com/syscoin/blockbook/common"
"github.com/syscoin/blockbook/db"
)
func TestMain(m *testing.M) {
// set the current directory to blockbook root so that ./static/ works
if err := os.Chdir(".."); err != nil {
glog.Fatal("Chdir error:", err)
}
c := m.Run()
chaincfg.ResetParams()
os.Exit(c)
}
func setupRocksDB(t *testing.T, parser bchain.BlockChainParser) (*db.RocksDB, *common.InternalState, string) {
tmp, err := ioutil.TempDir("", "testdb")
if err != nil {
t.Fatal(err)
}
d, err := db.NewRocksDB(tmp, 100000, -1, parser, nil)
if err != nil {
t.Fatal(err)
}
is, err := d.LoadInternalState("fakecoin")
if err != nil {
t.Fatal(err)
}
d.SetInternalState(is)
return d, is, tmp
}
func closeAndDestroyRocksDB(t *testing.T, db *db.RocksDB, dbpath string) {
// destroy db
if err := db.Close(); err != nil {
t.Fatal(err)
}
os.RemoveAll(dbpath)
}
type testBitcoinParser struct {
*btc.BitcoinParser
}
func bitcoinTestnetParser() *btc.BitcoinParser {
return btc.NewBitcoinParser(
btc.GetChainParams("test"),
&btc.Configuration{BlockAddressesToKeep: 1})
}
// getFiatRatesMockData reads a stub JSON response from a file and returns its content as string
func getFiatRatesMockData(dateParam string) (string, error) {
var filename string
if dateParam == "current" {
filename = "fiat/mock_data/current.json"
} else {
filename = "fiat/mock_data/" + dateParam + ".json"
}
mockFile, err := os.Open(filename)
if err != nil {
glog.Errorf("Cannot open file %v", filename)
return "", err
}
b, err := ioutil.ReadAll(mockFile)
if err != nil {
glog.Errorf("Cannot read file %v", filename)
return "", err
}
return string(b), nil
}
func TestFiatRates(t *testing.T) {
d, _, tmp := setupRocksDB(t, &testBitcoinParser{
BitcoinParser: bitcoinTestnetParser(),
})
defer closeAndDestroyRocksDB(t, d, tmp)
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var err error
var mockData string
if r.URL.Path == "/ping" {
w.WriteHeader(200)
} else if r.URL.Path == "/coins/bitcoin/history" {
date := r.URL.Query()["date"][0]
mockData, err = getFiatRatesMockData(date) // get stub rates by date
} else if r.URL.Path == "/coins/bitcoin" {
mockData, err = getFiatRatesMockData("current") // get "latest" stub rates
} else {
t.Errorf("Unknown URL path: %v", r.URL.Path)
}
if err != nil {
t.Errorf("Error loading stub data: %v", err)
}
fmt.Fprintln(w, mockData)
}))
defer mockServer.Close()
// real CoinGecko API
//configJSON := `{"fiat_rates": "coingecko", "fiat_rates_params": "{\"url\": \"https://api.coingecko.com/api/v3\", \"coin\": \"bitcoin\", \"periodSeconds\": 60}"}`
// mocked CoinGecko API
configJSON := `{"fiat_rates": "coingecko", "fiat_rates_params": "{\"url\": \"` + mockServer.URL + `\", \"coin\": \"bitcoin\", \"periodSeconds\": 60}"}`
type fiatRatesConfig struct {
FiatRates string `json:"fiat_rates"`
FiatRatesParams string `json:"fiat_rates_params"`
}
var config fiatRatesConfig
err := json.Unmarshal([]byte(configJSON), &config)
if err != nil {
t.Errorf("Error parsing config: %v", err)
}
if config.FiatRates == "" || config.FiatRatesParams == "" {
t.Errorf("Error parsing FiatRates config - empty parameter")
return
}
testStartTime := time.Date(2019, 11, 22, 16, 0, 0, 0, time.UTC)
fiatRates, err := NewFiatRatesDownloader(d, config.FiatRates, config.FiatRatesParams, &testStartTime, nil)
if err != nil {
t.Errorf("FiatRates init error: %v\n", err)
}
if config.FiatRates == "coingecko" {
timestamp, err := fiatRates.findEarliestMarketData()
if err != nil {
t.Errorf("Error looking up earliest market data: %v", err)
return
}
earliestTimestamp, _ := time.Parse(db.FiatRatesTimeFormat, "20130429000000")
if *timestamp != earliestTimestamp {
t.Errorf("Incorrect earliest available timestamp found. Wanted: %v, got: %v", earliestTimestamp, timestamp)
return
}
// After verifying that findEarliestMarketData works correctly,
// set the earliest available timestamp to 2 days ago for easier testing
*timestamp = fiatRates.startTime.Add(time.Duration(-24*2) * time.Hour)
err = fiatRates.syncHistorical(timestamp)
if err != nil {
t.Errorf("RatesDownloader syncHistorical error: %v", err)
return
}
ticker, err := fiatRates.downloader.getTicker(fiatRates.startTime)
if err != nil {
// Do not exit on GET error, log it, wait and try again
glog.Errorf("Sync GetData error: %v", err)
return
}
err = fiatRates.db.FiatRatesStoreTicker(ticker)
if err != nil {
glog.Errorf("Sync StoreTicker error %v", err)
return
}
}
}