@elisra-devops/docgen-data-provider 1.21.0 → 1.23.0

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.
Files changed (49) hide show
  1. package/bin/helpers/helper.js.map +1 -1
  2. package/bin/helpers/test/tfs.test.d.ts +1 -0
  3. package/bin/helpers/test/tfs.test.js +613 -0
  4. package/bin/helpers/test/tfs.test.js.map +1 -0
  5. package/bin/helpers/tfs.js +4 -8
  6. package/bin/helpers/tfs.js.map +1 -1
  7. package/bin/modules/GitDataProvider.js.map +1 -1
  8. package/bin/modules/PipelinesDataProvider.js +3 -2
  9. package/bin/modules/PipelinesDataProvider.js.map +1 -1
  10. package/bin/modules/ResultDataProvider.d.ts +199 -17
  11. package/bin/modules/ResultDataProvider.js +611 -195
  12. package/bin/modules/ResultDataProvider.js.map +1 -1
  13. package/bin/modules/TestDataProvider.js +7 -7
  14. package/bin/modules/TestDataProvider.js.map +1 -1
  15. package/bin/modules/TicketsDataProvider.d.ts +1 -1
  16. package/bin/modules/TicketsDataProvider.js +3 -2
  17. package/bin/modules/TicketsDataProvider.js.map +1 -1
  18. package/bin/modules/test/JfrogDataProvider.test.d.ts +1 -0
  19. package/bin/modules/test/JfrogDataProvider.test.js +110 -0
  20. package/bin/modules/test/JfrogDataProvider.test.js.map +1 -0
  21. package/bin/modules/test/ResultDataProvider.test.d.ts +1 -0
  22. package/bin/modules/test/ResultDataProvider.test.js +478 -0
  23. package/bin/modules/test/ResultDataProvider.test.js.map +1 -0
  24. package/bin/modules/test/gitDataProvider.test.js +424 -120
  25. package/bin/modules/test/gitDataProvider.test.js.map +1 -1
  26. package/bin/modules/test/managmentDataProvider.test.js +283 -28
  27. package/bin/modules/test/managmentDataProvider.test.js.map +1 -1
  28. package/bin/modules/test/pipelineDataProvider.test.js +229 -45
  29. package/bin/modules/test/pipelineDataProvider.test.js.map +1 -1
  30. package/bin/modules/test/testDataProvider.test.js +225 -81
  31. package/bin/modules/test/testDataProvider.test.js.map +1 -1
  32. package/bin/modules/test/ticketsDataProvider.test.js +310 -82
  33. package/bin/modules/test/ticketsDataProvider.test.js.map +1 -1
  34. package/package.json +1 -1
  35. package/src/helpers/helper.ts +16 -14
  36. package/src/helpers/test/tfs.test.ts +748 -0
  37. package/src/helpers/tfs.ts +4 -8
  38. package/src/modules/GitDataProvider.ts +10 -10
  39. package/src/modules/PipelinesDataProvider.ts +2 -2
  40. package/src/modules/ResultDataProvider.ts +815 -260
  41. package/src/modules/TestDataProvider.ts +8 -8
  42. package/src/modules/TicketsDataProvider.ts +5 -9
  43. package/src/modules/test/JfrogDataProvider.test.ts +171 -0
  44. package/src/modules/test/ResultDataProvider.test.ts +581 -0
  45. package/src/modules/test/gitDataProvider.test.ts +671 -187
  46. package/src/modules/test/managmentDataProvider.test.ts +386 -26
  47. package/src/modules/test/pipelineDataProvider.test.ts +281 -52
  48. package/src/modules/test/testDataProvider.test.ts +307 -105
  49. package/src/modules/test/ticketsDataProvider.test.ts +425 -129
@@ -15,6 +15,28 @@ const tfs_1 = require("../helpers/tfs");
15
15
  const logger_1 = require("../utils/logger");
16
16
  const testStepParserHelper_1 = require("../utils/testStepParserHelper");
17
17
  const pLimit = require('p-limit');
