Skip to content

Commit

Permalink
Publish failed gradle test results
Browse files Browse the repository at this point in the history
Signed-off-by: Rishabh Singh <[email protected]>
  • Loading branch information
rishabh6788 committed Mar 20, 2024
1 parent 0721e85 commit 81d2858
Showing 1 changed file with 94 additions and 0 deletions.
94 changes: 94 additions & 0 deletions vars/publishGradleCheckTestResults.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

/** Library to fetch failing tests at the end of gradle-check run and index the results in an OpenSearch cluster.
*
* @param Map args = [:] args A map of the following parameters
* @param args.prNumber <required> - The pull_request number that triggered the gradle-check run. If Null then use post_merge_action string.
* @param args.prDescription <required> - The subject of the pull_request. If prNumber is null then it signifies push action on branch.
*/

import hudson.tasks.test.AbstractTestResultAction
import groovy.json.JsonOutput
import java.text.SimpleDateFormat
import java.util.Date

void call(Map args = [:]) {
def lib = library(identifier: 'jenkins@main', retriever: legacySCM(scm))
def finalJsonDoc = ""
def buildNumber = currentBuild.number
def buildDescription = currentBuild.description
def buildDuration = currentBuild.duration
def buildResult = currentBuild.result
def buildStartTime = currentBuild.startTimeInMillis
def prString = isNullOrEmpty(args.prNumber.toString()) ? "post_merge_action" : "${args.prNumber}"
def prDescription = args.prDescription.toString()
def currentDate = new Date()
def formattedDate = new SimpleDateFormat("MM-yyyy").format(currentDate)

println("The formatted date is ${formattedDate}")
def indexName = "gradle-check-${formattedDate}"


def test_docs = getFailedTestRecords(buildNumber, prString, prDescription, buildResult, buildDuration, buildStartTime)

if (test_docs) {
for (doc in test_docs) {
def jsonDoc = JsonOutput.toJson(doc)
finalJsonDoc += "{\"index\": {\"_index\": \"${indexName}\"}}\n" + "${jsonDoc}\n"
}
writeFile file: "failed-test-records.json", text: finalJsonDoc

def fileContents = readFile(file: "failed-test-records.json").trim()
println("File Content is:\n${fileContents}")
indexFailedTestData()
}
}

List<Map<String, String>> getFailedTestRecords(buildNumber, prString, prDescription, buildResult, buildDuration, buildStartTime) {
def testResults = []
AbstractTestResultAction testResultAction = currentBuild.rawBuild.getAction(AbstractTestResultAction.class)
if (testResultAction != null) {
def testsTotal = testResultAction.totalCount
def testsFailed = testResultAction.failCount
def testsSkipped = testResultAction.skipCount
def testsPassed = testsTotal - testsFailed - testsSkipped
def failedTests = testResultAction.getFailedTests()

if (failedTests){
for (test in failedTests) {
def failDocument = ['build_number': buildNumber, 'pull_request': prString, 'pr_description': prDescription, 'test_class': test.getParent().getName(), 'test_name': test.fullName, 'test_status': 'FAILED', 'build_result': buildResult, 'test_fail_count': testsFailed, 'test_skipped_count': testsSkipped, 'test_passed_count': testsPassed, 'build_duration': buildDuration, 'build_start_time': buildStartTime]
testResults.add(failDocument)
}
} else {
println("No test failed.")
}
}
return testResults
}

void indexFailedTestData() {

withCredentials([
string(credentialsId: 'jenkins-metric-account-number', variable: 'METRICS_ACCOUNT_NUMBER')
]) {
withAWS(role: 'jenkins-metric-account-role', roleAccount: "${METRICS_ACCOUNT_NUMBER}", duration: 900, roleSessionName: 'test-session') {
awsCredentials, awsRegion ->
// Extract access key, secret key, and session token from credentials object
def accessKeyId = awsCredentials.getAWSAccessKeyId()
def secretAccessKey = awsCredentials.getAWSSecretKey()
def sessionToken = awsCredentials.getSessionToken()

println("The creds are ${accessKeyId}, ${secretAccessKey}, ${sessionToken}")
}

}
}

boolean isNullOrEmpty(String str) { return (str == 'Null' || str.allWhitespace || str.isEmpty()) }

0 comments on commit 81d2858

Please sign in to comment.