Use new kotlin.io.path API in tests

This commit is contained in:
Ilya Gorbunov
2020-11-16 08:30:04 +03:00
parent d38e145529
commit b2b2629e79
27 changed files with 173 additions and 116 deletions
@@ -27,6 +27,9 @@ import org.junit.Assert
import java.io.File
import java.io.FileWriter
import java.io.IOException
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.Path
import kotlin.io.path.createTempDirectory
import kotlin.test.assertTrue
data class ConfigurationKey(val kind: ConfigurationKind, val jdkKind: TestJdkKind, val configuration: String)
@@ -345,14 +348,15 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
FileWriter(file).use { fw -> fw.write("sdk.dir=$sdkRoot") }
}
@OptIn(ExperimentalPathApi::class)
@JvmStatic
fun main(args: Array<String>) {
val tmpFolder = createTempDir()
println("Created temporary folder for android tests: " + tmpFolder.absolutePath)
val rootFolder = File("")
val pathManager = PathManager(rootFolder.absolutePath, tmpFolder.absolutePath)
val tmpFolder = createTempDirectory().toAbsolutePath().toString()
println("Created temporary folder for android tests: $tmpFolder")
val rootFolder = Path("").toAbsolutePath().toString()
val pathManager = PathManager(rootFolder, tmpFolder)
generate(pathManager, true)
println("Android test project is generated into " + tmpFolder.absolutePath + " folder")
println("Android test project is generated into $tmpFolder folder")
}
}
}
@@ -35,7 +35,10 @@ import java.io.ByteArrayOutputStream
import java.io.File
import java.io.PrintStream
import java.net.URLClassLoader
import java.nio.file.Path
import kotlin.io.path.*
@OptIn(ExperimentalPathApi::class)
class CompilerApiTest : KotlinIntegrationTestBase() {
private val compilerLibDir = getCompilerLib()
@@ -119,7 +122,7 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
verbose = true,
reportPerf = true)
val logFile = createTempFile("kotlin-daemon-test.", ".log")
val logFile: Path = createTempFile("kotlin-daemon-test.", ".log")
val daemonJVMOptions = configureDaemonJVMOptions("D$COMPILE_DAEMON_LOG_PATH_PROPERTY=\"${logFile.loggerCompatiblePath}\"",
inheritMemoryLimits = false, inheritOtherJvmOptions = false, inheritAdditionalProperties = false)
@@ -137,7 +140,8 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
}
finally {
KotlinCompilerClient.shutdownCompileService(compilerId, daemonOptions)
logFile.delete()
runCatching { logFile.deleteIfExists() }
.onFailure { e -> println("Failed to delete log file: $e") }
}
}
}
@@ -158,7 +162,7 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
verbose = true,
reportPerf = true)
val logFile = createTempFile("kotlin-daemon-test.", ".log")
val logFile: Path = createTempFile("kotlin-daemon-test.", ".log")
val daemonJVMOptions = configureDaemonJVMOptions("D$COMPILE_DAEMON_LOG_PATH_PROPERTY=\"${logFile.loggerCompatiblePath}\"",
inheritMemoryLimits = false, inheritOtherJvmOptions = false, inheritAdditionalProperties = false)
@@ -174,7 +178,8 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
}
finally {
KotlinCompilerClient.shutdownCompileService(compilerId, daemonOptions)
logFile.delete()
runCatching { logFile.deleteIfExists() }
.onFailure { e -> println("Failed to delete log file: $e") }
}
}
}
@@ -36,10 +36,13 @@ import java.lang.management.ManagementFactory
import java.net.URL
import java.net.URLClassLoader
import java.nio.charset.Charset
import java.nio.file.Path
import java.rmi.server.UnicastRemoteObject
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.invariantSeparatorsPath
import kotlin.script.dependencies.Environment
import kotlin.script.dependencies.ScriptContents
import kotlin.script.experimental.dependencies.DependenciesResolver
@@ -997,9 +1000,12 @@ internal inline fun withLogFile(prefix: String, suffix: String = ".log", printLo
// if file path is given in windows form (using backslash as a separator); the reason is unknown
// this function makes a path with forward slashed, that works on windows too
internal val File.loggerCompatiblePath: String
get() =
if (OSKind.current == OSKind.Windows) absolutePath.replace('\\', '/')
else absolutePath
get() = invariantSeparatorsPath
@OptIn(ExperimentalPathApi::class)
internal val Path.loggerCompatiblePath: String
get() = invariantSeparatorsPath
open class TestKotlinScriptDummyDependenciesResolver : DependenciesResolver {
@@ -28,13 +28,16 @@ import org.junit.Assert
import org.junit.runner.RunWith
import java.io.File
import java.net.URLClassLoader
import java.nio.file.Path
import java.util.logging.LogManager
import java.util.logging.Logger
import kotlin.io.path.*
private val logFiles = arrayListOf<String>()
// TODO: remove ignore annotation from tests.
@OptIn(ExperimentalPathApi::class)
@RunWith(IgnoreAll::class)
class CompilerApiTest : KotlinIntegrationTestBase() {
@@ -43,7 +46,7 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
private val compilerLibDir = getCompilerLib()
private fun createNewLogFile(): File {
private fun createNewLogFile(): Path {
println("creating logFile")
val newLogFile = createTempFile("kotlin-daemon-experimental-test.", ".log")
println("logFile created (${newLogFile.loggerCompatiblePath})")
@@ -51,7 +54,7 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
return newLogFile
}
private val currentLogFile: File by lazy {
private val currentLogFile: Path by lazy {
val newLogFile = createNewLogFile()
val cfg: String =
"handlers = java.util.logging.FileHandler\n" +
@@ -67,7 +70,7 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
newLogFile
}
private val externalLogFile: File by lazy { createNewLogFile() }
private val externalLogFile: Path by lazy { createNewLogFile() }
private val log by lazy {
currentLogFile
@@ -3,6 +3,8 @@
* that can be found in the license/LICENSE.txt file.
*/
@file:OptIn(ExperimentalPathApi::class)
package org.jetbrains.kotlin.daemon.experimental.integration
import junit.framework.TestCase
@@ -38,6 +40,7 @@ import java.net.URL
import java.net.URLClassLoader
import java.nio.channels.ClosedChannelException
import java.nio.charset.Charset
import java.nio.file.Path
import java.rmi.ConnectException
import java.rmi.ConnectIOException
import java.rmi.UnmarshalException
@@ -46,6 +49,7 @@ import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.logging.LogManager
import kotlin.concurrent.thread
import kotlin.io.path.*
import kotlin.script.dependencies.Environment
import kotlin.script.dependencies.ScriptContents
import kotlin.script.experimental.dependencies.DependenciesResolver
@@ -64,7 +68,7 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
val kotlinCompilerClientInstance = KotlinCompilerDaemonClient.instantiate(DaemonProtocolVariant.SOCKETS)
private fun createNewLogFile(): File {
private fun createNewLogFile(): Path {
println("creating logFile")
val newLogFile = createTempFile("kotlin-daemon-experimental-test.", ".log")
println("logFile created (${newLogFile.loggerCompatiblePath})")
@@ -595,8 +599,8 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
shutdownDelayMilliseconds = 1,
runFilesPath = File(tmpdir, getTestName(true)).absolutePath
)
val clientFlag = createTempFile(getTestName(true), "-client.alive")
val sessionFlag = createTempFile(getTestName(true), "-session.alive")
val clientFlag = createTempFile(getTestName(true), "-client.alive").toFile()
val sessionFlag = createTempFile(getTestName(true), "-session.alive").toFile()
try {
withLogFile("kotlin-daemon-test") { logFile ->
val daemonJVMOptions = makeTestDaemonJvmOptions(logFile)
@@ -635,8 +639,8 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
shutdownDelayMilliseconds = 1,
runFilesPath = File(tmpdir, getTestName(true)).absolutePath
)
val clientFlag = createTempFile(getTestName(true), "-client.alive")
val sessionFlag = createTempFile(getTestName(true), "-session.alive")
val clientFlag = createTempFile(getTestName(true), "-client.alive").toFile()
val sessionFlag = createTempFile(getTestName(true), "-session.alive").toFile()
try {
withLogFile("kotlin-daemon-test") { logFile ->
val daemonJVMOptions = makeTestDaemonJvmOptions(logFile)
@@ -678,8 +682,8 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
shutdownDelayMilliseconds = 3000,
runFilesPath = File(tmpdir, getTestName(true)).absolutePath
)
val clientFlag = createTempFile(getTestName(true), "-client.alive")
val clientFlag2 = createTempFile(getTestName(true), "-client.alive")
val clientFlag = createTempFile(getTestName(true), "-client.alive").toFile()
val clientFlag2 = createTempFile(getTestName(true), "-client.alive").toFile()
try {
withLogFile("kotlin-daemon-test") { logFile ->
val daemonJVMOptions = makeTestDaemonJvmOptions(logFile)
@@ -769,8 +773,7 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
assertEquals("Compilation failed:\n$resOutput", 0, resCode)
println("OK")
} finally {
if (clientAliveFile.exists())
clientAliveFile.delete()
clientAliveFile.deleteIfExists()
}
}
@@ -1427,7 +1430,7 @@ fun restoreSystemProperty(propertyName: String, backupValue: String?) {
}
internal inline fun withFlagFile(prefix: String, suffix: String? = null, body: (File) -> Unit) {
val file = createTempFile(prefix, suffix)
val file = createTempFile(prefix, suffix).toFile()
try {
body(file)
} finally {
@@ -1436,7 +1439,7 @@ internal inline fun withFlagFile(prefix: String, suffix: String? = null, body: (
}
internal inline fun withLogFile(prefix: String, suffix: String = ".log", printLogOnException: Boolean = true, body: (File) -> Unit) {
val logFile = createTempFile(prefix, suffix)
val logFile = createTempFile(prefix, suffix).toFile()
println("LOG FILE : ${logFile.path}")
try {
body(logFile)
@@ -1449,13 +1452,6 @@ internal inline fun withLogFile(prefix: String, suffix: String = ".log", printLo
}
}
// java.util.Logger used in the daemon silently forgets to log into a file specified in the config on Windows,
// if file path is given in windows form (using backslash as a separator); the reason is unknown
// this function makes a path with forward slashed, that works on windows too
internal val File.loggerCompatiblePath: String
get() =
if (OSKind.current == OSKind.Windows) absolutePath.replace('\\', '/')
else absolutePath
open class TestKotlinScriptDummyDependenciesResolver : DependenciesResolver {
@@ -24,6 +24,7 @@ import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.net.InetSocketAddress
import java.util.logging.Logger
import kotlin.io.path.*
@OptIn(KtorExperimentalAPI::class)
class TestServer(val serverPort: Int = 6999) {
@@ -44,6 +45,7 @@ val testServer = TestServer()
@RunWith(IgnoreAll::class)
@Suppress("UNCHECKED_CAST")
@OptIn(ExperimentalPathApi::class)
class ClientSerializationTest : KotlinIntegrationTestBase() {
val file = createTempFile()
@@ -31,11 +31,14 @@ import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.io.PrintStream
import java.nio.file.Path
import java.util.*
import java.util.logging.LogManager
import java.util.logging.Logger
import kotlin.concurrent.schedule
import kotlin.io.path.*
@OptIn(ExperimentalPathApi::class)
@RunWith(IgnoreAll::class)
class ConnectionsTest : KotlinIntegrationTestBase() {
@@ -247,15 +250,15 @@ class ConnectionsTest : KotlinIntegrationTestBase() {
extraAction
)
private val clientFiles = arrayListOf<File>()
private val clientFiles = mutableListOf<Path>()
private fun generateClient(): String {
val file = createTempFile(getTestName(true), ".alive")
clientFiles.add(file)
return file.absolutePath
return file.toAbsolutePath().toString()
}
private fun deleteClients() {
clientFiles.forEach { it.delete() }
clientFiles.forEach { it.deleteIfExists() }
}
private fun endTest() {
@@ -22,6 +22,7 @@ import org.junit.Assert
import org.junit.Before
import org.junit.Test
import java.io.File
import java.nio.file.Files
import java.util.*
class BuildDiffsStorageTest {
@@ -30,7 +31,7 @@ class BuildDiffsStorageTest {
@Before
fun setUp() {
storageFile = File.createTempFile("BuildDiffsStorageTest", "storage")
storageFile = Files.createTempFile("BuildDiffsStorageTest", "storage").toFile()
}
@After
+1
View File
@@ -5,6 +5,7 @@ plugins {
}
dependencies {
testCompile(kotlinStdlib("jdk8"))
testCompile(project(":kotlin-scripting-compiler"))
testCompile(project(":core:descriptors"))
testCompile(project(":core:descriptors.jvm"))
@@ -12,6 +12,7 @@ import org.jetbrains.kotlin.test.MockLibraryUtil
import java.io.File
import java.util.*
import java.util.regex.Pattern
import kotlin.io.path.*
const val JSPECIFY_NULLNESS_MISMATCH_MARK = "jspecify_nullness_mismatch"
@@ -30,6 +31,7 @@ abstract class AbstractJspecifyAnnotationsTest : AbstractDiagnosticsTest() {
)
}
@OptIn(ExperimentalPathApi::class)
override fun doTest(filePath: String) {
val ktSourceCode = File(filePath).readText()
val javaSourcesFilename = javaSourcesPathRegex.matcher(ktSourceCode).also { it.find() }.group(1)
@@ -51,7 +53,7 @@ abstract class AbstractJspecifyAnnotationsTest : AbstractDiagnosticsTest() {
appendLine("// FILE: main.kt\n$ktSourceCode")
}
super.doTest(createTempFile().apply { writeText(mergedSourceCode) }.path)
super.doTest(createTempFile().apply { writeText(mergedSourceCode) }.toString())
}
private fun makeJavaClassesPublicAndSeparatedByFiles(javaCode: String): String {
@@ -21,6 +21,7 @@ import com.intellij.openapi.util.text.StringUtil;
import kotlin.Pair;
import kotlin.collections.CollectionsKt;
import kotlin.io.FilesKt;
import kotlin.io.path.PathsKt;
import kotlin.text.Charsets;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.checkers.AbstractForeignAnnotationsTestKt;
@@ -37,12 +38,17 @@ import org.jetbrains.kotlin.test.CompilerTestUtil;
import org.jetbrains.kotlin.test.InTextDirectivesUtils;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TestCaseWithTmpdir;
import org.jetbrains.kotlin.utils.ExceptionUtilsKt;
import org.jetbrains.kotlin.utils.JsMetadataVersion;
import org.jetbrains.kotlin.utils.PathUtil;
import org.jetbrains.kotlin.utils.StringsKt;
import org.junit.Assert;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
@@ -232,15 +238,20 @@ public abstract class AbstractCliTest extends TestCaseWithTmpdir {
@NotNull String tempDir
) {
String filePath = kotlin.text.StringsKt.substringAfter(argument, argumentPrefix, argument);
File file = new File(filePath);
if (!file.exists()) return argument;
Path file = Paths.get(filePath);
if (!Files.exists(file)) return argument;
File result = FilesKt.createTempFile(file.getAbsolutePath(), tempFileSuffix, new File(tempDir));
String oldContent = FilesKt.readText(file, Charsets.UTF_8);
String newContent = replaceTestPaths(oldContent, testDataDir, tempDir);
FilesKt.writeText(result, newContent, Charsets.UTF_8);
try {
Path result = Files.createTempFile(Paths.get(tempDir), file.getFileName().toString(), tempFileSuffix);
String oldContent = PathsKt.readText(file, Charsets.UTF_8);
String newContent = replaceTestPaths(oldContent, testDataDir, tempDir);
PathsKt.writeText(result, newContent, Charsets.UTF_8);
return argumentPrefix + result.getAbsolutePath();
return argumentPrefix + result.toAbsolutePath();
}
catch (IOException e) {
throw ExceptionUtilsKt.rethrow(e);
}
}
private static String replaceTestPaths(@NotNull String str, @NotNull String testDataDir, @NotNull String tempDir) {