forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.test.js
More file actions
274 lines (234 loc) · 9.21 KB
/
Copy pathapp.test.js
File metadata and controls
274 lines (234 loc) · 9.21 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
import request from "supertest";
import mongoose from "mongoose";
import { MongoMemoryServer } from "mongodb-memory-server";
import app from "../app.js";
import {
calculateFeeSplit,
buildSep7Uri,
USDC_ISSUER,
} from "../src/services/stellar/stellarService.js";
import {
paymentsInitialized,
paymentsSubmitted,
paymentsConfirmed,
paymentsFailed,
} from "../src/config/metrics.js";
let mongoServer;
beforeAll(async () => {
if (process.env.MONGO_URI && !process.env.MONGO_URI.includes("localhost")) {
try {
await mongoose.connect(process.env.MONGO_URI);
return;
} catch (_err) {
// Fallback to MongoMemoryServer
}
}
mongoServer = await MongoMemoryServer.create();
await mongoose.connect(mongoServer.getUri());
}, 30000);
afterAll(async () => {
await mongoose.disconnect();
if (mongoServer) {
await mongoServer.stop();
}
});
// Read a labeled counter value via prom-client's public API (internals like
// counter.hashMap are not part of the v15 contract).
const counterValue = async (counter, labels) => {
const { values } = await counter.get();
const match = values.find(
(v) => JSON.stringify(v.labels) === JSON.stringify(labels)
);
return match ? match.value : 0;
};
describe("DeenBridge API", () => {
it("should respond to GET / with welcome message", async () => {
const res = await request(app).get("/");
expect(res.statusCode).toBe(200);
expect(res.text).toContain("Welcome to DeenBridge API");
});
it("should respond to GET /health", async () => {
const res = await request(app).get("/health");
expect(res.statusCode).toBe(200);
expect(res.body).toHaveProperty("success", true);
});
it("should respond to GET /api/courses", async () => {
const res = await request(app).get("/api/courses");
expect(res.statusCode).toBe(200);
expect(res.body).toHaveProperty("success");
});
it("should respond to GET /api/spaces", async () => {
const res = await request(app).get("/api/spaces");
expect(res.statusCode).toBe(200);
expect(res.body).toHaveProperty("success");
});
});
describe("Request ID propagation", () => {
it("should return X-Request-Id header on every response", async () => {
const res = await request(app).get("/");
expect(res.headers["x-request-id"]).toBeDefined();
});
it("should honor incoming X-Request-Id header", async () => {
const customId = "my-test-request-id-123";
const res = await request(app)
.get("/health")
.set("X-Request-Id", customId);
expect(res.headers["x-request-id"]).toBe(customId);
});
});
describe("Metrics endpoint", () => {
it("should return Prometheus text format when no token is configured", async () => {
const tokenBefore = process.env.METRICS_TOKEN;
delete process.env.METRICS_TOKEN;
const res = await request(app).get("/metrics");
expect(res.statusCode).toBe(200);
expect(res.headers["content-type"]).toMatch(/^text\/plain/);
expect(res.text).toContain("http_request_duration_seconds");
expect(res.text).toContain("payments_initialized_total");
expect(res.text).toContain("payments_submitted_total");
expect(res.text).toContain("payments_confirmed_total");
expect(res.text).toContain("payments_failed_total");
expect(res.text).toContain("horizon_request_duration_seconds");
if (tokenBefore !== undefined) {
process.env.METRICS_TOKEN = tokenBefore;
}
});
it("should require Bearer token when METRICS_TOKEN is set", async () => {
process.env.METRICS_TOKEN = "secret-token-456";
const resNoAuth = await request(app).get("/metrics");
expect(resNoAuth.statusCode).toBe(401);
const resAuth = await request(app)
.get("/metrics")
.set("Authorization", "Bearer secret-token-456");
expect(resAuth.statusCode).toBe(200);
delete process.env.METRICS_TOKEN;
});
});
describe("Funnel counter increments", () => {
beforeEach(() => {
paymentsInitialized.reset();
paymentsSubmitted.reset();
paymentsConfirmed.reset();
paymentsFailed.reset();
});
it("purchase funnel counters increment correctly", async () => {
paymentsInitialized.inc({ type: "purchase" });
paymentsSubmitted.inc({ type: "purchase" });
paymentsConfirmed.inc({ type: "purchase" });
expect(await counterValue(paymentsInitialized, { type: "purchase" })).toBe(1);
expect(await counterValue(paymentsSubmitted, { type: "purchase" })).toBe(1);
expect(await counterValue(paymentsConfirmed, { type: "purchase" })).toBe(1);
});
it("donation funnel counters increment correctly", async () => {
paymentsInitialized.inc({ type: "donation" });
paymentsSubmitted.inc({ type: "donation" });
paymentsConfirmed.inc({ type: "donation" });
expect(await counterValue(paymentsInitialized, { type: "donation" })).toBe(1);
expect(await counterValue(paymentsSubmitted, { type: "donation" })).toBe(1);
expect(await counterValue(paymentsConfirmed, { type: "donation" })).toBe(1);
});
it("failed counter increments with reason label", async () => {
paymentsFailed.inc({ type: "purchase", reason: "stellar_error" });
expect(
await counterValue(paymentsFailed, {
type: "purchase",
reason: "stellar_error",
})
).toBe(1);
});
});
describe("Stellar donations", () => {
it("should respond to GET /api/stellar/donation/stats (503 when donation wallet is not configured)", async () => {
const res = await request(app).get("/api/stellar/donation/stats");
if (process.env.DONATION_WALLET_PUBLIC_KEY && res.statusCode === 200) {
// Wallet configured: shaped stats response
expect(res.statusCode).toBe(200);
expect(res.body).toHaveProperty("poolBalance");
expect(res.body).toHaveProperty("donationCount");
expect(res.body).toHaveProperty("totalDonated");
expect(Array.isArray(res.body.recent)).toBe(true);
} else {
expect([503, 500]).toContain(res.statusCode);
expect(res.body).toHaveProperty("success", false);
}
});
it("should require auth for POST /api/stellar/donation/initialize", async () => {
const res = await request(app)
.post("/api/stellar/donation/initialize")
.send({ amount: "10", publicKey: "GABC" });
expect(res.statusCode).toBe(401);
});
it("should require auth for POST /api/stellar/donation/submit", async () => {
const res = await request(app)
.post("/api/stellar/donation/submit")
.send({ donationId: "x", signedXdr: "y" });
expect(res.statusCode).toBe(401);
});
});
describe("Stellar service (unit, no network)", () => {
const PLATFORM_WALLET =
"GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5";
describe("calculateFeeSplit", () => {
it("splits an amount between creator and platform", () => {
const split = calculateFeeSplit("10", 5, PLATFORM_WALLET);
expect(split).not.toBeNull();
expect(split.creatorAmount).toBe("9.5");
expect(split.platformAmount).toBe("0.5");
expect(split.platformWallet).toBe(PLATFORM_WALLET);
});
it("handles fractional fee percents with 7-decimal precision", () => {
const split = calculateFeeSplit("10", 2.5, PLATFORM_WALLET);
expect(split.creatorAmount).toBe("9.75");
expect(split.platformAmount).toBe("0.25");
});
it("gives the rounding remainder to the creator and sums exactly", () => {
const split = calculateFeeSplit("9.9999999", 3, PLATFORM_WALLET);
expect(split.platformAmount).toBe("0.2999999");
expect(split.creatorAmount).toBe("9.7");
const toStroops = (a) => {
const [whole, frac = ""] = a.split(".");
return (
BigInt(whole) * 10000000n + BigInt((frac + "0000000").slice(0, 7))
);
};
expect(
toStroops(split.creatorAmount) + toStroops(split.platformAmount)
).toBe(toStroops("9.9999999"));
});
it("returns null when no fee percent is configured", () => {
expect(calculateFeeSplit("10", 0, PLATFORM_WALLET)).toBeNull();
});
it("returns null when no platform wallet is configured", () => {
expect(calculateFeeSplit("10", 5, "")).toBeNull();
});
it("returns null when the fee rounds down to zero stroops", () => {
expect(calculateFeeSplit("0.0000001", 5, PLATFORM_WALLET)).toBeNull();
});
});
describe("buildSep7Uri", () => {
it("builds a web+stellar:pay URI with USDC asset params", () => {
const uri = buildSep7Uri({
destination: PLATFORM_WALLET,
amount: "25",
});
expect(uri.startsWith("web+stellar:pay?")).toBe(true);
const params = new URLSearchParams(uri.split("?")[1]);
expect(params.get("destination")).toBe(PLATFORM_WALLET);
expect(params.get("amount")).toBe("25");
expect(params.get("asset_code")).toBe("USDC");
expect(params.get("asset_issuer")).toBe(USDC_ISSUER);
expect(params.get("memo")).toBeNull();
expect(params.get("memo_type")).toBeNull();
});
it("includes memo and memo_type only when a memo is provided", () => {
const uri = buildSep7Uri({
destination: PLATFORM_WALLET,
amount: "1.5",
memo: "DNB-SADAQAH",
});
const params = new URLSearchParams(uri.split("?")[1]);
expect(params.get("memo")).toBe("DNB-SADAQAH");
expect(params.get("memo_type")).toBe("MEMO_TEXT");
});
});
});