I have several folders trying to seperate my tests up into unit, integration, 3rd party, db. This way I can have my tests seperated into chunks purposes, to make TDD easier/faster. Here is the task that I am trying to use.
task integrationTest(type: Test) {
testClassesDir = sourceSets.integration.output.classesDir
classpath = sourceSets.integration.runtimeClasspath
maxParallelForks 8
maxHeapSize = "4048m"
}
I know there is testReportDir, but it's deprecated. I want to be able to use the new method.
I have tried the following closures:
reports {
html = file("$buildDir/reports/intTests")
}
reports {
setDestination = file("$buildDir/reports/intTests")
}
reports {
destinationDir = file("$buildDir/reports/intTests")
}
destinationDir = file("$buildDir/reports/intTests")
I think you want
integrationTest.reports.html.destination = file("$buildDir/reports/intTests")
You may want to consult the api docs for TestTaskReports which shows that the html report is a DirectoryReport extending ConfigurableReport and that that provides the destination accessor referred to in the one liner above.
Maybe you can implement your own task of type TestReport similar to here. Note the feature is incubating though.
Related
I want to execute tagged JUnit 5 tests, eg. only slow tests, with gradle.
I want to do the same like this in maven:
mvn test -Dgroups="slow"
But what is the equivalent in gradle? Or is there anything at all?
To execute all JUnit 5 tests which are marked with #Tag("slow"). I know it's quite simple to create a dedicated task like this:
tasks.withType(Test::class.java).configureEach {
useJUnitPlatform() {
includeTags("slow")
}
}
But I have a lot of different tags and I don't want to have a task for each single tag. Or worse, having one task for all permutations.
Another possibility would be to pass self defined properties to the task like this
tasks.withType(Test::class.java).configureEach {
val includeTagsList = System.getProperty("includeTags", "")!!.split(",")
.map { it.trim() }
.filter { it.isNotBlank() }
if (includeTagsList.isNotEmpty()) {
includeTags(*includeTagsList.toTypedArray())
}
}
The last time I checked, Gradle didn't have built-in support for configuring JUnit Platform include and exclude tags via the command line, so you'll have to go with your second approach.
But... there's no need to split, map, and filter the tags: just use a tag expression instead: https://junit.org/junit5/docs/current/user-guide/#running-tests-tag-expressions
You can create a separate task and to choose do you want to run the task or to skip it.
For example add this code in build.gradle:
def slowTests= tasks.register("slowTests", Test) {
useJUnitPlatform {
includeTags "slow"
}
}
Now if you want to run only slow tests:
./gradlew clean build -x test slowTests
Background: Running Android Studio 3.0-beta7 and trying to get a javadoc task to work for an Android library (the fact that this is not available as a ready-made task in the first place is really strange), and I managed to tweak an answer to a different question for my needs, ending up with this code (https://stackoverflow.com/a/46810617/1226020):
task javadoc(type: Javadoc) {
failOnError false
source = android.sourceSets.main.java.srcDirs
// Also add the generated R class to avoid errors...
// TODO: debug is hard-coded
source += "$buildDir/generated/source/r/debug/"
// ... but exclude the R classes from the docs
excludes += "**/R.java"
// TODO: "compile" is deprecated in Gradle 4.1,
// but "implementation" and "api" are not resolvable :(
classpath += configurations.compile
afterEvaluate {
// Wait after evaluation to add the android classpath
// to avoid "buildToolsVersion is not specified" error
classpath += files(android.getBootClasspath())
// Process AAR dependencies
def aarDependencies = classpath.filter { it.name.endsWith('.aar') }
classpath -= aarDependencies
aarDependencies.each { aar ->
System.out.println("Adding classpath for aar: " + aar.name)
// Extract classes.jar from the AAR dependency, and add it to the javadoc classpath
def outputPath = "$buildDir/tmp/exploded-aar/${aar.name.replace('.aar', '.jar')}"
classpath += files(outputPath)
// Use a task so the actual extraction only happens before the javadoc task is run
dependsOn task(name: "extract ${aar.name}").doLast {
extractEntry(aar, 'classes.jar', outputPath)
}
}
}
}
// Utility method to extract only one entry in a zip file
private def extractEntry(archive, entryPath, outputPath) {
if (!archive.exists()) {
throw new GradleException("archive $archive not found")
}
def zip = new java.util.zip.ZipFile(archive)
zip.entries().each {
if (it.name == entryPath) {
def path = new File(outputPath)
if (!path.exists()) {
path.getParentFile().mkdirs()
// Surely there's a simpler is->os utility except
// the one in java.nio.Files? Ah well...
def buf = new byte[1024]
def is = zip.getInputStream(it)
def os = new FileOutputStream(path)
def len
while ((len = is.read(buf)) != -1) {
os.write(buf, 0, len)
}
os.close()
}
}
}
zip.close()
}
This code tries to find all dependency AAR:s, loops through them and extracts classes.jar from them, and puts them in a temp folder that is added to the classpath during javadoc generation. Basically trying to reproduce what the really old android gradle plugin used to do with "exploded-aar".
However, the code relies on using compile dependencies. Using api or implementation that are recommended with Gradle 4.1 will not work, since these are not resolvable from a Gradle task.
Question: how can I get a list of dependencies using the api or implementation directives when e.g. configuration.api renders a "not resolvable" error?
Bonus question: is there a new, better way to create javadocs for a library with Android Studio 3.0 that doesn't involve 100 lines of workarounds?
You can wait for this to be merged:
https://issues.apache.org/jira/browse/MJAVADOC-450
Basically, the current Maven Javadoc plugin ignores classifiers such as AAR.
I ran in to the same problem when trying your answer to this question when this error message kept me from resolving the implementation dependencies:
Resolving configuration 'implementation' directly is not allowed
Then I discovered that this answer has a solution that makes resolving of the implementation and api configurations possible:
configurations.implementation.setCanBeResolved(true)
I'm not sure how dirty this workaround is, but it seems to do the trick for the javadocJar task situation.
I want to generate both HTML and console report in CodeNarc in Gradle.
My build.gradle:
apply plugin: 'codenarc'
...
codenarc {
toolVersion = '0.24.1'
configFile = file('config/codenarc/codenarc.groovy')
reportFormat = 'html'
}
This works fine, but I'd like also to have report displayed on console, as right now only link to HTML is displayed there. How can I request multiple report types?
Instead of running a second task to generate another report, you could make the following change to add another report format.
Then grab one of the files and write it to the console.
(You could just grab the HTML or XML report and write that to the console, but it may be hard to read without some formatting.)
Note: The reports closure will get you reports in different formats. The doLast will print the output of one of those reports to the console. If you do not need the console output, you can remove the doLast closure.
I would suggest changing your task like this:
task codenarcConsoleReport {
doLast {
println file("${codenarc.reportsDir}/main.txt").text
}
}
codenarcMain {
finalizedBy codenarcConsoleReport
reports {
text.enabled = true
html.enabled = true
xml {
enabled = true
destination = file("${codenarc.reportsDir}/customFileName.xml")
}
}
}
Note: This will not cause your task to run twice.
Best way I can think of is to create a separate task:
task codeNarcConsole(type: CodeNarc) {
// other config
reportFormat = 'console'
}
check.dependsOn('codeNarcConsole')
Not ideal, but workable. You could also post to Gradle Bugs about this to get it improved.
Let's say that I have created separate tasks for running integration and acceptance tests in my gradle build script. When I run the build task I want to run testing tasks before in this order: unit tests(test task), integration tests (intergationTest task) and acceptance tests (acceptanceTest task). Is this possible and how?
You are looking for "should run after" described in Gradle documentation - http://www.gradle.org/docs/current/userguide/more_about_tasks.html
Here's how you can do it without creating artificial dependencies:
https://caffeineinduced.wordpress.com/2015/01/25/run-a-list-of-gradle-tasks-in-specific-order/
TLDR; version:
//--- build aliases : define a synonym here if you want a shortcut to run multiple targets
def buildAliases = [
'all' : ['clean', 'assemble', 'runProvisioner', 'stopTomcat', 'installTomcat', 'deployToTomcat', 'startTomcat'],
'rebuild' : ['clean', 'assemble']
]
def expandedTaskList = []
gradle.startParameter.taskNames.each {
expandedTaskList << (buildAliases[it] ? buildAliases[it] : it)
}
gradle.startParameter.taskNames = expandedTaskList.flatten()
println "\n\n\texpanded task list: ${gradle.startParameter.taskNames }\n\n"
This is what I did on my projects.
check.dependsOn integTest
integTest.mustRunAfter test
tasks.withType(Pmd) {
mustRunAfter integTest // Pointing to a task
}
tasks.withType(FindBugs) {
mustRunAfter tasks.withType(Pmd) // Pointing to a group of tasks under Pmd
}
tasks.withType(Checkstyle) {
mustRunAfter tasks.withType(FindBugs)
}
It helped me to order tasks by group.
I created this helper method based on a solution that I found on Gradle forum.
Task.metaClass.runFirst = { Task... others ->
delegate.dependsOn(others)
delegate.mustRunAfter(others[0])
for (def i=0; i < others.size() - 1; i++) {
def before = others[i]
def after = others[i+1]
after.mustRunAfter(before)
}
}
Then you can create tasks X, A, B and C and use like this:
X.runFirst A, B, C
The first answer in the list turned out to be great for me. I used
X.shouldRunAfter Y
UPDATE: While using this "solution" for a short while i found out, that it does not work 100% as intended. I don't know why though. Any help to make it work would be appreciated. Maybe it does not work properly when there is more than one task in the Set?! While testing i did add some dummy-Tasks which only printed a text inbetween each of the other tasks and all seemed to be ok.
After some attempts with other solutions i came up with this solution:
It uses the mustRunAfter command to chain Sets of Tasks into the required order.
I'm working with Sets instead of individual Tasks, because i got circular dependency issues otherwise, since some tasks already depended on each other.
Also important to note: the isNotEmpty() check was essential, as it would otherwise break the enforced ordering if an ampty set was passed to the method.
tasks.register("cleanAndGenerate") {
var lastTasks: Set<Task> = setOf()
fun findTasks(taskName: String): Set<Task> {
return if (taskName.startsWith(":")) { // task in specific sub-project
setOf(tasks.findByPath(taskName)!!)
} else { // tasks in all (sub-)projects
getTasksByName(taskName, true)
}
}
fun dependsOnSequential(taskName: String) {
val tasks = findTasks(taskName)
tasks.forEach { task -> task.mustRunAfter(lastTasks) }
dependsOn(tasks)
if (tasks.isNotEmpty()) {
lastTasks = tasks
}
}
dependsOnSequential(":project1:clean") // task in specific sub-project
dependsOnSequential(":project2:clean")
dependsOnSequential("task1") // tasks in all (sub-)projects
dependsOnSequential("task2")
// add more as needed
}
We have two databases for which we'd like to manage their migrations using flyway's gradle plugin.
I'd like to have a single task that can migrate both databases. However, I can't seem to get the flywayMigrate task to be called twice from a single task.
Here's what I have...
task migrateFoo() {
doFirst {
flyway {
url = 'jdbc:mysql://localhost/foo'
user = 'root'
password = 'password'
locations = ['filesystem:dev/src/db/foo']
sqlMigrationPrefix = ""
initOnMigrate = true
outOfOrder = true
}
}
doLast {
tasks.flywayMigrate.execute()
}
}
task migrateBar() {
doFirst {
flyway {
url = 'jdbc:mysql://localhost/bar'
user = 'root'
password = 'password'
locations = ['filesystem:dev/src/db/bar']
sqlMigrationPrefix = ""
initOnMigrate = true
outOfOrder = true
}
}
doLast {
tasks.flywayMigrate.execute()
}
}
task migrate(dependsOn: ['migrateFoo','migrateBar']) {}
Explicitly calling either migrateFoo or migrateBar from the command line works fine, however, if I try to call the migrate task only database foo is updated.
Both the doFirst and doLast tasks of the migrateBar task are called, however, the tasks.flywayMigrate.execute() task isn't called the second time from migrateBar.
How can I get flyway to migrate both foo and bar from a single task?
First, you should never call execute() on a task (bad things will happen). Also, a task will be executed at most once per Gradle invocation.
To answer your question, apparently the flyway plugin doesn't support having multiple tasks of the same type. Looking at its implementation, I think you'll have to roll your own task. Something like:
import com.googlecode.flyway.core.Flyway
import org.katta.gradle.plugin.flyway.task.AbstractFlywayTask
class MigrateOtherDb extends AbstractFlywayTask {
#Override
void executeTask(Flyway flyway) {
// set any flyway properties here that differ from
// those common with other flyway tasks
println "Executing flyway migrate"
flyway.migrate()
}
task migrateOtherDb(type: MigrateOtherDb)
I recommend to file a feature request to support multiple tasks of the same type, with a convenient way to configure them.
I also had the same problem. I wanted to run flyway migrations for different databases and even for the same database with different configurations in ONE gradle build.
for each database i need to migrate normal data tables and static data tables, so i use two flyway version tables and also two locations for the scripts. E.g.
ENV: dev MIGRATION1: data (locations: db/scripts/data table: _flyway_version_data)
MIGRATION2: static (locations: db/scripts/static table: _flyway_version_static)
ENV: test MIGRATION1 ....
MIGRATION2 ....
As Peter states above, the flyway tasks are only executed ONCE no matter how often you call them.
The workaround i found does not seem to be nicest, but it works:
in build.gradle
task migrateFlywayDevData(type: GradleBuild) {
buildFile = 'build.gradle'
tasks = ['flywayMigrate']
startParameter.projectProperties = [env: "dev", type="data"]
}
task migrateFlywayDevStatic(type: GradleBuild) {
buildFile = 'build.gradle'
tasks = ['flywayMigrate']
startParameter.projectProperties = [env: "test", type="static"]
}
....(task defs for test env)
Basically i create a new gradle build for each of the configurations.
"buildFile = 'build.gradle'"
refers to itself, so all code is contained in one build.gradle file.
The gradle call is then:
gradle migrateFlywayDevData migrateFlywayDevStatic ...
This is the first version. so code might be easily improved.
However this solution lets you execute flyway tasks multiple times with one gradle call.
Feel free to comment (flyway plugin configuration is not shown here)