forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprices.test.js
More file actions
284 lines (235 loc) · 8.73 KB
/
Copy pathprices.test.js
File metadata and controls
284 lines (235 loc) · 8.73 KB
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
284
'use strict';
// --- Mocks (must precede all imports) ---
jest.mock('../src/services/cache', () => ({
get: jest.fn(),
set: jest.fn(),
del: jest.fn(),
disconnect: jest.fn(),
isConnected: jest.fn(() => false),
}));
const mockGetPrice = jest.fn();
const mockFetchFreshPrice = jest.fn();
jest.mock('../src/services/priceOracle', () => ({
getPrice: mockGetPrice,
fetchFreshPrice: mockFetchFreshPrice,
refreshAllCachedPrices: jest.fn(),
}));
jest.mock('../src/logger', () => ({
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
}));
jest.mock('../src/services/apiKeys', () => ({
validateApiKey: jest.fn(),
}));
// --- Imports ---
process.env.ADMIN_API_KEY = 'b'.repeat(64);
const express = require('express');
const request = require('supertest');
const pricesRouter = require('../src/routes/prices');
const logger = require('../src/logger');
const { errorHandler } = require('../src/middleware/errorHandler');
const apiKeys = require('../src/services/apiKeys');
function buildApp() {
const app = express();
app.use(express.json());
app.use('/api/v1', pricesRouter);
app.use(errorHandler);
return app;
}
function priceResponse(overrides = {}) {
return {
asset_code: 'USDC',
issuer: 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
price_usd: 1.01,
source: 'coingecko',
fetched_at: '2026-06-25T00:00:00.000Z',
is_stale: false,
stale_warning: null,
sources_attempted: ['coingecko'],
redis_unavailable: false,
...overrides,
};
}
describe('price routes', () => {
let app;
beforeEach(() => {
app = buildApp();
mockGetPrice.mockReset();
mockFetchFreshPrice.mockReset();
apiKeys.validateApiKey.mockReset();
logger.error.mockClear();
});
describe('GET /api/v1/prices/:asset_code', () => {
test('returns the full price response shape', async () => {
mockGetPrice.mockResolvedValueOnce(priceResponse());
const res = await request(app)
.get('/api/v1/prices/usdc')
.query({ issuer: 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' });
expect(res.status).toBe(200);
expect(mockGetPrice).toHaveBeenCalledWith(
'USDC',
'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
);
expect(res.body).toEqual({
asset_code: 'USDC',
issuer: 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
price_usd: 1.01,
source: 'coingecko',
fetched_at: '2026-06-25T00:00:00.000Z',
is_stale: false,
stale_warning: null,
sources_attempted: ['coingecko'],
redis_unavailable: false,
});
});
test('preserves stale warnings from the oracle', async () => {
mockGetPrice.mockResolvedValueOnce(
priceResponse({
is_stale: true,
stale_warning: 'Price is 45.0 minutes old (threshold: 30 min)',
})
);
const res = await request(app).get('/api/v1/prices/USDC');
expect(res.status).toBe(200);
expect(res.body.is_stale).toBe(true);
expect(res.body.stale_warning).toBe('Price is 45.0 minutes old (threshold: 30 min)');
});
test('handles native XLM without an issuer', async () => {
mockGetPrice.mockResolvedValueOnce(
priceResponse({
asset_code: 'XLM',
issuer: null,
price_usd: 0.12,
source: 'stellar_dex',
})
);
const res = await request(app).get('/api/v1/prices/xlm');
expect(res.status).toBe(200);
expect(mockGetPrice).toHaveBeenCalledWith('XLM', null);
expect(res.body.asset_code).toBe('XLM');
expect(res.body.issuer).toBeNull();
});
test('returns 404 with a structured error when no source has data', async () => {
mockGetPrice.mockResolvedValueOnce(
priceResponse({
price_usd: null,
source: 'unavailable',
is_stale: true,
stale_warning: 'No price data available from any source',
})
);
const res = await request(app).get('/api/v1/prices/UNKNOWN');
expect(res.status).toBe(404);
expect(res.body.error).toMatchObject({
code: 'NOT_FOUND',
message: expect.stringContaining('UNKNOWN'),
});
});
test('rejects invalid asset codes before oracle lookup', async () => {
const res = await request(app).get('/api/v1/prices/TOO-LONG-ASSET');
expect(res.status).toBe(400);
expect(res.body.error).toMatchObject({
code: 'VALIDATION_ERROR',
message: 'Validation failed',
});
expect(res.body.error.details.fields.asset_code).toEqual(
expect.arrayContaining(['Asset code must be alphanumeric'])
);
expect(mockGetPrice).not.toHaveBeenCalled();
});
test('rejects malformed issuers before oracle lookup', async () => {
const res = await request(app)
.get('/api/v1/prices/USDC')
.query({ issuer: 'not-a-stellar-address' });
expect(res.status).toBe(400);
expect(res.body.error).toMatchObject({
code: 'VALIDATION_ERROR',
message: 'Validation failed',
});
expect(res.body.error.details.fields.issuer).toEqual(
expect.arrayContaining(['Must be a valid Stellar public key'])
);
expect(mockGetPrice).not.toHaveBeenCalled();
});
test('hides stack traces on unhandled oracle errors', async () => {
mockGetPrice.mockRejectedValueOnce(new Error('redis exploded with stack details'));
const res = await request(app).get('/api/v1/prices/XLM');
expect(res.status).toBe(500);
expect(res.body.error).toMatchObject({ code: 'INTERNAL_ERROR' });
expect(JSON.stringify(res.body)).not.toContain('redis exploded');
});
test('Redis unavailable — 200 with redis_unavailable: true (graceful degradation)', async () => {
mockGetPrice.mockResolvedValueOnce(priceResponse({ redis_unavailable: true }));
const res = await request(app).get('/api/v1/prices/USDC');
expect(res.status).toBe(200);
expect(res.body.redis_unavailable).toBe(true);
expect(res.body.price_usd).not.toBeNull();
});
});
describe('GET /api/v1/prices/:asset_code/refresh', () => {
test('no Authorization header — 401', async () => {
const res = await request(app).get('/api/v1/prices/XLM/refresh');
expect(res.status).toBe(401);
expect(res.body.error).toMatchObject({
code: 'UNAUTHORIZED',
message: 'Missing or invalid API key',
});
});
test('invalid API key — 401', async () => {
apiKeys.validateApiKey.mockResolvedValue(null);
const res = await request(app)
.get('/api/v1/prices/XLM/refresh')
.set('Authorization', 'Bearer bad-key');
expect(res.status).toBe(401);
expect(res.body.error).toMatchObject({
code: 'UNAUTHORIZED',
message: 'Missing or invalid API key',
});
});
test('valid API key — 200 with full response shape', async () => {
apiKeys.validateApiKey.mockResolvedValue({ scopes: [] });
mockFetchFreshPrice.mockResolvedValueOnce(priceResponse({ asset_code: 'XLM' }));
const res = await request(app)
.get('/api/v1/prices/XLM/refresh')
.set('Authorization', 'Bearer valid-key');
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
asset_code: 'XLM',
price_usd: expect.any(Number),
});
});
test('valid API key + oracle throws — 500, no internal details leaked', async () => {
apiKeys.validateApiKey.mockResolvedValue({ scopes: [] });
mockFetchFreshPrice.mockRejectedValueOnce(new Error('External source failed'));
const res = await request(app)
.get('/api/v1/prices/XLM/refresh')
.set('Authorization', 'Bearer valid-key');
expect(res.status).toBe(500);
expect(res.body.error).toMatchObject({ code: 'INTERNAL_ERROR' });
expect(res.body).not.toHaveProperty('stack');
expect(JSON.stringify(res.body)).not.toContain('External source failed');
});
test('validates params and calls fresh oracle lookup', async () => {
apiKeys.validateApiKey.mockResolvedValue({ scopes: [] });
mockFetchFreshPrice.mockResolvedValueOnce(
priceResponse({
asset_code: 'USDC',
source: 'stellar_dex',
sources_attempted: ['stellar_dex'],
})
);
const res = await request(app)
.get('/api/v1/prices/usdc/refresh')
.set('Authorization', `Bearer ${process.env.ADMIN_API_KEY}`)
.query({ issuer: 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' });
expect(res.status).toBe(200);
expect(mockFetchFreshPrice).toHaveBeenCalledWith(
'USDC',
'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
);
expect(res.body.source).toBe('stellar_dex');
});
});
});