summaryrefslogtreecommitdiffstats
path: root/exchange_test.go
blob: 89e73935ceb93addf107741333d9ecc163213ad3 (plain) (blame)
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
package exchange

import (
	"bytes"
	"encoding/json"
	"flag"
	"log"
	"net/url"
	"os"
	"testing"
	"time"

	"github.com/google/go-querystring/query"
	"github.com/shopspring/decimal"
	"github.com/stretchr/testify/require"
)

const (
	keyFile = ".key"

	// $1 CAD ≅ 70¢ USD (±20%)
	// This is the rate at the time of writing. It may need to be
	// changed later if something drastic occurs in either country.
	usdPerCad   = 0.70
	rateEpsilon = 0.20

	floatEpsilon = 1e-7
)

var apiKey string

func TestMain(m *testing.M) {
	flag.BoolVar(&debug, "debug", false, "log debug info to stderr")
	flag.Parse()

	// Load API key
	buf, err := os.ReadFile(keyFile)
	if err != nil {
		log.Fatalf("error loading API key: %v\n", err)
	}
	apiKey = string(bytes.TrimSpace(buf))

	m.Run()
}

func TestUnmarshalApiError(t *testing.T) {
	data := `
{
  "status": {
    "timestamp": "2018-06-02T22:51:28.209Z",
    "error_code": 1002,
    "error_message": "API key missing.",
    "elapsed": 10,
    "credit_count": 0
  }
}
`
	want := apiError{
		status{"API key missing."},
	}
	var info apiError
	err := json.Unmarshal([]byte(data), &info)
	require.NoError(t, err)
	require.Equal(t, want, info)
}

func TestPriceConversionQuery(t *testing.T) {
	q := priceConversionQuery{123, "USD", "CAD"}
	want := url.Values{
		"amount":  {"123"},
		"symbol":  {"USD"},
		"convert": {"CAD"},
	}
	vals, err := query.Values(q)
	require.NoError(t, err)
	require.Equal(t, want, vals)
}

func TestUnmarshalPriceConversionResponse(t *testing.T) {
	data := `
{
  "data": [
    {
      "id": 32134,
      "symbol": "CAD",
      "name": "Caduceus Protocol (new)",
      "amount": 1,
      "quote": {
        "USD": {
          "price": 0.00026617250802605987,
          "last_updated": "2026-07-09T17:31:05.000Z"
        }
      },
      "last_updated": "2026-07-09T17:30:00.000Z"
    },
    {
      "id": 2784,
      "symbol": "CAD",
      "name": "Canadian Dollar",
      "amount": 1,
      "quote": {
        "USD": {
          "price": 0.7060965078585,
          "last_updated": "2026-07-09T17:31:05.000Z"
        }
      },
      "last_updated": "2026-07-09T17:31:05.000Z"
    }
  ],
  "status": {
    "timestamp": "2026-07-09T17:32:29.378Z",
    "error_code": 0,
    "error_message": null,
    "elapsed": 25,
    "credit_count": 1,
    "notice": null
  }
}

`
	want := response[[]priceConversion]{
		Data: []priceConversion{
			{
				32134,
				map[string]price{
					"USD": {decimal.RequireFromString("0.00026617250802605987")},
				},
			}, {
				2784,
				map[string]price{
					"USD": {decimal.RequireFromString("0.7060965078585")},
				},
			},
		},
	}
	var conv response[[]priceConversion]
	err := json.Unmarshal([]byte(data), &conv)
	require.NoError(t, err)
	require.Equal(t, want, conv)
}

func TestRateCache(t *testing.T) {
	clnt := NewClient(apiKey)
	defer clnt.Close()
	from, to := "CAD", "USD"

	// Repeat to exercise cache
	for i := 0; i < 5; i++ {
		rate, err := clnt.Rate(from, to)
		require.NoError(t, err)
		t.Log(rate)
		require.InEpsilon(t, usdPerCad, rate.InexactFloat64(), rateEpsilon)
	}
}

func TestRateCacheExpire(t *testing.T) {
	ttl := time.Millisecond
	clnt := NewClient(apiKey, WithTTL(ttl))
	defer clnt.Close()
	from, to := "CAD", "USD"
	check := func() {
		rate, err := clnt.Rate(from, to)
		require.NoError(t, err)
		t.Log(rate)
		require.InEpsilon(t, usdPerCad, rate.InexactFloat64(), rateEpsilon)
	}
	check()             // retrieve
	time.Sleep(2 * ttl) // expire
	check()             // refresh
}

func TestRateFiatFiat(t *testing.T) {
	testRate(t, "AUD", "CAD")
}

func TestRateFiatCrypto(t *testing.T) {
	testRate(t, "CAD", "XMR")
}

func TestRateCryptoCrypto(t *testing.T) {
	testRate(t, "XMR", "BTC")
}

func testRate(t *testing.T, from, to string) {
	c := NewClient(apiKey)
	defer c.Close()

	aPerB := rate(t, c, from, to)
	bPerA := rate(t, c, to, from)
	require.NotZero(t, aPerB)
	require.NotZero(t, bPerA)
	require.InEpsilon(t, bPerA.InexactFloat64(), decimal.NewFromInt(1).Div(aPerB).InexactFloat64(), floatEpsilon)
}

func rate(t *testing.T, c *Client, from, to string) decimal.Decimal {
	t.Helper()
	rate, err := c.Rate(from, to)
	require.NoError(t, err)
	t.Logf("1 %s = %v %s\n", from, rate, to)
	return rate
}