@reportportal/client-javascript 5.0.2 → 5.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,711 +1,719 @@
1
- /* eslint-disable quotes,no-console,class-methods-use-this */
2
- const UniqId = require('uniqid');
3
- const { URLSearchParams } = require('url');
4
- const helpers = require('./helpers');
5
- const RestClient = require('./rest');
6
- const Analytics = require('../analytics/analytics');
7
- const { RP_STATUSES } = require('./constants/statuses');
8
- const { CLIENT_JAVASCRIPT_EVENTS, getAgentEventLabel } = require('./../analytics/events');
9
-
10
- const MULTIPART_BOUNDARY = Math.floor(Math.random() * 10000000000).toString();
11
-
12
- class RPClient {
13
- /**
14
- * Create a client for RP.
15
- * @param {Object} params - config object.
16
- * params should look like this
17
- * {
18
- * token: "00000000-0000-0000-0000-000000000000",
19
- * endpoint: "http://localhost:8080/api/v1",
20
- * launch: "YOUR LAUNCH NAME",
21
- * project: "PROJECT NAME",
22
- * }
23
- *
24
- * @param {Object} agentParams - agent's info object.
25
- * agentParams should look like this
26
- * {
27
- * name: "AGENT NAME",
28
- * version: "AGENT VERSION",
29
- * }
30
- */
31
- constructor(params, agentParams) {
32
- this.debug = params.debug;
33
- this.isLaunchMergeRequired = params.isLaunchMergeRequired === undefined ? false : params.isLaunchMergeRequired;
34
- this.map = {};
35
- this.baseURL = [params.endpoint, params.project].join('/');
36
- const headers = Object.assign({
37
- 'User-Agent': 'NodeJS',
38
- Authorization: `bearer ${params.token}`,
39
- }, params.headers || {});
40
- this.headers = headers;
41
- this.options = {
42
- headers,
43
- };
44
- this.token = params.token;
45
- this.config = params;
46
- this.helpers = helpers;
47
- this.restClient = new RestClient({
48
- baseURL: this.baseURL,
49
- headers: this.headers,
50
- });
51
- this.analytics = new Analytics(agentParams);
52
- this.launchUuid = '';
53
- this.nonRetriedItemMap = new Map();
54
- }
55
-
56
- // eslint-disable-next-line valid-jsdoc
57
- /**
58
- *
59
- * @Private
60
- */
61
- logDebug(msg) {
62
- if (this.debug) {
63
- console.log(msg);
64
- }
65
- }
66
-
67
- calculateNonRetriedItemMapKey(launchId, parentId, name, itemId = '') {
68
- return `${launchId}__${parentId}__${name}__${itemId}`;
69
- }
70
-
71
- getUniqId() {
72
- return UniqId();
73
- }
74
-
75
- getRejectAnswer(tempId, error) {
76
- return {
77
- tempId,
78
- promise: Promise.reject(error),
79
- };
80
- }
81
-
82
- getNewItemObj(startPromiseFunc) {
83
- let resolveFinish;
84
- let rejectFinish;
85
- const obj = {
86
- promiseStart: (new Promise(startPromiseFunc)),
87
- realId: '',
88
- children: [],
89
- finishSend: false,
90
- promiseFinish: (new Promise((resolve, reject) => {
91
- resolveFinish = resolve;
92
- rejectFinish = reject;
93
- })),
94
- };
95
- obj.resolveFinish = resolveFinish;
96
- obj.rejectFinish = rejectFinish;
97
- return obj;
98
- }
99
-
100
- // eslint-disable-next-line valid-jsdoc
101
- /**
102
- *
103
- * @Private
104
- */
105
- cleanMap(ids) {
106
- ids.forEach((id) => {
107
- delete this.map[id];
108
- });
109
- }
110
-
111
- checkConnect() {
112
- const url = [this.config.endpoint.replace('/v2', '/v1'), 'user'].join('/');
113
- return RestClient.request('GET', url, {}, { headers: this.headers });
114
- }
115
-
116
- triggerAnalyticsEvent() {
117
- if (this.config.disableGA) {
118
- return;
119
- }
120
-
121
- if (this.analytics.agentParams) {
122
- const label = getAgentEventLabel(this.analytics.agentParams);
123
- this.analytics.trackEvent(Object.assign(CLIENT_JAVASCRIPT_EVENTS.START_LAUNCH, { label }));
124
- } else {
125
- this.analytics.trackEvent(CLIENT_JAVASCRIPT_EVENTS.START_LAUNCH);
126
- }
127
- }
128
-
129
- /**
130
- * Start launch and report it.
131
- * @param {Object} launchDataRQ - request object.
132
- * launchDataRQ should look like this
133
- * {
134
- "description": "string" (support markdown),
135
- "mode": "DEFAULT" or "DEBUG",
136
- "name": "string",
137
- "startTime": this.helper.now(),
138
- "attributes": [
139
- {
140
- "key": "string",
141
- "value": "string"
142
- },
143
- {
144
- "value": "string"
145
- }
146
- ]
147
- * }
148
- * @Returns an object which contains a tempID and a promise
149
- *
150
- * As system attributes, this method sends the following data (these data are not for public use):
151
- * client name, version;
152
- * agent name, version (if given);
153
- * browser name, version (if given);
154
- * OS type, architecture;
155
- * RAMSize;
156
- * nodeJS version;
157
- *
158
- * This method works in two ways:
159
- * First - If launchDataRQ object doesn't contain ID field,
160
- * it would create a new Launch instance at the Report Portal with it ID.
161
- * Second - If launchDataRQ would contain ID field,
162
- * client would connect to the existing Launch which ID
163
- * has been sent , and would send all data to it.
164
- * Notice that Launch which ID has been sent must be 'IN PROGRESS' state at the Report Portal
165
- * or it would throw an error.
166
- * @Returns {Object} - an object which contains a tempID and a promise
167
- */
168
- startLaunch(launchDataRQ) {
169
- const tempId = this.getUniqId();
170
-
171
- if (launchDataRQ.id) {
172
- this.map[tempId] = this.getNewItemObj(resolve => resolve(launchDataRQ));
173
- this.map[tempId].realId = launchDataRQ.id;
174
- this.launchUuid = launchDataRQ.id;
175
- } else {
176
- const systemAttr = helpers.getSystemAttribute();
177
- const attributes = Array.isArray(launchDataRQ.attributes)
178
- ? launchDataRQ.attributes.concat(systemAttr)
179
- : systemAttr;
180
- const launchData = Object.assign(
181
- { name: this.config.launch || 'Test launch name', startTime: this.helpers.now() },
182
- launchDataRQ,
183
- { attributes },
184
- );
185
-
186
- this.map[tempId] = this.getNewItemObj((resolve, reject) => {
187
- const url = 'launch';
188
- this.logDebug(`Start launch ${tempId}`);
189
- this.restClient.create(url, launchData, { headers: this.headers })
190
- .then((response) => {
191
- this.map[tempId].realId = response.id;
192
- this.launchUuid = response.id;
193
-
194
- if (this.isLaunchMergeRequired) {
195
- helpers.saveLaunchIdToFile(response.id);
196
- }
197
-
198
- resolve(response);
199
- }, (error) => {
200
- console.dir(error);
201
- reject(error);
202
- });
203
- });
204
- }
205
- this.triggerAnalyticsEvent();
206
- return {
207
- tempId,
208
- promise: this.map[tempId].promiseStart,
209
- };
210
- }
211
-
212
- /**
213
- * Finish launch.
214
- * @param {string} launchTempId - temp launch id (returned in the query "startLaunch").
215
- * @param {Object} finishExecutionRQ - finish launch info should include time and status.
216
- * finishExecutionRQ should look like this
217
- * {
218
- * "endTime": this.helper.now(),
219
- * "status": "passed" or one of ‘passed’, ‘failed’, ‘stopped’, ‘skipped’, ‘interrupted’, ‘cancelled’
220
- * }
221
- * @Returns {Object} - an object which contains a tempID and a promise
222
- */
223
- finishLaunch(launchTempId, finishExecutionRQ) {
224
- const launchObj = this.map[launchTempId];
225
- if (!launchObj) {
226
- return this.getRejectAnswer(launchTempId, new Error(`Launch "${launchTempId}" not found`));
227
- }
228
-
229
- const finishExecutionData = Object.assign({ endTime: this.helpers.now() }, finishExecutionRQ);
230
-
231
- launchObj.finishSend = true;
232
- Promise.all(launchObj.children.map(itemId => this.map[itemId].promiseFinish))
233
- .then(() => {
234
- launchObj.promiseStart
235
- .then(() => {
236
- this.logDebug(`Finish launch ${launchTempId}`);
237
- const url = ['launch', launchObj.realId, 'finish'].join('/');
238
- this.restClient.update(url, finishExecutionData, { headers: this.headers })
239
- .then((response) => {
240
- this.logDebug(`Success finish launch ${launchTempId}`);
241
- launchObj.resolveFinish(response);
242
- }, (error) => {
243
- this.logDebug(`Error finish launch ${launchTempId}`);
244
- console.dir(error);
245
- launchObj.rejectFinish(error);
246
- });
247
- }, (error) => {
248
- launchObj.rejectFinish(error);
249
- });
250
- }, (error) => {
251
- launchObj.rejectFinish(error);
252
- });
253
-
254
- return {
255
- tempId: launchTempId,
256
- promise: launchObj.promiseFinish,
257
- };
258
- }
259
-
260
- /*
261
- * This method is used to create data object for merge request to ReportPortal.
262
- *
263
- * @Returns {Object} - an object which contains a data for merge launches in ReportPortal.
264
- */
265
- getMergeLaunchesRequest(launchIds) {
266
- return {
267
- description: "Merged launch",
268
- endTime: this.helpers.now(),
269
- extendSuitesDescription: true,
270
- launches: launchIds,
271
- mergeType: "BASIC",
272
- mode: "DEFAULT",
273
- name: this.config.launch || 'Test launch name',
274
- attributes: this.config.attributes,
275
- };
276
- }
277
-
278
- /*
279
- * This method is used for merge launches in ReportPortal.
280
- *
281
- * Please, keep in mind that this method is work only in case
282
- * the option isLaunchMergeRequired is true.
283
- */
284
- mergeLaunches() {
285
- if (this.isLaunchMergeRequired) {
286
- const launchUUIds = helpers.readLaunchesFromFile();
287
- const params = new URLSearchParams({
288
- 'filter.in.uuid': launchUUIds,
289
- });
290
- const launchSearchUrl = `launch?${params.toString()}`;
291
- return this.restClient.retrieveSyncAPI(launchSearchUrl, { headers: this.headers })
292
- .then((response) => {
293
- const launchIds = response.content.map(launch => launch.id);
294
- this.logDebug(`Found launches: ${launchIds}`);
295
- return launchIds;
296
- }, (error) => {
297
- console.dir(error);
298
- })
299
- .then((launchIds) => {
300
- const request = this.getMergeLaunchesRequest(launchIds);
301
- const mergeURL = 'launch/merge';
302
- return this.restClient.create(mergeURL, request, { headers: this.headers });
303
- })
304
- .then(() => {
305
- this.logDebug(`Launches successfully merged!`);
306
- })
307
- .catch((error) => {
308
- this.logDebug('ERROR');
309
- this.logDebug(error);
310
- });
311
- }
312
- this.logDebug('Option isLaunchMergeRequired is false');
313
- }
314
-
315
- /*
316
- * This method is used for frameworks as Jasmine. There is problem when
317
- * it doesn't wait for promise resolve and stop the process. So it better to call
318
- * this method at the spec's function as @afterAll() and manually resolve this promise.
319
- *
320
- * @return Promise
321
- */
322
- getPromiseFinishAllItems(launchTempId) {
323
- const launchObj = this.map[launchTempId];
324
- return Promise.all(launchObj.children.map(itemId => this.map[itemId].promiseFinish));
325
- }
326
-
327
-
328
- /**
329
- * Update launch.
330
- * @param {string} launchTempId - temp launch id (returned in the query "startLaunch").
331
- * @param {Object} launchData - new launch data
332
- * launchData should look like this
333
- * {
334
- "description": "string" (support markdown),
335
- "mode": "DEFAULT" or "DEBUG",
336
- "attributes": [
337
- {
338
- "key": "string",
339
- "value": "string"
340
- },
341
- {
342
- "value": "string"
343
- }
344
- ]
345
- }
346
- * @Returns {Object} - an object which contains a tempId and a promise
347
- */
348
- updateLaunch(launchTempId, launchData) {
349
- const launchObj = this.map[launchTempId];
350
- if (!launchObj) {
351
- return this.getRejectAnswer(launchTempId, new Error(`Launch "${launchTempId}" not found`));
352
- }
353
- let resolvePromise;
354
- let rejectPromise;
355
- const promise = new Promise((resolve, reject) => {
356
- resolvePromise = resolve;
357
- rejectPromise = reject;
358
- });
359
-
360
- launchObj.promiseFinish.then(() => {
361
- const url = ['launch', launchObj.realId, 'update'].join('/');
362
- this.restClient.update(url, launchData, { headers: this.headers })
363
- .then((response) => {
364
- resolvePromise(response);
365
- }, (error) => {
366
- rejectPromise(error);
367
- });
368
- }, (error) => {
369
- rejectPromise(error);
370
- });
371
- return {
372
- tempId: launchTempId,
373
- promise,
374
- };
375
- }
376
-
377
-
378
- /**
379
- * If there is no parentItemId starts Suite, else starts test or item.
380
- * @param {Object} testItemDataRQ - object with item parameters
381
- * testItemDataRQ should look like this
382
- * {
383
- "description": "string" (support markdown),
384
- "name": "string",
385
- "startTime": this.helper.now(),
386
- "attributes": [
387
- {
388
- "key": "string",
389
- "value": "string"
390
- },
391
- {
392
- "value": "string"
393
- }
394
- ],
395
- "type": 'SUITE' or one of 'SUITE', 'STORY', 'TEST',
396
- 'SCENARIO', 'STEP', 'BEFORE_CLASS', 'BEFORE_GROUPS',
397
- 'BEFORE_METHOD', 'BEFORE_SUITE', 'BEFORE_TEST',
398
- 'AFTER_CLASS', 'AFTER_GROUPS', 'AFTER_METHOD',
399
- 'AFTER_SUITE', 'AFTER_TEST'
400
- }
401
- * @param {string} launchTempId - temp launch id (returned in the query "startLaunch").
402
- * @param {string} parentTempId (optional) - temp item id (returned in the query "startTestItem").
403
- * @Returns {Object} - an object which contains a tempId and a promise
404
- */
405
- startTestItem(testItemDataRQ, launchTempId, parentTempId) {
406
- let parentMapId = launchTempId;
407
- const launchObj = this.map[launchTempId];
408
- if (!launchObj) {
409
- return this.getRejectAnswer(launchTempId, new Error(`Launch "${launchTempId}" not found`));
410
- }
411
- if (launchObj.finishSend) {
412
- const err = new Error(`Launch "${launchTempId}" is already finished, you can not add an item to it`);
413
- return this.getRejectAnswer(launchTempId, err);
414
- }
415
-
416
- const testCaseId = testItemDataRQ.testCaseId
417
- || helpers.generateTestCaseId(testItemDataRQ.codeRef, testItemDataRQ.parameters);
418
- const testItemData = Object.assign({
419
- startTime: this.helpers.now(),
420
- }, testItemDataRQ, testCaseId && { testCaseId });
421
-
422
- let parentPromise = launchObj.promiseStart;
423
- if (parentTempId) {
424
- parentMapId = parentTempId;
425
- const parentObj = this.map[parentTempId];
426
- if (!parentObj) {
427
- return this.getRejectAnswer(launchTempId, new Error(`Item "${parentTempId}" not found`));
428
- }
429
- parentPromise = parentObj.promiseStart;
430
- }
431
-
432
- const itemKey = this.calculateNonRetriedItemMapKey(
433
- launchTempId,
434
- parentTempId,
435
- testItemDataRQ.name,
436
- testItemDataRQ.uniqueId,
437
- );
438
- const firstNonRetriedItemPromise = testItemDataRQ.retry && this.nonRetriedItemMap.get(itemKey);
439
- if (firstNonRetriedItemPromise) {
440
- parentPromise = Promise.all([parentPromise, firstNonRetriedItemPromise]);
441
- }
442
-
443
- const tempId = this.getUniqId();
444
- this.map[tempId] = this.getNewItemObj((resolve, reject) => {
445
- parentPromise.then(() => {
446
- const realLaunchId = this.map[launchTempId].realId;
447
- let url = 'item/';
448
- if (parentTempId) {
449
- const realParentId = this.map[parentTempId].realId;
450
- url += `${realParentId}`;
451
- }
452
- testItemData.launchUuid = realLaunchId;
453
- this.logDebug(`Start test item ${tempId}`);
454
- this.restClient.create(url, testItemData, { headers: this.headers })
455
- .then((response) => {
456
- this.logDebug(`Success start item ${tempId}`);
457
- this.map[tempId].realId = response.id;
458
- this.nonRetriedItemMap.delete(itemKey);
459
- resolve(response);
460
- }, (error) => {
461
- this.logDebug(`Error start item ${tempId}:`);
462
- console.dir(error);
463
- reject(error);
464
- });
465
- }, (error) => {
466
- reject(error);
467
- });
468
- });
469
- this.map[parentMapId].children.push(tempId);
470
-
471
- if (!testItemDataRQ.retry) {
472
- this.nonRetriedItemMap.set(itemKey, this.map[tempId].promiseStart);
473
- }
474
-
475
- return {
476
- tempId,
477
- promise: this.map[tempId].promiseStart,
478
- };
479
- }
480
-
481
- /**
482
- * Finish Suite or Step level.
483
- * @param {string} itemTempId - temp item id (returned in the query "startTestItem").
484
- * @param {Object} finishTestItemRQ - object with item parameters.
485
- * finishTestItemRQ should look like this
486
- {
487
- "endTime": this.helper.now(),
488
- "issue": {
489
- "comment": "string",
490
- "externalSystemIssues": [
491
- {
492
- "submitDate": 0,
493
- "submitter": "string",
494
- "systemId": "string",
495
- "ticketId": "string",
496
- "url": "string"
497
- }
498
- ],
499
- "issueType": "string"
500
- },
501
- "status": "passed" or one of 'passed', 'failed', 'stopped', 'skipped', 'interrupted', 'cancelled'
502
- }
503
- * @Returns {Object} - an object which contains a tempId and a promise
504
- */
505
- finishTestItem(itemTempId, finishTestItemRQ) {
506
- const itemObj = this.map[itemTempId];
507
- if (!itemObj) {
508
- return this.getRejectAnswer(itemTempId, new Error(`Item "${itemTempId}" not found`));
509
- }
510
-
511
- const finishTestItemData = Object.assign({
512
- endTime: this.helpers.now(),
513
- }, itemObj.children.length ? {} : { status: RP_STATUSES.PASSED }, finishTestItemRQ);
514
-
515
- itemObj.finishSend = true;
516
- Promise.all(itemObj.children.map(itemId => this.map[itemId].promiseFinish))
517
- .then(() => {
518
- this.cleanMap(itemObj.children);
519
- this.finishTestItemPromiseStart(itemObj,
520
- itemTempId,
521
- Object.assign(finishTestItemData, { launchUuid: this.launchUuid }));
522
- }, () => {
523
- this.cleanMap(itemObj.children);
524
- this.logDebug(`Error finish children of test item ${itemTempId}`);
525
- this.logDebug(`Finish test item ${itemTempId}`);
526
- this.finishTestItemPromiseStart(itemObj,
527
- itemTempId,
528
- Object.assign(finishTestItemData, { launchUuid: this.launchUuid }));
529
- });
530
-
531
- return {
532
- tempId: itemTempId,
533
- promise: itemObj.promiseFinish,
534
- };
535
- }
536
-
537
- saveLog(itemObj, requestPromiseFunc) {
538
- const tempId = this.getUniqId();
539
- this.map[tempId] = this.getNewItemObj((resolve, reject) => {
540
- itemObj.promiseStart.then(() => {
541
- this.logDebug(`Save log ${tempId}`);
542
- requestPromiseFunc(itemObj.realId, this.launchUuid).then((response) => {
543
- this.logDebug(`Successfully save log ${tempId}`);
544
- resolve(response);
545
- }, (error) => {
546
- this.logDebug(`Error finish log: ${error}`);
547
- reject(error);
548
- });
549
- }, (error) => {
550
- reject(error);
551
- });
552
- });
553
- itemObj.children.push(tempId);
554
-
555
- const logObj = this.map[tempId];
556
- logObj.finishSend = true;
557
- logObj.promiseStart.then(response => logObj.resolveFinish(response), error => logObj.rejectFinish(error));
558
-
559
- return {
560
- tempId,
561
- promise: this.map[tempId].promiseFinish,
562
- };
563
- }
564
-
565
- sendLog(itemTempId, saveLogRQ, fileObj) {
566
- const saveLogData = Object.assign({
567
- time: this.helpers.now(),
568
- message: '',
569
- level: '',
570
- }, saveLogRQ);
571
-
572
- if (fileObj) {
573
- return this.sendLogWithFile(itemTempId, saveLogData, fileObj);
574
- }
575
- return this.sendLogWithoutFile(itemTempId, saveLogData);
576
- }
577
-
578
- /**
579
- * Send log of test results.
580
- * @param {string} itemTempId - temp item id (returned in the query "startTestItem").
581
- * @param {Object} saveLogRQ - object with data of test result.
582
- * saveLogRQ should look like this
583
- * {
584
- * level: 'error' or one of 'trace', 'debug', 'info', 'warn', 'error', '',
585
- * message: 'string' (support markdown),
586
- * time: this.helpers.now()
587
- * }
588
- * @Returns {Object} - an object which contains a tempId and a promise
589
- */
590
- sendLogWithoutFile(itemTempId, saveLogRQ) {
591
- const itemObj = this.map[itemTempId];
592
- if (!itemObj) {
593
- return this.getRejectAnswer(itemTempId, new Error(`Item "${itemTempId}" not found`));
594
- }
595
-
596
- const requestPromise = (itemUuid, launchUuid) => {
597
- const url = 'log';
598
- const isItemUuid = itemUuid !== launchUuid;
599
- // eslint-disable-next-line max-len
600
- return this.restClient.create(url, Object.assign(saveLogRQ, { launchUuid }, isItemUuid && { itemUuid }), { headers: this.headers });
601
- };
602
- return this.saveLog(itemObj, requestPromise);
603
- }
604
-
605
- /**
606
- * Send log of test results with file.
607
- * @param {string} itemTempId - temp item id (returned in the query "startTestItem").
608
- * @param {Object} saveLogRQ - object with data of test result.
609
- * saveLogRQ should look like this
610
- * {
611
- * level: 'error' or one of 'trace', 'debug', 'info', 'warn', 'error', '',
612
- * message: 'string' (support markdown),
613
- * time: this.helpers.now()
614
- * }
615
- * @param {Object} fileObj - object with file data.
616
- * fileObj should look like this
617
- * {
618
- name: 'string',
619
- type: "image/png" or your file mimeType
620
- (supported types: 'image/*', application/ ['xml', 'javascript', 'json', 'css', 'php'],
621
- another format will be opened in a new browser tab ),
622
- content: file
623
- * }
624
- * @Returns {Object} - an object which contains a tempId and a promise
625
- */
626
- sendLogWithFile(itemTempId, saveLogRQ, fileObj) {
627
- const itemObj = this.map[itemTempId];
628
- if (!itemObj) {
629
- return this.getRejectAnswer(itemTempId, new Error(`Item "${itemTempId}" not found`));
630
- }
631
- // eslint-disable-next-line max-len
632
- const requestPromise = (itemUuid, launchUuid) => {
633
- const isItemUuid = itemUuid !== launchUuid;
634
-
635
- // eslint-disable-next-line max-len
636
- return this.getRequestLogWithFile(Object.assign(saveLogRQ, { launchUuid }, isItemUuid && { itemUuid }), fileObj);
637
- };
638
-
639
- return this.saveLog(itemObj, requestPromise);
640
- }
641
-
642
- getRequestLogWithFile(saveLogRQ, fileObj) {
643
- const url = 'log';
644
- // eslint-disable-next-line no-param-reassign
645
- saveLogRQ.file = { name: fileObj.name };
646
- return this.restClient.create(
647
- url,
648
- this.buildMultiPartStream([saveLogRQ], fileObj, MULTIPART_BOUNDARY),
649
- {
650
- headers: Object.assign({}, this.headers, {
651
- 'Content-Type': `multipart/form-data; boundary=${MULTIPART_BOUNDARY}`,
652
- }),
653
- },
654
- )
655
- .then(response => response)
656
- .catch((error) => {
657
- this.logDebug('ERROR');
658
- this.logDebug(error);
659
- });
660
- }
661
-
662
- // eslint-disable-next-line valid-jsdoc
663
- /**
664
- *
665
- * @Private
666
- */
667
- buildMultiPartStream(jsonPart, filePart, boundary) {
668
- const eol = "\r\n";
669
- const bx = `--${boundary}`;
670
- const buffers = [
671
- // eslint-disable-next-line function-paren-newline
672
- Buffer.from(
673
- // eslint-disable-next-line prefer-template
674
- bx + eol + "Content-Disposition: form-data; name=\"json_request_part\""
675
- + eol + "Content-Type: application/json" + eol
676
- + eol + eol + JSON.stringify(jsonPart) + eol,
677
- ),
678
- // eslint-disable-next-line function-paren-newline
679
- Buffer.from(
680
- // eslint-disable-next-line prefer-template
681
- bx + eol + "Content-Disposition: form-data; name=\"file\"; filename=\"" + filePart.name + "\"" + eol
682
- + "Content-Type: " + filePart.type + eol + eol,
683
- ),
684
- Buffer.from(filePart.content, 'base64'),
685
- Buffer.from(`${eol + bx}--${eol}`),
686
- ];
687
- return Buffer.concat(buffers);
688
- }
689
-
690
- finishTestItemPromiseStart(itemObj, itemTempId, finishTestItemData) {
691
- itemObj.promiseStart
692
- .then(() => {
693
- const url = ['item', itemObj.realId].join('/');
694
- this.logDebug(`Finish test item ${itemTempId}`);
695
- // eslint-disable-next-line max-len
696
- this.restClient.update(url, Object.assign(finishTestItemData, { launchUuid: this.launchUuid }), { headers: this.headers })
697
- .then((response) => {
698
- this.logDebug(`Success finish item ${itemTempId}`);
699
- itemObj.resolveFinish(response);
700
- }, (error) => {
701
- this.logDebug(`Error finish test item ${itemTempId}`);
702
- console.dir(error);
703
- itemObj.rejectFinish(error);
704
- });
705
- }, (error) => {
706
- itemObj.rejectFinish(error);
707
- });
708
- }
709
- }
710
-
711
- module.exports = RPClient;
1
+ /* eslint-disable quotes,no-console,class-methods-use-this */
2
+ const UniqId = require('uniqid');
3
+ const { URLSearchParams } = require('url');
4
+ const helpers = require('./helpers');
5
+ const RestClient = require('./rest');
6
+ const Analytics = require('../analytics/analytics');
7
+ const { RP_STATUSES } = require('./constants/statuses');
8
+ const { CLIENT_JAVASCRIPT_EVENTS, getAgentEventLabel } = require('../analytics/events');
9
+
10
+ const MULTIPART_BOUNDARY = Math.floor(Math.random() * 10000000000).toString();
11
+
12
+ class RPClient {
13
+ /**
14
+ * Create a client for RP.
15
+ * @param {Object} params - config object.
16
+ * params should look like this
17
+ * {
18
+ * token: "00000000-0000-0000-0000-000000000000",
19
+ * endpoint: "http://localhost:8080/api/v1",
20
+ * launch: "YOUR LAUNCH NAME",
21
+ * project: "PROJECT NAME",
22
+ * }
23
+ *
24
+ * @param {Object} agentParams - agent's info object.
25
+ * agentParams should look like this
26
+ * {
27
+ * name: "AGENT NAME",
28
+ * version: "AGENT VERSION",
29
+ * }
30
+ */
31
+ constructor(params, agentParams) {
32
+ this.debug = params.debug;
33
+ this.isLaunchMergeRequired = params.isLaunchMergeRequired === undefined ? false : params.isLaunchMergeRequired;
34
+ this.map = {};
35
+ this.baseURL = [params.endpoint, params.project].join('/');
36
+ const headers = {
37
+ 'User-Agent': 'NodeJS',
38
+ Authorization: `bearer ${params.token}`,
39
+ ...(params.headers || {}),
40
+ };
41
+ this.headers = headers;
42
+ this.token = params.token;
43
+ this.config = params;
44
+ this.helpers = helpers;
45
+ this.restClient = new RestClient({
46
+ baseURL: this.baseURL,
47
+ headers: this.headers,
48
+ restClientConfig: params.restClientConfig,
49
+ });
50
+ this.analytics = new Analytics(agentParams);
51
+ this.launchUuid = '';
52
+ this.nonRetriedItemMap = new Map();
53
+ }
54
+
55
+ // eslint-disable-next-line valid-jsdoc
56
+ /**
57
+ *
58
+ * @Private
59
+ */
60
+ logDebug(msg) {
61
+ if (this.debug) {
62
+ console.log(msg);
63
+ }
64
+ }
65
+
66
+ calculateNonRetriedItemMapKey(launchId, parentId, name, itemId = '') {
67
+ return `${launchId}__${parentId}__${name}__${itemId}`;
68
+ }
69
+
70
+ getUniqId() {
71
+ return UniqId();
72
+ }
73
+
74
+ getRejectAnswer(tempId, error) {
75
+ return {
76
+ tempId,
77
+ promise: Promise.reject(error),
78
+ };
79
+ }
80
+
81
+ getNewItemObj(startPromiseFunc) {
82
+ let resolveFinish;
83
+ let rejectFinish;
84
+ const obj = {
85
+ promiseStart: (new Promise(startPromiseFunc)),
86
+ realId: '',
87
+ children: [],
88
+ finishSend: false,
89
+ promiseFinish: (new Promise((resolve, reject) => {
90
+ resolveFinish = resolve;
91
+ rejectFinish = reject;
92
+ })),
93
+ };
94
+ obj.resolveFinish = resolveFinish;
95
+ obj.rejectFinish = rejectFinish;
96
+ return obj;
97
+ }
98
+
99
+ // eslint-disable-next-line valid-jsdoc
100
+ /**
101
+ *
102
+ * @Private
103
+ */
104
+ cleanMap(ids) {
105
+ ids.forEach((id) => {
106
+ delete this.map[id];
107
+ });
108
+ }
109
+
110
+ checkConnect() {
111
+ const url = [this.config.endpoint.replace('/v2', '/v1'), 'user'].join('/');
112
+ return RestClient.request('GET', url, {}, { headers: this.headers });
113
+ }
114
+
115
+ triggerAnalyticsEvent() {
116
+ if (process.env.REPORTPORTAL_CLIENT_JS_NO_ANALYTICS) {
117
+ return;
118
+ }
119
+
120
+ if (this.analytics.agentParams) {
121
+ const label = getAgentEventLabel(this.analytics.agentParams);
122
+ this.analytics.trackEvent(Object.assign(CLIENT_JAVASCRIPT_EVENTS.START_LAUNCH, { label }));
123
+ } else {
124
+ this.analytics.trackEvent(CLIENT_JAVASCRIPT_EVENTS.START_LAUNCH);
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Start launch and report it.
130
+ * @param {Object} launchDataRQ - request object.
131
+ * launchDataRQ should look like this
132
+ * {
133
+ "description": "string" (support markdown),
134
+ "mode": "DEFAULT" or "DEBUG",
135
+ "name": "string",
136
+ "startTime": this.helper.now(),
137
+ "attributes": [
138
+ {
139
+ "key": "string",
140
+ "value": "string"
141
+ },
142
+ {
143
+ "value": "string"
144
+ }
145
+ ]
146
+ * }
147
+ * @Returns an object which contains a tempID and a promise
148
+ *
149
+ * As system attributes, this method sends the following data (these data are not for public use):
150
+ * client name, version;
151
+ * agent name, version (if given);
152
+ * browser name, version (if given);
153
+ * OS type, architecture;
154
+ * RAMSize;
155
+ * nodeJS version;
156
+ *
157
+ * This method works in two ways:
158
+ * First - If launchDataRQ object doesn't contain ID field,
159
+ * it would create a new Launch instance at the Report Portal with it ID.
160
+ * Second - If launchDataRQ would contain ID field,
161
+ * client would connect to the existing Launch which ID
162
+ * has been sent , and would send all data to it.
163
+ * Notice that Launch which ID has been sent must be 'IN PROGRESS' state at the Report Portal
164
+ * or it would throw an error.
165
+ * @Returns {Object} - an object which contains a tempID and a promise
166
+ */
167
+ startLaunch(launchDataRQ) {
168
+ const tempId = this.getUniqId();
169
+
170
+ if (launchDataRQ.id) {
171
+ this.map[tempId] = this.getNewItemObj((resolve) => resolve(launchDataRQ));
172
+ this.map[tempId].realId = launchDataRQ.id;
173
+ this.launchUuid = launchDataRQ.id;
174
+ } else {
175
+ const systemAttr = helpers.getSystemAttribute();
176
+ const attributes = Array.isArray(launchDataRQ.attributes)
177
+ ? launchDataRQ.attributes.concat(systemAttr)
178
+ : systemAttr;
179
+ const launchData = {
180
+ name: this.config.launch || 'Test launch name',
181
+ startTime: this.helpers.now(),
182
+ ...launchDataRQ,
183
+ attributes,
184
+ };
185
+
186
+ this.map[tempId] = this.getNewItemObj((resolve, reject) => {
187
+ const url = 'launch';
188
+ this.logDebug(`Start launch ${tempId}`);
189
+ this.restClient.create(url, launchData, { headers: this.headers })
190
+ .then((response) => {
191
+ this.map[tempId].realId = response.id;
192
+ this.launchUuid = response.id;
193
+
194
+ if (this.isLaunchMergeRequired) {
195
+ helpers.saveLaunchIdToFile(response.id);
196
+ }
197
+
198
+ resolve(response);
199
+ }, (error) => {
200
+ console.dir(error);
201
+ reject(error);
202
+ });
203
+ });
204
+ }
205
+ this.triggerAnalyticsEvent();
206
+ return {
207
+ tempId,
208
+ promise: this.map[tempId].promiseStart,
209
+ };
210
+ }
211
+
212
+ /**
213
+ * Finish launch.
214
+ * @param {string} launchTempId - temp launch id (returned in the query "startLaunch").
215
+ * @param {Object} finishExecutionRQ - finish launch info should include time and status.
216
+ * finishExecutionRQ should look like this
217
+ * {
218
+ * "endTime": this.helper.now(),
219
+ * "status": "passed" or one of ‘passed’, ‘failed’, ‘stopped’, ‘skipped’, ‘interrupted’, ‘cancelled’
220
+ * }
221
+ * @Returns {Object} - an object which contains a tempID and a promise
222
+ */
223
+ finishLaunch(launchTempId, finishExecutionRQ) {
224
+ const launchObj = this.map[launchTempId];
225
+ if (!launchObj) {
226
+ return this.getRejectAnswer(launchTempId, new Error(`Launch "${launchTempId}" not found`));
227
+ }
228
+
229
+ const finishExecutionData = { endTime: this.helpers.now(), ...finishExecutionRQ };
230
+
231
+ launchObj.finishSend = true;
232
+ Promise.all(launchObj.children.map((itemId) => this.map[itemId].promiseFinish))
233
+ .then(() => {
234
+ launchObj.promiseStart
235
+ .then(() => {
236
+ this.logDebug(`Finish launch ${launchTempId}`);
237
+ const url = ['launch', launchObj.realId, 'finish'].join('/');
238
+ this.restClient.update(url, finishExecutionData, { headers: this.headers })
239
+ .then((response) => {
240
+ this.logDebug(`Success finish launch ${launchTempId}`);
241
+ launchObj.resolveFinish(response);
242
+ }, (error) => {
243
+ this.logDebug(`Error finish launch ${launchTempId}`);
244
+ console.dir(error);
245
+ launchObj.rejectFinish(error);
246
+ });
247
+ }, (error) => {
248
+ launchObj.rejectFinish(error);
249
+ });
250
+ }, (error) => {
251
+ launchObj.rejectFinish(error);
252
+ });
253
+
254
+ return {
255
+ tempId: launchTempId,
256
+ promise: launchObj.promiseFinish,
257
+ };
258
+ }
259
+
260
+ /*
261
+ * This method is used to create data object for merge request to ReportPortal.
262
+ *
263
+ * @Returns {Object} - an object which contains a data for merge launches in ReportPortal.
264
+ */
265
+ getMergeLaunchesRequest(launchIds) {
266
+ return {
267
+ description: "Merged launch",
268
+ endTime: this.helpers.now(),
269
+ extendSuitesDescription: true,
270
+ launches: launchIds,
271
+ mergeType: "BASIC",
272
+ mode: "DEFAULT",
273
+ name: this.config.launch || 'Test launch name',
274
+ attributes: this.config.attributes,
275
+ };
276
+ }
277
+
278
+ /*
279
+ * This method is used for merge launches in ReportPortal.
280
+ *
281
+ * Please, keep in mind that this method is work only in case
282
+ * the option isLaunchMergeRequired is true.
283
+ */
284
+ mergeLaunches() {
285
+ if (this.isLaunchMergeRequired) {
286
+ const launchUUIds = helpers.readLaunchesFromFile();
287
+ const params = new URLSearchParams({
288
+ 'filter.in.uuid': launchUUIds,
289
+ });
290
+ const launchSearchUrl = `launch?${params.toString()}`;
291
+ return this.restClient.retrieveSyncAPI(launchSearchUrl, { headers: this.headers })
292
+ .then((response) => {
293
+ const launchIds = response.content.map((launch) => launch.id);
294
+ this.logDebug(`Found launches: ${launchIds}`);
295
+ return launchIds;
296
+ }, (error) => {
297
+ console.dir(error);
298
+ })
299
+ .then((launchIds) => {
300
+ const request = this.getMergeLaunchesRequest(launchIds);
301
+ const mergeURL = 'launch/merge';
302
+ return this.restClient.create(mergeURL, request, { headers: this.headers });
303
+ })
304
+ .then(() => {
305
+ this.logDebug(`Launches successfully merged!`);
306
+ })
307
+ .catch((error) => {
308
+ this.logDebug('ERROR');
309
+ this.logDebug(error);
310
+ });
311
+ }
312
+ this.logDebug('Option isLaunchMergeRequired is false');
313
+ }
314
+
315
+ /*
316
+ * This method is used for frameworks as Jasmine. There is problem when
317
+ * it doesn't wait for promise resolve and stop the process. So it better to call
318
+ * this method at the spec's function as @afterAll() and manually resolve this promise.
319
+ *
320
+ * @return Promise
321
+ */
322
+ getPromiseFinishAllItems(launchTempId) {
323
+ const launchObj = this.map[launchTempId];
324
+ return Promise.all(launchObj.children.map((itemId) => this.map[itemId].promiseFinish));
325
+ }
326
+
327
+ /**
328
+ * Update launch.
329
+ * @param {string} launchTempId - temp launch id (returned in the query "startLaunch").
330
+ * @param {Object} launchData - new launch data
331
+ * launchData should look like this
332
+ * {
333
+ "description": "string" (support markdown),
334
+ "mode": "DEFAULT" or "DEBUG",
335
+ "attributes": [
336
+ {
337
+ "key": "string",
338
+ "value": "string"
339
+ },
340
+ {
341
+ "value": "string"
342
+ }
343
+ ]
344
+ }
345
+ * @Returns {Object} - an object which contains a tempId and a promise
346
+ */
347
+ updateLaunch(launchTempId, launchData) {
348
+ const launchObj = this.map[launchTempId];
349
+ if (!launchObj) {
350
+ return this.getRejectAnswer(launchTempId, new Error(`Launch "${launchTempId}" not found`));
351
+ }
352
+ let resolvePromise;
353
+ let rejectPromise;
354
+ const promise = new Promise((resolve, reject) => {
355
+ resolvePromise = resolve;
356
+ rejectPromise = reject;
357
+ });
358
+
359
+ launchObj.promiseFinish.then(() => {
360
+ const url = ['launch', launchObj.realId, 'update'].join('/');
361
+ this.restClient.update(url, launchData, { headers: this.headers })
362
+ .then((response) => {
363
+ resolvePromise(response);
364
+ }, (error) => {
365
+ rejectPromise(error);
366
+ });
367
+ }, (error) => {
368
+ rejectPromise(error);
369
+ });
370
+ return {
371
+ tempId: launchTempId,
372
+ promise,
373
+ };
374
+ }
375
+
376
+ /**
377
+ * If there is no parentItemId starts Suite, else starts test or item.
378
+ * @param {Object} testItemDataRQ - object with item parameters
379
+ * testItemDataRQ should look like this
380
+ * {
381
+ "description": "string" (support markdown),
382
+ "name": "string",
383
+ "startTime": this.helper.now(),
384
+ "attributes": [
385
+ {
386
+ "key": "string",
387
+ "value": "string"
388
+ },
389
+ {
390
+ "value": "string"
391
+ }
392
+ ],
393
+ "type": 'SUITE' or one of 'SUITE', 'STORY', 'TEST',
394
+ 'SCENARIO', 'STEP', 'BEFORE_CLASS', 'BEFORE_GROUPS',
395
+ 'BEFORE_METHOD', 'BEFORE_SUITE', 'BEFORE_TEST',
396
+ 'AFTER_CLASS', 'AFTER_GROUPS', 'AFTER_METHOD',
397
+ 'AFTER_SUITE', 'AFTER_TEST'
398
+ }
399
+ * @param {string} launchTempId - temp launch id (returned in the query "startLaunch").
400
+ * @param {string} parentTempId (optional) - temp item id (returned in the query "startTestItem").
401
+ * @Returns {Object} - an object which contains a tempId and a promise
402
+ */
403
+ startTestItem(testItemDataRQ, launchTempId, parentTempId) {
404
+ let parentMapId = launchTempId;
405
+ const launchObj = this.map[launchTempId];
406
+ if (!launchObj) {
407
+ return this.getRejectAnswer(launchTempId, new Error(`Launch "${launchTempId}" not found`));
408
+ }
409
+ if (launchObj.finishSend) {
410
+ const err = new Error(`Launch "${launchTempId}" is already finished, you can not add an item to it`);
411
+ return this.getRejectAnswer(launchTempId, err);
412
+ }
413
+
414
+ const testCaseId = testItemDataRQ.testCaseId
415
+ || helpers.generateTestCaseId(testItemDataRQ.codeRef, testItemDataRQ.parameters);
416
+ const testItemData = { startTime: this.helpers.now(), ...testItemDataRQ, ...(testCaseId && { testCaseId }) };
417
+
418
+ let parentPromise = launchObj.promiseStart;
419
+ if (parentTempId) {
420
+ parentMapId = parentTempId;
421
+ const parentObj = this.map[parentTempId];
422
+ if (!parentObj) {
423
+ return this.getRejectAnswer(launchTempId, new Error(`Item "${parentTempId}" not found`));
424
+ }
425
+ parentPromise = parentObj.promiseStart;
426
+ }
427
+
428
+ const itemKey = this.calculateNonRetriedItemMapKey(
429
+ launchTempId,
430
+ parentTempId,
431
+ testItemDataRQ.name,
432
+ testItemDataRQ.uniqueId,
433
+ );
434
+ const firstNonRetriedItemPromise = testItemDataRQ.retry && this.nonRetriedItemMap.get(itemKey);
435
+ if (firstNonRetriedItemPromise) {
436
+ parentPromise = Promise.all([parentPromise, firstNonRetriedItemPromise]);
437
+ }
438
+
439
+ const tempId = this.getUniqId();
440
+ this.map[tempId] = this.getNewItemObj((resolve, reject) => {
441
+ parentPromise.then(() => {
442
+ const realLaunchId = this.map[launchTempId].realId;
443
+ let url = 'item/';
444
+ if (parentTempId) {
445
+ const realParentId = this.map[parentTempId].realId;
446
+ url += `${realParentId}`;
447
+ }
448
+ testItemData.launchUuid = realLaunchId;
449
+ this.logDebug(`Start test item ${tempId}`);
450
+ this.restClient.create(url, testItemData, { headers: this.headers })
451
+ .then((response) => {
452
+ this.logDebug(`Success start item ${tempId}`);
453
+ this.map[tempId].realId = response.id;
454
+ this.nonRetriedItemMap.delete(itemKey);
455
+ resolve(response);
456
+ }, (error) => {
457
+ this.logDebug(`Error start item ${tempId}:`);
458
+ console.dir(error);
459
+ reject(error);
460
+ });
461
+ }, (error) => {
462
+ reject(error);
463
+ });
464
+ });
465
+ this.map[parentMapId].children.push(tempId);
466
+
467
+ if (!testItemDataRQ.retry) {
468
+ this.nonRetriedItemMap.set(itemKey, this.map[tempId].promiseStart);
469
+ }
470
+
471
+ return {
472
+ tempId,
473
+ promise: this.map[tempId].promiseStart,
474
+ };
475
+ }
476
+
477
+ /**
478
+ * Finish Suite or Step level.
479
+ * @param {string} itemTempId - temp item id (returned in the query "startTestItem").
480
+ * @param {Object} finishTestItemRQ - object with item parameters.
481
+ * finishTestItemRQ should look like this
482
+ {
483
+ "endTime": this.helper.now(),
484
+ "issue": {
485
+ "comment": "string",
486
+ "externalSystemIssues": [
487
+ {
488
+ "submitDate": 0,
489
+ "submitter": "string",
490
+ "systemId": "string",
491
+ "ticketId": "string",
492
+ "url": "string"
493
+ }
494
+ ],
495
+ "issueType": "string"
496
+ },
497
+ "status": "passed" or one of 'passed', 'failed', 'stopped', 'skipped', 'interrupted', 'cancelled'
498
+ }
499
+ * @Returns {Object} - an object which contains a tempId and a promise
500
+ */
501
+ finishTestItem(itemTempId, finishTestItemRQ) {
502
+ const itemObj = this.map[itemTempId];
503
+ if (!itemObj) {
504
+ return this.getRejectAnswer(itemTempId, new Error(`Item "${itemTempId}" not found`));
505
+ }
506
+
507
+ const finishTestItemData = {
508
+ endTime: this.helpers.now(),
509
+ ...(itemObj.children.length ? {} : { status: RP_STATUSES.PASSED }),
510
+ ...finishTestItemRQ,
511
+ };
512
+
513
+ itemObj.finishSend = true;
514
+ Promise.all(itemObj.children.map((itemId) => this.map[itemId] && this.map[itemId].promiseFinish))
515
+ .then(() => {
516
+ this.cleanMap(itemObj.children);
517
+ this.finishTestItemPromiseStart(
518
+ itemObj,
519
+ itemTempId,
520
+ Object.assign(finishTestItemData, { launchUuid: this.launchUuid }),
521
+ );
522
+ }, () => {
523
+ this.cleanMap(itemObj.children);
524
+ this.logDebug(`Error finish children of test item ${itemTempId}`);
525
+ this.logDebug(`Finish test item ${itemTempId}`);
526
+ this.finishTestItemPromiseStart(
527
+ itemObj,
528
+ itemTempId,
529
+ Object.assign(finishTestItemData, { launchUuid: this.launchUuid }),
530
+ );
531
+ });
532
+
533
+ return {
534
+ tempId: itemTempId,
535
+ promise: itemObj.promiseFinish,
536
+ };
537
+ }
538
+
539
+ saveLog(itemObj, requestPromiseFunc) {
540
+ const tempId = this.getUniqId();
541
+ this.map[tempId] = this.getNewItemObj((resolve, reject) => {
542
+ itemObj.promiseStart.then(() => {
543
+ this.logDebug(`Save log ${tempId}`);
544
+ requestPromiseFunc(itemObj.realId, this.launchUuid).then((response) => {
545
+ this.logDebug(`Successfully save log ${tempId}`);
546
+ resolve(response);
547
+ }, (error) => {
548
+ this.logDebug(`Error finish log: ${error}`);
549
+ reject(error);
550
+ });
551
+ }, (error) => {
552
+ reject(error);
553
+ });
554
+ });
555
+ itemObj.children.push(tempId);
556
+
557
+ const logObj = this.map[tempId];
558
+ logObj.finishSend = true;
559
+ logObj.promiseStart.then((response) => logObj.resolveFinish(response), (error) => logObj.rejectFinish(error));
560
+
561
+ return {
562
+ tempId,
563
+ promise: this.map[tempId].promiseFinish,
564
+ };
565
+ }
566
+
567
+ sendLog(itemTempId, saveLogRQ, fileObj) {
568
+ const saveLogData = {
569
+ time: this.helpers.now(),
570
+ message: '',
571
+ level: '',
572
+ ...saveLogRQ,
573
+ };
574
+
575
+ if (fileObj) {
576
+ return this.sendLogWithFile(itemTempId, saveLogData, fileObj);
577
+ }
578
+ return this.sendLogWithoutFile(itemTempId, saveLogData);
579
+ }
580
+
581
+ /**
582
+ * Send log of test results.
583
+ * @param {string} itemTempId - temp item id (returned in the query "startTestItem").
584
+ * @param {Object} saveLogRQ - object with data of test result.
585
+ * saveLogRQ should look like this
586
+ * {
587
+ * level: 'error' or one of 'trace', 'debug', 'info', 'warn', 'error', '',
588
+ * message: 'string' (support markdown),
589
+ * time: this.helpers.now()
590
+ * }
591
+ * @Returns {Object} - an object which contains a tempId and a promise
592
+ */
593
+ sendLogWithoutFile(itemTempId, saveLogRQ) {
594
+ const itemObj = this.map[itemTempId];
595
+ if (!itemObj) {
596
+ return this.getRejectAnswer(itemTempId, new Error(`Item "${itemTempId}" not found`));
597
+ }
598
+
599
+ const requestPromise = (itemUuid, launchUuid) => {
600
+ const url = 'log';
601
+ const isItemUuid = itemUuid !== launchUuid;
602
+ return this.restClient.create(
603
+ url,
604
+ Object.assign(
605
+ saveLogRQ,
606
+ { launchUuid },
607
+ isItemUuid && { itemUuid },
608
+ ),
609
+ { headers: this.headers },
610
+ );
611
+ };
612
+ return this.saveLog(itemObj, requestPromise);
613
+ }
614
+
615
+ /**
616
+ * Send log of test results with file.
617
+ * @param {string} itemTempId - temp item id (returned in the query "startTestItem").
618
+ * @param {Object} saveLogRQ - object with data of test result.
619
+ * saveLogRQ should look like this
620
+ * {
621
+ * level: 'error' or one of 'trace', 'debug', 'info', 'warn', 'error', '',
622
+ * message: 'string' (support markdown),
623
+ * time: this.helpers.now()
624
+ * }
625
+ * @param {Object} fileObj - object with file data.
626
+ * fileObj should look like this
627
+ * {
628
+ name: 'string',
629
+ type: "image/png" or your file mimeType
630
+ (supported types: 'image/*', application/ ['xml', 'javascript', 'json', 'css', 'php'],
631
+ another format will be opened in a new browser tab ),
632
+ content: file
633
+ * }
634
+ * @Returns {Object} - an object which contains a tempId and a promise
635
+ */
636
+ sendLogWithFile(itemTempId, saveLogRQ, fileObj) {
637
+ const itemObj = this.map[itemTempId];
638
+ if (!itemObj) {
639
+ return this.getRejectAnswer(itemTempId, new Error(`Item "${itemTempId}" not found`));
640
+ }
641
+ // eslint-disable-next-line max-len
642
+ const requestPromise = (itemUuid, launchUuid) => {
643
+ const isItemUuid = itemUuid !== launchUuid;
644
+
645
+ // eslint-disable-next-line max-len
646
+ return this.getRequestLogWithFile(Object.assign(saveLogRQ, { launchUuid }, isItemUuid && { itemUuid }), fileObj);
647
+ };
648
+
649
+ return this.saveLog(itemObj, requestPromise);
650
+ }
651
+
652
+ getRequestLogWithFile(saveLogRQ, fileObj) {
653
+ const url = 'log';
654
+ // eslint-disable-next-line no-param-reassign
655
+ saveLogRQ.file = { name: fileObj.name };
656
+ return this.restClient.create(
657
+ url,
658
+ this.buildMultiPartStream([saveLogRQ], fileObj, MULTIPART_BOUNDARY),
659
+ {
660
+ headers: { ...this.headers, 'Content-Type': `multipart/form-data; boundary=${MULTIPART_BOUNDARY}` },
661
+ },
662
+ )
663
+ .then((response) => response)
664
+ .catch((error) => {
665
+ this.logDebug('ERROR');
666
+ this.logDebug(error);
667
+ });
668
+ }
669
+
670
+ // eslint-disable-next-line valid-jsdoc
671
+ /**
672
+ *
673
+ * @Private
674
+ */
675
+ buildMultiPartStream(jsonPart, filePart, boundary) {
676
+ const eol = "\r\n";
677
+ const bx = `--${boundary}`;
678
+ const buffers = [
679
+ // eslint-disable-next-line function-paren-newline
680
+ Buffer.from(
681
+ // eslint-disable-next-line prefer-template
682
+ bx + eol + "Content-Disposition: form-data; name=\"json_request_part\""
683
+ + eol + "Content-Type: application/json" + eol
684
+ + eol + eol + JSON.stringify(jsonPart) + eol,
685
+ ),
686
+ // eslint-disable-next-line function-paren-newline
687
+ Buffer.from(
688
+ // eslint-disable-next-line prefer-template
689
+ bx + eol + "Content-Disposition: form-data; name=\"file\"; filename=\"" + filePart.name + "\"" + eol
690
+ + "Content-Type: " + filePart.type + eol + eol,
691
+ ),
692
+ Buffer.from(filePart.content, 'base64'),
693
+ Buffer.from(`${eol + bx}--${eol}`),
694
+ ];
695
+ return Buffer.concat(buffers);
696
+ }
697
+
698
+ finishTestItemPromiseStart(itemObj, itemTempId, finishTestItemData) {
699
+ itemObj.promiseStart
700
+ .then(() => {
701
+ const url = ['item', itemObj.realId].join('/');
702
+ this.logDebug(`Finish test item ${itemTempId}`);
703
+ // eslint-disable-next-line max-len
704
+ this.restClient.update(url, Object.assign(finishTestItemData, { launchUuid: this.launchUuid }), { headers: this.headers })
705
+ .then((response) => {
706
+ this.logDebug(`Success finish item ${itemTempId}`);
707
+ itemObj.resolveFinish(response);
708
+ }, (error) => {
709
+ this.logDebug(`Error finish test item ${itemTempId}`);
710
+ console.dir(error);
711
+ itemObj.rejectFinish(error);
712
+ });
713
+ }, (error) => {
714
+ itemObj.rejectFinish(error);
715
+ });
716
+ }
717
+ }
718
+
719
+ module.exports = RPClient;