18
+ /**
19
+ * Provides methods to fetch, process, and summarize test data from Azure DevOps.
20
+ *
21
+ * This class includes functionalities for:
22
+ * - Fetching test suites, test points, and test cases.
23
+ * - Aligning test steps with iterations and generating detailed results.
24
+ * - Fetching result data based on work items and test runs.
25
+ * - Summarizing test group results, test results, and detailed results.
26
+ * - Fetching linked work items and open PCRs (Problem Change Requests).
27
+ * - Generating test logs and mapping attachments for download.
28
+ * - Supporting test reporter functionalities with customizable field selection and filtering.
29
+ *
30
+ * Key Features:
31
+ * - Hierarchical and flat test suite processing.
32
+ * - Step-level and test-level result alignment.
33
+ * - Customizable result summaries and detailed reports.
34
+ * - Integration with Azure DevOps APIs for fetching and processing test data.
35
+ * - Support for additional configurations like open PCRs, test logs, and step execution analysis.
36
+ *
37
+ * Usage:
38
+ * Instantiate the class with the organization URL and token, and use the provided methods to fetch and process test data.
39
+ */
18
40
  class ResultDataProvider {
19
41
  constructor(orgUrl, token) {
20
42
  this.orgUrl = '';
@@ -41,7 +63,200 @@ class ResultDataProvider {
41
63
  this.testStepParserHelper = new testStepParserHelper_1.default(orgUrl, token);
42
64
  }
43
65
  /**
44
- * Retrieves test suites by test plan ID and processes them into a flat structure with hierarchy names.
66
+ * Combines the results of test group result summary, test results summary, and detailed results summary into a single key-value pair array.
67
+ */
68
+ async getCombinedResultsSummary(testPlanId, projectName, selectedSuiteIds, addConfiguration = false, isHierarchyGroupName = false, includeOpenPCRs = false, includeTestLog = false, stepExecution, stepAnalysis, includeHardCopyRun = false) {
69
+ const combinedResults = [];
70
+ try {
71
+ // Fetch test suites
72
+ const suites = await this.fetchTestSuites(testPlanId, projectName, selectedSuiteIds, isHierarchyGroupName);
73
+ // Prepare test data for summaries
74
+ const testPointsPromises = suites.map((suite) => this.limit(() => this.fetchTestPoints(projectName, testPlanId, suite.testSuiteId)
75
+ .then((testPointsItems) => (Object.assign(Object.assign({}, suite), { testPointsItems })))
76
+ .catch((error) => {
77
+ logger_1.default.error(`Error occurred for suite ${suite.testSuiteId}: ${error.message}`);
78
+ return Object.assign(Object.assign({}, suite), { testPointsItems: [] });
79
+ })));
80
+ const testPoints = await Promise.all(testPointsPromises);
81
+ // 1. Calculate Test Group Result Summary
82
+ const summarizedResults = testPoints
83
+ .filter((testPoint) => testPoint.testPointsItems && testPoint.testPointsItems.length > 0)
84
+ .map((testPoint) => {
85
+ const groupResultSummary = this.calculateGroupResultSummary(testPoint.testPointsItems || [], includeHardCopyRun);
86
+ return Object.assign(Object.assign({}, testPoint), { groupResultSummary });
87
+ });
88
+ const totalSummary = this.calculateTotalSummary(summarizedResults, includeHardCopyRun);
89
+ const testGroupArray = summarizedResults.map((item) => (Object.assign({ testGroupName: item.testGroupName }, item.groupResultSummary)));
90
+ testGroupArray.push(Object.assign({ testGroupName: 'Total' }, totalSummary));
91
+ // Add test group result summary to combined results
92
+ combinedResults.push({
93
+ contentControl: 'test-group-summary-content-control',
94
+ data: testGroupArray,
95
+ skin: 'test-result-test-group-summary-table',
96
+ });
97
+ // 2. Calculate Test Results Summary
98
+ const flattenedTestPoints = this.flattenTestPoints(testPoints);
99
+ const testResultsSummary = flattenedTestPoints.map((testPoint) => this.formatTestResult(testPoint, addConfiguration, includeHardCopyRun));
100
+ // Add test results summary to combined results
101
+ combinedResults.push({
102
+ contentControl: 'test-result-summary-content-control',
103
+ data: testResultsSummary,
104
+ skin: 'test-result-table',
105
+ });
106
+ // 3. Calculate Detailed Results Summary
107
+ const testData = await this.fetchTestData(suites, projectName, testPlanId);
108
+ const runResults = await this.fetchAllResultData(testData, projectName);
109
+ const detailedStepResultsSummary = this.alignStepsWithIterations(testData, runResults);
110
+ //Filter out all the results with no comment
111
+ const filteredDetailedResults = detailedStepResultsSummary.filter((result) => result && (result.stepComments !== '' || result.stepStatus === 'Failed'));
112
+ // Add detailed results summary to combined results
113
+ combinedResults.push({
114
+ contentControl: 'detailed-test-result-content-control',
115
+ data: !includeHardCopyRun ? filteredDetailedResults : [],
116
+ skin: 'detailed-test-result-table',
117
+ });
118
+ if (includeOpenPCRs) {
119
+ //5. Open PCRs data (only if enabled)
120
+ await this.fetchOpenPcrData(testResultsSummary, projectName, combinedResults);
121
+ }
122
+ //6. Test Log (only if enabled)
123
+ if (includeTestLog) {
124
+ this.fetchTestLogData(flattenedTestPoints, combinedResults);
125
+ }
126
+ if (stepAnalysis && stepAnalysis.isEnabled) {
127
+ const mappedAnalysisData = runResults.filter((result) => {
128
+ var _a, _b, _c;
129
+ return result.comment ||
130
+ ((_b = (_a = result.iteration) === null || _a === void 0 ? void 0 : _a.attachments) === null || _b === void 0 ? void 0 : _b.length) > 0 ||
131
+ ((_c = result.analysisAttachments) === null || _c === void 0 ? void 0 : _c.length) > 0;
132
+ });
133
+ const mappedAnalysisResultData = stepAnalysis.generateRunAttachments.isEnabled
134
+ ? this.mapAttachmentsUrl(mappedAnalysisData, projectName)
135
+ : mappedAnalysisData;
136
+ if ((mappedAnalysisResultData === null || mappedAnalysisResultData === void 0 ? void 0 : mappedAnalysisResultData.length) > 0) {
137
+ combinedResults.push({
138
+ contentControl: 'appendix-a-content-control',
139
+ data: mappedAnalysisResultData,
140
+ skin: 'step-analysis-appendix-skin',
141
+ });
142
+ }
143
+ }
144
+ if (stepExecution && stepExecution.isEnabled) {
145
+ const mappedAnalysisData = stepExecution.generateAttachments.isEnabled &&
146
+ stepExecution.generateAttachments.runAttachmentMode !== 'planOnly'
147
+ ? runResults.filter((result) => { var _a, _b; return ((_b = (_a = result.iteration) === null || _a === void 0 ? void 0 : _a.attachments) === null || _b === void 0 ? void 0 : _b.length) > 0; })
148
+ : [];
149
+ const mappedAnalysisResultData = mappedAnalysisData.length > 0 ? this.mapAttachmentsUrl(mappedAnalysisData, projectName) : [];
150
+ const mappedDetailedResults = this.mapStepResultsForExecutionAppendix(detailedStepResultsSummary, mappedAnalysisResultData);
151
+ combinedResults.push({
152
+ contentControl: 'appendix-b-content-control',
153
+ data: mappedDetailedResults,
154
+ skin: 'step-execution-appendix-skin',
155
+ });
156
+ }
157
+ return combinedResults;
158
+ }
159
+ catch (error) {
160
+ logger_1.default.error(`Error during getCombinedResultsSummary: ${error.message}`);
161
+ if (error.response) {
162
+ logger_1.default.error(`Response Data: ${JSON.stringify(error.response.data)}`);
163
+ }
164
+ // Ensure the error is rethrown to propagate it correctly
165
+ throw new Error(error.message || 'Unknown error occurred during getCombinedResultsSummary');
166
+ }
167
+ }
168
+ /**
169
+ * Fetches and processes test reporter results for a given test plan and project.
170
+ *
171
+ * @param testPlanId - The ID of the test plan to fetch results for.
172
+ * @param projectName - The name of the project associated with the test plan.
173
+ * @param selectedSuiteIds - An array of suite IDs to filter the test results.
174
+ * @param selectedFields - An array of field names to include in the results.
175
+ * @param enableRunStepStatusFilter - A flag to enable filtering out test steps with a "Not Run" status.
176
+ * @returns A promise that resolves to an array of test reporter results, formatted for use in a test-reporter-table.
177
+ *
178
+ * @throws Will log an error if any step in the process fails.
179
+ */
180
+ async getTestReporterResults(testPlanId, projectName, selectedSuiteIds, selectedFields, enableRunStepStatusFilter) {
181
+ const fetchedTestResults = [];
182
+ logger_1.default.debug(`Fetching test reporter results for test plan ID: ${testPlanId}, project name: ${projectName}`);
183
+ logger_1.default.debug(`Selected suite IDs: ${selectedSuiteIds}`);
184
+ try {
185
+ const plan = await this.fetchTestPlanName(testPlanId, projectName);
186
+ const suites = await this.fetchTestSuites(testPlanId, projectName, selectedSuiteIds, true);
187
+ const testData = await this.fetchTestData(suites, projectName, testPlanId);
188
+ const runResults = await this.fetchAllResultDataTestReporter(testData, projectName, selectedFields);
189
+ const testReporterData = this.alignStepsWithIterationsTestReporter(testData, runResults, selectedFields);
190
+ const isNotRunStep = (result) => {
191
+ return result && result.stepStatus === 'Not Run';
192
+ };
193
+ // Apply filters sequentially based on enabled flags
194
+ let filteredResults = testReporterData;
195
+ // filter: Test step run status
196
+ if (enableRunStepStatusFilter) {
197
+ filteredResults = filteredResults.filter((result) => !isNotRunStep(result));
198
+ }
199
+ // Use the final filtered results
200
+ fetchedTestResults.push({
201
+ contentControl: 'test-reporter-table',
202
+ customName: `Test Results for ${plan}`,
203
+ data: filteredResults || [],
204
+ skin: 'test-reporter-table',
205
+ });
206
+ return fetchedTestResults;
207
+ }
208
+ catch (error) {
209
+ logger_1.default.error(`Error during getTestReporterResults: ${error.message}`);
210
+ }
211
+ }
212
+ /**
213
+ * Mapping each attachment to a proper URL for downloading it
214
+ * @param runResults Array of run results
215
+ */
216
+ mapAttachmentsUrl(runResults, project) {
217
+ return runResults.map((result) => {
218
+ var _a;
219
+ if (!result.iteration) {
220
+ return result;
221
+ }
222
+ const { iteration, analysisAttachments } = result, restResult = __rest(result, ["iteration", "analysisAttachments"]);
223
+ //add downloadUri field for each attachment
224
+ const baseDownloadUrl = `${this.orgUrl}${project}/_apis/test/runs/${result.lastRunId}/results/${result.lastResultId}/attachments`;
225
+ if (iteration && ((_a = iteration.attachments) === null || _a === void 0 ? void 0 : _a.length) > 0) {
226
+ const { attachments, actionResults } = iteration, restOfIteration = __rest(iteration, ["attachments", "actionResults"]);
227
+ const attachmentPathToIndexMap = this.CreateAttachmentPathIndexMap(actionResults);
228
+ const mappedAttachments = attachments.map((attachment) => (Object.assign(Object.assign({}, attachment), { stepNo: attachmentPathToIndexMap.has(attachment.actionPath)
229
+ ? attachmentPathToIndexMap.get(attachment.actionPath)
230
+ : undefined, downloadUrl: `${baseDownloadUrl}/${attachment.id}/${attachment.name}` })));
231
+ restResult.iteration = Object.assign(Object.assign({}, restOfIteration), { attachments: mappedAttachments });
232
+ }
233
+ if (analysisAttachments && analysisAttachments.length > 0) {
234
+ restResult.analysisAttachments = analysisAttachments.map((attachment) => (Object.assign(Object.assign({}, attachment), { downloadUrl: `${baseDownloadUrl}/${attachment.id}/${attachment.fileName}` })));
235
+ }
236
+ return Object.assign({}, restResult);
237
+ });
238
+ }
239
+ async fetchTestPlanName(testPlanId, teamProject) {
240
+ try {
241
+ const url = `${this.orgUrl}${teamProject}/_apis/testplan/Plans/${testPlanId}?api-version=5.1`;
242
+ const testPlan = await tfs_1.TFSServices.getItemContent(url, this.token);
243
+ return testPlan.name;
244
+ }
245
+ catch (error) {
246
+ logger_1.default.error(`Error during fetching Test Plan Name: ${error.message}`);
247
+ return '';
248
+ }
249
+ }
250
+ /**
251
+ * Fetches test suites for a given test plan and project, optionally filtering by selected suite IDs.
252
+ *
253
+ * @param testPlanId - The ID of the test plan to fetch suites for.
254
+ * @param projectName - The name of the project containing the test plan.
255
+ * @param selectedSuiteIds - An optional array of suite IDs to filter the results by.
256
+ * @param isHierarchyGroupName - A flag indicating whether to build the test group name hierarchically. Defaults to `true`.
257
+ * @returns A promise that resolves to an array of objects containing `testSuiteId` and `testGroupName`.
258
+ * Returns an empty array if no test suites are found or an error occurs.
259
+ * @throws Will log an error message if fetching test suites fails.
45
260
  */
46
261
  async fetchTestSuites(testPlanId, projectName, selectedSuiteIds, isHierarchyGroupName = true) {
47
262
  try {
@@ -117,6 +332,8 @@ class ResultDataProvider {
117
332
  currentSuite = parentSuite;
118
333
  }
119
334
  const parts = path.split('/');
335
+ if (parts.length - 1 === 1)
336
+ return parts[1];
120
337
  return parts.length > 3
121
338
  ? `${parts[1]}/.../${parts[parts.length - 1]}`
122
339
  : `${parts[1]}/${parts[parts.length - 1]}`;
@@ -128,7 +345,7 @@ class ResultDataProvider {
128
345
  try {
129
346
  const url = `${this.orgUrl}${projectName}/_apis/testplan/Plans/${testPlanId}/Suites/${testSuiteId}/TestPoint?includePointDetails=true`;
130
347
  const { value: testPoints, count } = await tfs_1.TFSServices.getItemContent(url, this.token);
131
- return count !== 0 ? testPoints.map(this.mapTestPoint) : [];
348
+ return count !== 0 ? testPoints.map((testPoint) => this.mapTestPoint(testPoint, projectName)) : [];
132
349
  }
133
350
  catch (error) {
134
351
  logger_1.default.error(`Error during fetching Test Points: ${error.message}`);
@@ -138,11 +355,12 @@ class ResultDataProvider {
138
355
  /**
139
356
  * Maps raw test point data to a simplified object.
140
357
  */
141
- mapTestPoint(testPoint) {
358
+ mapTestPoint(testPoint, projectName) {
142
359
  var _a, _b, _c, _d, _e;
143
360
  return {
144
361
  testCaseId: testPoint.testCaseReference.id,
145
362
  testCaseName: testPoint.testCaseReference.name,
363
+ testCaseUrl: `${this.orgUrl}${projectName}/_workitems/edit/${testPoint.testCaseReference.id}`,
146
364
  configurationName: (_a = testPoint.configuration) === null || _a === void 0 ? void 0 : _a.name,
147
365
  outcome: ((_b = testPoint.results) === null || _b === void 0 ? void 0 : _b.outcome) || 'Not Run',
148
366
  lastRunId: (_c = testPoint.results) === null || _c === void 0 ? void 0 : _c.lastTestRunId,
@@ -159,25 +377,103 @@ class ResultDataProvider {
159
377
  return testCases;
160
378
  }
161
379
  /**
162
- * Fetches iterations data by run and result IDs.
380
+ * Fetches result data based on a work item base (WiBase) for a specific test run and result.
381
+ *
382
+ * @param projectName - The name of the project in Azure DevOps.
383
+ * @param runId - The ID of the test run.
384
+ * @param resultId - The ID of the test result.
385
+ * @param options - Optional parameters for customizing the data retrieval.
386
+ * @param options.expandWorkItem - If true, expands all fields of the work item.
387
+ * @param options.selectedFields - An array of field names to filter the work item fields.
388
+ * @param options.processRelatedRequirements - If true, processes related requirements linked to the work item.
389
+ * @param options.includeFullErrorStack - If true, includes the full error stack in the logs when an error occurs.
390
+ * @returns A promise that resolves to an object containing the fetched result data, including:
391
+ * - `stepsResultXml`: The test steps result in XML format.
392
+ * - `analysisAttachments`: Attachments related to the test result analysis.
393
+ * - `testCaseRevision`: The revision number of the test case.
394
+ * - `filteredFields`: The filtered fields from the work item based on the selected fields.
395
+ * - `relatedRequirements`: An array of related requirements with details such as ID, title, customer ID, and URL.
396
+ * If an error occurs, logs the error and returns `null`.
397
+ *
398
+ * @throws Logs an error message if the data retrieval fails.
163
399
  */
164
- async fetchResult(projectName, runId, resultId) {
400
+ async fetchResultDataBasedOnWiBase(projectName, runId, resultId, options = {}) {
401
+ var _a, _b, _c, _d;
165
402
  try {
166
403
  const url = `${this.orgUrl}${projectName}/_apis/test/runs/${runId}/results/${resultId}?detailsToInclude=Iterations`;
167
404
  const resultData = await tfs_1.TFSServices.getItemContent(url, this.token);
168
405
  const attachmentsUrl = `${this.orgUrl}${projectName}/_apis/test/runs/${runId}/results/${resultId}/attachments`;
169
406
  const { value: analysisAttachments } = await tfs_1.TFSServices.getItemContent(attachmentsUrl, this.token);
170
- const wiUrl = `${this.orgUrl}${projectName}/_apis/wit/workItems/${resultData.testCase.id}/revisions/${resultData.testCaseRevision}`;
407
+ // Build workItem URL with optional expand parameter
408
+ const expandParam = options.expandWorkItem ? '?$expand=all' : '';
409
+ const wiUrl = `${this.orgUrl}${projectName}/_apis/wit/workItems/${resultData.testCase.id}/revisions/${resultData.testCaseRevision}${expandParam}`;
171
410
  const wiByRevision = await tfs_1.TFSServices.getItemContent(wiUrl, this.token);
172
- return Object.assign(Object.assign({}, resultData), { stepsResultXml: wiByRevision.fields['Microsoft.VSTS.TCM.Steps'] || undefined, analysisAttachments, testCaseRevision: resultData.testCaseRevision });
411
+ let filteredFields = {};
412
+ let relatedRequirements = [];
413
+ // Process selected fields if provided
414
+ if (((_a = options.selectedFields) === null || _a === void 0 ? void 0 : _a.length) && options.processRelatedRequirements) {
415
+ const filtered = (_c = (_b = options.selectedFields) === null || _b === void 0 ? void 0 : _b.filter((field) => field.includes('@testCaseWorkItemField'))) === null || _c === void 0 ? void 0 : _c.map((field) => field.split('@')[0]);
416
+ const selectedFieldSet = new Set(filtered);
417
+ if (selectedFieldSet.size !== 0) {
418
+ // Process related requirements if needed
419
+ const { relations } = wiByRevision;
420
+ if (relations) {
421
+ for (const relation of relations) {
422
+ if ((_d = relation.rel) === null || _d === void 0 ? void 0 : _d.includes('System.LinkTypes.Hierarchy')) {
423
+ const relatedUrl = relation.url;
424
+ const wi = await tfs_1.TFSServices.getItemContent(relatedUrl, this.token);
425
+ if (wi.fields['System.WorkItemType'] === 'Requirement') {
426
+ const { id, fields, _links } = wi;
427
+ const requirementTitle = fields['System.Title'];
428
+ const customerFieldKey = Object.keys(fields).find((key) => key.toLowerCase().includes('customer'));
429
+ const customerId = customerFieldKey ? fields[customerFieldKey] : undefined;
430
+ const url = _links.html.href;
431
+ relatedRequirements.push({ id, requirementTitle, customerId, url });
432
+ }
433
+ }
434
+ }
435
+ }
436
+ // Filter fields based on selected field set
437
+ filteredFields = Object.keys(wiByRevision.fields)
438
+ .filter((key) => selectedFieldSet.has(key))
439
+ .reduce((obj, key) => {
440
+ var _a, _b;
441
+ obj[key] = (_b = (_a = wiByRevision.fields[key]) === null || _a === void 0 ? void 0 : _a.displayName) !== null && _b !== void 0 ? _b : wiByRevision.fields[key];
442
+ return obj;
443
+ }, {});
444
+ }
445
+ }
446
+ return Object.assign(Object.assign({}, resultData), { stepsResultXml: wiByRevision.fields['Microsoft.VSTS.TCM.Steps'] || undefined, analysisAttachments, testCaseRevision: resultData.testCaseRevision, filteredFields,
447
+ relatedRequirements });
173
448
  }
174
449
  catch (error) {
175
450
  logger_1.default.error(`Error while fetching run result: ${error.message}`);
451
+ if (options.includeFullErrorStack) {
452
+ logger_1.default.error(`Error stack: ${error.stack}`);
453
+ }
176
454
  return null;
177
455
  }
178
456
  }
179
457
  /**
180
- * Converts run status from API format to a more readable format.
458
+ * Fetches result data based on the specified work item (WI) details.
459
+ *
460
+ * @param projectName - The name of the project associated with the work item.
461
+ * @param runId - The unique identifier of the test run.
462
+ * @param resultId - The unique identifier of the test result.
463
+ * @returns A promise that resolves to the result data.
464
+ */
465
+ async fetchResultDataBasedOnWi(projectName, runId, resultId) {
466
+ return this.fetchResultDataBasedOnWiBase(projectName, runId, resultId);
467
+ }
468
+ /**
469
+ * Converts a run status string into a human-readable format.
470
+ *
471
+ * @param status - The status string to convert. Expected values are:
472
+ * - `'passed'`: Indicates the run was successful.
473
+ * - `'failed'`: Indicates the run was unsuccessful.
474
+ * - `'notApplicable'`: Indicates the run is not applicable.
475
+ * - Any other value will default to `'Not Run'`.
476
+ * @returns A human-readable string representing the run status.
181
477
  */
182
478
  convertRunStatus(status) {
183
479
  switch (status) {
@@ -191,7 +487,19 @@ class ResultDataProvider {
191
487
  return 'Not Run';
192
488
  }
193
489
  }
194
- setRunStatus(actionResult) {
490
+ /**
491
+ * Converts the outcome of an action result based on specific conditions.
492
+ *
493
+ * - If the outcome is 'Unspecified' and the action result is a shared step title,
494
+ * it returns an empty string.
495
+ * - If the outcome is 'Unspecified' but not a shared step title, it returns 'Not Run'.
496
+ * - If the outcome is not 'Not Run', it returns the original outcome.
497
+ * - Otherwise, it returns an empty string.
498
+ *
499
+ * @param actionResult - The action result object containing the outcome and other properties.
500
+ * @returns A string representing the converted outcome.
501
+ */
502
+ convertUnspecifiedRunStatus(actionResult) {
195
503
  if (actionResult.outcome === 'Unspecified' && actionResult.isSharedStepTitle) {
196
504
  return '';
197
505
  }
@@ -202,13 +510,24 @@ class ResultDataProvider {
202
510
  : '';
203
511
  }
204
512
  /**
205
- * Aligns test steps with their corresponding iterations.
513
+ * Aligns test steps with iterations and generates detailed results based on the provided options.
514
+ *
515
+ * @param testData - An array of test data objects containing test points and test cases.
516
+ * @param iterations - An array of iteration data used to map test cases to their respective iterations.
517
+ * @param options - Configuration options for processing the test data.
518
+ * @param options.selectedFields - An optional array of selected fields to filter step-level properties.
519
+ * @param options.createResultObject - A callback function to create a result object for each test or step.
520
+ * @param options.shouldProcessStepLevel - A callback function to determine whether to process at the step level.
521
+ * @returns An array of detailed result objects, either at the test level or step level, depending on the options.
206
522
  */
207
- alignStepsWithIterations(testData, iterations) {
523
+ alignStepsWithIterationsBase(testData, iterations, options) {
524
+ var _a, _b;
208
525
  const detailedResults = [];
209
526
  if (!iterations || (iterations === null || iterations === void 0 ? void 0 : iterations.length) === 0) {
210
527
  return detailedResults;
211
528
  }
529
+ // Process filtered fields if available
530
+ const filteredFields = new Set(((_b = (_a = options.selectedFields) === null || _a === void 0 ? void 0 : _a.filter((field) => field.includes('@stepsRunProperties'))) === null || _b === void 0 ? void 0 : _b.map((field) => field.split('@')[0])) || []);
212
531
  for (const testItem of testData) {
213
532
  for (const point of testItem.testPointsItems) {
214
533
  const testCase = testItem.testCasesItems.find((tc) => tc.workItem.id === point.testCaseId);
@@ -221,32 +540,77 @@ class ResultDataProvider {
221
540
  }
222
541
  if (point.lastRunId && point.lastResultId) {
223
542
  const iterationKey = `${point.lastRunId}-${point.lastResultId}-${testCase.workItem.id}`;
224
- const testCastObj = iterationsMap[iterationKey];
225
- if (!testCastObj || !testCastObj.iteration || !testCastObj.iteration.actionResults)
543
+ const fetchedTestCase = iterationsMap[iterationKey];
544
+ if (!fetchedTestCase || !fetchedTestCase.iteration)
226
545
  continue;
227
- const { actionResults } = testCastObj === null || testCastObj === void 0 ? void 0 : testCastObj.iteration;
228
- for (let i = 0; i < (actionResults === null || actionResults === void 0 ? void 0 : actionResults.length); i++) {
229
- const stepIdentifier = parseInt(actionResults[i].stepIdentifier, 10);
230
- const resultObj = {
231
- testId: point.testCaseId,
232
- testCaseRevision: testCastObj.testCaseRevision,
233
- testName: point.testCaseName,
234
- stepIdentifier: stepIdentifier,
235
- actionPath: actionResults[i].actionPath,
236
- stepNo: actionResults[i].stepPosition,
237
- stepAction: actionResults[i].action,
238
- stepExpected: actionResults[i].expected,
239
- isSharedStepTitle: actionResults[i].isSharedStepTitle,
240
- stepStatus: this.setRunStatus(actionResults[i]),
241
- stepComments: actionResults[i].errorMessage || '',
242
- };
546
+ // Determine if we should process at step level
547
+ const shouldProcessSteps = options.shouldProcessStepLevel(fetchedTestCase, filteredFields);
548
+ if (!shouldProcessSteps) {
549
+ // Create a test-level result object
550
+ const resultObj = options.createResultObject({
551
+ testItem,
552
+ point,
553
+ fetchedTestCase,
554
+ filteredFields,
555
+ });
243
556
  detailedResults.push(resultObj);
244
557
  }
558
+ else {
559
+ // Create step-level result objects
560
+ const { actionResults } = fetchedTestCase === null || fetchedTestCase === void 0 ? void 0 : fetchedTestCase.iteration;
561
+ for (let i = 0; i < (actionResults === null || actionResults === void 0 ? void 0 : actionResults.length); i++) {
562
+ const resultObj = options.createResultObject({
563
+ testItem,
564
+ point,
565
+ fetchedTestCase,
566
+ actionResult: actionResults[i],
567
+ filteredFields,
568
+ });
569
+ detailedResults.push(resultObj);
570
+ }
571
+ }
245
572
  }
246
573
  }
247
574
  }
248
575
  return detailedResults;
249
576
  }
577
+ /**
578
+ * Aligns test steps with their corresponding iterations by processing the provided test data and iterations.
579
+ * This method utilizes a base alignment function with custom logic for processing step-level data and creating result objects.
580
+ *
581
+ * @param testData - An array of test data objects containing information about test cases and their steps.
582
+ * @param iterations - An array of iteration objects containing action results for each test case.
583
+ * @returns An array of aligned step data objects, each containing detailed information about a test step and its status.
584
+ *
585
+ * The alignment process includes:
586
+ * - Filtering and processing step-level data based on the presence of iteration and action results.
587
+ * - Creating result objects for each step, including details such as test ID, step identifier, action path, step status, and comments.
588
+ */
589
+ alignStepsWithIterations(testData, iterations) {
590
+ return this.alignStepsWithIterationsBase(testData, iterations, {
591
+ shouldProcessStepLevel: (fetchedTestCase) => fetchedTestCase != null &&
592
+ fetchedTestCase.iteration != null &&
593
+ fetchedTestCase.iteration.actionResults != null,
594
+ createResultObject: ({ point, fetchedTestCase, actionResult }) => {
595
+ if (!actionResult)
596
+ return null;
597
+ const stepIdentifier = parseInt(actionResult.stepIdentifier, 10);
598
+ return {
599
+ testId: point.testCaseId,
600
+ testCaseRevision: fetchedTestCase.testCaseRevision,
601
+ testName: point.testCaseName,
602
+ stepIdentifier: stepIdentifier,
603
+ actionPath: actionResult.actionPath,
604
+ stepNo: actionResult.stepPosition,
605
+ stepAction: actionResult.action,
606
+ stepExpected: actionResult.expected,
607
+ isSharedStepTitle: actionResult.isSharedStepTitle,
608
+ stepStatus: this.convertUnspecifiedRunStatus(actionResult),
609
+ stepComments: actionResult.errorMessage || '',
610
+ };
611
+ },
612
+ });
613
+ }
250
614
  /**
251
615
  * Creates a mapping of iterations by their unique keys.
252
616
  */
@@ -276,12 +640,19 @@ class ResultDataProvider {
276
640
  })));
277
641
  }
278
642
  /**
279
- * Fetches result data for all test points within the given test data.
643
+ * Fetches all result data based on the provided test data, project name, and fetch strategy.
644
+ * This method processes the test data, filters valid test points, and sequentially fetches
645
+ * result data for each valid point using the provided fetch strategy.
646
+ *
647
+ * @param testData - An array of test data objects containing test suite and test points information.
648
+ * @param projectName - The name of the project for which the result data is being fetched.
649
+ * @param fetchStrategy - A function that defines the strategy for fetching result data. It takes
650
+ * the project name, test suite ID, a test point, and additional arguments,
651
+ * and returns a Promise resolving to the fetched result data.
652
+ * @param additionalArgs - An optional array of additional arguments to be passed to the fetch strategy.
653
+ * @returns A Promise that resolves to an array of fetched result data.
280
654
  */
281
- /**
282
- * Fetches result data for all test points within the given test data, sequentially to avoid context-related errors.
283
- */
284
- async fetchAllResultData(testData, projectName) {
655
+ async fetchAllResultDataBase(testData, projectName, fetchStrategy, additionalArgs = []) {
285
656
  const results = [];
286
657
  for (const item of testData) {
287
658
  if (item.testPointsItems && item.testPointsItems.length > 0) {
@@ -290,7 +661,7 @@ class ResultDataProvider {
290
661
  const validPoints = testPointsItems.filter((point) => point && point.lastRunId && point.lastResultId);
291
662
  // Fetch results for each point sequentially
292
663
  for (const point of validPoints) {
293
- const resultData = await this.fetchResultData(projectName, testSuiteId, point);
664
+ const resultData = await fetchStrategy(projectName, testSuiteId, point, ...additionalArgs);
294
665
  if (resultData !== null) {
295
666
  results.push(resultData);
296
667
  }
@@ -300,11 +671,17 @@ class ResultDataProvider {
300
671
  return results;
301
672
  }
302
673
  /**
303
- * Fetches result Data data for a specific test point.
674
+ * Fetches result data for all test points within the given test data, sequentially to avoid context-related errors.
304
675
  */
305
- async fetchResultData(projectName, testSuiteId, point) {
676
+ async fetchAllResultData(testData, projectName) {
677
+ return this.fetchAllResultDataBase(testData, projectName, (projectName, testSuiteId, point) => this.fetchResultData(projectName, testSuiteId, point));
678
+ }
679
+ /**
680
+ * Base method for fetching result data for test points
681
+ */
682
+ async fetchResultDataBase(projectName, testSuiteId, point, fetchResultMethod, createResponseObject, additionalArgs = []) {
306
683
  const { lastRunId, lastResultId } = point;
307
- const resultData = await this.fetchResult(projectName, lastRunId.toString(), lastResultId.toString());
684
+ const resultData = await fetchResultMethod(projectName, lastRunId.toString(), lastResultId.toString(), ...additionalArgs);
308
685
  const iteration = resultData.iterationDetails.length > 0
309
686
  ? resultData.iterationDetails[resultData.iterationDetails.length - 1]
310
687
  : undefined;
@@ -338,22 +715,30 @@ class ResultDataProvider {
338
715
  .sort((a, b) => this.compareActionResults(a.stepPosition, b.stepPosition));
339
716
  }
340
717
  return (resultData === null || resultData === void 0 ? void 0 : resultData.testCase)
341
- ? {
342
- testCaseName: `${resultData.testCase.name} - ${resultData.testCase.id}`,
343
- testCaseId: resultData.testCase.id,
344
- testSuiteName: `${resultData.testSuite.name}`,
345
- testSuiteId,
346
- lastRunId,
347
- lastResultId,
348
- iteration,
349
- testCaseRevision: resultData.testCaseRevision,
350
- failureType: resultData.failureType,
351
- resolution: resultData.resolutionState,
352
- comment: resultData.comment,
353
- analysisAttachments: resultData.analysisAttachments,
354
- }
718
+ ? createResponseObject(resultData, testSuiteId, point, ...additionalArgs)
355
719
  : null;
356
720
  }
721
+ /**
722
+ * Fetches result Data for a specific test point
723
+ */
724
+ async fetchResultData(projectName, testSuiteId, point) {
725
+ return this.fetchResultDataBase(projectName, testSuiteId, point, (project, runId, resultId) => this.fetchResultDataBasedOnWi(project, runId, resultId), (resultData, testSuiteId, point) => ({
726
+ testCaseName: `${resultData.testCase.name} - ${resultData.testCase.id}`,
727
+ testCaseId: resultData.testCase.id,
728
+ testSuiteName: `${resultData.testSuite.name}`,
729
+ testSuiteId,
730
+ lastRunId: point.lastRunId,
731
+ lastResultId: point.lastResultId,
732
+ iteration: resultData.iterationDetails.length > 0
733
+ ? resultData.iterationDetails[resultData.iterationDetails.length - 1]
734
+ : undefined,
735
+ testCaseRevision: resultData.testCaseRevision,
736
+ failureType: resultData.failureType,
737
+ resolution: resultData.resolutionState,
738
+ comment: resultData.comment,
739
+ analysisAttachments: resultData.analysisAttachments,
740
+ }));
741
+ }
357
742
  /**
358
743
  * Fetches all the linked work items (WI) for the given test case.
359
744
  * @param project Project name
@@ -476,33 +861,6 @@ class ResultDataProvider {
476
861
  });
477
862
  }
478
863
  }
479
- /**
480
- * Mapping each attachment to a proper URL for downloading it
481
- * @param runResults Array of run results
482
- */
483
- mapAttachmentsUrl(runResults, project) {
484
- return runResults.map((result) => {
485
- var _a;
486
- if (!result.iteration) {
487
- return result;
488
- }
489
- const { iteration, analysisAttachments } = result, restResult = __rest(result, ["iteration", "analysisAttachments"]);
490
- //add downloadUri field for each attachment
491
- const baseDownloadUrl = `${this.orgUrl}${project}/_apis/test/runs/${result.lastRunId}/results/${result.lastResultId}/attachments`;
492
- if (iteration && ((_a = iteration.attachments) === null || _a === void 0 ? void 0 : _a.length) > 0) {
493
- const { attachments, actionResults } = iteration, restOfIteration = __rest(iteration, ["attachments", "actionResults"]);
494
- const attachmentPathToIndexMap = this.CreateAttachmentPathIndexMap(actionResults);
495
- const mappedAttachments = attachments.map((attachment) => (Object.assign(Object.assign({}, attachment), { stepNo: attachmentPathToIndexMap.has(attachment.actionPath)
496
- ? attachmentPathToIndexMap.get(attachment.actionPath)
497
- : undefined, downloadUrl: `${baseDownloadUrl}/${attachment.id}/${attachment.name}` })));
498
- restResult.iteration = Object.assign(Object.assign({}, restOfIteration), { attachments: mappedAttachments });
499
- }
500
- if (analysisAttachments && analysisAttachments.length > 0) {
501
- restResult.analysisAttachments = analysisAttachments.map((attachment) => (Object.assign(Object.assign({}, attachment), { downloadUrl: `${baseDownloadUrl}/${attachment.id}/${attachment.fileName}` })));
502
- }
503
- return Object.assign({}, restResult);
504
- });
505
- }
506
864
  CreateAttachmentPathIndexMap(actionResults) {
507
865
  const attachmentPathToIndexMap = new Map();
508
866
  for (let i = 0; i < actionResults.length; i++) {
@@ -511,122 +869,6 @@ class ResultDataProvider {
511
869
  }
512
870
  return attachmentPathToIndexMap;
513
871
  }
514
- /**
515
- * Combines the results of test group result summary, test results summary, and detailed results summary into a single key-value pair array.
516
- */
517
- async getCombinedResultsSummary(testPlanId, projectName, selectedSuiteIds, addConfiguration = false, isHierarchyGroupName = false, includeOpenPCRs = false, includeTestLog = false, stepExecution, stepAnalysis, includeHardCopyRun = false) {
518
- const combinedResults = [];
519
- try {
520
- // Fetch test suites
521
- const suites = await this.fetchTestSuites(testPlanId, projectName, selectedSuiteIds, isHierarchyGroupName);
522
- // Prepare test data for summaries
523
- const testPointsPromises = suites.map((suite) => this.limit(() => this.fetchTestPoints(projectName, testPlanId, suite.testSuiteId)
524
- .then((testPointsItems) => (Object.assign(Object.assign({}, suite), { testPointsItems })))
525
- .catch((error) => {
526
- logger_1.default.error(`Error occurred for suite ${suite.testSuiteId}: ${error.message}`);
527
- return Object.assign(Object.assign({}, suite), { testPointsItems: [] });
528
- })));
529
- const testPoints = await Promise.all(testPointsPromises);
530
- // 1. Calculate Test Group Result Summary
531
- const summarizedResults = testPoints
532
- .filter((testPoint) => testPoint.testPointsItems && testPoint.testPointsItems.length > 0)
533
- .map((testPoint) => {
534
- const groupResultSummary = this.calculateGroupResultSummary(testPoint.testPointsItems || [], includeHardCopyRun);
535
- return Object.assign(Object.assign({}, testPoint), { groupResultSummary });
536
- });
537
- const totalSummary = this.calculateTotalSummary(summarizedResults, includeHardCopyRun);
538
- const testGroupArray = summarizedResults.map((item) => (Object.assign({ testGroupName: item.testGroupName }, item.groupResultSummary)));
539
- testGroupArray.push(Object.assign({ testGroupName: 'Total' }, totalSummary));
540
- // Add test group result summary to combined results
541
- combinedResults.push({
542
- contentControl: 'test-group-summary-content-control',
543
- data: testGroupArray,
544
- skin: 'test-result-test-group-summary-table',
545
- });
546
- // 2. Calculate Test Results Summary
547
- const flattenedTestPoints = this.flattenTestPoints(testPoints);
548
- const testResultsSummary = flattenedTestPoints.map((testPoint) => this.formatTestResult(testPoint, addConfiguration, includeHardCopyRun));
549
- // Add test results summary to combined results
550
- combinedResults.push({
551
- contentControl: 'test-result-summary-content-control',
552
- data: testResultsSummary,
553
- skin: 'test-result-table',
554
- });
555
- // 3. Calculate Detailed Results Summary
556
- const testData = await this.fetchTestData(suites, projectName, testPlanId);
557
- const runResults = await this.fetchAllResultData(testData, projectName);
558
- const detailedStepResultsSummary = this.alignStepsWithIterations(testData, runResults);
559
- //Filter out all the results with no comment
560
- const filteredDetailedResults = detailedStepResultsSummary.filter((result) => result && (result.stepComments !== '' || result.stepStatus === 'Failed'));
561
- // Add detailed results summary to combined results
562
- combinedResults.push({
563
- contentControl: 'detailed-test-result-content-control',
564
- data: !includeHardCopyRun ? filteredDetailedResults : [],
565
- skin: 'detailed-test-result-table',
566
- });
567
- if (includeOpenPCRs) {
568
- //5. Open PCRs data (only if enabled)
569
- await this.fetchOpenPcrData(testResultsSummary, projectName, combinedResults);
570
- }
571
- //6. Test Log (only if enabled)
572
- if (includeTestLog) {
573
- this.fetchTestLogData(flattenedTestPoints, combinedResults);
574
- }
575
- if (stepAnalysis && stepAnalysis.isEnabled) {
576
- const mappedAnalysisData = runResults.filter((result) => {
577
- var _a, _b, _c;
578
- return result.comment ||
579
- ((_b = (_a = result.iteration) === null || _a === void 0 ? void 0 : _a.attachments) === null || _b === void 0 ? void 0 : _b.length) > 0 ||
580
- ((_c = result.analysisAttachments) === null || _c === void 0 ? void 0 : _c.length) > 0;
581
- });
582
- const mappedAnalysisResultData = stepAnalysis.generateRunAttachments.isEnabled
583
- ? this.mapAttachmentsUrl(mappedAnalysisData, projectName)
584
- : mappedAnalysisData;
585
- if ((mappedAnalysisResultData === null || mappedAnalysisResultData === void 0 ? void 0 : mappedAnalysisResultData.length) > 0) {
586
- combinedResults.push({
587
- contentControl: 'appendix-a-content-control',
588
- data: mappedAnalysisResultData,
589
- skin: 'step-analysis-appendix-skin',
590
- });
591
- }
592
- }
593
- if (stepExecution && stepExecution.isEnabled) {
594
- const mappedAnalysisData = stepExecution.generateAttachments.isEnabled &&
595
- stepExecution.generateAttachments.runAttachmentMode !== 'planOnly'
596
- ? runResults.filter((result) => { var _a, _b; return ((_b = (_a = result.iteration) === null || _a === void 0 ? void 0 : _a.attachments) === null || _b === void 0 ? void 0 : _b.length) > 0; })
597
- : [];
598
- const mappedAnalysisResultData = mappedAnalysisData.length > 0 ? this.mapAttachmentsUrl(mappedAnalysisData, projectName) : [];
599
- const mappedDetailedResults = this.mapStepResultsForExecutionAppendix(detailedStepResultsSummary, mappedAnalysisResultData);
600
- combinedResults.push({
601
- contentControl: 'appendix-b-content-control',
602
- data: mappedDetailedResults,
603
- skin: 'step-execution-appendix-skin',
604
- });
605
- }
606
- return combinedResults;
607
- }
608
- catch (error) {
609
- logger_1.default.error(`Error during getCombinedResultsSummary: ${error.message}`);
610
- if (error.response) {
611
- logger_1.default.error(`Response Data: ${JSON.stringify(error.response.data)}`);
612
- }
613
- throw error;
614
- }
615
- }
616
- // private mapStepResultsForExecutionAppendix(detailedResults: any[]): any {
617
- // return detailedResults?.length > 0
618
- // ? detailedResults.map((result) => {
619
- // return {
620
- // testId: result.testId,
621
- // testCaseRevision: result.testCaseRevision || undefined,
622
- // stepNo: result.stepNo,
623
- // stepIdentifier: result.stepIdentifier,
624
- // stepStatus: result.stepStatus,
625
- // stepComments: result.stepComments,
626
- // };
627
- // })
628
- // : [];
629
- // }
630
872
  mapStepResultsForExecutionAppendix(detailedResults, runResultData) {
631
873
  // Create maps first to avoid repeated lookups
632
874
  const testCaseIdToStepsMap = new Map();
@@ -778,6 +1020,180 @@ class ResultDataProvider {
778
1020
  }
779
1021
  return formattedResult;
780
1022
  }
1023
+ /**
1024
+ * Fetches result data based on the Work Item Test Reporter.
1025
+ *
1026
+ * This method retrieves detailed result data for a specific test run and result ID,
1027
+ * including related work items, selected fields, and additional processing options.
1028
+ *
1029
+ * @param projectName - The name of the project containing the test run.
1030
+ * @param runId - The unique identifier of the test run.
1031
+ * @param resultId - The unique identifier of the test result.
1032
+ * @param selectedFields - (Optional) An array of field names to include in the result data.
1033
+ * @returns A promise that resolves to the fetched result data.
1034
+ */
1035
+ async fetchResultDataBasedOnWiTestReporter(projectName, runId, resultId, selectedFields) {
1036
+ return this.fetchResultDataBasedOnWiBase(projectName, runId, resultId, {
1037
+ expandWorkItem: true,
1038
+ selectedFields,
1039
+ processRelatedRequirements: true,
1040
+ includeFullErrorStack: true,
1041
+ });
1042
+ }
1043
+ /**
1044
+ * Fetches all result data for the test reporter by processing the provided test data.
1045
+ *
1046
+ * This method utilizes the `fetchAllResultDataBase` function to retrieve and process
1047
+ * result data for a specific project and test reporter. It applies a callback to fetch
1048
+ * result data for individual test points.
1049
+ *
1050
+ * @param testData - An array of test data objects to process.
1051
+ * @param projectName - The name of the project for which result data is being fetched.
1052
+ * @param selectedFields - An optional array of field names to include in the result data.
1053
+ * @returns A promise that resolves to an array of processed result data.
1054
+ */
1055
+ async fetchAllResultDataTestReporter(testData, projectName, selectedFields) {
1056
+ return this.fetchAllResultDataBase(testData, projectName, (projectName, testSuiteId, point, selectedFields) => this.fetchResultDataForTestReporter(projectName, testSuiteId, point, selectedFields), [selectedFields]);
1057
+ }
1058
+ /**
1059
+ * Aligns test steps with iterations for the test reporter by processing test data and iterations
1060
+ * and generating a structured result object based on the provided selected fields.
1061
+ *
1062
+ * @param testData - An array of test data objects to be processed.
1063
+ * @param iterations - An array of iteration objects to align with the test data.
1064
+ * @param selectedFields - An array of selected fields to determine which properties to include in the result.
1065
+ * @returns An array of structured result objects containing aligned test steps and iterations.
1066
+ *
1067
+ * The method uses a base alignment function and provides custom logic for:
1068
+ * - Determining whether step-level processing should occur based on the fetched test case and filtered fields.
1069
+ * - Creating a result object with properties such as suite name, test case details, priority, run information,
1070
+ * failure type, automation status, execution date, configuration name, state, error message, and related requirements.
1071
+ * - Including step-specific properties (e.g., step number, action, expected result, status, and comments) if action results are available
1072
+ * and the corresponding fields are selected.
1073
+ */
1074
+ alignStepsWithIterationsTestReporter(testData, iterations, selectedFields) {
1075
+ return this.alignStepsWithIterationsBase(testData, iterations, {
1076
+ selectedFields,
1077
+ shouldProcessStepLevel: (fetchedTestCase, filteredFields) => fetchedTestCase != null &&
1078
+ fetchedTestCase.iteration != null &&
1079
+ fetchedTestCase.iteration.actionResults != null &&
1080
+ filteredFields.size > 0,
1081
+ createResultObject: ({ testItem, point, fetchedTestCase, actionResult, filteredFields = new Set(), }) => {
1082
+ var _a;
1083
+ const baseObj = {
1084
+ suiteName: testItem.testGroupName,
1085
+ testCase: {
1086
+ id: point.testCaseId,
1087
+ title: point.testCaseName,
1088
+ url: point.testCaseUrl,
1089
+ result: fetchedTestCase.testCaseResult,
1090
+ comment: (_a = fetchedTestCase.iteration) === null || _a === void 0 ? void 0 : _a.comment,
1091
+ },
1092
+ priority: fetchedTestCase.priority,
1093
+ runBy: fetchedTestCase.runBy,
1094
+ activatedBy: fetchedTestCase.activatedBy,
1095
+ assignedTo: fetchedTestCase.assignedTo,
1096
+ failureType: fetchedTestCase.failureType,
1097
+ automationStatus: fetchedTestCase.automationStatus,
1098
+ executionDate: fetchedTestCase.executionDate,
1099
+ configurationName: fetchedTestCase.configurationName,
1100
+ errorMessage: fetchedTestCase.errorMessage,
1101
+ relatedRequirements: fetchedTestCase.relatedRequirements,
1102
+ };
1103
+ // If we have action results, add step-specific properties
1104
+ if (actionResult) {
1105
+ return Object.assign(Object.assign({}, baseObj), { stepNo: actionResult.stepPosition, stepAction: filteredFields.has('includeSteps') ? actionResult.action : undefined, stepExpected: filteredFields.has('includeSteps') ? actionResult.expected : undefined, stepStatus: filteredFields.has('stepRunStatus')
1106
+ ? this.convertUnspecifiedRunStatus(actionResult)
1107
+ : undefined, stepComments: filteredFields.has('testStepComment') ? actionResult.errorMessage : undefined });
1108
+ }
1109
+ return baseObj;
1110
+ },
1111
+ });
1112
+ }
1113
+ /**
1114
+ * Fetches result data for a test reporter based on the provided project, test suite, and point information.
1115
+ * This method processes the result data and formats it according to the selected fields.
1116
+ *
1117
+ * @param projectName - The name of the project.
1118
+ * @param testSuiteId - The ID of the test suite.
1119
+ * @param point - The test point containing details such as last run ID, result ID, and configuration name.
1120
+ * @param selectedFields - An optional array of field names to filter and include in the response.
1121
+ *
1122
+ * @returns A promise that resolves to the formatted result data object containing details about the test case,
1123
+ * test suite, last run, iteration, and other selected fields.
1124
+ */
1125
+ async fetchResultDataForTestReporter(projectName, testSuiteId, point, selectedFields) {
1126
+ return this.fetchResultDataBase(projectName, testSuiteId, point, (project, runId, resultId, fields) => this.fetchResultDataBasedOnWiTestReporter(project, runId, resultId, fields), (resultData, testSuiteId, point, selectedFields) => {
1127
+ var _a, _b;
1128
+ const { lastRunId, lastResultId, configurationName, lastResultDetails } = point;
1129
+ const iteration = resultData.iterationDetails.length > 0
1130
+ ? resultData.iterationDetails[resultData.iterationDetails.length - 1]
1131
+ : undefined;
1132
+ const resultDataResponse = {
1133
+ testCaseName: `${resultData.testCase.name} - ${resultData.testCase.id}`,
1134
+ testCaseId: resultData.testCase.id,
1135
+ testSuiteName: `${resultData.testSuite.name}`,
1136
+ testSuiteId,
1137
+ lastRunId,
1138
+ lastResultId,
1139
+ iteration,
1140
+ testCaseRevision: resultData.testCaseRevision,
1141
+ resolution: resultData.resolutionState,
1142
+ automationStatus: resultData.filteredFields['Microsoft.VSTS.TCM.AutomationStatus'] || undefined,
1143
+ analysisAttachments: resultData.analysisAttachments,
1144
+ failureType: undefined,
1145
+ comment: undefined,
1146
+ priority: undefined,
1147
+ runBy: undefined,
1148
+ executionDate: undefined,
1149
+ testCaseResult: undefined,
1150
+ errorMessage: undefined,
1151
+ configurationName: undefined,
1152
+ relatedRequirements: undefined,
1153
+ lastRunResult: undefined,
1154
+ };
1155
+ const filteredFields = (_a = selectedFields === null || selectedFields === void 0 ? void 0 : selectedFields.filter((field) => field.includes('@runResultField') || field.includes('@linked'))) === null || _a === void 0 ? void 0 : _a.map((field) => field.split('@')[0]);
1156
+ if (filteredFields && filteredFields.length > 0) {
1157
+ for (const field of filteredFields) {
1158
+ switch (field) {
1159
+ case 'priority':
1160
+ resultDataResponse.priority = resultData.priority;
1161
+ break;
1162
+ case 'testCaseResult':
1163
+ const outcome = (_b = resultData.iterationDetails[resultData.iterationDetails.length - 1]) === null || _b === void 0 ? void 0 : _b.outcome;
1164
+ resultDataResponse.testCaseResult = {
1165
+ resultMessage: `${outcome} in Run ${lastRunId}`,
1166
+ url: `${this.orgUrl}${projectName}/_testManagement/runs?runId=${lastRunId}&_a=resultSummary&resultId=${lastResultId}`,
1167
+ };
1168
+ break;
1169
+ case 'failureType':
1170
+ resultDataResponse.failureType = resultData.failureType;
1171
+ break;
1172
+ case 'testCaseComment':
1173
+ resultDataResponse.comment = resultData.comment || undefined;
1174
+ break;
1175
+ case 'runBy':
1176
+ const runBy = lastResultDetails.runBy.displayName;
1177
+ resultDataResponse.runBy = runBy;
1178
+ break;
1179
+ case 'executionDate':
1180
+ resultDataResponse.executionDate = lastResultDetails.dateCompleted;
1181
+ break;
1182
+ case 'configurationName':
1183
+ resultDataResponse.configurationName = configurationName;
1184
+ break;
1185
+ case 'associatedRequirement':
1186
+ resultDataResponse.relatedRequirements = resultData.relatedRequirements;
1187
+ break;
1188
+ default:
1189
+ logger_1.default.debug(`Field ${field} not handled`);
1190
+ break;
1191
+ }
1192
+ }
1193
+ }
1194
+ return resultDataResponse;
1195
+ }, [selectedFields]);
1196
+ }
781
1197
  }
782
1198
  exports.default = ResultDataProvider;
783
1199
  //# sourceMappingURL=ResultDataProvider.js.map