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

View File

@@ -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")
}
}
}

View File

@@ -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") }
}
}
}

View File

@@ -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 {

View File

@@ -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

View File

@@ -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 {

View File

@@ -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()

View File

@@ -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() {

View File

@@ -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

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"))

View File

@@ -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 {

View File

@@ -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) {

View File

@@ -10,27 +10,24 @@ import org.gradle.internal.exceptions.LocationAwareException
import org.gradle.internal.resource.UriTextResource
import org.jetbrains.kotlin.idea.scripting.gradle.importing.parsePositionFromException
import org.junit.Test
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter
import java.lang.RuntimeException
import kotlin.io.path.*
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class KotlinDslScriptModelTest {
@OptIn(ExperimentalPathApi::class)
@Test
fun testExceptionPositionParsing() {
val file = File(createTempDir("kotlinDslTest"), "build.gradle.kts")
val file = createTempDirectory("kotlinDslTest") / "build.gradle.kts"
val line = 10
val mockScriptSource = TextResourceScriptSource(UriTextResource("build file", file))
val mockScriptSource = TextResourceScriptSource(UriTextResource("build file", file.toFile()))
val mockException = LocationAwareException(RuntimeException(), mockScriptSource, line)
val stringWriter = StringWriter()
mockException.printStackTrace(PrintWriter(stringWriter))
val fromException = parsePositionFromException(stringWriter.toString())
val fromException = parsePositionFromException(mockException.stackTraceToString())
assertNotNull(fromException, "Position should be parsed")
assertEquals(fromException.first, file.absolutePath, "Wrong file name parsed")
assertEquals(fromException.first, file.toAbsolutePath().toString(), "Wrong file name parsed")
assertEquals(fromException.second.line, line, "Wrong line number parsed")
file.parent.deleteExisting()
}
}

View File

@@ -7,15 +7,16 @@ package org.jetbrains.kotlin.idea.perf.util
import com.intellij.openapi.util.io.FileUtilRt
import com.sun.management.HotSpotDiagnosticMXBean
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.lang.management.ManagementFactory
import java.nio.file.Files
import java.nio.file.Path
import java.text.SimpleDateFormat
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import kotlin.io.path.*
@OptIn(ExperimentalPathApi::class)
object HeapDumper {
private const val HOTSPOT_BEAN_NAME = "com.sun.management:type=HotSpotDiagnostic"
@@ -30,15 +31,15 @@ object HeapDumper {
fun dumpHeap(fileNamePrefix: String, live: Boolean = true) {
val format = SimpleDateFormat("yyyyMMdd-HHmmss")
val timestamp = format.format(Date())
val tempFile = File.createTempFile(fileNamePrefix, ".hprof")
tempFile.delete()
val tempFile = createTempFile(fileNamePrefix, ".hprof")
tempFile.deleteIfExists()
val fileName = "build/$fileNamePrefix-$timestamp.hprof.zip"
logMessage { "Dumping a heap into $tempFile ..." }
try {
hotspotMBean.dumpHeap(tempFile.toString(), live)
logMessage { "Heap dump is $tempFile ready." }
zipFile(tempFile, File(fileName))
zipFile(tempFile, Path(fileName))
val testName = "Heap dump $timestamp"
TeamCity.test(testName) {
@@ -50,9 +51,9 @@ object HeapDumper {
}
}
private fun zipFile(srcFile: File, targetFile: File) {
FileInputStream(srcFile).use { fis ->
ZipOutputStream(FileOutputStream(targetFile)).use { os ->
private fun zipFile(srcFile: Path, targetFile: Path) {
srcFile.inputStream().use { fis ->
ZipOutputStream(targetFile.outputStream()).use { os ->
os.putNextEntry(ZipEntry(srcFile.name))
FileUtilRt.copy(fis, os)
os.closeEntry()

View File

@@ -15,16 +15,19 @@ import org.jetbrains.kotlin.incremental.testingUtils.assertEqualDirectories
import org.jetbrains.kotlin.jps.build.fixtures.EnableICFixture
import org.jetbrains.kotlin.jps.incremental.KotlinDataContainerTarget
import java.io.File
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.createTempDirectory
import kotlin.reflect.KFunction1
class RelocatableJpsCachesTest : BaseKotlinJpsBuildTestCase() {
private val enableICFixture = EnableICFixture()
private lateinit var workingDir: File
@OptIn(ExperimentalPathApi::class)
override fun setUp() {
super.setUp()
enableICFixture.setUp()
workingDir = createTempDir("RelocatableJpsCachesTest", getTestName(false))
workingDir = createTempDirectory("RelocatableJpsCachesTest-" + getTestName(false)).toFile()
}
override fun tearDown() {

View File

@@ -65,8 +65,10 @@ import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import java.io.File
import kotlin.io.path.*
import org.jetbrains.kotlin.konan.file.File as KonanFile
@OptIn(ExperimentalPathApi::class)
@Ignore
class GenerateIrRuntime {
private val lookupTracker: LookupTracker = LookupTracker.DO_NOTHING
@@ -251,7 +253,7 @@ class GenerateIrRuntime {
val irVersion = KlibIrVersion.INSTANCE.toString()
val versions = KotlinLibraryVersioning(libraryVersion, compilerVersion, abiVersion, metadataVersion, irVersion)
val file = createTempFile(directory = workingDir)
val file = createTempFile(directory = workingDir.toPath()).toFile()
val writer = KotlinLibraryOnlyIrWriter(file.absolutePath, "", versions, BuiltInsPlatform.JS, emptyList(), false)
val files = fullRuntimeSourceSet
val analysisResult = doFrontEnd(files)
@@ -273,7 +275,7 @@ class GenerateIrRuntime {
val irVersion = KlibIrVersion.INSTANCE.toString()
val versions = KotlinLibraryVersioning(libraryVersion, compilerVersion, abiVersion, metadataVersion, irVersion)
val file = createTempFile(directory = workingDir)
val file = createTempFile(directory = workingDir.toPath()).toFile()
val writer = KotlinLibraryOnlyIrWriter(file.absolutePath, "", versions, BuiltInsPlatform.JS, emptyList(), true)
val files = fullRuntimeSourceSet
val analysisResult = doFrontEnd(files)
@@ -473,15 +475,16 @@ class GenerateIrRuntime {
return psi2IrTranslator.generateModuleFragment(psi2IrContext, files, irProviders, emptyList(), null)
}
@OptIn(ExperimentalPathApi::class)
private fun doSerializeModule(moduleFragment: IrModuleFragment, bindingContext: BindingContext, files: List<KtFile>, perFile: Boolean = false): String {
val tmpKlibDir = createTempDir().also { it.deleteOnExit() }
val tmpKlibDir = createTempDirectory().also { it.toFile().deleteOnExit() }.toString()
serializeModuleIntoKlib(
moduleName,
project,
configuration,
bindingContext,
files,
tmpKlibDir.path,
tmpKlibDir,
emptyList(),
moduleFragment,
mutableMapOf(),
@@ -490,7 +493,7 @@ class GenerateIrRuntime {
perFile
)
return tmpKlibDir.path
return tmpKlibDir
}
private fun doDeserializeModuleMetadata(moduleRef: KotlinLibrary): ModuleDescriptorImpl {

View File

@@ -6,6 +6,7 @@
package kotlin.script.experimental.test
import java.io.File
import java.nio.file.Files
import kotlin.contracts.ExperimentalContracts
import kotlin.script.experimental.dependencies.*
import kotlin.script.experimental.api.ResultWithDiagnostics
@@ -17,8 +18,7 @@ import kotlin.script.experimental.dependencies.impl.makeResolveFailureResult
class ResolversTest : ResolversTestBase() {
private fun <T> withTempFile(body: (file: File) -> T): T {
createTempFile()
val file = createTempFile()
val file = Files.createTempFile(null, null).toFile()
file.deleteOnExit()
try {
return body(file)

View File

@@ -3,17 +3,20 @@
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:OptIn(ExperimentalPathApi::class)
package kotlin.script.experimental.jvmhost.test
import junit.framework.TestCase
import org.junit.Assert
import org.junit.Test
import java.io.File
import java.io.FileOutputStream
import java.net.URLClassLoader
import java.nio.file.Path
import java.util.jar.JarEntry
import java.util.jar.JarOutputStream
import java.util.jar.Manifest
import kotlin.io.path.*
import kotlin.script.experimental.jvm.util.classPathFromTypicalResourceUrls
import kotlin.script.experimental.jvm.util.classpathFromClass
import kotlin.script.experimental.jvm.util.classpathFromClassloader
@@ -21,22 +24,22 @@ import kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContext
class ClassPathTest : TestCase() {
lateinit var tempDir: File
lateinit var tempDir: Path
override fun setUp() {
tempDir = createTempDir(ClassPathTest::class.simpleName!!)
tempDir = createTempDirectory(ClassPathTest::class.simpleName!!)
super.setUp()
}
override fun tearDown() {
super.tearDown()
tempDir.deleteRecursively()
tempDir.toFile().deleteRecursively()
}
@Test
fun testExtractFromFat() {
val collection = createTempFile("col", ".jar", directory = tempDir).apply { createCollectionJar(emulatedCollectionFiles, "BOOT-INF") }
val cl = URLClassLoader(arrayOf(collection.toURI().toURL()), null)
val collection = createTempFile(directory = tempDir, "col", ".jar").apply { createCollectionJar(emulatedCollectionFiles, "BOOT-INF") }
val cl = URLClassLoader(arrayOf(collection.toUri().toURL()), null)
val cp = classpathFromClassloader(cl, true)
Assert.assertTrue(cp != null && cp.isNotEmpty())
@@ -45,40 +48,40 @@ class ClassPathTest : TestCase() {
@Test
fun testDetectClasspathFromResources() {
val root1 = createTempDir("root1", directory = tempDir)
val jar = createTempFile("jar1", ".jar", directory = tempDir).apply { createJarWithManifest() }
val root1 = createTempDirectory(directory = tempDir, "root1")
val jar = createTempFile(directory = tempDir, "jar1", ".jar").apply { createJarWithManifest() }
val cl = URLClassLoader(
(emulatedClasspath.map { File(root1, it).apply { mkdirs() }.toURI().toURL() }
+ jar.toURI().toURL()).toTypedArray(),
(emulatedClasspath.map { (root1 / it).apply { createDirectories() }.toUri().toURL() }
+ jar.toUri().toURL()).toTypedArray(),
null
)
val cp = cl.classPathFromTypicalResourceUrls().toList().map { it.canonicalFile }
Assert.assertTrue(cp.contains(jar.canonicalFile))
Assert.assertTrue(cp.contains(jar.toFile().canonicalFile))
for (el in emulatedClasspath) {
Assert.assertTrue(cp.contains(File(root1, el).canonicalFile))
Assert.assertTrue(cp.contains((root1 / el).toFile().canonicalFile))
}
}
@Test
fun testFilterClasspath() {
val tempDir = createTempDir().canonicalFile
val tempDir = createTempDirectory().toRealPath()
try {
val files = listOf(
File(tempDir, "projX/classes"),
File(tempDir, "projX/test-classes"),
File(tempDir, "projY/classes")
(tempDir / "projX/classes"),
(tempDir / "projX/test-classes"),
(tempDir / "projY/classes")
)
files.forEach { it.mkdirs() }
files.forEach { it.createDirectories() }
val classloader = URLClassLoader(files.map { it.toURI().toURL() }.toTypedArray(), null)
val classloader = URLClassLoader(files.map { it.toUri().toURL() }.toTypedArray(), null)
val classpath =
scriptCompilationClasspathFromContextOrNull("projX", classLoader = classloader)!!.map { it.toRelativeString(tempDir) }
scriptCompilationClasspathFromContextOrNull("projX", classLoader = classloader)!!.map { it.toPath().relativeTo(tempDir) }
Assert.assertEquals(files.dropLast(1).map { it.toRelativeString(tempDir) }, classpath)
Assert.assertEquals(files.dropLast(1).map { it.relativeTo(tempDir) }, classpath)
} finally {
tempDir.deleteRecursively()
tempDir.toFile().deleteRecursively()
}
}
@@ -103,8 +106,8 @@ private val emulatedClasspath = arrayOf(
"module2/classes/java/test/"
)
fun File.createCollectionJar(fileNames: Array<String>, infDirName: String) {
FileOutputStream(this).use { fileStream ->
fun Path.createCollectionJar(fileNames: Array<String>, infDirName: String) {
this.outputStream().use { fileStream ->
val jarStream = JarOutputStream(fileStream)
jarStream.putNextEntry(JarEntry("$infDirName/classes/"))
jarStream.putNextEntry(JarEntry("$infDirName/lib/"))
@@ -131,8 +134,8 @@ fun testUnpackedCollection(classpath: List<File>, fileNames: Array<String>) {
jars.checkFiles(cpJars.first().parentFile.parentFile)
}
fun File.createJarWithManifest() {
FileOutputStream(this).use { fileStream ->
fun Path.createJarWithManifest() {
this.outputStream().use { fileStream ->
val jarStream = JarOutputStream(fileStream, Manifest())
jarStream.finish()
}

View File

@@ -23,6 +23,7 @@ import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.io.File
import org.jetbrains.kotlin.gradle.util.createTempDir
import kotlin.test.assertEquals
private val DEFAULT_GRADLE_VERSION = GradleVersionRequired.AtLeast("5.6.4")

View File

@@ -6,6 +6,7 @@
package org.jetbrains.kotlin.gradle
import org.jetbrains.kotlin.gradle.util.findFileByName
import org.jetbrains.kotlin.gradle.util.createTempDir
import org.junit.Test
import java.io.File
import java.net.URI
@@ -123,7 +124,7 @@ abstract class AbstractConfigurationCacheIT : BaseGradleIT() {
* directory.
*/
private fun copyReportToTempDir(htmlReportFile: File): File =
createTempDir().let { tempDir ->
createTempDir("report").let { tempDir ->
htmlReportFile.parentFile.copyRecursively(tempDir)
tempDir.resolve(htmlReportFile.name)
}

View File

@@ -15,6 +15,7 @@ import org.junit.After
import org.junit.Before
import java.io.File
import java.lang.IllegalStateException
import java.nio.file.Files
import kotlin.test.*
class BuildSessionLoggerTest {
@@ -25,7 +26,7 @@ class BuildSessionLoggerTest {
@Before
fun prepareFolder() {
rootFolder = File.createTempFile("kotlin-stats", "")
rootFolder = Files.createTempFile("kotlin-stats", "").toFile()
rootFolder.delete()
rootFolder.mkdirs()
}

View File

@@ -9,6 +9,7 @@ dependencies {
testCompile(project(":kotlin-main-kts"))
testCompileOnly(project(":compiler:cli"))
testCompileOnly(project(":kotlin-scripting-jvm-host-unshaded"))
testCompile(kotlinStdlib("jdk8"))
testCompile(commonDep("junit"))
testCompile(projectTests(":kotlin-scripting-compiler")) { isTransitive = false }
testRuntime(project(":kotlin-compiler-embeddable"))

View File

@@ -17,6 +17,8 @@ import org.junit.Assert
import org.junit.Ignore
import org.junit.Test
import java.io.File
import java.nio.file.Path
import kotlin.io.path.*
class MainKtsIT {
@@ -51,42 +53,44 @@ class MainKtsIT {
runWithKotlincAndMainKts("$TEST_DATA_ROOT/context-classloader.main.kts", listOf("MainKtsConfigurator"))
}
@OptIn(ExperimentalPathApi::class)
@Test
fun testCachedReflection() {
val cache = createTempDir("main.kts.test")
val cache = createTempDirectory("main.kts.test")
try {
runWithKotlinRunner("$TEST_DATA_ROOT/use-reflect.main.kts", listOf("false"), cacheDir = cache)
// second run uses the cached script
runWithKotlinRunner("$TEST_DATA_ROOT/use-reflect.main.kts", listOf("false"), cacheDir = cache)
} finally {
cache.deleteRecursively()
cache.toFile().deleteRecursively()
}
}
@OptIn(ExperimentalPathApi::class)
@Test
fun testCache() {
val script = File("$TEST_DATA_ROOT/import-test.main.kts").absolutePath
val cache = createTempDir("main.kts.test")
val cache = createTempDirectory("main.kts.test")
try {
Assert.assertTrue(cache.exists() && cache.listFiles { f: File -> f.extension == "jar" }?.isEmpty() == true)
Assert.assertTrue(cache.exists() && cache.listDirectoryEntries("*.jar").isEmpty())
runWithKotlinRunner(script, OUT_FROM_IMPORT_TEST, cacheDir = cache)
val cacheFile = cache.listFiles { f: File -> f.extension.equals("jar", ignoreCase = true) }?.firstOrNull()
val cacheFile = cache.listDirectoryEntries("*.jar").firstOrNull()
Assert.assertTrue(cacheFile != null && cacheFile.exists())
// run generated jar with java
val javaExecutable = File(File(System.getProperty("java.home"), "bin"), "java")
val args = listOf(javaExecutable.absolutePath, "-jar", cacheFile!!.path)
val args = listOf(javaExecutable.absolutePath, "-jar", cacheFile!!.toString())
runAndCheckResults(
args, OUT_FROM_IMPORT_TEST,
additionalEnvVars = listOf(COMPILED_SCRIPTS_CACHE_DIR_ENV_VAR to cache.absolutePath)
additionalEnvVars = listOf(COMPILED_SCRIPTS_CACHE_DIR_ENV_VAR to cache.toAbsolutePath().toString())
)
// this run should use the cached script
runWithKotlinRunner(script, OUT_FROM_IMPORT_TEST, cacheDir = cache)
} finally {
cache.deleteRecursively()
cache.toFile().deleteRecursively()
}
}
@@ -127,11 +131,11 @@ fun runWithKotlinRunner(
scriptPath: String,
expectedOutPatterns: List<String> = emptyList(),
expectedExitCode: Int = 0,
cacheDir: File? = null
cacheDir: Path? = null
) {
runWithKotlinLauncherScript(
"kotlin", listOf(scriptPath), expectedOutPatterns, expectedExitCode,
additionalEnvVars = listOf(COMPILED_SCRIPTS_CACHE_DIR_ENV_VAR to (cacheDir?.absolutePath ?: ""))
additionalEnvVars = listOf(COMPILED_SCRIPTS_CACHE_DIR_ENV_VAR to (cacheDir?.toAbsolutePath()?.toString() ?: ""))
)
}

View File

@@ -10,14 +10,16 @@ import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.config.Services
import java.io.File
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.createTempDirectory
abstract class BaseJvmAbiTest : TestCase() {
private lateinit var workingDir: File
@OptIn(ExperimentalPathApi::class)
override fun setUp() {
super.setUp()
workingDir = createTempDir(javaClass.simpleName)
workingDir.deleteOnExit()
workingDir = createTempDirectory(javaClass.simpleName).toFile().apply { deleteOnExit() }
}
override fun tearDown() {

View File

@@ -21,6 +21,8 @@ import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.test.TestJdkKind
import org.junit.Assert
import java.io.File
import java.nio.file.Files
import kotlin.io.path.*
import kotlin.script.experimental.annotations.KotlinScript
import kotlin.script.experimental.api.*
import kotlin.script.experimental.host.ScriptingHostConfiguration
@@ -160,7 +162,7 @@ object CompileTimeFibonacciConfiguration : ScriptCompilationConfiguration(
.mapIndexed { index, number -> "val FIB_${index + 1} = $number" }
.joinToString("\n")
val file = createTempFile("CompileTimeFibonacci", ".fib.kts")
val file = Files.createTempFile("CompileTimeFibonacci", ".fib.kts").toFile()
.apply {
deleteOnExit()
writeText(sourceCode)

View File

@@ -18,6 +18,7 @@ val embeddableTestRuntime by configurations.creating {
dependencies {
allTestsRuntime(commonDep("junit"))
testCompile(kotlinStdlib("jdk8"))
testCompile(project(":kotlin-scripting-ide-services-unshaded"))
testCompile(project(":kotlin-scripting-compiler"))
testCompile(project(":kotlin-scripting-dependencies"))

View File

@@ -14,6 +14,7 @@ import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.config.Services
import org.jetbrains.kotlin.scripting.ide_services.test_util.*
import java.io.File
import kotlin.io.path.*
import kotlin.script.experimental.api.*
import kotlin.script.experimental.jvm.impl.KJvmCompiledScript
import kotlin.script.experimental.jvm.jvm
@@ -318,14 +319,15 @@ class JvmIdeServicesTest : TestCase() {
}
}
@OptIn(ExperimentalPathApi::class)
companion object {
private const val MODULE_PATH = "plugins/scripting/scripting-ide-services-test"
private val outputJarDir = createTempDir("temp-ide-services").toPath()
private val outputJarDir = createTempDirectory("temp-ide-services")
private data class CliCompilationResult(val exitCode: ExitCode, val outputJarPath: String)
private fun compileFile(inputKtFileName: String, outputJarName: String): CliCompilationResult {
val jarPath = outputJarDir.resolve(outputJarName).toAbsolutePath().toString().replace('\\', '/')
val jarPath = outputJarDir.resolve(outputJarName).toAbsolutePath().invariantSeparatorsPath
val compilerArgs = arrayOf(
"$MODULE_PATH/testData/$inputKtFileName",

View File

@@ -33,6 +33,7 @@ import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileNotFoundException
import java.io.PrintStream
import java.nio.file.Files
import kotlin.test.assertEquals
@@ -51,7 +52,7 @@ class CompilerClientIT {
}
private val clientAliveFile by lazy {
createTempFile("client", ".alive").apply {
Files.createTempFile("client", ".alive").toFile().apply {
deleteOnExit()
}
}