Reformat :kotlin-gradle-plugin-integration-tests

This commit is contained in:
Alexey Tsvetkov
2018-05-04 17:58:37 +03:00
parent 39c000bb4d
commit f00e243822
28 changed files with 556 additions and 423 deletions
@@ -1,6 +1,5 @@
package org.jetbrains.kotlin.gradle
import org.gradle.util.VersionNumber
import org.jetbrains.kotlin.gradle.util.getFileByName
import org.jetbrains.kotlin.gradle.util.getFilesByNames
import org.jetbrains.kotlin.gradle.util.isLegacyAndroidGradleVersion
@@ -10,7 +9,9 @@ import org.junit.Test
import java.io.File
class KotlinAndroidGradleIT : AbstractKotlinAndroidGradleTests(gradleVersion = GradleVersionRequired.AtLeast("3.4"), androidGradlePluginVersion = "2.3.0")
class KotlinAndroidGradleIT :
AbstractKotlinAndroidGradleTests(gradleVersion = GradleVersionRequired.AtLeast("3.4"), androidGradlePluginVersion = "2.3.0")
class KotlinAndroidWithJackGradleIT : AbstractKotlinAndroidWithJackGradleTests(androidGradlePluginVersion = "2.3.+")
// TODO If we there is a way to fetch the latest Android plugin version, test against the latest version
@@ -31,17 +32,17 @@ abstract class KotlinAndroid3GradleIT(
File(project.projectDir, "Lib/build.gradle").modify { text ->
// Change the applied plugin to com.android.feature
text.replace("com.android.library", "com.android.feature")
.replace("compileSdkVersion 22", "compileSdkVersion 26")
.apply { assert(!equals(text)) }
.replace("compileSdkVersion 22", "compileSdkVersion 26")
.apply { assert(!equals(text)) }
}
// Check that Kotlin tasks were created for both lib and feature variants:
val kotlinTaskNames =
listOf("Debug", "Release").flatMap { buildType ->
listOf("Flavor1", "Flavor2").flatMap { flavor ->
listOf("", "Feature").map { isFeature -> ":Lib:compile$flavor$buildType${isFeature}Kotlin" }
}
listOf("Debug", "Release").flatMap { buildType ->
listOf("Flavor1", "Flavor2").flatMap { flavor ->
listOf("", "Feature").map { isFeature -> ":Lib:compile$flavor$buildType${isFeature}Kotlin" }
}
}
project.build(":Lib:assemble") {
assertSuccessful()
@@ -56,8 +57,10 @@ abstract class AbstractKotlinAndroidGradleTests(
) : BaseGradleIT() {
override fun defaultBuildOptions() =
super.defaultBuildOptions().copy(androidHome = KotlinTestUtils.findAndroidSdk(),
androidGradlePluginVersion = androidGradlePluginVersion)
super.defaultBuildOptions().copy(
androidHome = KotlinTestUtils.findAndroidSdk(),
androidGradlePluginVersion = androidGradlePluginVersion
)
@Test
fun testSimpleCompile() {
@@ -132,11 +135,13 @@ abstract class AbstractKotlinAndroidGradleTests(
}
val getSomethingKt = project.projectDir.walk().filter { it.isFile && it.name.endsWith("getSomething.kt") }.first()
getSomethingKt.writeText("""
getSomethingKt.writeText(
"""
package foo
fun getSomething() = 10
""")
"""
)
project.build("assembleDebug", options = options) {
assertSuccessful()
@@ -149,8 +154,8 @@ fun getSomething() = 10
fun testIncrementalBuildWithNoChanges() {
val project = Project("AndroidIncrementalSingleModuleProject", gradleVersion)
val tasksToExecute = arrayOf(
":app:compileDebugKotlin",
":app:compileDebugJavaWithJavac"
":app:compileDebugKotlin",
":app:compileDebugJavaWithJavac"
)
project.build("assembleDebug") {
@@ -174,8 +179,12 @@ fun getSomething() = 10
}
val androidModuleKt = project.projectDir.getFileByName("AndroidModule.kt")
androidModuleKt.modify { it.replace("fun provideApplicationContext(): Context {",
"fun provideApplicationContext(): Context? {") }
androidModuleKt.modify {
it.replace(
"fun provideApplicationContext(): Context {",
"fun provideApplicationContext(): Context? {"
)
}
// rebuilt because DaggerApplicationComponent.java was regenerated
val baseApplicationKt = project.projectDir.getFileByName("BaseApplication.kt")
// rebuilt because BuildConfig.java was regenerated (timestamp was changed)
@@ -183,11 +192,13 @@ fun getSomething() = 10
project.build(":app:assembleDebug", options = options) {
assertSuccessful()
assertCompiledKotlinSources(project.relativize(
assertCompiledKotlinSources(
project.relativize(
androidModuleKt,
baseApplicationKt,
useBuildConfigJavaKt
))
)
)
}
}
@@ -231,7 +242,7 @@ fun getSomething() = 10
project.build("assembleDebug", options = options) {
assertSuccessful()
val affectedSources = project.projectDir.getFilesByNames(
"MyActivity.kt", "noLayoutUsages.kt"
"MyActivity.kt", "noLayoutUsages.kt"
)
val relativePaths = project.relativize(affectedSources)
assertCompiledKotlinSources(relativePaths)
@@ -304,14 +315,16 @@ fun getSomething() = 10
abstract class AbstractKotlinAndroidWithJackGradleTests(
private val androidGradlePluginVersion: String
private val androidGradlePluginVersion: String
) : BaseGradleIT() {
fun getEnvJDK_18() = System.getenv()["JDK_18"]
override fun defaultBuildOptions() =
super.defaultBuildOptions().copy(androidHome = KotlinTestUtils.findAndroidSdk(),
androidGradlePluginVersion = androidGradlePluginVersion, javaHome = File(getEnvJDK_18()))
super.defaultBuildOptions().copy(
androidHome = KotlinTestUtils.findAndroidSdk(),
androidGradlePluginVersion = androidGradlePluginVersion, javaHome = File(getEnvJDK_18())
)
@Test
fun testSimpleCompile() {
@@ -92,9 +92,9 @@ abstract class BaseGradleIT {
@Synchronized
fun prepareWrapper(
version: String,
environmentVariables: Map<String, String> = mapOf(),
withDaemon: Boolean = true
version: String,
environmentVariables: Map<String, String> = mapOf(),
withDaemon: Boolean = true
): File {
val wrapperDir = gradleWrappers.getOrPut(version) { createNewWrapperDir(version) }
@@ -121,11 +121,11 @@ abstract class BaseGradleIT {
private fun createNewWrapperDir(version: String): File =
createTempDir("GradleWrapper-$version-")
.apply {
File(BaseGradleIT.resourcesRootFile, "GradleWrapper").copyRecursively(this)
val wrapperProperties = File(this, "gradle/wrapper/gradle-wrapper.properties")
wrapperProperties.modify { it.replace("<GRADLE_WRAPPER_VERSION>", version) }
}
.apply {
File(BaseGradleIT.resourcesRootFile, "GradleWrapper").copyRecursively(this)
val wrapperProperties = File(this, "gradle/wrapper/gradle-wrapper.properties")
wrapperProperties.modify { it.replace("<GRADLE_WRAPPER_VERSION>", version) }
}
private val runnerGradleVersion = System.getProperty("runnerGradleVersion")
@@ -160,19 +160,19 @@ abstract class BaseGradleIT {
// the second parameter is for using with ToolingAPI, that do not like --daemon/--no-daemon options at all
data class BuildOptions(
val withDaemon: Boolean = false,
val daemonOptionSupported: Boolean = true,
val incremental: Boolean? = null,
val androidHome: File? = null,
val javaHome: File? = null,
val androidGradlePluginVersion: String? = null,
val forceOutputToStdout: Boolean = false,
val debug: Boolean = false,
val freeCommandLineArgs: List<String> = emptyList(),
val kotlinVersion: String = KOTLIN_VERSION,
val kotlinDaemonDebugPort: Int? = null,
val usePreciseJavaTracking: Boolean? = null,
val withBuildCache: Boolean = false
val withDaemon: Boolean = false,
val daemonOptionSupported: Boolean = true,
val incremental: Boolean? = null,
val androidHome: File? = null,
val javaHome: File? = null,
val androidGradlePluginVersion: String? = null,
val forceOutputToStdout: Boolean = false,
val debug: Boolean = false,
val freeCommandLineArgs: List<String> = emptyList(),
val kotlinVersion: String = KOTLIN_VERSION,
val kotlinDaemonDebugPort: Int? = null,
val usePreciseJavaTracking: Boolean? = null,
val withBuildCache: Boolean = false
)
open inner class Project(
@@ -190,10 +190,10 @@ abstract class BaseGradleIT {
}
fun relativize(files: Iterable<File>): List<String> =
files.map { it.relativeTo(projectDir).path }
files.map { it.relativeTo(projectDir).path }
fun relativize(vararg files: File): List<String> =
files.map { it.relativeTo(projectDir).path }
files.map { it.relativeTo(projectDir).path }
fun performModifications() {
for (file in projectDir.walk()) {
@@ -222,13 +222,19 @@ abstract class BaseGradleIT {
}
private fun getCompiledFiles(regex: Regex, output: String) = regex.findAll(output)
.asIterable()
.flatMap { it.groups[1]!!.value.split(", ")
.map { File(project.projectDir, it).canonicalFile } }
.asIterable()
.flatMap {
it.groups[1]!!.value.split(", ")
.map { File(project.projectDir, it).canonicalFile }
}
fun getCompiledKotlinSources(output: String) = getCompiledFiles(kotlinSourcesListRegex, output)
val compiledJavaSources: Iterable<File> by lazy { javaSourcesListRegex.findAll(output).asIterable().flatMap { it.groups[1]!!.value.split(" ").filter { it.endsWith(".java", ignoreCase = true) }.map { File(it).canonicalFile } } }
val compiledJavaSources: Iterable<File> by lazy {
javaSourcesListRegex.findAll(output).asIterable().flatMap {
it.groups[1]!!.value.split(" ").filter { it.endsWith(".java", ignoreCase = true) }.map { File(it).canonicalFile }
}
}
}
// Basically the same as `Project.build`, tells gradle to wait for debug on 5005 port
@@ -254,8 +260,7 @@ abstract class BaseGradleIT {
val result = runProcess(cmd, projectDir, env, options)
try {
CompiledProject(this, result.output, result.exitCode).check()
}
catch (t: Throwable) {
} catch (t: Throwable) {
// to prevent duplication of output
if (!options.forceOutputToStdout) {
System.out.println(result.output)
@@ -370,10 +375,17 @@ abstract class BaseGradleIT {
return this
}
fun CompiledProject.assertContainFiles(expected: Iterable<String>, actual: Iterable<String>, messagePrefix: String = ""): CompiledProject {
fun CompiledProject.assertContainFiles(
expected: Iterable<String>,
actual: Iterable<String>,
messagePrefix: String = ""
): CompiledProject {
val expectedNormalized = expected.map(::normalizePath).toSortedSet()
val actualNormalized = actual.map(::normalizePath).toSortedSet()
assertTrue(actualNormalized.containsAll(expectedNormalized), messagePrefix + "expected files: ${expectedNormalized.joinToString()}\n !in actual files: ${actualNormalized.joinToString()}")
assertTrue(
actualNormalized.containsAll(expectedNormalized),
messagePrefix + "expected files: ${expectedNormalized.joinToString()}\n !in actual files: ${actualNormalized.joinToString()}"
)
return this
}
@@ -403,33 +415,33 @@ abstract class BaseGradleIT {
fun CompiledProject.getOutputForTask(taskName: String): String {
val taskOutputRegex = ("\\[LIFECYCLE] \\[class org\\.gradle(?:\\.internal\\.buildevents)?\\.TaskExecutionLogger] :$taskName" +
"([\\s\\S]+?)" +
"Finished executing task ':$taskName'").toRegex()
"([\\s\\S]+?)" +
"Finished executing task ':$taskName'").toRegex()
return taskOutputRegex.find(output)?.run { groupValues[1] } ?: error("Cannot find output for task $taskName")
}
fun CompiledProject.assertCompiledKotlinSources(
sources: Iterable<String>,
weakTesting: Boolean = false,
tasks: List<String>) {
sources: Iterable<String>,
weakTesting: Boolean = false,
tasks: List<String>
) {
for (task in tasks) {
assertCompiledKotlinSources(sources, weakTesting, getOutputForTask(task), suffix = " in task ${task}")
}
}
fun CompiledProject.assertCompiledKotlinSources(
expectedSources: Iterable<String>,
weakTesting: Boolean = false,
output: String = this.output,
suffix: String = ""
expectedSources: Iterable<String>,
weakTesting: Boolean = false,
output: String = this.output,
suffix: String = ""
): CompiledProject {
val messagePrefix = "Compiled Kotlin files differ${suffix}:\n "
val actualSources = getCompiledKotlinSources(output).projectRelativePaths(this.project)
return if (weakTesting) {
assertContainFiles(expectedSources, actualSources, messagePrefix)
}
else {
} else {
assertSameFiles(expectedSources, actualSources, messagePrefix)
}
}
@@ -441,23 +453,23 @@ abstract class BaseGradleIT {
projectDir.getFileByName(name)
fun CompiledProject.assertCompiledJavaSources(
sources: Iterable<String>,
weakTesting: Boolean = false
sources: Iterable<String>,
weakTesting: Boolean = false
): CompiledProject =
if (weakTesting)
assertContainFiles(sources, compiledJavaSources.projectRelativePaths(this.project), "Compiled Java files differ:\n ")
else
assertSameFiles(sources, compiledJavaSources.projectRelativePaths(this.project), "Compiled Java files differ:\n ")
if (weakTesting)
assertContainFiles(sources, compiledJavaSources.projectRelativePaths(this.project), "Compiled Java files differ:\n ")
else
assertSameFiles(sources, compiledJavaSources.projectRelativePaths(this.project), "Compiled Java files differ:\n ")
fun Project.resourcesDir(subproject: String? = null, sourceSet: String = "main"): String =
(subproject?.plus("/") ?: "") + "build/" +
(if (testGradleVersionBelow("4.0")) "classes/" else "resources/") +
sourceSet + "/"
(subproject?.plus("/") ?: "") + "build/" +
(if (testGradleVersionBelow("4.0")) "classes/" else "resources/") +
sourceSet + "/"
fun Project.classesDir(subproject: String? = null, sourceSet: String = "main", language: String = "kotlin"): String =
(subproject?.plus("/") ?: "") + "build/classes/" +
(if (testGradleVersionAtLeast("4.0")) "$language/" else "") +
sourceSet + "/"
(subproject?.plus("/") ?: "") + "build/classes/" +
(if (testGradleVersionAtLeast("4.0")) "$language/" else "") +
sourceSet + "/"
fun Project.testGradleVersionAtLeast(version: String): Boolean =
GradleVersion.version(chooseWrapperVersionOrFinishTest()) >= GradleVersion.version(version)
@@ -465,73 +477,73 @@ abstract class BaseGradleIT {
fun Project.testGradleVersionBelow(version: String): Boolean = !testGradleVersionAtLeast(version)
fun CompiledProject.kotlinClassesDir(subproject: String? = null, sourceSet: String = "main"): String =
project.classesDir(subproject, sourceSet, language = "kotlin")
project.classesDir(subproject, sourceSet, language = "kotlin")
fun CompiledProject.javaClassesDir(subproject: String? = null, sourceSet: String = "main"): String =
project.classesDir(subproject, sourceSet, language = "java")
project.classesDir(subproject, sourceSet, language = "java")
private fun Project.createBuildCommand(wrapperDir: File, params: Array<out String>, options: BuildOptions): List<String> =
createGradleCommand(wrapperDir, createGradleTailParameters(options, params))
createGradleCommand(wrapperDir, createGradleTailParameters(options, params))
fun Project.gradleBuildScript(subproject: String? = null): File =
File(projectDir, subproject?.plus("/").orEmpty() + "build.gradle")
private fun Project.createGradleTailParameters(options: BuildOptions, params: Array<out String> = arrayOf()): List<String> =
params.toMutableList().apply {
add("--stacktrace")
when (minLogLevel) {
// Do not allow to configure Gradle project with `ERROR` log level (error logs visible on all log levels)
LogLevel.ERROR -> error("Log level ERROR is not supported by Gradle command-line")
// Omit log level argument for default `LIFECYCLE` log level,
// because there is no such command-line option `--lifecycle`
// see https://docs.gradle.org/current/userguide/logging.html#sec:choosing_a_log_level
LogLevel.LIFECYCLE -> Unit
//Command line option for other log levels
else -> add("--${minLogLevel.name.toLowerCase()}")
}
if (options.daemonOptionSupported) {
add(if (options.withDaemon) "--daemon" else "--no-daemon")
}
add("-Pkotlin_version=" + options.kotlinVersion)
options.incremental?.let { add("-Pkotlin.incremental=$it") }
options.usePreciseJavaTracking?.let { add("-Pkotlin.incremental.usePreciseJavaTracking=$it") }
options.androidGradlePluginVersion?.let { add("-Pandroid_tools_version=$it")}
if (options.debug) {
add("-Dorg.gradle.debug=true")
}
options.kotlinDaemonDebugPort?.let { port ->
add("-Dkotlin.daemon.jvm.options=-agentlib:jdwp=transport=dt_socket\\,server=y\\,suspend=y\\,address=$port")
}
System.getProperty("maven.repo.local")?.let {
add("-Dmaven.repo.local=$it") // TODO: proper escaping
}
if (options.withBuildCache) {
add("--build-cache")
} else {
// Override possibly enabled system-wide caching:
add("-Dorg.gradle.caching=false")
}
// Workaround: override a console type set in the user machine gradle.properties (since Gradle 4.3):
add("--console=plain")
addAll(options.freeCommandLineArgs)
params.toMutableList().apply {
add("--stacktrace")
when (minLogLevel) {
// Do not allow to configure Gradle project with `ERROR` log level (error logs visible on all log levels)
LogLevel.ERROR -> error("Log level ERROR is not supported by Gradle command-line")
// Omit log level argument for default `LIFECYCLE` log level,
// because there is no such command-line option `--lifecycle`
// see https://docs.gradle.org/current/userguide/logging.html#sec:choosing_a_log_level
LogLevel.LIFECYCLE -> Unit
//Command line option for other log levels
else -> add("--${minLogLevel.name.toLowerCase()}")
}
if (options.daemonOptionSupported) {
add(if (options.withDaemon) "--daemon" else "--no-daemon")
}
add("-Pkotlin_version=" + options.kotlinVersion)
options.incremental?.let { add("-Pkotlin.incremental=$it") }
options.usePreciseJavaTracking?.let { add("-Pkotlin.incremental.usePreciseJavaTracking=$it") }
options.androidGradlePluginVersion?.let { add("-Pandroid_tools_version=$it") }
if (options.debug) {
add("-Dorg.gradle.debug=true")
}
options.kotlinDaemonDebugPort?.let { port ->
add("-Dkotlin.daemon.jvm.options=-agentlib:jdwp=transport=dt_socket\\,server=y\\,suspend=y\\,address=$port")
}
System.getProperty("maven.repo.local")?.let {
add("-Dmaven.repo.local=$it") // TODO: proper escaping
}
if (options.withBuildCache) {
add("--build-cache")
} else {
// Override possibly enabled system-wide caching:
add("-Dorg.gradle.caching=false")
}
// Workaround: override a console type set in the user machine gradle.properties (since Gradle 4.3):
add("--console=plain")
addAll(options.freeCommandLineArgs)
}
private fun createEnvironmentVariablesMap(options: BuildOptions): Map<String, String> =
hashMapOf<String, String>().apply {
options.androidHome?.let { sdkDir ->
sdkDir.parentFile.mkdirs()
put("ANDROID_HOME", sdkDir.canonicalPath)
}
options.javaHome?.let {
put("JAVA_HOME", it.canonicalPath)
}
hashMapOf<String, String>().apply {
options.androidHome?.let { sdkDir ->
sdkDir.parentFile.mkdirs()
put("ANDROID_HOME", sdkDir.canonicalPath)
}
options.javaHome?.let {
put("JAVA_HOME", it.canonicalPath)
}
}
private fun String.normalize() = this.lineSequence().joinToString(SYSTEM_LINE_SEPARATOR)
fun copyRecursively(source: File, target: File) {
@@ -7,7 +7,8 @@ import org.junit.runners.Parameterized.Parameters
@RunWith(Parameterized::class)
abstract class BaseMultiGradleVersionIT : BaseGradleIT() {
@Parameter lateinit var gradleVersionString: String
@Parameter
lateinit var gradleVersionString: String
protected val gradleVersion get() = GradleVersionRequired.Exact(gradleVersionString)
@@ -22,7 +22,7 @@ import java.io.File
class BuildCacheIT : BaseGradleIT() {
override fun defaultBuildOptions(): BuildOptions =
super.defaultBuildOptions().copy(withBuildCache = true)
super.defaultBuildOptions().copy(withBuildCache = true)
companion object {
private val GRADLE_VERSION = GradleVersionRequired.AtLeast("4.3")
@@ -145,11 +145,13 @@ class BuildCacheIT : BaseGradleIT() {
assertContains("Caching disabled for task ':kaptKotlin': 'Caching is disabled by default for kapt")
}
File(projectDir, "build.gradle").appendText("\n" + """
File(projectDir, "build.gradle").appendText(
"\n" + """
afterEvaluate {
kaptKotlin.useBuildCache = true
}
""".trimIndent())
""".trimIndent()
)
build("clean", "build") {
assertSuccessful()
@@ -28,10 +28,11 @@ import kotlin.test.assertEquals
class BuildCacheRelocationIT : BaseGradleIT() {
override fun defaultBuildOptions(): BuildOptions =
super.defaultBuildOptions().copy(
withBuildCache = true,
androidGradlePluginVersion = "3.0.0",
androidHome = KotlinTestUtils.findAndroidSdk())
super.defaultBuildOptions().copy(
withBuildCache = true,
androidGradlePluginVersion = "3.0.0",
androidHome = KotlinTestUtils.findAndroidSdk()
)
@Parameterized.Parameter
lateinit var testCase: TestCase
@@ -70,19 +71,19 @@ class BuildCacheRelocationIT : BaseGradleIT() {
assertEquals(firstOutputHashes, secondOutputHashes)
cacheableTaskNames.forEach { assertContains(":$it FROM-CACHE") }
}
}
finally {
} finally {
workingDir = originalWorkingDir
workingDirs.forEach { it.deleteRecursively() }
}
}
class TestCase(
val projectName: String,
val cacheableTaskNames: List<String>,
val projectDirectoryPrefix: String? = null,
val outputRootPaths: List<String> = listOf("build"),
val initProject: Project.() -> Unit = { }) {
val projectName: String,
val cacheableTaskNames: List<String>,
val projectDirectoryPrefix: String? = null,
val outputRootPaths: List<String> = listOf("build"),
val initProject: Project.() -> Unit = { }
) {
override fun toString(): String = (projectDirectoryPrefix?.plus("/") ?: "") + projectName
@@ -96,62 +97,65 @@ class BuildCacheRelocationIT : BaseGradleIT() {
@JvmStatic
@Parameterized.Parameters(name = "project: {0}")
fun testCases(): List<Array<TestCase>> = listOf(
TestCase("simpleProject",
cacheableTaskNames = listOf("compileKotlin", "compileTestKotlin")
),
TestCase("simple", projectDirectoryPrefix = "kapt2",
cacheableTaskNames = listOf(
"kaptKotlin", "kaptGenerateStubsKotlin", "compileKotlin", "compileTestKotlin", "compileJava"),
initProject = { File(projectDir, "build.gradle").appendText("\nkapt.useBuildCache = true") }
),
TestCase("kotlin2JsDceProject",
cacheableTaskNames = listOf("mainProject", "libraryProject").map { "$it:compileKotlin2Js" } +
"mainProject:runDceKotlinJs",
initProject = {
// Fix the problem that the destinationDir of the compile task (i.e. buildDir) contains files from other tasks:
File(projectDir, "mainProject/build.gradle").modify { it.replace("/exampleapp.js", "/web/exampleapp.js") }
File(projectDir, "libraryProject/build.gradle").modify { it.replace("/examplelib.js", "/web/examplelib.js") }
// Fix assembling the JAR from the whole buildDir
File(projectDir, "libraryProject/build.gradle").modify {
it.replace("from buildDir", "from compileKotlin2Js.destinationDir")
TestCase(
"simpleProject",
cacheableTaskNames = listOf("compileKotlin", "compileTestKotlin")
),
TestCase("simple", projectDirectoryPrefix = "kapt2",
cacheableTaskNames = listOf(
"kaptKotlin", "kaptGenerateStubsKotlin", "compileKotlin", "compileTestKotlin", "compileJava"
),
initProject = { File(projectDir, "build.gradle").appendText("\nkapt.useBuildCache = true") }
),
TestCase("kotlin2JsDceProject",
cacheableTaskNames = listOf("mainProject", "libraryProject").map { "$it:compileKotlin2Js" } +
"mainProject:runDceKotlinJs",
initProject = {
// Fix the problem that the destinationDir of the compile task (i.e. buildDir) contains files from other tasks:
File(projectDir, "mainProject/build.gradle").modify { it.replace("/exampleapp.js", "/web/exampleapp.js") }
File(projectDir, "libraryProject/build.gradle").modify { it.replace("/examplelib.js", "/web/examplelib.js") }
// Fix assembling the JAR from the whole buildDir
File(projectDir, "libraryProject/build.gradle").modify {
it.replace("from buildDir", "from compileKotlin2Js.destinationDir")
}
}
),
TestCase("multiplatformProject",
cacheableTaskNames = listOf(
"lib:compileKotlinCommon", "libJvm:compileKotlin", "libJvm:compileTestKotlin",
"libJs:compileKotlin2Js", "libJs:compileTestKotlin2Js"
),
outputRootPaths = listOf("lib", "libJvm", "libJs").map { "$it/build" }
),
TestCase("AndroidProject",
cacheableTaskNames = listOf("Lib", "Android").flatMap { module ->
listOf("Flavor1", "Flavor2").flatMap { flavor ->
listOf("Debug", "Release").map { buildType ->
"$module:compile$flavor${buildType}Kotlin"
}
}
),
TestCase("multiplatformProject",
cacheableTaskNames = listOf(
"lib:compileKotlinCommon", "libJvm:compileKotlin", "libJvm:compileTestKotlin",
"libJs:compileKotlin2Js", "libJs:compileTestKotlin2Js"),
outputRootPaths = listOf("lib", "libJvm", "libJs").map { "$it/build" }
),
TestCase("AndroidProject",
cacheableTaskNames = listOf("Lib", "Android").flatMap { module ->
listOf("Flavor1", "Flavor2").flatMap { flavor ->
listOf("Debug", "Release").map { buildType ->
"$module:compile$flavor${buildType}Kotlin"
}
}
},
outputRootPaths = listOf("Lib", "Android", "Test").map { "$it/build" }
),
TestCase("android-dagger", projectDirectoryPrefix = "kapt2",
cacheableTaskNames = listOf("Debug", "Release").flatMap { buildType ->
listOf("kapt", "kaptGenerateStubs", "compile").map { kotlinTask ->
"app:$kotlinTask${buildType}Kotlin"
}
},
outputRootPaths = listOf("app/build"),
initProject = { File(projectDir, "app/build.gradle").appendText("\nkapt.useBuildCache = true") }
)
},
outputRootPaths = listOf("Lib", "Android", "Test").map { "$it/build" }
),
TestCase("android-dagger", projectDirectoryPrefix = "kapt2",
cacheableTaskNames = listOf("Debug", "Release").flatMap { buildType ->
listOf("kapt", "kaptGenerateStubs", "compile").map { kotlinTask ->
"app:$kotlinTask${buildType}Kotlin"
}
},
outputRootPaths = listOf("app/build"),
initProject = { File(projectDir, "app/build.gradle").appendText("\nkapt.useBuildCache = true") }
)
).map { arrayOf(it) }
}
private val outputExtensions = setOf("java", "kt", "class", "js", "kotlin_module")
fun hashOutputFiles(directories: List<File>) =
directories.flatMap { dir ->
dir.walkTopDown()
.filter { it.extension in outputExtensions }
.map { it.relativeTo(dir) to it.readBytes().contentHashCode() }
.toList()
}
directories.flatMap { dir ->
dir.walkTopDown()
.filter { it.extension in outputExtensions }
.map { it.relativeTo(dir) to it.readBytes().contentHashCode() }
.toList()
}
}
@@ -41,7 +41,7 @@ class ClassFileIsRemovedIT : BaseGradleIT() {
}
}
fun doTest(buildOptions: BuildOptions, transformDummy: (File)->Unit) {
fun doTest(buildOptions: BuildOptions, transformDummy: (File) -> Unit) {
val project = Project("kotlinInJavaRoot")
project.build("build", options = buildOptions) {
assertSuccessful()
@@ -21,7 +21,7 @@ import org.jetbrains.kotlin.gradle.util.modify
import org.junit.Test
import java.io.File
class CoroutinesIT: BaseGradleIT() {
class CoroutinesIT : BaseGradleIT() {
companion object {
private const val LOCAL_PROPERTIES = "local.properties"
private const val GRADLE_PROPERTIES = "gradle.properties"
@@ -97,10 +97,10 @@ class CoroutinesIT: BaseGradleIT() {
// todo: replace with project that actually uses coroutines after their syntax is finalized
private val jvmProject: Project
get() = Project("kotlinProject")
get() = Project("kotlinProject")
private val jsProject: Project
get() = Project("kotlin2JsProject")
get() = Project("kotlin2JsProject")
private fun Project.doTest(coroutineSupport: String, propertyFileName: String?) {
if (propertyFileName != null) {
@@ -9,8 +9,10 @@ class ExecutionStrategyJsIT : ExecutionStrategyIT() {
override fun setupProject(project: Project) {
super.setupProject(project)
val buildGradle = File(project.projectDir, "app/build.gradle")
buildGradle.modify { it.replace("apply plugin: \"kotlin\"", "apply plugin: \"kotlin2js\"") +
"\ncompileKotlin2Js.kotlinOptions.outputFile = \"web/js/out.js\"" }
buildGradle.modify {
it.replace("apply plugin: \"kotlin\"", "apply plugin: \"kotlin2js\"") +
"\ncompileKotlin2Js.kotlinOptions.outputFile = \"web/js/out.js\""
}
}
override fun CompiledProject.checkOutput() {
@@ -60,7 +62,7 @@ open class ExecutionStrategyIT : BaseGradleIT() {
protected open fun setupProject(project: Project) {
project.setupWorkingDir()
File(project.projectDir, "app/build.gradle").appendText(
"\ntasks.withType(org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile).all { kotlinOptions.allWarningsAsErrors = true }"
"\ntasks.withType(org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile).all { kotlinOptions.allWarningsAsErrors = true }"
)
}
@@ -14,13 +14,15 @@ class IncrementalCompilationMultiProjectIT : BaseGradleIT() {
}
private fun androidBuildOptions() =
BuildOptions(withDaemon = true,
androidHome = KotlinTestUtils.findAndroidSdk(),
androidGradlePluginVersion = ANDROID_GRADLE_PLUGIN_VERSION,
incremental = true)
BuildOptions(
withDaemon = true,
androidHome = KotlinTestUtils.findAndroidSdk(),
androidGradlePluginVersion = ANDROID_GRADLE_PLUGIN_VERSION,
incremental = true
)
override fun defaultBuildOptions(): BuildOptions =
super.defaultBuildOptions().copy(withDaemon = true, incremental = true)
super.defaultBuildOptions().copy(withDaemon = true, incremental = true)
@Test
fun testDuplicatedClass() {
@@ -66,14 +68,16 @@ class IncrementalCompilationMultiProjectIT : BaseGradleIT() {
}
val aKt = project.projectDir.getFileByName("A.kt")
aKt.writeText("""
aKt.writeText(
"""
package bar
open class A {
fun a() {}
fun newA() {}
}
""")
"""
)
project.build("build") {
assertSuccessful()
@@ -96,8 +100,9 @@ open class A {
project.build("build") {
assertFailed()
val affectedSources = project.projectDir.getFilesByNames(
"B.kt", "barUseAB.kt", "barUseB.kt",
"BB.kt", "fooCallUseAB.kt", "fooUseB.kt")
"B.kt", "barUseAB.kt", "barUseB.kt",
"BB.kt", "fooCallUseAB.kt", "fooUseB.kt"
)
val relativePaths = project.relativize(affectedSources)
assertCompiledKotlinSources(relativePaths, weakTesting = false)
}
@@ -176,11 +181,13 @@ open class A {
val libGroovySrcBar = File(lib, "src/main/groovy/bar").apply { mkdirs() }
val groovyClass = File(libGroovySrcBar, "GroovyClass.groovy")
groovyClass.writeText("""
groovyClass.writeText(
"""
package bar
class GroovyClass {}
""")
"""
)
project.build("build") {
assertSuccessful()
@@ -269,24 +276,26 @@ abstract class IncrementalCompilationJavaChangesBase(val usePreciseJavaTracking:
}
override fun defaultBuildOptions(): BuildOptions =
super.defaultBuildOptions().copy(withDaemon = true, incremental = true)
super.defaultBuildOptions().copy(withDaemon = true, incremental = true)
protected val trackedJavaClass = "TrackedJavaClass.java"
private val javaClass = "JavaClass.java"
protected val changeBody: (String)->String = { it.replace("Hello, World!", "Hello, World!!!!") }
protected val changeSignature: (String)->String = { it.replace("String getString", "Object getString") }
protected val changeBody: (String) -> String = { it.replace("Hello, World!", "Hello, World!!!!") }
protected val changeSignature: (String) -> String = { it.replace("String getString", "Object getString") }
@Test
fun testModifySignatureJavaInLib() {
doTest(javaClass, changeBody,
expectedAffectedSources = listOf("JavaClassChild.kt", "useJavaClass.kt", "useJavaClassFooMethodUsage.kt")
doTest(
javaClass, changeBody,
expectedAffectedSources = listOf("JavaClassChild.kt", "useJavaClass.kt", "useJavaClassFooMethodUsage.kt")
)
}
@Test
fun testModifyBodyJavaInLib() {
doTest(javaClass, changeBody,
expectedAffectedSources = listOf("JavaClassChild.kt", "useJavaClass.kt", "useJavaClassFooMethodUsage.kt")
doTest(
javaClass, changeBody,
expectedAffectedSources = listOf("JavaClassChild.kt", "useJavaClass.kt", "useJavaClassFooMethodUsage.kt")
)
}
@@ -294,9 +303,9 @@ abstract class IncrementalCompilationJavaChangesBase(val usePreciseJavaTracking:
abstract fun testModifyBodyTrackedJavaInLib()
protected fun doTest(
fileToModify: String,
transformFile: (String)->String,
expectedAffectedSources: Collection<String>
fileToModify: String,
transformFile: (String) -> String,
expectedAffectedSources: Collection<String>
) {
val project = Project("incrementalMultiproject")
@@ -19,10 +19,12 @@ open class Kapt3AndroidIT : Kapt3BaseIT() {
get() = "2.3.0"
private fun androidBuildOptions() =
BuildOptions(withDaemon = true,
androidHome = KotlinTestUtils.findAndroidSdk(),
androidGradlePluginVersion = androidGradlePluginVersion,
freeCommandLineArgs = listOf("-Pkapt.verbose=true"))
BuildOptions(
withDaemon = true,
androidHome = KotlinTestUtils.findAndroidSdk(),
androidGradlePluginVersion = androidGradlePluginVersion,
freeCommandLineArgs = listOf("-Pkapt.verbose=true")
)
override fun defaultBuildOptions() = androidBuildOptions()
@@ -27,7 +27,7 @@ abstract class Kapt3BaseIT : BaseGradleIT() {
}
override fun defaultBuildOptions(): BuildOptions =
super.defaultBuildOptions().copy(withDaemon = true)
super.defaultBuildOptions().copy(withDaemon = true)
fun CompiledProject.assertKaptSuccessful() {
KAPT_SUCCESSFUL_REGEX.findAll(this.output).count() > 0
@@ -129,9 +129,11 @@ open class Kapt3IT : Kapt3BaseIT() {
Project("arguments", directoryPrefix = "kapt2").build("build") {
assertSuccessful()
assertKaptSuccessful()
assertContains("Options: {suffix=Customized, justColon=:, justEquals==, containsColon=a:b, " +
"containsEquals=a=b, startsWithColon=:a, startsWithEquals==a, endsWithColon=a:, " +
"endsWithEquals=a:, withSpace=a b c,")
assertContains(
"Options: {suffix=Customized, justColon=:, justEquals==, containsColon=a:b, " +
"containsEquals=a=b, startsWithColon=:a, startsWithEquals==a, endsWithColon=a:, " +
"endsWithEquals=a:, withSpace=a b c,"
)
assertContains("-Xmaxerrs=500, -Xlint:all=-Xlint:all") // Javac options test
assertFileExists("build/generated/source/kapt/main/example/TestClassCustomized.java")
assertFileExists(kotlinClassesDir() + "example/TestClass.class")
@@ -252,7 +254,7 @@ open class Kapt3IT : Kapt3BaseIT() {
// add annotation
val exampleAnn = "@example.ExampleAnnotation "
internalDummyKt.modify { it.addBeforeSubstring(exampleAnn, "internal class InternalDummy")}
internalDummyKt.modify { it.addBeforeSubstring(exampleAnn, "internal class InternalDummy") }
project.build("classes", options = options) {
assertSuccessful()
@@ -260,7 +262,7 @@ open class Kapt3IT : Kapt3BaseIT() {
}
// remove annotation
internalDummyKt.modify { it.replace(exampleAnn, "")}
internalDummyKt.modify { it.replace(exampleAnn, "") }
project.build("classes", options = options) {
assertSuccessful()
@@ -391,8 +393,10 @@ open class Kapt3IT : Kapt3BaseIT() {
project.build("build") {
assertSuccessful()
assertNotContains(":example:kaptKotlin UP-TO-DATE",
":example:kaptGenerateStubsKotlin UP-TO-DATE")
assertNotContains(
":example:kaptKotlin UP-TO-DATE",
":example:kaptGenerateStubsKotlin UP-TO-DATE"
)
assertContains("Additional warning message from AP")
}
@@ -6,7 +6,7 @@ import org.jetbrains.kotlin.gradle.util.modify
import org.junit.Test
import java.io.File
class KaptIT: BaseGradleIT() {
class KaptIT : BaseGradleIT() {
@Test
fun testSimple() {
@@ -11,7 +11,7 @@ class KaptIncrementalWithStubsIT : KaptIncrementalBaseIT(shouldUseStubs = true)
class Kapt3Incremental : KaptIncrementalBaseIT(shouldUseStubs = false, useKapt3 = true)
abstract class KaptIncrementalBaseIT(val shouldUseStubs: Boolean, val useKapt3: Boolean = false): BaseGradleIT() {
abstract class KaptIncrementalBaseIT(val shouldUseStubs: Boolean, val useKapt3: Boolean = false) : BaseGradleIT() {
init {
if (useKapt3) {
assert(!shouldUseStubs)
@@ -46,10 +46,10 @@ abstract class KaptIncrementalBaseIT(val shouldUseStubs: Boolean, val useKapt3:
}
private val annotatedElements =
arrayOf("A", "funA", "valA", "funUtil", "valUtil", "B", "funB", "valB", "useB")
arrayOf("A", "funA", "valA", "funUtil", "valUtil", "B", "funB", "valB", "useB")
override fun defaultBuildOptions(): BuildOptions =
super.defaultBuildOptions().copy(incremental = true)
super.defaultBuildOptions().copy(incremental = true)
@Test
fun testBasic() {
@@ -65,12 +65,16 @@ abstract class KaptIncrementalBaseIT(val shouldUseStubs: Boolean, val useKapt3:
project.build("build") {
assertSuccessful()
assertContains(":compileKotlin UP-TO-DATE",
":compileJava UP-TO-DATE")
assertContains(
":compileKotlin UP-TO-DATE",
":compileJava UP-TO-DATE"
)
if (useKapt3) {
assertContains(":kaptKotlin UP-TO-DATE",
":kaptGenerateStubsKotlin UP-TO-DATE")
assertContains(
":kaptKotlin UP-TO-DATE",
":kaptGenerateStubsKotlin UP-TO-DATE"
)
}
if (shouldUseStubs) {
@@ -171,7 +175,7 @@ abstract class KaptIncrementalBaseIT(val shouldUseStubs: Boolean, val useKapt3:
}
}
with (project.projectDir) {
with(project.projectDir) {
getFileByName("B.kt").delete()
getFileByName("useB.kt").delete()
}
@@ -222,14 +226,14 @@ abstract class KaptIncrementalBaseIT(val shouldUseStubs: Boolean, val useKapt3:
assertCompiledKotlinSources(project.relativize(bKt, useBKt), tasks = listOf("kaptGenerateStubsKotlin"))
// java removal is detected
assertCompiledKotlinSources(project.relativize(project.projectDir.allKotlinFiles()),
tasks = listOf("compileKotlin"))
}
else if (shouldUseStubs) {
assertCompiledKotlinSources(
project.relativize(project.projectDir.allKotlinFiles()),
tasks = listOf("compileKotlin")
)
} else if (shouldUseStubs) {
// java removal is detected
assertCompiledKotlinSources(project.relativize(project.projectDir.allKotlinFiles()))
}
else {
} else {
val useBKt = project.projectDir.getFileByName("useB.kt")
assertCompiledKotlinSources(project.relativize(bKt, useBKt))
}
@@ -258,12 +262,14 @@ abstract class KaptIncrementalBaseIT(val shouldUseStubs: Boolean, val useKapt3:
}
private fun CompiledProject.assertCompiledKotlinSourcesHandleKapt3(
sources: Iterable<String>,
weakTesting: Boolean = false
sources: Iterable<String>,
weakTesting: Boolean = false
) {
if (useKapt3) {
assertCompiledKotlinSources(sources, weakTesting,
tasks = listOf("compileKotlin", "kaptGenerateStubsKotlin"))
assertCompiledKotlinSources(
sources, weakTesting,
tasks = listOf("compileKotlin", "kaptGenerateStubsKotlin")
)
} else {
assertCompiledKotlinSources(sources, weakTesting)
}
@@ -271,8 +277,10 @@ abstract class KaptIncrementalBaseIT(val shouldUseStubs: Boolean, val useKapt3:
private fun CompiledProject.assertKapt3FullyExecuted() {
if (useKapt3) {
assertNotContains(":kaptKotlin UP-TO-DATE",
":kaptGenerateStubsKotlin UP-TO-DATE")
assertNotContains(
":kaptKotlin UP-TO-DATE",
":kaptGenerateStubsKotlin UP-TO-DATE"
)
}
}
@@ -300,8 +308,7 @@ abstract class KaptIncrementalBaseIT(val shouldUseStubs: Boolean, val useKapt3:
if (shouldUseStubs) {
assertContains(usingStubs)
}
else {
} else {
assertNotContains(usingStubs)
}
}
@@ -20,15 +20,16 @@ class Kotlin2JsGradlePluginIT : BaseGradleIT() {
assertReportExists()
assertContains(
":libraryProject:jarSources",
":mainProject:compileKotlin2Js",
":libraryProject:compileKotlin2Js"
":libraryProject:jarSources",
":mainProject:compileKotlin2Js",
":libraryProject:compileKotlin2Js"
)
listOf("mainProject/web/js/app.js",
"mainProject/web/js/lib/kotlin.js",
"libraryProject/build/kotlin2js/main/test-library.js",
"mainProject/web/js/app.js.map"
listOf(
"mainProject/web/js/app.js",
"mainProject/web/js/lib/kotlin.js",
"libraryProject/build/kotlin2js/main/test-library.js",
"mainProject/web/js/app.js.map"
).forEach { assertFileExists(it) }
}
@@ -67,8 +68,10 @@ class Kotlin2JsGradlePluginIT : BaseGradleIT() {
val jarPath = "build/libs/kotlin2JsNoOutputFileProject.jar"
assertFileExists(jarPath)
val jar = ZipFile(fileInWorkingDir(jarPath))
assertEquals(1, jar.entries().asSequence().count { it.name == "kotlin2JsNoOutputFileProject.js" },
"The jar should contain an entry `kotlin2JsNoOutputFileProject.js` with no duplicates")
assertEquals(
1, jar.entries().asSequence().count { it.name == "kotlin2JsNoOutputFileProject.js" },
"The jar should contain an entry `kotlin2JsNoOutputFileProject.js` with no duplicates"
)
}
}
@@ -83,8 +86,10 @@ class Kotlin2JsGradlePluginIT : BaseGradleIT() {
val jarPath = "build/libs/kotlin2JsModuleKind.jar"
assertFileExists(jarPath)
val jar = ZipFile(fileInWorkingDir(jarPath))
assertEquals(1, jar.entries().asSequence().count { it.name == "app.js" },
"The jar should contain an entry `app.js` with no duplicates")
assertEquals(
1, jar.entries().asSequence().count { it.name == "app.js" },
"The jar should contain an entry `app.js` with no duplicates"
)
}
}
@@ -116,8 +121,8 @@ class Kotlin2JsGradlePluginIT : BaseGradleIT() {
assertSuccessful()
assertContains(
":compileKotlin2Js",
":compileTestKotlin2Js"
":compileKotlin2Js",
":compileTestKotlin2Js"
)
assertFileExists("build/kotlin2js/main/module.js")
@@ -142,8 +147,8 @@ class Kotlin2JsGradlePluginIT : BaseGradleIT() {
assertSuccessful()
assertContains(
":compileKotlin2Js",
":compileIntegrationTestKotlin2Js"
":compileKotlin2Js",
":compileIntegrationTestKotlin2Js"
)
assertFileExists("build/kotlin2js/main/module.js")
@@ -152,8 +157,10 @@ class Kotlin2JsGradlePluginIT : BaseGradleIT() {
val jarPath = "build/libs/kotlin2JsProjectWithCustomSourceset-inttests.jar"
assertFileExists(jarPath)
val jar = ZipFile(fileInWorkingDir(jarPath))
assertEquals(1, jar.entries().asSequence().count { it.name == "module-inttests.js" },
"The jar should contain an entry `module-inttests.js` with no duplicates")
assertEquals(
1, jar.entries().asSequence().count { it.name == "module-inttests.js" },
"The jar should contain an entry `module-inttests.js` with no duplicates"
)
}
}
@@ -238,9 +245,9 @@ class Kotlin2JsGradlePluginIT : BaseGradleIT() {
project.setupWorkingDir()
File(project.projectDir, "mainProject/build.gradle").modify {
it + "\n" +
"runDceKotlinJs.dceOptions.outputDirectory = \"\${buildDir}/min\"\n" +
"runRhino.args = [\"-f\", \"min/kotlin.js\", \"-f\", \"min/examplelib.js\", \"-f\", \"min/exampleapp.js\"," +
"\"-f\", \"../check.js\"]\n"
"runDceKotlinJs.dceOptions.outputDirectory = \"\${buildDir}/min\"\n" +
"runRhino.args = [\"-f\", \"min/kotlin.js\", \"-f\", \"min/examplelib.js\", \"-f\", \"min/exampleapp.js\"," +
"\"-f\", \"../check.js\"]\n"
}
project.build("runRhino") {
@@ -262,7 +269,7 @@ class Kotlin2JsGradlePluginIT : BaseGradleIT() {
project.setupWorkingDir()
File(project.projectDir, "mainProject/build.gradle").modify {
it + "\n" +
"runDceKotlinJs.dceOptions.devMode = true\n"
"runDceKotlinJs.dceOptions.devMode = true\n"
}
project.build("runRhino") {
@@ -45,7 +45,11 @@ class KotlinDaemonIT : BaseGradleIT() {
assert(createdSessions.size == 1) { "Created multiple sessions per build ${createdSessions.joinToString()}" }
val existingSessions = output.findAllStringsPrefixed(EXISTING_SESSION_FILE_PREFIX)
Assert.assertArrayEquals("Existing sessions don't match created sessions for two module projects", createdSessions, existingSessions)
Assert.assertArrayEquals(
"Existing sessions don't match created sessions for two module projects",
createdSessions,
existingSessions
)
val deletedSessions = output.findAllStringsPrefixed(DELETED_SESSION_FILE_PREFIX)
Assert.assertArrayEquals("Deleted sessions don't match created sessions", createdSessions, deletedSessions)
@@ -28,7 +28,7 @@ import kotlin.test.assertNotEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class KotlinGradleIT: BaseGradleIT() {
class KotlinGradleIT : BaseGradleIT() {
@Test
fun testCrossCompile() {
@@ -42,7 +42,12 @@ class KotlinGradleIT: BaseGradleIT() {
project.build("compileDeployKotlin", "build") {
assertSuccessful()
assertContains(":compileKotlin UP-TO-DATE", ":compileTestKotlin UP-TO-DATE", ":compileDeployKotlin UP-TO-DATE", ":compileJava UP-TO-DATE")
assertContains(
":compileKotlin UP-TO-DATE",
":compileTestKotlin UP-TO-DATE",
":compileDeployKotlin UP-TO-DATE",
":compileJava UP-TO-DATE"
)
}
}
@@ -98,7 +103,7 @@ class KotlinGradleIT: BaseGradleIT() {
val MEMORY_MAX_GROWTH_LIMIT_KB = 500
val BUILD_COUNT = 15
val reportMemoryUsage = "-Dkotlin.gradle.test.report.memory.usage=true"
val options = BaseGradleIT.BuildOptions(withDaemon = true)
val options = BaseGradleIT.BuildOptions(withDaemon = true)
fun exitTestDaemon() {
project.build(userVariantArg, reportMemoryUsage, "exit", options = options) {
@@ -113,7 +118,7 @@ class KotlinGradleIT: BaseGradleIT() {
project.build(userVariantArg, reportMemoryUsage, "clean", "build", options = options) {
assertSuccessful()
val matches = "\\[KOTLIN\\]\\[PERF\\] Used memory after build: (\\d+) kb \\(difference since build start: ([+-]?\\d+) kb\\)"
.toRegex().find(output)
.toRegex().find(output)
assert(matches != null && matches.groups.size == 3) { "Used memory after build is not reported by plugin" }
reportedMemory = matches!!.groupValues[1].toInt()
}
@@ -131,15 +136,16 @@ class KotlinGradleIT: BaseGradleIT() {
val totalMaximum = usedMemory.max()!!
val maxGrowth = totalMaximum - establishedMaximum
assertTrue(maxGrowth <= MEMORY_MAX_GROWTH_LIMIT_KB,
"Maximum used memory over series of builds growth $maxGrowth (from $establishedMaximum to $totalMaximum) kb > $MEMORY_MAX_GROWTH_LIMIT_KB kb")
assertTrue(
maxGrowth <= MEMORY_MAX_GROWTH_LIMIT_KB,
"Maximum used memory over series of builds growth $maxGrowth (from $establishedMaximum to $totalMaximum) kb > $MEMORY_MAX_GROWTH_LIMIT_KB kb"
)
// testing that nothing remains locked by daemon, see KT-9440
project.build(userVariantArg, "clean", options = BaseGradleIT.BuildOptions(withDaemon = true)) {
assertSuccessful()
}
}
finally {
} finally {
exitTestDaemon()
}
}
@@ -194,8 +200,10 @@ class KotlinGradleIT: BaseGradleIT() {
project.build("build", options = options) {
assertSuccessful()
assertNoWarnings()
val affectedSources = project.projectDir.getFilesByNames("Greeter.kt", "KotlinGreetingJoiner.kt",
"TestGreeter.kt", "TestKotlinGreetingJoiner.kt")
val affectedSources = project.projectDir.getFilesByNames(
"Greeter.kt", "KotlinGreetingJoiner.kt",
"TestGreeter.kt", "TestKotlinGreetingJoiner.kt"
)
assertCompiledKotlinSources(project.relativize(affectedSources), weakTesting = false)
}
}
@@ -511,7 +519,7 @@ class KotlinGradleIT: BaseGradleIT() {
fun updateBuildGradle(langVersion: String, apiVersion: String) {
buildGradle.writeText(
"""
"""
$buildGradleContentCopy
compileKotlin {
@@ -520,7 +528,8 @@ class KotlinGradleIT: BaseGradleIT() {
apiVersion = '$apiVersion'
}
}
""".trimIndent())
""".trimIndent()
)
}
assert(buildGradleContentCopy.indexOf("languageVersion") < 0) { "build.gradle should not contain 'languageVersion'" }
@@ -605,17 +614,20 @@ class KotlinGradleIT: BaseGradleIT() {
// Check that the Java source in a non-full-depth package structure was located correctly:
checkBytecodeContains(
File(project.projectDir, kotlinClassesDir() + "my/pack/name/app/MyApp.class"),
"my/pack/name/util/JUtil.util")
File(project.projectDir, kotlinClassesDir() + "my/pack/name/app/MyApp.class"),
"my/pack/name/util/JUtil.util"
)
}
}
@Test
fun testDisableSeparateClassesDirs() {
fun CompiledProject.check(copyClassesToJavaOutput: Boolean?,
expectBuildCacheWarning: Boolean,
expectGradleLowVersionWarning: Boolean) {
fun CompiledProject.check(
copyClassesToJavaOutput: Boolean?,
expectBuildCacheWarning: Boolean,
expectGradleLowVersionWarning: Boolean
) {
val separateDirPath = kotlinClassesDir() + "demo/KotlinGreetingJoiner.class"
val singleDirPath = javaClassesDir() + "demo/KotlinGreetingJoiner.class"
@@ -645,20 +657,26 @@ class KotlinGradleIT: BaseGradleIT() {
Project("simpleProject", GradleVersionRequired.Exact("4.0")).apply {
build("build") {
check(copyClassesToJavaOutput = false,
expectBuildCacheWarning = false,
expectGradleLowVersionWarning = false)
check(
copyClassesToJavaOutput = false,
expectBuildCacheWarning = false,
expectGradleLowVersionWarning = false
)
}
File(projectDir, "build.gradle").appendText("\nkotlin.copyClassesToJavaOutput = true")
build("clean", "build") {
check(copyClassesToJavaOutput = true,
expectBuildCacheWarning = false,
expectGradleLowVersionWarning = false)
check(
copyClassesToJavaOutput = true,
expectBuildCacheWarning = false,
expectGradleLowVersionWarning = false
)
}
build("clean", "build", options = defaultBuildOptions().copy(withBuildCache = true)) {
check(copyClassesToJavaOutput = true,
expectBuildCacheWarning = true,
expectGradleLowVersionWarning = false)
check(
copyClassesToJavaOutput = true,
expectBuildCacheWarning = true,
expectGradleLowVersionWarning = false
)
}
projectDir.deleteRecursively()
}
@@ -667,9 +685,11 @@ class KotlinGradleIT: BaseGradleIT() {
setupWorkingDir()
File(projectDir, "build.gradle").appendText("\nkotlin.copyClassesToJavaOutput = true")
build("build") {
check(copyClassesToJavaOutput = null,
expectBuildCacheWarning = false,
expectGradleLowVersionWarning = true)
check(
copyClassesToJavaOutput = null,
expectBuildCacheWarning = false,
expectGradleLowVersionWarning = true
)
}
}
}
@@ -678,7 +698,8 @@ class KotlinGradleIT: BaseGradleIT() {
fun testSrcDirTaskDependency() {
Project("simpleProject", GradleVersionRequired.AtLeast("4.1")).apply {
setupWorkingDir()
File(projectDir, "build.gradle").appendText("""${'\n'}
File(projectDir, "build.gradle").appendText(
"""${'\n'}
task generateSources {
outputs.dir('generated')
doLast {
@@ -692,10 +713,13 @@ class KotlinGradleIT: BaseGradleIT() {
}
}
sourceSets.main.java.srcDir(tasks.generateSources)
""".trimIndent())
File(projectDir, "src/main/kotlin/helloWorld.kt").appendText("""${'\n'}
""".trimIndent()
)
File(projectDir, "src/main/kotlin/helloWorld.kt").appendText(
"""${'\n'}
fun usageOfGeneratedSource() = test.TestClass()
""".trimIndent())
""".trimIndent()
)
build("build") {
assertSuccessful()
@@ -712,7 +736,8 @@ class KotlinGradleIT: BaseGradleIT() {
File(projectDir, additionalSrcDir).mkdirs()
File(projectDir, "$additionalSrcDir/additionalSource.kt").writeText("fun hello() = 123")
File(projectDir, "build.gradle").appendText("""${'\n'}
File(projectDir, "build.gradle").appendText(
"""${'\n'}
task sourcesJar(type: Jar) {
from sourceSets.main.allSource
classifier 'source'
@@ -720,7 +745,8 @@ class KotlinGradleIT: BaseGradleIT() {
}
sourceSets.main.kotlin.srcDir('$additionalSrcDir') // test that additional srcDir is included
""".trimIndent())
""".trimIndent()
)
build("sourcesJar") {
assertSuccessful()
@@ -113,7 +113,8 @@ class KotlinGradlePluginMultiVersionIT : BaseMultiGradleVersionIT() {
}
}
@Test fun testApplyPluginFromBuildSrc() {
@Test
fun testApplyPluginFromBuildSrc() {
val project = Project("kotlinProjectWithBuildSrc", gradleVersion)
project.setupWorkingDir()
File(project.projectDir, "buildSrc/build.gradle").modify { it.replace("\$kotlin_version", KOTLIN_VERSION) }
@@ -135,8 +136,10 @@ class KotlinGradlePluginMultiVersionIT : BaseMultiGradleVersionIT() {
fun testJavaLibraryCompatibility() {
val project = Project("javaLibraryProject", gradleVersion)
Assume.assumeTrue("The java-library plugin is supported only in Gradle 3.4+ (current: $gradleVersion)",
project.testGradleVersionAtLeast("3.4"))
Assume.assumeTrue(
"The java-library plugin is supported only in Gradle 3.4+ (current: $gradleVersion)",
project.testGradleVersionAtLeast("3.4")
)
val compileKotlinTasks = listOf(":libA:compileKotlin", ":libB:compileKotlin", ":app:compileKotlin")
project.build("build") {
@@ -149,8 +152,8 @@ class KotlinGradlePluginMultiVersionIT : BaseMultiGradleVersionIT() {
for (path in listOf("libA/src/main/kotlin/HelloA.kt", "libB/src/main/kotlin/HelloB.kt", "app/src/main/kotlin/App.kt")) {
File(project.projectDir, path).modify { original ->
original.replace("helloA", "helloA1")
.replace("helloB", "helloB1")
.apply { assert(!equals(original)) }
.replace("helloB", "helloB1")
.apply { assert(!equals(original)) }
}
}
@@ -33,12 +33,14 @@ class MultiplatformGradleIT : BaseGradleIT() {
project.build("build") {
assertSuccessful()
assertContains(":lib:compileKotlinCommon",
":lib:compileTestKotlinCommon",
":libJvm:compileKotlin",
":libJvm:compileTestKotlin",
":libJs:compileKotlin2Js",
":libJs:compileTestKotlin2Js")
assertContains(
":lib:compileKotlinCommon",
":lib:compileTestKotlinCommon",
":libJvm:compileKotlin",
":libJvm:compileTestKotlin",
":libJs:compileKotlin2Js",
":libJs:compileTestKotlin2Js"
)
assertFileExists("lib/build/classes/kotlin/main/foo/PlatformClass.kotlin_metadata")
assertFileExists("lib/build/classes/kotlin/test/foo/PlatformTest.kotlin_metadata")
assertFileExists("libJvm/build/classes/kotlin/main/foo/PlatformClass.class")
@@ -73,8 +75,9 @@ class MultiplatformGradleIT : BaseGradleIT() {
setupWorkingDir()
File(projectDir, "lib/build.gradle").appendText(
"\ncompileKotlinCommon.kotlinOptions.freeCompilerArgs = ['-Xno-inline']" +
"\ncompileKotlinCommon.kotlinOptions.suppressWarnings = true")
"\ncompileKotlinCommon.kotlinOptions.freeCompilerArgs = ['-Xno-inline']" +
"\ncompileKotlinCommon.kotlinOptions.suppressWarnings = true"
)
build("build") {
assertSuccessful()
@@ -98,7 +101,7 @@ class MultiplatformGradleIT : BaseGradleIT() {
// Remove the root project buildscript dependency, needed for the same purpose:
File(projectDir, "build.gradle").modify {
it.replace("classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:\$kotlin_version\"", "")
.apply { assert(!equals(it)) }
.apply { assert(!equals(it)) }
}
// Instead, add the dependencies directly to the subprojects buildscripts:
@@ -205,7 +208,8 @@ class MultiplatformGradleIT : BaseGradleIT() {
@Test
fun testCommonModuleAsTransitiveDependency() = with(Project("multiplatformProject")) {
setupWorkingDir()
gradleBuildScript("libJvm").appendText("""
gradleBuildScript("libJvm").appendText(
"""
${'\n'}
task printCompileConfiguration(type: DefaultTask) {
doFirst {
@@ -214,7 +218,8 @@ class MultiplatformGradleIT : BaseGradleIT() {
}
}
}
""".trimIndent())
""".trimIndent()
)
build("printCompileConfiguration") {
assertSuccessful()
@@ -242,7 +247,8 @@ class MultiplatformGradleIT : BaseGradleIT() {
setupWorkingDir()
val successMarker = "Found JavaCompile task:"
gradleBuildScript("lib").appendText("\n" + """
gradleBuildScript("lib").appendText(
"\n" + """
afterEvaluate {
println('$successMarker ' + tasks.getByName('compileJava').path)
println('$successMarker ' + tasks.getByName('compileTestJava').path)
@@ -33,12 +33,13 @@ class PluginsDslIT : BaseGradleIT() {
val project = projectWithMavenLocalPlugins("applyAllPlugins")
val kotlinPluginClasses = setOf(
"org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper",
"org.jetbrains.kotlin.gradle.internal.Kapt3GradleSubplugin",
"org.jetbrains.kotlin.allopen.gradle.AllOpenGradleSubplugin",
"org.jetbrains.kotlin.allopen.gradle.SpringGradleSubplugin",
"org.jetbrains.kotlin.noarg.gradle.NoArgGradleSubplugin",
"org.jetbrains.kotlin.noarg.gradle.KotlinJpaSubplugin")
"org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper",
"org.jetbrains.kotlin.gradle.internal.Kapt3GradleSubplugin",
"org.jetbrains.kotlin.allopen.gradle.AllOpenGradleSubplugin",
"org.jetbrains.kotlin.allopen.gradle.SpringGradleSubplugin",
"org.jetbrains.kotlin.noarg.gradle.NoArgGradleSubplugin",
"org.jetbrains.kotlin.noarg.gradle.KotlinJpaSubplugin"
)
project.build("build") {
assertSuccessful()
@@ -81,12 +82,12 @@ class PluginsDslIT : BaseGradleIT() {
}
result.projectDir.walkTopDown()
.filter { it.isFile && it.name == "build.gradle" }
.forEach { buildGradle ->
buildGradle.modify { text ->
text.replace(PLUGIN_MARKER_VERSION_PLACEHOLDER, MARKER_VERSION)
}
.filter { it.isFile && it.name == "build.gradle" }
.forEach { buildGradle ->
buildGradle.modify { text ->
text.replace(PLUGIN_MARKER_VERSION_PLACEHOLDER, MARKER_VERSION)
}
}
return result
}
@@ -97,10 +98,7 @@ class PluginsDslIT : BaseGradleIT() {
private object MavenLocalUrlProvider {
/** The URL that points to the Gradle's mavenLocal() repository. */
val mavenLocalUrl by lazy {
val path = propertyMavenLocalRepoPath ?:
homeSettingsLocalRepoPath ?:
m2HomeSettingsLocalRepoPath ?:
defaultM2RepoPath
val path = propertyMavenLocalRepoPath ?: homeSettingsLocalRepoPath ?: m2HomeSettingsLocalRepoPath ?: defaultM2RepoPath
File(path).toURI().toString()
}
@@ -17,14 +17,19 @@ class SimpleKotlinGradleIT : BaseGradleIT() {
assertContains("Finished executing kotlin compiler using daemon strategy")
assertTrue {
fileInWorkingDir("build/reports/tests/classes/demo.TestSource.html").exists() ||
fileInWorkingDir("build/reports/tests/test/classes/demo.TestSource.html").exists()
fileInWorkingDir("build/reports/tests/test/classes/demo.TestSource.html").exists()
}
assertContains(":compileKotlin", ":compileTestKotlin", ":compileDeployKotlin")
}
project.build("compileDeployKotlin", "build") {
assertSuccessful()
assertContains(":compileKotlin UP-TO-DATE", ":compileTestKotlin UP-TO-DATE", ":compileDeployKotlin UP-TO-DATE", ":compileJava UP-TO-DATE")
assertContains(
":compileKotlin UP-TO-DATE",
":compileTestKotlin UP-TO-DATE",
":compileDeployKotlin UP-TO-DATE",
":compileJava UP-TO-DATE"
)
}
}
@@ -60,6 +65,7 @@ class SimpleKotlinGradleIT : BaseGradleIT() {
assertContains("This type is sealed")
}
}
@Test
fun testJvmTarget() {
Project("jvmTarget").build("build") {
@@ -115,13 +121,17 @@ class SimpleKotlinGradleIT : BaseGradleIT() {
assertTrue(openClass.exists())
assertTrue(closedClass.exists())
checkBytecodeContains(openClass,
"public class test/OpenClass {",
"public method()V")
checkBytecodeContains(
openClass,
"public class test/OpenClass {",
"public method()V"
)
checkBytecodeContains(closedClass,
"public final class test/ClosedClass {",
"public final method()V")
checkBytecodeContains(
closedClass,
"public final class test/ClosedClass {",
"public final method()V"
)
}
}
@@ -136,13 +146,17 @@ class SimpleKotlinGradleIT : BaseGradleIT() {
assertTrue(openClass.exists())
assertTrue(closedClass.exists())
checkBytecodeContains(openClass,
"public class test/OpenClass {",
"public method()V")
checkBytecodeContains(
openClass,
"public class test/OpenClass {",
"public method()V"
)
checkBytecodeContains(closedClass,
"public final class test/ClosedClass {",
"public final method()V")
checkBytecodeContains(
closedClass,
"public final class test/ClosedClass {",
"public final method()V"
)
}
}
@@ -16,7 +16,7 @@ class TestRootAffectedIT : BaseGradleIT() {
val kotlinGreetingJoinerFile = project.projectDir.getFileByName("KotlinGreetingJoiner.kt")
kotlinGreetingJoinerFile.modify {
val replacing = "fun addName(name: String?): Unit"
val replacing = "fun addName(name: String?): Unit"
val replacement = "fun addName(name: String): Unit"
assert(it.contains(replacing)) { "API has changed!" }
it.replace(replacing, replacement)
@@ -10,26 +10,36 @@ import java.io.File
class UpToDateIT : BaseGradleIT() {
@Test
fun testLanguageVersionChange() {
testMutations(*propertyMutationChain("compileKotlin.kotlinOptions.languageVersion",
"null", "'1.1'", "'1.0'", "null"))
testMutations(
*propertyMutationChain(
"compileKotlin.kotlinOptions.languageVersion",
"null", "'1.1'", "'1.0'", "null"
)
)
}
@Test
fun testApiVersionChange() {
testMutations(*propertyMutationChain("compileKotlin.kotlinOptions.apiVersion",
"null", "'1.1'", "'1.0'", "null"))
testMutations(
*propertyMutationChain(
"compileKotlin.kotlinOptions.apiVersion",
"null", "'1.1'", "'1.0'", "null"
)
)
}
@Test
fun testOther() {
testMutations(emptyMutation,
OptionMutation("compileKotlin.kotlinOptions.jvmTarget", "'1.6'", "'1.8'"),
OptionMutation("compileKotlin.kotlinOptions.freeCompilerArgs", "[]", "['-Xallow-kotlin-package']"),
OptionMutation("kotlin.experimental.coroutines", "'error'", "'enable'"),
OptionMutation("archivesBaseName", "'someName'", "'otherName'"),
subpluginOptionMutation,
externalOutputMutation,
compilerClasspathMutation)
testMutations(
emptyMutation,
OptionMutation("compileKotlin.kotlinOptions.jvmTarget", "'1.6'", "'1.8'"),
OptionMutation("compileKotlin.kotlinOptions.freeCompilerArgs", "[]", "['-Xallow-kotlin-package']"),
OptionMutation("kotlin.experimental.coroutines", "'error'", "'enable'"),
OptionMutation("archivesBaseName", "'someName'", "'otherName'"),
subpluginOptionMutation,
externalOutputMutation,
compilerClasspathMutation
)
}
private fun testMutations(vararg mutations: ProjectMutation) {
@@ -44,8 +54,7 @@ class UpToDateIT : BaseGradleIT() {
try {
assertSuccessful()
it.checkAfterRebuild(this)
}
catch (e: Throwable) {
} catch (e: Throwable) {
throw RuntimeException("Mutation '${it.name}' has failed", e)
}
}
@@ -103,11 +112,13 @@ class UpToDateIT : BaseGradleIT() {
override val name: String get() = "subpluginOptionMutation"
override fun initProject(project: Project) = with(project) {
buildGradle.appendText("\n" + """
buildGradle.appendText(
"\n" + """
buildscript { dependencies { classpath "org.jetbrains.kotlin:kotlin-allopen:${'$'}kotlin_version" } }
apply plugin: "kotlin-allopen"
allOpen { annotation("allopen.Foo"); annotation("allopen.Bar") }
""".trimIndent())
""".trimIndent()
)
}
override fun mutateProject(project: Project) = with(project) {
@@ -131,7 +142,7 @@ class UpToDateIT : BaseGradleIT() {
if (testGradleVersionAtLeast("4.0"))
project.classesDir()
else
// Before 4.0, we should delete the classes from the temporary dir to make compileKotlin rerun:
// Before 4.0, we should delete the classes from the temporary dir to make compileKotlin rerun:
"build/kotlin-classes/main/"
helloWorldKtClass = File(projectDir, kotlinOutputPath + "demo/KotlinGreetingJoiner.class")
@@ -155,12 +166,12 @@ class UpToDateIT : BaseGradleIT() {
}
private fun propertyMutationChain(path: String, vararg values: String): Array<ProjectMutation> =
arrayListOf<ProjectMutation>().apply {
for (i in 1..values.lastIndex) {
add(OptionMutation(path, values[i - 1], values[i], shouldInit = i == 1))
}
arrayListOf<ProjectMutation>().apply {
for (i in 1..values.lastIndex) {
add(OptionMutation(path, values[i - 1], values[i], shouldInit = i == 1))
}
}.toTypedArray()
}.toTypedArray()
private inner class OptionMutation(
private val path: String,
@@ -4,24 +4,24 @@ import java.io.File
import java.nio.file.Files
fun File.getFileByName(name: String): File =
findFileByName(name) ?: throw AssertionError("Could not find file with name '$name' in $this")
findFileByName(name) ?: throw AssertionError("Could not find file with name '$name' in $this")
fun File.getFilesByNames(vararg names: String): List<File> =
names.map { getFileByName(it) }
names.map { getFileByName(it) }
fun File.findFileByName(name: String): File? =
walk().filter { it.isFile && it.name.equals(name, ignoreCase = true) }.firstOrNull()
walk().filter { it.isFile && it.name.equals(name, ignoreCase = true) }.firstOrNull()
fun File.allKotlinFiles(): Iterable<File> =
allFilesWithExtension("kt")
allFilesWithExtension("kt")
fun File.allJavaFiles(): Iterable<File> =
allFilesWithExtension("java")
allFilesWithExtension("java")
fun File.allFilesWithExtension(ext: String): Iterable<File> =
walk().filter { it.isFile && it.extension.equals(ext, ignoreCase = true) }.toList()
walk().filter { it.isFile && it.extension.equals(ext, ignoreCase = true) }.toList()
fun File.modify(transform: (String)->String) {
fun File.modify(transform: (String) -> String) {
writeText(transform(readText()))
}
@@ -4,10 +4,10 @@ import org.jetbrains.kotlin.gradle.BaseGradleIT
import java.io.File
class ProcessRunResult(
private val cmd: List<String>,
private val workingDir: File,
val exitCode: Int,
val output: String
private val cmd: List<String>,
private val workingDir: File,
val exitCode: Int,
val output: String
) {
val isSuccessful: Boolean
get() = exitCode == 0
@@ -21,10 +21,10 @@ Executing process was ${if (isSuccessful) "successful" else "unsuccessful"}
}
fun runProcess(
cmd: List<String>,
workingDir: File,
environmentVariables: Map<String, String> = mapOf(),
options: BaseGradleIT.BuildOptions? = null
cmd: List<String>,
workingDir: File,
environmentVariables: Map<String, String> = mapOf(),
options: BaseGradleIT.BuildOptions? = null
): ProcessRunResult {
val builder = ProcessBuilder(cmd)
builder.environment().putAll(environmentVariables)
@@ -1,4 +1,4 @@
package org.jetbrains.kotlin.gradle.util
fun String.addBeforeSubstring(prefix: String, substring: String): String =
replace(substring, prefix + substring)
replace(substring, prefix + substring)
@@ -3,4 +3,4 @@ package org.jetbrains.kotlin.gradle.util
import org.gradle.util.VersionNumber
fun isLegacyAndroidGradleVersion(androidGradlePluginVersion: String): Boolean =
VersionNumber.parse(androidGradlePluginVersion) < VersionNumber.parse("3.0.0-alpha1")
VersionNumber.parse(androidGradlePluginVersion) < VersionNumber.parse("3.0.0-alpha1")
@@ -13,10 +13,10 @@ import kotlin.test.assertEquals
abstract class BaseIncrementalGradleIT : BaseGradleIT() {
inner class JpsTestProject(
val buildLogFinder: BuildLogFinder,
val resourcesBase: File,
val relPath: String,
minLogLevel: LogLevel = LogLevel.DEBUG
val buildLogFinder: BuildLogFinder,
val resourcesBase: File,
val relPath: String,
minLogLevel: LogLevel = LogLevel.DEBUG
) : Project(File(relPath).name, GradleVersionRequired.Exact("2.10"), null, minLogLevel) {
override val resourcesRoot = File(resourcesBase, relPath)
@@ -42,13 +42,15 @@ abstract class BaseIncrementalGradleIT : BaseGradleIT() {
assertReportExists()
}
val buildLogFile = buildLogFinder.findBuildLog(resourcesRoot) ?:
throw IllegalStateException("build log file not found in $resourcesRoot")
val buildLogFile =
buildLogFinder.findBuildLog(resourcesRoot) ?: throw IllegalStateException("build log file not found in $resourcesRoot")
val buildLogSteps = parseTestBuildLog(buildLogFile)
val modifications = getModificationsToPerform(resourcesRoot,
moduleNames = null,
allowNoFilesWithSuffixInTestData = false,
touchPolicy = TouchPolicy.CHECKSUM)
val modifications = getModificationsToPerform(
resourcesRoot,
moduleNames = null,
allowNoFilesWithSuffixInTestData = false,
touchPolicy = TouchPolicy.CHECKSUM
)
assert(modifications.size == buildLogSteps.size) {
"Modifications count (${modifications.size}) != expected build log steps count (${buildLogSteps.size})"
@@ -67,14 +69,17 @@ abstract class BaseIncrementalGradleIT : BaseGradleIT() {
rebuildAndCompareOutput(rebuildSucceedExpected = buildLogSteps.last().compileSucceeded)
}
private fun JpsTestProject.buildAndAssertStageResults(expected: BuildStep, options: BuildOptions = defaultBuildOptions(), weakTesting: Boolean = false) {
private fun JpsTestProject.buildAndAssertStageResults(
expected: BuildStep,
options: BuildOptions = defaultBuildOptions(),
weakTesting: Boolean = false
) {
build("build", options = options) {
if (expected.compileSucceeded) {
assertSuccessful()
assertCompiledJavaSources(expected.compiledJavaFiles, weakTesting)
assertCompiledKotlinSources(expected.compiledKotlinFiles, weakTesting)
}
else {
} else {
assertFailed()
}
}
@@ -5,6 +5,7 @@ import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.io.File
@RunWith(Parameterized::class)
class KotlinGradlePluginJpsParametrizedIT : BaseIncrementalGradleIT() {
@@ -18,26 +19,28 @@ class KotlinGradlePluginJpsParametrizedIT : BaseIncrementalGradleIT() {
}
override fun defaultBuildOptions() =
super.defaultBuildOptions().copy(incremental = true)
super.defaultBuildOptions().copy(incremental = true)
companion object {
private val jpsResourcesPath = File("../../../jps-plugin/testData/incremental")
private val ignoredDirs = setOf(File(jpsResourcesPath, "cacheVersionChanged"),
File(jpsResourcesPath, "changeIncrementalOption"),
File(jpsResourcesPath, "custom"),
File(jpsResourcesPath, "lookupTracker"))
private val ignoredDirs = setOf(
File(jpsResourcesPath, "cacheVersionChanged"),
File(jpsResourcesPath, "changeIncrementalOption"),
File(jpsResourcesPath, "custom"),
File(jpsResourcesPath, "lookupTracker")
)
private val buildLogFinder = BuildLogFinder(isGradleEnabled = true)
@Suppress("unused")
@Parameterized.Parameters(name = "{0}")
@JvmStatic
fun data(): List<Array<String>> =
jpsResourcesPath.walk()
.onEnter { it !in ignoredDirs }
.filter { it.isDirectory && buildLogFinder.findBuildLog(it) != null }
.map { arrayOf(it.toRelativeString(jpsResourcesPath)) }
.toList()
jpsResourcesPath.walk()
.onEnter { it !in ignoredDirs }
.filter { it.isDirectory && buildLogFinder.findBuildLog(it) != null }
.map { arrayOf(it.toRelativeString(jpsResourcesPath)) }
.toList()
}
}