从gradle项目目录创建jacoco exec文件

从gradle项目目录创建jacoco exec文件,gradle,jacoco,gradle-plugin,Gradle,Jacoco,Gradle Plugin,如何将jacocoexec文件的位置从自定义gradle插件更改为不在项目目录中。我的插件中有以下代码: project.afterEvaluate { def testTasks = project.tasks.withType(Test) testTasks.each { task -> task.jacoco.destinationFile = file("/home/skgupta/jacoco/${task.name}.exec") } }

如何将jacoco
exec
文件的位置从自定义gradle插件更改为不在项目目录中。我的插件中有以下代码:

project.afterEvaluate {
    def testTasks = project.tasks.withType(Test)
    testTasks.each { task ->
        task.jacoco.destinationFile = file("/home/skgupta/jacoco/${task.name}.exec")
    }
}
但是当我运行测试时,
.exec
文件是在
/jacoco/.exec
下生成的

当我在我的
build.gradle
中更改
destinationFile
目录的值时,它工作得非常好

我错过了什么

编辑:这里是插件的完整代码

class TestInfraPlugin implements Plugin<Project> {

    Project project

    void apply(Project target) {
        this.project = target
        logger = target.logger
        configureConfigurations(target)
        configureTestNG()
        configureCodeCoverage(target)
    }

    public void configureTestNG() {
        logger.debug "Configuring the EMTest task with default values."
        project.afterEvaluate {
            project.ext.testClassesDir = new File(project.properties['emdi.T_WORK'] + '/testClasses')
            /* Create one task of type ExtractConfiguration, to extract the lrgConfig configuration to $T_WORK/testClasses
             * The extraction of the test jar before the tests are run is mandatory because the 'Test' task 
             * ONLY works on the files in directory and NOT on the jars. Thus we extract the jar and point the testClasses 
             * property to the location where the jar is extracted.
             *  
             * NOTE: 
             *  1. This is only one task per gradle. 
             *  2. All the jars in the lrgConfig are extracted before any testblock is run.
             *  3. The LRG will not run if user uses other configuration than 'lrgConfig'
             *     (which applies without cutover to 'Test' task also.)
             */
            def testTasks = project.tasks.withType(EMTest)
            /* Silently log and return if there are no EMTest tasks. 
             * This case would be hit :
             *     a) When testinfraPlugin is applied to build.gradle
             *     b) (in Future)if <lrg>.gradle has test-blocks of non-Java types.
             */
            if (testTasks != null && testTasks.size() == 0) {
                logger.info "There are no tasks of type EMTest."
                return
            }

            def extractTask = project.tasks.findByPath('extractTestClasses') ?:
                    project.task('extractTestClasses', type: ExtractConfiguration) {
                        configuration = project.configurations.testConfig
                        to = project.testClassesDir
                    }
            /* 
             * 1. Adding the 'extractTask' to all EMTest, to ensure that 'extractTask' is run before any 'EMTest'.
             * 2. For lazy evaluation of lrgConfig, we are NOT running the task here, but just adding as dependent task.
             */
            testTasks.each { task ->
                logger.debug "Adding dependsOn extractTask for task: ${task.name}"
                task.dependsOn extractTask
                /* TODO: The code below is to change the location of the jacoco file, but it is not working
                 * When the same is tried directly from build.gradle (tried as fresh project), it works.
                 * I have opened SO question as: http://stackoverflow.com/questions/28039011/create-jacoco-exec-file-out-of-gradle-project-dir
                 * If we have solution for this, we can get-away with the workaround we applied in the TestResultsHandler.groovy
                 *
                 * NOTE: I tried with beforeEvaluate, and it really does not work because EMTest tasks are not evaluated by then.
                 * I also tried with 'java.io.File', etc other options. Nothing works.
                 *
                 */
                task.jacoco.destinationFile = task.project.file( '/scratch/skgupta/git_storage/emdi/work/jacocobuild/' + task.name + '.exec')
                println "Value of destinationFile in jacoco extension is "+ task.jacoco.getDestinationFile()
            }
        }

       logger.debug "Applying plugins implicitly."
        applyPlugin('java')
    /* Apply jacoco plugin */
        applyPlugin('jacoco')

    }

    /**
     * Apply plugin with given name.
     * 
     * @param pluginName - The name of the plugin to apply.
     * 
     */
    protected void applyPlugin(String pluginName) {
        logger.debug "Checking if the plugin, ${pluginName} is already applied."
        if (project.plugins.hasPlugin(pluginName)) {
            logger.debug "Plugin is already applied."
            return
        }
        logger.debug "Applying plugin, ${pluginName}"
        project.apply plugin: pluginName

        logger.debug "Verifying if the plugin is applied."
        if (project.plugins.hasPlugin(pluginName)) {
            logger.debug "Successfully applied plugin, ${pluginName}"
        }
        else {
            logger.error "Failed to apply plugin, ${pluginName}"
        }
    }

