-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathJiraUseCase.groovy
More file actions
443 lines (362 loc) · 19 KB
/
JiraUseCase.groovy
File metadata and controls
443 lines (362 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package org.ods.orchestration.usecase
import com.cloudbees.groovy.cps.NonCPS
import org.ods.orchestration.parser.JUnitParser
import org.ods.orchestration.service.JiraService
import org.ods.util.IPipelineSteps
import org.ods.util.ILogger
import org.ods.orchestration.util.MROPipelineUtil
import org.ods.orchestration.util.Project
import org.ods.orchestration.util.Project.JiraDataItem
@SuppressWarnings(['IfStatementBraces', 'LineLength'])
class JiraUseCase {
class IssueTypes {
static final String DOCUMENTATION_TRACKING = 'Documentation'
static final String DOCUMENTATION_CHAPTER = 'Documentation Chapter'
static final String RELEASE_STATUS = 'Release Status'
}
class CustomIssueFields {
static final String CONTENT = 'EDP Content'
static final String HEADING_NUMBER = 'EDP Heading Number'
static final String DOCUMENT_VERSION = 'Document Version'
static final String RELEASE_VERSION = 'ProductRelease Version'
}
class LabelPrefix {
static final String DOCUMENT = 'Doc:'
}
private Project project
private JiraService jira
private IPipelineSteps steps
private AbstractJiraUseCaseSupport support
private MROPipelineUtil util
private ILogger logger
JiraUseCase(Project project, IPipelineSteps steps, MROPipelineUtil util, JiraService jira, ILogger logger) {
this.project = project
this.steps = steps
this.util = util
this.jira = jira
this.logger = logger
}
void setSupport(AbstractJiraUseCaseSupport support) {
this.support = support
}
void applyXunitTestResultsAsTestIssueLabels(List testIssues, Map testResults) {
if (!this.jira) return
// Handle Jira test issues for which a corresponding test exists in testResults
def matchedHandler = { result ->
result.each { testIssue, testCase ->
def issueLabels = [TestIssueLabels.Succeeded as String]
if (testCase.skipped || testCase.error || testCase.failure) {
if (testCase.error) {
issueLabels = [TestIssueLabels.Error as String]
}
if (testCase.failure) {
issueLabels = [TestIssueLabels.Failed as String]
}
if (testCase.skipped) {
issueLabels = [TestIssueLabels.Skipped as String]
}
}
this.jira.removeLabelsFromIssue(testIssue.key, TestIssueLabels.values().collect { it.toString() })
this.jira.addLabelsToIssue(testIssue.key, issueLabels)
}
}
// Handle Jira test issues for which no corresponding test exists in testResults
def unmatchedHandler = { result ->
result.each { testIssue ->
this.jira.removeLabelsFromIssue(testIssue.key, TestIssueLabels.values().collect { it.toString() })
this.jira.addLabelsToIssue(testIssue.key, [TestIssueLabels.Missing as String])
}
}
this.matchTestIssuesAgainstTestResults(testIssues, testResults, matchedHandler, unmatchedHandler)
}
boolean checkTestsIssueMatchesTestCase(Map testIssue, Map testCase) {
def issueKeyClean = testIssue.key.replaceAll('-', '')
return testCase.name.startsWith("${issueKeyClean} ") ||
testCase.name.startsWith("${issueKeyClean}-") ||
testCase.name.startsWith("${issueKeyClean}_")
}
@NonCPS
String convertHTMLImageSrcIntoBase64Data(String html) {
def server = this.jira.baseURL
def pattern = ~/src="(${server}.*?\.(?:gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG))"/
def result = html.replaceAll(pattern) { match ->
def src = match[1]
def img = this.jira.getFileFromJira(src)
return "src=\"data:${img.contentType};base64,${img.data.encodeBase64()}\""
}
return result
}
void createBugsForFailedTestIssues(List testIssues, Set testFailures, String comment) {
if (!this.jira) return
testFailures.each { failure ->
// FIXME: this.project.versionFromReleaseStatusIssue loads data from Jira and should therefore be called not more
// than once. However, it's also called via this.getVersionFromReleaseStatusIssue in Project.groovy.
String version = this.project.versionFromReleaseStatusIssue
def bug = this.jira.createIssueTypeBug(
this.project.jiraProjectKey, failure.type, failure.text, version)
// Maintain a list of all Jira test issues affected by the current bug
def bugAffectedTestIssues = [:]
this.walkTestIssuesAndTestResults(testIssues, failure) { testIssue, testCase, isMatch ->
// Find the testcases within the current failure that corresponds to a Jira test issue
if (isMatch) {
// Add a reference to the current bug to the Jira test issue
if (null == testIssue.bugs) {
testIssue.bugs = []
}
testIssue.bugs << bug.key
// Add a link to the current bug on the Jira test issue (within Jira)
this.jira.createIssueLinkTypeBlocks(bug, testIssue)
bugAffectedTestIssues << [(testIssue.key): testIssue]
}
}
// Create a JiraDataItem from the newly created bug
def bugJiraDataItem = new JiraDataItem(project, [ // add project reference for access to Project.JiraDataItem
key: bug.key,
name: failure.type,
assignee: "Unassigned",
dueDate: "",
status: "TO DO",
tests: bugAffectedTestIssues.keySet() as List,
versions: [ "${version}" ]
], Project.JiraDataItem.TYPE_BUGS)
// Add JiraDataItem into the Jira data structure
this.project.data.jira.bugs[bug.key] = bugJiraDataItem
// Add the resolved JiraDataItem into the Jira data structure
this.project.data.jiraResolved.bugs[bug.key] = bugJiraDataItem.cloneIt()
this.project.data.jiraResolved.bugs[bug.key].tests = bugAffectedTestIssues.values() as List
this.jira.appendCommentToIssue(bug.key, comment)
}
}
/**
* Obtains all document chapter data attached attached to a given version
* @param versionName the version name from jira
* @return Map (key: issue) with all the document chapter issues and its relevant content
*/
@SuppressWarnings(['AbcMetric'])
Map<String, Map> getDocumentChapterData(String projectKey, String versionName = null) {
if (!this.jira) return [:]
def docChapterIssueFields = this.project.getJiraFieldsForIssueType(JiraUseCase.IssueTypes.DOCUMENTATION_CHAPTER)
def contentField = docChapterIssueFields[CustomIssueFields.CONTENT].id
def headingNumberField = docChapterIssueFields[CustomIssueFields.HEADING_NUMBER].id
def jql = "project = ${projectKey} " +
"AND issuetype = '${JiraUseCase.IssueTypes.DOCUMENTATION_CHAPTER}'"
if (versionName) {
jql = jql + " AND fixVersion = '${versionName}'"
}
def jqlQuery = [
fields: ['key', 'status', 'summary', 'labels', 'issuelinks', contentField, headingNumberField],
jql: jql,
expand: ['renderedFields'],
]
def result = this.jira.searchByJQLQuery(jqlQuery)
if (!result || result.total == 0) {
this.logger.warn("There are no document chapters assigned to this version. Using JQL query: '${jqlQuery}'.")
return [:]
}
return result.issues.collectEntries { issue ->
def number = issue.fields.find { field ->
headingNumberField == field.key && field.value
}
if (!number) {
throw new IllegalArgumentException("Error: could not find heading number for issue '${issue.key}'.")
}
number = number.getValue().trim()
def content = issue.renderedFields.find { field ->
contentField == field.key && field.value
}
content = content ? content.getValue() : ""
this.thumbnailImageReplacement(content)
def documentTypes = (issue.fields.labels ?: [])
.findAll { String l -> l.startsWith(LabelPrefix.DOCUMENT) }
.collect { String l -> l.replace(LabelPrefix.DOCUMENT, '') }
if (documentTypes.size() == 0) {
throw new IllegalArgumentException("Error: issue '${issue.key}' of type " +
"'${JiraUseCase.IssueTypes.DOCUMENTATION_CHAPTER}' contains no " +
"document labels. There should be at least one label starting with '${LabelPrefix.DOCUMENT}'")
}
def predecessorLinks = issue.fields.issuelinks
.findAll { it.type.name == "Succeeds" && it.outwardIssue?.key }
.collect { it.outwardIssue.key }
return [(issue.key as String): [
section: "sec${number.replaceAll(/\./, "s")}".toString(),
number: number,
heading: issue.fields.summary,
documents: documentTypes,
content: content?.replaceAll("\u00a0", " ") ?: " ",
status: issue.fields.status.name,
key: issue.key as String,
predecessors: predecessorLinks.isEmpty()? [] : predecessorLinks,
versions: versionName? [versionName] : [],
]
]
}
}
String getVersionFromReleaseStatusIssue() {
if (!this.jira) {
logger.warn("WARNING: this.jira has an invalid value.")
return ""
}
def releaseStatusIssueKey = this.project.buildParams.releaseStatusJiraIssueKey as String
def releaseStatusIssueFields = this.project.getJiraFieldsForIssueType(JiraUseCase.IssueTypes.RELEASE_STATUS)
def productReleaseVersionField = releaseStatusIssueFields[CustomIssueFields.RELEASE_VERSION]
def versionField = this.jira.getTextFieldsOfIssue(releaseStatusIssueKey, [productReleaseVersionField.id])
if (!versionField || !versionField[productReleaseVersionField.id]?.name) {
throw new IllegalArgumentException('Unable to obtain version name from release status issue' +
" ${releaseStatusIssueKey}. Please check that field with name" +
" '${productReleaseVersionField.name}' and id '${productReleaseVersionField.id}' " +
'has a correct version value.')
}
return versionField[productReleaseVersionField.id].name
}
void matchTestIssuesAgainstTestResults(List testIssues, Map testResults,
Closure matchedHandler, Closure unmatchedHandler = null,
boolean checkDuplicateTestResults = true) {
def duplicateKeysErrorMessage = "Error: the following test cases are implemented multiple times each: "
def duplicatesKeys = []
def result = [
matched: [:],
unmatched: []
]
this.walkTestIssuesAndTestResults(testIssues, testResults) { testIssue, testCase, isMatch ->
if (isMatch) {
if (result.matched.get(testIssue) != null) {
duplicatesKeys.add(testIssue.key)
}
result.matched << [
(testIssue): testCase
]
}
}
testIssues.each { testIssue ->
if (!result.matched.keySet().contains(testIssue) && mustRun(testIssue)) {
result.unmatched << testIssue
}
}
if (matchedHandler) {
matchedHandler(result.matched)
}
if (unmatchedHandler) {
unmatchedHandler(result.unmatched)
}
if (checkDuplicateTestResults && duplicatesKeys) {
throw new IllegalStateException("${duplicateKeysErrorMessage}${duplicatesKeys.join(', ')}.");
}
}
private boolean mustRun(testIssue) {
return !project.promotingToProd() ||
testIssue.testType?.equalsIgnoreCase(Project.TestType.INSTALLATION)
}
void reportTestResultsForComponent(String componentName, List<String> testTypes, Map testResults) {
if (!this.jira) return
def testComponent = "${componentName ?: 'project'}"
def testMessage = componentName ? " for component '${componentName}'" : ''
if (logger.debugMode) {
logger.debug('Reporting unit test results to corresponding test cases in Jira' +
"${testMessage}. Test type: '${testTypes}'.\nTest results: ${testResults}")
}
logger.startClocked("${testComponent}-jira-fetch-tests-${testTypes}")
def testIssues = this.project.getAutomatedTests(componentName, testTypes)
logger.debugClocked("${testComponent}-jira-fetch-tests-${testTypes}",
"Found automated tests$testMessage. Test type: ${testTypes}: " +
"${testIssues?.size()}")
this.util.warnBuildIfTestResultsContainFailure(testResults)
this.matchTestIssuesAgainstTestResults(testIssues, testResults, null) { unexecutedJiraTests ->
if (!unexecutedJiraTests.isEmpty()) {
this.util.warnBuildAboutUnexecutedJiraTests(unexecutedJiraTests)
}
}
logger.startClocked("${testComponent}-jira-report-tests-${testTypes}")
this.support.applyXunitTestResults(testIssues, testResults)
logger.debugClocked("${testComponent}-jira-report-tests-${testTypes}")
if (['Q', 'P'].contains(this.project.buildParams.targetEnvironmentToken)) {
logger.startClocked("${testComponent}-jira-report-bugs-${testTypes}")
// Create bugs for erroneous test issues
def errors = JUnitParser.Helper.getErrors(testResults)
this.createBugsForFailedTestIssues(testIssues, errors, this.steps.env.RUN_DISPLAY_URL)
// Create bugs for failed test issues
def failures = JUnitParser.Helper.getFailures(testResults)
this.createBugsForFailedTestIssues(testIssues, failures, this.steps.env.RUN_DISPLAY_URL)
logger.debugClocked("${testComponent}-jira-report-bugs-${testTypes}")
}
}
void reportTestResultsForProject(List<String> testTypes, Map testResults) {
// No componentName passed to method to get all automated issues from project
this.reportTestResultsForComponent(
null, testTypes, testResults)
}
void updateJiraReleaseStatusBuildNumber() {
if (!this.jira) return
def releaseStatusIssueKey = this.project.buildParams.releaseStatusJiraIssueKey
def releaseStatusIssueFields = this.project.getJiraFieldsForIssueType(JiraUseCase.IssueTypes.RELEASE_STATUS)
def releaseStatusIssueBuildNumberField = releaseStatusIssueFields['Release Build']
this.jira.updateTextFieldsOnIssue(releaseStatusIssueKey, [(releaseStatusIssueBuildNumberField.id): "${this.project.buildParams.version}-${this.steps.env.BUILD_NUMBER}"])
}
void updateJiraReleaseStatusResult(String message, boolean isError) {
if (!this.jira) {
logger.warn("updateJiraReleaseStatusResult: Could *NOT* update release status result because jira has invalid value.")
return
}
def status = isError ? 'Failed' : 'Successful'
logger.info("Updating Jira release status with result ${status} and comment ${message}")
def releaseStatusIssueKey = this.project.buildParams.releaseStatusJiraIssueKey
def releaseStatusIssueFields = this.project.getJiraFieldsForIssueType(JiraUseCase.IssueTypes.RELEASE_STATUS)
def releaseStatusIssueReleaseManagerStatusField = releaseStatusIssueFields['Release Manager Status']
this.jira.updateSelectListFieldsOnIssue(releaseStatusIssueKey, [(releaseStatusIssueReleaseManagerStatusField.id): status])
logger.startClocked("jira-update-release-${releaseStatusIssueKey}")
addCommentInReleaseStatus(message)
logger.debugClocked("jira-update-release-${releaseStatusIssueKey}")
}
void addCommentInReleaseStatus(String message) {
def releaseStatusIssueKey = this.project.buildParams.releaseStatusJiraIssueKey
if (message) {
String commentToAdd = "${message}\n\nSee: ${this.steps.env.RUN_DISPLAY_URL}"
commentToAdd += "\n\nPlease note that for a successful Deploy to D, the above-mentioned issues need to be in status Done."
logger.debug("Adding comment to Jira issue with key ${releaseStatusIssueKey}: ${commentToAdd}")
this.jira.appendCommentToIssue(releaseStatusIssueKey, commentToAdd)
logger.info("Comment was added to Jira issue with key ${releaseStatusIssueKey}: ${commentToAdd}")
} else {
logger.warn("*NO* Comment was added to Jira issue with key ${releaseStatusIssueKey}")
}
}
Long getLatestDocVersionId(List<Map> trackingIssues) {
def documentationTrackingIssueFields = this.project.getJiraFieldsForIssueType(IssueTypes.DOCUMENTATION_TRACKING)
def documentVersionField = documentationTrackingIssueFields[CustomIssueFields.DOCUMENT_VERSION].id as String
// We will use the biggest ID available
def versionList = trackingIssues.collect { issue ->
def versionNumber = 0L
def version = this.jira.getTextFieldsOfIssue(issue.key as String, [documentVersionField])?.getAt(documentVersionField)
if (version) {
try {
versionNumber = version.toLong()
} catch (NumberFormatException _) {
this.logger.warn("Document tracking issue '${issue.key}' does not contain a valid numerical" +
" version. It contains value '${version}'.")
}
}
return versionNumber
}
def result = versionList.max()
logger.debug("Retrieved max doc version ${versionList.max()} from doc tracking issues " +
"${trackingIssues.collect { it.key } }")
return result
}
private void walkTestIssuesAndTestResults(List testIssues, Map testResults, Closure visitor) {
testResults.testsuites.each { testSuite ->
testSuite.testcases.each { testCase ->
def testIssue = testIssues.find { testIssue ->
this.checkTestsIssueMatchesTestCase(testIssue, testCase)
}
def isMatch = testIssue != null
visitor(testIssue, testCase, isMatch)
}
}
}
@NonCPS
private thumbnailImageReplacement(content) {
def matcher = content =~ /<a.*id="(.*)_thumb".*href="(.*?)"/
matcher.each {
def imageMatcher = content =~ /<a.*id="${it[1]}_thumb".*src="(.*?)"/
content = content.replace(imageMatcher[0][1], it[2])
}
}
}