stdlib tests: move JVM-only test source files

This commit is contained in:
Ilya Gorbunov
2018-01-25 23:28:32 +03:00
parent ba873e2b46
commit 9b38e5e7b5
32 changed files with 0 additions and 17 deletions
-64
View File
@@ -1,64 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.exceptions
import kotlin.test.*
import test.collections.assertArrayNotSameButEquals
import java.io.PrintWriter
import java.io.*
import java.nio.charset.Charset
class ExceptionJVMTest {
@Test fun printStackTraceOnRuntimeException() {
assertPrintStackTrace(RuntimeException("Crikey!"))
assertPrintStackTraceStream(RuntimeException("Crikey2"))
}
@Test fun printStackTraceOnError() {
assertPrintStackTrace(Error("Oh dear"))
assertPrintStackTraceStream(Error("Oh dear2"))
}
fun assertPrintStackTrace(t: Throwable) {
val buffer = StringWriter()
val writer = PrintWriter(buffer)
t.printStackTrace(writer)
comparePrintedThrowableResult(t, buffer.buffer)
}
fun assertPrintStackTraceStream(t: Throwable) {
val byteBuffer = ByteArrayOutputStream()
PrintStream(byteBuffer).use {
t.printStackTrace(it)
}
val stream = PrintStream(byteBuffer)
stream.use {
t.printStackTrace(stream)
}
val bytes = assertNotNull(byteBuffer.toByteArray())
val content = bytes.toString(Charset.defaultCharset())
comparePrintedThrowableResult(t, content)
}
private fun comparePrintedThrowableResult(throwable: Throwable, printedThrowable: CharSequence) {
val stackTrace = throwable.stackTrace
val lines = printedThrowable.lines()
assertEquals(throwable.toString(), lines[0])
stackTrace.forEachIndexed { index, frame ->
assertTrue(lines.any { frame.toString() in it }, "frame at index $index is not found in the printed message")
}
}
@Test fun changeStackTrace() {
val exception = RuntimeException("Fail")
var stackTrace = exception.stackTrace
stackTrace = stackTrace.dropLast(1).toTypedArray()
exception.stackTrace = stackTrace
assertArrayNotSameButEquals(stackTrace, exception.stackTrace)
}
}
@@ -1,206 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.collections
import test.assertStaticAndRuntimeTypeIs
import kotlin.test.*
import kotlin.comparisons.*
import java.util.*
import test.io.deserializeFromHex
import test.io.serializeAndDeserialize
class CollectionJVMTest {
private fun <T> identitySetOf(vararg values: T): MutableSet<T> {
val map = IdentityHashMap<T, String>()
values.forEach { map.put(it, "") }
return map.keys
}
private data class IdentityData(public val value: Int)
@Test fun removeAllWithDifferentEquality() {
val data = listOf(IdentityData(1), IdentityData(1))
val list = data.toMutableList()
list -= identitySetOf(data[0]) as Iterable<IdentityData>
assertTrue(list.single() === data[1], "Identity contains should be used")
val list2 = data.toMutableList()
list2 -= hashSetOf(data[0]) as Iterable<IdentityData>
assertTrue(list2.isEmpty(), "Equality contains should be used")
val set3: MutableSet<IdentityData> = identitySetOf(*data.toTypedArray())
set3 -= arrayOf(data[1])
assertTrue(set3.isEmpty(), "Array doesn't have contains, equality contains is used instead")
}
@Test fun flatMap() {
val data = listOf("", "foo", "bar", "x", "")
val characters = data.flatMap { it.toList() }
println("Got list of characters ${characters}")
assertEquals(7, characters.size)
val text = characters.joinToString("")
assertEquals("foobarx", text)
}
@Test fun filterIntoLinkedList() {
val data = listOf("foo", "bar")
val foo = data.filterTo(LinkedList<String>()) { it.startsWith("f") }
assertTrue {
foo.all { it.startsWith("f") }
}
assertEquals(1, foo.size)
assertEquals(listOf("foo"), foo)
assertStaticAndRuntimeTypeIs<LinkedList<String>>(foo)
}
@Test fun filterNotIntoLinkedListOf() {
val data = listOf("foo", "bar")
val foo = data.filterNotTo(LinkedList<String>()) { it.startsWith("f") }
assertTrue {
foo.all { !it.startsWith("f") }
}
assertEquals(1, foo.size)
assertEquals(listOf("bar"), foo)
assertStaticAndRuntimeTypeIs<LinkedList<String>>(foo)
}
@Test fun filterNotNullIntoLinkedListOf() {
val data = listOf(null, "foo", null, "bar")
val foo = data.filterNotNullTo(LinkedList<String>())
assertEquals(2, foo.size)
assertEquals(LinkedList(listOf("foo", "bar")), foo)
assertStaticAndRuntimeTypeIs<LinkedList<String>>(foo)
}
@Test fun filterIntoSortedSet() {
val data = listOf("foo", "bar")
val sorted = data.filterTo(sortedSetOf<String>()) { it.length == 3 }
assertEquals(2, sorted.size)
assertEquals(sortedSetOf("bar", "foo"), sorted)
assertStaticAndRuntimeTypeIs<TreeSet<String>>(sorted)
}
@Test fun first() {
assertEquals(19, TreeSet(listOf(90, 47, 19)).first())
}
@Test fun last() {
val data = listOf("foo", "bar")
assertEquals("bar", data.last())
assertEquals(25, listOf(15, 19, 20, 25).last())
assertEquals('a', LinkedList(listOf('a')).last())
}
@Test fun lastException() {
assertFails { LinkedList<String>().last() }
}
@Test fun contains() {
assertTrue(LinkedList(listOf(15, 19, 20)).contains(15))
}
@Test fun toArray() {
val data = listOf("foo", "bar")
val arr = data.toTypedArray()
println("Got array ${arr}")
assertEquals(2, arr.size)
todo {
assertTrue {
arr.isArrayOf<String>()
}
}
}
@Test fun toSortedSet() {
val data = listOf("foo", "Foo", "bar")
val set1 = data.toSortedSet()
assertEquals(listOf("Foo", "bar", "foo"), set1.toList())
val set2 = data.toSortedSet(reverseOrder())
assertEquals(listOf("foo", "bar", "Foo"), set2.toList())
val set3 = data.toSortedSet(String.CASE_INSENSITIVE_ORDER)
assertEquals(listOf("bar", "foo"), set3.toList())
}
@Test fun takeReturnsFirstNElements() {
expect(setOf(1, 2)) { sortedSetOf(1, 2, 3, 4, 5).take(2).toSet() }
}
@Test fun filterIsInstanceList() {
val values: List<Any> = listOf(1, 2, 3.toDouble(), "abc", "cde")
val intValues: List<Int> = values.filterIsInstance<Int>()
assertEquals(listOf(1, 2), intValues)
val doubleValues: List<Double> = values.filterIsInstance<Double>()
assertEquals(listOf(3.0), doubleValues)
val stringValues: List<String> = values.filterIsInstance<String>()
assertEquals(listOf("abc", "cde"), stringValues)
val anyValues: List<Any> = values.filterIsInstance<Any>()
assertEquals(values.toList(), anyValues)
val charValues: List<Char> = values.filterIsInstance<Char>()
assertEquals(0, charValues.size)
}
@Test fun filterIsInstanceArray() {
val src: Array<Any> = arrayOf(1, 2, 3.toDouble(), "abc", "cde")
val intValues: List<Int> = src.filterIsInstance<Int>()
assertEquals(listOf(1, 2), intValues)
val doubleValues: List<Double> = src.filterIsInstance<Double>()
assertEquals(listOf(3.0), doubleValues)
val stringValues: List<String> = src.filterIsInstance<String>()
assertEquals(listOf("abc", "cde"), stringValues)
val anyValues: List<Any> = src.filterIsInstance<Any>()
assertEquals(src.toList(), anyValues)
val charValues: List<Char> = src.filterIsInstance<Char>()
assertEquals(0, charValues.size)
}
@Test fun emptyListIsSerializable() = testSingletonSerialization(emptyList<Any>())
@Test fun emptySetIsSerializable() = testSingletonSerialization(emptySet<Any>())
@Test fun emptyMapIsSerializable() = testSingletonSerialization(emptyMap<Any, Any>())
private fun testSingletonSerialization(value: Any) {
val result = serializeAndDeserialize(value)
assertEquals(value, result)
assertTrue(value === result)
}
@Test fun deserializeEmptyList() = testPersistedDeserialization(
"ac ed 00 05 73 72 00 1c 6b 6f 74 6c 69 6e 2e 63 6f 6c 6c 65 63 74 69 6f 6e 73 2e 45 6d 70 74 79 4c 69 73 74 99 6f c7 d0 a7 e0 60 32 02 00 00 78 70",
emptyList<Any>())
@Test fun deserializeEmptySet() = testPersistedDeserialization(
"ac ed 00 05 73 72 00 1b 6b 6f 74 6c 69 6e 2e 63 6f 6c 6c 65 63 74 69 6f 6e 73 2e 45 6d 70 74 79 53 65 74 2f 46 b0 15 76 d7 e2 f4 02 00 00 78 70",
emptySet<Any>())
@Test fun deserializeEmptyMap() = testPersistedDeserialization(
"ac ed 00 05 73 72 00 1b 6b 6f 74 6c 69 6e 2e 63 6f 6c 6c 65 63 74 69 6f 6e 73 2e 45 6d 70 74 79 4d 61 70 72 72 37 71 cb 04 4c d2 02 00 00 78 70",
emptyMap<Any, Any>())
private fun testPersistedDeserialization(hexValue: String, expected: Any) {
val actual = deserializeFromHex<Any>(hexValue)
assertEquals(expected, actual)
}
}
@@ -1,23 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:kotlin.jvm.JvmVersion
package test.collections
import java.util.*
class LinkedListTest : OrderedIterableTests<LinkedList<String>>( { LinkedList(it.asList()) }, LinkedList<String>())
@@ -1,20 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.collections
import kotlin.test.*
import java.util.*
class IteratorsJVMTest {
@Test fun testEnumeration() {
val v = Vector<Int>()
for (i in 1..5)
v.add(i)
var sum = 0
for (k in v.elements())
sum += k
assertEquals(15, sum)
}
}
@@ -1,66 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.collections
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import kotlin.test.*
import kotlin.comparisons.*
class MapJVMTest {
@Test fun createSortedMap() {
val map = sortedMapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1))
assertEquals(1, map["a"])
assertEquals(2, map["b"])
assertEquals(3, map["c"])
assertEquals(listOf("a", "b", "c"), map.keys.toList())
}
@Test fun toSortedMap() {
val map = mapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1))
val sorted = map.toSortedMap()
assertEquals(1, sorted["a"])
assertEquals(2, sorted["b"])
assertEquals(3, sorted["c"])
assertEquals(listOf("a", "b", "c"), sorted.keys.toList())
}
@Test fun toSortedMapWithComparator() {
val map = mapOf(Pair("c", 3), Pair("bc", 2), Pair("bd", 4), Pair("abc", 1))
val sorted = map.toSortedMap(compareBy<String> { it.length }.thenBy { it })
assertEquals(listOf("c", "bc", "bd", "abc"), sorted.keys.toList())
assertEquals(1, sorted["abc"])
assertEquals(2, sorted["bc"])
assertEquals(3, sorted["c"])
}
@Test fun toProperties() {
val map = mapOf("a" to "A", "b" to "B")
val prop = map.toProperties()
assertEquals(2, prop.size)
assertEquals("A", prop.getProperty("a", "fail"))
assertEquals("B", prop.getProperty("b", "fail"))
}
@Test fun iterateAndRemove() {
val map = (1..5).associateByTo(linkedMapOf(), { it }, { 'a' + it })
val iterator = map.iterator()
while (iterator.hasNext()) {
if (iterator.next().key % 2 == 0)
iterator.remove()
}
assertEquals(listOf(1, 3, 5), map.keys.toList())
assertEquals(listOf('b', 'd', 'f'), map.values.toList())
}
@Test fun getOrPutFailsOnConcurrentMap() {
val map = ConcurrentHashMap<String, Int>()
// not an error anymore
expect(1) {
map.getOrPut("x") { 1 }
}
expect(1) {
(map as MutableMap<String, Int>).getOrPut("x") { 1 }
}
}
}
@@ -1,29 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:JvmVersion
package test.collections
import kotlin.test.*
class MutableCollectionJVMTest {
@Test fun shuffledRnd() {
val rnd1 = java.util.Random(42L)
val rnd2 = java.util.Random(42L)
val list = MutableList(100) { it }
val shuffled1 = list.shuffled(rnd1)
val shuffled2 = list.shuffled(rnd2)
assertNotEquals(list, shuffled1)
assertEquals(list.toSet(), shuffled1.toSet())
assertEquals(list.size, shuffled1.distinct().size)
assertEquals(shuffled1, shuffled2)
}
}
@@ -1,26 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.collections
import kotlin.test.*
class SequenceJVMTest {
@Test fun filterIsInstance() {
val src: Sequence<Any> = listOf(1, 2, 3.toDouble(), "abc", "cde").asSequence()
val intValues: Sequence<Int> = src.filterIsInstance<Int>()
assertEquals(listOf(1, 2), intValues.toList())
val doubleValues: Sequence<Double> = src.filterIsInstance<Double>()
assertEquals(listOf(3.0), doubleValues.toList())
val stringValues: Sequence<String> = src.filterIsInstance<String>()
assertEquals(listOf("abc", "cde"), stringValues.toList())
val anyValues: Sequence<Any> = src.filterIsInstance<Any>()
assertEquals(src.toList(), anyValues.toList())
val charValues: Sequence<Char> = src.filterIsInstance<Char>()
assertEquals(0, charValues.toList().size)
}
}
@@ -1,51 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.concurrent
import kotlin.concurrent.*
import kotlin.test.*
import java.util.concurrent.*
import java.util.concurrent.TimeUnit.*
class ThreadTest {
@Test fun scheduledTask() {
val pool = Executors.newFixedThreadPool(1)
val countDown = CountDownLatch(1)
pool.execute {
countDown.countDown()
}
assertTrue(countDown.await(2, SECONDS), "Count down is executed")
}
@Test fun callableInvoke() {
val pool = Executors.newFixedThreadPool(1)
val future = pool.submit<String> { // type specification required here to choose overload for callable, see KT-7882
"Hello"
}
assertEquals("Hello", future.get(2, SECONDS))
}
@Test fun threadLocalGetOrSet() {
val v = ThreadLocal<String>()
assertEquals("v1", v.getOrSet { "v1" })
assertEquals("v1", v.get())
assertEquals("v1", v.getOrSet { "v2" })
v.set(null)
assertEquals("v2", v.getOrSet { "v2" })
v.set("v3")
assertEquals("v3", v.getOrSet { "v2" })
val w = object: ThreadLocal<String>() {
override fun initialValue() = "default"
}
assertEquals("default", w.getOrSet { "v1" })
}
}
@@ -1,32 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.concurrent
import java.util.*
import kotlin.concurrent.*
import kotlin.test.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
class TimerTest {
@Test fun scheduledTask() {
val timer = Timer()
val latch = CountDownLatch(10)
val startedAt = System.nanoTime()
lateinit var callbackTask: TimerTask
val task = timer.scheduleAtFixedRate(100, 10) {
callbackTask = this
latch.countDown()
if (latch.count == 0L) this.cancel()
}
if (!latch.await(1500, TimeUnit.MILLISECONDS)) throw TimeoutException()
val elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt)
val expectedRange = 100L..500L
assertTrue(elapsed in expectedRange, "Expected elapsed ($elapsed ms) to fit in range $expectedRange")
assertSame(task, callbackTask)
}
}
-90
View File
@@ -1,90 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
@file:kotlin.jvm.JvmVersion
package test.io
import org.junit.Test
import java.nio.charset.Charset
import kotlin.test.*
class ConsoleTest {
private val linuxLineSeparator: String = "\n"
private val windowsLineSeparator: String = "\r\n"
@Test
fun shouldReadEmptyLine() {
testReadLine("", emptyList())
}
@Test
fun shouldReadSingleLine() {
for (length in 1..3) {
val line = buildString { repeat(length) { append('a' + it) } }
testReadLine(line, listOf(line))
}
}
@Test
fun trailingEmptyLineIsIgnored() {
testReadLine(linuxLineSeparator, listOf(""))
testReadLine(windowsLineSeparator, listOf(""))
testReadLine("a$linuxLineSeparator", listOf("a"))
testReadLine("a$windowsLineSeparator", listOf("a"))
}
@Test
fun shouldReadOneLine() {
testReadLine("first", listOf("first"))
}
@Test
fun shouldReadTwoLines() {
testReadLine("first${linuxLineSeparator}second", listOf("first", "second"))
}
@Test
fun shouldReadConsecutiveEmptyLines() {
testReadLine("$linuxLineSeparator$linuxLineSeparator", listOf("", ""))
testReadLine("$linuxLineSeparator$windowsLineSeparator", listOf("", ""))
testReadLine("$windowsLineSeparator$linuxLineSeparator", listOf("", ""))
testReadLine("$windowsLineSeparator$windowsLineSeparator", listOf("", ""))
}
@Test
fun shouldReadWindowsLineSeparator() {
testReadLine("first${windowsLineSeparator}second", listOf("first", "second"))
}
@Test
fun shouldReadMultibyteEncodings() {
testReadLine("first${linuxLineSeparator}second", listOf("first", "second"), charset = Charsets.UTF_32)
}
private fun testReadLine(text: String, expected: List<String>, charset: Charset = Charsets.UTF_8) {
val actual = readLines(text, charset)
assertEquals(expected, actual)
val referenceExpected = readLinesReference(text, charset)
assertEquals(referenceExpected, actual, "Comparing to reference readLine")
}
private fun readLines(text: String, charset: Charset): List<String> {
text.byteInputStream(charset).use { stream ->
val decoder = charset.newDecoder()
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
return generateSequence { readLine(stream, decoder) }.toList().also {
assertTrue("All bytes should be read") { stream.read() == -1 }
}
}
}
private fun readLinesReference(text: String, charset: Charset): List<String> {
text.byteInputStream(charset).bufferedReader(charset).use { reader ->
return generateSequence { reader.readLine() }.toList()
}
}
}
-458
View File
@@ -1,458 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.io
import java.io.File
import java.io.IOException
import java.util.*
import kotlin.test.*
class FileTreeWalkTest {
companion object {
val referenceFilenames =
listOf("1", "1/2", "1/3", "1/3/4.txt", "1/3/5.txt", "6", "7.txt", "8", "8/9.txt")
fun createTestFiles(): File {
val basedir = createTempDir()
for (name in referenceFilenames) {
val file = basedir.resolve(name)
if (file.extension.isEmpty())
file.mkdir()
else
file.createNewFile()
}
return basedir
}
}
@Test fun withSimple() {
val basedir = createTestFiles()
try {
val referenceNames = setOf("") + referenceFilenames
val namesTopDown = HashSet<String>()
for (file in basedir.walkTopDown()) {
val name = file.relativeToOrSelf(basedir).invariantSeparatorsPath
assertFalse(namesTopDown.contains(name), "$name is visited twice")
namesTopDown.add(name)
}
assertEquals(referenceNames, namesTopDown)
val namesBottomUp = HashSet<String>()
for (file in basedir.walkBottomUp()) {
val name = file.relativeToOrSelf(basedir).invariantSeparatorsPath
assertFalse(namesBottomUp.contains(name), "$name is visited twice")
namesBottomUp.add(name)
}
assertEquals(referenceNames, namesBottomUp)
} finally {
basedir.deleteRecursively()
}
}
@Test fun singleFile() {
val testFile = createTempFile()
val nonExistantFile = testFile.resolve("foo")
try {
for (walk in listOf(File::walkTopDown, File::walkBottomUp)) {
assertEquals(testFile, walk(testFile).single(), "${walk.name}")
assertEquals(testFile, testFile.walk().onEnter { false }.single(), "${walk.name} - enter should not be called for single file")
assertTrue(walk(nonExistantFile).none(), "${walk.name} - enter should not be called for single file")
}
}
finally {
testFile.delete()
}
}
@Test fun withEnterLeave() {
val basedir = createTestFiles()
try {
val referenceNames =
setOf("", "1", "1/2", "6", "8")
val namesTopDownEnter = HashSet<String>()
val namesTopDownLeave = HashSet<String>()
val namesTopDown = HashSet<String>()
fun enter(file: File): Boolean {
val name = file.relativeToOrSelf(basedir).invariantSeparatorsPath
assertTrue(file.isDirectory, "$name is not directory, only directories should be entered")
assertFalse(namesTopDownEnter.contains(name), "$name is entered twice")
assertFalse(namesTopDownLeave.contains(name), "$name is left before entrance")
if (file.name == "3") return false // filter out 3
namesTopDownEnter.add(name)
return true
}
fun leave(file: File) {
val name = file.relativeToOrSelf(basedir).invariantSeparatorsPath
assertTrue(file.isDirectory, "$name is not directory, only directories should be left")
assertFalse(namesTopDownLeave.contains(name), "$name is left twice")
namesTopDownLeave.add(name)
assertTrue(namesTopDownEnter.contains(name), "$name is left before entrance")
}
fun visit(file: File) {
val name = file.relativeToOrSelf(basedir).invariantSeparatorsPath
if (file.isDirectory) {
assertTrue(namesTopDownEnter.contains(name), "$name is visited before entrance")
namesTopDown.add(name)
assertFalse(namesTopDownLeave.contains(name), "$name is visited after leaving")
}
if (file == basedir)
return
val parent = file.parentFile
if (parent != null) {
val parentName = parent.relativeToOrSelf(basedir).invariantSeparatorsPath
assertTrue(namesTopDownEnter.contains(parentName),
"$name is visited before entering its parent $parentName")
assertFalse(namesTopDownLeave.contains(parentName),
"$name is visited after leaving its parent $parentName")
}
}
for (file in basedir.walkTopDown().onEnter(::enter).onLeave(::leave)) {
visit(file)
}
assertEquals(referenceNames, namesTopDownEnter)
assertEquals(referenceNames, namesTopDownLeave)
namesTopDownEnter.clear()
namesTopDownLeave.clear()
namesTopDown.clear()
for (file in basedir.walkBottomUp().onEnter(::enter).onLeave(::leave)) {
visit(file)
}
assertEquals(referenceNames, namesTopDownEnter)
assertEquals(referenceNames, namesTopDownLeave)
} finally {
basedir.deleteRecursively()
}
}
@Test fun withFilterAndMap() {
val basedir = createTestFiles()
try {
val referenceNames = setOf("", "1", "1/2", "1/3", "6", "8")
assertEquals(referenceNames, basedir.walkTopDown().filter { it.isDirectory }.map {
it.relativeToOrSelf(basedir).invariantSeparatorsPath
}.toHashSet())
} finally {
basedir.deleteRecursively()
}
}
@Test fun withDeleteTxtTopDown() {
val basedir = createTestFiles()
try {
val referenceNames = setOf("", "1", "1/2", "1/3", "6", "8")
val namesTopDown = HashSet<String>()
fun enter(file: File) {
assertTrue(file.isDirectory)
for (child in file.listFiles()) {
if (child.name.endsWith("txt"))
child.delete()
}
}
for (file in basedir.walkTopDown().onEnter { enter(it); true }) {
val name = file.relativeToOrSelf(basedir).invariantSeparatorsPath
assertFalse(namesTopDown.contains(name), "$name is visited twice")
namesTopDown.add(name)
}
assertEquals(referenceNames, namesTopDown)
} finally {
basedir.deleteRecursively()
}
}
@Test fun withDeleteTxtBottomUp() {
val basedir = createTestFiles()
try {
val referenceNames = setOf("", "1", "1/2", "1/3", "6", "8")
val namesTopDown = HashSet<String>()
fun enter(file: File) {
assertTrue(file.isDirectory)
for (child in file.listFiles()) {
if (child.name.endsWith("txt"))
child.delete()
}
}
for (file in basedir.walkBottomUp().onEnter { enter(it); true }) {
val name = file.relativeToOrSelf(basedir).invariantSeparatorsPath
assertFalse(namesTopDown.contains(name), "$name is visited twice")
namesTopDown.add(name)
}
assertEquals(referenceNames, namesTopDown)
} finally {
basedir.deleteRecursively()
}
}
private fun compareWalkResults(expected: Set<String>, basedir: File, filter: (File) -> Boolean) {
val namesTopDown = HashSet<String>()
for (file in basedir.walkTopDown().onEnter { filter(it) }) {
val name = file.toRelativeString(basedir)
assertFalse(namesTopDown.contains(name), "$name is visited twice")
namesTopDown.add(name)
}
assertEquals(expected, namesTopDown, "Top-down walk results differ")
val namesBottomUp = HashSet<String>()
for (file in basedir.walkBottomUp().onEnter { filter(it) }) {
val name = file.toRelativeString(basedir)
assertFalse(namesBottomUp.contains(name), "$name is visited twice")
namesBottomUp.add(name)
}
assertEquals(expected, namesBottomUp, "Bottom-up walk results differ")
}
@Test fun withDirectoryFilter() {
val basedir = createTestFiles()
try {
// Every directory ended with 3 and its content is filtered out
fun filter(file: File): Boolean = !file.name.endsWith("3")
val referenceNames = listOf("", "1", "1/2", "6", "7.txt", "8", "8/9.txt").map { File(it).path }.toSet()
compareWalkResults(referenceNames, basedir, ::filter)
} finally {
basedir.deleteRecursively()
}
}
@Test fun withTotalDirectoryFilter() {
val basedir = createTestFiles()
try {
val referenceNames = emptySet<String>()
compareWalkResults(referenceNames, basedir, { false })
} finally {
basedir.deleteRecursively()
}
}
@Test fun withForEach() {
val basedir = createTestFiles()
try {
var i = 0
basedir.walkTopDown().forEach { _ -> i++ }
assertEquals(10, i);
i = 0
basedir.walkBottomUp().forEach { _ -> i++ }
assertEquals(10, i);
} finally {
basedir.deleteRecursively()
}
}
@Test fun withCount() {
val basedir = createTestFiles()
try {
assertEquals(10, basedir.walkTopDown().count());
assertEquals(10, basedir.walkBottomUp().count());
} finally {
basedir.deleteRecursively()
}
}
@Test fun withReduce() {
val basedir = createTestFiles()
try {
val res = basedir.walkTopDown().reduce { a, b -> if (a.canonicalPath > b.canonicalPath) a else b }
assertTrue(res.endsWith("9.txt"), "Expected end with 9.txt actual: ${res.name}")
} finally {
basedir.deleteRecursively()
}
}
@Test fun withVisitorAndDepth() {
val basedir = createTestFiles()
try {
val files = HashSet<File>()
val dirs = HashSet<File>()
val failed = HashSet<String>()
val stack = ArrayList<File>()
fun beforeVisitDirectory(dir: File): Boolean {
stack.add(dir)
dirs.add(dir.relativeToOrSelf(basedir))
return true
}
fun afterVisitDirectory(dir: File) {
assertEquals(stack.last(), dir)
stack.removeAt(stack.lastIndex)
}
fun visitFile(file: File) {
assertTrue(stack.last().listFiles().contains(file), file.toString())
files.add(file.relativeToOrSelf(basedir))
}
fun visitDirectoryFailed(dir: File, @Suppress("UNUSED_PARAMETER") e: IOException) {
assertEquals(stack.last(), dir)
//stack.removeAt(stack.lastIndex)
failed.add(dir.name)
}
basedir.walkTopDown().onEnter(::beforeVisitDirectory).onLeave(::afterVisitDirectory).
onFail(::visitDirectoryFailed).forEach { it -> if (!it.isDirectory) visitFile(it) }
assertTrue(stack.isEmpty())
for (fileName in arrayOf("", "1", "1/2", "1/3", "6", "8")) {
assertTrue(dirs.contains(File(fileName)), fileName)
}
for (fileName in arrayOf("1/3/4.txt", "1/3/4.txt", "7.txt", "8/9.txt")) {
assertTrue(files.contains(File(fileName)), fileName)
}
//limit maxDepth
files.clear()
dirs.clear()
basedir.walkTopDown().onEnter(::beforeVisitDirectory).onLeave(::afterVisitDirectory).maxDepth(1).
forEach { it -> if (it != basedir) visitFile(it) }
assertTrue(stack.isEmpty())
assertEquals(setOf(File("")), dirs)
for (file in arrayOf("1", "6", "7.txt", "8")) {
assertTrue(files.contains(File(file)), file.toString())
}
//restrict access
if (File(basedir, "1").setReadable(false)) {
try {
files.clear()
dirs.clear()
basedir.walkTopDown().onEnter(::beforeVisitDirectory).onLeave(::afterVisitDirectory).
onFail(::visitDirectoryFailed).forEach { it -> if (!it.isDirectory) visitFile(it) }
assertTrue(stack.isEmpty())
assertEquals(setOf("1"), failed)
assertEquals(listOf("", "1", "6", "8").map { File(it) }.toSet(), dirs)
assertEquals(listOf("7.txt", "8/9.txt").map { File(it) }.toSet(), files)
} finally {
File(basedir, "1").setReadable(true)
}
} else {
System.err.println("cannot restrict access")
}
} finally {
basedir.deleteRecursively()
}
}
@Test fun topDown() {
val basedir = createTestFiles()
try {
val visited = HashSet<File>()
val block: (File) -> Unit = {
assertTrue(!visited.contains(it), it.toString())
assertTrue(it == basedir && visited.isEmpty() || visited.contains(it.parentFile), it.toString())
visited.add(it)
}
basedir.walkTopDown().forEach(block)
assertEquals(10, visited.size)
} finally {
basedir.deleteRecursively()
}
}
@Test fun restrictedAccess() {
val basedir = createTestFiles()
val restricted = File(basedir, "1")
try {
if (restricted.setReadable(false)) {
val visited = HashSet<File>()
val block: (File) -> Unit = {
assertTrue(!visited.contains(it), it.toString())
assertTrue(it == basedir && visited.isEmpty() || visited.contains(it.parentFile), it.toString())
visited.add(it)
}
basedir.walkTopDown().forEach(block)
assertEquals(6, visited.size)
}
} finally {
restricted.setReadable(true)
basedir.deleteRecursively()
}
}
@Test fun backup() {
var count = 0
fun makeBackup(file: File) {
count++
val bakFile = File(file.toString() + ".bak")
file.copyTo(bakFile)
}
val basedir1 = createTestFiles()
try {
basedir1.walkTopDown().forEach {
if (it.isFile) {
makeBackup(it)
}
}
assertEquals(4, count)
} finally {
basedir1.deleteRecursively()
}
count = 0
val basedir2 = createTestFiles()
try {
basedir2.walkTopDown().forEach {
if (it.isFile) {
makeBackup(it)
}
}
assertEquals(4, count)
} finally {
basedir2.deleteRecursively()
}
}
@Test fun find() {
val basedir = createTestFiles()
try {
File(basedir, "8/4.txt").createNewFile()
var count = 0
basedir.walkTopDown().takeWhile { _ -> count == 0 }.forEach {
if (it.name == "4.txt") {
count++
}
}
assertEquals(1, count)
} finally {
basedir.deleteRecursively()
}
}
@Test fun findGits() {
val basedir = createTestFiles()
try {
File(basedir, "1/3/.git").mkdir()
File(basedir, "1/2/.git").mkdir()
File(basedir, "6/.git").mkdir()
val found = HashSet<File>()
for (file in basedir.walkTopDown()) {
if (file.name == ".git") {
found.add(file.parentFile)
}
}
assertEquals(3, found.size)
} finally {
basedir.deleteRecursively()
}
}
@Test fun streamFileTree() {
val dir = createTempDir()
try {
val subDir1 = createTempDir(prefix = "d1_", directory = dir)
val subDir2 = createTempDir(prefix = "d2_", directory = dir)
createTempDir(prefix = "d1_", directory = subDir1)
createTempFile(prefix = "f1_", directory = subDir1)
createTempDir(prefix = "d1_", directory = subDir2)
assertEquals(6, dir.walkTopDown().count())
} finally {
dir.deleteRecursively()
}
dir.mkdir()
try {
val it = dir.walkTopDown().iterator()
it.next()
assertFailsWith<NoSuchElementException>("Second call to next() should fail.") { it.next() }
} finally {
dir.delete()
}
}
}
-621
View File
@@ -1,621 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.io
import java.io.*
import java.util.*
import kotlin.io.walkTopDown
import kotlin.test.*
class FilesTest {
private val isCaseInsensitiveFileSystem = File("C:/") == File("c:/")
private val isBackslashSeparator = File.separatorChar == '\\'
@Test fun testPath() {
val fileSuf = System.currentTimeMillis().toString()
val file1 = createTempFile("temp", fileSuf)
assertTrue(file1.path.endsWith(fileSuf), file1.path)
}
@Test fun testCreateTempDir() {
val dirSuf = System.currentTimeMillis().toString()
val dir1 = createTempDir("temp", dirSuf)
assertTrue(dir1.exists() && dir1.isDirectory && dir1.name.startsWith("temp") && dir1.name.endsWith(dirSuf))
assertFailsWith(IllegalArgumentException::class) {
createTempDir("a")
}
val dir2 = createTempDir("temp")
assertTrue(dir2.exists() && dir2.isDirectory && dir2.name.endsWith(".tmp"))
val dir3 = createTempDir()
assertTrue(dir3.exists() && dir3.isDirectory)
dir1.delete()
dir2.delete()
dir3.delete()
}
@Test fun testCreateTempFile() {
val fileSuf = System.currentTimeMillis().toString()
val file1 = createTempFile("temp", fileSuf)
assertTrue(file1.exists() && file1.name.startsWith("temp") && file1.name.endsWith(fileSuf))
assertFailsWith(IllegalArgumentException::class) {
createTempFile("a")
}
val file2 = createTempFile("temp")
assertTrue(file2.exists() && file2.name.endsWith(".tmp"))
val file3 = createTempFile()
assertTrue(file3.exists())
file1.delete()
file2.delete()
file3.delete()
}
@Test fun listFilesWithFilter() {
val dir = createTempDir("temp")
createTempFile("temp1", ".kt", dir)
createTempFile("temp2", ".java", dir)
createTempFile("temp3", ".kt", dir)
// This line works only with Kotlin File.listFiles(filter)
val result = dir.listFiles { it -> it.name.endsWith(".kt") } // todo ambiguity on SAM
assertEquals(2, result!!.size)
// This line works both with Kotlin File.listFiles(filter) and the same Java function because of SAM
val result2 = dir.listFiles { it -> it.name.endsWith(".kt") }
assertEquals(2, result2!!.size)
}
@Test fun relativeToRooted() {
val file1 = File("/foo/bar/baz")
val file2 = File("/foo/baa/ghoo")
assertEquals("../../bar/baz", file1.relativeTo(file2).invariantSeparatorsPath)
val file3 = File("/foo/bar")
assertEquals("baz", file1.toRelativeString(file3))
assertEquals("..", file3.toRelativeString(file1))
val file4 = File("/foo/bar/")
assertEquals("baz", file1.toRelativeString(file4))
assertEquals("..", file4.toRelativeString(file1))
assertEquals("", file3.toRelativeString(file4))
assertEquals("", file4.toRelativeString(file3))
val file5 = File("/foo/baran")
assertEquals("../bar", file3.relativeTo(file5).invariantSeparatorsPath)
assertEquals("../baran", file5.relativeTo(file3).invariantSeparatorsPath)
assertEquals("../bar", file4.relativeTo(file5).invariantSeparatorsPath)
assertEquals("../baran", file5.relativeTo(file4).invariantSeparatorsPath)
if (isBackslashSeparator) {
val file6 = File("C:\\Users\\Me")
val file7 = File("C:\\Users\\Me\\Documents")
assertEquals("..", file6.toRelativeString(file7))
assertEquals("Documents", file7.toRelativeString(file6))
val file8 = File("""\\my.host\home/user/documents/vip""")
val file9 = File("""\\my.host\home/other/images/nice""")
assertEquals("../../../user/documents/vip", file8.relativeTo(file9).invariantSeparatorsPath)
assertEquals("../../../other/images/nice", file9.relativeTo(file8).invariantSeparatorsPath)
}
if (isCaseInsensitiveFileSystem) {
assertEquals("bar", File("C:/bar").toRelativeString(File("c:/")))
}
}
@Test fun relativeToRelative() {
val nested = File("foo/bar")
val base = File("foo")
assertEquals("bar", nested.toRelativeString(base))
assertEquals("..", base.toRelativeString(nested))
val empty = File("")
val current = File(".")
val parent = File("..")
val outOfRoot = File("../bar")
assertEquals(File("../bar"), outOfRoot.relativeTo(empty))
assertEquals(File("../../bar"), outOfRoot.relativeTo(base))
assertEquals("bar", outOfRoot.toRelativeString(parent))
assertEquals("..", parent.toRelativeString(outOfRoot))
val root = File("/root")
val files = listOf(nested, base, empty, outOfRoot, current, parent)
val bases = listOf(nested, base, empty, current)
for (file in files)
assertEquals("", file.toRelativeString(file), "file should have empty path relative to itself: $file")
for (file in files) {
@Suppress("NAME_SHADOWING")
for (base in bases) {
val rootedFile = root.resolve(file)
val rootedBase = root.resolve(base)
assertEquals(file.relativeTo(base), rootedFile.relativeTo(rootedBase), "nested: $file, base: $base")
assertEquals(file.toRelativeString(base), rootedFile.toRelativeString(rootedBase), "strings, nested: $file, base: $base")
}
}
}
@Test fun relativeToFails() {
val absolute = File("/foo/bar/baz")
val relative = File("foo/bar")
val networkShare1 = File("""\\my.host\share1/folder""")
val networkShare2 = File("""\\my.host\share2\folder""")
fun assertFailsRelativeTo(file: File, base: File) {
val e = assertFailsWith<IllegalArgumentException>("file: $file, base: $base") { file.relativeTo(base) }
val message = assertNotNull(e.message)
assert(file.toString() in message)
assert(base.toString() in message)
}
val allFiles = listOf(absolute, relative) + if (isBackslashSeparator) listOf(networkShare1, networkShare2) else emptyList()
for (file in allFiles) {
for (base in allFiles) {
if (file != base) assertFailsRelativeTo(file, base)
}
}
assertFailsRelativeTo(File("y"), File("../x"))
if (isBackslashSeparator) {
val fileOnC = File("C:/dir1")
val fileOnD = File("D:/dir2")
assertFailsRelativeTo(fileOnC, fileOnD)
}
}
@Test fun relativeTo() {
assertEquals("kotlin", File("src/kotlin").toRelativeString(File("src")))
assertEquals("", File("dir").toRelativeString(File("dir")))
assertEquals("..", File("dir").toRelativeString(File("dir/subdir")))
assertEquals(File("../../test"), File("test").relativeTo(File("dir/dir")))
}
@Suppress("INVISIBLE_MEMBER")
private fun checkFilePathComponents(f: File, root: File, elements: List<String>) {
assertEquals(root, f.root)
val components = f.toComponents()
assertEquals(root, components.root)
assertEquals(elements, components.segments.map { it.toString() })
}
@Test fun filePathComponents() {
checkFilePathComponents(File("/foo/bar"), File("/"), listOf("foo", "bar"))
checkFilePathComponents(File("/foo/bar/gav"), File("/"), listOf("foo", "bar", "gav"))
checkFilePathComponents(File("/foo/bar/gav/"), File("/"), listOf("foo", "bar", "gav"))
checkFilePathComponents(File("bar/gav"), File(""), listOf("bar", "gav"))
checkFilePathComponents(File("C:/bar/gav"), File("C:/"), listOf("bar", "gav"))
checkFilePathComponents(File("C:/"), File("C:/"), listOf())
checkFilePathComponents(File("C:"), File("C:"), listOf())
if (isBackslashSeparator) {
// Check only in Windows
checkFilePathComponents(File("\\\\host.ru\\home\\mike"), File("\\\\host.ru\\home"), listOf("mike"))
checkFilePathComponents(File("//host.ru/home/mike"), File("//host.ru/home"), listOf("mike"))
checkFilePathComponents(File("\\foo\\bar"), File("\\"), listOf("foo", "bar"))
checkFilePathComponents(File("C:\\bar\\gav"), File("C:\\"), listOf("bar", "gav"))
checkFilePathComponents(File("C:\\"), File("C:\\"), listOf())
}
checkFilePathComponents(File(""), File(""), listOf())
checkFilePathComponents(File("."), File(""), listOf("."))
checkFilePathComponents(File(".."), File(""), listOf(".."))
}
@Test fun fileRoot() {
val rooted = File("/foo/bar")
assertTrue(rooted.isRooted)
// assertEquals("/", rooted.root.invariantSeparatorsPath)
if (isBackslashSeparator) {
val diskRooted = File("""C:\foo\bar""")
assertTrue(diskRooted.isRooted)
// assertEquals("""C:\""", diskRooted.rootName)
val networkRooted = File("""\\network\share\""")
assertTrue(networkRooted.isRooted)
// assertEquals("""\\network\share""", networkRooted.rootName)
}
val relative = File("foo/bar")
assertFalse(relative.isRooted)
// assertEquals("", relative.rootName)
}
@Test fun startsWith() {
assertTrue(File("foo/bar").startsWith(File("foo/bar")))
assertTrue(File("foo/bar").startsWith(File("foo")))
assertTrue(File("foo/bar").startsWith(""))
assertFalse(File("foo/bar").startsWith(File("/")))
assertFalse(File("foo/bar").startsWith(File("/foo")))
assertFalse(File("foo/bar").startsWith("fo"))
assertTrue(File("/foo/bar").startsWith(File("/foo/bar")))
assertTrue(File("/foo/bar").startsWith(File("/foo")))
assertTrue(File("/foo/bar").startsWith("/"))
assertFalse(File("/foo/bar").startsWith(""))
assertFalse(File("/foo/bar").startsWith(File("foo")))
assertFalse(File("/foo/bar").startsWith("/fo"))
if (isBackslashSeparator) {
assertTrue(File("C:\\Users\\Me\\Temp\\Game").startsWith("C:\\Users\\Me"))
assertFalse(File("C:\\Users\\Me\\Temp\\Game").startsWith("C:\\Users\\He"))
assertTrue(File("C:\\Users\\Me").startsWith("C:\\"))
}
if (isCaseInsensitiveFileSystem) {
assertTrue(File("C:\\Users\\Me").startsWith("c:\\"))
}
}
@Test fun endsWith() {
assertTrue(File("/foo/bar").endsWith("bar"))
assertTrue(File("/foo/bar").endsWith("foo/bar"))
assertTrue(File("/foo/bar").endsWith("/foo/bar"))
assertTrue(File("foo/bar").endsWith("foo/bar"))
assertTrue(File("foo/bar").endsWith("bar/"))
assertFalse(File("/foo/bar").endsWith("ar"))
assertFalse(File("/foo/bar").endsWith("/bar"))
assertFalse(File("/foo/bar/gav/bar").endsWith("/bar"))
assertFalse(File("/foo/bar/gav/bar").endsWith("/gav/bar"))
assertFalse(File("/foo/bar/gav").endsWith("/bar"))
assertFalse(File("foo/bar").endsWith("/bar"))
if (isCaseInsensitiveFileSystem) {
assertTrue(File("/foo/bar").endsWith("Bar"))
}
}
/*
@Test fun subPath() {
if (isBackslashSeparator) {
// Check only in Windows
assertEquals(File("mike"), File("//my.host.net/home/mike/temp").subPath(0, 1))
assertEquals(File("mike"), File("\\\\my.host.net\\home\\mike\\temp").subPath(0, 1))
}
assertEquals(File("bar/gav"), File("/foo/bar/gav/hi").subPath(1, 3))
assertEquals(File("foo"), File("/foo/bar/gav/hi").subPath(0, 1))
assertEquals(File("gav/hi"), File("/foo/bar/gav/hi").subPath(2, 4))
}
*/
@Test fun normalize() {
assertEquals(File("/foo/bar/baaz"), File("/foo/./bar/gav/../baaz").normalize())
assertEquals(File("/foo/bar/baaz"), File("/foo/bak/../bar/gav/../baaz").normalize())
assertEquals(File("../../bar"), File("../foo/../../bar").normalize())
// For Unix C:\windows is not correct so it's not the same as C:/windows
if (isBackslashSeparator) {
assertEquals(File("C:\\windows"), File("C:\\home\\..\\documents\\..\\windows").normalize())
assertEquals(File("C:/windows"), File("C:/home/../documents/../windows").normalize())
}
assertEquals(File("foo"), File("gav/bar/../../foo").normalize())
assertEquals(File("/../foo"), File("/bar/../../foo").normalize())
}
@Test fun resolve() {
assertEquals(File("/foo/bar/gav"), File("/foo/bar").resolve("gav"))
assertEquals(File("/foo/bar/gav"), File("/foo/bar/").resolve("gav"))
assertEquals(File("/gav"), File("/foo/bar").resolve("/gav"))
// For Unix C:\path is not correct so it's cannot be automatically converted
if (isBackslashSeparator) {
assertEquals(File("C:\\Users\\Me\\Documents\\important.doc"),
File("C:\\Users\\Me").resolve("Documents\\important.doc"))
assertEquals(File("C:/Users/Me/Documents/important.doc"),
File("C:/Users/Me").resolve("Documents/important.doc"))
}
assertEquals(File(""), File("").resolve(""))
assertEquals(File("bar"), File("").resolve("bar"))
assertEquals(File("foo/bar"), File("foo").resolve("bar"))
// should it normalize such paths?
// assertEquals(File("bar"), File("foo").resolve("../bar"))
// assertEquals(File("../bar"), File("foo").resolve("../../bar"))
// assertEquals(File("foo/bar"), File("foo").resolve("./bar"))
}
@Test fun resolveSibling() {
assertEquals(File("/foo/gav"), File("/foo/bar").resolveSibling("gav"))
assertEquals(File("/foo/gav"), File("/foo/bar/").resolveSibling("gav"))
assertEquals(File("/gav"), File("/foo/bar").resolveSibling("/gav"))
// For Unix C:\path is not correct so it's cannot be automatically converted
if (isBackslashSeparator) {
assertEquals(File("C:\\Users\\Me\\Documents\\important.doc"),
File("C:\\Users\\Me\\profile.ini").resolveSibling("Documents\\important.doc"))
assertEquals(File("C:/Users/Me/Documents/important.doc"),
File("C:/Users/Me/profile.ini").resolveSibling("Documents/important.doc"))
}
assertEquals(File("gav"), File("foo").resolveSibling("gav"))
assertEquals(File("../gav"), File("").resolveSibling("gav"))
}
@Test fun extension() {
assertEquals("bbb", File("aaa.bbb").extension)
assertEquals("", File("aaa").extension)
assertEquals("", File("aaa.").extension)
// maybe we should think that such files have name .bbb and no extension
assertEquals("bbb", File(".bbb").extension)
assertEquals("", File("/my.dir/log").extension)
}
@Test fun nameWithoutExtension() {
assertEquals("aaa", File("aaa.bbb").nameWithoutExtension)
assertEquals("aaa", File("aaa").nameWithoutExtension)
assertEquals("aaa", File("aaa.").nameWithoutExtension)
assertEquals("", File(".bbb").nameWithoutExtension)
assertEquals("log", File("/my.dir/log").nameWithoutExtension)
}
@Test fun testCopyTo() {
val srcFile = createTempFile()
val dstFile = createTempFile()
try {
srcFile.writeText("Hello, World!")
assertFailsWith(FileAlreadyExistsException::class, "copy do not overwrite existing file") {
srcFile.copyTo(dstFile)
}
var dst = srcFile.copyTo(dstFile, overwrite = true)
assertTrue(dst === dstFile)
compareFiles(srcFile, dst, "copy with overwrite over existing file")
assertTrue(dstFile.delete())
dst = srcFile.copyTo(dstFile)
compareFiles(srcFile, dst, "copy to new file")
assertTrue(dstFile.delete())
dstFile.mkdir()
val child = File(dstFile, "child")
child.createNewFile()
assertFailsWith(FileAlreadyExistsException::class, "copy with overwrite do not overwrite non-empty dir") {
srcFile.copyTo(dstFile, overwrite = true)
}
child.delete()
srcFile.copyTo(dstFile, overwrite = true)
assertEquals(srcFile.readText(), dstFile.readText(), "copy with overwrite over empty dir")
assertTrue(srcFile.delete())
assertTrue(dstFile.delete())
assertFailsWith(NoSuchFileException::class) {
srcFile.copyTo(dstFile)
}
srcFile.mkdir()
srcFile.resolve("somefile").writeText("some content")
dstFile.writeText("")
assertFailsWith(FileAlreadyExistsException::class, "copy dir do not overwrite file") {
srcFile.copyTo(dstFile)
}
srcFile.copyTo(dstFile, overwrite = true)
assertTrue(dstFile.isDirectory)
assertTrue(dstFile.listFiles()!!.isEmpty(), "only directory is copied, but not its content")
assertFailsWith(FileAlreadyExistsException::class, "copy dir do not overwrite dir") {
srcFile.copyTo(dstFile)
}
srcFile.copyTo(dstFile, overwrite = true)
assertTrue(dstFile.isDirectory)
assertTrue(dstFile.listFiles()!!.isEmpty(), "only directory is copied, but not its content")
dstFile.resolve("somefile2").writeText("some content2")
assertFailsWith(FileAlreadyExistsException::class, "copy dir do not overwrite dir") {
srcFile.copyTo(dstFile, overwrite = true)
}
}
finally {
srcFile.deleteRecursively()
dstFile.deleteRecursively()
}
}
@Test fun copyToNameWithoutParent() {
val currentDir = File("").absoluteFile!!
val srcFile = createTempFile()
val dstFile = createTempFile(directory = currentDir)
try {
srcFile.writeText("Hello, World!", Charsets.UTF_8)
dstFile.delete()
val dstRelative = File(dstFile.name)
srcFile.copyTo(dstRelative)
assertEquals(srcFile.readText(), dstFile.readText())
}
finally {
dstFile.delete()
srcFile.delete()
}
}
@Test fun deleteRecursively() {
val dir = createTempDir()
dir.delete()
dir.mkdir()
val subDir = File(dir, "subdir");
subDir.mkdir()
File(dir, "test1.txt").createNewFile()
File(subDir, "test2.txt").createNewFile()
assertTrue(dir.deleteRecursively())
assertFalse(dir.exists())
assertTrue(dir.deleteRecursively())
}
@Test fun deleteRecursivelyWithFail() {
val basedir = FileTreeWalkTest.createTestFiles()
val restricted = File(basedir, "1")
try {
if (restricted.setReadable(false)) {
if (File(basedir, "7.txt").setReadable(false)) {
assertFalse(basedir.deleteRecursively(), "Expected incomplete recursive deletion.")
restricted.setReadable(true)
File(basedir, "7.txt").setReadable(true)
var i = 0
for (file in basedir.walkTopDown()) {
i++
}
assertEquals(6, i)
}
}
} finally {
restricted.setReadable(true)
File(basedir, "7.txt").setReadable(true)
basedir.deleteRecursively()
}
}
fun compareFiles(src: File, dst: File, message: String? = null) {
assertTrue(dst.exists())
assertEquals(src.isFile, dst.isFile, message)
if (dst.isFile) {
assertTrue(Arrays.equals(src.readBytes(), dst.readBytes()), message)
}
}
fun compareDirectories(src: File, dst: File) {
for (srcFile in src.walkTopDown()) {
val dstFile = dst.resolve(srcFile.relativeTo(src))
compareFiles(srcFile, dstFile)
}
}
@Test fun copyRecursively() {
val src = createTempDir()
val dst = createTempDir()
dst.delete()
fun check() = compareDirectories(src, dst)
try {
val subDir1 = createTempDir(prefix = "d1_", directory = src)
val subDir2 = createTempDir(prefix = "d2_", directory = src)
createTempDir(prefix = "d1_", directory = subDir1)
val file1 = createTempFile(prefix = "f1_", directory = src)
val file2 = createTempFile(prefix = "f2_", directory = subDir1)
file1.writeText("hello")
file2.writeText("wazzup")
createTempDir(prefix = "d1_", directory = subDir2)
assertTrue(src.copyRecursively(dst))
check()
assertFailsWith(FileAlreadyExistsException::class) {
src.copyRecursively(dst)
}
var conflicts = 0
src.copyRecursively(dst) {
_: File, e: IOException ->
if (e is FileAlreadyExistsException) {
conflicts++
OnErrorAction.SKIP
} else {
throw e
}
}
assertEquals(2, conflicts)
if (subDir1.setReadable(false)) {
try {
dst.deleteRecursively()
var caught = false
assertTrue(src.copyRecursively(dst) {
_: File, e: IOException ->
if (e is AccessDeniedException) {
caught = true
OnErrorAction.SKIP
} else {
throw e
}
})
assertTrue(caught)
check()
} finally {
subDir1.setReadable(true)
}
}
src.deleteRecursively()
dst.deleteRecursively()
assertFailsWith(NoSuchFileException::class) {
src.copyRecursively(dst)
}
assertFalse(src.copyRecursively(dst) { _, _ -> OnErrorAction.TERMINATE })
} finally {
src.deleteRecursively()
dst.deleteRecursively()
}
}
@Test fun copyRecursivelyWithOverwrite() {
val src = createTempDir()
val dst = createTempDir()
fun check() = compareDirectories(src, dst)
try {
val srcFile = src.resolve("test")
val dstFile = dst.resolve("test")
srcFile.writeText("text1")
src.copyRecursively(dst)
srcFile.writeText("text1 modified")
src.copyRecursively(dst, overwrite = true)
check()
dstFile.delete()
dstFile.mkdir()
dstFile.resolve("subFile").writeText("subfile")
src.copyRecursively(dst, overwrite = true)
check()
srcFile.delete()
srcFile.mkdir()
srcFile.resolve("subFile").writeText("text2")
src.copyRecursively(dst, overwrite = true)
check()
}
finally {
src.deleteRecursively()
dst.deleteRecursively()
}
}
@Test fun helpers1() {
val str = "123456789\n"
System.setIn(str.byteInputStream())
val reader = System.`in`.bufferedReader()
assertEquals("123456789", reader.readLine())
val stringReader = str.reader()
assertEquals('1', stringReader.read().toChar())
assertEquals('2', stringReader.read().toChar())
assertEquals('3', stringReader.read().toChar())
}
@Test fun helpers2() {
val file = createTempFile()
val writer = file.printWriter()
val str1 = "Hello, world!"
val str2 = "Everything is wonderful!"
writer.println(str1)
writer.println(str2)
writer.close()
val reader = file.bufferedReader()
assertEquals(str1, reader.readLine())
assertEquals(str2, reader.readLine())
}
}
-42
View File
@@ -1,42 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.io
import kotlin.test.*
import java.io.Writer
import java.io.BufferedReader
class IOStreamsTest {
@Test fun testGetStreamOfFile() {
val tmpFile = createTempFile()
var writer: Writer? = null
try {
writer = tmpFile.outputStream().writer()
writer.write("Hello, World!")
} finally {
writer?.close()
}
val act: String?
var reader: BufferedReader? = null
try {
reader = tmpFile.inputStream().reader().buffered()
act = reader.readLine()
} finally {
reader?.close()
}
assertEquals("Hello, World!", act)
}
@Test fun testInputStreamIterator() {
val x = ByteArray(10) { it.toByte() }
val result = mutableListOf<Byte>()
x.inputStream().buffered().use { stream ->
for(b in stream) {
result += b
}
}
assertEquals(x.asList(), result)
}
}
-199
View File
@@ -1,199 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.io
import kotlin.test.*
import java.io.File
import java.io.Reader
import java.io.StringReader
import java.net.URL
import java.util.ArrayList
fun sample(): Reader = StringReader("Hello\nWorld");
class ReadWriteTest {
@Test fun testAppendText() {
val file = File.createTempFile("temp", System.nanoTime().toString())
file.writeText("Hello\n")
file.appendText("World\n")
file.appendText("Again")
assertEquals("Hello\nWorld\nAgain", file.readText())
assertEquals(listOf("Hello", "World", "Again"), file.readLines(Charsets.UTF_8))
file.deleteOnExit()
}
@Test fun reader() {
val list = ArrayList<String>()
/* TODO would be nicer maybe to write this as
reader.lines.forEach { ... }
as we could one day maybe write that as
for (line in reader.lines)
if the for(elem in thing) {...} statement could act as syntax sugar for
thing.forEach{ elem -> ... }
if thing is not an Iterable/array/Iterator but has a suitable forEach method
*/
sample().forEachLine {
list.add(it)
}
assertEquals(listOf("Hello", "World"), list)
assertEquals(listOf("Hello", "World"), sample().readLines())
sample().useLines {
assertEquals(listOf("Hello", "World"), it.toList())
}
var reader = StringReader("")
var c = 0
reader.forEachLine { c++ }
assertEquals(0, c)
reader = StringReader(" ")
reader.forEachLine { c++ }
assertEquals(1, c)
reader = StringReader(" \n")
c = 0
reader.forEachLine { c++ }
assertEquals(1, c)
reader = StringReader(" \n ")
c = 0
reader.forEachLine { c++ }
assertEquals(2, c)
}
@Test fun file() {
val file = File.createTempFile("temp", System.nanoTime().toString())
val writer = file.outputStream().writer().buffered()
writer.write("Hello")
writer.newLine()
writer.write("World")
writer.close()
//file.replaceText("Hello\nWorld")
file.forEachBlock { arr: ByteArray, size: Int ->
assertTrue(size >= 11 && size <= 12, size.toString())
assertTrue(arr.contains('W'.toByte()))
}
val list = ArrayList<String>()
file.forEachLine(Charsets.UTF_8, {
list.add(it)
})
assertEquals(arrayListOf("Hello", "World"), list)
assertEquals(arrayListOf("Hello", "World"), file.readLines())
file.useLines {
assertEquals(arrayListOf("Hello", "World"), it.toList())
}
val text = file.inputStream().reader().readText()
assertTrue(text.contains("Hello"))
assertTrue(text.contains("World"))
file.writeText("")
var c = 0
file.forEachLine { c++ }
assertEquals(0, c)
file.writeText(" ")
file.forEachLine { c++ }
assertEquals(1, c)
file.writeText(" \n")
c = 0
file.forEachLine { c++ }
assertEquals(1, c)
file.writeText(" \n ")
c = 0
file.forEachLine { c++ }
assertEquals(2, c)
file.deleteOnExit()
}
@Test fun testUse() {
val list = ArrayList<String>()
val reader = sample().buffered()
reader.use {
while (true) {
val line = it.readLine()
if (line != null)
list.add(line)
else
break
}
}
assertEquals(arrayListOf("Hello", "World"), list)
}
@Test fun testPlatformNullUse() {
fun <T> platformNull() = @Suppress("UNCHECKED_CAST") java.util.Collections.singleton(null as T).first()
val resource = platformNull<java.io.Closeable>()
val result = resource.use {
"ok"
}
assertEquals("ok", result)
}
@Test fun testURL() {
val url = URL("http://kotlinlang.org")
val text = url.readText()
assertFalse(text.isEmpty())
val text2 = url.readText(charset("UTF8"))
assertFalse(text2.isEmpty())
}
}
class LineIteratorTest {
@Test fun useLines() {
// TODO we should maybe zap the useLines approach as it encourages
// use of iterators which don't close the underlying stream
val list1 = sample().useLines { it.toList() }
val list2 = sample().useLines<ArrayList<String>>{ it.toCollection(arrayListOf()) }
assertEquals(listOf("Hello", "World"), list1)
assertEquals(listOf("Hello", "World"), list2)
}
@Test fun manualClose() {
val reader = sample().buffered()
try {
val list = reader.lineSequence().toList()
assertEquals(arrayListOf("Hello", "World"), list)
} finally {
reader.close()
}
}
@Test fun boundaryConditions() {
var reader = StringReader("").buffered()
assertEquals(emptyList(), reader.lineSequence().toList())
reader.close()
reader = StringReader(" ").buffered()
assertEquals(listOf(" "), reader.lineSequence().toList())
reader.close()
reader = StringReader(" \n").buffered()
assertEquals(listOf(" "), reader.lineSequence().toList())
reader.close()
reader = StringReader(" \n ").buffered()
assertEquals(listOf(" ", " "), reader.lineSequence().toList())
reader.close()
}
}
@@ -1,87 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.io
import java.io.*
import kotlin.test.*
private class Serial(val name: String) : Serializable {
override fun toString() = name
}
private data class DataType(val name: String, val value: Int, val percent: Double) : Serializable
private enum class EnumSingleton { INSTANCE }
private object ObjectSingleton : Serializable {
private fun readResolve(): Any = ObjectSingleton
}
private class OldSchoolSingleton private constructor() : Serializable {
private fun readResolve(): Any = INSTANCE
companion object {
val INSTANCE = OldSchoolSingleton()
}
}
class SerializableTest {
@Test fun testClosure() {
val tuple = Triple("Ivan", 12, Serial("serial"))
val fn = { tuple.toString() }
val deserialized = serializeAndDeserialize(fn)
assertEquals(fn(), deserialized())
}
@Test fun testComplexClosure() {
val y = 12
val fn1 = { x: Int -> (x + y).toString() }
val fn2: Int.(Int) -> String = { fn1(this + it) }
val deserialized = serializeAndDeserialize(fn2)
assertEquals(5.fn2(10), 5.deserialized(10))
}
@Test fun testDataClass() {
val data = DataType("name", 176, 1.4)
val deserialized = serializeAndDeserialize(data)
assertEquals(data, deserialized)
}
@Test fun testSingletons() {
assertTrue(EnumSingleton.INSTANCE === serializeAndDeserialize(EnumSingleton.INSTANCE))
assertTrue(OldSchoolSingleton.INSTANCE === serializeAndDeserialize(OldSchoolSingleton.INSTANCE))
assertTrue(ObjectSingleton === serializeAndDeserialize(ObjectSingleton))
}
}
public fun <T> serializeToByteArray(value: T): ByteArray {
val outputStream = ByteArrayOutputStream()
val objectOutputStream = ObjectOutputStream(outputStream)
objectOutputStream.writeObject(value)
objectOutputStream.close()
outputStream.close()
return outputStream.toByteArray()
}
public fun <T> deserializeFromByteArray(bytes: ByteArray): T {
val inputStream = ByteArrayInputStream(bytes)
val inputObjectStream = ObjectInputStream(inputStream)
@Suppress("UNCHECKED_CAST")
return inputObjectStream.readObject() as T
}
public fun <T> serializeAndDeserialize(value: T): T {
val bytes = serializeToByteArray(value)
return deserializeFromByteArray(bytes)
}
private fun hexToBytes(value: String): ByteArray = value.split(" ").map { Integer.parseInt(it, 16).toByte() }.toByteArray()
public fun <T> deserializeFromHex(value: String) = deserializeFromByteArray<T>(hexToBytes(value))
public fun <T> serializeToHex(value: T) =
serializeToByteArray(value).joinToString(" ") { (it.toInt() and 0xFF).toString(16).padStart(2, '0') }
-23
View File
@@ -1,23 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmVersion
package test.collections.js
public actual fun <V> stringMapOf(vararg pairs: Pair<String, V>): HashMap<String, V> = hashMapOf<String, V>(*pairs)
public actual fun <V> linkedStringMapOf(vararg pairs: Pair<String, V>): LinkedHashMap<String, V> = linkedMapOf(*pairs)
public actual fun stringSetOf(vararg elements: String): HashSet<String> = hashSetOf(*elements)
public actual fun linkedStringSetOf(vararg elements: String): LinkedHashSet<String> = linkedSetOf(*elements)
@@ -1,17 +0,0 @@
@file:kotlin.jvm.JvmVersion // TODO: Can't run in JS: spaces in function name KT-4160
package test.language
import kotlin.test.*
class EscapedTestNamesTest {
@Test fun `strings equal`() {
val actual = "abc"
assertEquals("abc", actual)
}
@Test fun `numbers equal`() {
val actual = 5
assertEquals(5, actual)
}
}
@@ -1,105 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.numbers
import java.math.BigInteger
import java.math.BigDecimal
import kotlin.test.*
import java.math.MathContext
import java.math.RoundingMode
class BigNumbersTest {
@Test fun testBigInteger() {
val a = BigInteger("2")
val b = BigInteger("3")
assertEquals(BigInteger("5"), a + b)
assertEquals(BigInteger("-1"), a - b)
assertEquals(BigInteger("6"), a * b)
assertEquals(BigInteger("0"), a / b)
assertEquals(BigInteger("-2"), -a)
assertEquals(BigInteger("-2"), -a % b)
assertEquals(BigInteger("1"), (-a).mod(b))
assertEquals(BigInteger("-2"), (-a).remainder(b))
assertEquals(BigInteger("3"), a.inc())
assertEquals(BigInteger("1"), a.dec())
assertEquals(BigInteger("-3"), a.inv())
assertEquals(BigInteger("2"), a and b)
assertEquals(BigInteger("3"), a or b)
assertEquals(BigInteger("1"), a xor b)
assertEquals(BigInteger("4"), a shl 1)
assertEquals(BigInteger("1"), a shr 1)
assertEquals(BigInteger("0"), a shr 2)
assertEquals(BigInteger("-4"), -a shl 1)
assertEquals(BigInteger("-1"), -a shr 1)
assertEquals(BigInteger("-1"), -a shr 2)
assertEquals(BigInteger("2"), 2.toBigInteger())
assertEquals(BigInteger("-3"), -3L.toBigInteger())
assertEquals(BigDecimal("2"), a.toBigDecimal())
assertEquals(BigDecimal("0.02"), a.toBigDecimal(2))
assertEquals(BigDecimal("2E+2"), a.toBigDecimal(-2))
assertEquals(BigDecimal("2.6E+3"), BigInteger("253").toBigDecimal(-1, MathContext(2, RoundingMode.UP)))
assertEquals(BigDecimal("2.6E+2"), BigInteger("253").toBigDecimal(mathContext = MathContext(2, RoundingMode.UP)))
assertEquals(BigDecimal("3"), BigInteger("253").toBigDecimal(2, MathContext(1, RoundingMode.UP)))
var c = 2.toBigInteger()
assertEquals(BigInteger("2"), c++)
assertEquals(BigInteger("3"), c)
assertEquals(BigInteger("4"), ++c)
assertEquals(BigInteger("4"), c)
assertEquals(BigInteger("4"), c--)
assertEquals(BigInteger("3"), c)
assertEquals(BigInteger("2"), --c)
assertEquals(BigInteger("2"), c)
}
@Test fun testBigDecimal() {
val a = BigDecimal("2")
val b = BigDecimal("3")
assertEquals(BigDecimal("5"), a + b)
assertEquals(BigDecimal("-1"), a - b)
assertEquals(BigDecimal("6"), a * b)
assertEquals(BigDecimal("2"), BigDecimal("4") / a)
assertEquals(BigDecimal("-2"), -a)
assertEquals(BigDecimal("-2"), -a % b)
assertEquals(BigDecimal("-2"), (-a).mod(b))
assertEquals(BigDecimal("-2"), (-a).rem(b))
assertEquals(BigDecimal("3"), a.inc())
assertEquals(BigDecimal("1"), a.dec())
assertEquals(BigDecimal("2"), 2.toBigDecimal())
assertEquals(BigDecimal("-3"), -3L.toBigDecimal())
assertEquals(BigDecimal("2.0"), 2f.toBigDecimal())
assertEquals(BigDecimal("0.5"), 0.5.toBigDecimal())
var c = "1.5".toBigDecimal()
assertEquals(BigDecimal("1.5"), c++)
assertEquals(BigDecimal("2.5"), c)
assertEquals(BigDecimal("3.5"), ++c)
assertEquals(BigDecimal("3.5"), c)
assertEquals(BigDecimal("3.5"), c--)
assertEquals(BigDecimal("2.5"), c)
assertEquals(BigDecimal("1.5"), --c)
assertEquals(BigDecimal("1.5"), c)
}
@Test fun bigDecimalDivRounding() {
val (d1, d2, d3, d4, d5) = (1..5).map { BigDecimal(it.toString()) }
val d7 = BigDecimal("7")
assertEquals(d1, d2 / d3)
assertEquals(d2, d3 / d2)
assertEquals(d2, d5 / d2)
assertEquals(d4, d7 / d2)
assertEquals(d1, d7 / d5)
}
}
@@ -1,93 +0,0 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:kotlin.jvm.JvmVersion
package test.numbers
import kotlin.test.*
class CompanionIntrinsicObjectsJVMTest {
@Test fun intTest() {
val i = Int
i.MAX_VALUE
assertEquals(java.lang.Integer.MAX_VALUE, Int.MAX_VALUE)
assertEquals(java.lang.Integer.MIN_VALUE, Int.MIN_VALUE)
}
@Test fun doubleTest() {
val d = Double
d.NaN
assertEquals(java.lang.Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)
assertEquals(java.lang.Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY)
assertEquals(java.lang.Double.NaN, Double.NaN)
assertEquals(java.lang.Double.MAX_VALUE, Double.MAX_VALUE)
assertEquals(java.lang.Double.MIN_VALUE, Double.MIN_VALUE)
}
@Test fun floatTest() {
val f = Float
f.NEGATIVE_INFINITY
assertEquals(java.lang.Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)
assertEquals(java.lang.Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY)
assertEquals(java.lang.Float.NaN, Float.NaN)
assertEquals(java.lang.Float.MAX_VALUE, Float.MAX_VALUE)
assertEquals(java.lang.Float.MIN_VALUE, Float.MIN_VALUE)
}
@Test fun longTest() {
val l = Long
l.MAX_VALUE
assertEquals(java.lang.Long.MAX_VALUE, Long.MAX_VALUE)
assertEquals(java.lang.Long.MIN_VALUE, Long.MIN_VALUE)
}
@Test fun shortTest() {
val s = Short
s.MIN_VALUE
assertEquals(java.lang.Short.MAX_VALUE, Short.MAX_VALUE)
assertEquals(java.lang.Short.MIN_VALUE, Short.MIN_VALUE)
}
@Test fun byteTest() {
val b = Byte
b.MAX_VALUE
assertEquals(java.lang.Byte.MAX_VALUE, Byte.MAX_VALUE)
assertEquals(java.lang.Byte.MIN_VALUE, Byte.MIN_VALUE)
}
@Test fun charTest() {
val ch = Char
ch.MIN_SURROGATE
assertEquals(ch, Char)
}
@Test fun stringTest() {
val s = String
s.CASE_INSENSITIVE_ORDER
assertEquals(s, String)
}
}
@@ -1,34 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.numbers
import kotlin.test.*
import kotlin.math.*
class MathJVMTest {
@Test fun IEEEremainder() {
val data = arrayOf( // a a IEEErem 2.5
doubleArrayOf(-2.0, 0.5),
doubleArrayOf(-1.25, -1.25),
doubleArrayOf( 0.0, 0.0),
doubleArrayOf( 1.0, 1.0),
doubleArrayOf( 1.25, 1.25),
doubleArrayOf( 1.5, -1.0),
doubleArrayOf( 2.0, -0.5),
doubleArrayOf( 2.5, 0.0),
doubleArrayOf( 3.5, 1.0),
doubleArrayOf( 3.75, -1.25),
doubleArrayOf( 4.0, -1.0)
)
for ((a, r) in data) {
assertEquals(r, a.IEEErem(2.5), "($a).IEEErem(2.5)")
}
assertTrue(Double.NaN.IEEErem(2.5).isNaN())
assertTrue(2.0.IEEErem(Double.NaN).isNaN())
assertTrue(Double.POSITIVE_INFINITY.IEEErem(2.0).isNaN())
assertTrue(2.0.IEEErem(0.0).isNaN())
assertEquals(PI, PI.IEEErem(Double.NEGATIVE_INFINITY))
}
}
@@ -1,56 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.numbers
import java.math.BigDecimal
import kotlin.test.*
class NumbersJVMTest {
@Test fun intMinMaxValues() {
assertEquals(java.lang.Integer.MIN_VALUE, Int.MIN_VALUE)
assertEquals(java.lang.Integer.MAX_VALUE, Int.MAX_VALUE)
}
@Test fun longMinMaxValues() {
assertEquals(java.lang.Long.MIN_VALUE, Long.MIN_VALUE)
assertEquals(java.lang.Long.MAX_VALUE, Long.MAX_VALUE)
}
@Test fun shortMinMaxValues() {
assertEquals(java.lang.Short.MIN_VALUE, Short.MIN_VALUE)
assertEquals(java.lang.Short.MAX_VALUE, Short.MAX_VALUE)
}
@Test fun byteMinMaxValues() {
assertEquals(java.lang.Byte.MIN_VALUE, Byte.MIN_VALUE)
assertEquals(java.lang.Byte.MAX_VALUE, Byte.MAX_VALUE)
}
@Test fun doubleMinMaxValues() {
assertEquals(java.lang.Double.MIN_VALUE, Double.MIN_VALUE)
assertEquals(java.lang.Double.MAX_VALUE, Double.MAX_VALUE)
assertEquals(java.lang.Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)
assertEquals(java.lang.Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY)
}
@Test fun floatMinMaxValues() {
assertEquals(java.lang.Float.MIN_VALUE, Float.MIN_VALUE)
assertEquals(java.lang.Float.MAX_VALUE, Float.MAX_VALUE)
assertEquals(java.lang.Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)
assertEquals(java.lang.Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY)
}
@Test fun floatToBits() {
val PI_F = kotlin.math.PI.toFloat()
assertEquals(0x40490fdb, PI_F.toBits())
assertEquals(PI_F, Float.fromBits(0x40490fdb))
for (value in listOf(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE, -1.0F, -Float.MIN_VALUE, -0.0F, 0.0F, Float.POSITIVE_INFINITY, Float.MAX_VALUE, 1.0F, Float.MIN_VALUE)) {
assertEquals(value, Float.fromBits(value.toBits()))
assertEquals(value, Float.fromBits(value.toRawBits()))
}
assertTrue(Float.NaN.toBits().let(Float.Companion::fromBits).isNaN())
assertTrue(Float.NaN.toRawBits().let { Float.fromBits(it) }.isNaN())
}
}
@@ -1,28 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:JvmVersion
package test.properties.delegation.lazy
import kotlin.test.*
import kotlin.jvm.Volatile
class SynchronizedLazyValTest {
@Volatile
var result = 0
val a by lazy(this) {
++result
}
@Test fun doTest() {
synchronized(this) {
kotlin.concurrent.thread { a } // not available in js
result = 1
a
}
assertTrue(a == 2, "fail: initializer should be invoked only once")
assertTrue(result == 2, "fail result should be incremented after test")
}
}
@@ -1,109 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.ranges
import java.lang.Integer.MAX_VALUE as MaxI
import java.lang.Integer.MIN_VALUE as MinI
import java.lang.Byte.MAX_VALUE as MaxB
import java.lang.Byte.MIN_VALUE as MinB
import java.lang.Short.MAX_VALUE as MaxS
import java.lang.Short.MIN_VALUE as MinS
import java.lang.Long.MAX_VALUE as MaxL
import java.lang.Long.MIN_VALUE as MinL
import java.lang.Character.MAX_VALUE as MaxC
import java.lang.Character.MIN_VALUE as MinC
import kotlin.test.*
// Test data for codegen is generated from this class. If you change it, rerun GenerateTests
public class RangeIterationJVMTest : RangeIterationTestBase() {
@Test fun maxValueToMaxValue() {
doTest(MaxI..MaxI, MaxI, MaxI, 1, listOf(MaxI))
doTest(MaxB..MaxB, MaxB.toInt(), MaxB.toInt(), 1, listOf(MaxB.toInt()))
doTest(MaxS..MaxS, MaxS.toInt(), MaxS.toInt(), 1, listOf(MaxS.toInt()))
doTest(MaxL..MaxL, MaxL, MaxL, 1.toLong(), listOf(MaxL))
doTest(MaxC..MaxC, MaxC, MaxC, 1, listOf(MaxC))
}
@Test fun maxValueMinusTwoToMaxValue() {
doTest((MaxI - 2)..MaxI, MaxI - 2, MaxI, 1, listOf(MaxI - 2, MaxI - 1, MaxI))
doTest((MaxB - 2).toByte()..MaxB, (MaxB - 2).toInt(), MaxB.toInt(), 1, listOf((MaxB - 2).toInt(), (MaxB - 1).toInt(), MaxB.toInt()))
doTest((MaxS - 2).toShort()..MaxS, (MaxS - 2).toInt(), MaxS.toInt(), 1, listOf((MaxS - 2).toInt(), (MaxS - 1).toInt(), MaxS.toInt()))
doTest((MaxL - 2).toLong()..MaxL, (MaxL - 2).toLong(), MaxL, 1.toLong(), listOf((MaxL - 2).toLong(), (MaxL - 1).toLong(), MaxL))
doTest((MaxC - 2)..MaxC, (MaxC - 2), MaxC, 1, listOf((MaxC - 2), (MaxC - 1), MaxC))
}
@Test fun maxValueToMinValue() {
doTest(MaxI..MinI, MaxI, MinI, 1, listOf())
doTest(MaxB..MinB, MaxB.toInt(), MinB.toInt(), 1, listOf())
doTest(MaxS..MinS, MaxS.toInt(), MinS.toInt(), 1, listOf())
doTest(MaxL..MinL, MaxL, MinL, 1.toLong(), listOf())
doTest(MaxC..MinC, MaxC, MinC, 1, listOf())
}
@Test fun progressionMaxValueToMaxValue() {
doTest(MaxI..MaxI step 1, MaxI, MaxI, 1, listOf(MaxI))
doTest(MaxB..MaxB step 1, MaxB.toInt(), MaxB.toInt(), 1, listOf(MaxB.toInt()))
doTest(MaxS..MaxS step 1, MaxS.toInt(), MaxS.toInt(), 1, listOf(MaxS.toInt()))
doTest(MaxL..MaxL step 1, MaxL, MaxL, 1.toLong(), listOf(MaxL))
doTest(MaxC..MaxC step 1, MaxC, MaxC, 1, listOf(MaxC))
}
@Test fun progressionMaxValueMinusTwoToMaxValue() {
doTest((MaxI - 2)..MaxI step 2, MaxI - 2, MaxI, 2, listOf(MaxI - 2, MaxI))
doTest((MaxB - 2).toByte()..MaxB step 2, (MaxB - 2).toInt(), MaxB.toInt(), 2, listOf((MaxB - 2).toInt(), MaxB.toInt()))
doTest((MaxS - 2).toShort()..MaxS step 2, (MaxS - 2).toInt(), MaxS.toInt(), 2, listOf((MaxS - 2).toInt(), MaxS.toInt()))
doTest((MaxL - 2).toLong()..MaxL step 2, (MaxL - 2).toLong(), MaxL, 2.toLong(), listOf((MaxL - 2).toLong(), MaxL))
doTest((MaxC - 2)..MaxC step 2, (MaxC - 2), MaxC, 2, listOf((MaxC - 2), MaxC))
}
@Test fun progressionMaxValueToMinValue() {
doTest(MaxI..MinI step 1, MaxI, MinI, 1, listOf())
doTest(MaxB..MinB step 1, MaxB.toInt(), MinB.toInt(), 1, listOf())
doTest(MaxS..MinS step 1, MaxS.toInt(), MinS.toInt(), 1, listOf())
doTest(MaxL..MinL step 1, MaxL, MinL, 1.toLong(), listOf())
doTest(MaxC..MinC step 1, MaxC, MinC, 1, listOf())
}
@Test fun progressionMinValueToMinValue() {
doTest(MinI..MinI step 1, MinI, MinI, 1, listOf(MinI))
doTest(MinB..MinB step 1, MinB.toInt(), MinB.toInt(), 1, listOf(MinB.toInt()))
doTest(MinS..MinS step 1, MinS.toInt(), MinS.toInt(), 1, listOf(MinS.toInt()))
doTest(MinL..MinL step 1, MinL, MinL, 1.toLong(), listOf(MinL))
doTest(MinC..MinC step 1, MinC, MinC, 1, listOf(MinC))
}
@Test fun inexactToMaxValue() {
doTest((MaxI - 5)..MaxI step 3, MaxI - 5, MaxI - 2, 3, listOf(MaxI - 5, MaxI - 2))
doTest((MaxB - 5).toByte()..MaxB step 3, (MaxB - 5).toInt(), (MaxB - 2).toInt(), 3, listOf((MaxB - 5).toInt(), (MaxB - 2).toInt()))
doTest((MaxS - 5).toShort()..MaxS step 3, (MaxS - 5).toInt(), (MaxS - 2).toInt(), 3, listOf((MaxS - 5).toInt(), (MaxS - 2).toInt()))
doTest((MaxL - 5).toLong()..MaxL step 3, (MaxL - 5).toLong(), (MaxL - 2).toLong(), 3.toLong(), listOf((MaxL - 5).toLong(), (MaxL - 2).toLong()))
doTest((MaxC - 5)..MaxC step 3, (MaxC - 5), (MaxC - 2), 3, listOf((MaxC - 5), (MaxC - 2)))
}
@Test fun progressionDownToMinValue() {
doTest((MinI + 2) downTo MinI step 1, MinI + 2, MinI, -1, listOf(MinI + 2, MinI + 1, MinI))
doTest((MinB + 2).toByte() downTo MinB step 1, (MinB + 2).toInt(), MinB.toInt(), -1, listOf((MinB + 2).toInt(), (MinB + 1).toInt(), MinB.toInt()))
doTest((MinS + 2).toShort() downTo MinS step 1, (MinS + 2).toInt(), MinS.toInt(), -1, listOf((MinS + 2).toInt(), (MinS + 1).toInt(), MinS.toInt()))
doTest((MinL + 2).toLong() downTo MinL step 1, (MinL + 2).toLong(), MinL, -1.toLong(), listOf((MinL + 2).toLong(), (MinL + 1).toLong(), MinL))
doTest((MinC + 2) downTo MinC step 1, (MinC + 2), MinC, -1, listOf((MinC + 2), (MinC + 1), MinC))
}
@Test fun inexactDownToMinValue() {
doTest((MinI + 5) downTo MinI step 3, MinI + 5, MinI + 2, -3, listOf(MinI + 5, MinI + 2))
doTest((MinB + 5).toByte() downTo MinB step 3, (MinB + 5).toInt(), (MinB + 2).toInt(), -3, listOf((MinB + 5).toInt(), (MinB + 2).toInt()))
doTest((MinS + 5).toShort() downTo MinS step 3, (MinS + 5).toInt(), (MinS + 2).toInt(), -3, listOf((MinS + 5).toInt(), (MinS + 2).toInt()))
doTest((MinL + 5).toLong() downTo MinL step 3, (MinL + 5).toLong(), (MinL + 2).toLong(), -3.toLong(), listOf((MinL + 5).toLong(), (MinL + 2).toLong()))
doTest((MinC + 5) downTo MinC step 3, (MinC + 5), (MinC + 2), -3, listOf((MinC + 5), (MinC + 2)))
}
}
@@ -1,23 +0,0 @@
@file:kotlin.jvm.JvmVersion
@file:Suppress("DEPRECATION", "DEPRECATED_JAVA_ANNOTATION")
package test.reflection
import kotlin.test.*
@Retention(AnnotationRetention.RUNTIME)
annotation class MyAnno
@MyAnno
@java.lang.Deprecated
class AnnotatedClass
class AnnotationTest {
@Test fun annotationType() {
val kAnnotations = AnnotatedClass::class.java.annotations.map { it!!.annotationClass }
val jAnnotations = AnnotatedClass::class.java.annotations.map { it!!.annotationClass.java }
assertTrue(kAnnotations.containsAll(listOf(MyAnno::class, java.lang.Deprecated::class)))
assertTrue(jAnnotations.containsAll(listOf(MyAnno::class.java, java.lang.Deprecated::class.java)))
}
}
-37
View File
@@ -1,37 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test
import kotlin.test.assertEquals
@JvmVersion
public actual fun assertTypeEquals(expected: Any?, actual: Any?) {
assertEquals(expected?.javaClass, actual?.javaClass)
}
@JvmVersion
public actual fun randomInt(limit: Int): Int = (Math.random() * limit).toInt()
@kotlin.jvm.JvmVersion
private val isJava6 = System.getProperty("java.version").startsWith("1.6.")
@kotlin.jvm.JvmVersion
internal actual fun String.removeLeadingPlusOnJava6(): String =
if (isJava6) removePrefix("+") else this
@kotlin.jvm.JvmVersion
internal actual fun doubleTotalOrderEquals(a: Double?, b: Double?) = (a as Any?) == b
-17
View File
@@ -1,17 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.text
import kotlin.test.*
class CharJVMTest {
@Test fun getCategory() {
assertEquals(CharCategory.DECIMAL_DIGIT_NUMBER, '7'.category)
assertEquals(CharCategory.CURRENCY_SYMBOL, '$'.category)
assertEquals(CharCategory.LOWERCASE_LETTER, 'a'.category)
assertEquals(CharCategory.UPPERCASE_LETTER, 'Õ'.category)
assertTrue(',' in CharCategory.OTHER_PUNCTUATION)
}
}
@@ -1,72 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:kotlin.jvm.JvmVersion
package test.text
import kotlin.test.*
import test.collections.compare
import test.io.*
import java.util.regex.Pattern
class RegexJVMTest {
@Test fun matchGroups() {
val input = "1a 2b 3c"
val regex = "(\\d)(\\w)".toRegex()
val matches = regex.findAll(input).toList()
assertTrue(matches.all { it.groups.size == 3 })
val m1 = matches[0]
assertEquals("1a", m1.groups[0]?.value)
assertEquals(0..1, m1.groups[0]?.range)
assertEquals("1", m1.groups[1]?.value)
assertEquals(0..0, m1.groups[1]?.range)
assertEquals("a", m1.groups[2]?.value)
assertEquals(1..1, m1.groups[2]?.range)
val m2 = matches[1]
assertEquals("2", m2.groups[1]?.value)
assertEquals(3..3, m2.groups[1]?.range)
assertEquals("b", m2.groups[2]?.value)
assertEquals(4..4, m2.groups[2]?.range)
}
private fun compareRegex(expected: Regex, actual: Regex) = compare(expected, actual) {
propertyEquals(Regex::pattern)
propertyEquals(Regex::options)
propertyEquals("flags") { toPattern().flags() }
}
private fun equivalentAfterDeserialization(regex: Regex) = compareRegex(regex, serializeAndDeserialize(regex))
@Test fun serializeDeserializeRegex() {
equivalentAfterDeserialization(Regex(""))
equivalentAfterDeserialization(Regex("\\w+"))
equivalentAfterDeserialization(Regex("\\w+", RegexOption.IGNORE_CASE))
equivalentAfterDeserialization(Regex("\\w+", setOf(RegexOption.LITERAL, RegexOption.MULTILINE)))
equivalentAfterDeserialization(Pattern.compile("\\w+", Pattern.UNICODE_CASE).toRegex())
}
@Test fun deserializeRegexFromHex() {
val expected = Regex("\\w+", RegexOption.IGNORE_CASE)
// println(serializeToHex(expected))
val deserialized = deserializeFromHex<Regex>("ac ed 00 05 73 72 00 1c 6b 6f 74 6c 69 6e 2e 74 65 78 74 2e 52 65 67 65 78 24 53 65 72 69 61 6c 69 7a 65 64 00 00 00 00 00 00 00 00 02 00 02 49 00 05 66 6c 61 67 73 4c 00 07 70 61 74 74 65 72 6e 74 00 12 4c 6a 61 76 61 2f 6c 61 6e 67 2f 53 74 72 69 6e 67 3b 78 70 00 00 00 42 74 00 03 5c 77 2b")
compareRegex(expected, deserialized)
}
}
@@ -1,22 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.text
import kotlin.test.*
class StringBuilderJVMTest() {
@Test fun stringBuildWithInitialCapacity() {
val s = buildString(123) {
assertEquals(123, capacity())
}
assertEquals("", s)
}
@Test fun getAndSetChar() {
val sb = StringBuilder("abc")
sb[1] = 'z'
assertEquals("azc", sb.toString())
assertEquals('c', sb[2])
}
}
@@ -1,71 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.text
import test.collections.assertArrayNotSameButEquals
import java.util.*
import kotlin.test.*
class StringJVMTest {
@Test fun testSplitByPattern() = withOneCharSequenceArg("ab1cd2def3") { s ->
val isDigit = "\\d".toRegex()
assertEquals(listOf("ab", "cd", "def", ""), s.split(isDigit))
assertEquals(listOf("ab", "cd", "def3"), s.split(isDigit, 3))
// deprecation replacement equivalence
assertEquals("\\d".toPattern().split(s).toList(), s.split("\\d".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().toList())
assertFails {
s.split(isDigit, -1)
}
}
@Test fun sliceCharSequenceFails() = withOneCharSequenceArg { arg1 ->
assertFails {
arg1("abc").slice(1..4)
}
assertFails {
arg1("ABCDabcd").slice(listOf(10))
}
}
@Test fun formatter() {
assertEquals("12", "%d%d".format(1, 2))
assertEquals("12", String.format("%d%d", 1, 2))
assertEquals("1,234,567.890", "%,.3f".format(Locale.ENGLISH, 1234567.890))
assertEquals("1.234.567,890", "%,.3f".format(Locale.GERMAN, 1234567.890))
assertEquals("1 234 567,890", "%,.3f".format(Locale("fr"), 1234567.890))
assertEquals("1,234,567.890", String.format(Locale.ENGLISH, "%,.3f", 1234567.890))
assertEquals("1.234.567,890", String.format(Locale.GERMAN, "%,.3f", 1234567.890))
assertEquals("1 234 567,890", String.format(Locale("fr"), "%,.3f", 1234567.890))
}
@Test fun toByteArrayEncodings() {
val s = "hello®"
assertEquals(String(s.toByteArray()), String(s.toByteArray(Charsets.UTF_8)))
}
@Test fun toCharArray() {
val s = "hello"
val chars = s.toCharArray()
assertArrayNotSameButEquals(charArrayOf('h', 'e', 'l', 'l', 'o'), chars)
val buffer = CharArray(4)
s.toCharArray(buffer, 2, 1, 3)
assertArrayNotSameButEquals(charArrayOf('\u0000', '\u0000', 'e', 'l'), buffer)
}
@Test fun orderIgnoringCase() {
val list = listOf("Beast", "Ast", "asterisk")
assertEquals(listOf("Ast", "Beast", "asterisk"), list.sorted())
assertEquals(listOf("Ast", "asterisk", "Beast"), list.sortedWith(String.CASE_INSENSITIVE_ORDER))
}
@Test fun charsets() {
assertEquals("UTF-32", Charsets.UTF_32.name())
assertEquals("UTF-32LE", Charsets.UTF_32LE.name())
assertEquals("UTF-32BE", Charsets.UTF_32BE.name())
}
}
@@ -1,153 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:JvmVersion
package test.text
import test.*
import kotlin.test.*
class StringNumberConversionJVMTest {
@JvmVersion
@Test fun toIntArabicDigits() {
compareConversion({ it.toInt() }, { it.toIntOrNull() }) {
assertProduces("٢٣١٩٦٠", 231960)
}
}
@JvmVersion
@Test fun toLongArabicDigits() {
compareConversion({ it.toLong() }, { it.toLongOrNull() }) {
assertProduces("٢٣١٩٦٠٧٧٨٤٥٩", 231960778459)
}
}
@kotlin.jvm.JvmVersion
@Test fun toFloat() {
compareConversion(String::toFloat, String::toFloatOrNull) {
assertProduces("77.0", 77.0f)
assertProduces("-1e39", Float.NEGATIVE_INFINITY)
assertProduces("1000000000000000000000000000000000000000", Float.POSITIVE_INFINITY)
assertFailsOrNull("dark side")
assertFailsOrNull("")
assertFailsOrNull(" ")
}
}
@kotlin.jvm.JvmVersion
@Test fun toHexDouble() {
compareConversion(String::toDouble, String::toDoubleOrNull, ::doubleTotalOrderEquals) {
assertProduces("0x77p1", (0x77 shl 1).toDouble())
assertProduces("0x.77P8", 0x77.toDouble())
assertFailsOrNull("0x77e1")
}
}
@kotlin.jvm.JvmVersion
@Test fun byteToStringWithRadix() {
assertEquals("7a", 0x7a.toByte().toString(16))
assertEquals("-80", Byte.MIN_VALUE.toString(radix = 16))
assertEquals("3v", Byte.MAX_VALUE.toString(radix = 32))
assertEquals("-40", Byte.MIN_VALUE.toString(radix = 32))
assertFailsWith<IllegalArgumentException>("Expected to fail with radix 37") { 37.toByte().toString(radix = 37) }
assertFailsWith<IllegalArgumentException>("Expected to fail with radix 1") { 1.toByte().toString(radix = 1) }
}
@kotlin.jvm.JvmVersion
@Test fun shortToStringWithRadix() {
assertEquals("7FFF", 0x7FFF.toShort().toString(radix = 16).toUpperCase())
assertEquals("-8000", (-0x8000).toShort().toString(radix = 16))
assertEquals("-sfs", (-29180).toShort().toString(radix = 32))
assertFailsWith<IllegalArgumentException>("Expected to fail with radix 37") { 37.toShort().toString(radix = 37) }
assertFailsWith<IllegalArgumentException>("Expected to fail with radix 1") { 1.toShort().toString(radix = 1) }
}
@kotlin.jvm.JvmVersion
@Test fun intToStringWithRadix() {
assertEquals("-ff", (-255).toString(radix = 16))
assertEquals("1100110", 102.toString(radix = 2))
assertEquals("kona", 411787.toString(radix = 27))
assertFailsWith<IllegalArgumentException>("Expected to fail with radix 37") { 37.toString(radix = 37) }
assertFailsWith<IllegalArgumentException>("Expected to fail with radix 1") { 1.toString(radix = 1) }
}
@kotlin.jvm.JvmVersion
@Test fun longToStringWithRadix() {
assertEquals("7f11223344556677", 0x7F11223344556677.toString(radix = 16))
assertEquals("hazelnut", 1356099454469L.toString(radix = 36))
assertEquals("-8000000000000000", Long.MIN_VALUE.toString(radix = 16))
assertFailsWith<IllegalArgumentException>("Expected to fail with radix 37") { 37L.toString(radix = 37) }
assertFailsWith<IllegalArgumentException>("Expected to fail with radix 1") { 1L.toString(radix = 1) }
}
@kotlin.jvm.JvmVersion
@Test fun toBigInteger() {
compareConversion(String::toBigInteger, String::toBigIntegerOrNull) {
assertProduces("0", java.math.BigInteger.ZERO)
assertProduces("1", java.math.BigInteger.ONE)
assertProduces("-1", java.math.BigInteger.ONE.negate())
assertProduces("100000000000000000000", java.math.BigInteger("100000000000000000000"))
assertFailsOrNull("")
assertFailsOrNull("-")
assertFailsOrNull("a")
assertFailsOrNull("-x")
assertFailsOrNull("1000 000")
}
compareConversionWithRadix(String::toBigInteger, String::toBigIntegerOrNull) {
assertProduces(16, "ABCDEF90ABCDEF9012345678", java.math.BigInteger("ABCDEF90ABCDEF9012345678", 16))
assertProduces(36, "HazelnutHazelnut", java.math.BigInteger.valueOf(1356099454469L).let { it.multiply(java.math.BigInteger.valueOf(36).pow(8)).add(it) })
assertFailsOrNull(16, "EFG")
assertFailsOrNull(10, "-1A")
assertFailsOrNull(2, "-")
assertFailsOrNull(3, "")
assertFailsWith<IllegalArgumentException>("Expected to fail with radix 37") { "37".toBigInteger(radix = 37) }
assertFailsWith<IllegalArgumentException>("Expected to fail with radix 1") { "1".toBigIntegerOrNull(radix = 1) }
}
}
@kotlin.jvm.JvmVersion
@Test fun toBigDecimal() {
fun bd(value: String) = java.math.BigDecimal(value)
compareConversion(String::toBigDecimal, String::toBigDecimalOrNull) {
assertProduces("-77", bd("-77"))
assertProduces("-77.0", bd("-77.0"))
assertProduces("77.", bd("77"))
assertProduces("123456789012345678901234567890.123456789", bd("123456789012345678901234567890.123456789"))
assertProduces("-1.77", bd("-1.77"))
assertProduces("+.77", bd("0.77"))
assertProduces("7.7e1", bd("77"))
assertProduces("+770e-1", bd("77.0"))
assertFailsOrNull("7..7")
assertFailsOrNull("\t-77 \n")
assertFailsOrNull("007 not a number")
assertFailsOrNull("")
assertFailsOrNull(" ")
}
var mc = java.math.MathContext(3, java.math.RoundingMode.UP)
compareConversion( { it.toBigDecimal(mc) }, { it.toBigDecimalOrNull(mc) }) {
assertProduces("1.991", bd("2.00"))
mc = java.math.MathContext(1, java.math.RoundingMode.UNNECESSARY)
assertFailsWith<ArithmeticException> { "2.991".toBigDecimal(mc) }
assertFailsWith<ArithmeticException> { "2.991".toBigDecimalOrNull(mc) }
}
}
}
@@ -1,37 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:JvmVersion
package test.utils
import kotlin.test.*
class AssertionsJVMTest() {
@Test fun passingAssert() {
assert(true)
var called = false
assert(true) { called = true; "some message" }
assertFalse(called)
}
@Test fun failingAssert() {
val error = assertFailsWith<AssertionError> {
assert(false)
}
assertEquals("Assertion failed", error.message)
}
@Test fun failingAssertWithMessage() {
val error = assertFailsWith<AssertionError> {
assert(false) { "Hello" }
}
assertEquals("Hello", error.message)
}
}
-170
View File
@@ -1,170 +0,0 @@
@file:kotlin.jvm.JvmVersion
package test.utils
import kotlin.*
import kotlin.test.*
import kotlin.concurrent.thread
import test.io.serializeAndDeserialize
import java.util.*
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CyclicBarrier
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
class LazyJVMTest {
@Test fun synchronizedLazy() {
val counter = AtomicInteger(0)
val lazy = lazy {
val value = counter.incrementAndGet()
Thread.sleep(16)
value
}
val threads = 3
val barrier = CyclicBarrier(threads)
val accessThreads = List(threads) { thread { barrier.await(); lazy.value } }
accessThreads.forEach { it.join() }
assertEquals(1, counter.get())
}
@Test fun synchronizedLazyRace() {
racyTest(initialize = {
val counter = AtomicInteger(0)
lazy { counter.incrementAndGet() }
},
access = { lazy, _ -> lazy.value },
validate = { result -> result.all { it == 1 } }
)
}
@Test fun externallySynchronizedLazy() {
val counter = AtomicInteger(0)
var initialized: Boolean = false
val runs = ConcurrentHashMap<Int, Boolean>()
val lock = Any()
val initializer = {
val value = counter.incrementAndGet()
runs += (value to initialized)
Thread.sleep(16)
initialized = true
value
}
val lazy1 = lazy(lock, initializer)
val lazy2 = lazy(lock, initializer)
val accessThreads = listOf(lazy1, lazy2).map { thread { it.value } }
accessThreads.forEach { it.join() }
assertEquals(2, counter.get())
@Suppress("NAME_SHADOWING")
for ((counter, initialized) in runs) {
assertEquals(initialized, counter == 2, "Expected uninitialized on first, initialized on second call: initialized=$initialized, counter=$counter")
}
}
@Test fun externallySynchronizedLazyRace() {
val threads = 3
racyTest(threads,
initialize = {
val counter = AtomicInteger(0)
var initialized = false
val initializer = {
(counter.incrementAndGet() to initialized).also {
initialized = true
}
}
val lock = Any()
List(threads) { lazy(lock, initializer) }
},
access = { lazies, runnerIndex -> lazies[runnerIndex].value },
validate = { result -> result.all { (id, initialized) -> initialized == (id != 1)} })
}
@Test fun publishOnceLazy() {
val counter = AtomicInteger(0)
val initialized = AtomicBoolean(false)
val threads = 3
val values = Random().let { r -> List(threads) { 50 + r.nextInt(50) } }
data class Run(val value: Int, val initialized: Boolean)
val runs = ConcurrentLinkedQueue<Run>()
val initializer = {
val id = counter.getAndIncrement()
val value = values[id]
runs += Run(value, initialized.get())
Thread.sleep(value.toLong())
initialized.set(true)
value
}
val lazy = lazy(LazyThreadSafetyMode.PUBLICATION, initializer)
val barrier = CyclicBarrier(threads)
val accessThreads = List(threads) { thread { barrier.await(); lazy.value } }
val result = run { while (!lazy.isInitialized()) /* wait */; lazy.value }
accessThreads.forEach { it.join() }
assertEquals(threads, counter.get())
assertEquals(result, lazy.value, "Value must not change after isInitialized is set: $lazy, runs: $runs")
runs.forEach {
assertFalse(it.initialized, "Expected uninitialized on all initializer executions, runs: $runs")
}
}
@Test fun publishOnceLazyRace() {
racyTest(initialize = { lazy(LazyThreadSafetyMode.PUBLICATION) { Thread.currentThread().id } },
access = { lazy, _ -> lazy.value },
validate = { result -> result.all { v -> v == result[0] } } )
}
@Test fun lazyInitializationForcedOnSerialization() {
for(mode in listOf(LazyThreadSafetyMode.SYNCHRONIZED, LazyThreadSafetyMode.PUBLICATION, LazyThreadSafetyMode.NONE)) {
val lazy = lazy(mode) { "initialized" }
assertFalse(lazy.isInitialized())
val lazy2 = serializeAndDeserialize(lazy)
assertTrue(lazy.isInitialized())
assertTrue(lazy2.isInitialized())
assertEquals(lazy.value, lazy2.value)
}
}
private fun <TState : Any, TResult> racyTest(
threads: Int = 3, runs: Int = 5000,
initialize: () -> TState,
access: (TState, runnerIndex: Int) -> TResult,
validate: (List<TResult>) -> Boolean) {
val runResult = java.util.Collections.synchronizedList(mutableListOf<TResult>())
val invalidResults = mutableListOf<Pair<Int, List<TResult>>>()
lateinit var state: TState
var runId = -1
val barrier = CyclicBarrier(threads) {
if (runId >= 0) {
if (!validate(runResult))
invalidResults.add(runId to runResult.toList())
runResult.clear()
}
state = initialize()
runId += 1
}
val runners = List(threads) { index -> thread {
barrier.await()
repeat(runs) {
runResult += access(state, index)
barrier.await()
}
}}
runners.forEach { it.join() }
assertTrue(invalidResults.isEmpty(), invalidResults.joinToString("\n") { (index, result) -> "At run #$index: $result" })
}
}