-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathapi.ts
More file actions
364 lines (339 loc) · 10.3 KB
/
Copy pathapi.ts
File metadata and controls
364 lines (339 loc) · 10.3 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
import axios from "axios";
import {
TCG_TRIGGER_URL,
TCG_POLL_URL,
FETCH_DETAILS_URL,
FORM_FIELDS_URL,
BULK_CREATE_URL,
} from "./config.js";
import {
DefaultFieldMaps,
Scenario,
CreateTestCasesFromFileArgs,
} from "./types.js";
import { createTestCasePayload } from "./helpers.js";
import config from "../../../config.js";
import { DOMAINS } from "../../../lib/domains.js";
/**
* Fetch default and custom form fields for a project.
*/
export async function fetchFormFields(
projectId: string,
): Promise<{ default_fields: any; custom_fields: any }> {
const res = await axios.get(FORM_FIELDS_URL(projectId), {
headers: {
"API-TOKEN": `${config.browserstackUsername}:${config.browserstackAccessKey}`,
},
});
return res.data;
}
/**
* Trigger AI-based test case generation for a document.
*/
export async function triggerTestCaseGeneration(
document: string,
documentId: number,
folderId: string,
projectId: string,
source: string,
): Promise<string> {
const res = await axios.post(
TCG_TRIGGER_URL,
{
document,
documentId,
folderId,
projectId,
source,
webhookUrl: `${DOMAINS.TEST_MANAGEMENT}/api/v1/projects/${projectId}/folder/${folderId}/webhooks/tcg`,
},
{
headers: {
"API-TOKEN": `${config.browserstackUsername}:${config.browserstackAccessKey}`,
"Content-Type": "application/json",
"request-source": source,
},
},
);
if (res.status !== 200) {
throw new Error(`Trigger failed: ${res.statusText}`);
}
return res.data["x-bstack-traceRequestId"];
}
/**
* Initiate a fetch for test-case details; returns the traceRequestId for polling.
*/
export async function fetchTestCaseDetails(
documentId: number,
folderId: string,
projectId: string,
testCaseIds: string[],
source: string,
): Promise<string> {
if (testCaseIds.length === 0) {
throw new Error("No testCaseIds provided to fetchTestCaseDetails");
}
const res = await axios.post(
FETCH_DETAILS_URL,
{
document_id: documentId,
folder_id: folderId,
project_id: projectId,
test_case_ids: testCaseIds,
},
{
headers: {
"API-TOKEN": `${config.browserstackUsername}:${config.browserstackAccessKey}`,
"request-source": source,
"Content-Type": "application/json",
},
},
);
if (res.data.data.success !== true) {
throw new Error(`Fetch details failed: ${res.data.data.message}`);
}
return res.data.request_trace_id;
}
/**
* Poll for a given traceRequestId until all test-case details are returned.
*/
export async function pollTestCaseDetails(
traceRequestId: string,
): Promise<Record<string, any>> {
const detailMap: Record<string, any> = {};
let done = false;
while (!done) {
// add a bit of jitter to avoid synchronized polling storms
await new Promise((r) => setTimeout(r, 10000 + Math.random() * 5000));
const poll = await axios.post(
`${TCG_POLL_URL}?x-bstack-traceRequestId=${encodeURIComponent(
traceRequestId,
)}`,
{},
{
headers: {
"API-TOKEN": `${config.browserstackUsername}:${config.browserstackAccessKey}`,
},
},
);
if (!poll.data.data.success) {
throw new Error(`Polling failed: ${poll.data.data.message}`);
}
for (const msg of poll.data.data.message) {
if (msg.type === "termination") {
done = true;
}
if (msg.type === "testcase_details") {
for (const test of msg.data.testcase_details) {
detailMap[test.id] = {
steps: test.steps,
preconditions: test.preconditions,
};
}
}
}
}
return detailMap;
}
/**
* Poll for scenarios & testcases, trigger detail fetches, then poll all details in parallel.
*/
export async function pollScenariosTestDetails(
args: CreateTestCasesFromFileArgs,
traceId: string,
context: any,
documentId: number,
source: string,
): Promise<Record<string, Scenario>> {
const { folderId, projectReferenceId } = args;
const scenariosMap: Record<string, Scenario> = {};
const detailPromises: Promise<Record<string, any>>[] = [];
let iteratorCount = 0;
// Promisify interval-style polling using a wrapper
await new Promise<void>((resolve, reject) => {
const intervalId = setInterval(async () => {
try {
const poll = await axios.post(
`${TCG_POLL_URL}?x-bstack-traceRequestId=${encodeURIComponent(traceId)}`,
{},
{
headers: {
"API-TOKEN": `${config.browserstackUsername}:${config.browserstackAccessKey}`,
},
},
);
if (poll.status !== 200) {
clearInterval(intervalId);
reject(new Error(`Polling error: ${poll.statusText}`));
return;
}
for (const msg of poll.data.data.message) {
if (msg.type === "scenario") {
msg.data.scenarios.forEach((sc: any) => {
scenariosMap[sc.id] = { id: sc.id, name: sc.name, testcases: [] };
});
const count = Object.keys(scenariosMap).length;
await context.sendNotification({
method: "notifications/progress",
params: {
progressToken: context._meta?.progressToken ?? traceId,
progress: count,
total: count,
message: `Fetched ${count} scenarios`,
},
});
}
if (msg.type === "testcase") {
const sc = msg.data.scenario;
if (sc) {
const array = Array.isArray(msg.data.testcases)
? msg.data.testcases
: msg.data.testcases
? [msg.data.testcases]
: [];
const ids = array.map((tc: any) => tc.id || tc.test_case_id);
const reqId = await fetchTestCaseDetails(
documentId,
folderId,
projectReferenceId,
ids,
source,
);
detailPromises.push(pollTestCaseDetails(reqId));
scenariosMap[sc.id] ||= {
id: sc.id,
name: sc.name,
testcases: [],
traceId,
};
scenariosMap[sc.id].testcases.push(...array);
iteratorCount++;
const total = Object.keys(scenariosMap).length;
await context.sendNotification({
method: "notifications/progress",
params: {
progressToken: context._meta?.progressToken ?? traceId,
progress: iteratorCount,
total,
message: `Fetched ${array.length} test cases for scenario ${iteratorCount} out of ${total}`,
},
});
}
}
if (msg.type === "termination") {
clearInterval(intervalId);
resolve();
}
}
} catch (err) {
clearInterval(intervalId);
reject(err);
}
}, 10000); // 10 second interval
});
// once all detail fetches are triggered, wait for them to complete
const detailsList = await Promise.all(detailPromises);
const allDetails = detailsList.reduce((acc, cur) => ({ ...acc, ...cur }), {});
// attach the fetched detail objects back to each testcase
for (const scenario of Object.values(scenariosMap)) {
scenario.testcases = scenario.testcases.map((tc: any) => ({
...tc,
...(allDetails[tc.id || tc.test_case_id] ?? {}),
}));
}
return scenariosMap;
}
/**
* Bulk-create generated test cases in BrowserStack.
*/
export async function bulkCreateTestCases(
scenariosMap: Record<string, Scenario>,
projectId: string,
folderId: string,
fieldMaps: DefaultFieldMaps,
booleanFieldId: number | undefined,
traceId: string,
context: any,
documentId: number,
): Promise<string> {
const results: Record<string, any> = {};
const total = Object.keys(scenariosMap).length;
let doneCount = 0;
let testCaseCount = 0;
for (const { id, testcases } of Object.values(scenariosMap)) {
const testCaseLength = testcases.length;
testCaseCount += testCaseLength;
if (testCaseLength === 0) continue;
const payload = {
test_cases: testcases.map((tc) =>
createTestCasePayload(
tc,
id,
folderId,
fieldMaps,
documentId,
booleanFieldId,
traceId,
),
),
};
try {
const resp = await axios.post(
BULK_CREATE_URL(projectId, folderId),
payload,
{
headers: {
"API-TOKEN": `${config.browserstackUsername}:${config.browserstackAccessKey}`,
"Content-Type": "application/json",
},
},
);
results[id] = resp.data;
await context.sendNotification({
method: "notifications/progress",
params: {
progressToken: context._meta?.progressToken ?? "bulk-create",
message: `Bulk create done for scenario ${doneCount} of ${total}`,
total,
progress: doneCount,
},
});
} catch (error) {
//send notification
await context.sendNotification({
method: "notifications/progress",
params: {
progressToken: context._meta?.progressToken ?? traceId,
message: `Bulk create failed for scenario ${id}: ${error instanceof Error ? error.message : "Unknown error"}`,
total,
progress: doneCount,
},
});
//continue to next scenario
continue;
}
doneCount++;
}
const resultString = `Total of ${testCaseCount} test cases created in ${total} scenarios.`;
return resultString;
}
export async function projectIdentifierToId(
projectId: string,
): Promise<string> {
const url = `${DOMAINS.TEST_MANAGEMENT}/api/v1/projects/?q=${projectId}`;
const response = await axios.get(url, {
headers: {
"API-TOKEN": `${config.browserstackUsername}:${config.browserstackAccessKey}`,
accept: "application/json, text/plain, */*",
},
});
if (response.data.success !== true) {
throw new Error(`Failed to fetch project ID: ${response.statusText}`);
}
for (const project of response.data.projects) {
if (project.identifier === projectId) {
return project.id;
}
}
throw new Error(`Project with identifier ${projectId} not found.`);
}