/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Display all failed tests at the end of the build.

def failedTests = new LinkedHashSet() // for dedupe due to weird afterTest classMethod issue

def genFailInfo(def task, TestDescriptor desc) {
  boolean isSuite = (desc.name == 'classMethod')
  def name = isSuite ? desc.className : "${desc.className}.${desc.name}"
  def historyUrl = "https://develocity.apache.org/scans/tests?search.rootProjectNames=solr-root&tests.container=$desc.className"
  if (!isSuite) { // is test method specific
    historyUrl += "&tests.test=$desc.name"
    historyUrl += " http://fucit.org/solr-jenkins-reports/history-trend-of-recent-failures.html#series/$name"
  }
  def logName = buildinfra.getOutputLogName(desc.parent ?: desc)
  def output = file("${task.testOutputsDir}/${logName}")
  def repro = "./gradlew ${task.project.path}:test --tests \"${name}\" ${task.project.testOptionsForReproduceLine}"
  return ["name": name, "project": "${task.project.path}", "historyUrl": historyUrl, "output": output, "reproduce": repro]
}

allprojects {
  plugins.withType(JavaPlugin).configureEach {
    tasks.withType(Test).configureEach { Test task ->
      afterTest { desc, result ->
        if (result.resultType == TestResult.ResultType.FAILURE) {
          failedTests << genFailInfo(task, desc)
        }
      }

      afterSuite { desc, result ->
        if (result.exceptions) {
          failedTests << genFailInfo(task, desc)
        }
      }
    }
  }
}

gradle.buildFinished { result ->
  if (!failedTests) return
  def formatted = failedTests
      .sort { a, b -> b.project <=> a.project }
      .collect { e -> """
  - ${e.name} (${e.project})
    Test history: ${e.historyUrl}
    Test output: ${e.output}
    Reproduce with: ${e.reproduce}
""" // In Groovy there is no incidental leading whitespace, so must fully left justify
      }
      .join()

  logger.error("ERROR: The following test(s) have failed:${formatted}")
}
