-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.fixtures.ts
More file actions
395 lines (360 loc) · 9.89 KB
/
api.fixtures.ts
File metadata and controls
395 lines (360 loc) · 9.89 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
import { APIRequestContext, Page, Browser, chromium } from '@playwright/test';
import type { EmployeeData, DepartmentData } from './data.fixtures';
import { loginAsRole, getTokenFromProfile } from './auth.fixtures';
import testUsers from '../config/test-users.json';
/**
* API Fixtures
*
* Provides helper functions for API operations:
* - Creating resources via API
* - Deleting resources for test cleanup
* - Making authenticated API requests
* - Token acquisition for roles
*/
const API_BASE_URL = 'https://localhost:44378/api/v1';
/**
* Gets an access token for a specific role using browser-based authentication
*
* Creates a temporary browser session, logs in as the specified role,
* extracts the access token from the profile page, and returns it.
*
* @param request - Playwright APIRequestContext (not used but kept for API compatibility)
* @param role - User role ('employee', 'manager', or 'hradmin')
* @returns Promise resolving to access token string
*
* @example
* const token = await getTokenForRole(request, 'hradmin');
* await createEmployee(request, token, employeeData);
*/
export async function getTokenForRole(
request: APIRequestContext,
role: 'employee' | 'manager' | 'hradmin'
): Promise<string> {
// Launch a temporary browser to get the token
const browser = await chromium.launch();
const context = await browser.newContext({
ignoreHTTPSErrors: true,
});
const page = await context.newPage();
try {
// Login as the specified role
await loginAsRole(page, role);
// Extract token from profile page
const token = await getTokenFromProfile(page);
if (!token) {
throw new Error(`Failed to extract token for role: ${role}`);
}
return token;
} finally {
// Always clean up the browser
await context.close();
await browser.close();
}
}
/**
* Makes an authenticated API request
*
* @param request - Playwright APIRequestContext
* @param token - Bearer token for authorization
* @param method - HTTP method
* @param endpoint - API endpoint (relative to base URL)
* @param data - Request body data (optional)
* @returns Promise resolving to API response
*/
async function makeAuthenticatedRequest(
request: APIRequestContext,
token: string,
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
endpoint: string,
data?: any
) {
const url = `${API_BASE_URL}${endpoint}`;
const options: any = {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
ignoreHTTPSErrors: true,
};
if (data) {
options.data = data;
}
switch (method) {
case 'GET':
return await request.get(url, options);
case 'POST':
return await request.post(url, options);
case 'PUT':
return await request.put(url, options);
case 'DELETE':
return await request.delete(url, options);
}
}
/**
* Creates an employee via API
*
* @param request - Playwright APIRequestContext
* @param token - Bearer token (must have write permission)
* @param data - Employee data
* @returns Promise resolving to created employee (with ID)
*
* @example
* const employee = await createEmployee(request, token, {
* firstName: 'John',
* lastName: 'Doe',
* email: 'john.doe@example.com'
* });
*/
export async function createEmployee(
request: APIRequestContext,
token: string,
data: EmployeeData
): Promise<any> {
const response = await makeAuthenticatedRequest(
request,
token,
'POST',
'/employees',
data
);
if (!response.ok()) {
const errorText = await response.text();
throw new Error(`Failed to create employee: ${response.status()} - ${errorText}`);
}
const result = await response.json();
return result.data || result;
}
/**
* Deletes an employee via API
*
* @param request - Playwright APIRequestContext
* @param token - Bearer token (must have delete permission)
* @param id - Employee ID to delete
* @returns Promise that resolves when deletion is complete
*
* @example
* await deleteEmployee(request, token, 123);
*/
export async function deleteEmployee(
request: APIRequestContext,
token: string,
id: number
): Promise<void> {
const response = await makeAuthenticatedRequest(
request,
token,
'DELETE',
`/employees/${id}`
);
if (!response.ok() && response.status() !== 404) {
const errorText = await response.text();
throw new Error(`Failed to delete employee: ${response.status()} - ${errorText}`);
}
}
/**
* Gets employee by ID via API
*
* @param request - Playwright APIRequestContext
* @param token - Bearer token
* @param id - Employee ID
* @returns Promise resolving to employee data
*/
export async function getEmployee(
request: APIRequestContext,
token: string,
id: number
): Promise<any> {
const response = await makeAuthenticatedRequest(
request,
token,
'GET',
`/employees/${id}`
);
if (!response.ok()) {
const errorText = await response.text();
throw new Error(`Failed to get employee: ${response.status()} - ${errorText}`);
}
const result = await response.json();
return result.data || result;
}
/**
* Creates a department via API
*
* @param request - Playwright APIRequestContext
* @param token - Bearer token (must have write permission)
* @param data - Department data
* @returns Promise resolving to created department (with ID)
*
* @example
* const department = await createDepartment(request, token, {
* name: 'Engineering',
* description: 'Software Development'
* });
*/
export async function createDepartment(
request: APIRequestContext,
token: string,
data: DepartmentData
): Promise<any> {
const response = await makeAuthenticatedRequest(
request,
token,
'POST',
'/departments',
data
);
if (!response.ok()) {
const errorText = await response.text();
throw new Error(`Failed to create department: ${response.status()} - ${errorText}`);
}
const result = await response.json();
return result.data || result;
}
/**
* Deletes a department via API
*
* @param request - Playwright APIRequestContext
* @param token - Bearer token (must have delete permission)
* @param id - Department ID to delete
* @returns Promise that resolves when deletion is complete
*
* @example
* await deleteDepartment(request, token, 456);
*/
export async function deleteDepartment(
request: APIRequestContext,
token: string,
id: number
): Promise<void> {
const response = await makeAuthenticatedRequest(
request,
token,
'DELETE',
`/departments/${id}`
);
if (!response.ok() && response.status() !== 404) {
const errorText = await response.text();
throw new Error(`Failed to delete department: ${response.status()} - ${errorText}`);
}
}
/**
* Gets all employees via API
*
* @param request - Playwright APIRequestContext
* @param token - Bearer token
* @returns Promise resolving to array of employees
*/
export async function getAllEmployees(
request: APIRequestContext,
token: string
): Promise<any[]> {
const response = await makeAuthenticatedRequest(
request,
token,
'GET',
'/employees'
);
if (!response.ok()) {
const errorText = await response.text();
throw new Error(`Failed to get employees: ${response.status()} - ${errorText}`);
}
const result = await response.json();
return result.data || result.items || result;
}
/**
* Gets all departments via API
*
* @param request - Playwright APIRequestContext
* @param token - Bearer token
* @returns Promise resolving to array of departments
*/
export async function getAllDepartments(
request: APIRequestContext,
token: string
): Promise<any[]> {
const response = await makeAuthenticatedRequest(
request,
token,
'GET',
'/departments'
);
if (!response.ok()) {
const errorText = await response.text();
throw new Error(`Failed to get departments: ${response.status()} - ${errorText}`);
}
const result = await response.json();
return result.data || result.items || result;
}
/**
* Updates an employee via API
*
* @param request - Playwright APIRequestContext
* @param token - Bearer token (must have write permission)
* @param id - Employee ID to update
* @param data - Updated employee data
* @returns Promise resolving to updated employee
*/
export async function updateEmployee(
request: APIRequestContext,
token: string,
id: number,
data: Partial<EmployeeData>
): Promise<any> {
const response = await makeAuthenticatedRequest(
request,
token,
'PUT',
`/employees/${id}`,
data
);
if (!response.ok()) {
const errorText = await response.text();
throw new Error(`Failed to update employee: ${response.status()} - ${errorText}`);
}
const result = await response.json();
return result.data || result;
}
/**
* Cleans up test data by deleting multiple employees
*
* @param request - Playwright APIRequestContext
* @param token - Bearer token (must have delete permission)
* @param ids - Array of employee IDs to delete
* @returns Promise that resolves when all deletions are complete
*
* @example
* await cleanupEmployees(request, token, [1, 2, 3]);
*/
export async function cleanupEmployees(
request: APIRequestContext,
token: string,
ids: number[]
): Promise<void> {
await Promise.all(
ids.map(id => deleteEmployee(request, token, id).catch(() => {
// Ignore errors during cleanup
}))
);
}
/**
* Cleans up test data by deleting multiple departments
*
* @param request - Playwright APIRequestContext
* @param token - Bearer token (must have delete permission)
* @param ids - Array of department IDs to delete
* @returns Promise that resolves when all deletions are complete
*
* @example
* await cleanupDepartments(request, token, [10, 11, 12]);
*/
export async function cleanupDepartments(
request: APIRequestContext,
token: string,
ids: number[]
): Promise<void> {
await Promise.all(
ids.map(id => deleteDepartment(request, token, id).catch(() => {
// Ignore errors during cleanup
}))
);
}