-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-api.js
More file actions
406 lines (358 loc) Β· 12 KB
/
test-api.js
File metadata and controls
406 lines (358 loc) Β· 12 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#!/usr/bin/env node
/**
* Project-350 API Automated Test Suite
* Tests all implemented API endpoints for functionality and data integrity
*/
const axios = require("axios");
const colors = require("colors");
class APITester {
constructor(baseURL = "http://localhost:3000") {
this.baseURL = baseURL;
this.authToken = null;
this.adminToken = null;
this.testResults = {
passed: 0,
failed: 0,
errors: [],
};
}
log(message, type = "info") {
const timestamp = new Date().toISOString();
switch (type) {
case "success":
console.log(`[${timestamp}] β
${message}`.green);
break;
case "error":
console.log(`[${timestamp}] β ${message}`.red);
break;
case "warning":
console.log(`[${timestamp}] β οΈ ${message}`.yellow);
break;
default:
console.log(`[${timestamp}] βΉοΈ ${message}`.blue);
}
}
async test(name, testFn) {
try {
this.log(`Testing: ${name}`);
await testFn();
this.testResults.passed++;
this.log(`PASSED: ${name}`, "success");
} catch (error) {
this.testResults.failed++;
this.testResults.errors.push({ name, error: error.message });
this.log(`FAILED: ${name} - ${error.message}`, "error");
}
}
async setupAuth() {
// Register test user
try {
await axios.post(`${this.baseURL}/api/auth/register`, {
name: "Test User",
email: "testuser@example.com",
password: "password123",
});
} catch (error) {
// User might already exist
}
// Login to get token
const loginResponse = await axios.post(`${this.baseURL}/api/auth/login`, {
email: "testuser@example.com",
password: "password123",
});
this.authToken = loginResponse.data.token;
this.log("Authentication setup completed", "success");
}
async runAuthTests() {
this.log("Starting Authentication Tests...", "info");
await this.test("User Registration", async () => {
const response = await axios.post(`${this.baseURL}/api/auth/register`, {
name: "New Test User",
email: `test${Date.now()}@example.com`,
password: "password123",
});
if (response.status !== 201) throw new Error("Registration failed");
});
await this.test("User Login", async () => {
const response = await axios.post(`${this.baseURL}/api/auth/login`, {
email: "testuser@example.com",
password: "password123",
});
if (!response.data.token) throw new Error("No token received");
});
await this.test("Profile Update", async () => {
const response = await axios.post(
`${this.baseURL}/api/auth/profile/update`,
{
name: "Updated Test User",
bio: "Test bio",
},
{
headers: { Authorization: `Bearer ${this.authToken}` },
}
);
if (response.status !== 200) throw new Error("Profile update failed");
});
}
async runEmergencyTests() {
this.log("Starting Emergency Assistance Tests...", "info");
await this.test("Get Emergency Types", async () => {
const response = await axios.get(`${this.baseURL}/api/emergency/types`);
if (!response.data.types || !Array.isArray(response.data.types)) {
throw new Error("Emergency types not returned properly");
}
});
await this.test("Search Emergency Contacts", async () => {
const response = await axios.get(
`${this.baseURL}/api/emergency/search?location=Dhaka`
);
if (!response.data.contacts)
throw new Error("Search results not returned");
});
await this.test("Get Contacts by Location", async () => {
const response = await axios.get(`${this.baseURL}/api/emergency/Dhaka`);
if (!response.data.contacts)
throw new Error("Location contacts not returned");
});
}
async runExpenseTests() {
this.log("Starting Expense Tracker Tests...", "info");
await this.test("Get Expense Categories", async () => {
const response = await axios.get(
`${this.baseURL}/api/expenses/categories`
);
if (
!response.data.categories ||
!Array.isArray(response.data.categories)
) {
throw new Error("Expense categories not returned properly");
}
});
let expenseId;
await this.test("Add Expense", async () => {
const response = await axios.post(
`${this.baseURL}/api/expenses`,
{
category: "food",
amount: 25.5,
description: "Test expense",
date: "2024-01-15",
},
{
headers: { Authorization: `Bearer ${this.authToken}` },
}
);
if (response.status !== 201) throw new Error("Expense creation failed");
expenseId = response.data.expense?.expenseID;
});
await this.test("Get User Expenses", async () => {
const response = await axios.get(`${this.baseURL}/api/expenses`, {
headers: { Authorization: `Bearer ${this.authToken}` },
});
if (!response.data.expenses)
throw new Error("User expenses not returned");
});
await this.test("Get Expense Summary", async () => {
const response = await axios.get(`${this.baseURL}/api/expenses/summary`, {
headers: { Authorization: `Bearer ${this.authToken}` },
});
if (!response.data.summary)
throw new Error("Expense summary not returned");
});
await this.test("Search Expenses", async () => {
const response = await axios.get(
`${this.baseURL}/api/expenses/search?q=test`,
{
headers: { Authorization: `Bearer ${this.authToken}` },
}
);
if (!response.data.expenses)
throw new Error("Search results not returned");
});
if (expenseId) {
await this.test("Get Specific Expense", async () => {
const response = await axios.get(
`${this.baseURL}/api/expenses/${expenseId}`,
{
headers: { Authorization: `Bearer ${this.authToken}` },
}
);
if (!response.data.expense)
throw new Error("Specific expense not returned");
});
await this.test("Update Expense", async () => {
const response = await axios.put(
`${this.baseURL}/api/expenses/${expenseId}`,
{
description: "Updated test expense",
},
{
headers: { Authorization: `Bearer ${this.authToken}` },
}
);
if (response.status !== 200) throw new Error("Expense update failed");
});
await this.test("Delete Expense", async () => {
const response = await axios.delete(
`${this.baseURL}/api/expenses/${expenseId}`,
{
headers: { Authorization: `Bearer ${this.authToken}` },
}
);
if (response.status !== 200) throw new Error("Expense deletion failed");
});
}
}
async runTripTests() {
this.log("Starting Trip Management Tests...", "info");
let tripId;
await this.test("Create Trip", async () => {
const response = await axios.post(
`${this.baseURL}/api/trips`,
{
destination: "Cox's Bazar, Bangladesh",
duration: 3,
budget: 500,
preferences: ["beach", "adventure"],
},
{
headers: { Authorization: `Bearer ${this.authToken}` },
}
);
if (response.status !== 201) throw new Error("Trip creation failed");
tripId = response.data.trip?.tripID;
});
if (tripId) {
await this.test("Get Trip by ID", async () => {
const response = await axios.get(
`${this.baseURL}/api/trips/${tripId}`,
{
headers: { Authorization: `Bearer ${this.authToken}` },
}
);
if (!response.data) throw new Error("Trip not returned");
});
}
}
async runBlogTests() {
this.log("Starting Blog Management Tests...", "info");
await this.test("Get All Blogs", async () => {
const response = await axios.get(`${this.baseURL}/api/blogs`);
if (!response.data.blogs) throw new Error("Blogs not returned");
});
// Note: Blog creation requires a valid trip ID, which we'd get from trip creation
}
async runGroupTests() {
this.log("Starting Group Management Tests...", "info");
await this.test("Get All Groups", async () => {
const response = await axios.get(`${this.baseURL}/api/groups`);
if (!Array.isArray(response.data))
throw new Error("Groups not returned as array");
});
}
async runTranslationTests() {
this.log("Starting Translation Tests...", "info");
await this.test("Translate Text", async () => {
const response = await axios.post(`${this.baseURL}/api/translate`, {
text: "Hello, how are you?",
sourceLang: "en",
targetLang: "bn",
});
if (!response.data.translatedText)
throw new Error("Translation not returned");
});
}
async runErrorTests() {
this.log("Starting Error Handling Tests...", "info");
await this.test("Unauthorized Access", async () => {
try {
await axios.get(`${this.baseURL}/api/expenses`, {
headers: { Authorization: "Bearer invalid_token" },
});
throw new Error("Should have failed with unauthorized");
} catch (error) {
if (error.response?.status !== 401) {
throw new Error("Expected 401 status code");
}
}
});
await this.test("Invalid Data Validation", async () => {
try {
await axios.post(
`${this.baseURL}/api/expenses`,
{
// Missing required fields
amount: "invalid",
},
{
headers: { Authorization: `Bearer ${this.authToken}` },
}
);
throw new Error("Should have failed with validation error");
} catch (error) {
if (error.response?.status !== 400) {
throw new Error("Expected 400 status code");
}
}
});
await this.test("Not Found Handling", async () => {
try {
await axios.get(`${this.baseURL}/api/expenses/nonexistent_id`, {
headers: { Authorization: `Bearer ${this.authToken}` },
});
throw new Error("Should have failed with not found");
} catch (error) {
if (error.response?.status !== 404) {
throw new Error("Expected 404 status code");
}
}
});
}
async runAllTests() {
console.log("π Starting Project-350 API Test Suite...".bold.cyan);
console.log("============================================".cyan);
try {
// Setup authentication first
await this.setupAuth();
// Run all test suites
await this.runAuthTests();
await this.runEmergencyTests();
await this.runExpenseTests();
await this.runTripTests();
await this.runBlogTests();
await this.runGroupTests();
await this.runTranslationTests();
await this.runErrorTests();
// Print results
this.printResults();
} catch (error) {
this.log(`Test suite failed to run: ${error.message}`, "error");
}
}
printResults() {
console.log("\nπ Test Results Summary".bold.cyan);
console.log("========================".cyan);
console.log(`β
Passed: ${this.testResults.passed}`.green);
console.log(`β Failed: ${this.testResults.failed}`.red);
console.log(
`π Success Rate: ${(
(this.testResults.passed /
(this.testResults.passed + this.testResults.failed)) *
100
).toFixed(2)}%`
);
if (this.testResults.errors.length > 0) {
console.log("\nπ Failed Tests Details:".bold.red);
this.testResults.errors.forEach((error, index) => {
console.log(`${index + 1}. ${error.name}: ${error.error}`.red);
});
}
console.log("\nπ API Test Suite Completed!".bold.green);
}
}
// Run the test suite
if (require.main === module) {
const tester = new APITester();
tester.runAllTests().catch(console.error);
}
module.exports = APITester;