-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsdk-test.js
More file actions
268 lines (223 loc) · 7.99 KB
/
sdk-test.js
File metadata and controls
268 lines (223 loc) · 7.99 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
#!/usr/bin/env node
/**
* Comprehensive SDK Test Suite for sBTC Express
* This runs against a local server at http://localhost:3001 by default.
* It will attempt to start the server automatically if not running.
*/
const { spawn } = require("child_process");
const axios = require("axios");
const BASE_URL = "http://localhost:3001";
const API_BASE = `${BASE_URL}/api/v1`;
// Pretty logging helpers
const colors = {
reset: "\x1b[0m",
bright: "\x1b[1m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
magenta: "\x1b[35m",
cyan: "\x1b[36m",
};
function log(msg, color = colors.reset) {
console.log(`${color}${msg}${colors.reset}`);
}
function logSection(title) {
log(`\n${"=".repeat(60)}`, colors.cyan);
log(title, colors.cyan);
log(`${"=".repeat(60)}`, colors.cyan);
}
let total = 0,
passed = 0,
failed = 0;
function t(name, cond, details = "") {
total++;
if (cond) {
passed++;
log(`✅ ${name}`, colors.green);
} else {
failed++;
log(`❌ ${name}`, colors.red);
if (details) log(` ${details}`, colors.yellow);
}
}
async function isServerUp() {
try {
const res = await axios.get(`${BASE_URL}/api/health`, { timeout: 1500 });
return res.status === 200;
} catch (_) {
return false;
}
}
async function ensureServerRunning() {
if (await isServerUp()) return null;
log("Starting server (not detected on port 3001)...", colors.yellow);
const child = spawn("node", ["dist/server.js"], {
cwd: __dirname,
stdio: ["ignore", "inherit", "inherit"],
env: { ...process.env, NODE_ENV: process.env.NODE_ENV || "development" },
});
// Wait until health passes or timeout ~10s
const start = Date.now();
while (Date.now() - start < 10000) {
if (await isServerUp()) return child;
await new Promise((r) => setTimeout(r, 500));
}
throw new Error("Server did not start within 10s");
}
async function run() {
log("🚀 SDK Tests starting", colors.bright);
const maybeServer = await ensureServerRunning();
// Load built SDK
const {
createSbtcExpress,
SbtcExpressError,
} = require("./dist/sdk/sbtc-express-sdk.js");
// Initialize SDK (API key can be any string format for demo; API endpoints that require keys use eitherAuth)
const client = createSbtcExpress(
"sk_test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
{ baseUrl: API_BASE }
);
try {
// AUTH
logSection("AUTH");
const email = `sdk_${Date.now()}@example.com`;
const password = "TestPassword123!";
const reg = await client.auth.register(email, password, "SDK Test Biz");
t(
"Register returns tokens + merchant",
!!(reg && reg.tokens && reg.merchant)
);
const login = await client.auth.login(email, password);
t(
"Login returns tokens + merchant",
!!(login && login.tokens && login.merchant)
);
const prof = await client.auth.profile();
t("Profile returns merchant email", prof && prof.email === email);
const refreshed = await client.auth.refresh();
t("Refresh returns new tokens", !!(refreshed && refreshed.access_token));
// SETTINGS
logSection("SETTINGS");
const acc = await client.settings.getAccount();
t("Get account settings", !!acc);
const updatedAcc = await client.settings.updateAccount({ timezone: "UTC" });
t("Update account settings", updatedAcc && updatedAcc.timezone === "UTC");
const sec = await client.settings.getSecurity();
t("Get security settings", !!sec);
const pay = await client.settings.getPayments();
t("Get payment settings", !!pay);
const noti = await client.settings.getNotifications();
t("Get notification settings", !!noti);
// Create API key via settings
const createdKey = await client.settings.createApiKey({
name: "SDK Test Key",
});
t(
"Create API key via settings",
!!(createdKey && createdKey.id && createdKey.key)
);
// Update API key
const updKey = await client.settings.updateApiKey(createdKey.id, {
description: "updated",
});
t("Update API key via settings", !!(updKey && updKey.message));
// Security logs
const logs = await client.settings.getSecurityLogs({ limit: 10 });
t("Get security logs", !!(logs && Array.isArray(logs.logs)));
// PAYMENTS
logSection("PAYMENTS");
const p = await client.payments.create({
amount: 12345,
description: "SDK test payment",
});
t("Create payment", !!(p && p.id && p.amount === 12345));
const got = await client.payments.retrieve(p.id);
t("Retrieve payment by id", got && got.id === p.id);
const list = await client.payments.list({ limit: 5 });
t("List payments", !!(list && Array.isArray(list.data)));
const stats = await client.payments.stats();
t("Payment stats", typeof stats.total_payments === "number");
// PAYMENT LINKS
logSection("PAYMENT LINKS");
const link = await client.paymentLinks.create({
name: "Test Link",
amount: 9999,
description: "SDK link",
});
t("Create payment link", !!(link && link.id));
const linkGot = await client.paymentLinks.retrieve(link.id);
t("Retrieve payment link", linkGot && linkGot.id === link.id);
const linkUpd = await client.paymentLinks.update(link.id, {
description: "updated",
});
t("Update payment link", linkUpd && linkUpd.description === "updated");
const linkList = await client.paymentLinks.list({ limit: 5 });
t("List payment links", !!(linkList && Array.isArray(linkList.data)));
// WEBHOOK ENDPOINTS
logSection("WEBHOOK ENDPOINTS");
const wh = await client.webhooks.endpoints.create({
url: "https://example.com/webhook",
enabled_events: ["payment.confirmed"],
description: "sdk test",
enabled: true,
});
t("Create webhook endpoint", !!(wh && wh.id && wh.secret));
const whList = await client.webhooks.endpoints.list({ limit: 10 });
t("List webhook endpoints", Array.isArray(whList));
const whTest = await client.webhooks.endpoints.test(wh.id);
t("Test webhook endpoint", typeof whTest.test_sent === "boolean");
const rolled = await client.webhooks.endpoints.rollSecret(wh.id);
t("Roll webhook secret", !!rolled.secret);
const deliveries = await client.webhooks.endpoints.deliveries(wh.id, {
limit: 5,
});
t("Webhook deliveries list", Array.isArray(deliveries));
// DASHBOARD
logSection("DASHBOARD");
const overview = await client.dashboard.overview();
t(
"Dashboard overview",
overview && typeof overview.total_payments === "number"
);
const recent = await client.dashboard.recentPayments(5);
t("Dashboard recent payments", Array.isArray(recent));
// AUTO REFRESH (force 401 by corrupting access token, keep refresh token)
logSection("AUTO REFRESH");
const tokens = client.getTokens();
client.setTokens({ ...tokens, access_token: "invalid-token" });
const accAfterRefresh = await client.settings.getAccount();
t("Auto refresh on 401 works", !!accAfterRefresh);
// CLEANUP: delete API key created via settings
const delRes = await client.settings.deleteApiKey(createdKey.id);
t("Delete API key via settings", !!(delRes && delRes.message));
// CLEANUP: delete webhook endpoint
const delWh = await client.webhooks.endpoints.delete(wh.id);
t("Delete webhook endpoint", !!(delWh && delWh.deleted));
} catch (err) {
if (err && err.name === "SbtcExpressError") {
t(
"Unhandled SbtcExpressError",
false,
`${err.type} ${err.code || ""} ${err.message}`
);
} else {
t("Unhandled error", false, err?.message || String(err));
}
} finally {
logSection("SDK TEST SUMMARY");
log(
`Total: ${total} Passed: ${passed} Failed: ${failed}`,
failed === 0 ? colors.green : colors.red
);
if (maybeServer) {
log("Stopping auto-started server...", colors.yellow);
maybeServer.kill("SIGINT");
}
process.exit(failed > 0 ? 1 : 0);
}
}
if (require.main === module) {
run();
}
module.exports = { run };