    /**
     * Add the configuration, lrgConfig, to the current project.
     *
     * The configuration lrgConfig defines the dependencies for the tools like testng, restassured, etc.
     * @param project - the project to which the config will be added.
     */
    protected void configureConfigurations(Project project) {
        logger.debug "Creating the configurations to hold tools GAV"
        project.configurations {
            /* This will be empty configuration, and will be populated by lrg owner with gav of the lrg jar */
            testConfig

            /* This will be empty configuration, and will be populated by lrg owner during test jar build */
            lrgConfig

            /* Configuration to hold the gav of the testng jar(s) */
            testNG

            /* Configuration to hold the GAV of the webdriver jar(s) */
            webdriver

            /* Configuration to hold the GAV of the restAssured jar(s) */
            restAssured
        }
        project.dependencies {
            /* 
             * Currently adding opensource testng jar path here. This will be replaced by
             * GAV of the tools testng only jar once they decouple it.
             * Bug 19276096 - SPLIT OUT TESTNG JAR FROM EM-QATOOL-UIFWK-WEBDRIVER.JAR| 
             */
            testNG group: 'com.mycomp.myprod.emdi', name: 'em-qatool-uifwk-webdriver',version: '1.0.0', transitive: false

            /*
             * webdriver config would contain reference to the tools webdriver jar, which currently
             * also has testng fwk in it. This will be replaced by gav of the webdriver only jar once
             * it is decoupled
             * Bug 19276096 - SPLIT OUT TESTNG JAR FROM EM-QATOOL-UIFWK-WEBDRIVER.JAR| 
             */
            webdriver group: 'com.mycomp.myprod.emdi', name: 'em-qatool-uifwk-webdriver',version: '1.0.0', transitive: false

            /* Add rest-assured libraries */
            restAssured group: 'org.codehaus.groovy', name:'groovy-all', version:'2.2.1'
            restAssured group: 'com.jayway.restassured', name:'json-path', version:'1.8.1'
            restAssured group: 'org.apache.commons', name:'commons-lang3', version:'3.1'
            restAssured group: 'org.hamcrest', name:'hamcrest-core', version: '1.3'
            restAssured group: 'org.apache.httpcomponents', name:'httpclient', version:'4.3.1'
            restAssured group: 'org.apache.httpcomponents', name:'httpcore', version:'4.3'
            restAssured group: 'org.apache.httpcomponents', name:'httpmime', version:'4.3.1'
            restAssured group: 'com.jayway.restassured', name:'xml-path', version:'1.9.0'
            restAssured group: 'com.jayway.restassured', name:'rest-assured-common', version:'2.3.1'
            restAssured group: 'com.jayway.restassured', name:'rest-assured', version:'2.3.1'
        }
        /* 
         * Currently the QA's build.gradle use lrgConfig for compilation. 
         * Hence setting lrgConfig as well with the testng gav for backward compatibility
         * TODO: This must be removed in future versions of testinfra 
         * 
         */
        project.configurations.lrgConfig.extendsFrom(project.configurations.testNG, project.configurations.restAssured)
    }
}
类TestInfraPlugin实现插件{
工程项目
无效申请(项目目标){
this.project=target
logger=target.logger
配置配置(目标)
configureTestNG()
ConfigureCodeOverage(目标)
}
public void configureTestNG(){
logger.debug“使用默认值配置EMTest任务。”
项目后评估{
project.ext.testClassesDir=新文件(project.properties['emdi.T_-WORK']+'/testClasses')
/*创建一个ExtractConfiguration类型的任务,将lrgConfig配置提取到$T_WORK/TestClass
*必须在运行测试之前提取测试jar,因为“测试”任务
*只在目录中的文件上工作,而不在jar上工作
*属性设置为提取jar的位置。
*  
*注:
*1.每个年级只有一项任务。
*2.在运行任何测试块之前,将提取lrgConfig中的所有JAR。
*3.如果用户使用“lrgConfig”以外的其他配置,LRG将不会运行
*(也适用于“测试”任务,无需切换。)
*/
def testTasks=project.tasks.withType(EMTest)
/*如果没有EMTest任务,则以静默方式记录并返回。
*这种情况将受到以下影响:
*a)当testinfraPlugin应用于build.gradle时
*b)(将来)if.gradle有非Java类型的测试块。
*/
if(testTasks!=null&&testTasks.size()=0){
logger.info“没有EMTest类型的任务。”
返回
}
def extractTask=project.tasks.findByPath('extractTestClasses')?:
任务('ExtractTestClass',类型:ExtractConfiguration){
配置=project.configurations.testConfig
to=project.testClassesDir
}
/* 
*1.将“extractTask”添加到所有EMTest,以确保在任何“EMTest”之前运行“extractTask”。
*2.对于lrgConfig的延迟评估,我们不在这里运行任务,而只是添加为依赖任务。
*/
testTasks.each{task->
logger.debug“为任务${task.name}添加dependsOn extractTask”
task.dependsOn提取任务
/*TODO:下面的代码用于更改jacoco文件的位置,但它不起作用
*当直接从build.gradle(尝试作为新项目)尝试相同的方法时,它会起作用。
*我提出的问题如下:http://stackoverflow.com/questions/28039011/create-jacoco-exec-file-out-of-gradle-project-dir
*如果我们对此有解决方案,我们就可以不使用在TestResultsHandler.groovy中应用的变通方法
*
*注意:我尝试了beforeEvaluate,但它确实不起作用,因为EMTest任务在此之前不会被评估。
*我还尝试了“java.io.File”等其他选项。没有任何效果。
*
*/
task.jacoco.destinationFile=task.project.file('/scratch/skgupta/git_storage/emdi/work/jacobuild/'+task.name+'.exec'))
println“jacoco扩展中destinationFile的值为”+task.jacoco.getDestinationFile()
}
}
logger.debug“隐式应用插件”
applyPlugin('java')
/*应用jacoco插件*/
applyPlugin('jacoco')
}
/**
*应用具有给定名称的插件。
* 
*@param pluginName-要应用的插件的名称。
* 
*/
受保护的void applyPlugin(字符串pluginName){
logger.debug“检查插件${pluginName}是否已应用。”
if(project.plugins.hasPlugin(pluginName)){
logger.debug“插件已应用。”
返回
}
logger.debug“正在应用插件,${pluginName}”
project.apply插件:pluginName
logger.debug“验证插件是否已应用。”
if(project.plugins.hasPlugin(pluginName)){
logger.debug“已成功应用插件,${pluginName}”
}
否则{
logger.error“未能应用插件,${pluginName}”
}
}
/**
*将配置lrgConfig添加到当前项目。
*
*配置lrgConfig定义了testng、restassured等工具的依赖关系。
*@param project-将添加配置的项目。
*/
受保护的无效配置(项目){
logger.debug“创建用于保存工具GAV的配置”
project.configurations{
/*这将是空配置,由lrg所有者使用lrg jar的gav填充*/
测试配置
/*这将是空配置,在测试jar构建期间由lrgowner填充*/
lrgConfig
/*用于保存testng jar的gav的配置*/
testNG
/*保存webdriver jar的GAV的配置*/
网络驱动程序
/*用于保持重新启动的jar的GAV的配置*/
R
   test {
     maxParallelForks = 5
     forkEvery = 50
     ignoreFailures = true

     testReportDir = file("$buildDir/reports/tests/UT")
     testResultsDir = file("$buildDir/test-results/UT")

     //testLogging.showStandardStreams = true

     //onOutput { descriptor, event ->
     //    logger.lifecycle("Test: " + descriptor + " produced standard out/err: " + event.message )
     //}

     //Following Jacoco test section is required only in Jenkins instance extra common file
     jacoco {
        //The following vars works ONLY with 1.6 of Gradle
        destPath = file("$buildDir/jacoco/UT/jacocoUT.exec")
        classDumpPath = file("$buildDir/jacoco/UT/classpathdumps")

        //Following vars works only with versions >= 1.7 version of Gradle
        //destinationFile = file("$buildDir/jacoco/UT/jacocoUT.exec")
        //  classDumpFile = file("$buildDir/jacoco/UT/classpathdumps")
     }
   }

   task integrationTest( type: Test) {
     //Always run tests
     outputs.upToDateWhen { false }
     ignoreFailures = true

     testClassesDir = sourceSets.integrationTest.output.classesDir
     classpath = sourceSets.integrationTest.runtimeClasspath

     testReportDir = file("$buildDir/reports/tests/IT")
     testResultsDir = file("$buildDir/test-results/IT")

     //Following Jacoco test section is required only in Jenkins instance extra common file
     //jacoco {
        //This works with 1.6
      //  destPath = file("$buildDir/jacoco/IT/jacocoIT.exec")
      //  classDumpPath = file("$buildDir/jacoco/IT/classpathdumps")

        //Following works only with versions >= 1.7 version of Gradle
        //destinationFile = file("$buildDir/jacoco/IT/jacocoIT.exec")
        //  classDumpFile = file("$buildDir/jacoco/IT/classpathdumps")
     //}
  }
project.gradle.taskGraph.whenReady {
  //integrationTest {
  //  ignoreFailures = true
  //}
}