Minor: normalize '@Test' annotation casing in all tests.

This commit is contained in:
Ilya Gorbunov
2016-11-16 21:26:39 +03:00
parent 50cd620f92
commit 6a70761783
48 changed files with 749 additions and 751 deletions
@@ -40,7 +40,7 @@ public class GenerateRangesCodegenTestData {
new File("libraries/stdlib/test/ranges/RangeIterationJVMTest.kt") new File("libraries/stdlib/test/ranges/RangeIterationJVMTest.kt")
}; };
private static final Pattern TEST_FUN_PATTERN = Pattern.compile("test fun (\\w+)\\(\\) \\{.+?}", Pattern.DOTALL); private static final Pattern TEST_FUN_PATTERN = Pattern.compile("@Test fun (\\w+)\\(\\) \\{.+?}", Pattern.DOTALL);
private static final Pattern SUBTEST_INVOCATION_PATTERN = Pattern.compile("doTest\\(([^,]+), [^,]+, [^,]+, [^,]+,\\s+listOf[\\w<>]*\\(([^\\n]*)\\)\\)", Pattern.DOTALL); private static final Pattern SUBTEST_INVOCATION_PATTERN = Pattern.compile("doTest\\(([^,]+), [^,]+, [^,]+, [^,]+,\\s+listOf[\\w<>]*\\(([^\\n]*)\\)\\)", Pattern.DOTALL);
// $LIST.size() check is needed in order for tests not to run forever // $LIST.size() check is needed in order for tests not to run forever
+4 -4
View File
@@ -4,19 +4,19 @@ package test.exceptions
import kotlin.test.* import kotlin.test.*
import test.collections.assertArrayNotSameButEquals import test.collections.assertArrayNotSameButEquals
import org.junit.Test as test import org.junit.Test
import java.io.PrintWriter import java.io.PrintWriter
import java.io.* import java.io.*
import java.nio.charset.Charset import java.nio.charset.Charset
class ExceptionJVMTest { class ExceptionJVMTest {
@test fun printStackTraceOnRuntimeException() { @Test fun printStackTraceOnRuntimeException() {
assertPrintStackTrace(RuntimeException("Crikey!")) assertPrintStackTrace(RuntimeException("Crikey!"))
assertPrintStackTraceStream(RuntimeException("Crikey2")) assertPrintStackTraceStream(RuntimeException("Crikey2"))
} }
@test fun printStackTraceOnError() { @Test fun printStackTraceOnError() {
assertPrintStackTrace(Error("Oh dear")) assertPrintStackTrace(Error("Oh dear"))
assertPrintStackTraceStream(Error("Oh dear2")) assertPrintStackTraceStream(Error("Oh dear2"))
} }
@@ -55,7 +55,7 @@ class ExceptionJVMTest {
} }
} }
@test fun changeStackTrace() { @Test fun changeStackTrace() {
val exception = RuntimeException("Fail") val exception = RuntimeException("Fail")
var stackTrace = exception.stackTrace var stackTrace = exception.stackTrace
stackTrace = stackTrace.dropLast(1).toTypedArray() stackTrace = stackTrace.dropLast(1).toTypedArray()
+15 -15
View File
@@ -1,6 +1,6 @@
package test.tuples package test.tuples
import org.junit.Test as test import org.junit.Test
import kotlin.test.assertTrue import kotlin.test.assertTrue
import kotlin.test.assertEquals import kotlin.test.assertEquals
import kotlin.test.assertNotEquals import kotlin.test.assertNotEquals
@@ -8,22 +8,22 @@ import kotlin.test.assertNotEquals
class PairTest { class PairTest {
val p = Pair(1, "a") val p = Pair(1, "a")
@test fun pairFirstAndSecond() { @Test fun pairFirstAndSecond() {
assertEquals(1, p.first) assertEquals(1, p.first)
assertEquals("a", p.second) assertEquals("a", p.second)
} }
@test fun pairMultiAssignment() { @Test fun pairMultiAssignment() {
val (a, b) = p val (a, b) = p
assertEquals(1, a) assertEquals(1, a)
assertEquals("a", b) assertEquals("a", b)
} }
@test fun pairToString() { @Test fun pairToString() {
assertEquals("(1, a)", p.toString()) assertEquals("(1, a)", p.toString())
} }
@test fun pairEquals() { @Test fun pairEquals() {
assertEquals(Pair(1, "a"), p) assertEquals(Pair(1, "a"), p)
assertNotEquals(Pair(2, "a"), p) assertNotEquals(Pair(2, "a"), p)
assertNotEquals(Pair(1, "b"), p) assertNotEquals(Pair(1, "b"), p)
@@ -31,7 +31,7 @@ class PairTest {
assertNotEquals("", (p as Any)) assertNotEquals("", (p as Any))
} }
@test fun pairHashCode() { @Test fun pairHashCode() {
assertEquals(Pair(1, "a").hashCode(), p.hashCode()) assertEquals(Pair(1, "a").hashCode(), p.hashCode())
assertNotEquals(Pair(2, "a").hashCode(), p.hashCode()) assertNotEquals(Pair(2, "a").hashCode(), p.hashCode())
assertNotEquals(0, Pair(null, "b").hashCode()) assertNotEquals(0, Pair(null, "b").hashCode())
@@ -39,13 +39,13 @@ class PairTest {
assertEquals(0, Pair(null, null).hashCode()) assertEquals(0, Pair(null, null).hashCode())
} }
@test fun pairHashSet() { @Test fun pairHashSet() {
val s = hashSetOf(Pair(1, "a"), Pair(1, "b"), Pair(1, "a")) val s = hashSetOf(Pair(1, "a"), Pair(1, "b"), Pair(1, "a"))
assertEquals(2, s.size) assertEquals(2, s.size)
assertTrue(s.contains(p)) assertTrue(s.contains(p))
} }
@test fun pairToList() { @Test fun pairToList() {
assertEquals(listOf(1, 2), (1 to 2).toList()) assertEquals(listOf(1, 2), (1 to 2).toList())
assertEquals(listOf(1, null), (1 to null).toList()) assertEquals(listOf(1, null), (1 to null).toList())
assertEquals(listOf(1, "2"), (1 to "2").toList()) assertEquals(listOf(1, "2"), (1 to "2").toList())
@@ -55,24 +55,24 @@ class PairTest {
class TripleTest { class TripleTest {
val t = Triple(1, "a", 0.07) val t = Triple(1, "a", 0.07)
@test fun tripleFirstAndSecond() { @Test fun tripleFirstAndSecond() {
assertEquals(1, t.first) assertEquals(1, t.first)
assertEquals("a", t.second) assertEquals("a", t.second)
assertEquals(0.07, t.third) assertEquals(0.07, t.third)
} }
@test fun tripleMultiAssignment() { @Test fun tripleMultiAssignment() {
val (a, b, c) = t val (a, b, c) = t
assertEquals(1, a) assertEquals(1, a)
assertEquals("a", b) assertEquals("a", b)
assertEquals(0.07, c) assertEquals(0.07, c)
} }
@test fun tripleToString() { @Test fun tripleToString() {
assertEquals("(1, a, 0.07)", t.toString()) assertEquals("(1, a, 0.07)", t.toString())
} }
@test fun tripleEquals() { @Test fun tripleEquals() {
assertEquals(Triple(1, "a", 0.07), t) assertEquals(Triple(1, "a", 0.07), t)
assertNotEquals(Triple(2, "a", 0.07), t) assertNotEquals(Triple(2, "a", 0.07), t)
assertNotEquals(Triple(1, "b", 0.07), t) assertNotEquals(Triple(1, "b", 0.07), t)
@@ -81,7 +81,7 @@ class TripleTest {
assertNotEquals("", (t as Any)) assertNotEquals("", (t as Any))
} }
@test fun tripleHashCode() { @Test fun tripleHashCode() {
assertEquals(Triple(1, "a", 0.07).hashCode(), t.hashCode()) assertEquals(Triple(1, "a", 0.07).hashCode(), t.hashCode())
assertNotEquals(Triple(2, "a", 0.07).hashCode(), t.hashCode()) assertNotEquals(Triple(2, "a", 0.07).hashCode(), t.hashCode())
assertNotEquals(0, Triple(null, "b", 0.07).hashCode()) assertNotEquals(0, Triple(null, "b", 0.07).hashCode())
@@ -90,13 +90,13 @@ class TripleTest {
assertEquals(0, Triple(null, null, null).hashCode()) assertEquals(0, Triple(null, null, null).hashCode())
} }
@test fun tripleHashSet() { @Test fun tripleHashSet() {
val s = hashSetOf(Triple(1, "a", 0.07), Triple(1, "b", 0.07), Triple(1, "a", 0.07)) val s = hashSetOf(Triple(1, "a", 0.07), Triple(1, "b", 0.07), Triple(1, "a", 0.07))
assertEquals(2, s.size) assertEquals(2, s.size)
assertTrue(s.contains(t)) assertTrue(s.contains(t))
} }
@test fun tripleToList() { @Test fun tripleToList() {
assertEquals(listOf(1, 2, 3), (Triple(1, 2, 3)).toList()) assertEquals(listOf(1, 2, 3), (Triple(1, 2, 3)).toList())
assertEquals(listOf(1, null, 3), (Triple(1, null, 3)).toList()) assertEquals(listOf(1, null, 3), (Triple(1, null, 3)).toList())
assertEquals(listOf(1, 2, "3"), (Triple(1, 2, "3")).toList()) assertEquals(listOf(1, 2, "3"), (Triple(1, 2, "3")).toList())
+100 -100
View File
@@ -19,7 +19,7 @@ package test.collections
import test.collections.behaviors.listBehavior import test.collections.behaviors.listBehavior
import test.comparisons.STRING_CASE_INSENSITIVE_ORDER import test.comparisons.STRING_CASE_INSENSITIVE_ORDER
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
import kotlin.comparisons.* import kotlin.comparisons.*
fun <T> assertArrayNotSameButEquals(expected: Array<out T>, actual: Array<out T>, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) } fun <T> assertArrayNotSameButEquals(expected: Array<out T>, actual: Array<out T>, message: String = "") { assertTrue(expected !== actual && expected contentEquals actual, message) }
@@ -39,7 +39,7 @@ class ArraysTest {
override fun hashCode(): Int = value override fun hashCode(): Int = value
} }
@test fun orEmptyNull() { @Test fun orEmptyNull() {
val x: Array<String>? = null val x: Array<String>? = null
val y: Array<out String>? = null val y: Array<out String>? = null
val xArray = x.orEmpty() val xArray = x.orEmpty()
@@ -48,7 +48,7 @@ class ArraysTest {
expect(0) { yArray.size } expect(0) { yArray.size }
} }
@test fun orEmptyNotNull() { @Test fun orEmptyNotNull() {
val x: Array<String>? = arrayOf("1", "2") val x: Array<String>? = arrayOf("1", "2")
val xArray = x.orEmpty() val xArray = x.orEmpty()
expect(2) { xArray.size } expect(2) { xArray.size }
@@ -56,7 +56,7 @@ class ArraysTest {
expect("2") { xArray[1] } expect("2") { xArray[1] }
} }
@test fun emptyArrayLastIndex() { @Test fun emptyArrayLastIndex() {
val arr1 = IntArray(0) val arr1 = IntArray(0)
assertEquals(-1, arr1.lastIndex) assertEquals(-1, arr1.lastIndex)
@@ -64,7 +64,7 @@ class ArraysTest {
assertEquals(-1, arr2.lastIndex) assertEquals(-1, arr2.lastIndex)
} }
@test fun arrayLastIndex() { @Test fun arrayLastIndex() {
val arr1 = intArrayOf(0, 1, 2, 3, 4) val arr1 = intArrayOf(0, 1, 2, 3, 4)
assertEquals(4, arr1.lastIndex) assertEquals(4, arr1.lastIndex)
assertEquals(4, arr1[arr1.lastIndex]) assertEquals(4, arr1[arr1.lastIndex])
@@ -74,7 +74,7 @@ class ArraysTest {
assertEquals("4", arr2[arr2.lastIndex]) assertEquals("4", arr2[arr2.lastIndex])
} }
@test fun byteArray() { @Test fun byteArray() {
val arr = ByteArray(2) val arr = ByteArray(2)
val expected: Byte = 0 val expected: Byte = 0
@@ -83,7 +83,7 @@ class ArraysTest {
assertEquals(expected, arr[1]) assertEquals(expected, arr[1])
} }
@test fun byteArrayInit() { @Test fun byteArrayInit() {
val arr = ByteArray(2) { it.toByte() } val arr = ByteArray(2) { it.toByte() }
assertEquals(2, arr.size) assertEquals(2, arr.size)
@@ -91,7 +91,7 @@ class ArraysTest {
assertEquals(1.toByte(), arr[1]) assertEquals(1.toByte(), arr[1])
} }
@test fun shortArray() { @Test fun shortArray() {
val arr = ShortArray(2) val arr = ShortArray(2)
val expected: Short = 0 val expected: Short = 0
@@ -100,7 +100,7 @@ class ArraysTest {
assertEquals(expected, arr[1]) assertEquals(expected, arr[1])
} }
@test fun shortArrayInit() { @Test fun shortArrayInit() {
val arr = ShortArray(2) { it.toShort() } val arr = ShortArray(2) { it.toShort() }
assertEquals(2, arr.size) assertEquals(2, arr.size)
@@ -108,7 +108,7 @@ class ArraysTest {
assertEquals(1.toShort(), arr[1]) assertEquals(1.toShort(), arr[1])
} }
@test fun intArray() { @Test fun intArray() {
val arr = IntArray(2) val arr = IntArray(2)
assertEquals(arr.size, 2) assertEquals(arr.size, 2)
@@ -116,7 +116,7 @@ class ArraysTest {
assertEquals(0, arr[1]) assertEquals(0, arr[1])
} }
@test fun intArrayInit() { @Test fun intArrayInit() {
val arr = IntArray(2) { it.toInt() } val arr = IntArray(2) { it.toInt() }
assertEquals(2, arr.size) assertEquals(2, arr.size)
@@ -124,7 +124,7 @@ class ArraysTest {
assertEquals(1.toInt(), arr[1]) assertEquals(1.toInt(), arr[1])
} }
@test fun longArray() { @Test fun longArray() {
val arr = LongArray(2) val arr = LongArray(2)
val expected: Long = 0 val expected: Long = 0
@@ -133,7 +133,7 @@ class ArraysTest {
assertEquals(expected, arr[1]) assertEquals(expected, arr[1])
} }
@test fun longArrayInit() { @Test fun longArrayInit() {
val arr = LongArray(2) { it.toLong() } val arr = LongArray(2) { it.toLong() }
assertEquals(2, arr.size) assertEquals(2, arr.size)
@@ -141,7 +141,7 @@ class ArraysTest {
assertEquals(1.toLong(), arr[1]) assertEquals(1.toLong(), arr[1])
} }
@test fun floatArray() { @Test fun floatArray() {
val arr = FloatArray(2) val arr = FloatArray(2)
val expected: Float = 0.0F val expected: Float = 0.0F
@@ -150,7 +150,7 @@ class ArraysTest {
assertEquals(expected, arr[1]) assertEquals(expected, arr[1])
} }
@test fun floatArrayInit() { @Test fun floatArrayInit() {
val arr = FloatArray(2) { it.toFloat() } val arr = FloatArray(2) { it.toFloat() }
assertEquals(2, arr.size) assertEquals(2, arr.size)
@@ -158,7 +158,7 @@ class ArraysTest {
assertEquals(1.toFloat(), arr[1]) assertEquals(1.toFloat(), arr[1])
} }
@test fun doubleArray() { @Test fun doubleArray() {
val arr = DoubleArray(2) val arr = DoubleArray(2)
assertEquals(arr.size, 2) assertEquals(arr.size, 2)
@@ -166,7 +166,7 @@ class ArraysTest {
assertEquals(0.0, arr[1]) assertEquals(0.0, arr[1])
} }
@test fun doubleArrayInit() { @Test fun doubleArrayInit() {
val arr = DoubleArray(2) { it.toDouble() } val arr = DoubleArray(2) { it.toDouble() }
assertEquals(2, arr.size) assertEquals(2, arr.size)
@@ -174,7 +174,7 @@ class ArraysTest {
assertEquals(1.toDouble(), arr[1]) assertEquals(1.toDouble(), arr[1])
} }
@test fun charArray() { @Test fun charArray() {
val arr = CharArray(2) val arr = CharArray(2)
val expected: Char = '\u0000' val expected: Char = '\u0000'
@@ -183,7 +183,7 @@ class ArraysTest {
assertEquals(expected, arr[1]) assertEquals(expected, arr[1])
} }
@test fun charArrayInit() { @Test fun charArrayInit() {
val arr = CharArray(2) { 'a' + it } val arr = CharArray(2) { 'a' + it }
assertEquals(2, arr.size) assertEquals(2, arr.size)
@@ -191,14 +191,14 @@ class ArraysTest {
assertEquals('b', arr[1]) assertEquals('b', arr[1])
} }
@test fun booleanArray() { @Test fun booleanArray() {
val arr = BooleanArray(2) val arr = BooleanArray(2)
assertEquals(arr.size, 2) assertEquals(arr.size, 2)
assertEquals(false, arr[0]) assertEquals(false, arr[0])
assertEquals(false, arr[1]) assertEquals(false, arr[1])
} }
@test fun booleanArrayInit() { @Test fun booleanArrayInit() {
val arr = BooleanArray(2) { it % 2 == 0 } val arr = BooleanArray(2) { it % 2 == 0 }
assertEquals(2, arr.size) assertEquals(2, arr.size)
@@ -206,7 +206,7 @@ class ArraysTest {
assertEquals(false, arr[1]) assertEquals(false, arr[1])
} }
@test fun contentEquals() { @Test fun contentEquals() {
val arr1 = arrayOf("a", 1, null) val arr1 = arrayOf("a", 1, null)
val arr2 = arrayOf(*arr1) val arr2 = arrayOf(*arr1)
assertTrue(arr1 contentEquals arr2) assertTrue(arr1 contentEquals arr2)
@@ -214,7 +214,7 @@ class ArraysTest {
assertFalse(arr1 contentEquals arr3) assertFalse(arr1 contentEquals arr3)
} }
@test fun contentDeepEquals() { @Test fun contentDeepEquals() {
val arr1 = arrayOf("a", 1, intArrayOf(2)) val arr1 = arrayOf("a", 1, intArrayOf(2))
val arr2 = arrayOf("a", 1, intArrayOf(2)) val arr2 = arrayOf("a", 1, intArrayOf(2))
assertFalse(arr1 contentEquals arr2) assertFalse(arr1 contentEquals arr2)
@@ -223,17 +223,17 @@ class ArraysTest {
assertFalse(arr1 contentDeepEquals arr2) assertFalse(arr1 contentDeepEquals arr2)
} }
@test fun contentToString() { @Test fun contentToString() {
val arr = arrayOf("a", 1, null) val arr = arrayOf("a", 1, null)
assertEquals(arr.asList().toString(), arr.contentToString()) assertEquals(arr.asList().toString(), arr.contentToString())
} }
@test fun contentDeepToString() { @Test fun contentDeepToString() {
val arr = arrayOf("aa", 1, null, charArrayOf('d')) val arr = arrayOf("aa", 1, null, charArrayOf('d'))
assertEquals("[aa, 1, null, [d]]", arr.contentDeepToString()) assertEquals("[aa, 1, null, [d]]", arr.contentDeepToString())
} }
@test fun contentDeepToStringNoRecursion() { @Test fun contentDeepToStringNoRecursion() {
// a[b[a, b]] // a[b[a, b]]
val b = arrayOfNulls<Any>(2) val b = arrayOfNulls<Any>(2)
val a = arrayOf(b) val a = arrayOf(b)
@@ -247,19 +247,19 @@ class ArraysTest {
assertEquals("[[[...], [...]]]", result) assertEquals("[[[...], [...]]]", result)
} }
@test fun contentHashCode() { @Test fun contentHashCode() {
val arr = arrayOf("a", 1, null, Value(5)) val arr = arrayOf("a", 1, null, Value(5))
assertEquals(listOf(*arr).hashCode(), arr.contentHashCode()) assertEquals(listOf(*arr).hashCode(), arr.contentHashCode())
assertEquals((1*31 + 2)*31 + 3, arrayOf(Value(2), Value(3)).contentHashCode()) assertEquals((1*31 + 2)*31 + 3, arrayOf(Value(2), Value(3)).contentHashCode())
} }
@test fun contentDeepHashCode() { @Test fun contentDeepHashCode() {
val arr = arrayOf(null, Value(2), arrayOf(Value(3))) val arr = arrayOf(null, Value(2), arrayOf(Value(3)))
assertEquals(((1*31 + 0)*31 + 2) * 31 + (1 * 31 + 3), arr.contentDeepHashCode()) assertEquals(((1*31 + 0)*31 + 2) * 31 + (1 * 31 + 3), arr.contentDeepHashCode())
} }
@test fun min() { @Test fun min() {
expect(null, { arrayOf<Int>().min() }) expect(null, { arrayOf<Int>().min() })
expect(1, { arrayOf(1).min() }) expect(1, { arrayOf(1).min() })
expect(2, { arrayOf(2, 3).min() }) expect(2, { arrayOf(2, 3).min() })
@@ -268,7 +268,7 @@ class ArraysTest {
expect("a", { arrayOf("a", "b").min() }) expect("a", { arrayOf("a", "b").min() })
} }
@test fun minInPrimitiveArrays() { @Test fun minInPrimitiveArrays() {
expect(null, { intArrayOf().min() }) expect(null, { intArrayOf().min() })
expect(1, { intArrayOf(1).min() }) expect(1, { intArrayOf(1).min() })
expect(2, { intArrayOf(2, 3).min() }) expect(2, { intArrayOf(2, 3).min() })
@@ -280,7 +280,7 @@ class ArraysTest {
expect('a', { charArrayOf('a', 'b').min() }) expect('a', { charArrayOf('a', 'b').min() })
} }
@test fun max() { @Test fun max() {
expect(null, { arrayOf<Int>().max() }) expect(null, { arrayOf<Int>().max() })
expect(1, { arrayOf(1).max() }) expect(1, { arrayOf(1).max() })
expect(3, { arrayOf(2, 3).max() }) expect(3, { arrayOf(2, 3).max() })
@@ -289,7 +289,7 @@ class ArraysTest {
expect("b", { arrayOf("a", "b").max() }) expect("b", { arrayOf("a", "b").max() })
} }
@test fun maxInPrimitiveArrays() { @Test fun maxInPrimitiveArrays() {
expect(null, { intArrayOf().max() }) expect(null, { intArrayOf().max() })
expect(1, { intArrayOf(1).max() }) expect(1, { intArrayOf(1).max() })
expect(3, { intArrayOf(2, 3).max() }) expect(3, { intArrayOf(2, 3).max() })
@@ -301,29 +301,29 @@ class ArraysTest {
expect('b', { charArrayOf('a', 'b').max() }) expect('b', { charArrayOf('a', 'b').max() })
} }
@test fun minWith() { @Test fun minWith() {
assertEquals(null, arrayOf<Int>().minWith(naturalOrder()) ) assertEquals(null, arrayOf<Int>().minWith(naturalOrder()) )
assertEquals("a", arrayOf("a", "B").minWith(STRING_CASE_INSENSITIVE_ORDER)) assertEquals("a", arrayOf("a", "B").minWith(STRING_CASE_INSENSITIVE_ORDER))
} }
@test fun minWithInPrimitiveArrays() { @Test fun minWithInPrimitiveArrays() {
expect(null, { intArrayOf().minWith(naturalOrder()) }) expect(null, { intArrayOf().minWith(naturalOrder()) })
expect(1, { intArrayOf(1).minWith(naturalOrder()) }) expect(1, { intArrayOf(1).minWith(naturalOrder()) })
expect(4, { intArrayOf(2, 3, 4).minWith(compareBy { it % 4 }) }) expect(4, { intArrayOf(2, 3, 4).minWith(compareBy { it % 4 }) })
} }
@test fun maxWith() { @Test fun maxWith() {
assertEquals(null, arrayOf<Int>().maxWith(naturalOrder()) ) assertEquals(null, arrayOf<Int>().maxWith(naturalOrder()) )
assertEquals("B", arrayOf("a", "B").maxWith(STRING_CASE_INSENSITIVE_ORDER)) assertEquals("B", arrayOf("a", "B").maxWith(STRING_CASE_INSENSITIVE_ORDER))
} }
@test fun maxWithInPrimitiveArrays() { @Test fun maxWithInPrimitiveArrays() {
expect(null, { intArrayOf().maxWith(naturalOrder()) }) expect(null, { intArrayOf().maxWith(naturalOrder()) })
expect(1, { intArrayOf(1).maxWith(naturalOrder()) }) expect(1, { intArrayOf(1).maxWith(naturalOrder()) })
expect(-4, { intArrayOf(2, 3, -4).maxWith(compareBy { it*it }) }) expect(-4, { intArrayOf(2, 3, -4).maxWith(compareBy { it*it }) })
} }
@test fun minBy() { @Test fun minBy() {
expect(null, { arrayOf<Int>().minBy { it } }) expect(null, { arrayOf<Int>().minBy { it } })
expect(1, { arrayOf(1).minBy { it } }) expect(1, { arrayOf(1).minBy { it } })
expect(3, { arrayOf(2, 3).minBy { -it } }) expect(3, { arrayOf(2, 3).minBy { -it } })
@@ -331,7 +331,7 @@ class ArraysTest {
expect("b", { arrayOf("b", "abc").minBy { it.length } }) expect("b", { arrayOf("b", "abc").minBy { it.length } })
} }
@test fun minByInPrimitiveArrays() { @Test fun minByInPrimitiveArrays() {
expect(null, { intArrayOf().minBy { it } }) expect(null, { intArrayOf().minBy { it } })
expect(1, { intArrayOf(1).minBy { it } }) expect(1, { intArrayOf(1).minBy { it } })
expect(3, { intArrayOf(2, 3).minBy { -it } }) expect(3, { intArrayOf(2, 3).minBy { -it } })
@@ -342,7 +342,7 @@ class ArraysTest {
expect(2.0, { doubleArrayOf(2.0, 3.0).minBy { Math.sqrt(it) } }) expect(2.0, { doubleArrayOf(2.0, 3.0).minBy { Math.sqrt(it) } })
} }
@test fun maxBy() { @Test fun maxBy() {
expect(null, { arrayOf<Int>().maxBy { it } }) expect(null, { arrayOf<Int>().maxBy { it } })
expect(1, { arrayOf(1).maxBy { it } }) expect(1, { arrayOf(1).maxBy { it } })
expect(2, { arrayOf(2, 3).maxBy { -it } }) expect(2, { arrayOf(2, 3).maxBy { -it } })
@@ -350,7 +350,7 @@ class ArraysTest {
expect("abc", { arrayOf("b", "abc").maxBy { it.length } }) expect("abc", { arrayOf("b", "abc").maxBy { it.length } })
} }
@test fun maxByInPrimitiveArrays() { @Test fun maxByInPrimitiveArrays() {
expect(null, { intArrayOf().maxBy { it } }) expect(null, { intArrayOf().maxBy { it } })
expect(1, { intArrayOf(1).maxBy { it } }) expect(1, { intArrayOf(1).maxBy { it } })
expect(2, { intArrayOf(2, 3).maxBy { -it } }) expect(2, { intArrayOf(2, 3).maxBy { -it } })
@@ -361,29 +361,29 @@ class ArraysTest {
expect(3.0, { doubleArrayOf(2.0, 3.0).maxBy { Math.sqrt(it) } }) expect(3.0, { doubleArrayOf(2.0, 3.0).maxBy { Math.sqrt(it) } })
} }
@test fun minIndex() { @Test fun minIndex() {
val a = intArrayOf(1, 7, 9, -42, 54, 93) val a = intArrayOf(1, 7, 9, -42, 54, 93)
expect(3, { a.indices.minBy { a[it] } }) expect(3, { a.indices.minBy { a[it] } })
} }
@test fun maxIndex() { @Test fun maxIndex() {
val a = intArrayOf(1, 7, 9, 239, 54, 93) val a = intArrayOf(1, 7, 9, 239, 54, 93)
expect(3, { a.indices.maxBy { a[it] } }) expect(3, { a.indices.maxBy { a[it] } })
} }
@test fun minByEvaluateOnce() { @Test fun minByEvaluateOnce() {
var c = 0 var c = 0
expect(1, { arrayOf(5, 4, 3, 2, 1).minBy { c++; it * it } }) expect(1, { arrayOf(5, 4, 3, 2, 1).minBy { c++; it * it } })
assertEquals(5, c) assertEquals(5, c)
} }
@test fun maxByEvaluateOnce() { @Test fun maxByEvaluateOnce() {
var c = 0 var c = 0
expect(5, { arrayOf(5, 4, 3, 2, 1).maxBy { c++; it * it } }) expect(5, { arrayOf(5, 4, 3, 2, 1).maxBy { c++; it * it } })
assertEquals(5, c) assertEquals(5, c)
} }
@test fun sum() { @Test fun sum() {
expect(0) { arrayOf<Int>().sum() } expect(0) { arrayOf<Int>().sum() }
expect(14) { arrayOf(2, 3, 9).sum() } expect(14) { arrayOf(2, 3, 9).sum() }
expect(3.0) { arrayOf(1.0, 2.0).sum() } expect(3.0) { arrayOf(1.0, 2.0).sum() }
@@ -393,7 +393,7 @@ class ArraysTest {
expect(3.0F) { arrayOf<Float>(1.0F, 2.0F).sum() } expect(3.0F) { arrayOf<Float>(1.0F, 2.0F).sum() }
} }
@test fun sumInPrimitiveArrays() { @Test fun sumInPrimitiveArrays() {
expect(0) { intArrayOf().sum() } expect(0) { intArrayOf().sum() }
expect(14) { intArrayOf(2, 3, 9).sum() } expect(14) { intArrayOf(2, 3, 9).sum() }
expect(3.0) { doubleArrayOf(1.0, 2.0).sum() } expect(3.0) { doubleArrayOf(1.0, 2.0).sum() }
@@ -403,7 +403,7 @@ class ArraysTest {
expect(3.0F) { floatArrayOf(1.0F, 2.0F).sum() } expect(3.0F) { floatArrayOf(1.0F, 2.0F).sum() }
} }
@test fun average() { @Test fun average() {
expect(0.0) { arrayOf<Int>().average() } expect(0.0) { arrayOf<Int>().average() }
expect(3.8) { arrayOf(1, 2, 5, 8, 3).average() } expect(3.8) { arrayOf(1, 2, 5, 8, 3).average() }
expect(2.1) { arrayOf(1.6, 2.6, 3.6, 0.6).average() } expect(2.1) { arrayOf(1.6, 2.6, 3.6, 0.6).average() }
@@ -414,7 +414,7 @@ class ArraysTest {
// for each arr with size > 0 arr.average() = arr.sum().toDouble() / arr.size() // for each arr with size > 0 arr.average() = arr.sum().toDouble() / arr.size()
} }
@test fun indexOfInPrimitiveArrays() { @Test fun indexOfInPrimitiveArrays() {
expect(-1) { byteArrayOf(1, 2, 3).indexOf(0) } expect(-1) { byteArrayOf(1, 2, 3).indexOf(0) }
expect(0) { byteArrayOf(1, 2, 3).indexOf(1) } expect(0) { byteArrayOf(1, 2, 3).indexOf(1) }
expect(1) { byteArrayOf(1, 2, 3).indexOf(2) } expect(1) { byteArrayOf(1, 2, 3).indexOf(2) }
@@ -455,7 +455,7 @@ class ArraysTest {
expect(-1) { booleanArrayOf(true).indexOf(false) } expect(-1) { booleanArrayOf(true).indexOf(false) }
} }
@test fun indexOf() { @Test fun indexOf() {
expect(-1) { arrayOf("cat", "dog", "bird").indexOf("mouse") } expect(-1) { arrayOf("cat", "dog", "bird").indexOf("mouse") }
expect(0) { arrayOf("cat", "dog", "bird").indexOf("cat") } expect(0) { arrayOf("cat", "dog", "bird").indexOf("cat") }
expect(1) { arrayOf("cat", "dog", "bird").indexOf("dog") } expect(1) { arrayOf("cat", "dog", "bird").indexOf("dog") }
@@ -473,7 +473,7 @@ class ArraysTest {
expect(2) { sequenceOf("cat", "dog", "bird").indexOfFirst { it.endsWith('d') } } expect(2) { sequenceOf("cat", "dog", "bird").indexOfFirst { it.endsWith('d') } }
} }
@test fun lastIndexOf() { @Test fun lastIndexOf() {
expect(-1) { arrayOf("cat", "dog", "bird").lastIndexOf("mouse") } expect(-1) { arrayOf("cat", "dog", "bird").lastIndexOf("mouse") }
expect(0) { arrayOf("cat", "dog", "bird").lastIndexOf("cat") } expect(0) { arrayOf("cat", "dog", "bird").lastIndexOf("cat") }
expect(1) { arrayOf("cat", "dog", "bird").lastIndexOf("dog") } expect(1) { arrayOf("cat", "dog", "bird").lastIndexOf("dog") }
@@ -493,7 +493,7 @@ class ArraysTest {
expect(3) { sequenceOf("cat", "dog", "bird", "red").indexOfLast { it.endsWith('d') } } expect(3) { sequenceOf("cat", "dog", "bird", "red").indexOfLast { it.endsWith('d') } }
} }
@test fun isEmpty() { @Test fun isEmpty() {
assertTrue(emptyArray<String>().isEmpty()) assertTrue(emptyArray<String>().isEmpty())
assertFalse(arrayOf("").isEmpty()) assertFalse(arrayOf("").isEmpty())
assertTrue(intArrayOf().isEmpty()) assertTrue(intArrayOf().isEmpty())
@@ -514,12 +514,12 @@ class ArraysTest {
assertFalse(booleanArrayOf(false).isEmpty()) assertFalse(booleanArrayOf(false).isEmpty())
} }
@test fun isNotEmpty() { @Test fun isNotEmpty() {
assertFalse(intArrayOf().isNotEmpty()) assertFalse(intArrayOf().isNotEmpty())
assertTrue(intArrayOf(1).isNotEmpty()) assertTrue(intArrayOf(1).isNotEmpty())
} }
@test fun plusInference() { @Test fun plusInference() {
val arrayOfArrays: Array<Array<out Any>> = arrayOf(arrayOf<Any>("s") as Array<out Any>) val arrayOfArrays: Array<Array<out Any>> = arrayOf(arrayOf<Any>("s") as Array<out Any>)
val elementArray = arrayOf<Any>("a") as Array<out Any> val elementArray = arrayOf<Any>("a") as Array<out Any>
val arrayPlusElement: Array<Array<out Any>> = arrayOfArrays.plusElement(elementArray) val arrayPlusElement: Array<Array<out Any>> = arrayOfArrays.plusElement(elementArray)
@@ -533,7 +533,7 @@ class ArraysTest {
} }
@test fun plus() { @Test fun plus() {
assertEquals(listOf("1", "2", "3", "4"), listOf("1", "2") + arrayOf("3", "4")) assertEquals(listOf("1", "2", "3", "4"), listOf("1", "2") + arrayOf("3", "4"))
assertArrayNotSameButEquals(arrayOf("1", "2", "3"), arrayOf("1", "2") + "3") assertArrayNotSameButEquals(arrayOf("1", "2", "3"), arrayOf("1", "2") + "3")
assertArrayNotSameButEquals(arrayOf("1", "2", "3", "4"), arrayOf("1", "2") + arrayOf("3", "4")) assertArrayNotSameButEquals(arrayOf("1", "2", "3", "4"), arrayOf("1", "2") + arrayOf("3", "4"))
@@ -543,7 +543,7 @@ class ArraysTest {
assertArrayNotSameButEquals(intArrayOf(1, 2, 3, 4), intArrayOf(1, 2) + intArrayOf(3, 4)) assertArrayNotSameButEquals(intArrayOf(1, 2, 3, 4), intArrayOf(1, 2) + intArrayOf(3, 4))
} }
@test fun plusVararg() { @Test fun plusVararg() {
fun stringOnePlus(vararg a: String) = arrayOf("1") + a fun stringOnePlus(vararg a: String) = arrayOf("1") + a
fun longOnePlus(vararg a: Long) = longArrayOf(1) + a fun longOnePlus(vararg a: Long) = longArrayOf(1) + a
fun intOnePlus(vararg a: Int) = intArrayOf(1) + a fun intOnePlus(vararg a: Int) = intArrayOf(1) + a
@@ -553,7 +553,7 @@ class ArraysTest {
assertArrayNotSameButEquals(longArrayOf(1, 2), longOnePlus(2), "LongArray.plus") assertArrayNotSameButEquals(longArrayOf(1, 2), longOnePlus(2), "LongArray.plus")
} }
@test fun plusAssign() { @Test fun plusAssign() {
// lets use a mutable variable // lets use a mutable variable
var result = arrayOf("a") var result = arrayOf("a")
result += "foo" result += "foo"
@@ -562,23 +562,23 @@ class ArraysTest {
assertArrayNotSameButEquals(arrayOf("a", "foo", "beer", "cheese", "wine"), result) assertArrayNotSameButEquals(arrayOf("a", "foo", "beer", "cheese", "wine"), result)
} }
@test fun first() { @Test fun first() {
expect(1) { arrayOf(1, 2, 3).first() } expect(1) { arrayOf(1, 2, 3).first() }
expect(2) { arrayOf(1, 2, 3).first { it % 2 == 0 } } expect(2) { arrayOf(1, 2, 3).first { it % 2 == 0 } }
} }
@test fun last() { @Test fun last() {
expect(3) { arrayOf(1, 2, 3).last() } expect(3) { arrayOf(1, 2, 3).last() }
expect(2) { arrayOf(1, 2, 3).last { it % 2 == 0 } } expect(2) { arrayOf(1, 2, 3).last { it % 2 == 0 } }
} }
@test fun contains() { @Test fun contains() {
assertTrue(arrayOf("1", "2", "3", "4").contains("2")) assertTrue(arrayOf("1", "2", "3", "4").contains("2"))
assertTrue("3" in arrayOf("1", "2", "3", "4")) assertTrue("3" in arrayOf("1", "2", "3", "4"))
assertTrue("0" !in arrayOf("1", "2", "3", "4")) assertTrue("0" !in arrayOf("1", "2", "3", "4"))
} }
@test fun slice() { @Test fun slice() {
val iter: Iterable<Int> = listOf(3, 1, 2) val iter: Iterable<Int> = listOf(3, 1, 2)
assertEquals(listOf("B"), arrayOf("A", "B", "C").slice(1..1)) assertEquals(listOf("B"), arrayOf("A", "B", "C").slice(1..1))
@@ -595,7 +595,7 @@ class ArraysTest {
assertEquals(listOf(true, false, true), booleanArrayOf(true, false, true, true).slice(iter)) assertEquals(listOf(true, false, true), booleanArrayOf(true, false, true, true).slice(iter))
} }
@test fun sliceArray() { @Test fun sliceArray() {
val coll: Collection<Int> = listOf(3, 1, 2) val coll: Collection<Int> = listOf(3, 1, 2)
assertArrayNotSameButEquals(arrayOf("B"), arrayOf("A", "B", "C").sliceArray(1..1)) assertArrayNotSameButEquals(arrayOf("B"), arrayOf("A", "B", "C").sliceArray(1..1))
@@ -614,7 +614,7 @@ class ArraysTest {
assertArrayNotSameButEquals(booleanArrayOf(true, false, true), booleanArrayOf(true, false, true, true).sliceArray(coll)) assertArrayNotSameButEquals(booleanArrayOf(true, false, true), booleanArrayOf(true, false, true, true).sliceArray(coll))
} }
@test fun asIterable() { @Test fun asIterable() {
val arr1 = intArrayOf(1, 2, 3, 4, 5) val arr1 = intArrayOf(1, 2, 3, 4, 5)
val iter1 = arr1.asIterable() val iter1 = arr1.asIterable()
assertEquals(arr1.toList(), iter1.toList()) assertEquals(arr1.toList(), iter1.toList())
@@ -636,7 +636,7 @@ class ArraysTest {
assertEquals(iter4.toList(), emptyList<String>()) assertEquals(iter4.toList(), emptyList<String>())
} }
@test fun asList() { @Test fun asList() {
compare(listOf(1, 2, 3), intArrayOf(1, 2, 3).asList()) { listBehavior() } compare(listOf(1, 2, 3), intArrayOf(1, 2, 3).asList()) { listBehavior() }
compare(listOf<Byte>(1, 2, 3), byteArrayOf(1, 2, 3).asList()) { listBehavior() } compare(listOf<Byte>(1, 2, 3), byteArrayOf(1, 2, 3).asList()) { listBehavior() }
compare(listOf(true, false), booleanArrayOf(true, false).asList()) { listBehavior() } compare(listOf(true, false), booleanArrayOf(true, false).asList()) { listBehavior() }
@@ -651,7 +651,7 @@ class ArraysTest {
assertEquals(10, intsAsList[1], "Should reflect changes in original array") assertEquals(10, intsAsList[1], "Should reflect changes in original array")
} }
@test fun toPrimitiveArray() { @Test fun toPrimitiveArray() {
val genericArray: Array<Int> = arrayOf(1, 2, 3) val genericArray: Array<Int> = arrayOf(1, 2, 3)
val primitiveArray: IntArray = genericArray.toIntArray() val primitiveArray: IntArray = genericArray.toIntArray()
expect(3) { primitiveArray.size } expect(3) { primitiveArray.size }
@@ -663,14 +663,14 @@ class ArraysTest {
assertEquals(charList, charArray.asList()) assertEquals(charList, charArray.asList())
} }
@test fun toTypedArray() { @Test fun toTypedArray() {
val primitiveArray: LongArray = longArrayOf(1, 2, Long.MAX_VALUE) val primitiveArray: LongArray = longArrayOf(1, 2, Long.MAX_VALUE)
val genericArray: Array<Long> = primitiveArray.toTypedArray() val genericArray: Array<Long> = primitiveArray.toTypedArray()
expect(3) { genericArray.size } expect(3) { genericArray.size }
assertEquals(primitiveArray.asList(), genericArray.asList()) assertEquals(primitiveArray.asList(), genericArray.asList())
} }
@test fun copyOf() { @Test fun copyOf() {
booleanArrayOf(true, false, true).let { assertArrayNotSameButEquals(it, it.copyOf()) } booleanArrayOf(true, false, true).let { assertArrayNotSameButEquals(it, it.copyOf()) }
byteArrayOf(0, 1, 2, 3, 4, 5).let { assertArrayNotSameButEquals(it, it.copyOf()) } byteArrayOf(0, 1, 2, 3, 4, 5).let { assertArrayNotSameButEquals(it, it.copyOf()) }
shortArrayOf(0, 1, 2, 3, 4, 5).let { assertArrayNotSameButEquals(it, it.copyOf()) } shortArrayOf(0, 1, 2, 3, 4, 5).let { assertArrayNotSameButEquals(it, it.copyOf()) }
@@ -681,7 +681,7 @@ class ArraysTest {
charArrayOf('0', '1', '2', '3', '4', '5').let { assertArrayNotSameButEquals(it, it.copyOf()) } charArrayOf('0', '1', '2', '3', '4', '5').let { assertArrayNotSameButEquals(it, it.copyOf()) }
} }
@test fun copyAndResize() { @Test fun copyAndResize() {
assertArrayNotSameButEquals(arrayOf("1", "2"), arrayOf("1", "2", "3").copyOf(2)) assertArrayNotSameButEquals(arrayOf("1", "2"), arrayOf("1", "2", "3").copyOf(2))
assertArrayNotSameButEquals(arrayOf("1", "2", null), arrayOf("1", "2").copyOf(3)) assertArrayNotSameButEquals(arrayOf("1", "2", null), arrayOf("1", "2").copyOf(3))
@@ -695,7 +695,7 @@ class ArraysTest {
assertArrayNotSameButEquals(charArrayOf('A', 'B', '\u0000'), charArrayOf('A', 'B').copyOf(3)) assertArrayNotSameButEquals(charArrayOf('A', 'B', '\u0000'), charArrayOf('A', 'B').copyOf(3))
} }
@test fun copyOfRange() { @Test fun copyOfRange() {
assertArrayNotSameButEquals(booleanArrayOf(true, false, true), booleanArrayOf(true, false, true, true).copyOfRange(0, 3)) assertArrayNotSameButEquals(booleanArrayOf(true, false, true), booleanArrayOf(true, false, true, true).copyOfRange(0, 3))
assertArrayNotSameButEquals(byteArrayOf(0, 1, 2), byteArrayOf(0, 1, 2, 3, 4, 5).copyOfRange(0, 3)) assertArrayNotSameButEquals(byteArrayOf(0, 1, 2), byteArrayOf(0, 1, 2, 3, 4, 5).copyOfRange(0, 3))
assertArrayNotSameButEquals(shortArrayOf(0, 1, 2), shortArrayOf(0, 1, 2, 3, 4, 5).copyOfRange(0, 3)) assertArrayNotSameButEquals(shortArrayOf(0, 1, 2), shortArrayOf(0, 1, 2, 3, 4, 5).copyOfRange(0, 3))
@@ -708,7 +708,7 @@ class ArraysTest {
@test fun reduceIndexed() { @Test fun reduceIndexed() {
expect(-1) { intArrayOf(1, 2, 3).reduceIndexed { index, a, b -> index + a - b } } expect(-1) { intArrayOf(1, 2, 3).reduceIndexed { index, a, b -> index + a - b } }
expect(-1.toLong()) { longArrayOf(1, 2, 3).reduceIndexed { index, a, b -> index + a - b } } expect(-1.toLong()) { longArrayOf(1, 2, 3).reduceIndexed { index, a, b -> index + a - b } }
expect(-1F) { floatArrayOf(1F, 2F, 3F).reduceIndexed { index, a, b -> index + a - b } } expect(-1F) { floatArrayOf(1F, 2F, 3F).reduceIndexed { index, a, b -> index + a - b } }
@@ -724,7 +724,7 @@ class ArraysTest {
} }
} }
@test fun reduceRightIndexed() { @Test fun reduceRightIndexed() {
expect(1) { intArrayOf(1, 2, 3).reduceRightIndexed { index, a, b -> index + a - b } } expect(1) { intArrayOf(1, 2, 3).reduceRightIndexed { index, a, b -> index + a - b } }
expect(1.toLong()) { longArrayOf(1, 2, 3).reduceRightIndexed { index, a, b -> index + a - b } } expect(1.toLong()) { longArrayOf(1, 2, 3).reduceRightIndexed { index, a, b -> index + a - b } }
expect(1F) { floatArrayOf(1F, 2F, 3F).reduceRightIndexed { index, a, b -> index + a - b } } expect(1F) { floatArrayOf(1F, 2F, 3F).reduceRightIndexed { index, a, b -> index + a - b } }
@@ -740,7 +740,7 @@ class ArraysTest {
} }
} }
@test fun reduce() { @Test fun reduce() {
expect(-4) { intArrayOf(1, 2, 3).reduce { a, b -> a - b } } expect(-4) { intArrayOf(1, 2, 3).reduce { a, b -> a - b } }
expect(-4.toLong()) { longArrayOf(1, 2, 3).reduce { a, b -> a - b } } expect(-4.toLong()) { longArrayOf(1, 2, 3).reduce { a, b -> a - b } }
expect(-4F) { floatArrayOf(1F, 2F, 3F).reduce { a, b -> a - b } } expect(-4F) { floatArrayOf(1F, 2F, 3F).reduce { a, b -> a - b } }
@@ -756,7 +756,7 @@ class ArraysTest {
} }
} }
@test fun reduceRight() { @Test fun reduceRight() {
expect(2) { intArrayOf(1, 2, 3).reduceRight { a, b -> a - b } } expect(2) { intArrayOf(1, 2, 3).reduceRight { a, b -> a - b } }
expect(2.toLong()) { longArrayOf(1, 2, 3).reduceRight { a, b -> a - b } } expect(2.toLong()) { longArrayOf(1, 2, 3).reduceRight { a, b -> a - b } }
expect(2F) { floatArrayOf(1F, 2F, 3F).reduceRight { a, b -> a - b } } expect(2F) { floatArrayOf(1F, 2F, 3F).reduceRight { a, b -> a - b } }
@@ -772,7 +772,7 @@ class ArraysTest {
} }
} }
@test fun reverseInPlace() { @Test fun reverseInPlace() {
fun <TArray, T> doTest(build: Iterable<Int>.() -> TArray, reverse: TArray.() -> Unit, snapshot: TArray.() -> List<T>) { fun <TArray, T> doTest(build: Iterable<Int>.() -> TArray, reverse: TArray.() -> Unit, snapshot: TArray.() -> List<T>) {
val arrays = (0..4).map { n -> (1..n).build() } val arrays = (0..4).map { n -> (1..n).build() }
@@ -797,7 +797,7 @@ class ArraysTest {
} }
@test fun reversed() { @Test fun reversed() {
expect(listOf(3, 2, 1)) { intArrayOf(1, 2, 3).reversed() } expect(listOf(3, 2, 1)) { intArrayOf(1, 2, 3).reversed() }
expect(listOf<Byte>(3, 2, 1)) { byteArrayOf(1, 2, 3).reversed() } expect(listOf<Byte>(3, 2, 1)) { byteArrayOf(1, 2, 3).reversed() }
expect(listOf<Short>(3, 2, 1)) { shortArrayOf(1, 2, 3).reversed() } expect(listOf<Short>(3, 2, 1)) { shortArrayOf(1, 2, 3).reversed() }
@@ -809,7 +809,7 @@ class ArraysTest {
expect(listOf("3", "2", "1")) { arrayOf("1", "2", "3").reversed() } expect(listOf("3", "2", "1")) { arrayOf("1", "2", "3").reversed() }
} }
@test fun reversedArray() { @Test fun reversedArray() {
assertArrayNotSameButEquals(intArrayOf(3, 2, 1), intArrayOf(1, 2, 3).reversedArray()) assertArrayNotSameButEquals(intArrayOf(3, 2, 1), intArrayOf(1, 2, 3).reversedArray())
assertArrayNotSameButEquals(byteArrayOf(3, 2, 1), byteArrayOf(1, 2, 3).reversedArray()) assertArrayNotSameButEquals(byteArrayOf(3, 2, 1), byteArrayOf(1, 2, 3).reversedArray())
assertArrayNotSameButEquals(shortArrayOf(3, 2, 1), shortArrayOf(1, 2, 3).reversedArray()) assertArrayNotSameButEquals(shortArrayOf(3, 2, 1), shortArrayOf(1, 2, 3).reversedArray())
@@ -822,7 +822,7 @@ class ArraysTest {
assertArrayNotSameButEquals(arrayOf("3", "2", "1"), (arrayOf("1", "2", "3") as Array<out String>).reversedArray()) assertArrayNotSameButEquals(arrayOf("3", "2", "1"), (arrayOf("1", "2", "3") as Array<out String>).reversedArray())
} }
@test fun drop() { @Test fun drop() {
expect(listOf(1), { intArrayOf(1).drop(0) }) expect(listOf(1), { intArrayOf(1).drop(0) })
expect(listOf(), { intArrayOf().drop(1) }) expect(listOf(), { intArrayOf().drop(1) })
expect(listOf(), { intArrayOf(1).drop(1) }) expect(listOf(), { intArrayOf(1).drop(1) })
@@ -840,7 +840,7 @@ class ArraysTest {
} }
} }
@test fun dropLast() { @Test fun dropLast() {
expect(listOf(), { intArrayOf().dropLast(1) }) expect(listOf(), { intArrayOf().dropLast(1) })
expect(listOf(), { intArrayOf(1).dropLast(1) }) expect(listOf(), { intArrayOf(1).dropLast(1) })
expect(listOf(1), { intArrayOf(1).dropLast(0) }) expect(listOf(1), { intArrayOf(1).dropLast(0) })
@@ -858,7 +858,7 @@ class ArraysTest {
} }
} }
@test fun dropWhile() { @Test fun dropWhile() {
expect(listOf(), { intArrayOf().dropWhile { it < 3 } }) expect(listOf(), { intArrayOf().dropWhile { it < 3 } })
expect(listOf(), { intArrayOf(1).dropWhile { it < 3 } }) expect(listOf(), { intArrayOf(1).dropWhile { it < 3 } })
expect(listOf(3, 1), { intArrayOf(2, 3, 1).dropWhile { it < 3 } }) expect(listOf(3, 1), { intArrayOf(2, 3, 1).dropWhile { it < 3 } })
@@ -872,7 +872,7 @@ class ArraysTest {
expect(listOf("b", "a"), { arrayOf("a", "b", "a").dropWhile { it < "b" } }) expect(listOf("b", "a"), { arrayOf("a", "b", "a").dropWhile { it < "b" } })
} }
@test fun dropLastWhile() { @Test fun dropLastWhile() {
expect(listOf(), { intArrayOf().dropLastWhile { it < 3 } }) expect(listOf(), { intArrayOf().dropLastWhile { it < 3 } })
expect(listOf(), { intArrayOf(1).dropLastWhile { it < 3 } }) expect(listOf(), { intArrayOf(1).dropLastWhile { it < 3 } })
expect(listOf(2, 3), { intArrayOf(2, 3, 1).dropLastWhile { it < 3 } }) expect(listOf(2, 3), { intArrayOf(2, 3, 1).dropLastWhile { it < 3 } })
@@ -886,7 +886,7 @@ class ArraysTest {
expect(listOf("a", "b"), { arrayOf("a", "b", "a").dropLastWhile { it < "b" } }) expect(listOf("a", "b"), { arrayOf("a", "b", "a").dropLastWhile { it < "b" } })
} }
@test fun take() { @Test fun take() {
expect(listOf(), { intArrayOf().take(1) }) expect(listOf(), { intArrayOf().take(1) })
expect(listOf(), { intArrayOf(1).take(0) }) expect(listOf(), { intArrayOf(1).take(0) })
expect(listOf(1), { intArrayOf(1).take(1) }) expect(listOf(1), { intArrayOf(1).take(1) })
@@ -904,7 +904,7 @@ class ArraysTest {
} }
} }
@test fun takeLast() { @Test fun takeLast() {
expect(listOf(), { intArrayOf().takeLast(1) }) expect(listOf(), { intArrayOf().takeLast(1) })
expect(listOf(), { intArrayOf(1).takeLast(0) }) expect(listOf(), { intArrayOf(1).takeLast(0) })
expect(listOf(1), { intArrayOf(1).takeLast(1) }) expect(listOf(1), { intArrayOf(1).takeLast(1) })
@@ -922,7 +922,7 @@ class ArraysTest {
} }
} }
@test fun takeWhile() { @Test fun takeWhile() {
expect(listOf(), { intArrayOf().takeWhile { it < 3 } }) expect(listOf(), { intArrayOf().takeWhile { it < 3 } })
expect(listOf(1), { intArrayOf(1).takeWhile { it < 3 } }) expect(listOf(1), { intArrayOf(1).takeWhile { it < 3 } })
expect(listOf(2), { intArrayOf(2, 3, 1).takeWhile { it < 3 } }) expect(listOf(2), { intArrayOf(2, 3, 1).takeWhile { it < 3 } })
@@ -936,7 +936,7 @@ class ArraysTest {
expect(listOf("a"), { arrayOf("a", "c", "b").takeWhile { it < "c" } }) expect(listOf("a"), { arrayOf("a", "c", "b").takeWhile { it < "c" } })
} }
@test fun takeLastWhile() { @Test fun takeLastWhile() {
expect(listOf(), { intArrayOf().takeLastWhile { it < 3 } }) expect(listOf(), { intArrayOf().takeLastWhile { it < 3 } })
expect(listOf(1), { intArrayOf(1).takeLastWhile { it < 3 } }) expect(listOf(1), { intArrayOf(1).takeLastWhile { it < 3 } })
expect(listOf(1), { intArrayOf(2, 3, 1).takeLastWhile { it < 3 } }) expect(listOf(1), { intArrayOf(2, 3, 1).takeLastWhile { it < 3 } })
@@ -950,7 +950,7 @@ class ArraysTest {
expect(listOf("b"), { arrayOf("a", "c", "b").takeLastWhile { it < "c" } }) expect(listOf("b"), { arrayOf("a", "c", "b").takeLastWhile { it < "c" } })
} }
@test fun filter() { @Test fun filter() {
expect(listOf(), { intArrayOf().filter { it > 2 } }) expect(listOf(), { intArrayOf().filter { it > 2 } })
expect(listOf(), { intArrayOf(1).filter { it > 2 } }) expect(listOf(), { intArrayOf(1).filter { it > 2 } })
expect(listOf(3), { intArrayOf(2, 3).filter { it > 2 } }) expect(listOf(3), { intArrayOf(2, 3).filter { it > 2 } })
@@ -964,7 +964,7 @@ class ArraysTest {
expect(listOf("b"), { arrayOf("a", "b").filter { it > "a" } }) expect(listOf("b"), { arrayOf("a", "b").filter { it > "a" } })
} }
@test fun filterIndexed() { @Test fun filterIndexed() {
expect(listOf(), { intArrayOf().filterIndexed { i, v -> i > v } }) expect(listOf(), { intArrayOf().filterIndexed { i, v -> i > v } })
expect(listOf(2, 5, 8), { intArrayOf(2, 4, 3, 5, 8).filterIndexed { index, value -> index % 2 == value % 2 } }) expect(listOf(2, 5, 8), { intArrayOf(2, 4, 3, 5, 8).filterIndexed { index, value -> index % 2 == value % 2 } })
expect(listOf<Long>(2, 5, 8), { longArrayOf(2, 4, 3, 5, 8).filterIndexed { index, value -> index % 2 == (value % 2).toInt() } }) expect(listOf<Long>(2, 5, 8), { longArrayOf(2, 4, 3, 5, 8).filterIndexed { index, value -> index % 2 == (value % 2).toInt() } })
@@ -973,7 +973,7 @@ class ArraysTest {
expect(listOf("a", "c", "d"), { arrayOf("a", "b", "c", "d").filterIndexed { index, s -> s == "a" || index >= 2 } }) expect(listOf("a", "c", "d"), { arrayOf("a", "b", "c", "d").filterIndexed { index, s -> s == "a" || index >= 2 } })
} }
@test fun filterNot() { @Test fun filterNot() {
expect(listOf(), { intArrayOf().filterNot { it > 2 } }) expect(listOf(), { intArrayOf().filterNot { it > 2 } })
expect(listOf(1), { intArrayOf(1).filterNot { it > 2 } }) expect(listOf(1), { intArrayOf(1).filterNot { it > 2 } })
expect(listOf(2), { intArrayOf(2, 3).filterNot { it > 2 } }) expect(listOf(2), { intArrayOf(2, 3).filterNot { it > 2 } })
@@ -987,32 +987,32 @@ class ArraysTest {
expect(listOf("a"), { arrayOf("a", "b").filterNot { it > "a" } }) expect(listOf("a"), { arrayOf("a", "b").filterNot { it > "a" } })
} }
@test fun filterNotNull() { @Test fun filterNotNull() {
expect(listOf("a"), { arrayOf("a", null).filterNotNull() }) expect(listOf("a"), { arrayOf("a", null).filterNotNull() })
} }
@test fun map() { @Test fun map() {
assertEquals(listOf(1, 2, 4), arrayOf("a", "bc", "test").map { it.length }) assertEquals(listOf(1, 2, 4), arrayOf("a", "bc", "test").map { it.length })
assertEquals(listOf('a', 'b', 'c'), intArrayOf(1, 2, 3).map { 'a' + it - 1 }) assertEquals(listOf('a', 'b', 'c'), intArrayOf(1, 2, 3).map { 'a' + it - 1 })
assertEquals(listOf(1, 2, 3), longArrayOf(1000, 2000, 3000).map { (it / 1000).toInt() }) assertEquals(listOf(1, 2, 3), longArrayOf(1000, 2000, 3000).map { (it / 1000).toInt() })
assertEquals(listOf(1.0, 0.5, 0.4, 0.2, 0.1), doubleArrayOf(1.0, 2.0, 2.5, 5.0, 10.0).map { 1 / it }) assertEquals(listOf(1.0, 0.5, 0.4, 0.2, 0.1), doubleArrayOf(1.0, 2.0, 2.5, 5.0, 10.0).map { 1 / it })
} }
@test fun mapIndexed() { @Test fun mapIndexed() {
assertEquals(listOf(1, 1, 2), arrayOf("a", "bc", "test").mapIndexed { index, s -> s.length - index }) assertEquals(listOf(1, 1, 2), arrayOf("a", "bc", "test").mapIndexed { index, s -> s.length - index })
assertEquals(listOf(0, 2, 2), intArrayOf(3, 2, 1).mapIndexed { index, i -> i * index }) assertEquals(listOf(0, 2, 2), intArrayOf(3, 2, 1).mapIndexed { index, i -> i * index })
assertEquals(listOf("0;20", "1;21", "2;22"), longArrayOf(20, 21, 22).mapIndexed { index, it -> "$index;$it" }) assertEquals(listOf("0;20", "1;21", "2;22"), longArrayOf(20, 21, 22).mapIndexed { index, it -> "$index;$it" })
} }
@test fun mapNotNull() { @Test fun mapNotNull() {
assertEquals(listOf(2, 3), arrayOf("", "bc", "def").mapNotNull { if (it.isEmpty()) null else it.length }) assertEquals(listOf(2, 3), arrayOf("", "bc", "def").mapNotNull { if (it.isEmpty()) null else it.length })
} }
@test fun mapIndexedNotNull() { @Test fun mapIndexedNotNull() {
assertEquals(listOf(2), arrayOf("a", null, "test").mapIndexedNotNull { index, it -> it?.run { if (index != 0) length / index else null } }) assertEquals(listOf(2), arrayOf("a", null, "test").mapIndexedNotNull { index, it -> it?.run { if (index != 0) length / index else null } })
} }
@test fun flattenArray() { @Test fun flattenArray() {
val arr1: Array<Array<Int>> = arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6)) val arr1: Array<Array<Int>> = arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6))
val arr2: Array<out Array<Int>> = arr1 val arr2: Array<out Array<Int>> = arr1
val arr3: Array<out Array<out Int>> = arr1 val arr3: Array<out Array<out Int>> = arr1
@@ -1025,7 +1025,7 @@ class ArraysTest {
assertEquals(expected, arr4.flatten()) assertEquals(expected, arr4.flatten())
} }
@test fun asListPrimitives() { @Test fun asListPrimitives() {
// Array of primitives // Array of primitives
val arr = intArrayOf(1, 2, 3, 4, 2, 5) val arr = intArrayOf(1, 2, 3, 4, 2, 5)
val list = arr.asList() val list = arr.asList()
@@ -1057,7 +1057,7 @@ class ArraysTest {
assertEquals(IntArray(0).asList(), emptyList<Int>()) assertEquals(IntArray(0).asList(), emptyList<Int>())
} }
@test fun asListObjects() { @Test fun asListObjects() {
val arr = arrayOf("a", "b", "c", "d", "b", "e") val arr = arrayOf("a", "b", "c", "d", "b", "e")
val list = arr.asList() val list = arr.asList()
@@ -1090,7 +1090,7 @@ class ArraysTest {
assertEquals(Array(0, { "" }).asList(), emptyList<String>()) assertEquals(Array(0, { "" }).asList(), emptyList<String>())
} }
@test fun sort() { @Test fun sort() {
val intArr = intArrayOf(5, 2, 1, 9, 80, Int.MIN_VALUE, Int.MAX_VALUE) val intArr = intArrayOf(5, 2, 1, 9, 80, Int.MIN_VALUE, Int.MAX_VALUE)
intArr.sort() intArr.sort()
assertArrayNotSameButEquals(intArrayOf(Int.MIN_VALUE, 1, 2, 5, 9, 80, Int.MAX_VALUE), intArr) assertArrayNotSameButEquals(intArrayOf(Int.MIN_VALUE, 1, 2, 5, 9, 80, Int.MAX_VALUE), intArr)
@@ -1117,7 +1117,7 @@ class ArraysTest {
assertArrayNotSameButEquals(arrayOf("all", "Foo", "9", "80"), strArr) assertArrayNotSameButEquals(arrayOf("all", "Foo", "9", "80"), strArr)
} }
@test fun sortedTests() { @Test fun sortedTests() {
assertTrue(arrayOf<Long>().sorted().none()) assertTrue(arrayOf<Long>().sorted().none())
assertEquals(listOf(1), arrayOf(1).sorted()) assertEquals(listOf(1), arrayOf(1).sorted())
@@ -1160,7 +1160,7 @@ class ArraysTest {
} }
} }
@test fun sortByInPlace() { @Test fun sortByInPlace() {
val data = arrayOf("aa" to 20, "ab" to 3, "aa" to 3) val data = arrayOf("aa" to 20, "ab" to 3, "aa" to 3)
data.sortBy { it.second } data.sortBy { it.second }
assertArrayNotSameButEquals(arrayOf("ab" to 3, "aa" to 3, "aa" to 20), data) assertArrayNotSameButEquals(arrayOf("ab" to 3, "aa" to 3, "aa" to 20), data)
@@ -1172,14 +1172,14 @@ class ArraysTest {
assertArrayNotSameButEquals(arrayOf("aa" to 20, "aa" to 3, "ab" to 3), data) assertArrayNotSameButEquals(arrayOf("aa" to 20, "aa" to 3, "ab" to 3), data)
} }
@test fun sortedBy() { @Test fun sortedBy() {
val values = arrayOf("ac", "aD", "aba") val values = arrayOf("ac", "aD", "aba")
val indices = values.indices.toList().toIntArray() val indices = values.indices.toList().toIntArray()
assertEquals(listOf(1, 2, 0), indices.sortedBy { values[it] }) assertEquals(listOf(1, 2, 0), indices.sortedBy { values[it] })
} }
@test fun sortedNullableBy() { @Test fun sortedNullableBy() {
fun String.nullIfEmpty() = if (this.isEmpty()) null else this fun String.nullIfEmpty() = if (this.isEmpty()) null else this
arrayOf(null, "").let { arrayOf(null, "").let {
expect(listOf(null, "")) { it.sortedWith(nullsFirst(compareBy { it })) } expect(listOf(null, "")) { it.sortedWith(nullsFirst(compareBy { it })) }
@@ -1188,7 +1188,7 @@ class ArraysTest {
} }
} }
@test fun sortedWith() { @Test fun sortedWith() {
val comparator = compareBy { it: Int -> it % 3 }.thenByDescending { it } val comparator = compareBy { it: Int -> it % 3 }.thenByDescending { it }
fun <A, T> arrayData(array: A, comparator: Comparator<T>) = ArraySortedChecker<A, T>(array, comparator) fun <A, T> arrayData(array: A, comparator: Comparator<T>) = ArraySortedChecker<A, T>(array, comparator)
@@ -9,7 +9,7 @@ import kotlin.test.*
import kotlin.comparisons.* import kotlin.comparisons.*
import java.util.* import java.util.*
import org.junit.Test as test import org.junit.Test
class CollectionJVMTest { class CollectionJVMTest {
@@ -21,7 +21,7 @@ class CollectionJVMTest {
private data class IdentityData(public val value: Int) private data class IdentityData(public val value: Int)
@test fun removeAllWithDifferentEquality() { @Test fun removeAllWithDifferentEquality() {
val data = listOf(IdentityData(1), IdentityData(1)) val data = listOf(IdentityData(1), IdentityData(1))
val list = data.toMutableList() val list = data.toMutableList()
list -= identitySetOf(data[0]) as Iterable<IdentityData> list -= identitySetOf(data[0]) as Iterable<IdentityData>
@@ -36,7 +36,7 @@ class CollectionJVMTest {
assertTrue(set3.isEmpty(), "Array doesn't have contains, equality contains is used instead") assertTrue(set3.isEmpty(), "Array doesn't have contains, equality contains is used instead")
} }
@test fun flatMap() { @Test fun flatMap() {
val data = listOf("", "foo", "bar", "x", "") val data = listOf("", "foo", "bar", "x", "")
val characters = data.flatMap { it.toList() } val characters = data.flatMap { it.toList() }
println("Got list of characters ${characters}") println("Got list of characters ${characters}")
@@ -46,7 +46,7 @@ class CollectionJVMTest {
} }
@test fun filterIntoLinkedList() { @Test fun filterIntoLinkedList() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val foo = data.filterTo(LinkedList<String>()) { it.startsWith("f") } val foo = data.filterTo(LinkedList<String>()) { it.startsWith("f") }
@@ -61,7 +61,7 @@ class CollectionJVMTest {
} }
} }
@test fun filterNotIntoLinkedListOf() { @Test fun filterNotIntoLinkedListOf() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val foo = data.filterNotTo(LinkedList<String>()) { it.startsWith("f") } val foo = data.filterNotTo(LinkedList<String>()) { it.startsWith("f") }
@@ -76,7 +76,7 @@ class CollectionJVMTest {
} }
} }
@test fun filterNotNullIntoLinkedListOf() { @Test fun filterNotNullIntoLinkedListOf() {
val data = listOf(null, "foo", null, "bar") val data = listOf(null, "foo", null, "bar")
val foo = data.filterNotNullTo(LinkedList<String>()) val foo = data.filterNotNullTo(LinkedList<String>())
@@ -88,7 +88,7 @@ class CollectionJVMTest {
} }
} }
@test fun filterIntoSortedSet() { @Test fun filterIntoSortedSet() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val sorted = data.filterTo(sortedSetOf<String>()) { it.length == 3 } val sorted = data.filterTo(sortedSetOf<String>()) { it.length == 3 }
assertEquals(2, sorted.size) assertEquals(2, sorted.size)
@@ -98,26 +98,26 @@ class CollectionJVMTest {
} }
} }
@test fun first() { @Test fun first() {
assertEquals(19, TreeSet(listOf(90, 47, 19)).first()) assertEquals(19, TreeSet(listOf(90, 47, 19)).first())
} }
@test fun last() { @Test fun last() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
assertEquals("bar", data.last()) assertEquals("bar", data.last())
assertEquals(25, listOf(15, 19, 20, 25).last()) assertEquals(25, listOf(15, 19, 20, 25).last())
assertEquals('a', LinkedList(listOf('a')).last()) assertEquals('a', LinkedList(listOf('a')).last())
} }
@test fun lastException() { @Test fun lastException() {
assertFails { LinkedList<String>().last() } assertFails { LinkedList<String>().last() }
} }
@test fun contains() { @Test fun contains() {
assertTrue(LinkedList(listOf(15, 19, 20)).contains(15)) assertTrue(LinkedList(listOf(15, 19, 20)).contains(15))
} }
@test fun toArray() { @Test fun toArray() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val arr = data.toTypedArray() val arr = data.toTypedArray()
println("Got array ${arr}") println("Got array ${arr}")
@@ -129,7 +129,7 @@ class CollectionJVMTest {
} }
} }
@test fun toSortedSet() { @Test fun toSortedSet() {
val data = listOf("foo", "Foo", "bar") val data = listOf("foo", "Foo", "bar")
val set1 = data.toSortedSet() val set1 = data.toSortedSet()
assertEquals(listOf("Foo", "bar", "foo"), set1.toList()) assertEquals(listOf("Foo", "bar", "foo"), set1.toList())
@@ -141,11 +141,11 @@ class CollectionJVMTest {
assertEquals(listOf("bar", "foo"), set3.toList()) assertEquals(listOf("bar", "foo"), set3.toList())
} }
@test fun takeReturnsFirstNElements() { @Test fun takeReturnsFirstNElements() {
expect(setOf(1, 2)) { sortedSetOf(1, 2, 3, 4, 5).take(2).toSet() } expect(setOf(1, 2)) { sortedSetOf(1, 2, 3, 4, 5).take(2).toSet() }
} }
@test fun filterIsInstanceList() { @Test fun filterIsInstanceList() {
val values: List<Any> = listOf(1, 2, 3.toDouble(), "abc", "cde") val values: List<Any> = listOf(1, 2, 3.toDouble(), "abc", "cde")
val intValues: List<Int> = values.filterIsInstance<Int>() val intValues: List<Int> = values.filterIsInstance<Int>()
@@ -164,7 +164,7 @@ class CollectionJVMTest {
assertEquals(0, charValues.size) assertEquals(0, charValues.size)
} }
@test fun filterIsInstanceArray() { @Test fun filterIsInstanceArray() {
val src: Array<Any> = arrayOf(1, 2, 3.toDouble(), "abc", "cde") val src: Array<Any> = arrayOf(1, 2, 3.toDouble(), "abc", "cde")
val intValues: List<Int> = src.filterIsInstance<Int>() val intValues: List<Int> = src.filterIsInstance<Int>()
@@ -183,11 +183,11 @@ class CollectionJVMTest {
assertEquals(0, charValues.size) assertEquals(0, charValues.size)
} }
@test fun emptyListIsSerializable() = testSingletonSerialization(emptyList<Any>()) @Test fun emptyListIsSerializable() = testSingletonSerialization(emptyList<Any>())
@test fun emptySetIsSerializable() = testSingletonSerialization(emptySet<Any>()) @Test fun emptySetIsSerializable() = testSingletonSerialization(emptySet<Any>())
@test fun emptyMapIsSerializable() = testSingletonSerialization(emptyMap<Any, Any>()) @Test fun emptyMapIsSerializable() = testSingletonSerialization(emptyMap<Any, Any>())
private fun testSingletonSerialization(value: Any) { private fun testSingletonSerialization(value: Any) {
val result = serializeAndDeserialize(value) val result = serializeAndDeserialize(value)
@@ -209,15 +209,15 @@ class CollectionJVMTest {
return inputObjectStream.readObject() as T return inputObjectStream.readObject() as T
} }
@test fun deserializeEmptyList() = testPersistedDeserialization( @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", "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>()) emptyList<Any>())
@test fun deserializeEmptySet() = testPersistedDeserialization( @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", "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>()) emptySet<Any>())
@test fun deserializeEmptyMap() = testPersistedDeserialization( @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", "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>()) emptyMap<Any, Any>())
@@ -17,21 +17,21 @@
package test.collections package test.collections
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
import test.collections.behaviors.* import test.collections.behaviors.*
import test.comparisons.STRING_CASE_INSENSITIVE_ORDER import test.comparisons.STRING_CASE_INSENSITIVE_ORDER
import kotlin.comparisons.* import kotlin.comparisons.*
class CollectionTest { class CollectionTest {
@test fun joinTo() { @Test fun joinTo() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val buffer = StringBuilder() val buffer = StringBuilder()
data.joinTo(buffer, "-", "{", "}") data.joinTo(buffer, "-", "{", "}")
assertEquals("{foo-bar}", buffer.toString()) assertEquals("{foo-bar}", buffer.toString())
} }
@test fun joinToString() { @Test fun joinToString() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val text = data.joinToString("-", "<", ">") val text = data.joinToString("-", "<", ">")
assertEquals("<foo-bar>", text) assertEquals("<foo-bar>", text)
@@ -41,7 +41,7 @@ class CollectionTest {
assertEquals("a, b, c, *", text2) assertEquals("a, b, c, *", text2)
} }
@test fun filterNotNull() { @Test fun filterNotNull() {
val data = listOf(null, "foo", null, "bar") val data = listOf(null, "foo", null, "bar")
val foo = data.filterNotNull() val foo = data.filterNotNull()
@@ -54,7 +54,7 @@ class CollectionTest {
} }
/* /*
@test fun mapNotNull() { @Test fun mapNotNull() {
val data = listOf(null, "foo", null, "bar") val data = listOf(null, "foo", null, "bar")
val foo = data.mapNotNull { it.length() } val foo = data.mapNotNull { it.length() }
assertEquals(2, foo.size()) assertEquals(2, foo.size())
@@ -66,7 +66,7 @@ class CollectionTest {
} }
*/ */
@test fun listOfNotNull() { @Test fun listOfNotNull() {
val l1: List<Int> = listOfNotNull(null) val l1: List<Int> = listOfNotNull(null)
assertTrue(l1.isEmpty()) assertTrue(l1.isEmpty())
@@ -78,7 +78,7 @@ class CollectionTest {
assertEquals(listOf("value1", "value2"), l3) assertEquals(listOf("value1", "value2"), l3)
} }
@test fun filterIntoSet() { @Test fun filterIntoSet() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val foo = data.filterTo(hashSetOf<String>()) { it.startsWith("f") } val foo = data.filterTo(hashSetOf<String>()) { it.startsWith("f") }
@@ -93,7 +93,7 @@ class CollectionTest {
} }
} }
@test fun filterIsInstanceList() { @Test fun filterIsInstanceList() {
val values: List<Any> = listOf(1, 2, 3.0, "abc", "cde") val values: List<Any> = listOf(1, 2, 3.0, "abc", "cde")
val numberValues: List<Number> = values.filterIsInstance<Number>() val numberValues: List<Number> = values.filterIsInstance<Number>()
@@ -114,7 +114,7 @@ class CollectionTest {
assertEquals(0, charValues.size) assertEquals(0, charValues.size)
} }
@test fun filterIsInstanceArray() { @Test fun filterIsInstanceArray() {
val src: Array<Any> = arrayOf(1, 2, 3.0, "abc", "cde") val src: Array<Any> = arrayOf(1, 2, 3.0, "abc", "cde")
val numberValues: List<Number> = src.filterIsInstance<Number>() val numberValues: List<Number> = src.filterIsInstance<Number>()
@@ -135,7 +135,7 @@ class CollectionTest {
assertEquals(0, charValues.size) assertEquals(0, charValues.size)
} }
@test fun foldIndexed() { @Test fun foldIndexed() {
expect(42) { expect(42) {
val numbers = listOf(1, 2, 3, 4) val numbers = listOf(1, 2, 3, 4)
numbers.foldIndexed(0) { index, a, b -> index * (a + b) } numbers.foldIndexed(0) { index, a, b -> index * (a + b) }
@@ -152,7 +152,7 @@ class CollectionTest {
} }
} }
@test fun foldIndexedWithDifferentTypes() { @Test fun foldIndexedWithDifferentTypes() {
expect(10) { expect(10) {
val numbers = listOf("a", "ab", "abc") val numbers = listOf("a", "ab", "abc")
numbers.foldIndexed(1) { index, a, b -> a + b.length + index } numbers.foldIndexed(1) { index, a, b -> a + b.length + index }
@@ -164,35 +164,35 @@ class CollectionTest {
} }
} }
@test fun foldIndexedWithNonCommutativeOperation() { @Test fun foldIndexedWithNonCommutativeOperation() {
expect(4) { expect(4) {
val numbers = listOf(1, 2, 3) val numbers = listOf(1, 2, 3)
numbers.foldIndexed(7) { index, a, b -> index + a - b } numbers.foldIndexed(7) { index, a, b -> index + a - b }
} }
} }
@test fun foldRightIndexed() { @Test fun foldRightIndexed() {
expect("12343210") { expect("12343210") {
val numbers = listOf(1, 2, 3, 4) val numbers = listOf(1, 2, 3, 4)
numbers.map { it.toString() }.foldRightIndexed("") { index, a, b -> a + b + index } numbers.map { it.toString() }.foldRightIndexed("") { index, a, b -> a + b + index }
} }
} }
@test fun foldRightIndexedWithDifferentTypes() { @Test fun foldRightIndexedWithDifferentTypes() {
expect("12343210") { expect("12343210") {
val numbers = listOf(1, 2, 3, 4) val numbers = listOf(1, 2, 3, 4)
numbers.foldRightIndexed("") { index, a, b -> "" + a + b + index } numbers.foldRightIndexed("") { index, a, b -> "" + a + b + index }
} }
} }
@test fun foldRightIndexedWithNonCommutativeOperation() { @Test fun foldRightIndexedWithNonCommutativeOperation() {
expect(-4) { expect(-4) {
val numbers = listOf(1, 2, 3) val numbers = listOf(1, 2, 3)
numbers.foldRightIndexed(7) { index, a, b -> index + a - b } numbers.foldRightIndexed(7) { index, a, b -> index + a - b }
} }
} }
@test fun fold() { @Test fun fold() {
// lets calculate the sum of some numbers // lets calculate the sum of some numbers
expect(10) { expect(10) {
val numbers = listOf(1, 2, 3, 4) val numbers = listOf(1, 2, 3, 4)
@@ -211,7 +211,7 @@ class CollectionTest {
} }
} }
@test fun foldWithDifferentTypes() { @Test fun foldWithDifferentTypes() {
expect(7) { expect(7) {
val numbers = listOf("a", "ab", "abc") val numbers = listOf("a", "ab", "abc")
numbers.fold(1) { a, b -> a + b.length } numbers.fold(1) { a, b -> a + b.length }
@@ -223,49 +223,49 @@ class CollectionTest {
} }
} }
@test fun foldWithNonCommutativeOperation() { @Test fun foldWithNonCommutativeOperation() {
expect(1) { expect(1) {
val numbers = listOf(1, 2, 3) val numbers = listOf(1, 2, 3)
numbers.fold(7) { a, b -> a - b } numbers.fold(7) { a, b -> a - b }
} }
} }
@test fun foldRight() { @Test fun foldRight() {
expect("1234") { expect("1234") {
val numbers = listOf(1, 2, 3, 4) val numbers = listOf(1, 2, 3, 4)
numbers.map { it.toString() }.foldRight("") { a, b -> a + b } numbers.map { it.toString() }.foldRight("") { a, b -> a + b }
} }
} }
@test fun foldRightWithDifferentTypes() { @Test fun foldRightWithDifferentTypes() {
expect("1234") { expect("1234") {
val numbers = listOf(1, 2, 3, 4) val numbers = listOf(1, 2, 3, 4)
numbers.foldRight("") { a, b -> "" + a + b } numbers.foldRight("") { a, b -> "" + a + b }
} }
} }
@test fun foldRightWithNonCommutativeOperation() { @Test fun foldRightWithNonCommutativeOperation() {
expect(-5) { expect(-5) {
val numbers = listOf(1, 2, 3) val numbers = listOf(1, 2, 3)
numbers.foldRight(7) { a, b -> a - b } numbers.foldRight(7) { a, b -> a - b }
} }
} }
@test @Test
fun zipTransform() { fun zipTransform() {
expect(listOf("ab", "bc", "cd")) { expect(listOf("ab", "bc", "cd")) {
listOf("a", "b", "c").zip(listOf("b", "c", "d")) { a, b -> a + b } listOf("a", "b", "c").zip(listOf("b", "c", "d")) { a, b -> a + b }
} }
} }
@test @Test
fun zip() { fun zip() {
expect(listOf("a" to "b", "b" to "c", "c" to "d")) { expect(listOf("a" to "b", "b" to "c", "c" to "d")) {
listOf("a", "b", "c").zip(listOf("b", "c", "d")) listOf("a", "b", "c").zip(listOf("b", "c", "d"))
} }
} }
@test fun partition() { @Test fun partition() {
val data = listOf("foo", "bar", "something", "xyz") val data = listOf("foo", "bar", "something", "xyz")
val pair = data.partition { it.length == 3 } val pair = data.partition { it.length == 3 }
@@ -273,7 +273,7 @@ class CollectionTest {
assertEquals(listOf("something"), pair.second, "pair.second") assertEquals(listOf("something"), pair.second, "pair.second")
} }
@test fun reduceIndexed() { @Test fun reduceIndexed() {
expect("123") { expect("123") {
val list = listOf("1", "2", "3", "4") val list = listOf("1", "2", "3", "4")
list.reduceIndexed { index, a, b -> if (index == 3) a else a + b } list.reduceIndexed { index, a, b -> if (index == 3) a else a + b }
@@ -293,7 +293,7 @@ class CollectionTest {
} }
} }
@test fun reduceRightIndexed() { @Test fun reduceRightIndexed() {
expect("234") { expect("234") {
val list = listOf("1", "2", "3", "4") val list = listOf("1", "2", "3", "4")
list.reduceRightIndexed { index, a, b -> if (index == 0) b else a + b } list.reduceRightIndexed { index, a, b -> if (index == 0) b else a + b }
@@ -313,7 +313,7 @@ class CollectionTest {
} }
} }
@test fun reduce() { @Test fun reduce() {
expect("1234") { expect("1234") {
val list = listOf("1", "2", "3", "4") val list = listOf("1", "2", "3", "4")
list.reduce { a, b -> a + b } list.reduce { a, b -> a + b }
@@ -324,7 +324,7 @@ class CollectionTest {
} }
} }
@test fun reduceRight() { @Test fun reduceRight() {
expect("1234") { expect("1234") {
val list = listOf("1", "2", "3", "4") val list = listOf("1", "2", "3", "4")
list.reduceRight { a, b -> a + b } list.reduceRight { a, b -> a + b }
@@ -335,7 +335,7 @@ class CollectionTest {
} }
} }
@test fun groupBy() { @Test fun groupBy() {
val words = listOf("a", "abc", "ab", "def", "abcd") val words = listOf("a", "abc", "ab", "def", "abcd")
val byLength = words.groupBy { it.length } val byLength = words.groupBy { it.length }
assertEquals(4, byLength.size) assertEquals(4, byLength.size)
@@ -352,7 +352,7 @@ class CollectionTest {
assertEquals(listOf("abc", "def"), l3) assertEquals(listOf("abc", "def"), l3)
} }
@test fun groupByKeysAndValues() { @Test fun groupByKeysAndValues() {
val nameToTeam = listOf("Alice" to "Marketing", "Bob" to "Sales", "Carol" to "Marketing") val nameToTeam = listOf("Alice" to "Marketing", "Bob" to "Sales", "Carol" to "Marketing")
val namesByTeam = nameToTeam.groupBy({ it.second }, { it.first }) val namesByTeam = nameToTeam.groupBy({ it.second }, { it.first })
assertEquals( assertEquals(
@@ -367,14 +367,14 @@ class CollectionTest {
assertEquals(namesByTeam, mutableNamesByTeam) assertEquals(namesByTeam, mutableNamesByTeam)
} }
@test fun plusRanges() { @Test fun plusRanges() {
val range1 = 1..3 val range1 = 1..3
val range2 = 4..7 val range2 = 4..7
val combined = range1 + range2 val combined = range1 + range2
assertEquals((1..7).toList(), combined) assertEquals((1..7).toList(), combined)
} }
@test fun mapRanges() { @Test fun mapRanges() {
val range = (1..3).map { it * 2 } val range = (1..3).map { it * 2 }
assertEquals(listOf(2, 4, 6), range) assertEquals(listOf(2, 4, 6), range)
} }
@@ -386,17 +386,17 @@ class CollectionTest {
assertEquals(listOf("foo", "bar", "cheese", "wine"), list2) assertEquals(listOf("foo", "bar", "cheese", "wine"), list2)
} }
@test fun plusElement() = testPlus { it + "cheese" + "wine" } @Test fun plusElement() = testPlus { it + "cheese" + "wine" }
@test fun plusCollection() = testPlus { it + listOf("cheese", "wine") } @Test fun plusCollection() = testPlus { it + listOf("cheese", "wine") }
@test fun plusArray() = testPlus { it + arrayOf("cheese", "wine") } @Test fun plusArray() = testPlus { it + arrayOf("cheese", "wine") }
@test fun plusSequence() = testPlus { it + sequenceOf("cheese", "wine") } @Test fun plusSequence() = testPlus { it + sequenceOf("cheese", "wine") }
@test fun plusCollectionBug() { @Test fun plusCollectionBug() {
val list = listOf("foo", "bar") + listOf("cheese", "wine") val list = listOf("foo", "bar") + listOf("cheese", "wine")
assertEquals(listOf("foo", "bar", "cheese", "wine"), list) assertEquals(listOf("foo", "bar", "cheese", "wine"), list)
} }
@test fun plusCollectionInference() { @Test fun plusCollectionInference() {
val listOfLists = listOf(listOf("s")) val listOfLists = listOf(listOf("s"))
val elementList = listOf("a") val elementList = listOf("a")
val result: List<List<String>> = listOfLists.plusElement(elementList) val result: List<List<String>> = listOfLists.plusElement(elementList)
@@ -409,7 +409,7 @@ class CollectionTest {
assertEquals(listOf("a", listOf("b")), listOfAnyAndList, "should be list + Any") assertEquals(listOf("a", listOf("b")), listOfAnyAndList, "should be list + Any")
} }
@test fun plusAssign() { @Test fun plusAssign() {
// lets use a mutable variable of readonly list // lets use a mutable variable of readonly list
var l: List<String> = listOf("cheese") var l: List<String> = listOf("cheese")
val lOriginal = l val lOriginal = l
@@ -436,12 +436,12 @@ class CollectionTest {
assertEquals(expected_, b.toList()) assertEquals(expected_, b.toList())
} }
@test fun minusElement() = testMinus(expected = listOf("foo", "bar")) { it - "bar" - "zoo" } @Test fun minusElement() = testMinus(expected = listOf("foo", "bar")) { it - "bar" - "zoo" }
@test fun minusCollection() = testMinus { it - listOf("bar", "zoo") } @Test fun minusCollection() = testMinus { it - listOf("bar", "zoo") }
@test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") } @Test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") }
@test fun minusSequence() = testMinus { it - sequenceOf("bar", "zoo") } @Test fun minusSequence() = testMinus { it - sequenceOf("bar", "zoo") }
@test fun minusIsEager() { @Test fun minusIsEager() {
val source = listOf("foo", "bar") val source = listOf("foo", "bar")
val list = arrayListOf<String>() val list = arrayListOf<String>()
val result = source - list val result = source - list
@@ -452,7 +452,7 @@ class CollectionTest {
assertEquals(source, result) assertEquals(source, result)
} }
@test fun minusAssign() { @Test fun minusAssign() {
// lets use a mutable variable of readonly list // lets use a mutable variable of readonly list
val data: List<String> = listOf("cheese", "foo", "beer", "cheese", "wine") val data: List<String> = listOf("cheese", "foo", "beer", "cheese", "wine")
var l = data var l = data
@@ -475,7 +475,7 @@ class CollectionTest {
@test fun requireNoNulls() { @Test fun requireNoNulls() {
val data = arrayListOf<String?>("foo", "bar") val data = arrayListOf<String?>("foo", "bar")
val notNull = data.requireNoNulls() val notNull = data.requireNoNulls()
assertEquals(listOf("foo", "bar"), notNull) assertEquals(listOf("foo", "bar"), notNull)
@@ -488,7 +488,7 @@ class CollectionTest {
} }
} }
@test fun reverseInPlace() { @Test fun reverseInPlace() {
val data = arrayListOf<String>() val data = arrayListOf<String>()
data.reverse() data.reverse()
assertTrue(data.isEmpty()) assertTrue(data.isEmpty())
@@ -506,7 +506,7 @@ class CollectionTest {
assertEquals(listOf("zoo", "foo", "bar"), data) assertEquals(listOf("zoo", "foo", "bar"), data)
} }
@test fun reversed() { @Test fun reversed() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val rev = data.reversed() val rev = data.reversed()
assertEquals(listOf("bar", "foo"), rev) assertEquals(listOf("bar", "foo"), rev)
@@ -514,18 +514,18 @@ class CollectionTest {
} }
@test fun drop() { @Test fun drop() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(listOf("bar", "abc"), coll.drop(1)) assertEquals(listOf("bar", "abc"), coll.drop(1))
assertEquals(listOf("abc"), coll.drop(2)) assertEquals(listOf("abc"), coll.drop(2))
} }
@test fun dropWhile() { @Test fun dropWhile() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(listOf("bar", "abc"), coll.dropWhile { it.startsWith("f") }) assertEquals(listOf("bar", "abc"), coll.dropWhile { it.startsWith("f") })
} }
@test fun dropLast() { @Test fun dropLast() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(coll, coll.dropLast(0)) assertEquals(coll, coll.dropLast(0))
assertEquals(emptyList<String>(), coll.dropLast(coll.size)) assertEquals(emptyList<String>(), coll.dropLast(coll.size))
@@ -536,7 +536,7 @@ class CollectionTest {
assertFails { coll.dropLast(-1) } assertFails { coll.dropLast(-1) }
} }
@test fun dropLastWhile() { @Test fun dropLastWhile() {
val coll = listOf("Foo", "bare", "abc" ) val coll = listOf("Foo", "bare", "abc" )
assertEquals(coll, coll.dropLastWhile { false }) assertEquals(coll, coll.dropLastWhile { false })
assertEquals(listOf<String>(), coll.dropLastWhile { true }) assertEquals(listOf<String>(), coll.dropLastWhile { true })
@@ -544,7 +544,7 @@ class CollectionTest {
assertEquals(listOf("Foo"), coll.dropLastWhile { it.all { it in 'a'..'z' } }) assertEquals(listOf("Foo"), coll.dropLastWhile { it.all { it in 'a'..'z' } })
} }
@test fun take() { @Test fun take() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(emptyList<String>(), coll.take(0)) assertEquals(emptyList<String>(), coll.take(0))
assertEquals(listOf("foo"), coll.take(1)) assertEquals(listOf("foo"), coll.take(1))
@@ -555,7 +555,7 @@ class CollectionTest {
assertFails { coll.take(-1) } assertFails { coll.take(-1) }
} }
@test fun takeWhile() { @Test fun takeWhile() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(emptyList<String>(), coll.takeWhile { false }) assertEquals(emptyList<String>(), coll.takeWhile { false })
assertEquals(coll, coll.takeWhile { true }) assertEquals(coll, coll.takeWhile { true })
@@ -563,7 +563,7 @@ class CollectionTest {
assertEquals(listOf("foo", "bar", "abc"), coll.takeWhile { it.length == 3 }) assertEquals(listOf("foo", "bar", "abc"), coll.takeWhile { it.length == 3 })
} }
@test fun takeLast() { @Test fun takeLast() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(emptyList<String>(), coll.takeLast(0)) assertEquals(emptyList<String>(), coll.takeLast(0))
@@ -575,7 +575,7 @@ class CollectionTest {
assertFails { coll.takeLast(-1) } assertFails { coll.takeLast(-1) }
} }
@test fun takeLastWhile() { @Test fun takeLastWhile() {
val coll = listOf("foo", "bar", "abc") val coll = listOf("foo", "bar", "abc")
assertEquals(emptyList<String>(), coll.takeLastWhile { false }) assertEquals(emptyList<String>(), coll.takeLastWhile { false })
assertEquals(coll, coll.takeLastWhile { true }) assertEquals(coll, coll.takeLastWhile { true })
@@ -583,21 +583,21 @@ class CollectionTest {
assertEquals(listOf("bar", "abc"), coll.takeLastWhile { it[0] < 'c' }) assertEquals(listOf("bar", "abc"), coll.takeLastWhile { it[0] < 'c' })
} }
@test fun copyToArray() { @Test fun copyToArray() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val arr = data.toTypedArray() val arr = data.toTypedArray()
println("Got array ${arr}") println("Got array ${arr}")
assertEquals(2, arr.size) assertEquals(2, arr.size)
} }
@test fun count() { @Test fun count() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
assertEquals(2, data.count()) assertEquals(2, data.count())
assertEquals(3, hashSetOf(12, 14, 15).count()) assertEquals(3, hashSetOf(12, 14, 15).count())
assertEquals(0, ArrayList<Double>().count()) assertEquals(0, ArrayList<Double>().count())
} }
@test fun first() { @Test fun first() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
assertEquals("foo", data.first()) assertEquals("foo", data.first())
assertEquals(15, listOf(15, 19, 20, 25).first()) assertEquals(15, listOf(15, 19, 20, 25).first())
@@ -605,7 +605,7 @@ class CollectionTest {
assertFails { arrayListOf<Int>().first() } assertFails { arrayListOf<Int>().first() }
} }
@test fun last() { @Test fun last() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
assertEquals("bar", data.last()) assertEquals("bar", data.last())
assertEquals(25, listOf(15, 19, 20, 25).last()) assertEquals(25, listOf(15, 19, 20, 25).last())
@@ -613,7 +613,7 @@ class CollectionTest {
assertFails { arrayListOf<Int>().last() } assertFails { arrayListOf<Int>().last() }
} }
@test fun subscript() { @Test fun subscript() {
val list = arrayListOf("foo", "bar") val list = arrayListOf("foo", "bar")
assertEquals("foo", list[0]) assertEquals("foo", list[0])
assertEquals("bar", list[1]) assertEquals("bar", list[1])
@@ -636,7 +636,7 @@ class CollectionTest {
assertEquals(listOf("new", "thing", "works"), list) assertEquals(listOf("new", "thing", "works"), list)
} }
@test fun indices() { @Test fun indices() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
val indices = data.indices val indices = data.indices
assertEquals(0, indices.start) assertEquals(0, indices.start)
@@ -644,14 +644,14 @@ class CollectionTest {
assertEquals(0..data.size - 1, indices) assertEquals(0..data.size - 1, indices)
} }
@test fun contains() { @Test fun contains() {
assertFalse(hashSetOf<Int>().contains(12)) assertFalse(hashSetOf<Int>().contains(12))
assertTrue(listOf(15, 19, 20).contains(15)) assertTrue(listOf(15, 19, 20).contains(15))
assertTrue(hashSetOf(45, 14, 13).toIterable().contains(14)) assertTrue(hashSetOf(45, 14, 13).toIterable().contains(14))
} }
@test fun min() { @Test fun min() {
expect(null, { listOf<Int>().min() }) expect(null, { listOf<Int>().min() })
expect(1, { listOf(1).min() }) expect(1, { listOf(1).min() })
expect(2, { listOf(2, 3).min() }) expect(2, { listOf(2, 3).min() })
@@ -662,7 +662,7 @@ class CollectionTest {
expect(2, { listOf(2, 3).asSequence().min() }) expect(2, { listOf(2, 3).asSequence().min() })
} }
@test fun max() { @Test fun max() {
expect(null, { listOf<Int>().max() }) expect(null, { listOf<Int>().max() })
expect(1, { listOf(1).max() }) expect(1, { listOf(1).max() })
expect(3, { listOf(2, 3).max() }) expect(3, { listOf(2, 3).max() })
@@ -673,21 +673,21 @@ class CollectionTest {
expect(3, { listOf(2, 3).asSequence().max() }) expect(3, { listOf(2, 3).asSequence().max() })
} }
@test fun minWith() { @Test fun minWith() {
expect(null, { listOf<Int>().minWith(naturalOrder()) }) expect(null, { listOf<Int>().minWith(naturalOrder()) })
expect(1, { listOf(1).minWith(naturalOrder()) }) expect(1, { listOf(1).minWith(naturalOrder()) })
expect("a", { listOf("a", "B").minWith(STRING_CASE_INSENSITIVE_ORDER) }) expect("a", { listOf("a", "B").minWith(STRING_CASE_INSENSITIVE_ORDER) })
expect("a", { listOf("a", "B").asSequence().minWith(STRING_CASE_INSENSITIVE_ORDER) }) expect("a", { listOf("a", "B").asSequence().minWith(STRING_CASE_INSENSITIVE_ORDER) })
} }
@test fun maxWith() { @Test fun maxWith() {
expect(null, { listOf<Int>().maxWith(naturalOrder()) }) expect(null, { listOf<Int>().maxWith(naturalOrder()) })
expect(1, { listOf(1).maxWith(naturalOrder()) }) expect(1, { listOf(1).maxWith(naturalOrder()) })
expect("B", { listOf("a", "B").maxWith(STRING_CASE_INSENSITIVE_ORDER) }) expect("B", { listOf("a", "B").maxWith(STRING_CASE_INSENSITIVE_ORDER) })
expect("B", { listOf("a", "B").asSequence().maxWith(STRING_CASE_INSENSITIVE_ORDER) }) expect("B", { listOf("a", "B").asSequence().maxWith(STRING_CASE_INSENSITIVE_ORDER) })
} }
@test fun minBy() { @Test fun minBy() {
expect(null, { listOf<Int>().minBy { it } }) expect(null, { listOf<Int>().minBy { it } })
expect(1, { listOf(1).minBy { it } }) expect(1, { listOf(1).minBy { it } })
expect(3, { listOf(2, 3).minBy { -it } }) expect(3, { listOf(2, 3).minBy { -it } })
@@ -697,7 +697,7 @@ class CollectionTest {
expect(3, { listOf(2, 3).asSequence().minBy { -it } }) expect(3, { listOf(2, 3).asSequence().minBy { -it } })
} }
@test fun maxBy() { @Test fun maxBy() {
expect(null, { listOf<Int>().maxBy { it } }) expect(null, { listOf<Int>().maxBy { it } })
expect(1, { listOf(1).maxBy { it } }) expect(1, { listOf(1).maxBy { it } })
expect(2, { listOf(2, 3).maxBy { -it } }) expect(2, { listOf(2, 3).maxBy { -it } })
@@ -707,7 +707,7 @@ class CollectionTest {
expect(2, { listOf(2, 3).asSequence().maxBy { -it } }) expect(2, { listOf(2, 3).asSequence().maxBy { -it } })
} }
@test fun minByEvaluateOnce() { @Test fun minByEvaluateOnce() {
var c = 0 var c = 0
expect(1, { listOf(5, 4, 3, 2, 1).minBy { c++; it * it } }) expect(1, { listOf(5, 4, 3, 2, 1).minBy { c++; it * it } })
assertEquals(5, c) assertEquals(5, c)
@@ -716,7 +716,7 @@ class CollectionTest {
assertEquals(5, c) assertEquals(5, c)
} }
@test fun maxByEvaluateOnce() { @Test fun maxByEvaluateOnce() {
var c = 0 var c = 0
expect(5, { listOf(5, 4, 3, 2, 1).maxBy { c++; it * it } }) expect(5, { listOf(5, 4, 3, 2, 1).maxBy { c++; it * it } })
assertEquals(5, c) assertEquals(5, c)
@@ -725,7 +725,7 @@ class CollectionTest {
assertEquals(5, c) assertEquals(5, c)
} }
@test fun sum() { @Test fun sum() {
expect(0) { arrayListOf<Int>().sum() } expect(0) { arrayListOf<Int>().sum() }
expect(14) { listOf(2, 3, 9).sum() } expect(14) { listOf(2, 3, 9).sum() }
expect(3.0) { listOf(1.0, 2.0).sum() } expect(3.0) { listOf(1.0, 2.0).sum() }
@@ -734,7 +734,7 @@ class CollectionTest {
expect(3.0.toFloat()) { sequenceOf<Float>(1.0.toFloat(), 2.0.toFloat()).sum() } expect(3.0.toFloat()) { sequenceOf<Float>(1.0.toFloat(), 2.0.toFloat()).sum() }
} }
@test fun average() { @Test fun average() {
expect(0.0) { arrayListOf<Int>().average() } expect(0.0) { arrayListOf<Int>().average() }
expect(3.8) { listOf(1, 2, 5, 8, 3).average() } expect(3.8) { listOf(1, 2, 5, 8, 3).average() }
expect(2.1) { sequenceOf(1.6, 2.6, 3.6, 0.6).average() } expect(2.1) { sequenceOf(1.6, 2.6, 3.6, 0.6).average() }
@@ -744,7 +744,7 @@ class CollectionTest {
expect(n.toDouble()/2) { range.average() } expect(n.toDouble()/2) { range.average() }
} }
@test fun takeReturnsFirstNElements() { @Test fun takeReturnsFirstNElements() {
expect(listOf(1, 2, 3, 4, 5)) { (1..10).take(5) } expect(listOf(1, 2, 3, 4, 5)) { (1..10).take(5) }
expect(listOf(1, 2, 3, 4, 5)) { (1..10).toList().take(5) } expect(listOf(1, 2, 3, 4, 5)) { (1..10).toList().take(5) }
expect(listOf(1, 2)) { (1..10).take(2) } expect(listOf(1, 2)) { (1..10).take(2) }
@@ -755,7 +755,7 @@ class CollectionTest {
expect(listOf(1)) { listOf(1).take(10) } expect(listOf(1)) { listOf(1).take(10) }
} }
@test fun sortInPlace() { @Test fun sortInPlace() {
val data = listOf(11, 3, 7) val data = listOf(11, 3, 7)
val asc = data.toMutableList() val asc = data.toMutableList()
@@ -767,13 +767,13 @@ class CollectionTest {
assertEquals(listOf(11, 7, 3), desc) assertEquals(listOf(11, 7, 3), desc)
} }
@test fun sorted() { @Test fun sorted() {
val data = listOf(11, 3, 7) val data = listOf(11, 3, 7)
assertEquals(listOf(3, 7, 11), data.sorted()) assertEquals(listOf(3, 7, 11), data.sorted())
assertEquals(listOf(11, 7, 3), data.sortedDescending()) assertEquals(listOf(11, 7, 3), data.sortedDescending())
} }
@test fun sortByInPlace() { @Test fun sortByInPlace() {
val data = arrayListOf("aa" to 20, "ab" to 3, "aa" to 3) val data = arrayListOf("aa" to 20, "ab" to 3, "aa" to 3)
data.sortBy { it.second } data.sortBy { it.second }
assertEquals(listOf("ab" to 3, "aa" to 3, "aa" to 20), data) assertEquals(listOf("ab" to 3, "aa" to 3, "aa" to 20), data)
@@ -785,13 +785,13 @@ class CollectionTest {
assertEquals(listOf("aa" to 20, "aa" to 3, "ab" to 3), data) assertEquals(listOf("aa" to 20, "aa" to 3, "ab" to 3), data)
} }
@test fun sortedBy() { @Test fun sortedBy() {
assertEquals(listOf("two" to 3, "three" to 20), listOf("three" to 20, "two" to 3).sortedBy { it.second }) assertEquals(listOf("two" to 3, "three" to 20), listOf("three" to 20, "two" to 3).sortedBy { it.second })
assertEquals(listOf("three" to 20, "two" to 3), listOf("three" to 20, "two" to 3).sortedBy { it.first }) assertEquals(listOf("three" to 20, "two" to 3), listOf("three" to 20, "two" to 3).sortedBy { it.first })
assertEquals(listOf("three", "two"), listOf("two", "three").sortedByDescending { it.length }) assertEquals(listOf("three", "two"), listOf("two", "three").sortedByDescending { it.length })
} }
@test fun sortedNullableBy() { @Test fun sortedNullableBy() {
fun String.nullIfEmpty() = if (isEmpty()) null else this fun String.nullIfEmpty() = if (isEmpty()) null else this
listOf(null, "", "a").let { listOf(null, "", "a").let {
expect(listOf(null, "", "a")) { it.sortedWith(nullsFirst(compareBy { it })) } expect(listOf(null, "", "a")) { it.sortedWith(nullsFirst(compareBy { it })) }
@@ -800,7 +800,7 @@ class CollectionTest {
} }
} }
@test fun sortedByNullable() { @Test fun sortedByNullable() {
fun String.nonEmptyLength() = if (isEmpty()) null else length fun String.nonEmptyLength() = if (isEmpty()) null else length
listOf("", "sort", "abc").let { listOf("", "sort", "abc").let {
assertEquals(listOf("", "abc", "sort"), it.sortedBy { it.nonEmptyLength() }) assertEquals(listOf("", "abc", "sort"), it.sortedBy { it.nonEmptyLength() })
@@ -809,7 +809,7 @@ class CollectionTest {
} }
} }
@test fun sortedWith() { @Test fun sortedWith() {
val comparator = compareBy<String> { it.toUpperCase().reversed() } val comparator = compareBy<String> { it.toUpperCase().reversed() }
val data = listOf("cat", "dad", "BAD") val data = listOf("cat", "dad", "BAD")
@@ -818,18 +818,18 @@ class CollectionTest {
expect(listOf("BAD", "dad", "cat")) { data.sortedWith(comparator.reversed().reversed()) } expect(listOf("BAD", "dad", "cat")) { data.sortedWith(comparator.reversed().reversed()) }
} }
@test fun decomposeFirst() { @Test fun decomposeFirst() {
val (first) = listOf(1, 2) val (first) = listOf(1, 2)
assertEquals(first, 1) assertEquals(first, 1)
} }
@test fun decomposeSplit() { @Test fun decomposeSplit() {
val (key, value) = "key = value".split("=").map { it.trim() } val (key, value) = "key = value".split("=").map { it.trim() }
assertEquals(key, "key") assertEquals(key, "key")
assertEquals(value, "value") assertEquals(value, "value")
} }
@test fun decomposeList() { @Test fun decomposeList() {
val (a, b, c, d, e) = listOf(1, 2, 3, 4, 5) val (a, b, c, d, e) = listOf(1, 2, 3, 4, 5)
assertEquals(a, 1) assertEquals(a, 1)
assertEquals(b, 2) assertEquals(b, 2)
@@ -838,7 +838,7 @@ class CollectionTest {
assertEquals(e, 5) assertEquals(e, 5)
} }
@test fun decomposeArray() { @Test fun decomposeArray() {
val (a, b, c, d, e) = arrayOf(1, 2, 3, 4, 5) val (a, b, c, d, e) = arrayOf(1, 2, 3, 4, 5)
assertEquals(a, 1) assertEquals(a, 1)
assertEquals(b, 2) assertEquals(b, 2)
@@ -847,7 +847,7 @@ class CollectionTest {
assertEquals(e, 5) assertEquals(e, 5)
} }
@test fun decomposeIntArray() { @Test fun decomposeIntArray() {
val (a, b, c, d, e) = intArrayOf(1, 2, 3, 4, 5) val (a, b, c, d, e) = intArrayOf(1, 2, 3, 4, 5)
assertEquals(a, 1) assertEquals(a, 1)
assertEquals(b, 2) assertEquals(b, 2)
@@ -856,44 +856,44 @@ class CollectionTest {
assertEquals(e, 5) assertEquals(e, 5)
} }
@test fun unzipList() { @Test fun unzipList() {
val list = listOf(1 to 'a', 2 to 'b', 3 to 'c') val list = listOf(1 to 'a', 2 to 'b', 3 to 'c')
val (ints, chars) = list.unzip() val (ints, chars) = list.unzip()
assertEquals(listOf(1, 2, 3), ints) assertEquals(listOf(1, 2, 3), ints)
assertEquals(listOf('a', 'b', 'c'), chars) assertEquals(listOf('a', 'b', 'c'), chars)
} }
@test fun unzipArray() { @Test fun unzipArray() {
val array = arrayOf(1 to 'a', 2 to 'b', 3 to 'c') val array = arrayOf(1 to 'a', 2 to 'b', 3 to 'c')
val (ints, chars) = array.unzip() val (ints, chars) = array.unzip()
assertEquals(listOf(1, 2, 3), ints) assertEquals(listOf(1, 2, 3), ints)
assertEquals(listOf('a', 'b', 'c'), chars) assertEquals(listOf('a', 'b', 'c'), chars)
} }
@test fun specialLists() { @Test fun specialLists() {
compare(arrayListOf<Int>(), listOf<Int>()) { listBehavior() } compare(arrayListOf<Int>(), listOf<Int>()) { listBehavior() }
compare(arrayListOf<Double>(), emptyList<Double>()) { listBehavior() } compare(arrayListOf<Double>(), emptyList<Double>()) { listBehavior() }
compare(arrayListOf("value"), listOf("value")) { listBehavior() } compare(arrayListOf("value"), listOf("value")) { listBehavior() }
} }
@test fun specialSets() { @Test fun specialSets() {
compare(linkedSetOf<Int>(), setOf<Int>()) { setBehavior() } compare(linkedSetOf<Int>(), setOf<Int>()) { setBehavior() }
compare(hashSetOf<Double>(), emptySet<Double>()) { setBehavior() } compare(hashSetOf<Double>(), emptySet<Double>()) { setBehavior() }
compare(listOf("value").toMutableSet(), setOf("value")) { setBehavior() } compare(listOf("value").toMutableSet(), setOf("value")) { setBehavior() }
} }
@test fun specialMaps() { @Test fun specialMaps() {
compare(hashMapOf<String, Int>(), mapOf<String, Int>()) { mapBehavior() } compare(hashMapOf<String, Int>(), mapOf<String, Int>()) { mapBehavior() }
compare(linkedMapOf<Int, String>(), emptyMap<Int, String>()) { mapBehavior() } compare(linkedMapOf<Int, String>(), emptyMap<Int, String>()) { mapBehavior() }
compare(linkedMapOf(2 to 3), mapOf(2 to 3)) { mapBehavior() } compare(linkedMapOf(2 to 3), mapOf(2 to 3)) { mapBehavior() }
} }
@test fun toStringTest() { @Test fun toStringTest() {
// we need toString() inside pattern because of KT-8666 // we need toString() inside pattern because of KT-8666
assertEquals("[1, a, null, ${Long.MAX_VALUE.toString()}]", listOf(1, "a", null, Long.MAX_VALUE).toString()) assertEquals("[1, a, null, ${Long.MAX_VALUE.toString()}]", listOf(1, "a", null, Long.MAX_VALUE).toString())
} }
@test fun randomAccess() { @Test fun randomAccess() {
assertTrue(arrayListOf(1) is RandomAccess, "ArrayList is RandomAccess") assertTrue(arrayListOf(1) is RandomAccess, "ArrayList is RandomAccess")
assertTrue(listOf(1, 2) is RandomAccess, "Default read-only list implementation is RandomAccess") assertTrue(listOf(1, 2) is RandomAccess, "Default read-only list implementation is RandomAccess")
assertTrue(listOf(1) is RandomAccess, "Default singleton list is RandomAccess") assertTrue(listOf(1) is RandomAccess, "Default singleton list is RandomAccess")
@@ -1,13 +1,13 @@
@file:kotlin.jvm.JvmVersion @file:kotlin.jvm.JvmVersion
package test.collections package test.collections
import org.junit.Test as test import org.junit.Test
import kotlin.test.* import kotlin.test.*
import java.util.* import java.util.*
class IteratorsJVMTest { class IteratorsJVMTest {
@test fun testEnumeration() { @Test fun testEnumeration() {
val v = Vector<Int>() val v = Vector<Int>()
for (i in 1..5) for (i in 1..5)
v.add(i) v.add(i)
@@ -1,10 +1,10 @@
package test.collections package test.collections
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class IteratorsTest { class IteratorsTest {
@test fun iterationOverIterator() { @Test fun iterationOverIterator() {
val c = listOf(0, 1, 2, 3, 4, 5) val c = listOf(0, 1, 2, 3, 4, 5)
var s = "" var s = ""
for (i in c.iterator()) { for (i in c.iterator()) {
@@ -6,11 +6,11 @@ import java.util.concurrent.ConcurrentMap
import kotlin.test.assertEquals import kotlin.test.assertEquals
import kotlin.test.assertFails import kotlin.test.assertFails
import kotlin.test.expect import kotlin.test.expect
import org.junit.Test as test import org.junit.Test
import kotlin.comparisons.* import kotlin.comparisons.*
class MapJVMTest { class MapJVMTest {
@test fun createSortedMap() { @Test fun createSortedMap() {
val map = sortedMapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1)) val map = sortedMapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1))
assertEquals(1, map["a"]) assertEquals(1, map["a"])
assertEquals(2, map["b"]) assertEquals(2, map["b"])
@@ -18,7 +18,7 @@ class MapJVMTest {
assertEquals(listOf("a", "b", "c"), map.keys.toList()) assertEquals(listOf("a", "b", "c"), map.keys.toList())
} }
@test fun toSortedMap() { @Test fun toSortedMap() {
val map = mapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1)) val map = mapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1))
val sorted = map.toSortedMap() val sorted = map.toSortedMap()
assertEquals(1, sorted["a"]) assertEquals(1, sorted["a"])
@@ -27,7 +27,7 @@ class MapJVMTest {
assertEquals(listOf("a", "b", "c"), sorted.keys.toList()) assertEquals(listOf("a", "b", "c"), sorted.keys.toList())
} }
@test fun toSortedMapWithComparator() { @Test fun toSortedMapWithComparator() {
val map = mapOf(Pair("c", 3), Pair("bc", 2), Pair("bd", 4), Pair("abc", 1)) 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 }) val sorted = map.toSortedMap(compareBy<String> { it.length }.thenBy { it })
assertEquals(listOf("c", "bc", "bd", "abc"), sorted.keys.toList()) assertEquals(listOf("c", "bc", "bd", "abc"), sorted.keys.toList())
@@ -36,7 +36,7 @@ class MapJVMTest {
assertEquals(3, sorted["c"]) assertEquals(3, sorted["c"])
} }
@test fun toProperties() { @Test fun toProperties() {
val map = mapOf("a" to "A", "b" to "B") val map = mapOf("a" to "A", "b" to "B")
val prop = map.toProperties() val prop = map.toProperties()
assertEquals(2, prop.size) assertEquals(2, prop.size)
@@ -44,7 +44,7 @@ class MapJVMTest {
assertEquals("B", prop.getProperty("b", "fail")) assertEquals("B", prop.getProperty("b", "fail"))
} }
@test fun iterateAndRemove() { @Test fun iterateAndRemove() {
val map = (1..5).associateByTo(linkedMapOf(), { it }, { 'a' + it }) val map = (1..5).associateByTo(linkedMapOf(), { it }, { 'a' + it })
val iterator = map.iterator() val iterator = map.iterator()
while (iterator.hasNext()) { while (iterator.hasNext()) {
@@ -55,7 +55,7 @@ class MapJVMTest {
assertEquals(listOf('b', 'd', 'f'), map.values.toList()) assertEquals(listOf('b', 'd', 'f'), map.values.toList())
} }
@test fun getOrPutFailsOnConcurrentMap() { @Test fun getOrPutFailsOnConcurrentMap() {
val map = ConcurrentHashMap<String, Int>() val map = ConcurrentHashMap<String, Int>()
// not an error anymore // not an error anymore
+45 -45
View File
@@ -1,14 +1,14 @@
package test.collections package test.collections
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class MapTest { class MapTest {
// just a static type check // just a static type check
fun <T> assertStaticTypeIs(value: T) {} fun <T> assertStaticTypeIs(value: T) {}
@test fun getOrElse() { @Test fun getOrElse() {
val data = mapOf<String, Int>() val data = mapOf<String, Int>()
val a = data.getOrElse("foo") { 2 } val a = data.getOrElse("foo") { 2 }
assertEquals(2, a) assertEquals(2, a)
@@ -29,7 +29,7 @@ class MapTest {
} }
@Suppress("INVISIBLE_MEMBER") @Suppress("INVISIBLE_MEMBER")
@test fun getOrImplicitDefault() { @Test fun getOrImplicitDefault() {
val data: MutableMap<String, Int> = hashMapOf("bar" to 1) val data: MutableMap<String, Int> = hashMapOf("bar" to 1)
assertFailsWith<NoSuchElementException> { data.getOrImplicitDefault("foo") } assertFailsWith<NoSuchElementException> { data.getOrImplicitDefault("foo") }
assertEquals(1, data.getOrImplicitDefault("bar")) assertEquals(1, data.getOrImplicitDefault("bar"))
@@ -50,7 +50,7 @@ class MapTest {
assertEquals(42, withReplacedDefault.getOrImplicitDefault("loop")) assertEquals(42, withReplacedDefault.getOrImplicitDefault("loop"))
} }
@test fun getOrPut() { @Test fun getOrPut() {
val data = hashMapOf<String, Int>() val data = hashMapOf<String, Int>()
val a = data.getOrPut("foo") { 2 } val a = data.getOrPut("foo") { 2 }
assertEquals(2, a) assertEquals(2, a)
@@ -68,13 +68,13 @@ class MapTest {
assertEquals(1, d) assertEquals(1, d)
} }
@test fun sizeAndEmpty() { @Test fun sizeAndEmpty() {
val data = hashMapOf<String, Int>() val data = hashMapOf<String, Int>()
assertTrue { data.none() } assertTrue { data.none() }
assertEquals(data.size, 0) assertEquals(data.size, 0)
} }
@test fun setViaIndexOperators() { @Test fun setViaIndexOperators() {
val map = hashMapOf<String, String>() val map = hashMapOf<String, String>()
assertTrue { map.none() } assertTrue { map.none() }
assertEquals(map.size, 0) assertEquals(map.size, 0)
@@ -86,7 +86,7 @@ class MapTest {
assertEquals("James", map["name"]) assertEquals("James", map["name"])
} }
@test fun iterate() { @Test fun iterate() {
val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James") val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James")
val list = arrayListOf<String>() val list = arrayListOf<String>()
for (e in map) { for (e in map) {
@@ -98,13 +98,13 @@ class MapTest {
assertEquals("beverage,beer,location,Mells,name,James", list.joinToString(",")) assertEquals("beverage,beer,location,Mells,name,James", list.joinToString(","))
} }
@test fun stream() { @Test fun stream() {
val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James") val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James")
val named = map.asSequence().filter { it.key == "name" }.single() val named = map.asSequence().filter { it.key == "name" }.single()
assertEquals("James", named.value) assertEquals("James", named.value)
} }
@test fun iterateWithProperties() { @Test fun iterateWithProperties() {
val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James") val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James")
val list = arrayListOf<String>() val list = arrayListOf<String>()
for (e in map) { for (e in map) {
@@ -116,7 +116,7 @@ class MapTest {
assertEquals("beverage,beer,location,Mells,name,James", list.joinToString(",")) assertEquals("beverage,beer,location,Mells,name,James", list.joinToString(","))
} }
@test fun iterateWithExtraction() { @Test fun iterateWithExtraction() {
val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James") val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James")
val list = arrayListOf<String>() val list = arrayListOf<String>()
for ((key, value) in map) { for ((key, value) in map) {
@@ -128,13 +128,13 @@ class MapTest {
assertEquals("beverage,beer,location,Mells,name,James", list.joinToString(",")) assertEquals("beverage,beer,location,Mells,name,James", list.joinToString(","))
} }
@test fun contains() { @Test fun contains() {
val map = mapOf("a" to 1, "b" to 2) val map = mapOf("a" to 1, "b" to 2)
assertTrue("a" in map) assertTrue("a" in map)
assertTrue("c" !in map) assertTrue("c" !in map)
} }
@test fun map() { @Test fun map() {
val m1 = mapOf("beverage" to "beer", "location" to "Mells") val m1 = mapOf("beverage" to "beer", "location" to "Mells")
val list = m1.map { it.value + " rocks" } val list = m1.map { it.value + " rocks" }
@@ -142,13 +142,13 @@ class MapTest {
} }
@test fun mapNotNull() { @Test fun mapNotNull() {
val m1 = mapOf("a" to 1, "b" to null) val m1 = mapOf("a" to 1, "b" to null)
val list = m1.mapNotNull { it.value?.let { v -> "${it.key}$v" } } val list = m1.mapNotNull { it.value?.let { v -> "${it.key}$v" } }
assertEquals(listOf("a1"), list) assertEquals(listOf("a1"), list)
} }
@test fun mapValues() { @Test fun mapValues() {
val m1 = mapOf("beverage" to "beer", "location" to "Mells") val m1 = mapOf("beverage" to "beer", "location" to "Mells")
val m2 = m1.mapValues { it.value + "2" } val m2 = m1.mapValues { it.value + "2" }
@@ -160,7 +160,7 @@ class MapTest {
assertEquals(mapOf("beverage" to 4, "location" to 5), m3) assertEquals(mapOf("beverage" to 4, "location" to 5), m3)
} }
@test fun mapKeys() { @Test fun mapKeys() {
val m1 = mapOf("beverage" to "beer", "location" to "Mells") val m1 = mapOf("beverage" to "beer", "location" to "Mells")
val m2 = m1.mapKeys { it.key + "2" } val m2 = m1.mapKeys { it.key + "2" }
@@ -172,7 +172,7 @@ class MapTest {
assertEquals(mapOf(8 to "Mells"), m3) assertEquals(mapOf(8 to "Mells"), m3)
} }
@test fun createFrom() { @Test fun createFrom() {
val pairs = arrayOf("a" to 1, "b" to 2) val pairs = arrayOf("a" to 1, "b" to 2)
val expected = mapOf(*pairs) val expected = mapOf(*pairs)
@@ -189,7 +189,7 @@ class MapTest {
assertNotEquals(expected, mutableMap) assertNotEquals(expected, mutableMap)
} }
@test fun populateTo() { @Test fun populateTo() {
val pairs = arrayOf("a" to 1, "b" to 2) val pairs = arrayOf("a" to 1, "b" to 2)
val expected = mapOf(*pairs) val expected = mapOf(*pairs)
@@ -209,7 +209,7 @@ class MapTest {
assertEquals<Map<*, *>>(expected, mutableMap3) assertEquals<Map<*, *>>(expected, mutableMap3)
} }
@test fun createWithSelector() { @Test fun createWithSelector() {
val map = listOf("a", "bb", "ccc").associateBy { it.length } val map = listOf("a", "bb", "ccc").associateBy { it.length }
assertEquals(3, map.size) assertEquals(3, map.size)
assertEquals("a", map.get(1)) assertEquals("a", map.get(1))
@@ -217,14 +217,14 @@ class MapTest {
assertEquals("ccc", map.get(3)) assertEquals("ccc", map.get(3))
} }
@test fun createWithSelectorAndOverwrite() { @Test fun createWithSelectorAndOverwrite() {
val map = listOf("aa", "bb", "ccc").associateBy { it.length } val map = listOf("aa", "bb", "ccc").associateBy { it.length }
assertEquals(2, map.size) assertEquals(2, map.size)
assertEquals("bb", map.get(2)) assertEquals("bb", map.get(2))
assertEquals("ccc", map.get(3)) assertEquals("ccc", map.get(3))
} }
@test fun createWithSelectorForKeyAndValue() { @Test fun createWithSelectorForKeyAndValue() {
val map = listOf("a", "bb", "ccc").associateBy({ it.length }, { it.toUpperCase() }) val map = listOf("a", "bb", "ccc").associateBy({ it.length }, { it.toUpperCase() })
assertEquals(3, map.size) assertEquals(3, map.size)
assertEquals("A", map[1]) assertEquals("A", map[1])
@@ -232,7 +232,7 @@ class MapTest {
assertEquals("CCC", map[3]) assertEquals("CCC", map[3])
} }
@test fun createWithPairSelector() { @Test fun createWithPairSelector() {
val map = listOf("a", "bb", "ccc").associate { it.length to it.toUpperCase() } val map = listOf("a", "bb", "ccc").associate { it.length to it.toUpperCase() }
assertEquals(3, map.size) assertEquals(3, map.size)
assertEquals("A", map[1]) assertEquals("A", map[1])
@@ -240,20 +240,20 @@ class MapTest {
assertEquals("CCC", map[3]) assertEquals("CCC", map[3])
} }
@test fun createUsingTo() { @Test fun createUsingTo() {
val map = mapOf("a" to 1, "b" to 2) val map = mapOf("a" to 1, "b" to 2)
assertEquals(2, map.size) assertEquals(2, map.size)
assertEquals(1, map["a"]) assertEquals(1, map["a"])
assertEquals(2, map["b"]) assertEquals(2, map["b"])
} }
@test fun createMutableMap() { @Test fun createMutableMap() {
val map = mutableMapOf("b" to 1, "c" to 2) val map = mutableMapOf("b" to 1, "c" to 2)
map.put("a", 3) map.put("a", 3)
assertEquals(listOf("b" to 1, "c" to 2, "a" to 3), map.toList()) assertEquals(listOf("b" to 1, "c" to 2, "a" to 3), map.toList())
} }
@test fun createLinkedMap() { @Test fun createLinkedMap() {
val map = linkedMapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1)) val map = linkedMapOf(Pair("c", 3), Pair("b", 2), Pair("a", 1))
assertEquals(1, map["a"]) assertEquals(1, map["a"])
assertEquals(2, map["b"]) assertEquals(2, map["b"])
@@ -261,7 +261,7 @@ class MapTest {
assertEquals(listOf("c", "b", "a"), map.keys.toList()) assertEquals(listOf("c", "b", "a"), map.keys.toList())
} }
@test fun filter() { @Test fun filter() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2)) val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
val filteredByKey = map.filter { it.key[0] == 'b' } val filteredByKey = map.filter { it.key[0] == 'b' }
assertEquals(mapOf("b" to 3), filteredByKey) assertEquals(mapOf("b" to 3), filteredByKey)
@@ -276,7 +276,7 @@ class MapTest {
assertEquals(mapOf("a" to 2, "c" to 2), filteredByValue2) assertEquals(mapOf("a" to 2, "c" to 2), filteredByValue2)
} }
@test fun filterOutProjectedTo() { @Test fun filterOutProjectedTo() {
val map: Map<out String, Int> = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2)) val map: Map<out String, Int> = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
val filteredByKey = map.filterTo(mutableMapOf()) { it.key[0] == 'b' } val filteredByKey = map.filterTo(mutableMapOf()) { it.key[0] == 'b' }
@@ -296,7 +296,7 @@ class MapTest {
assertEquals(mapOf("a" to 2, "c" to 2), filteredByValue2) assertEquals(mapOf("a" to 2, "c" to 2), filteredByValue2)
} }
@test fun any() { @Test fun any() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2)) val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
assertTrue(map.any()) assertTrue(map.any())
assertFalse(emptyMap<String, Int>().any()) assertFalse(emptyMap<String, Int>().any())
@@ -308,7 +308,7 @@ class MapTest {
assertFalse(map.any { it.value == 5 }) assertFalse(map.any { it.value == 5 })
} }
@test fun all() { @Test fun all() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2)) val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
assertTrue(map.all { it.key != "d" }) assertTrue(map.all { it.key != "d" })
assertTrue(emptyMap<String, Int>().all { it.key == "d" }) assertTrue(emptyMap<String, Int>().all { it.key == "d" })
@@ -317,7 +317,7 @@ class MapTest {
assertFalse(map.all { it.value == 2 }) assertFalse(map.all { it.value == 2 })
} }
@test fun countBy() { @Test fun countBy() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2)) val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
assertEquals(3, map.count()) assertEquals(3, map.count())
@@ -328,7 +328,7 @@ class MapTest {
assertEquals(2, filteredByValue) assertEquals(2, filteredByValue)
} }
@test fun filterNot() { @Test fun filterNot() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2)) val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
val filteredByKey = map.filterNot { it.key == "b" } val filteredByKey = map.filterNot { it.key == "b" }
assertEquals(2, filteredByKey.size) assertEquals(2, filteredByKey.size)
@@ -350,18 +350,18 @@ class MapTest {
assertEquals(3, map["c"]) assertEquals(3, map["c"])
} }
@test fun plusAssign() = testPlusAssign { @Test fun plusAssign() = testPlusAssign {
it += "b" to 4 it += "b" to 4
it += "c" to 3 it += "c" to 3
} }
@test fun plusAssignList() = testPlusAssign { it += listOf("c" to 3, "b" to 4) } @Test fun plusAssignList() = testPlusAssign { it += listOf("c" to 3, "b" to 4) }
@test fun plusAssignArray() = testPlusAssign { it += arrayOf("c" to 3, "b" to 4) } @Test fun plusAssignArray() = testPlusAssign { it += arrayOf("c" to 3, "b" to 4) }
@test fun plusAssignSequence() = testPlusAssign { it += sequenceOf("c" to 3, "b" to 4) } @Test fun plusAssignSequence() = testPlusAssign { it += sequenceOf("c" to 3, "b" to 4) }
@test fun plusAssignMap() = testPlusAssign { it += mapOf("c" to 3, "b" to 4) } @Test fun plusAssignMap() = testPlusAssign { it += mapOf("c" to 3, "b" to 4) }
fun testPlus(doPlus: (Map<String, Int>) -> Map<String, Int>) { fun testPlus(doPlus: (Map<String, Int>) -> Map<String, Int>) {
val original = mapOf("A" to 1, "B" to 2) val original = mapOf("A" to 1, "B" to 2)
@@ -372,17 +372,17 @@ class MapTest {
assertEquals(3, extended["C"]) assertEquals(3, extended["C"])
} }
@test fun plus() = testPlus { it + ("C" to 3) + ("B" to 4) } @Test fun plus() = testPlus { it + ("C" to 3) + ("B" to 4) }
@test fun plusList() = testPlus { it + listOf("C" to 3, "B" to 4) } @Test fun plusList() = testPlus { it + listOf("C" to 3, "B" to 4) }
@test fun plusArray() = testPlus { it + arrayOf("C" to 3, "B" to 4) } @Test fun plusArray() = testPlus { it + arrayOf("C" to 3, "B" to 4) }
@test fun plusSequence() = testPlus { it + sequenceOf("C" to 3, "B" to 4) } @Test fun plusSequence() = testPlus { it + sequenceOf("C" to 3, "B" to 4) }
@test fun plusMap() = testPlus { it + mapOf("C" to 3, "B" to 4) } @Test fun plusMap() = testPlus { it + mapOf("C" to 3, "B" to 4) }
@test fun plusAny() { @Test fun plusAny() {
testPlusAny(emptyMap<String, String>(), 1 to "A") testPlusAny(emptyMap<String, String>(), 1 to "A")
testPlusAny(mapOf("A" to null), "A" as CharSequence to 2) testPlusAny(mapOf("A" to null), "A" as CharSequence to 2)
} }
@@ -413,13 +413,13 @@ class MapTest {
} }
@test fun plusEmptyList() = testIdempotent { it + listOf() } @Test fun plusEmptyList() = testIdempotent { it + listOf() }
@test fun plusEmptySet() = testIdempotent { it + setOf() } @Test fun plusEmptySet() = testIdempotent { it + setOf() }
@test fun plusAssignEmptyList() = testIdempotentAssign { it += listOf() } @Test fun plusAssignEmptyList() = testIdempotentAssign { it += listOf() }
@test fun plusAssignEmptySet() = testIdempotentAssign { it += setOf() } @Test fun plusAssignEmptySet() = testIdempotentAssign { it += setOf() }
} }
@@ -2,7 +2,7 @@ package test.collections
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class MutableCollectionTest { class MutableCollectionTest {
fun <T, C: MutableCollection<T>> testOperation(before: List<T>, after: List<T>, expectedModified: Boolean, toMutableCollection: (List<T>) -> C) fun <T, C: MutableCollection<T>> testOperation(before: List<T>, after: List<T>, expectedModified: Boolean, toMutableCollection: (List<T>) -> C)
@@ -16,7 +16,7 @@ class MutableCollectionTest {
= testOperation(before, after, expectedModified, { it.toMutableList() }) = testOperation(before, after, expectedModified, { it.toMutableList() })
@test fun addAll() { @Test fun addAll() {
val data = listOf("foo", "bar") val data = listOf("foo", "bar")
testOperation(emptyList(), data, true).let { assertAdd -> testOperation(emptyList(), data, true).let { assertAdd ->
@@ -34,7 +34,7 @@ class MutableCollectionTest {
} }
} }
@test fun removeAll() { @Test fun removeAll() {
val content = listOf("foo", "bar", "bar") val content = listOf("foo", "bar", "bar")
val data = listOf("bar") val data = listOf("bar")
val expected = listOf("foo") val expected = listOf("foo")
@@ -59,7 +59,7 @@ class MutableCollectionTest {
} }
} }
@test fun retainAll() { @Test fun retainAll() {
val content = listOf("foo", "bar", "bar") val content = listOf("foo", "bar", "bar")
val expected = listOf("bar", "bar") val expected = listOf("bar", "bar")
@@ -21,15 +21,15 @@ import test.collections.compare
import kotlin.test.assertEquals import kotlin.test.assertEquals
import kotlin.test.assertFalse import kotlin.test.assertFalse
import kotlin.test.assertTrue import kotlin.test.assertTrue
import org.junit.Test as test import org.junit.Test
class ReversedViewsTest { class ReversedViewsTest {
@test fun testNullToString() { @Test fun testNullToString() {
assertEquals("[null]", listOf<String?>(null).asReversed().toString()) assertEquals("[null]", listOf<String?>(null).asReversed().toString())
} }
@test fun testBehavior() { @Test fun testBehavior() {
val original = listOf(2L, 3L, Long.MAX_VALUE) val original = listOf(2L, 3L, Long.MAX_VALUE)
val reversed = original.reversed() val reversed = original.reversed()
compare(reversed, original.asReversed()) { compare(reversed, original.asReversed()) {
@@ -37,12 +37,12 @@ class ReversedViewsTest {
} }
} }
@test fun testSimple() { @Test fun testSimple() {
assertEquals(listOf(3, 2, 1), listOf(1, 2, 3).asReversed()) assertEquals(listOf(3, 2, 1), listOf(1, 2, 3).asReversed())
assertEquals(listOf(3, 2, 1), listOf(1, 2, 3).asReversed().toList()) assertEquals(listOf(3, 2, 1), listOf(1, 2, 3).asReversed().toList())
} }
@test fun testRandomAccess() { @Test fun testRandomAccess() {
val reversed = listOf(1, 2, 3).asReversed() val reversed = listOf(1, 2, 3).asReversed()
assertEquals(3, reversed[0]) assertEquals(3, reversed[0])
@@ -50,21 +50,21 @@ class ReversedViewsTest {
assertEquals(1, reversed[2]) assertEquals(1, reversed[2])
} }
@test fun testDoubleReverse() { @Test fun testDoubleReverse() {
assertEquals(listOf(1, 2, 3), listOf(1, 2, 3).asReversed().asReversed()) assertEquals(listOf(1, 2, 3), listOf(1, 2, 3).asReversed().asReversed())
assertEquals(listOf(2, 3), listOf(1, 2, 3, 4).asReversed().subList(1, 3).asReversed()) assertEquals(listOf(2, 3), listOf(1, 2, 3, 4).asReversed().subList(1, 3).asReversed())
} }
@test fun testEmpty() { @Test fun testEmpty() {
assertEquals(emptyList<Int>(), emptyList<Int>().asReversed()) assertEquals(emptyList<Int>(), emptyList<Int>().asReversed())
} }
@test fun testReversedSubList() { @Test fun testReversedSubList() {
val reversed = (1..10).toList().asReversed() val reversed = (1..10).toList().asReversed()
assertEquals(listOf(9, 8, 7), reversed.subList(1, 4)) assertEquals(listOf(9, 8, 7), reversed.subList(1, 4))
} }
@test fun testMutableSubList() { @Test fun testMutableSubList() {
val original = arrayListOf(1, 2, 3, 4) val original = arrayListOf(1, 2, 3, 4)
val reversedSubList = original.asReversed().subList(1, 3) val reversedSubList = original.asReversed().subList(1, 3)
@@ -78,26 +78,26 @@ class ReversedViewsTest {
assertEquals(listOf(1, 100, 4), original) assertEquals(listOf(1, 100, 4), original)
} }
@test fun testMutableSimple() { @Test fun testMutableSimple() {
assertEquals(listOf(3, 2, 1), mutableListOf(1, 2, 3).asReversed()) assertEquals(listOf(3, 2, 1), mutableListOf(1, 2, 3).asReversed())
assertEquals(listOf(3, 2, 1), mutableListOf(1, 2, 3).asReversed().toList()) assertEquals(listOf(3, 2, 1), mutableListOf(1, 2, 3).asReversed().toList())
} }
@test fun testMutableDoubleReverse() { @Test fun testMutableDoubleReverse() {
assertEquals(listOf(1, 2, 3), mutableListOf(1, 2, 3).asReversed().asReversed()) assertEquals(listOf(1, 2, 3), mutableListOf(1, 2, 3).asReversed().asReversed())
assertEquals(listOf(2, 3), mutableListOf(1, 2, 3, 4).asReversed().subList(1, 3).asReversed()) assertEquals(listOf(2, 3), mutableListOf(1, 2, 3, 4).asReversed().subList(1, 3).asReversed())
} }
@test fun testMutableEmpty() { @Test fun testMutableEmpty() {
assertEquals(emptyList<Int>(), mutableListOf<Int>().asReversed()) assertEquals(emptyList<Int>(), mutableListOf<Int>().asReversed())
} }
@test fun testMutableReversedSubList() { @Test fun testMutableReversedSubList() {
val reversed = (1..10).toMutableList().asReversed() val reversed = (1..10).toMutableList().asReversed()
assertEquals(listOf(9, 8, 7), reversed.subList(1, 4)) assertEquals(listOf(9, 8, 7), reversed.subList(1, 4))
} }
@test fun testMutableAdd() { @Test fun testMutableAdd() {
val original = mutableListOf(1, 2, 3) val original = mutableListOf(1, 2, 3)
val reversed = original.asReversed() val reversed = original.asReversed()
@@ -110,7 +110,7 @@ class ReversedViewsTest {
assertEquals(listOf(0, 1, 2, 3, 4), original) assertEquals(listOf(0, 1, 2, 3, 4), original)
} }
@test fun testMutableSet() { @Test fun testMutableSet() {
val original = mutableListOf(1, 2, 3) val original = mutableListOf(1, 2, 3)
val reversed = original.asReversed() val reversed = original.asReversed()
@@ -122,7 +122,7 @@ class ReversedViewsTest {
assertEquals(listOf(300, 200, 100), reversed) assertEquals(listOf(300, 200, 100), reversed)
} }
@test fun testMutableRemove() { @Test fun testMutableRemove() {
val original = mutableListOf("a", "b", "c") val original = mutableListOf("a", "b", "c")
val reversed = original.asReversed() val reversed = original.asReversed()
@@ -137,7 +137,7 @@ class ReversedViewsTest {
assertEquals(emptyList<String>(), original) assertEquals(emptyList<String>(), original)
} }
@test fun testMutableRemoveByObj() { @Test fun testMutableRemoveByObj() {
val original = mutableListOf("a", "b", "c") val original = mutableListOf("a", "b", "c")
val reversed = original.asReversed() val reversed = original.asReversed()
@@ -146,7 +146,7 @@ class ReversedViewsTest {
assertEquals(listOf("b", "a"), reversed) assertEquals(listOf("b", "a"), reversed)
} }
@test fun testMutableClear() { @Test fun testMutableClear() {
val original = mutableListOf(1, 2, 3) val original = mutableListOf(1, 2, 3)
val reversed = original.asReversed() val reversed = original.asReversed()
@@ -156,17 +156,17 @@ class ReversedViewsTest {
assertEquals(emptyList<Int>(), original) assertEquals(emptyList<Int>(), original)
} }
@test fun testContains() { @Test fun testContains() {
assertTrue { 1 in listOf(1, 2, 3).asReversed() } assertTrue { 1 in listOf(1, 2, 3).asReversed() }
assertTrue { 1 in mutableListOf(1, 2, 3).asReversed() } assertTrue { 1 in mutableListOf(1, 2, 3).asReversed() }
} }
@test fun testIndexOf() { @Test fun testIndexOf() {
assertEquals(2, listOf(1, 2, 3).asReversed().indexOf(1)) assertEquals(2, listOf(1, 2, 3).asReversed().indexOf(1))
assertEquals(2, mutableListOf(1, 2, 3).asReversed().indexOf(1)) assertEquals(2, mutableListOf(1, 2, 3).asReversed().indexOf(1))
} }
@test fun testBidirectionalModifications() { @Test fun testBidirectionalModifications() {
val original = mutableListOf(1, 2, 3, 4) val original = mutableListOf(1, 2, 3, 4)
val reversed = original.asReversed() val reversed = original.asReversed()
@@ -179,7 +179,7 @@ class ReversedViewsTest {
assertEquals(listOf(3, 2), reversed) assertEquals(listOf(3, 2), reversed)
} }
@test fun testGetIOOB() { @Test fun testGetIOOB() {
val success = try { val success = try {
listOf(1, 2, 3).asReversed().get(3) listOf(1, 2, 3).asReversed().get(3)
true true
@@ -190,7 +190,7 @@ class ReversedViewsTest {
assertFalse(success) assertFalse(success)
} }
@test fun testSetIOOB() { @Test fun testSetIOOB() {
val success = try { val success = try {
mutableListOf(1, 2, 3).asReversed().set(3, 0) mutableListOf(1, 2, 3).asReversed().set(3, 0)
true true
@@ -201,7 +201,7 @@ class ReversedViewsTest {
assertFalse(success) assertFalse(success)
} }
@test fun testAddIOOB() { @Test fun testAddIOOB() {
val success = try { val success = try {
mutableListOf(1, 2, 3).asReversed().add(4, 0) mutableListOf(1, 2, 3).asReversed().add(4, 0)
true true
@@ -212,7 +212,7 @@ class ReversedViewsTest {
assertFalse(success) assertFalse(success)
} }
@test fun testRemoveIOOB() { @Test fun testRemoveIOOB() {
val success = try { val success = try {
mutableListOf(1, 2, 3).asReversed().removeAt(3) mutableListOf(1, 2, 3).asReversed().removeAt(3)
true true
@@ -1,12 +1,12 @@
@file:kotlin.jvm.JvmVersion @file:kotlin.jvm.JvmVersion
package test.collections package test.collections
import org.junit.Test as test import org.junit.Test
import kotlin.test.assertEquals import kotlin.test.assertEquals
class SequenceJVMTest { class SequenceJVMTest {
@test fun filterIsInstance() { @Test fun filterIsInstance() {
val src: Sequence<Any> = listOf(1, 2, 3.toDouble(), "abc", "cde").asSequence() val src: Sequence<Any> = listOf(1, 2, 3.toDouble(), "abc", "cde").asSequence()
val intValues: Sequence<Int> = src.filterIsInstance<Int>() val intValues: Sequence<Int> = src.filterIsInstance<Int>()
@@ -1,6 +1,5 @@
package test.collections package test.collections
import org.junit.Test as test
import org.junit.Test import org.junit.Test
import kotlin.test.* import kotlin.test.*
import kotlin.comparisons.* import kotlin.comparisons.*
@@ -13,20 +12,20 @@ fun fibonacci(): Sequence<Int> {
public class SequenceTest { public class SequenceTest {
@test fun filterEmptySequence() { @Test fun filterEmptySequence() {
for (sequence in listOf(emptySequence<String>(), sequenceOf<String>())) { for (sequence in listOf(emptySequence<String>(), sequenceOf<String>())) {
assertEquals(0, sequence.filter { false }.count()) assertEquals(0, sequence.filter { false }.count())
assertEquals(0, sequence.filter { true }.count()) assertEquals(0, sequence.filter { true }.count())
} }
} }
@test fun mapEmptySequence() { @Test fun mapEmptySequence() {
for (sequence in listOf(emptySequence<String>(), sequenceOf<String>())) { for (sequence in listOf(emptySequence<String>(), sequenceOf<String>())) {
assertEquals(0, sequence.map { true }.count()) assertEquals(0, sequence.map { true }.count())
} }
} }
@test fun requireNoNulls() { @Test fun requireNoNulls() {
val sequence = sequenceOf<String?>("foo", "bar") val sequence = sequenceOf<String?>("foo", "bar")
val notNull = sequence.requireNoNulls() val notNull = sequence.requireNoNulls()
assertEquals(listOf("foo", "bar"), notNull.toList()) assertEquals(listOf("foo", "bar"), notNull.toList())
@@ -39,37 +38,37 @@ public class SequenceTest {
} }
} }
@test fun filterIndexed() { @Test fun filterIndexed() {
assertEquals(listOf(1, 2, 5, 13, 34), fibonacci().filterIndexed { index, value -> index % 2 == 1 }.take(5).toList()) assertEquals(listOf(1, 2, 5, 13, 34), fibonacci().filterIndexed { index, value -> index % 2 == 1 }.take(5).toList())
} }
@test fun filterNullable() { @Test fun filterNullable() {
val data = sequenceOf(null, "foo", null, "bar") val data = sequenceOf(null, "foo", null, "bar")
val filtered = data.filter { it == null || it == "foo" } val filtered = data.filter { it == null || it == "foo" }
assertEquals(listOf(null, "foo", null), filtered.toList()) assertEquals(listOf(null, "foo", null), filtered.toList())
} }
@test fun filterNot() { @Test fun filterNot() {
val data = sequenceOf(null, "foo", null, "bar") val data = sequenceOf(null, "foo", null, "bar")
val filtered = data.filterNot { it == null } val filtered = data.filterNot { it == null }
assertEquals(listOf("foo", "bar"), filtered.toList()) assertEquals(listOf("foo", "bar"), filtered.toList())
} }
@test fun filterNotNull() { @Test fun filterNotNull() {
val data = sequenceOf(null, "foo", null, "bar") val data = sequenceOf(null, "foo", null, "bar")
val filtered = data.filterNotNull() val filtered = data.filterNotNull()
assertEquals(listOf("foo", "bar"), filtered.toList()) assertEquals(listOf("foo", "bar"), filtered.toList())
} }
@test fun mapIndexed() { @Test fun mapIndexed() {
assertEquals(listOf(0, 1, 2, 6, 12), fibonacci().mapIndexed { index, value -> index * value }.takeWhile { i: Int -> i < 20 }.toList()) assertEquals(listOf(0, 1, 2, 6, 12), fibonacci().mapIndexed { index, value -> index * value }.takeWhile { i: Int -> i < 20 }.toList())
} }
@test fun mapNotNull() { @Test fun mapNotNull() {
assertEquals(listOf(0, 10, 110, 1220), fibonacci().mapNotNull { if (it % 5 == 0) it * 2 else null }.take(4).toList()) assertEquals(listOf(0, 10, 110, 1220), fibonacci().mapNotNull { if (it % 5 == 0) it * 2 else null }.take(4).toList())
} }
@test fun mapIndexedNotNull() { @Test fun mapIndexedNotNull() {
// find which terms are divisible by their index // find which terms are divisible by their index
assertEquals(listOf("1/1", "5/5", "144/12", "46368/24", "75025/25"), assertEquals(listOf("1/1", "5/5", "144/12", "46368/24", "75025/25"),
fibonacci().mapIndexedNotNull { index, value -> fibonacci().mapIndexedNotNull { index, value ->
@@ -78,38 +77,38 @@ public class SequenceTest {
} }
@test fun mapAndJoinToString() { @Test fun mapAndJoinToString() {
assertEquals("3, 5, 8", fibonacci().withIndex().filter { it.index > 3 }.take(3).joinToString { it.value.toString() }) assertEquals("3, 5, 8", fibonacci().withIndex().filter { it.index > 3 }.take(3).joinToString { it.value.toString() })
} }
@test fun withIndex() { @Test fun withIndex() {
val data = sequenceOf("foo", "bar") val data = sequenceOf("foo", "bar")
val indexed = data.withIndex().map { it.value.substring(0..it.index) }.toList() val indexed = data.withIndex().map { it.value.substring(0..it.index) }.toList()
assertEquals(listOf("f", "ba"), indexed) assertEquals(listOf("f", "ba"), indexed)
} }
@test fun filterAndTakeWhileExtractTheElementsWithinRange() { @Test fun filterAndTakeWhileExtractTheElementsWithinRange() {
assertEquals(listOf(144, 233, 377, 610, 987), fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.toList()) assertEquals(listOf(144, 233, 377, 610, 987), fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.toList())
} }
@test fun foldReducesTheFirstNElements() { @Test fun foldReducesTheFirstNElements() {
val sum = { a: Int, b: Int -> a + b } val sum = { a: Int, b: Int -> a + b }
assertEquals(listOf(13, 21, 34, 55, 89).fold(0, sum), fibonacci().filter { it > 10 }.take(5).fold(0, sum)) assertEquals(listOf(13, 21, 34, 55, 89).fold(0, sum), fibonacci().filter { it > 10 }.take(5).fold(0, sum))
} }
@test fun takeExtractsTheFirstNElements() { @Test fun takeExtractsTheFirstNElements() {
assertEquals(listOf(0, 1, 1, 2, 3, 5, 8, 13, 21, 34), fibonacci().take(10).toList()) assertEquals(listOf(0, 1, 1, 2, 3, 5, 8, 13, 21, 34), fibonacci().take(10).toList())
} }
@test fun mapAndTakeWhileExtractTheTransformedElements() { @Test fun mapAndTakeWhileExtractTheTransformedElements() {
assertEquals(listOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile { i: Int -> i < 20 }.toList()) assertEquals(listOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile { i: Int -> i < 20 }.toList())
} }
@test fun joinConcatenatesTheFirstNElementsAboveAThreshold() { @Test fun joinConcatenatesTheFirstNElementsAboveAThreshold() {
assertEquals("13, 21, 34, 55, 89, ...", fibonacci().filter { it > 10 }.joinToString(separator = ", ", limit = 5)) assertEquals("13, 21, 34, 55, 89, ...", fibonacci().filter { it > 10 }.joinToString(separator = ", ", limit = 5))
} }
@test fun drop() { @Test fun drop() {
assertEquals(emptyList(), emptySequence<Int>().drop(1).toList()) assertEquals(emptyList(), emptySequence<Int>().drop(1).toList())
listOf(2, 3, 4, 5).let { assertEquals(it, it.asSequence().drop(0).toList()) } listOf(2, 3, 4, 5).let { assertEquals(it, it.asSequence().drop(0).toList()) }
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(7).joinToString(limit = 10)) assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(7).joinToString(limit = 10))
@@ -117,7 +116,7 @@ public class SequenceTest {
assertFailsWith<IllegalArgumentException> { fibonacci().drop(-1) } assertFailsWith<IllegalArgumentException> { fibonacci().drop(-1) }
} }
@test fun take() { @Test fun take() {
assertEquals(emptyList(), emptySequence<Int>().take(1).toList()) assertEquals(emptyList(), emptySequence<Int>().take(1).toList())
assertEquals(emptyList(), fibonacci().take(0).toList()) assertEquals(emptyList(), fibonacci().take(0).toList())
@@ -131,7 +130,7 @@ public class SequenceTest {
assertFailsWith<IllegalArgumentException> { fibonacci().take(-1) } assertFailsWith<IllegalArgumentException> { fibonacci().take(-1) }
} }
@test fun subSequence() { @Test fun subSequence() {
assertEquals(listOf(2, 3, 5, 8), fibonacci().drop(3).take(4).toList()) assertEquals(listOf(2, 3, 5, 8), fibonacci().drop(3).take(4).toList())
assertEquals(listOf(2, 3, 5, 8), fibonacci().take(7).drop(3).toList()) assertEquals(listOf(2, 3, 5, 8), fibonacci().take(7).drop(3).toList())
@@ -145,23 +144,23 @@ public class SequenceTest {
} }
@test fun dropWhile() { @Test fun dropWhile() {
assertEquals("233, 377, 610", fibonacci().dropWhile { it < 200 }.take(3).joinToString(limit = 10)) assertEquals("233, 377, 610", fibonacci().dropWhile { it < 200 }.take(3).joinToString(limit = 10))
assertEquals("", sequenceOf(1).dropWhile { it < 200 }.joinToString(limit = 10)) assertEquals("", sequenceOf(1).dropWhile { it < 200 }.joinToString(limit = 10))
} }
@test fun zip() { @Test fun zip() {
expect(listOf("ab", "bc", "cd")) { expect(listOf("ab", "bc", "cd")) {
sequenceOf("a", "b", "c").zip(sequenceOf("b", "c", "d")) { a, b -> a + b }.toList() sequenceOf("a", "b", "c").zip(sequenceOf("b", "c", "d")) { a, b -> a + b }.toList()
} }
} }
@test fun zipPairs() { @Test fun zipPairs() {
val pairStr = (fibonacci() zip fibonacci().map { i -> i*2 }).joinToString(limit = 10) val pairStr = (fibonacci() zip fibonacci().map { i -> i*2 }).joinToString(limit = 10)
assertEquals("(0, 0), (1, 2), (1, 2), (2, 4), (3, 6), (5, 10), (8, 16), (13, 26), (21, 42), (34, 68), ...", pairStr) assertEquals("(0, 0), (1, 2), (1, 2), (2, 4), (3, 6), (5, 10), (8, 16), (13, 26), (21, 42), (34, 68), ...", pairStr)
} }
@test fun toStringJoinsNoMoreThanTheFirstTenElements() { @Test fun toStringJoinsNoMoreThanTheFirstTenElements() {
assertEquals("0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...", fibonacci().joinToString(limit = 10)) assertEquals("0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...", fibonacci().joinToString(limit = 10))
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().filter { it > 10 }.joinToString(limit = 10)) assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().filter { it > 10 }.joinToString(limit = 10))
assertEquals("144, 233, 377, 610, 987", fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.joinToString()) assertEquals("144, 233, 377, 610, 987", fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.joinToString())
@@ -176,12 +175,12 @@ public class SequenceTest {
} }
@test fun plusElement() = testPlus { it + "cheese" + "wine" } @Test fun plusElement() = testPlus { it + "cheese" + "wine" }
@test fun plusCollection() = testPlus { it + listOf("cheese", "wine") } @Test fun plusCollection() = testPlus { it + listOf("cheese", "wine") }
@test fun plusArray() = testPlus { it + arrayOf("cheese", "wine") } @Test fun plusArray() = testPlus { it + arrayOf("cheese", "wine") }
@test fun plusSequence() = testPlus { it + sequenceOf("cheese", "wine") } @Test fun plusSequence() = testPlus { it + sequenceOf("cheese", "wine") }
@test fun plusAssign() { @Test fun plusAssign() {
// lets use a mutable variable // lets use a mutable variable
var seq = sequenceOf("a") var seq = sequenceOf("a")
seq += "foo" seq += "foo"
@@ -198,12 +197,12 @@ public class SequenceTest {
assertEquals(expected_, b.toList()) assertEquals(expected_, b.toList())
} }
@test fun minusElement() = testMinus(expected = listOf("foo", "bar")) { it - "bar" - "zoo" } @Test fun minusElement() = testMinus(expected = listOf("foo", "bar")) { it - "bar" - "zoo" }
@test fun minusCollection() = testMinus { it - listOf("bar", "zoo") } @Test fun minusCollection() = testMinus { it - listOf("bar", "zoo") }
@test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") } @Test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") }
@test fun minusSequence() = testMinus { it - sequenceOf("bar", "zoo") } @Test fun minusSequence() = testMinus { it - sequenceOf("bar", "zoo") }
@test fun minusIsLazyIterated() { @Test fun minusIsLazyIterated() {
val seq = sequenceOf("foo", "bar") val seq = sequenceOf("foo", "bar")
val list = arrayListOf<String>() val list = arrayListOf<String>()
val result = seq - list val result = seq - list
@@ -214,7 +213,7 @@ public class SequenceTest {
assertEquals(emptyList<String>(), result.toList()) assertEquals(emptyList<String>(), result.toList())
} }
@test fun minusAssign() { @Test fun minusAssign() {
// lets use a mutable variable of readonly list // lets use a mutable variable of readonly list
val data = sequenceOf("cheese", "foo", "beer", "cheese", "wine") val data = sequenceOf("cheese", "foo", "beer", "cheese", "wine")
var l = data var l = data
@@ -229,7 +228,7 @@ public class SequenceTest {
@test fun iterationOverSequence() { @Test fun iterationOverSequence() {
var s = "" var s = ""
for (i in sequenceOf(0, 1, 2, 3, 4, 5)) { for (i in sequenceOf(0, 1, 2, 3, 4, 5)) {
s += i.toString() s += i.toString()
@@ -237,7 +236,7 @@ public class SequenceTest {
assertEquals("012345", s) assertEquals("012345", s)
} }
@test fun sequenceFromFunction() { @Test fun sequenceFromFunction() {
var count = 3 var count = 3
val sequence = generateSequence { val sequence = generateSequence {
@@ -253,7 +252,7 @@ public class SequenceTest {
} }
} }
@test fun sequenceFromFunctionWithInitialValue() { @Test fun sequenceFromFunctionWithInitialValue() {
val values = generateSequence(3) { n -> if (n > 0) n - 1 else null } val values = generateSequence(3) { n -> if (n > 0) n - 1 else null }
val expected = listOf(3, 2, 1, 0) val expected = listOf(3, 2, 1, 0)
assertEquals(expected, values.toList()) assertEquals(expected, values.toList())
@@ -279,7 +278,7 @@ public class SequenceTest {
} }
@test fun sequenceFromIterator() { @Test fun sequenceFromIterator() {
val list = listOf(3, 2, 1, 0) val list = listOf(3, 2, 1, 0)
val iterator = list.iterator() val iterator = list.iterator()
val sequence = iterator.asSequence() val sequence = iterator.asSequence()
@@ -289,7 +288,7 @@ public class SequenceTest {
} }
} }
@test fun makeSequenceOneTimeConstrained() { @Test fun makeSequenceOneTimeConstrained() {
val sequence = sequenceOf(1, 2, 3, 4) val sequence = sequenceOf(1, 2, 3, 4)
sequence.toList() sequence.toList()
sequence.toList() sequence.toList()
@@ -309,13 +308,13 @@ public class SequenceTest {
return result return result
} }
@test fun sequenceExtensions() { @Test fun sequenceExtensions() {
val d = ArrayList<Int>() val d = ArrayList<Int>()
sequenceOf(0, 1, 2, 3, 4, 5).takeWhileTo(d, { i -> i < 4 }) sequenceOf(0, 1, 2, 3, 4, 5).takeWhileTo(d, { i -> i < 4 })
assertEquals(4, d.size) assertEquals(4, d.size)
} }
@test fun flatMapAndTakeExtractTheTransformedElements() { @Test fun flatMapAndTakeExtractTheTransformedElements() {
val expected = listOf( val expected = listOf(
'3', // fibonacci(4) = 3 '3', // fibonacci(4) = 3
'5', // fibonacci(5) = 5 '5', // fibonacci(5) = 5
@@ -329,22 +328,22 @@ public class SequenceTest {
assertEquals(expected, fibonacci().drop(4).flatMap { it.toString().asSequence() }.take(10).toList()) assertEquals(expected, fibonacci().drop(4).flatMap { it.toString().asSequence() }.take(10).toList())
} }
@test fun flatMap() { @Test fun flatMap() {
val result = sequenceOf(1, 2).flatMap { (0..it).asSequence() } val result = sequenceOf(1, 2).flatMap { (0..it).asSequence() }
assertEquals(listOf(0, 1, 0, 1, 2), result.toList()) assertEquals(listOf(0, 1, 0, 1, 2), result.toList())
} }
@test fun flatMapOnEmpty() { @Test fun flatMapOnEmpty() {
val result = sequenceOf<Int>().flatMap { (0..it).asSequence() } val result = sequenceOf<Int>().flatMap { (0..it).asSequence() }
assertTrue(result.none()) assertTrue(result.none())
} }
@test fun flatMapWithEmptyItems() { @Test fun flatMapWithEmptyItems() {
val result = sequenceOf(1, 2, 4).flatMap { if (it == 2) sequenceOf<Int>() else (it - 1..it).asSequence() } val result = sequenceOf(1, 2, 4).flatMap { if (it == 2) sequenceOf<Int>() else (it - 1..it).asSequence() }
assertEquals(listOf(0, 1, 3, 4), result.toList()) assertEquals(listOf(0, 1, 3, 4), result.toList())
} }
@test fun flatten() { @Test fun flatten() {
val expected = listOf(0, 1, 0, 1, 2) val expected = listOf(0, 1, 0, 1, 2)
val seq = sequenceOf((0..1).asSequence(), (0..2).asSequence()).flatten() val seq = sequenceOf((0..1).asSequence(), (0..2).asSequence()).flatten()
@@ -360,31 +359,31 @@ public class SequenceTest {
assertEquals(expected, seqMappedIterable.toList()) assertEquals(expected, seqMappedIterable.toList())
} }
@test fun distinct() { @Test fun distinct() {
val sequence = fibonacci().dropWhile { it < 10 }.take(20) val sequence = fibonacci().dropWhile { it < 10 }.take(20)
assertEquals(listOf(1, 2, 3, 0), sequence.map { it % 4 }.distinct().toList()) assertEquals(listOf(1, 2, 3, 0), sequence.map { it % 4 }.distinct().toList())
} }
@test fun distinctBy() { @Test fun distinctBy() {
val sequence = fibonacci().dropWhile { it < 10 }.take(20) val sequence = fibonacci().dropWhile { it < 10 }.take(20)
assertEquals(listOf(13, 34, 55, 144), sequence.distinctBy { it % 4 }.toList()) assertEquals(listOf(13, 34, 55, 144), sequence.distinctBy { it % 4 }.toList())
} }
@test fun unzip() { @Test fun unzip() {
val seq = sequenceOf(1 to 'a', 2 to 'b', 3 to 'c') val seq = sequenceOf(1 to 'a', 2 to 'b', 3 to 'c')
val (ints, chars) = seq.unzip() val (ints, chars) = seq.unzip()
assertEquals(listOf(1, 2, 3), ints) assertEquals(listOf(1, 2, 3), ints)
assertEquals(listOf('a', 'b', 'c'), chars) assertEquals(listOf('a', 'b', 'c'), chars)
} }
@test fun sorted() { @Test fun sorted() {
sequenceOf(3, 7, 5).let { sequenceOf(3, 7, 5).let {
it.sorted().iterator().assertSorted { a, b -> a <= b } it.sorted().iterator().assertSorted { a, b -> a <= b }
it.sortedDescending().iterator().assertSorted { a, b -> a >= b } it.sortedDescending().iterator().assertSorted { a, b -> a >= b }
} }
} }
@test fun sortedBy() { @Test fun sortedBy() {
sequenceOf("it", "greater", "less").let { sequenceOf("it", "greater", "less").let {
it.sortedBy { it.length }.iterator().assertSorted { a, b -> compareValuesBy(a, b) { it.length } <= 0 } it.sortedBy { it.length }.iterator().assertSorted { a, b -> compareValuesBy(a, b) { it.length } <= 0 }
it.sortedByDescending { it.length }.iterator().assertSorted { a, b -> compareValuesBy(a, b) { it.length } >= 0 } it.sortedByDescending { it.length }.iterator().assertSorted { a, b -> compareValuesBy(a, b) { it.length } >= 0 }
@@ -396,7 +395,7 @@ public class SequenceTest {
} }
} }
@test fun sortedWith() { @Test fun sortedWith() {
val comparator = compareBy { s: String -> s.reversed() } val comparator = compareBy { s: String -> s.reversed() }
assertEquals(listOf("act", "wast", "test"), sequenceOf("act", "test", "wast").sortedWith(comparator).toList()) assertEquals(listOf("act", "wast", "test"), sequenceOf("act", "test", "wast").sortedWith(comparator).toList())
} }
@@ -1,32 +1,32 @@
package test.collections package test.collections
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class SetOperationsTest { class SetOperationsTest {
@test fun distinct() { @Test fun distinct() {
assertEquals(listOf(1, 3, 5), listOf(1, 3, 3, 1, 5, 1, 3).distinct()) assertEquals(listOf(1, 3, 5), listOf(1, 3, 3, 1, 5, 1, 3).distinct())
assertTrue(listOf<Int>().distinct().isEmpty()) assertTrue(listOf<Int>().distinct().isEmpty())
} }
@test fun distinctBy() { @Test fun distinctBy() {
assertEquals(listOf("some", "cat", "do"), arrayOf("some", "case", "cat", "do", "dog", "it").distinctBy { it.length }) assertEquals(listOf("some", "cat", "do"), arrayOf("some", "case", "cat", "do", "dog", "it").distinctBy { it.length })
assertTrue(charArrayOf().distinctBy { it }.isEmpty()) assertTrue(charArrayOf().distinctBy { it }.isEmpty())
} }
@test fun union() { @Test fun union() {
assertEquals(listOf(1, 3, 5), listOf(1, 3).union(listOf(5)).toList()) assertEquals(listOf(1, 3, 5), listOf(1, 3).union(listOf(5)).toList())
assertEquals(listOf(1), listOf<Int>().union(listOf(1)).toList()) assertEquals(listOf(1), listOf<Int>().union(listOf(1)).toList())
} }
@test fun subtract() { @Test fun subtract() {
assertEquals(listOf(1, 3), listOf(1, 3).subtract(listOf(5)).toList()) assertEquals(listOf(1, 3), listOf(1, 3).subtract(listOf(5)).toList())
assertEquals(listOf(1, 3), listOf(1, 3, 5).subtract(listOf(5)).toList()) assertEquals(listOf(1, 3), listOf(1, 3, 5).subtract(listOf(5)).toList())
assertTrue(listOf(1, 3, 5).subtract(listOf(1, 3, 5)).none()) assertTrue(listOf(1, 3, 5).subtract(listOf(1, 3, 5)).none())
assertTrue(listOf<Int>().subtract(listOf(1)).none()) assertTrue(listOf<Int>().subtract(listOf(1)).none())
} }
@test fun intersect() { @Test fun intersect() {
assertTrue(listOf(1, 3).intersect(listOf(5)).none()) assertTrue(listOf(1, 3).intersect(listOf(5)).none())
assertEquals(listOf(5), listOf(1, 3, 5).intersect(listOf(5)).toList()) assertEquals(listOf(5), listOf(1, 3, 5).intersect(listOf(5)).toList())
assertEquals(listOf(1, 3, 5), listOf(1, 3, 5).intersect(listOf(1, 3, 5)).toList()) assertEquals(listOf(1, 3, 5), listOf(1, 3, 5).intersect(listOf(1, 3, 5)).toList())
@@ -40,12 +40,12 @@ class SetOperationsTest {
assertEquals(setOf("foo", "bar", "cheese", "wine"), set2) assertEquals(setOf("foo", "bar", "cheese", "wine"), set2)
} }
@test fun plusElement() = testPlus { it + "bar" + "cheese" + "wine" } @Test fun plusElement() = testPlus { it + "bar" + "cheese" + "wine" }
@test fun plusCollection() = testPlus { it + listOf("bar", "cheese", "wine") } @Test fun plusCollection() = testPlus { it + listOf("bar", "cheese", "wine") }
@test fun plusArray() = testPlus { it + arrayOf("bar", "cheese", "wine") } @Test fun plusArray() = testPlus { it + arrayOf("bar", "cheese", "wine") }
@test fun plusSequence() = testPlus { it + sequenceOf("bar", "cheese", "wine") } @Test fun plusSequence() = testPlus { it + sequenceOf("bar", "cheese", "wine") }
@test fun plusAssign() { @Test fun plusAssign() {
// lets use a mutable variable // lets use a mutable variable
var set = setOf("a") var set = setOf("a")
val setOriginal = set val setOriginal = set
@@ -70,9 +70,9 @@ class SetOperationsTest {
assertEquals(setOf("foo"), b) assertEquals(setOf("foo"), b)
} }
@test fun minusElement() = testMinus { it - "bar" - "zoo" } @Test fun minusElement() = testMinus { it - "bar" - "zoo" }
@test fun minusCollection() = testMinus { it - listOf("bar", "zoo") } @Test fun minusCollection() = testMinus { it - listOf("bar", "zoo") }
@test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") } @Test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") }
@test fun minusSequence() = testMinus { it - sequenceOf("bar", "zoo") } @Test fun minusSequence() = testMinus { it - sequenceOf("bar", "zoo") }
} }
@@ -4,13 +4,13 @@ package test.concurrent
import kotlin.concurrent.* import kotlin.concurrent.*
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
import java.util.concurrent.* import java.util.concurrent.*
import java.util.concurrent.TimeUnit.* import java.util.concurrent.TimeUnit.*
class ThreadTest { class ThreadTest {
@test fun scheduledTask() { @Test fun scheduledTask() {
val pool = Executors.newFixedThreadPool(1) val pool = Executors.newFixedThreadPool(1)
val countDown = CountDownLatch(1) val countDown = CountDownLatch(1)
@@ -20,7 +20,7 @@ class ThreadTest {
assertTrue(countDown.await(2, SECONDS), "Count down is executed") assertTrue(countDown.await(2, SECONDS), "Count down is executed")
} }
@test fun callableInvoke() { @Test fun callableInvoke() {
val pool = Executors.newFixedThreadPool(1) val pool = Executors.newFixedThreadPool(1)
val future = pool.submit<String> { // type specification required here to choose overload for callable, see KT-7882 val future = pool.submit<String> { // type specification required here to choose overload for callable, see KT-7882
@@ -29,7 +29,7 @@ class ThreadTest {
assertEquals("Hello", future.get(2, SECONDS)) assertEquals("Hello", future.get(2, SECONDS))
} }
@test fun threadLocalGetOrSet() { @Test fun threadLocalGetOrSet() {
val v = ThreadLocal<String>() val v = ThreadLocal<String>()
assertEquals("v1", v.getOrSet { "v1" }) assertEquals("v1", v.getOrSet { "v1" })
@@ -7,10 +7,10 @@ import kotlin.test.*
import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicInteger
import java.util.Timer import java.util.Timer
import org.junit.Test as test import org.junit.Test
class TimerTest { class TimerTest {
@test fun scheduledTask() { @Test fun scheduledTask() {
val counter = AtomicInteger(0) val counter = AtomicInteger(0)
val timer = Timer() val timer = Timer()
+27 -27
View File
@@ -3,7 +3,7 @@ package test.io
import java.io.* import java.io.*
import java.util.* import java.util.*
import org.junit.Test as test import org.junit.Test
import kotlin.io.walkTopDown import kotlin.io.walkTopDown
import kotlin.test.* import kotlin.test.*
@@ -13,13 +13,13 @@ class FilesTest {
private val isBackslashSeparator = File.separatorChar == '\\' private val isBackslashSeparator = File.separatorChar == '\\'
@test fun testPath() { @Test fun testPath() {
val fileSuf = System.currentTimeMillis().toString() val fileSuf = System.currentTimeMillis().toString()
val file1 = createTempFile("temp", fileSuf) val file1 = createTempFile("temp", fileSuf)
assertTrue(file1.path.endsWith(fileSuf), file1.path) assertTrue(file1.path.endsWith(fileSuf), file1.path)
} }
@test fun testCreateTempDir() { @Test fun testCreateTempDir() {
val dirSuf = System.currentTimeMillis().toString() val dirSuf = System.currentTimeMillis().toString()
val dir1 = createTempDir("temp", dirSuf) val dir1 = createTempDir("temp", dirSuf)
assertTrue(dir1.exists() && dir1.isDirectory && dir1.name.startsWith("temp") && dir1.name.endsWith(dirSuf)) assertTrue(dir1.exists() && dir1.isDirectory && dir1.name.startsWith("temp") && dir1.name.endsWith(dirSuf))
@@ -38,7 +38,7 @@ class FilesTest {
dir3.delete() dir3.delete()
} }
@test fun testCreateTempFile() { @Test fun testCreateTempFile() {
val fileSuf = System.currentTimeMillis().toString() val fileSuf = System.currentTimeMillis().toString()
val file1 = createTempFile("temp", fileSuf) val file1 = createTempFile("temp", fileSuf)
assertTrue(file1.exists() && file1.name.startsWith("temp") && file1.name.endsWith(fileSuf)) assertTrue(file1.exists() && file1.name.startsWith("temp") && file1.name.endsWith(fileSuf))
@@ -57,7 +57,7 @@ class FilesTest {
file3.delete() file3.delete()
} }
@test fun listFilesWithFilter() { @Test fun listFilesWithFilter() {
val dir = createTempDir("temp") val dir = createTempDir("temp")
createTempFile("temp1", ".kt", dir) createTempFile("temp1", ".kt", dir)
@@ -72,7 +72,7 @@ class FilesTest {
assertEquals(2, result2!!.size) assertEquals(2, result2!!.size)
} }
@test fun relativeToRooted() { @Test fun relativeToRooted() {
val file1 = File("/foo/bar/baz") val file1 = File("/foo/bar/baz")
val file2 = File("/foo/baa/ghoo") val file2 = File("/foo/baa/ghoo")
@@ -116,7 +116,7 @@ class FilesTest {
} }
} }
@test fun relativeToRelative() { @Test fun relativeToRelative() {
val nested = File("foo/bar") val nested = File("foo/bar")
val base = File("foo") val base = File("foo")
@@ -150,7 +150,7 @@ class FilesTest {
} }
} }
@test fun relativeToFails() { @Test fun relativeToFails() {
val absolute = File("/foo/bar/baz") val absolute = File("/foo/bar/baz")
val relative = File("foo/bar") val relative = File("foo/bar")
val networkShare1 = File("""\\my.host\share1/folder""") val networkShare1 = File("""\\my.host\share1/folder""")
@@ -177,7 +177,7 @@ class FilesTest {
} }
} }
@test fun relativeTo() { @Test fun relativeTo() {
assertEquals("kotlin", File("src/kotlin").toRelativeString(File("src"))) assertEquals("kotlin", File("src/kotlin").toRelativeString(File("src")))
assertEquals("", File("dir").toRelativeString(File("dir"))) assertEquals("", File("dir").toRelativeString(File("dir")))
assertEquals("..", File("dir").toRelativeString(File("dir/subdir"))) assertEquals("..", File("dir").toRelativeString(File("dir/subdir")))
@@ -192,7 +192,7 @@ class FilesTest {
assertEquals(elements, components.segments.map { it.toString() }) assertEquals(elements, components.segments.map { it.toString() })
} }
@test fun filePathComponents() { @Test fun filePathComponents() {
checkFilePathComponents(File("/foo/bar"), File("/"), listOf("foo", "bar")) 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("/foo/bar/gav/"), File("/"), listOf("foo", "bar", "gav")) checkFilePathComponents(File("/foo/bar/gav/"), File("/"), listOf("foo", "bar", "gav"))
@@ -213,7 +213,7 @@ class FilesTest {
checkFilePathComponents(File(".."), File(""), listOf("..")) checkFilePathComponents(File(".."), File(""), listOf(".."))
} }
@test fun fileRoot() { @Test fun fileRoot() {
val rooted = File("/foo/bar") val rooted = File("/foo/bar")
assertTrue(rooted.isRooted) assertTrue(rooted.isRooted)
// assertEquals("/", rooted.root.invariantSeparatorsPath) // assertEquals("/", rooted.root.invariantSeparatorsPath)
@@ -233,7 +233,7 @@ class FilesTest {
// assertEquals("", relative.rootName) // assertEquals("", relative.rootName)
} }
@test fun startsWith() { @Test fun startsWith() {
assertTrue(File("foo/bar").startsWith(File("foo/bar"))) assertTrue(File("foo/bar").startsWith(File("foo/bar")))
assertTrue(File("foo/bar").startsWith(File("foo"))) assertTrue(File("foo/bar").startsWith(File("foo")))
assertTrue(File("foo/bar").startsWith("")) assertTrue(File("foo/bar").startsWith(""))
@@ -258,7 +258,7 @@ class FilesTest {
} }
} }
@test fun endsWith() { @Test fun endsWith() {
assertTrue(File("/foo/bar").endsWith("bar")) 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("/foo/bar"))
@@ -277,7 +277,7 @@ class FilesTest {
} }
/* /*
@test fun subPath() { @Test fun subPath() {
if (isBackslashSeparator) { if (isBackslashSeparator) {
// Check only in Windows // 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))
@@ -289,7 +289,7 @@ class FilesTest {
} }
*/ */
@test fun normalize() { @Test fun normalize() {
assertEquals(File("/foo/bar/baaz"), File("/foo/./bar/gav/../baaz").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("/foo/bar/baaz"), File("/foo/bak/../bar/gav/../baaz").normalize())
assertEquals(File("../../bar"), File("../foo/../../bar").normalize()) assertEquals(File("../../bar"), File("../foo/../../bar").normalize())
@@ -302,7 +302,7 @@ class FilesTest {
assertEquals(File("/../foo"), File("/bar/../../foo").normalize()) assertEquals(File("/../foo"), File("/bar/../../foo").normalize())
} }
@test fun resolve() { @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("/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")) assertEquals(File("/gav"), File("/foo/bar").resolve("/gav"))
@@ -322,7 +322,7 @@ class FilesTest {
// assertEquals(File("foo/bar"), File("foo").resolve("./bar")) // assertEquals(File("foo/bar"), File("foo").resolve("./bar"))
} }
@test fun resolveSibling() { @Test fun resolveSibling() {
assertEquals(File("/foo/gav"), File("/foo/bar").resolveSibling("gav")) assertEquals(File("/foo/gav"), File("/foo/bar").resolveSibling("gav"))
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")) assertEquals(File("/gav"), File("/foo/bar").resolveSibling("/gav"))
@@ -337,7 +337,7 @@ class FilesTest {
assertEquals(File("../gav"), File("").resolveSibling("gav")) assertEquals(File("../gav"), File("").resolveSibling("gav"))
} }
@test fun extension() { @Test fun extension() {
assertEquals("bbb", File("aaa.bbb").extension) assertEquals("bbb", File("aaa.bbb").extension)
assertEquals("", File("aaa").extension) assertEquals("", File("aaa").extension)
assertEquals("", File("aaa.").extension) assertEquals("", File("aaa.").extension)
@@ -346,7 +346,7 @@ class FilesTest {
assertEquals("", File("/my.dir/log").extension) assertEquals("", File("/my.dir/log").extension)
} }
@test fun nameWithoutExtension() { @Test fun nameWithoutExtension() {
assertEquals("aaa", File("aaa.bbb").nameWithoutExtension) assertEquals("aaa", File("aaa.bbb").nameWithoutExtension)
assertEquals("aaa", File("aaa").nameWithoutExtension) assertEquals("aaa", File("aaa").nameWithoutExtension)
assertEquals("aaa", File("aaa.").nameWithoutExtension) assertEquals("aaa", File("aaa.").nameWithoutExtension)
@@ -354,7 +354,7 @@ class FilesTest {
assertEquals("log", File("/my.dir/log").nameWithoutExtension) assertEquals("log", File("/my.dir/log").nameWithoutExtension)
} }
@test fun testCopyTo() { @Test fun testCopyTo() {
val srcFile = createTempFile() val srcFile = createTempFile()
val dstFile = createTempFile() val dstFile = createTempFile()
try { try {
@@ -419,7 +419,7 @@ class FilesTest {
} }
} }
@test fun copyToNameWithoutParent() { @Test fun copyToNameWithoutParent() {
val currentDir = File("").absoluteFile!! val currentDir = File("").absoluteFile!!
val srcFile = createTempFile() val srcFile = createTempFile()
val dstFile = createTempFile(directory = currentDir) val dstFile = createTempFile(directory = currentDir)
@@ -439,7 +439,7 @@ class FilesTest {
} }
} }
@test fun deleteRecursively() { @Test fun deleteRecursively() {
val dir = createTempDir() val dir = createTempDir()
dir.delete() dir.delete()
dir.mkdir() dir.mkdir()
@@ -453,7 +453,7 @@ class FilesTest {
assertTrue(dir.deleteRecursively()) assertTrue(dir.deleteRecursively())
} }
@test fun deleteRecursivelyWithFail() { @Test fun deleteRecursivelyWithFail() {
val basedir = FileTreeWalkTest.createTestFiles() val basedir = FileTreeWalkTest.createTestFiles()
val restricted = File(basedir, "1") val restricted = File(basedir, "1")
try { try {
@@ -491,7 +491,7 @@ class FilesTest {
} }
} }
@test fun copyRecursively() { @Test fun copyRecursively() {
val src = createTempDir() val src = createTempDir()
val dst = createTempDir() val dst = createTempDir()
dst.delete() dst.delete()
@@ -562,7 +562,7 @@ class FilesTest {
} }
} }
@test fun copyRecursivelyWithOverwrite() { @Test fun copyRecursivelyWithOverwrite() {
val src = createTempDir() val src = createTempDir()
val dst = createTempDir() val dst = createTempDir()
fun check() = compareDirectories(src, dst) fun check() = compareDirectories(src, dst)
@@ -596,7 +596,7 @@ class FilesTest {
} }
} }
@test fun helpers1() { @Test fun helpers1() {
val str = "123456789\n" val str = "123456789\n"
System.setIn(str.byteInputStream()) System.setIn(str.byteInputStream())
val reader = System.`in`.bufferedReader() val reader = System.`in`.bufferedReader()
@@ -607,7 +607,7 @@ class FilesTest {
assertEquals('3', stringReader.read().toChar()) assertEquals('3', stringReader.read().toChar())
} }
@test fun helpers2() { @Test fun helpers2() {
val file = createTempFile() val file = createTempFile()
val writer = file.printWriter() val writer = file.printWriter()
val str1 = "Hello, world!" val str1 = "Hello, world!"
+3 -3
View File
@@ -1,13 +1,13 @@
@file:kotlin.jvm.JvmVersion @file:kotlin.jvm.JvmVersion
package test.io package test.io
import org.junit.Test as test import org.junit.Test
import kotlin.test.* import kotlin.test.*
import java.io.Writer import java.io.Writer
import java.io.BufferedReader import java.io.BufferedReader
class IOStreamsTest { class IOStreamsTest {
@test fun testGetStreamOfFile() { @Test fun testGetStreamOfFile() {
val tmpFile = createTempFile() val tmpFile = createTempFile()
var writer: Writer? = null var writer: Writer? = null
try { try {
@@ -27,7 +27,7 @@ class IOStreamsTest {
assertEquals("Hello, World!", act) assertEquals("Hello, World!", act)
} }
@test fun testInputStreamIterator() { @Test fun testInputStreamIterator() {
val x = ByteArray(10) { it.toByte() } val x = ByteArray(10) { it.toByte() }
val result = mutableListOf<Byte>() val result = mutableListOf<Byte>()
+10 -10
View File
@@ -1,7 +1,7 @@
@file:kotlin.jvm.JvmVersion @file:kotlin.jvm.JvmVersion
package test.io package test.io
import org.junit.Test as test import org.junit.Test
import java.io.File import java.io.File
import kotlin.test.assertEquals import kotlin.test.assertEquals
import java.io.Reader import java.io.Reader
@@ -14,7 +14,7 @@ import kotlin.test.assertTrue
fun sample(): Reader = StringReader("Hello\nWorld"); fun sample(): Reader = StringReader("Hello\nWorld");
class ReadWriteTest { class ReadWriteTest {
@test fun testAppendText() { @Test fun testAppendText() {
val file = File.createTempFile("temp", System.nanoTime().toString()) val file = File.createTempFile("temp", System.nanoTime().toString())
file.writeText("Hello\n") file.writeText("Hello\n")
file.appendText("World\n") file.appendText("World\n")
@@ -25,7 +25,7 @@ class ReadWriteTest {
file.deleteOnExit() file.deleteOnExit()
} }
@test fun reader() { @Test fun reader() {
val list = ArrayList<String>() val list = ArrayList<String>()
/* TODO would be nicer maybe to write this as /* TODO would be nicer maybe to write this as
@@ -71,7 +71,7 @@ class ReadWriteTest {
assertEquals(2, c) assertEquals(2, c)
} }
@test fun file() { @Test fun file() {
val file = File.createTempFile("temp", System.nanoTime().toString()) val file = File.createTempFile("temp", System.nanoTime().toString())
val writer = file.outputStream().writer().buffered() val writer = file.outputStream().writer().buffered()
@@ -125,7 +125,7 @@ class ReadWriteTest {
@test fun testUse() { @Test fun testUse() {
val list = ArrayList<String>() val list = ArrayList<String>()
val reader = sample().buffered() val reader = sample().buffered()
@@ -142,7 +142,7 @@ class ReadWriteTest {
assertEquals(arrayListOf("Hello", "World"), list) assertEquals(arrayListOf("Hello", "World"), list)
} }
@test fun testPlatformNullUse() { @Test fun testPlatformNullUse() {
fun <T> platformNull() = java.util.Collections.singleton(null as T).first() fun <T> platformNull() = java.util.Collections.singleton(null as T).first()
val resource = platformNull<java.io.Closeable>() val resource = platformNull<java.io.Closeable>()
val result = resource.use { val result = resource.use {
@@ -151,7 +151,7 @@ class ReadWriteTest {
assertEquals("ok", result) assertEquals("ok", result)
} }
@test fun testURL() { @Test fun testURL() {
val url = URL("http://kotlinlang.org") val url = URL("http://kotlinlang.org")
val text = url.readText() val text = url.readText()
assertFalse(text.isEmpty()) assertFalse(text.isEmpty())
@@ -162,7 +162,7 @@ class ReadWriteTest {
class LineIteratorTest { class LineIteratorTest {
@test fun useLines() { @Test fun useLines() {
// TODO we should maybe zap the useLines approach as it encourages // TODO we should maybe zap the useLines approach as it encourages
// use of iterators which don't close the underlying stream // use of iterators which don't close the underlying stream
val list1 = sample().useLines { it.toList() } val list1 = sample().useLines { it.toList() }
@@ -172,7 +172,7 @@ class LineIteratorTest {
assertEquals(listOf("Hello", "World"), list2) assertEquals(listOf("Hello", "World"), list2)
} }
@test fun manualClose() { @Test fun manualClose() {
val reader = sample().buffered() val reader = sample().buffered()
try { try {
val list = reader.lineSequence().toList() val list = reader.lineSequence().toList()
@@ -182,7 +182,7 @@ class LineIteratorTest {
} }
} }
@test fun boundaryConditions() { @Test fun boundaryConditions() {
var reader = StringReader("").buffered() var reader = StringReader("").buffered()
assertEquals(emptyList(), reader.lineSequence().toList()) assertEquals(emptyList(), reader.lineSequence().toList())
reader.close() reader.close()
+3 -3
View File
@@ -16,12 +16,12 @@
package test.collections.js package test.collections.js
import org.junit.Test as test import org.junit.Test
import kotlin.test.* import kotlin.test.*
class JsArrayTest { class JsArrayTest {
@test fun arraySizeAndToList() { @Test fun arraySizeAndToList() {
val a1 = arrayOf<String>() val a1 = arrayOf<String>()
val a2 = arrayOf("foo") val a2 = arrayOf("foo")
val a3 = arrayOf("foo", "bar") val a3 = arrayOf("foo", "bar")
@@ -36,7 +36,7 @@ class JsArrayTest {
} }
@test fun arrayListFromCollection() { @Test fun arrayListFromCollection() {
var c: Collection<String> = arrayOf("A", "B", "C").toList() var c: Collection<String> = arrayOf("A", "B", "C").toList()
var a = ArrayList(c) var a = ArrayList(c)
+11 -11
View File
@@ -2,53 +2,53 @@ package test.collections.js
import kotlin.test.* import kotlin.test.*
import kotlin.comparisons.* import kotlin.comparisons.*
import org.junit.Test as test import org.junit.Test
class JsCollectionsTest { class JsCollectionsTest {
val TEST_LIST = arrayOf(2, 0, 9, 7, 1).toList() val TEST_LIST = arrayOf(2, 0, 9, 7, 1).toList()
@test fun collectionToArray() { @Test fun collectionToArray() {
val array = TEST_LIST.toTypedArray() val array = TEST_LIST.toTypedArray()
assertEquals(array.toList(), TEST_LIST) assertEquals(array.toList(), TEST_LIST)
} }
@test fun toListDoesNotCreateArrayView() { @Test fun toListDoesNotCreateArrayView() {
snapshotDoesNotCreateView(arrayOf("first", "last"), { it.toList() }) snapshotDoesNotCreateView(arrayOf("first", "last"), { it.toList() })
snapshotDoesNotCreateView(arrayOf<Any>("item", 1), { it.toList() }) snapshotDoesNotCreateView(arrayOf<Any>("item", 1), { it.toList() })
} }
@test fun toMutableListDoesNotCreateArrayView() { @Test fun toMutableListDoesNotCreateArrayView() {
snapshotDoesNotCreateView(arrayOf("first", "last"), { it.toMutableList() }) snapshotDoesNotCreateView(arrayOf("first", "last"), { it.toMutableList() })
snapshotDoesNotCreateView(arrayOf<Any>("item", 2), { it.toMutableList() }) snapshotDoesNotCreateView(arrayOf<Any>("item", 2), { it.toMutableList() })
} }
@test fun listOfDoesNotCreateView() { @Test fun listOfDoesNotCreateView() {
snapshotDoesNotCreateView(arrayOf("first", "last"), { listOf(*it) }) snapshotDoesNotCreateView(arrayOf("first", "last"), { listOf(*it) })
snapshotDoesNotCreateView(arrayOf<Any>("item", 3), { listOf(*it) }) snapshotDoesNotCreateView(arrayOf<Any>("item", 3), { listOf(*it) })
} }
@test fun mutableListOfDoesNotCreateView() { @Test fun mutableListOfDoesNotCreateView() {
snapshotDoesNotCreateView(arrayOf("first", "last"), { mutableListOf(*it) }) snapshotDoesNotCreateView(arrayOf("first", "last"), { mutableListOf(*it) })
snapshotDoesNotCreateView(arrayOf<Any>("item", 4), { mutableListOf(*it) }) snapshotDoesNotCreateView(arrayOf<Any>("item", 4), { mutableListOf(*it) })
} }
@test fun arrayListDoesNotCreateArrayView() { @Test fun arrayListDoesNotCreateArrayView() {
snapshotDoesNotCreateView(arrayOf(1, 2), { arrayListOf(*it) }) snapshotDoesNotCreateView(arrayOf(1, 2), { arrayListOf(*it) })
snapshotDoesNotCreateView(arrayOf<Any>("first", "last"), { arrayListOf(*it) }) snapshotDoesNotCreateView(arrayOf<Any>("first", "last"), { arrayListOf(*it) })
} }
@test fun arrayListCapacity() { @Test fun arrayListCapacity() {
val list = ArrayList<Any>(20) val list = ArrayList<Any>(20)
list.ensureCapacity(100) list.ensureCapacity(100)
list.trimToSize() list.trimToSize()
assertTrue(list.isEmpty()) assertTrue(list.isEmpty())
} }
@test fun listEqualsOperatesOnAny() { @Test fun listEqualsOperatesOnAny() {
assertFalse(listOf(1, 2, 3).equals(object {})) assertFalse(listOf(1, 2, 3).equals(object {}))
} }
@test fun arrayListValidatesIndexRange() { @Test fun arrayListValidatesIndexRange() {
val list = mutableListOf(1) val list = mutableListOf(1)
for (index in listOf(-1, 1, 3)) { for (index in listOf(-1, 1, 3)) {
if (index != list.size) { // size is a valid position index if (index != list.size) { // size is a valid position index
@@ -63,7 +63,7 @@ class JsCollectionsTest {
assertEquals(listOf(1), list) assertEquals(listOf(1), list)
} }
@test fun mutableIteratorRemove() { @Test fun mutableIteratorRemove() {
val a = mutableListOf(1, 2, 3) val a = mutableListOf(1, 2, 3)
val it = a.iterator() val it = a.iterator()
assertFailsWith<IllegalStateException> { it.remove() } assertFailsWith<IllegalStateException> { it.remove() }
+37 -37
View File
@@ -1,7 +1,7 @@
package test.collections.js package test.collections.js
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
import test.collections.* import test.collections.*
import test.collections.behaviors.* import test.collections.behaviors.*
@@ -17,7 +17,7 @@ class ComplexMapJsTest : MapJsTest() {
assertEquals(VALUES.toNormalizedList(), map.values.toNormalizedList()) assertEquals(VALUES.toNormalizedList(), map.values.toNormalizedList())
} }
@test override fun constructors() { @Test override fun constructors() {
doTest<String>() doTest<String>()
} }
@@ -28,7 +28,7 @@ class ComplexMapJsTest : MapJsTest() {
} }
class PrimitiveMapJsTest : MapJsTest() { class PrimitiveMapJsTest : MapJsTest() {
@test override fun constructors() { @Test override fun constructors() {
HashMap<String, Int>() HashMap<String, Int>()
HashMap<String, Int>(3) HashMap<String, Int>(3)
HashMap<String, Int>(3, 0.5f) HashMap<String, Int>(3, 0.5f)
@@ -43,7 +43,7 @@ class PrimitiveMapJsTest : MapJsTest() {
override fun emptyMutableMap(): MutableMap<String, Int> = stringMapOf() override fun emptyMutableMap(): MutableMap<String, Int> = stringMapOf()
override fun emptyMutableMapWithNullableKeyValue(): MutableMap<String?, Int?> = HashMap() override fun emptyMutableMapWithNullableKeyValue(): MutableMap<String?, Int?> = HashMap()
@test fun compareBehavior() { @Test fun compareBehavior() {
val specialJsStringMap = HashMap<String, Any>() val specialJsStringMap = HashMap<String, Any>()
specialJsStringMap.put("k1", "v1") specialJsStringMap.put("k1", "v1")
compare(genericHashMapOf("k1" to "v1"), specialJsStringMap) { mapBehavior() } compare(genericHashMapOf("k1" to "v1"), specialJsStringMap) { mapBehavior() }
@@ -55,7 +55,7 @@ class PrimitiveMapJsTest : MapJsTest() {
} }
class LinkedHashMapJsTest : MapJsTest() { class LinkedHashMapJsTest : MapJsTest() {
@test override fun constructors() { @Test override fun constructors() {
LinkedHashMap<String, Int>() LinkedHashMap<String, Int>()
LinkedHashMap<String, Int>(3) LinkedHashMap<String, Int>(3)
LinkedHashMap<String, Int>(3, 0.5f) LinkedHashMap<String, Int>(3, 0.5f)
@@ -72,7 +72,7 @@ class LinkedHashMapJsTest : MapJsTest() {
} }
class LinkedPrimitiveMapJsTest : MapJsTest() { class LinkedPrimitiveMapJsTest : MapJsTest() {
@test override fun constructors() { @Test override fun constructors() {
val map = createTestMap() val map = createTestMap()
assertEquals(KEYS.toNormalizedList(), map.keys.toNormalizedList()) assertEquals(KEYS.toNormalizedList(), map.keys.toNormalizedList())
@@ -90,7 +90,7 @@ abstract class MapJsTest {
val SPECIAL_NAMES = arrayOf("__proto__", "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable") val SPECIAL_NAMES = arrayOf("__proto__", "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable")
@test fun getOrElse() { @Test fun getOrElse() {
val data = emptyMap() val data = emptyMap()
val a = data.getOrElse("foo"){2} val a = data.getOrElse("foo"){2}
assertEquals(2, a) assertEquals(2, a)
@@ -100,7 +100,7 @@ abstract class MapJsTest {
assertEquals(0, data.size) assertEquals(0, data.size)
} }
@test fun getOrPut() { @Test fun getOrPut() {
val data = emptyMutableMap() val data = emptyMutableMap()
val a = data.getOrPut("foo"){2} val a = data.getOrPut("foo"){2}
assertEquals(2, a) assertEquals(2, a)
@@ -111,13 +111,13 @@ abstract class MapJsTest {
assertEquals(1, data.size) assertEquals(1, data.size)
} }
@test fun emptyMapGet() { @Test fun emptyMapGet() {
val map = emptyMap() val map = emptyMap()
assertEquals(null, map.get("foo"), """failed on map.get("foo")""") assertEquals(null, map.get("foo"), """failed on map.get("foo")""")
assertEquals(null, map["bar"], """failed on map["bar"]""") assertEquals(null, map["bar"], """failed on map["bar"]""")
} }
@test fun mapGet() { @Test fun mapGet() {
val map = createTestMap() val map = createTestMap()
for (i in KEYS.indices) { for (i in KEYS.indices) {
assertEquals(VALUES[i], map.get(KEYS[i]), """failed on map.get(KEYS[$i])""") assertEquals(VALUES[i], map.get(KEYS[i]), """failed on map.get(KEYS[$i])""")
@@ -127,7 +127,7 @@ abstract class MapJsTest {
assertEquals(null, map.get("foo")) assertEquals(null, map.get("foo"))
} }
@test fun mapPut() { @Test fun mapPut() {
val map = emptyMutableMap() val map = emptyMutableMap()
map.put("foo", 1) map.put("foo", 1)
@@ -143,7 +143,7 @@ abstract class MapJsTest {
assertEquals(2, map["bar"]) assertEquals(2, map["bar"])
} }
@test fun sizeAndEmptyForEmptyMap() { @Test fun sizeAndEmptyForEmptyMap() {
val data = emptyMap() val data = emptyMap()
assertTrue(data.isEmpty()) assertTrue(data.isEmpty())
@@ -153,7 +153,7 @@ abstract class MapJsTest {
assertEquals(0, data.size) assertEquals(0, data.size)
} }
@test fun sizeAndEmpty() { @Test fun sizeAndEmpty() {
val data = createTestMap() val data = createTestMap()
assertFalse(data.isEmpty()) assertFalse(data.isEmpty())
@@ -163,22 +163,22 @@ abstract class MapJsTest {
} }
// #KT-3035 // #KT-3035
@test fun emptyMapValues() { @Test fun emptyMapValues() {
val emptyMap = emptyMap() val emptyMap = emptyMap()
assertTrue(emptyMap.values.isEmpty()) assertTrue(emptyMap.values.isEmpty())
} }
@test fun mapValues() { @Test fun mapValues() {
val map = createTestMap() val map = createTestMap()
assertEquals(VALUES.toNormalizedList(), map.values.toNormalizedList()) assertEquals(VALUES.toNormalizedList(), map.values.toNormalizedList())
} }
@test fun mapKeySet() { @Test fun mapKeySet() {
val map = createTestMap() val map = createTestMap()
assertEquals(KEYS.toNormalizedList(), map.keys.toNormalizedList()) assertEquals(KEYS.toNormalizedList(), map.keys.toNormalizedList())
} }
@test fun mapEntrySet() { @Test fun mapEntrySet() {
val map = createTestMap() val map = createTestMap()
val actualKeys = ArrayList<String>() val actualKeys = ArrayList<String>()
@@ -192,7 +192,7 @@ abstract class MapJsTest {
assertEquals(VALUES.toNormalizedList(), actualValues.toNormalizedList()) assertEquals(VALUES.toNormalizedList(), actualValues.toNormalizedList())
} }
@test fun mapContainsKey() { @Test fun mapContainsKey() {
val map = createTestMap() val map = createTestMap()
assertTrue(map.containsKey(KEYS[0]) && assertTrue(map.containsKey(KEYS[0]) &&
@@ -204,7 +204,7 @@ abstract class MapJsTest {
map.containsKey(1 as Any)) map.containsKey(1 as Any))
} }
@test fun mapContainsValue() { @Test fun mapContainsValue() {
val map = createTestMap() val map = createTestMap()
assertTrue(map.containsValue(VALUES[0]) && assertTrue(map.containsValue(VALUES[0]) &&
@@ -216,20 +216,20 @@ abstract class MapJsTest {
map.containsValue(5)) map.containsValue(5))
} }
@test fun mapPutAll() { @Test fun mapPutAll() {
val map = createTestMap() val map = createTestMap()
val newMap = emptyMutableMap() val newMap = emptyMutableMap()
newMap.putAll(map) newMap.putAll(map)
assertEquals(KEYS.size, newMap.size) assertEquals(KEYS.size, newMap.size)
} }
@test fun mapPutAllFromCustomMap() { @Test fun mapPutAllFromCustomMap() {
val newMap = emptyMutableMap() val newMap = emptyMutableMap()
newMap.putAll(ConstMap) newMap.putAll(ConstMap)
assertEquals(ConstMap.entries.single().toPair(), newMap.entries.single().toPair()) assertEquals(ConstMap.entries.single().toPair(), newMap.entries.single().toPair())
} }
@test fun mapRemove() { @Test fun mapRemove() {
val map = createTestMutableMap() val map = createTestMutableMap()
val last = KEYS.size - 1 val last = KEYS.size - 1
val first = 0 val first = 0
@@ -246,14 +246,14 @@ abstract class MapJsTest {
assertEquals(KEYS.size - 3, map.size) assertEquals(KEYS.size - 3, map.size)
} }
@test fun mapClear() { @Test fun mapClear() {
val map = createTestMutableMap() val map = createTestMutableMap()
assertFalse(map.isEmpty()) assertFalse(map.isEmpty())
map.clear() map.clear()
assertTrue(map.isEmpty()) assertTrue(map.isEmpty())
} }
@test fun nullAsKey() { @Test fun nullAsKey() {
val map = emptyMutableMapWithNullableKeyValue() val map = emptyMutableMapWithNullableKeyValue()
assertTrue(map.isEmpty()) assertTrue(map.isEmpty())
@@ -266,7 +266,7 @@ abstract class MapJsTest {
assertEquals(null, map[null]) assertEquals(null, map[null])
} }
@test fun nullAsValue() { @Test fun nullAsValue() {
val map = emptyMutableMapWithNullableKeyValue() val map = emptyMutableMapWithNullableKeyValue()
val KEY = "Key" val KEY = "Key"
@@ -279,7 +279,7 @@ abstract class MapJsTest {
assertTrue(map.isEmpty()) assertTrue(map.isEmpty())
} }
@test fun setViaIndexOperators() { @Test fun setViaIndexOperators() {
val map = HashMap<String, String>() val map = HashMap<String, String>()
assertTrue{ map.isEmpty() } assertTrue{ map.isEmpty() }
assertEquals(map.size, 0) assertEquals(map.size, 0)
@@ -291,21 +291,21 @@ abstract class MapJsTest {
assertEquals("James", map["name"]) assertEquals("James", map["name"])
} }
@test fun createUsingPairs() { @Test fun createUsingPairs() {
val map = mapOf(Pair("a", 1), Pair("b", 2)) val map = mapOf(Pair("a", 1), Pair("b", 2))
assertEquals(2, map.size) assertEquals(2, map.size)
assertEquals(1, map.get("a")) assertEquals(1, map.get("a"))
assertEquals(2, map.get("b")) assertEquals(2, map.get("b"))
} }
@test fun createUsingTo() { @Test fun createUsingTo() {
val map = mapOf("a" to 1, "b" to 2) val map = mapOf("a" to 1, "b" to 2)
assertEquals(2, map.size) assertEquals(2, map.size)
assertEquals(1, map.get("a")) assertEquals(1, map.get("a"))
assertEquals(2, map.get("b")) assertEquals(2, map.get("b"))
} }
@test fun mapIteratorImplicitly() { @Test fun mapIteratorImplicitly() {
val map = createTestMap() val map = createTestMap()
val actualKeys = ArrayList<String>() val actualKeys = ArrayList<String>()
@@ -319,7 +319,7 @@ abstract class MapJsTest {
assertEquals(VALUES.toNormalizedList(), actualValues.toNormalizedList()) assertEquals(VALUES.toNormalizedList(), actualValues.toNormalizedList())
} }
@test fun mapIteratorExplicitly() { @Test fun mapIteratorExplicitly() {
val map = createTestMap() val map = createTestMap()
val actualKeys = ArrayList<String>() val actualKeys = ArrayList<String>()
@@ -334,7 +334,7 @@ abstract class MapJsTest {
assertEquals(VALUES.toNormalizedList(), actualValues.toNormalizedList()) assertEquals(VALUES.toNormalizedList(), actualValues.toNormalizedList())
} }
@test fun mapMutableIterator() { @Test fun mapMutableIterator() {
val map = createTestMutableMap() val map = createTestMutableMap()
map.keys.removeAll { it == KEYS[0] } map.keys.removeAll { it == KEYS[0] }
map.entries.removeAll { it.key == KEYS[1] } map.entries.removeAll { it.key == KEYS[1] }
@@ -343,7 +343,7 @@ abstract class MapJsTest {
assertEquals(1, map.size, "Expected 1 entry to remain in map, but got: $map") assertEquals(1, map.size, "Expected 1 entry to remain in map, but got: $map")
} }
@test fun mapCollectionPropertiesAreViews() { @Test fun mapCollectionPropertiesAreViews() {
val map = createTestMutableMap() val map = createTestMutableMap()
assertTrue(map.size >= 3) assertTrue(map.size >= 3)
val keys = map.keys val keys = map.keys
@@ -384,7 +384,7 @@ abstract class MapJsTest {
assertEquals(100, map[entry2.key], "set value via entry") assertEquals(100, map[entry2.key], "set value via entry")
} }
@test fun mapCollectionPropertiesDoNotSupportAdd() { @Test fun mapCollectionPropertiesDoNotSupportAdd() {
val map = createTestMutableMap() val map = createTestMutableMap()
val entry = map.entries.first() val entry = map.entries.first()
val (key, value) = entry val (key, value) = entry
@@ -394,7 +394,7 @@ abstract class MapJsTest {
assertFailsWith<UnsupportedOperationException> { map.values += value } assertFailsWith<UnsupportedOperationException> { map.values += value }
} }
@test fun specialNamesNotContainsInEmptyMap() { @Test fun specialNamesNotContainsInEmptyMap() {
val map = emptyMap() val map = emptyMap()
for (key in SPECIAL_NAMES) { for (key in SPECIAL_NAMES) {
@@ -402,7 +402,7 @@ abstract class MapJsTest {
} }
} }
@test fun specialNamesNotContainsInNonEmptyMap() { @Test fun specialNamesNotContainsInNonEmptyMap() {
val map = createTestMap() val map = createTestMap()
for (key in SPECIAL_NAMES) { for (key in SPECIAL_NAMES) {
@@ -410,7 +410,7 @@ abstract class MapJsTest {
} }
} }
@test fun putAndGetSpecialNamesToMap() { @Test fun putAndGetSpecialNamesToMap() {
val map = createTestMutableMap() val map = createTestMutableMap()
var value = 0 var value = 0
@@ -430,7 +430,7 @@ abstract class MapJsTest {
} }
} }
@test abstract fun constructors() @Test abstract fun constructors()
/* /*
test fun createLinkedMap() { test fun createLinkedMap() {
@@ -1,17 +1,17 @@
@file:kotlin.jvm.JvmVersion // TODO: Can't run in JS: spaces in function name KT-4160 @file:kotlin.jvm.JvmVersion // TODO: Can't run in JS: spaces in function name KT-4160
package test.language package test.language
import org.junit.Test as test import org.junit.Test
import kotlin.test.* import kotlin.test.*
class EscapedTestNamesTest { class EscapedTestNamesTest {
@test fun `strings equal`() { @Test fun `strings equal`() {
val actual = "abc" val actual = "abc"
assertEquals("abc", actual) assertEquals("abc", actual)
} }
@test fun `numbers equal`() { @Test fun `numbers equal`() {
val actual = 5 val actual = 5
assertEquals(5, actual) assertEquals(5, actual)
} }
@@ -1,35 +1,35 @@
package test.numbers package test.numbers
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
// TODO: Run these tests during compiler test only (JVM & JS) // TODO: Run these tests during compiler test only (JVM & JS)
class BitwiseOperationsTest { class BitwiseOperationsTest {
@test fun orForInt() { @Test fun orForInt() {
assertEquals(3, 2 or 1) assertEquals(3, 2 or 1)
} }
@test fun andForInt() { @Test fun andForInt() {
assertEquals(0, 1 and 0) assertEquals(0, 1 and 0)
} }
@test fun xorForInt() { @Test fun xorForInt() {
assertEquals(1, 2 xor 3) assertEquals(1, 2 xor 3)
} }
@test fun shlForInt() { @Test fun shlForInt() {
assertEquals(4, 1 shl 2) assertEquals(4, 1 shl 2)
} }
@test fun shrForInt() { @Test fun shrForInt() {
assertEquals(1, 2 shr 1) assertEquals(1, 2 shr 1)
} }
@test fun ushrForInt() { @Test fun ushrForInt() {
assertEquals(2147483647, -1 ushr 1) assertEquals(2147483647, -1 ushr 1)
} }
@test fun invForInt() { @Test fun invForInt() {
assertEquals(0, (-1).inv()) assertEquals(0, (-1).inv())
} }
} }
@@ -19,17 +19,17 @@ package test.numbers
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class CompanionIntrinsicObjectsJVMTest { class CompanionIntrinsicObjectsJVMTest {
@test fun intTest() { @Test fun intTest() {
val i = Int val i = Int
assertEquals(java.lang.Integer.MAX_VALUE, Int.MAX_VALUE) assertEquals(java.lang.Integer.MAX_VALUE, Int.MAX_VALUE)
assertEquals(java.lang.Integer.MIN_VALUE, Int.MIN_VALUE) assertEquals(java.lang.Integer.MIN_VALUE, Int.MIN_VALUE)
} }
@test fun doubleTest() { @Test fun doubleTest() {
val d = Double val d = Double
assertEquals(java.lang.Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) assertEquals(java.lang.Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)
@@ -40,7 +40,7 @@ class CompanionIntrinsicObjectsJVMTest {
assertEquals(java.lang.Double.MIN_VALUE, Double.MIN_VALUE) assertEquals(java.lang.Double.MIN_VALUE, Double.MIN_VALUE)
} }
@test fun floatTest() { @Test fun floatTest() {
val f = Float val f = Float
assertEquals(java.lang.Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) assertEquals(java.lang.Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)
@@ -51,34 +51,34 @@ class CompanionIntrinsicObjectsJVMTest {
assertEquals(java.lang.Float.MIN_VALUE, Float.MIN_VALUE) assertEquals(java.lang.Float.MIN_VALUE, Float.MIN_VALUE)
} }
@test fun longTest() { @Test fun longTest() {
val l = Long val l = Long
assertEquals(java.lang.Long.MAX_VALUE, Long.MAX_VALUE) assertEquals(java.lang.Long.MAX_VALUE, Long.MAX_VALUE)
assertEquals(java.lang.Long.MIN_VALUE, Long.MIN_VALUE) assertEquals(java.lang.Long.MIN_VALUE, Long.MIN_VALUE)
} }
@test fun shortTest() { @Test fun shortTest() {
val s = Short val s = Short
assertEquals(java.lang.Short.MAX_VALUE, Short.MAX_VALUE) assertEquals(java.lang.Short.MAX_VALUE, Short.MAX_VALUE)
assertEquals(java.lang.Short.MIN_VALUE, Short.MIN_VALUE) assertEquals(java.lang.Short.MIN_VALUE, Short.MIN_VALUE)
} }
@test fun byteTest() { @Test fun byteTest() {
val b = Byte val b = Byte
assertEquals(java.lang.Byte.MAX_VALUE, Byte.MAX_VALUE) assertEquals(java.lang.Byte.MAX_VALUE, Byte.MAX_VALUE)
assertEquals(java.lang.Byte.MIN_VALUE, Byte.MIN_VALUE) assertEquals(java.lang.Byte.MIN_VALUE, Byte.MIN_VALUE)
} }
@test fun charTest() { @Test fun charTest() {
val ch = Char val ch = Char
assertEquals(ch, Char) assertEquals(ch, Char)
} }
@test fun stringTest() { @Test fun stringTest() {
val s = String val s = String
assertEquals(s, String) assertEquals(s, String)
+3 -3
View File
@@ -5,10 +5,10 @@ import java.math.BigInteger
import java.math.BigDecimal import java.math.BigDecimal
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class MathTest { class MathTest {
@test fun testBigInteger() { @Test fun testBigInteger() {
val a = BigInteger("2") val a = BigInteger("2")
val b = BigInteger("3") val b = BigInteger("3")
@@ -21,7 +21,7 @@ class MathTest {
assertEquals(BigInteger("-2"), (-a).remainder(b)) assertEquals(BigInteger("-2"), (-a).remainder(b))
} }
@test fun testBigDecimal() { @Test fun testBigDecimal() {
val a = BigDecimal("2") val a = BigDecimal("2")
val b = BigDecimal("3") val b = BigDecimal("3")
@@ -2,46 +2,46 @@
package test.numbers package test.numbers
import java.math.BigDecimal import java.math.BigDecimal
import org.junit.Test as test import org.junit.Test
import kotlin.test.* import kotlin.test.*
class NumbersJVMTest { class NumbersJVMTest {
@test fun intMinMaxValues() { @Test fun intMinMaxValues() {
assertEquals(java.lang.Integer.MIN_VALUE, Int.MIN_VALUE) assertEquals(java.lang.Integer.MIN_VALUE, Int.MIN_VALUE)
assertEquals(java.lang.Integer.MAX_VALUE, Int.MAX_VALUE) assertEquals(java.lang.Integer.MAX_VALUE, Int.MAX_VALUE)
} }
@test fun longMinMaxValues() { @Test fun longMinMaxValues() {
assertEquals(java.lang.Long.MIN_VALUE, Long.MIN_VALUE) assertEquals(java.lang.Long.MIN_VALUE, Long.MIN_VALUE)
assertEquals(java.lang.Long.MAX_VALUE, Long.MAX_VALUE) assertEquals(java.lang.Long.MAX_VALUE, Long.MAX_VALUE)
} }
@test fun shortMinMaxValues() { @Test fun shortMinMaxValues() {
assertEquals(java.lang.Short.MIN_VALUE, Short.MIN_VALUE) assertEquals(java.lang.Short.MIN_VALUE, Short.MIN_VALUE)
assertEquals(java.lang.Short.MAX_VALUE, Short.MAX_VALUE) assertEquals(java.lang.Short.MAX_VALUE, Short.MAX_VALUE)
} }
@test fun byteMinMaxValues() { @Test fun byteMinMaxValues() {
assertEquals(java.lang.Byte.MIN_VALUE, Byte.MIN_VALUE) assertEquals(java.lang.Byte.MIN_VALUE, Byte.MIN_VALUE)
assertEquals(java.lang.Byte.MAX_VALUE, Byte.MAX_VALUE) assertEquals(java.lang.Byte.MAX_VALUE, Byte.MAX_VALUE)
} }
@test fun doubleMinMaxValues() { @Test fun doubleMinMaxValues() {
assertEquals(java.lang.Double.MIN_VALUE, Double.MIN_VALUE) assertEquals(java.lang.Double.MIN_VALUE, Double.MIN_VALUE)
assertEquals(java.lang.Double.MAX_VALUE, Double.MAX_VALUE) assertEquals(java.lang.Double.MAX_VALUE, Double.MAX_VALUE)
assertEquals(java.lang.Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) assertEquals(java.lang.Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)
assertEquals(java.lang.Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) assertEquals(java.lang.Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY)
} }
@test fun floatMinMaxValues() { @Test fun floatMinMaxValues() {
assertEquals(java.lang.Float.MIN_VALUE, Float.MIN_VALUE) assertEquals(java.lang.Float.MIN_VALUE, Float.MIN_VALUE)
assertEquals(java.lang.Float.MAX_VALUE, Float.MAX_VALUE) assertEquals(java.lang.Float.MAX_VALUE, Float.MAX_VALUE)
assertEquals(java.lang.Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) assertEquals(java.lang.Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)
assertEquals(java.lang.Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) assertEquals(java.lang.Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY)
} }
@test fun bigDecimalDivRounding() { @Test fun bigDecimalDivRounding() {
val (d1, d2, d3, d4, d5) = (1..5).map { BigDecimal(it.toString()) } val (d1, d2, d3, d4, d5) = (1..5).map { BigDecimal(it.toString()) }
val d7 = BigDecimal("7") val d7 = BigDecimal("7")
+9 -9
View File
@@ -1,6 +1,6 @@
package test.numbers package test.numbers
import org.junit.Test as test import org.junit.Test
import kotlin.test.* import kotlin.test.*
object NumbersTestConstants { object NumbersTestConstants {
@@ -21,7 +21,7 @@ class NumbersTest {
var one: Int = 1 var one: Int = 1
@test fun intMinMaxValues() { @Test fun intMinMaxValues() {
assertTrue(Int.MIN_VALUE < 0) assertTrue(Int.MIN_VALUE < 0)
assertTrue(Int.MAX_VALUE > 0) assertTrue(Int.MAX_VALUE > 0)
@@ -34,7 +34,7 @@ class NumbersTest {
// expect(Int.MAX_VALUE) { Int.MIN_VALUE - 1 } // expect(Int.MAX_VALUE) { Int.MIN_VALUE - 1 }
} }
@test fun longMinMaxValues() { @Test fun longMinMaxValues() {
assertTrue(Long.MIN_VALUE < 0) assertTrue(Long.MIN_VALUE < 0)
assertTrue(Long.MAX_VALUE > 0) assertTrue(Long.MAX_VALUE > 0)
@@ -46,7 +46,7 @@ class NumbersTest {
expect(Long.MAX_VALUE) { Long.MIN_VALUE - 1 } expect(Long.MAX_VALUE) { Long.MIN_VALUE - 1 }
} }
@test fun shortMinMaxValues() { @Test fun shortMinMaxValues() {
assertTrue(Short.MIN_VALUE < 0) assertTrue(Short.MIN_VALUE < 0)
assertTrue(Short.MAX_VALUE > 0) assertTrue(Short.MAX_VALUE > 0)
@@ -58,7 +58,7 @@ class NumbersTest {
expect(Short.MAX_VALUE) { (Short.MIN_VALUE - 1).toShort() } expect(Short.MAX_VALUE) { (Short.MIN_VALUE - 1).toShort() }
} }
@test fun byteMinMaxValues() { @Test fun byteMinMaxValues() {
assertTrue(Byte.MIN_VALUE < 0) assertTrue(Byte.MIN_VALUE < 0)
assertTrue(Byte.MAX_VALUE > 0) assertTrue(Byte.MAX_VALUE > 0)
@@ -70,7 +70,7 @@ class NumbersTest {
expect(Byte.MAX_VALUE) { (Byte.MIN_VALUE - 1).toByte() } expect(Byte.MAX_VALUE) { (Byte.MIN_VALUE - 1).toByte() }
} }
@test fun doubleMinMaxValues() { @Test fun doubleMinMaxValues() {
assertTrue(Double.MIN_VALUE > 0) assertTrue(Double.MIN_VALUE > 0)
assertTrue(Double.MAX_VALUE > 0) assertTrue(Double.MAX_VALUE > 0)
@@ -80,7 +80,7 @@ class NumbersTest {
expect(0.0) { Double.MIN_VALUE / 2 } expect(0.0) { Double.MIN_VALUE / 2 }
} }
@test fun floatMinMaxValues() { @Test fun floatMinMaxValues() {
assertTrue(Float.MIN_VALUE > 0) assertTrue(Float.MIN_VALUE > 0)
assertTrue(Float.MAX_VALUE > 0) assertTrue(Float.MAX_VALUE > 0)
@@ -90,7 +90,7 @@ class NumbersTest {
expect(0.0F) { Float.MIN_VALUE / 2.0F } expect(0.0F) { Float.MIN_VALUE / 2.0F }
} }
@test fun doubleProperties() { @Test fun doubleProperties() {
for (value in listOf(1.0, 0.0, Double.MIN_VALUE, Double.MAX_VALUE)) for (value in listOf(1.0, 0.0, Double.MIN_VALUE, Double.MAX_VALUE))
doTestNumber(value) doTestNumber(value)
for (value in listOf(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY)) for (value in listOf(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY))
@@ -98,7 +98,7 @@ class NumbersTest {
doTestNumber(Double.NaN, isNaN = true) doTestNumber(Double.NaN, isNaN = true)
} }
@test fun floatProperties() { @Test fun floatProperties() {
for (value in listOf(1.0F, 0.0F, Float.MAX_VALUE, Float.MIN_VALUE)) for (value in listOf(1.0F, 0.0F, Float.MAX_VALUE, Float.MIN_VALUE))
doTestNumber(value) doTestNumber(value)
for (value in listOf(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY)) for (value in listOf(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY))
@@ -1,11 +1,11 @@
package test.properties.delegation package test.properties.delegation
import org.junit.Test as test import org.junit.Test
import kotlin.test.* import kotlin.test.*
import kotlin.properties.* import kotlin.properties.*
class NotNullVarTest() { class NotNullVarTest() {
@test fun doTest() { @Test fun doTest() {
NotNullVarTestGeneric("a", "b").doTest() NotNullVarTestGeneric("a", "b").doTest()
} }
} }
@@ -31,7 +31,7 @@ class ObservablePropertyTest {
assertEquals(new, b, "New value has already been set") assertEquals(new, b, "New value has already been set")
}) })
@test fun doTest() { @Test fun doTest() {
b = 4 b = 4
assertTrue(b == 4, "fail: b != 4") assertTrue(b == 4, "fail: b != 4")
assertTrue(result, "fail: result should be true") assertTrue(result, "fail: result should be true")
@@ -49,7 +49,7 @@ class VetoablePropertyTest {
result result
}) })
@test fun doTest() { @Test fun doTest() {
val firstValue = A(true) val firstValue = A(true)
b = firstValue b = firstValue
assertTrue(b == firstValue, "fail1: b should be firstValue = A(true)") assertTrue(b == firstValue, "fail1: b should be firstValue = A(true)")
@@ -1,7 +1,7 @@
package test.properties.delegation.map package test.properties.delegation.map
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class ValByMapExtensionsTest { class ValByMapExtensionsTest {
val map: Map<String, String> = hashMapOf("a" to "all", "b" to "bar", "c" to "code") val map: Map<String, String> = hashMapOf("a" to "all", "b" to "bar", "c" to "code")
@@ -18,7 +18,7 @@ class ValByMapExtensionsTest {
val x: Double by genericMap val x: Double by genericMap
@test fun doTest() { @Test fun doTest() {
assertEquals("all", a) assertEquals("all", a)
assertEquals("bar", b) assertEquals("bar", b)
assertEquals("code", c) assertEquals("code", c)
@@ -43,7 +43,7 @@ class VarByMapExtensionsTest {
var a2: String by map2.withDefault { "empty" } var a2: String by map2.withDefault { "empty" }
//var x: Int by map2 // prohibited by type system //var x: Int by map2 // prohibited by type system
@test fun doTest() { @Test fun doTest() {
assertEquals("all", a) assertEquals("all", a)
assertEquals(null, b) assertEquals(null, b)
assertEquals(1, c) assertEquals(1, c)
@@ -1,6 +1,6 @@
package test.properties.delegation.lazy package test.properties.delegation.lazy
import org.junit.Test as test import org.junit.Test
import kotlin.properties.* import kotlin.properties.*
import kotlin.test.* import kotlin.test.*
@@ -10,7 +10,7 @@ class LazyValTest {
++result ++result
} }
@test fun doTest() { @Test fun doTest() {
a a
assertTrue(a == 1, "fail: initializer should be invoked only once") assertTrue(a == 1, "fail: initializer should be invoked only once")
} }
@@ -23,7 +23,7 @@ class SynchronizedLazyValTest {
++result ++result
} }
@test fun doTest() { @Test fun doTest() {
synchronized(this) { synchronized(this) {
kotlin.concurrent.thread { a } // not available in js kotlin.concurrent.thread { a } // not available in js
result = 1 result = 1
@@ -40,7 +40,7 @@ class UnsafeLazyValTest {
++result ++result
} }
@test fun doTest() { @Test fun doTest() {
a a
assertTrue(a == 1, "fail: initializer should be invoked only once") assertTrue(a == 1, "fail: initializer should be invoked only once")
} }
@@ -53,7 +53,7 @@ class NullableLazyValTest {
val a: Int? by lazy { resultA++; null} val a: Int? by lazy { resultA++; null}
val b by lazy { foo() } val b by lazy { foo() }
@test fun doTest() { @Test fun doTest() {
a a
b b
@@ -76,7 +76,7 @@ class UnsafeNullableLazyValTest {
val a: Int? by lazy(LazyThreadSafetyMode.NONE) { resultA++; null} val a: Int? by lazy(LazyThreadSafetyMode.NONE) { resultA++; null}
val b by lazy(LazyThreadSafetyMode.NONE) { foo() } val b by lazy(LazyThreadSafetyMode.NONE) { foo() }
@test fun doTest() { @Test fun doTest() {
a a
b b
@@ -96,7 +96,7 @@ class IdentityEqualsIsUsedToUnescapeLazyValTest {
var equalsCalled = 0 var equalsCalled = 0
private val a by lazy { ClassWithCustomEquality { equalsCalled++ } } private val a by lazy { ClassWithCustomEquality { equalsCalled++ } }
@test fun doTest() { @Test fun doTest() {
a a
a a
assertTrue(equalsCalled == 0, "fail: equals called $equalsCalled times.") assertTrue(equalsCalled == 0, "fail: equals called $equalsCalled times.")
@@ -1,7 +1,6 @@
package test.ranges package test.ranges
import org.junit.Test import org.junit.Test
import org.junit.Test as test
import kotlin.test.* import kotlin.test.*
class CoercionTest { class CoercionTest {
@@ -11,14 +11,14 @@ import java.lang.Long.MAX_VALUE as MaxL
import java.lang.Long.MIN_VALUE as MinL import java.lang.Long.MIN_VALUE as MinL
import java.lang.Character.MAX_VALUE as MaxC import java.lang.Character.MAX_VALUE as MaxC
import java.lang.Character.MIN_VALUE as MinC import java.lang.Character.MIN_VALUE as MinC
import org.junit.Test as test import org.junit.Test
import kotlin.test.* import kotlin.test.*
// Test data for codegen is generated from this class. If you change it, rerun GenerateTests // Test data for codegen is generated from this class. If you change it, rerun GenerateTests
public class RangeIterationJVMTest : RangeIterationTestBase() { public class RangeIterationJVMTest : RangeIterationTestBase() {
@test fun maxValueToMaxValue() { @Test fun maxValueToMaxValue() {
doTest(MaxI..MaxI, MaxI, MaxI, 1, listOf(MaxI)) doTest(MaxI..MaxI, MaxI, MaxI, 1, listOf(MaxI))
doTest(MaxB..MaxB, MaxB.toInt(), MaxB.toInt(), 1, listOf(MaxB.toInt())) doTest(MaxB..MaxB, MaxB.toInt(), MaxB.toInt(), 1, listOf(MaxB.toInt()))
doTest(MaxS..MaxS, MaxS.toInt(), MaxS.toInt(), 1, listOf(MaxS.toInt())) doTest(MaxS..MaxS, MaxS.toInt(), MaxS.toInt(), 1, listOf(MaxS.toInt()))
@@ -27,7 +27,7 @@ public class RangeIterationJVMTest : RangeIterationTestBase() {
doTest(MaxC..MaxC, MaxC, MaxC, 1, listOf(MaxC)) doTest(MaxC..MaxC, MaxC, MaxC, 1, listOf(MaxC))
} }
@test fun maxValueMinusTwoToMaxValue() { @Test fun maxValueMinusTwoToMaxValue() {
doTest((MaxI - 2)..MaxI, MaxI - 2, MaxI, 1, listOf(MaxI - 2, MaxI - 1, MaxI)) 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((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((MaxS - 2).toShort()..MaxS, (MaxS - 2).toInt(), MaxS.toInt(), 1, listOf((MaxS - 2).toInt(), (MaxS - 1).toInt(), MaxS.toInt()))
@@ -36,7 +36,7 @@ public class RangeIterationJVMTest : RangeIterationTestBase() {
doTest((MaxC - 2)..MaxC, (MaxC - 2), MaxC, 1, listOf((MaxC - 2), (MaxC - 1), MaxC)) doTest((MaxC - 2)..MaxC, (MaxC - 2), MaxC, 1, listOf((MaxC - 2), (MaxC - 1), MaxC))
} }
@test fun maxValueToMinValue() { @Test fun maxValueToMinValue() {
doTest(MaxI..MinI, MaxI, MinI, 1, listOf()) doTest(MaxI..MinI, MaxI, MinI, 1, listOf())
doTest(MaxB..MinB, MaxB.toInt(), MinB.toInt(), 1, listOf()) doTest(MaxB..MinB, MaxB.toInt(), MinB.toInt(), 1, listOf())
doTest(MaxS..MinS, MaxS.toInt(), MinS.toInt(), 1, listOf()) doTest(MaxS..MinS, MaxS.toInt(), MinS.toInt(), 1, listOf())
@@ -45,7 +45,7 @@ public class RangeIterationJVMTest : RangeIterationTestBase() {
doTest(MaxC..MinC, MaxC, MinC, 1, listOf()) doTest(MaxC..MinC, MaxC, MinC, 1, listOf())
} }
@test fun progressionMaxValueToMaxValue() { @Test fun progressionMaxValueToMaxValue() {
doTest(MaxI..MaxI step 1, MaxI, MaxI, 1, listOf(MaxI)) doTest(MaxI..MaxI step 1, MaxI, MaxI, 1, listOf(MaxI))
doTest(MaxB..MaxB step 1, MaxB.toInt(), MaxB.toInt(), 1, listOf(MaxB.toInt())) 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(MaxS..MaxS step 1, MaxS.toInt(), MaxS.toInt(), 1, listOf(MaxS.toInt()))
@@ -54,7 +54,7 @@ public class RangeIterationJVMTest : RangeIterationTestBase() {
doTest(MaxC..MaxC step 1, MaxC, MaxC, 1, listOf(MaxC)) doTest(MaxC..MaxC step 1, MaxC, MaxC, 1, listOf(MaxC))
} }
@test fun progressionMaxValueMinusTwoToMaxValue() { @Test fun progressionMaxValueMinusTwoToMaxValue() {
doTest((MaxI - 2)..MaxI step 2, MaxI - 2, MaxI, 2, listOf(MaxI - 2, MaxI)) 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((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((MaxS - 2).toShort()..MaxS step 2, (MaxS - 2).toInt(), MaxS.toInt(), 2, listOf((MaxS - 2).toInt(), MaxS.toInt()))
@@ -63,7 +63,7 @@ public class RangeIterationJVMTest : RangeIterationTestBase() {
doTest((MaxC - 2)..MaxC step 2, (MaxC - 2), MaxC, 2, listOf((MaxC - 2), MaxC)) doTest((MaxC - 2)..MaxC step 2, (MaxC - 2), MaxC, 2, listOf((MaxC - 2), MaxC))
} }
@test fun progressionMaxValueToMinValue() { @Test fun progressionMaxValueToMinValue() {
doTest(MaxI..MinI step 1, MaxI, MinI, 1, listOf()) doTest(MaxI..MinI step 1, MaxI, MinI, 1, listOf())
doTest(MaxB..MinB step 1, MaxB.toInt(), MinB.toInt(), 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(MaxS..MinS step 1, MaxS.toInt(), MinS.toInt(), 1, listOf())
@@ -72,7 +72,7 @@ public class RangeIterationJVMTest : RangeIterationTestBase() {
doTest(MaxC..MinC step 1, MaxC, MinC, 1, listOf()) doTest(MaxC..MinC step 1, MaxC, MinC, 1, listOf())
} }
@test fun progressionMinValueToMinValue() { @Test fun progressionMinValueToMinValue() {
doTest(MinI..MinI step 1, MinI, MinI, 1, listOf(MinI)) doTest(MinI..MinI step 1, MinI, MinI, 1, listOf(MinI))
doTest(MinB..MinB step 1, MinB.toInt(), MinB.toInt(), 1, listOf(MinB.toInt())) 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(MinS..MinS step 1, MinS.toInt(), MinS.toInt(), 1, listOf(MinS.toInt()))
@@ -81,7 +81,7 @@ public class RangeIterationJVMTest : RangeIterationTestBase() {
doTest(MinC..MinC step 1, MinC, MinC, 1, listOf(MinC)) doTest(MinC..MinC step 1, MinC, MinC, 1, listOf(MinC))
} }
@test fun inexactToMaxValue() { @Test fun inexactToMaxValue() {
doTest((MaxI - 5)..MaxI step 3, MaxI - 5, MaxI - 2, 3, listOf(MaxI - 5, MaxI - 2)) 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((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((MaxS - 5).toShort()..MaxS step 3, (MaxS - 5).toInt(), (MaxS - 2).toInt(), 3, listOf((MaxS - 5).toInt(), (MaxS - 2).toInt()))
@@ -90,7 +90,7 @@ public class RangeIterationJVMTest : RangeIterationTestBase() {
doTest((MaxC - 5)..MaxC step 3, (MaxC - 5), (MaxC - 2), 3, listOf((MaxC - 5), (MaxC - 2))) doTest((MaxC - 5)..MaxC step 3, (MaxC - 5), (MaxC - 2), 3, listOf((MaxC - 5), (MaxC - 2)))
} }
@test fun progressionDownToMinValue() { @Test fun progressionDownToMinValue() {
doTest((MinI + 2) downTo MinI step 1, MinI + 2, MinI, -1, listOf(MinI + 2, MinI + 1, MinI)) 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((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((MinS + 2).toShort() downTo MinS step 1, (MinS + 2).toInt(), MinS.toInt(), -1, listOf((MinS + 2).toInt(), (MinS + 1).toInt(), MinS.toInt()))
@@ -99,7 +99,7 @@ public class RangeIterationJVMTest : RangeIterationTestBase() {
doTest((MinC + 2) downTo MinC step 1, (MinC + 2), MinC, -1, listOf((MinC + 2), (MinC + 1), MinC)) doTest((MinC + 2) downTo MinC step 1, (MinC + 2), MinC, -1, listOf((MinC + 2), (MinC + 1), MinC))
} }
@test fun inexactDownToMinValue() { @Test fun inexactDownToMinValue() {
doTest((MinI + 5) downTo MinI step 3, MinI + 5, MinI + 2, -3, listOf(MinI + 5, MinI + 2)) 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((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((MinS + 5).toShort() downTo MinS step 3, (MinS + 5).toInt(), (MinS + 2).toInt(), -3, listOf((MinS + 5).toInt(), (MinS + 2).toInt()))
@@ -1,6 +1,6 @@
package test.ranges package test.ranges
import org.junit.Test as test import org.junit.Test
import kotlin.test.* import kotlin.test.*
public open class RangeIterationTestBase { public open class RangeIterationTestBase {
@@ -48,14 +48,14 @@ public open class RangeIterationTestBase {
// Test data for codegen is generated from this class. If you change it, rerun GenerateTests // Test data for codegen is generated from this class. If you change it, rerun GenerateTests
public class RangeIterationTest : RangeIterationTestBase() { public class RangeIterationTest : RangeIterationTestBase() {
@test fun emptyConstant() { @Test fun emptyConstant() {
doTest(IntRange.EMPTY, 1, 0, 1, listOf()) doTest(IntRange.EMPTY, 1, 0, 1, listOf())
doTest(LongRange.EMPTY, 1.toLong(), 0.toLong(), 1.toLong(), listOf()) doTest(LongRange.EMPTY, 1.toLong(), 0.toLong(), 1.toLong(), listOf())
doTest(CharRange.EMPTY, 1.toChar(), 0.toChar(), 1, listOf()) doTest(CharRange.EMPTY, 1.toChar(), 0.toChar(), 1, listOf())
} }
@test fun emptyRange() { @Test fun emptyRange() {
doTest(10..5, 10, 5, 1, listOf()) doTest(10..5, 10, 5, 1, listOf())
doTest(10.toByte()..(-5).toByte(), 10, (-5), 1, listOf()) doTest(10.toByte()..(-5).toByte(), 10, (-5), 1, listOf())
doTest(10.toShort()..(-5).toShort(), 10, (-5), 1, listOf()) doTest(10.toShort()..(-5).toShort(), 10, (-5), 1, listOf())
@@ -64,7 +64,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
doTest('z'..'a', 'z', 'a', 1, listOf()) doTest('z'..'a', 'z', 'a', 1, listOf())
} }
@test fun oneElementRange() { @Test fun oneElementRange() {
doTest(5..5, 5, 5, 1, listOf(5)) doTest(5..5, 5, 5, 1, listOf(5))
doTest(5.toByte()..5.toByte(), 5, 5, 1, listOf(5)) doTest(5.toByte()..5.toByte(), 5, 5, 1, listOf(5))
doTest(5.toShort()..5.toShort(), 5, 5, 1, listOf(5)) doTest(5.toShort()..5.toShort(), 5, 5, 1, listOf(5))
@@ -73,7 +73,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
doTest('k'..'k', 'k', 'k', 1, listOf('k')) doTest('k'..'k', 'k', 'k', 1, listOf('k'))
} }
@test fun simpleRange() { @Test fun simpleRange() {
doTest(3..9, 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9)) doTest(3..9, 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9))
doTest(3.toByte()..9.toByte(), 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9)) doTest(3.toByte()..9.toByte(), 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9))
doTest(3.toShort()..9.toShort(), 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9)) doTest(3.toShort()..9.toShort(), 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9))
@@ -83,7 +83,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
} }
@test fun simpleRangeWithNonConstantEnds() { @Test fun simpleRangeWithNonConstantEnds() {
doTest((1 + 2)..(10 - 1), 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9)) doTest((1 + 2)..(10 - 1), 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9))
doTest((1.toByte() + 2.toByte()).toByte()..(10.toByte() - 1.toByte()).toByte(), 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9)) doTest((1.toByte() + 2.toByte()).toByte()..(10.toByte() - 1.toByte()).toByte(), 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9))
doTest((1.toShort() + 2.toShort()).toShort()..(10.toShort() - 1.toShort()).toShort(), 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9)) doTest((1.toShort() + 2.toShort()).toShort()..(10.toShort() - 1.toShort()).toShort(), 3, 9, 1, listOf(3, 4, 5, 6, 7, 8, 9))
@@ -92,7 +92,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
doTest(("ace"[1])..("age"[1]), 'c', 'g', 1, listOf('c', 'd', 'e', 'f', 'g')) doTest(("ace"[1])..("age"[1]), 'c', 'g', 1, listOf('c', 'd', 'e', 'f', 'g'))
} }
@test fun openRange() { @Test fun openRange() {
doTest(1 until 5, 1, 4, 1, listOf(1, 2, 3, 4)) doTest(1 until 5, 1, 4, 1, listOf(1, 2, 3, 4))
doTest(1.toByte() until 5.toByte(), 1, 4, 1, listOf(1, 2, 3, 4)) doTest(1.toByte() until 5.toByte(), 1, 4, 1, listOf(1, 2, 3, 4))
doTest(1.toShort() until 5.toShort(), 1, 4, 1, listOf(1, 2, 3, 4)) doTest(1.toShort() until 5.toShort(), 1, 4, 1, listOf(1, 2, 3, 4))
@@ -101,7 +101,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
} }
@test fun emptyDownto() { @Test fun emptyDownto() {
doTest(5 downTo 10, 5, 10, -1, listOf()) doTest(5 downTo 10, 5, 10, -1, listOf())
doTest(5.toByte() downTo 10.toByte(), 5, 10, -1, listOf()) doTest(5.toByte() downTo 10.toByte(), 5, 10, -1, listOf())
doTest(5.toShort() downTo 10.toShort(), 5, 10, -1, listOf()) doTest(5.toShort() downTo 10.toShort(), 5, 10, -1, listOf())
@@ -110,7 +110,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
doTest('a' downTo 'z', 'a', 'z', -1, listOf()) doTest('a' downTo 'z', 'a', 'z', -1, listOf())
} }
@test fun oneElementDownTo() { @Test fun oneElementDownTo() {
doTest(5 downTo 5, 5, 5, -1, listOf(5)) doTest(5 downTo 5, 5, 5, -1, listOf(5))
doTest(5.toByte() downTo 5.toByte(), 5, 5, -1, listOf(5)) doTest(5.toByte() downTo 5.toByte(), 5, 5, -1, listOf(5))
doTest(5.toShort() downTo 5.toShort(), 5, 5, -1, listOf(5)) doTest(5.toShort() downTo 5.toShort(), 5, 5, -1, listOf(5))
@@ -119,7 +119,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
doTest('k' downTo 'k', 'k', 'k', -1, listOf('k')) doTest('k' downTo 'k', 'k', 'k', -1, listOf('k'))
} }
@test fun simpleDownTo() { @Test fun simpleDownTo() {
doTest(9 downTo 3, 9, 3, -1, listOf(9, 8, 7, 6, 5, 4, 3)) doTest(9 downTo 3, 9, 3, -1, listOf(9, 8, 7, 6, 5, 4, 3))
doTest(9.toByte() downTo 3.toByte(), 9, 3, -1, listOf(9, 8, 7, 6, 5, 4, 3)) doTest(9.toByte() downTo 3.toByte(), 9, 3, -1, listOf(9, 8, 7, 6, 5, 4, 3))
doTest(9.toShort() downTo 3.toShort(), 9, 3, -1, listOf(9, 8, 7, 6, 5, 4, 3)) doTest(9.toShort() downTo 3.toShort(), 9, 3, -1, listOf(9, 8, 7, 6, 5, 4, 3))
@@ -129,7 +129,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
} }
@test fun simpleSteppedRange() { @Test fun simpleSteppedRange() {
doTest(3..9 step 2, 3, 9, 2, listOf(3, 5, 7, 9)) doTest(3..9 step 2, 3, 9, 2, listOf(3, 5, 7, 9))
doTest(3.toByte()..9.toByte() step 2, 3, 9, 2, listOf(3, 5, 7, 9)) doTest(3.toByte()..9.toByte() step 2, 3, 9, 2, listOf(3, 5, 7, 9))
doTest(3.toShort()..9.toShort() step 2, 3, 9, 2, listOf(3, 5, 7, 9)) doTest(3.toShort()..9.toShort() step 2, 3, 9, 2, listOf(3, 5, 7, 9))
@@ -138,7 +138,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
doTest('c'..'g' step 2, 'c', 'g', 2, listOf('c', 'e', 'g')) doTest('c'..'g' step 2, 'c', 'g', 2, listOf('c', 'e', 'g'))
} }
@test fun simpleSteppedDownTo() { @Test fun simpleSteppedDownTo() {
doTest(9 downTo 3 step 2, 9, 3, -2, listOf(9, 7, 5, 3)) doTest(9 downTo 3 step 2, 9, 3, -2, listOf(9, 7, 5, 3))
doTest(9.toByte() downTo 3.toByte() step 2, 9, 3, -2, listOf(9, 7, 5, 3)) doTest(9.toByte() downTo 3.toByte() step 2, 9, 3, -2, listOf(9, 7, 5, 3))
doTest(9.toShort() downTo 3.toShort() step 2, 9, 3, -2, listOf(9, 7, 5, 3)) doTest(9.toShort() downTo 3.toShort() step 2, 9, 3, -2, listOf(9, 7, 5, 3))
@@ -149,7 +149,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
// 'inexact' means last element is not equal to sequence end // 'inexact' means last element is not equal to sequence end
@test fun inexactSteppedRange() { @Test fun inexactSteppedRange() {
doTest(3..8 step 2, 3, 7, 2, listOf(3, 5, 7)) doTest(3..8 step 2, 3, 7, 2, listOf(3, 5, 7))
doTest(3.toByte()..8.toByte() step 2, 3, 7, 2, listOf(3, 5, 7)) doTest(3.toByte()..8.toByte() step 2, 3, 7, 2, listOf(3, 5, 7))
doTest(3.toShort()..8.toShort() step 2, 3, 7, 2, listOf(3, 5, 7)) doTest(3.toShort()..8.toShort() step 2, 3, 7, 2, listOf(3, 5, 7))
@@ -159,7 +159,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
} }
// 'inexact' means last element is not equal to sequence end // 'inexact' means last element is not equal to sequence end
@test fun inexactSteppedDownTo() { @Test fun inexactSteppedDownTo() {
doTest(8 downTo 3 step 2, 8, 4, -2, listOf(8, 6, 4)) doTest(8 downTo 3 step 2, 8, 4, -2, listOf(8, 6, 4))
doTest(8.toByte() downTo 3.toByte() step 2, 8, 4, -2, listOf(8, 6, 4)) doTest(8.toByte() downTo 3.toByte() step 2, 8, 4, -2, listOf(8, 6, 4))
doTest(8.toShort() downTo 3.toShort() step 2, 8, 4, -2, listOf(8, 6, 4)) doTest(8.toShort() downTo 3.toShort() step 2, 8, 4, -2, listOf(8, 6, 4))
@@ -169,7 +169,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
} }
@test fun reversedEmptyRange() { @Test fun reversedEmptyRange() {
doTest((5..3).reversed(), 3, 5, -1, listOf()) doTest((5..3).reversed(), 3, 5, -1, listOf())
doTest((5.toByte()..3.toByte()).reversed(), 3, 5, -1, listOf()) doTest((5.toByte()..3.toByte()).reversed(), 3, 5, -1, listOf())
doTest((5.toShort()..3.toShort()).reversed(), 3, 5, -1, listOf()) doTest((5.toShort()..3.toShort()).reversed(), 3, 5, -1, listOf())
@@ -178,7 +178,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
doTest(('c'..'a').reversed(), 'a', 'c', -1, listOf()) doTest(('c'..'a').reversed(), 'a', 'c', -1, listOf())
} }
@test fun reversedEmptyBackSequence() { @Test fun reversedEmptyBackSequence() {
doTest((3 downTo 5).reversed(), 5, 3, 1, listOf()) doTest((3 downTo 5).reversed(), 5, 3, 1, listOf())
doTest((3.toByte() downTo 5.toByte()).reversed(), 5, 3, 1, listOf()) doTest((3.toByte() downTo 5.toByte()).reversed(), 5, 3, 1, listOf())
doTest((3.toShort() downTo 5.toShort()).reversed(), 5, 3, 1, listOf()) doTest((3.toShort() downTo 5.toShort()).reversed(), 5, 3, 1, listOf())
@@ -187,7 +187,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
doTest(('a' downTo 'c').reversed(), 'c', 'a', 1, listOf()) doTest(('a' downTo 'c').reversed(), 'c', 'a', 1, listOf())
} }
@test fun reversedRange() { @Test fun reversedRange() {
doTest((3..5).reversed(), 5, 3, -1, listOf(5, 4, 3)) doTest((3..5).reversed(), 5, 3, -1, listOf(5, 4, 3))
doTest((3.toByte()..5.toByte()).reversed(),5, 3, -1, listOf(5, 4, 3)) doTest((3.toByte()..5.toByte()).reversed(),5, 3, -1, listOf(5, 4, 3))
doTest((3.toShort()..5.toShort()).reversed(), 5, 3, -1, listOf(5, 4, 3)) doTest((3.toShort()..5.toShort()).reversed(), 5, 3, -1, listOf(5, 4, 3))
@@ -196,7 +196,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
doTest(('a'..'c').reversed(), 'c', 'a', -1, listOf('c', 'b', 'a')) doTest(('a'..'c').reversed(), 'c', 'a', -1, listOf('c', 'b', 'a'))
} }
@test fun reversedBackSequence() { @Test fun reversedBackSequence() {
doTest((5 downTo 3).reversed(), 3, 5, 1, listOf(3, 4, 5)) doTest((5 downTo 3).reversed(), 3, 5, 1, listOf(3, 4, 5))
doTest((5.toByte() downTo 3.toByte()).reversed(), 3, 5, 1, listOf(3, 4, 5)) doTest((5.toByte() downTo 3.toByte()).reversed(), 3, 5, 1, listOf(3, 4, 5))
doTest((5.toShort() downTo 3.toShort()).reversed(), 3, 5, 1, listOf(3, 4, 5)) doTest((5.toShort() downTo 3.toShort()).reversed(), 3, 5, 1, listOf(3, 4, 5))
@@ -206,7 +206,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
} }
@test fun reversedSimpleSteppedRange() { @Test fun reversedSimpleSteppedRange() {
doTest((3..9 step 2).reversed(), 9, 3, -2, listOf(9, 7, 5, 3)) doTest((3..9 step 2).reversed(), 9, 3, -2, listOf(9, 7, 5, 3))
doTest((3.toByte()..9.toByte() step 2).reversed(), 9, 3, -2, listOf(9, 7, 5, 3)) doTest((3.toByte()..9.toByte() step 2).reversed(), 9, 3, -2, listOf(9, 7, 5, 3))
doTest((3.toShort()..9.toShort() step 2).reversed(), 9, 3, -2, listOf(9, 7, 5, 3)) doTest((3.toShort()..9.toShort() step 2).reversed(), 9, 3, -2, listOf(9, 7, 5, 3))
@@ -217,7 +217,7 @@ public class RangeIterationTest : RangeIterationTestBase() {
// invariant progression.reversed().toList() == progression.toList().reversed() is preserved // invariant progression.reversed().toList() == progression.toList().reversed() is preserved
// 'inexact' means that start of reversed progression is not the end of original progression, but the last element // 'inexact' means that start of reversed progression is not the end of original progression, but the last element
@test fun reversedInexactSteppedDownTo() { @Test fun reversedInexactSteppedDownTo() {
doTest((8 downTo 3 step 2).reversed(), 4, 8, 2, listOf(4, 6, 8)) doTest((8 downTo 3 step 2).reversed(), 4, 8, 2, listOf(4, 6, 8))
doTest((8.toByte() downTo 3.toByte() step 2).reversed(), 4, 8, 2, listOf(4, 6, 8)) doTest((8.toByte() downTo 3.toByte() step 2).reversed(), 4, 8, 2, listOf(4, 6, 8))
doTest((8.toShort() downTo 3.toShort() step 2).reversed(), 4, 8, 2, listOf(4, 6, 8)) doTest((8.toShort() downTo 3.toShort() step 2).reversed(), 4, 8, 2, listOf(4, 6, 8))
+4 -4
View File
@@ -3,19 +3,19 @@ package test.ranges
import java.lang.Double as jDouble import java.lang.Double as jDouble
import java.lang.Float as jFloat import java.lang.Float as jFloat
import org.junit.Test as test import org.junit.Test
import kotlin.test.* import kotlin.test.*
public class RangeJVMTest { public class RangeJVMTest {
@test fun doubleRange() { @Test fun doubleRange() {
val range = -1.0..3.14159265358979 val range = -1.0..3.14159265358979
assertFalse(jDouble.NEGATIVE_INFINITY in range) assertFalse(jDouble.NEGATIVE_INFINITY in range)
assertFalse(jDouble.POSITIVE_INFINITY in range) assertFalse(jDouble.POSITIVE_INFINITY in range)
assertFalse(jDouble.NaN in range) assertFalse(jDouble.NaN in range)
} }
@test fun floatRange() { @Test fun floatRange() {
val range = -1.0f..3.14159f val range = -1.0f..3.14159f
assertFalse(jFloat.NEGATIVE_INFINITY in range) assertFalse(jFloat.NEGATIVE_INFINITY in range)
assertFalse(jFloat.POSITIVE_INFINITY in range) assertFalse(jFloat.POSITIVE_INFINITY in range)
@@ -23,7 +23,7 @@ public class RangeJVMTest {
assertFalse(jFloat.NaN in range) assertFalse(jFloat.NaN in range)
} }
@test fun illegalProgressionCreation() { @Test fun illegalProgressionCreation() {
fun assertFailsWithIllegalArgument(f: () -> Unit) = assertFailsWith(IllegalArgumentException::class, block = f) fun assertFailsWithIllegalArgument(f: () -> Unit) = assertFailsWith(IllegalArgumentException::class, block = f)
// create Progression explicitly with increment = 0 // create Progression explicitly with increment = 0
assertFailsWithIllegalArgument { IntProgression.fromClosedRange(0, 5, 0) } assertFailsWithIllegalArgument { IntProgression.fromClosedRange(0, 5, 0) }
+12 -12
View File
@@ -1,10 +1,10 @@
package test.ranges package test.ranges
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
public class RangeTest { public class RangeTest {
@test fun intRange() { @Test fun intRange() {
val range = -5..9 val range = -5..9
assertFalse(-1000 in range) assertFalse(-1000 in range)
assertFalse(-6 in range) assertFalse(-6 in range)
@@ -39,7 +39,7 @@ public class RangeTest {
assertTrue((1 until Int.MIN_VALUE).isEmpty()) assertTrue((1 until Int.MIN_VALUE).isEmpty())
} }
@test fun byteRange() { @Test fun byteRange() {
val range = (-5).toByte()..9.toByte() val range = (-5).toByte()..9.toByte()
assertFalse((-100).toByte() in range) assertFalse((-100).toByte() in range)
assertFalse((-6).toByte() in range) assertFalse((-6).toByte() in range)
@@ -74,7 +74,7 @@ public class RangeTest {
assertTrue((0.toByte() until Int.MIN_VALUE).isEmpty()) assertTrue((0.toByte() until Int.MIN_VALUE).isEmpty())
} }
@test fun shortRange() { @Test fun shortRange() {
val range = (-5).toShort()..9.toShort() val range = (-5).toShort()..9.toShort()
assertFalse((-1000).toShort() in range) assertFalse((-1000).toShort() in range)
assertFalse((-6).toShort() in range) assertFalse((-6).toShort() in range)
@@ -108,7 +108,7 @@ public class RangeTest {
assertTrue((0.toShort() until Int.MIN_VALUE).isEmpty()) assertTrue((0.toShort() until Int.MIN_VALUE).isEmpty())
} }
@test fun longRange() { @Test fun longRange() {
val range = -5L..9L val range = -5L..9L
assertFalse(-10000000L in range) assertFalse(-10000000L in range)
assertFalse(-6L in range) assertFalse(-6L in range)
@@ -145,7 +145,7 @@ public class RangeTest {
} }
@test fun charRange() { @Test fun charRange() {
val range = 'c'..'w' val range = 'c'..'w'
assertFalse('0' in range) assertFalse('0' in range)
assertFalse('b' in range) assertFalse('b' in range)
@@ -172,7 +172,7 @@ public class RangeTest {
assertTrue(('A' until '\u0000').isEmpty()) assertTrue(('A' until '\u0000').isEmpty())
} }
@test fun doubleRange() { @Test fun doubleRange() {
val range = -1.0..3.14159265358979 val range = -1.0..3.14159265358979
assertFalse(-1e200 in range) assertFalse(-1e200 in range)
assertFalse(-100.0 in range) assertFalse(-100.0 in range)
@@ -198,7 +198,7 @@ public class RangeTest {
assertTrue(1.toFloat() in range) assertTrue(1.toFloat() in range)
} }
@test fun floatRange() { @Test fun floatRange() {
val range = -1.0f..3.14159f val range = -1.0f..3.14159f
assertFalse(-1e30f in range) assertFalse(-1e30f in range)
assertFalse(-100.0f in range) assertFalse(-100.0f in range)
@@ -226,7 +226,7 @@ public class RangeTest {
assertFalse(Double.MAX_VALUE in range) assertFalse(Double.MAX_VALUE in range)
} }
@test fun isEmpty() { @Test fun isEmpty() {
assertTrue((2..1).isEmpty()) assertTrue((2..1).isEmpty())
assertTrue((2L..0L).isEmpty()) assertTrue((2L..0L).isEmpty())
assertTrue((1.toShort()..-1.toShort()).isEmpty()) assertTrue((1.toShort()..-1.toShort()).isEmpty())
@@ -245,7 +245,7 @@ public class RangeTest {
assertTrue(("range".."progression").isEmpty()) assertTrue(("range".."progression").isEmpty())
} }
@test fun emptyEquals() { @Test fun emptyEquals() {
assertTrue(IntRange.EMPTY == IntRange.EMPTY) assertTrue(IntRange.EMPTY == IntRange.EMPTY)
assertEquals(IntRange.EMPTY, IntRange.EMPTY) assertEquals(IntRange.EMPTY, IntRange.EMPTY)
assertEquals(0L..42L, 0L..42L) assertEquals(0L..42L, 0L..42L)
@@ -270,7 +270,7 @@ public class RangeTest {
assertFalse(("aa".."bb") == ("aaa".."bbb")) assertFalse(("aa".."bb") == ("aaa".."bbb"))
} }
@test fun emptyHashCode() { @Test fun emptyHashCode() {
assertEquals((0..42).hashCode(), (0..42).hashCode()) assertEquals((0..42).hashCode(), (0..42).hashCode())
assertEquals((1.23..4.56).hashCode(), (1.23..4.56).hashCode()) assertEquals((1.23..4.56).hashCode(), (1.23..4.56).hashCode())
@@ -289,7 +289,7 @@ public class RangeTest {
assertEquals(("range".."progression").hashCode(), ("hashcode".."equals").hashCode()) assertEquals(("range".."progression").hashCode(), ("hashcode".."equals").hashCode())
} }
@test fun comparableRange() { @Test fun comparableRange() {
val range = "island".."isle" val range = "island".."isle"
assertFalse("apple" in range) assertFalse("apple" in range)
assertFalse("icicle" in range) assertFalse("icicle" in range)
@@ -2,7 +2,7 @@
package test.reflection package test.reflection
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
@Retention(AnnotationRetention.RUNTIME) @Retention(AnnotationRetention.RUNTIME)
annotation class MyAnno annotation class MyAnno
@@ -13,7 +13,7 @@ class AnnotatedClass
class AnnotationTest { class AnnotationTest {
@test fun annotationType() { @Test fun annotationType() {
val kAnnotations = AnnotatedClass::class.java.annotations.map { it!!.annotationClass } val kAnnotations = AnnotatedClass::class.java.annotations.map { it!!.annotationClass }
val jAnnotations = AnnotatedClass::class.java.annotations.map { it!!.annotationClass.java } val jAnnotations = AnnotatedClass::class.java.annotations.map { it!!.annotationClass.java }
+2 -2
View File
@@ -2,11 +2,11 @@
package test.text package test.text
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class CharJVMTest { class CharJVMTest {
@test fun getCategory() { @Test fun getCategory() {
assertEquals(CharCategory.DECIMAL_DIGIT_NUMBER, '7'.category) assertEquals(CharCategory.DECIMAL_DIGIT_NUMBER, '7'.category)
assertEquals(CharCategory.CURRENCY_SYMBOL, '$'.category) assertEquals(CharCategory.CURRENCY_SYMBOL, '$'.category)
assertEquals(CharCategory.LOWERCASE_LETTER, 'a'.category) assertEquals(CharCategory.LOWERCASE_LETTER, 'a'.category)
+14 -14
View File
@@ -3,11 +3,11 @@ package test.text
import kotlin.text.* import kotlin.text.*
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class RegexTest { class RegexTest {
@test fun matchResult() { @Test fun matchResult() {
val p = "\\d+".toRegex() val p = "\\d+".toRegex()
val input = "123 456 789" val input = "123 456 789"
@@ -35,12 +35,12 @@ class RegexTest {
assertEquals(null, noMatch) assertEquals(null, noMatch)
} }
@test fun matchIgnoreCase() { @Test fun matchIgnoreCase() {
for (input in listOf("ascii", "shrödinger")) for (input in listOf("ascii", "shrödinger"))
assertTrue(input.toUpperCase().matches(input.toLowerCase().toRegex(RegexOption.IGNORE_CASE))) assertTrue(input.toUpperCase().matches(input.toLowerCase().toRegex(RegexOption.IGNORE_CASE)))
} }
@test fun matchSequence() { @Test fun matchSequence() {
val input = "123 456 789" val input = "123 456 789"
val pattern = "\\d+".toRegex() val pattern = "\\d+".toRegex()
@@ -54,7 +54,7 @@ class RegexTest {
assertEquals(listOf(0..2, 4..6, 8..10), matches.map { it.range }.toList()) assertEquals(listOf(0..2, 4..6, 8..10), matches.map { it.range }.toList())
} }
@test fun matchAllSequence() { @Test fun matchAllSequence() {
val input = "test" val input = "test"
val pattern = ".*".toRegex() val pattern = ".*".toRegex()
val matches = pattern.findAll(input).toList() val matches = pattern.findAll(input).toList()
@@ -63,7 +63,7 @@ class RegexTest {
assertEquals(2, matches.size) assertEquals(2, matches.size)
} }
@test fun matchGroups() { @Test fun matchGroups() {
val input = "1a 2b 3c" val input = "1a 2b 3c"
val pattern = "(\\d)(\\w)".toRegex() val pattern = "(\\d)(\\w)".toRegex()
@@ -97,7 +97,7 @@ class RegexTest {
} }
} }
@test fun matchOptionalGroup() { @Test fun matchOptionalGroup() {
val pattern = "(hi)|(bye)".toRegex(RegexOption.IGNORE_CASE) val pattern = "(hi)|(bye)".toRegex(RegexOption.IGNORE_CASE)
pattern.find("Hi!")!!.let { m -> pattern.find("Hi!")!!.let { m ->
@@ -127,14 +127,14 @@ class RegexTest {
} }
} }
@test fun matchMultiline() { @Test fun matchMultiline() {
val regex = "^[a-z]*$".toRegex(setOf(RegexOption.IGNORE_CASE, RegexOption.MULTILINE)) val regex = "^[a-z]*$".toRegex(setOf(RegexOption.IGNORE_CASE, RegexOption.MULTILINE))
val matchedValues = regex.findAll("test\n\nLine").map { it.value }.toList() val matchedValues = regex.findAll("test\n\nLine").map { it.value }.toList()
assertEquals(listOf("test", "", "Line"), matchedValues) assertEquals(listOf("test", "", "Line"), matchedValues)
} }
@test fun matchEntire() { @Test fun matchEntire() {
val regex = "(\\d)(\\w)".toRegex() val regex = "(\\d)(\\w)".toRegex()
assertNull(regex.matchEntire("1a 2b")) assertNull(regex.matchEntire("1a 2b"))
@@ -145,7 +145,7 @@ class RegexTest {
} }
} }
@test fun matchEntireLazyQuantor() { @Test fun matchEntireLazyQuantor() {
val regex = "a+b+?".toRegex() val regex = "a+b+?".toRegex()
val input = StringBuilder("aaaabbbb") val input = StringBuilder("aaaabbbb")
@@ -153,13 +153,13 @@ class RegexTest {
assertEquals("aaaabbbb", regex.matchEntire(input)!!.value) assertEquals("aaaabbbb", regex.matchEntire(input)!!.value)
} }
@test fun escapeLiteral() { @Test fun escapeLiteral() {
val literal = """[-\/\\^$*+?.()|[\]{}]""" val literal = """[-\/\\^$*+?.()|[\]{}]"""
assertTrue(Regex.fromLiteral(literal).matches(literal)) assertTrue(Regex.fromLiteral(literal).matches(literal))
assertTrue(Regex.escape(literal).toRegex().matches(literal)) assertTrue(Regex.escape(literal).toRegex().matches(literal))
} }
@test fun replace() { @Test fun replace() {
val input = "123-456" val input = "123-456"
val pattern = "(\\d+)".toRegex() val pattern = "(\\d+)".toRegex()
assertEquals("(123)-(456)", pattern.replace(input, "($1)")) assertEquals("(123)-(456)", pattern.replace(input, "($1)"))
@@ -168,14 +168,14 @@ class RegexTest {
assertEquals("X-456", pattern.replaceFirst(input, "X")) assertEquals("X-456", pattern.replaceFirst(input, "X"))
} }
@test fun replaceEvaluator() { @Test fun replaceEvaluator() {
val input = "/12/456/7890/" val input = "/12/456/7890/"
val pattern = "\\d+".toRegex() val pattern = "\\d+".toRegex()
assertEquals("/2/3/4/", pattern.replace(input, { it.value.length.toString() } )) assertEquals("/2/3/4/", pattern.replace(input, { it.value.length.toString() } ))
} }
@test fun split() { @Test fun split() {
val input = """ val input = """
some ${"\t"} word some ${"\t"} word
split split
@@ -2,17 +2,17 @@
package test.text package test.text
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class StringBuilderJVMTest() { class StringBuilderJVMTest() {
@test fun stringBuildWithInitialCapacity() { @Test fun stringBuildWithInitialCapacity() {
val s = buildString(123) { val s = buildString(123) {
assertEquals(123, capacity()) assertEquals(123, capacity())
} }
} }
@test fun getAndSetChar() { @Test fun getAndSetChar() {
val sb = StringBuilder("abc") val sb = StringBuilder("abc")
sb[1] = 'z' sb[1] = 'z'
@@ -1,11 +1,11 @@
package test.text package test.text
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class StringBuilderTest { class StringBuilderTest {
@test fun stringBuild() { @Test fun stringBuild() {
val s = buildString { val s = buildString {
append("a") append("a")
append(true) append(true)
@@ -13,20 +13,20 @@ class StringBuilderTest {
assertEquals("atrue", s) assertEquals("atrue", s)
} }
@test fun appendMany() { @Test fun appendMany() {
assertEquals("a1", StringBuilder().append("a", "1").toString()) assertEquals("a1", StringBuilder().append("a", "1").toString())
assertEquals("a1", StringBuilder().append("a", 1).toString()) assertEquals("a1", StringBuilder().append("a", 1).toString())
assertEquals("a1", StringBuilder().append("a", StringBuilder().append("1")).toString()) assertEquals("a1", StringBuilder().append("a", StringBuilder().append("1")).toString())
} }
@test fun append() { @Test fun append() {
// this test is needed for JS implementation // this test is needed for JS implementation
assertEquals("em", buildString { assertEquals("em", buildString {
append("element", 2, 4) append("element", 2, 4)
}) })
} }
@test fun asCharSequence() { @Test fun asCharSequence() {
val original = "Some test string" val original = "Some test string"
val sb = StringBuilder(original) val sb = StringBuilder(original)
val result = sb.toString() val result = sb.toString()
@@ -41,7 +41,7 @@ class StringBuilderTest {
assertEquals(result.substring(2, 6), cs.subSequence(2, 6).toString()) assertEquals(result.substring(2, 6), cs.subSequence(2, 6).toString())
} }
@test fun constructors() { @Test fun constructors() {
StringBuilder().let { sb -> StringBuilder().let { sb ->
assertEquals(0, sb.length) assertEquals(0, sb.length)
assertEquals("", sb.toString()) assertEquals("", sb.toString())
+13 -13
View File
@@ -5,35 +5,35 @@ import test.collections.assertArrayNotSameButEquals
import java.util.Locale import java.util.Locale
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class StringJVMTest { class StringJVMTest {
@test fun toBoolean() { @Test fun toBoolean() {
assertEquals(true, "true".toBoolean()) assertEquals(true, "true".toBoolean())
assertEquals(true, "True".toBoolean()) assertEquals(true, "True".toBoolean())
assertEquals(false, "false".toBoolean()) assertEquals(false, "false".toBoolean())
assertEquals(false, "not so true".toBoolean()) assertEquals(false, "not so true".toBoolean())
} }
@test fun toByte() { @Test fun toByte() {
assertEquals(77.toByte(), "77".toByte()) assertEquals(77.toByte(), "77".toByte())
assertFails { "255".toByte() } assertFails { "255".toByte() }
} }
@test fun toShort() { @Test fun toShort() {
assertEquals(77.toShort(), "77".toShort()) assertEquals(77.toShort(), "77".toShort())
} }
@test fun toInt() { @Test fun toInt() {
assertEquals(77, "77".toInt()) assertEquals(77, "77".toInt())
} }
@test fun toLong() { @Test fun toLong() {
assertEquals(77.toLong(), "77".toLong()) assertEquals(77.toLong(), "77".toLong())
} }
@test fun testSplitByPattern() = withOneCharSequenceArg("ab1cd2def3") { s -> @Test fun testSplitByPattern() = withOneCharSequenceArg("ab1cd2def3") { s ->
val isDigit = "\\d".toRegex() val isDigit = "\\d".toRegex()
assertEquals(listOf("ab", "cd", "def", ""), s.split(isDigit)) assertEquals(listOf("ab", "cd", "def", ""), s.split(isDigit))
assertEquals(listOf("ab", "cd", "def3"), s.split(isDigit, 3)) assertEquals(listOf("ab", "cd", "def3"), s.split(isDigit, 3))
@@ -46,7 +46,7 @@ class StringJVMTest {
} }
} }
@test fun sliceCharSequenceFails() = withOneCharSequenceArg { arg1 -> @Test fun sliceCharSequenceFails() = withOneCharSequenceArg { arg1 ->
assertFails { assertFails {
arg1("abc").slice(1..4) arg1("abc").slice(1..4)
} }
@@ -55,7 +55,7 @@ class StringJVMTest {
} }
} }
@test fun formatter() { @Test fun formatter() {
assertEquals("12", "%d%d".format(1, 2)) assertEquals("12", "%d%d".format(1, 2))
assertEquals("12", String.format("%d%d", 1, 2)) assertEquals("12", String.format("%d%d", 1, 2))
@@ -67,12 +67,12 @@ class StringJVMTest {
assertEquals("1 234 567,890", String.format(Locale("fr"), "%,.3f", 1234567.890)) assertEquals("1 234 567,890", String.format(Locale("fr"), "%,.3f", 1234567.890))
} }
@test fun toByteArrayEncodings() { @Test fun toByteArrayEncodings() {
val s = "hello®" val s = "hello®"
assertEquals(String(s.toByteArray()), String(s.toByteArray(Charsets.UTF_8))) assertEquals(String(s.toByteArray()), String(s.toByteArray(Charsets.UTF_8)))
} }
@test fun toCharArray() { @Test fun toCharArray() {
val s = "hello" val s = "hello"
val chars = s.toCharArray() val chars = s.toCharArray()
assertArrayNotSameButEquals(charArrayOf('h', 'e', 'l', 'l', 'o'), chars) assertArrayNotSameButEquals(charArrayOf('h', 'e', 'l', 'l', 'o'), chars)
@@ -82,13 +82,13 @@ class StringJVMTest {
assertArrayNotSameButEquals(charArrayOf('\u0000', '\u0000', 'e', 'l'), buffer) assertArrayNotSameButEquals(charArrayOf('\u0000', '\u0000', 'e', 'l'), buffer)
} }
@test fun orderIgnoringCase() { @Test fun orderIgnoringCase() {
val list = listOf("Beast", "Ast", "asterisk") val list = listOf("Beast", "Ast", "asterisk")
assertEquals(listOf("Ast", "Beast", "asterisk"), list.sorted()) assertEquals(listOf("Ast", "Beast", "asterisk"), list.sorted())
assertEquals(listOf("Ast", "asterisk", "Beast"), list.sortedWith(String.CASE_INSENSITIVE_ORDER)) assertEquals(listOf("Ast", "asterisk", "Beast"), list.sortedWith(String.CASE_INSENSITIVE_ORDER))
} }
@test fun charsets() { @Test fun charsets() {
assertEquals("UTF-32", Charsets.UTF_32.name()) assertEquals("UTF-32", Charsets.UTF_32.name())
assertEquals("UTF-32LE", Charsets.UTF_32LE.name()) assertEquals("UTF-32LE", Charsets.UTF_32LE.name())
assertEquals("UTF-32BE", Charsets.UTF_32BE.name()) assertEquals("UTF-32BE", Charsets.UTF_32BE.name())
+93 -93
View File
@@ -17,7 +17,7 @@
package test.text package test.text
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
fun createString(content: String): CharSequence = content fun createString(content: String): CharSequence = content
@@ -50,7 +50,7 @@ fun Char.isAsciiUpperCase() = this in 'A'..'Z'
class StringTest { class StringTest {
@test fun isEmptyAndBlank() = withOneCharSequenceArg { arg1 -> @Test fun isEmptyAndBlank() = withOneCharSequenceArg { arg1 ->
class Case(val value: String?, val isNull: Boolean = false, val isEmpty: Boolean = false, val isBlank: Boolean = false) class Case(val value: String?, val isNull: Boolean = false, val isEmpty: Boolean = false, val isBlank: Boolean = false)
val cases = listOf( val cases = listOf(
@@ -72,7 +72,7 @@ class StringTest {
} }
} }
@test fun orEmpty() { @Test fun orEmpty() {
val s: String? = "hey" val s: String? = "hey"
val ns: String? = null val ns: String? = null
@@ -80,7 +80,7 @@ class StringTest {
assertEquals("", ns.orEmpty()) assertEquals("", ns.orEmpty())
} }
@test fun startsWithString() { @Test fun startsWithString() {
assertTrue("abcd".startsWith("ab")) assertTrue("abcd".startsWith("ab"))
assertTrue("abcd".startsWith("abcd")) assertTrue("abcd".startsWith("abcd"))
assertTrue("abcd".startsWith("a")) assertTrue("abcd".startsWith("a"))
@@ -94,7 +94,7 @@ class StringTest {
assertTrue("abcd".startsWith("aB", ignoreCase = true)) assertTrue("abcd".startsWith("aB", ignoreCase = true))
} }
@test fun startsWithStringForCharSequence() = withTwoCharSequenceArgs { arg1, arg2 -> @Test fun startsWithStringForCharSequence() = withTwoCharSequenceArgs { arg1, arg2 ->
fun String.startsWithCs(prefix: String, ignoreCase: Boolean = false): Boolean = fun String.startsWithCs(prefix: String, ignoreCase: Boolean = false): Boolean =
arg1(this).startsWith(arg2(prefix), ignoreCase) arg1(this).startsWith(arg2(prefix), ignoreCase)
@@ -111,7 +111,7 @@ class StringTest {
assertTrue("abcd".startsWithCs("aB", ignoreCase = true)) assertTrue("abcd".startsWithCs("aB", ignoreCase = true))
} }
@test fun endsWithString() { @Test fun endsWithString() {
assertTrue("abcd".endsWith("d")) assertTrue("abcd".endsWith("d"))
assertTrue("abcd".endsWith("abcd")) assertTrue("abcd".endsWith("abcd"))
assertFalse("abcd".endsWith("b")) assertFalse("abcd".endsWith("b"))
@@ -122,7 +122,7 @@ class StringTest {
assertTrue("".endsWith("")) assertTrue("".endsWith(""))
} }
@test fun endsWithStringForCharSequence() = withTwoCharSequenceArgs { arg1, arg2 -> @Test fun endsWithStringForCharSequence() = withTwoCharSequenceArgs { arg1, arg2 ->
fun String.endsWithCs(suffix: String, ignoreCase: Boolean = false): Boolean = fun String.endsWithCs(suffix: String, ignoreCase: Boolean = false): Boolean =
arg1(this).endsWith(arg2(suffix), ignoreCase) arg1(this).endsWith(arg2(suffix), ignoreCase)
@@ -136,7 +136,7 @@ class StringTest {
assertTrue("".endsWithCs("")) assertTrue("".endsWithCs(""))
} }
@test fun startsWithChar() = withOneCharSequenceArg { arg1 -> @Test fun startsWithChar() = withOneCharSequenceArg { arg1 ->
fun String.startsWith(char: Char, ignoreCase: Boolean = false): Boolean = fun String.startsWith(char: Char, ignoreCase: Boolean = false): Boolean =
arg1(this).startsWith(char, ignoreCase) arg1(this).startsWith(char, ignoreCase)
@@ -147,7 +147,7 @@ class StringTest {
assertFalse("".startsWith('a')) assertFalse("".startsWith('a'))
} }
@test fun endsWithChar() = withOneCharSequenceArg { arg1 -> @Test fun endsWithChar() = withOneCharSequenceArg { arg1 ->
fun String.endsWith(char: Char, ignoreCase: Boolean = false): Boolean = fun String.endsWith(char: Char, ignoreCase: Boolean = false): Boolean =
arg1(this).endsWith(char, ignoreCase) arg1(this).endsWith(char, ignoreCase)
@@ -158,7 +158,7 @@ class StringTest {
assertFalse("".endsWith('a')) assertFalse("".endsWith('a'))
} }
@test fun commonPrefix() = withTwoCharSequenceArgs { arg1, arg2 -> @Test fun commonPrefix() = withTwoCharSequenceArgs { arg1, arg2 ->
fun String.commonPrefixWith(other: String, ignoreCase: Boolean = false): String = fun String.commonPrefixWith(other: String, ignoreCase: Boolean = false): String =
arg1(this).commonPrefixWith(arg2(other), ignoreCase) arg1(this).commonPrefixWith(arg2(other), ignoreCase)
@@ -177,7 +177,7 @@ class StringTest {
assertEquals(dth54, "$dth54$dth54".commonPrefixWith("$dth54$dth55")) assertEquals(dth54, "$dth54$dth54".commonPrefixWith("$dth54$dth55"))
} }
@test fun commonSuffix() = withTwoCharSequenceArgs { arg1, arg2 -> @Test fun commonSuffix() = withTwoCharSequenceArgs { arg1, arg2 ->
fun String.commonSuffixWith(other: String, ignoreCase: Boolean = false): String = fun String.commonSuffixWith(other: String, ignoreCase: Boolean = false): String =
arg1(this).commonSuffixWith(arg2(other), ignoreCase) arg1(this).commonSuffixWith(arg2(other), ignoreCase)
@@ -196,14 +196,14 @@ class StringTest {
assertEquals("$dth54", "d$dth54".commonSuffixWith("s$dth54")) assertEquals("$dth54", "d$dth54".commonSuffixWith("s$dth54"))
} }
@test fun capitalize() { @Test fun capitalize() {
assertEquals("A", "A".capitalize()) assertEquals("A", "A".capitalize())
assertEquals("A", "a".capitalize()) assertEquals("A", "a".capitalize())
assertEquals("Abcd", "abcd".capitalize()) assertEquals("Abcd", "abcd".capitalize())
assertEquals("Abcd", "Abcd".capitalize()) assertEquals("Abcd", "Abcd".capitalize())
} }
@test fun decapitalize() { @Test fun decapitalize() {
assertEquals("a", "A".decapitalize()) assertEquals("a", "A".decapitalize())
assertEquals("a", "a".decapitalize()) assertEquals("a", "a".decapitalize())
assertEquals("abcd", "abcd".decapitalize()) assertEquals("abcd", "abcd".decapitalize())
@@ -211,7 +211,7 @@ class StringTest {
assertEquals("uRL", "URL".decapitalize()) assertEquals("uRL", "URL".decapitalize())
} }
@test fun slice() { @Test fun slice() {
val iter = listOf(4, 3, 0, 1) val iter = listOf(4, 3, 0, 1)
// abcde // abcde
// 01234 // 01234
@@ -220,7 +220,7 @@ class StringTest {
assertEquals("edab", "abcde".slice(iter)) assertEquals("edab", "abcde".slice(iter))
} }
@test fun sliceCharSequence() = withOneCharSequenceArg { arg1 -> @Test fun sliceCharSequence() = withOneCharSequenceArg { arg1 ->
val iter = listOf(4, 3, 0, 1) val iter = listOf(4, 3, 0, 1)
val data = arg1("ABCDabcd") val data = arg1("ABCDabcd")
@@ -231,13 +231,13 @@ class StringTest {
assertEquals("aDAB", data.slice(iter).toString()) assertEquals("aDAB", data.slice(iter).toString())
} }
@test fun reverse() { @Test fun reverse() {
assertEquals("dcba", "abcd".reversed()) assertEquals("dcba", "abcd".reversed())
assertEquals("4321", "1234".reversed()) assertEquals("4321", "1234".reversed())
assertEquals("", "".reversed()) assertEquals("", "".reversed())
} }
@test fun reverseCharSequence() = withOneCharSequenceArg { arg1 -> @Test fun reverseCharSequence() = withOneCharSequenceArg { arg1 ->
fun String.reversedCs(): CharSequence = arg1(this).reversed() fun String.reversedCs(): CharSequence = arg1(this).reversed()
assertContentEquals("dcba", "abcd".reversedCs()) assertContentEquals("dcba", "abcd".reversedCs())
@@ -245,7 +245,7 @@ class StringTest {
assertContentEquals("", "".reversedCs()) assertContentEquals("", "".reversedCs())
} }
@test fun indices() = withOneCharSequenceArg { arg1 -> @Test fun indices() = withOneCharSequenceArg { arg1 ->
fun String.indices(): IntRange = arg1(this).indices fun String.indices(): IntRange = arg1(this).indices
assertEquals(0..4, "abcde".indices()) assertEquals(0..4, "abcde".indices())
@@ -253,7 +253,7 @@ class StringTest {
assertTrue("".indices().isEmpty()) assertTrue("".indices().isEmpty())
} }
@test fun replaceRange() = withTwoCharSequenceArgs { arg1, arg2 -> @Test fun replaceRange() = withTwoCharSequenceArgs { arg1, arg2 ->
val s = arg1("sample text") val s = arg1("sample text")
val replacement = arg2("??") val replacement = arg2("??")
@@ -270,7 +270,7 @@ class StringTest {
assertContentEquals(replacement.toString(), s.replaceRange(s.indices, replacement)) assertContentEquals(replacement.toString(), s.replaceRange(s.indices, replacement))
} }
@test fun removeRange() = withOneCharSequenceArg("sample text") { s -> @Test fun removeRange() = withOneCharSequenceArg("sample text") { s ->
assertContentEquals("sae text", s.removeRange(2, 5)) assertContentEquals("sae text", s.removeRange(2, 5))
assertContentEquals("sa text", s.removeRange(2..5)) assertContentEquals("sa text", s.removeRange(2..5))
@@ -284,7 +284,7 @@ class StringTest {
assertContentEquals(s.toString().replaceRange(2..5, ""), s.removeRange(2..5)) assertContentEquals(s.toString().replaceRange(2..5, ""), s.removeRange(2..5))
} }
@test fun substringDelimited() { @Test fun substringDelimited() {
val s = "-1,22,3+" val s = "-1,22,3+"
// chars // chars
assertEquals("22,3+", s.substringAfter(',')) assertEquals("22,3+", s.substringAfter(','))
@@ -308,7 +308,7 @@ class StringTest {
} }
@test fun replaceDelimited() { @Test fun replaceDelimited() {
val s = "/user/folder/file.extension" val s = "/user/folder/file.extension"
// chars // chars
assertEquals("/user/folder/file.doc", s.replaceAfter('.', "doc")) assertEquals("/user/folder/file.doc", s.replaceAfter('.', "doc"))
@@ -331,7 +331,7 @@ class StringTest {
assertEquals("xxx", s.replaceBeforeLast("=", "/new/path", "xxx")) assertEquals("xxx", s.replaceBeforeLast("=", "/new/path", "xxx"))
} }
@test fun repeat() = withOneCharSequenceArg { arg1 -> @Test fun repeat() = withOneCharSequenceArg { arg1 ->
fun String.repeat(n: Int): String = arg1(this).repeat(n) fun String.repeat(n: Int): String = arg1(this).repeat(n)
assertFails { "foo".repeat(-1) } assertFails { "foo".repeat(-1) }
@@ -344,14 +344,14 @@ class StringTest {
assertEquals("aaaaaaaaaaaaa", "a".repeat(13)) assertEquals("aaaaaaaaaaaaa", "a".repeat(13))
} }
@test fun stringIterator() = withOneCharSequenceArg("239") { data -> @Test fun stringIterator() = withOneCharSequenceArg("239") { data ->
var sum = 0 var sum = 0
for(c in data) for(c in data)
sum += (c - '0') sum += (c - '0')
assertTrue(sum == 14) assertTrue(sum == 14)
} }
@test fun trimStart() = withOneCharSequenceArg { arg1 -> @Test fun trimStart() = withOneCharSequenceArg { arg1 ->
fun String.trimStartCS(): CharSequence = arg1(this).trimStart() fun String.trimStartCS(): CharSequence = arg1(this).trimStart()
assertContentEquals("", "".trimStartCS()) assertContentEquals("", "".trimStartCS())
assertContentEquals("a", "a".trimStartCS()) assertContentEquals("a", "a".trimStartCS())
@@ -371,7 +371,7 @@ class StringTest {
assertContentEquals("123a", arg1("ab123a").trimStart { !it.isAsciiDigit() }) assertContentEquals("123a", arg1("ab123a").trimStart { !it.isAsciiDigit() })
} }
@test fun trimEnd() = withOneCharSequenceArg { arg1 -> @Test fun trimEnd() = withOneCharSequenceArg { arg1 ->
fun String.trimEndCS(): CharSequence = arg1(this).trimEnd() fun String.trimEndCS(): CharSequence = arg1(this).trimEnd()
assertContentEquals("", "".trimEndCS()) assertContentEquals("", "".trimEndCS())
assertContentEquals("a", "a".trimEndCS()) assertContentEquals("a", "a".trimEndCS())
@@ -391,7 +391,7 @@ class StringTest {
assertContentEquals("ab123", arg1("ab123a").trimEnd { !it.isAsciiDigit() }) assertContentEquals("ab123", arg1("ab123a").trimEnd { !it.isAsciiDigit() })
} }
@test fun trimStartAndEnd() = withOneCharSequenceArg { arg1 -> @Test fun trimStartAndEnd() = withOneCharSequenceArg { arg1 ->
val examples = arrayOf("a", val examples = arrayOf("a",
" a ", " a ",
" a ", " a ",
@@ -420,7 +420,7 @@ class StringTest {
} }
} }
@test fun padStart() = withOneCharSequenceArg { arg1 -> @Test fun padStart() = withOneCharSequenceArg { arg1 ->
val s = arg1("s") val s = arg1("s")
assertContentEquals("s", s.padStart(0)) assertContentEquals("s", s.padStart(0))
assertContentEquals("s", s.padStart(1)) assertContentEquals("s", s.padStart(1))
@@ -431,7 +431,7 @@ class StringTest {
} }
} }
@test fun padEnd() = withOneCharSequenceArg { arg1 -> @Test fun padEnd() = withOneCharSequenceArg { arg1 ->
val s = arg1("s") val s = arg1("s")
assertContentEquals("s", s.padEnd(0)) assertContentEquals("s", s.padEnd(0))
assertContentEquals("s", s.padEnd(1)) assertContentEquals("s", s.padEnd(1))
@@ -442,21 +442,21 @@ class StringTest {
} }
} }
@test fun removePrefix() = withOneCharSequenceArg("pre") { prefix -> @Test fun removePrefix() = withOneCharSequenceArg("pre") { prefix ->
assertEquals("fix", "prefix".removePrefix(prefix), "Removes prefix") assertEquals("fix", "prefix".removePrefix(prefix), "Removes prefix")
assertEquals("prefix", "preprefix".removePrefix(prefix), "Removes prefix once") assertEquals("prefix", "preprefix".removePrefix(prefix), "Removes prefix once")
assertEquals("sample", "sample".removePrefix(prefix)) assertEquals("sample", "sample".removePrefix(prefix))
assertEquals("sample", "sample".removePrefix("")) assertEquals("sample", "sample".removePrefix(""))
} }
@test fun removeSuffix() = withOneCharSequenceArg("fix") { suffix -> @Test fun removeSuffix() = withOneCharSequenceArg("fix") { suffix ->
assertEquals("suf", "suffix".removeSuffix(suffix), "Removes suffix") assertEquals("suf", "suffix".removeSuffix(suffix), "Removes suffix")
assertEquals("suffix", "suffixfix".removeSuffix(suffix), "Removes suffix once") assertEquals("suffix", "suffixfix".removeSuffix(suffix), "Removes suffix once")
assertEquals("sample", "sample".removeSuffix(suffix)) assertEquals("sample", "sample".removeSuffix(suffix))
assertEquals("sample", "sample".removeSuffix("")) assertEquals("sample", "sample".removeSuffix(""))
} }
@test fun removeSurrounding() = withOneCharSequenceArg { arg1 -> @Test fun removeSurrounding() = withOneCharSequenceArg { arg1 ->
val pre = arg1("<") val pre = arg1("<")
val post = arg1(">") val post = arg1(">")
assertEquals("value", "<value>".removeSurrounding(pre, post)) assertEquals("value", "<value>".removeSurrounding(pre, post))
@@ -468,7 +468,7 @@ class StringTest {
assertEquals("<->", "<->".removeSurrounding(arg1("<-"), arg1("->")), "Does not remove overlapping prefix and suffix") assertEquals("<->", "<->".removeSurrounding(arg1("<-"), arg1("->")), "Does not remove overlapping prefix and suffix")
} }
@test fun removePrefixCharSequence() = withTwoCharSequenceArgs { arg1, arg2 -> @Test fun removePrefixCharSequence() = withTwoCharSequenceArgs { arg1, arg2 ->
fun String.removePrefix(prefix: String) = arg1(this).removePrefix(arg2(prefix)) fun String.removePrefix(prefix: String) = arg1(this).removePrefix(arg2(prefix))
val prefix = "pre" val prefix = "pre"
@@ -478,7 +478,7 @@ class StringTest {
assertContentEquals("sample", "sample".removePrefix("")) assertContentEquals("sample", "sample".removePrefix(""))
} }
@test fun removeSuffixCharSequence() = withTwoCharSequenceArgs { arg1, arg2 -> @Test fun removeSuffixCharSequence() = withTwoCharSequenceArgs { arg1, arg2 ->
fun String.removeSuffix(suffix: String) = arg1(this).removeSuffix(arg2(suffix)) fun String.removeSuffix(suffix: String) = arg1(this).removeSuffix(arg2(suffix))
val suffix = "fix" val suffix = "fix"
@@ -488,7 +488,7 @@ class StringTest {
assertContentEquals("sample", "sample".removeSuffix("")) assertContentEquals("sample", "sample".removeSuffix(""))
} }
@test fun removeSurroundingCharSequence() = withTwoCharSequenceArgs { arg1, arg2 -> @Test fun removeSurroundingCharSequence() = withTwoCharSequenceArgs { arg1, arg2 ->
fun String.removeSurrounding(prefix: String, postfix: String) = arg1(this).removeSurrounding(arg2(prefix), arg2(postfix)) fun String.removeSurrounding(prefix: String, postfix: String) = arg1(this).removeSurrounding(arg2(prefix), arg2(postfix))
assertContentEquals("value", "<value>".removeSurrounding("<", ">")) assertContentEquals("value", "<value>".removeSurrounding("<", ">"))
@@ -517,7 +517,7 @@ class StringTest {
*/ */
@test fun split() = withOneCharSequenceArg { arg1 -> @Test fun split() = withOneCharSequenceArg { arg1 ->
operator fun String.unaryPlus(): CharSequence = arg1(this) operator fun String.unaryPlus(): CharSequence = arg1(this)
assertEquals(listOf(""), (+"").split(";")) assertEquals(listOf(""), (+"").split(";"))
@@ -534,7 +534,7 @@ class StringTest {
assertEquals(listOf("", "", "b", "b", "", ""), (+"abba").split("a", "")) assertEquals(listOf("", "", "b", "b", "", ""), (+"abba").split("a", ""))
} }
@test fun splitToLines() = withOneCharSequenceArg { arg1 -> @Test fun splitToLines() = withOneCharSequenceArg { arg1 ->
val string = arg1("first line\rsecond line\nthird line\r\nlast line") val string = arg1("first line\rsecond line\nthird line\r\nlast line")
assertEquals(listOf("first line", "second line", "third line", "last line"), string.lines()) assertEquals(listOf("first line", "second line", "third line", "last line"), string.lines())
@@ -544,7 +544,7 @@ class StringTest {
} }
@test fun indexOfAnyChar() = withOneCharSequenceArg("abracadabra") { string -> @Test fun indexOfAnyChar() = withOneCharSequenceArg("abracadabra") { string ->
val chars = charArrayOf('d', 'b') val chars = charArrayOf('d', 'b')
assertEquals(1, string.indexOfAny(chars)) assertEquals(1, string.indexOfAny(chars))
assertEquals(6, string.indexOfAny(chars, startIndex = 2)) assertEquals(6, string.indexOfAny(chars, startIndex = 2))
@@ -557,7 +557,7 @@ class StringTest {
assertEquals(-1, string.indexOfAny(charArrayOf())) assertEquals(-1, string.indexOfAny(charArrayOf()))
} }
@test fun indexOfAnyCharIgnoreCase() = withOneCharSequenceArg("abraCadabra") { string -> @Test fun indexOfAnyCharIgnoreCase() = withOneCharSequenceArg("abraCadabra") { string ->
val chars = charArrayOf('B', 'c') val chars = charArrayOf('B', 'c')
assertEquals(1, string.indexOfAny(chars, ignoreCase = true)) assertEquals(1, string.indexOfAny(chars, ignoreCase = true))
assertEquals(4, string.indexOfAny(chars, startIndex = 2, ignoreCase = true)) assertEquals(4, string.indexOfAny(chars, startIndex = 2, ignoreCase = true))
@@ -568,7 +568,7 @@ class StringTest {
assertEquals(-1, string.lastIndexOfAny(chars, startIndex = 0, ignoreCase = true)) assertEquals(-1, string.lastIndexOfAny(chars, startIndex = 0, ignoreCase = true))
} }
@test fun indexOfAnyString() = withOneCharSequenceArg("abracadabra") { string -> @Test fun indexOfAnyString() = withOneCharSequenceArg("abracadabra") { string ->
val substrings = listOf("rac", "ra") val substrings = listOf("rac", "ra")
assertEquals(2, string.indexOfAny(substrings)) assertEquals(2, string.indexOfAny(substrings))
assertEquals(9, string.indexOfAny(substrings, startIndex = 3)) assertEquals(9, string.indexOfAny(substrings, startIndex = 3))
@@ -584,7 +584,7 @@ class StringTest {
assertEquals(-1, string.indexOfAny(listOf())) assertEquals(-1, string.indexOfAny(listOf()))
} }
@test fun indexOfAnyStringIgnoreCase() = withOneCharSequenceArg("aBraCadaBrA") { string -> @Test fun indexOfAnyStringIgnoreCase() = withOneCharSequenceArg("aBraCadaBrA") { string ->
val substrings = listOf("rAc", "Ra") val substrings = listOf("rAc", "Ra")
assertEquals(2, string.indexOfAny(substrings, ignoreCase = true)) assertEquals(2, string.indexOfAny(substrings, ignoreCase = true))
@@ -596,7 +596,7 @@ class StringTest {
assertEquals(-1, string.lastIndexOfAny(substrings, startIndex = 1, ignoreCase = true)) assertEquals(-1, string.lastIndexOfAny(substrings, startIndex = 1, ignoreCase = true))
} }
@test fun findAnyOfStrings() = withOneCharSequenceArg("abracadabra") { string -> @Test fun findAnyOfStrings() = withOneCharSequenceArg("abracadabra") { string ->
val substrings = listOf("rac", "ra") val substrings = listOf("rac", "ra")
assertEquals(2 to "rac", string.findAnyOf(substrings)) assertEquals(2 to "rac", string.findAnyOf(substrings))
assertEquals(9 to "ra", string.findAnyOf(substrings, startIndex = 3)) assertEquals(9 to "ra", string.findAnyOf(substrings, startIndex = 3))
@@ -612,7 +612,7 @@ class StringTest {
assertEquals(null, string.findAnyOf(listOf())) assertEquals(null, string.findAnyOf(listOf()))
} }
@test fun findAnyOfStringsIgnoreCase() = withOneCharSequenceArg("aBraCadaBrA") { string -> @Test fun findAnyOfStringsIgnoreCase() = withOneCharSequenceArg("aBraCadaBrA") { string ->
val substrings = listOf("rAc", "Ra") val substrings = listOf("rAc", "Ra")
assertEquals(2 to substrings[0], string.findAnyOf(substrings, ignoreCase = true)) assertEquals(2 to substrings[0], string.findAnyOf(substrings, ignoreCase = true))
@@ -624,7 +624,7 @@ class StringTest {
assertEquals(null, string.findLastAnyOf(substrings, startIndex = 1, ignoreCase = true)) assertEquals(null, string.findLastAnyOf(substrings, startIndex = 1, ignoreCase = true))
} }
@test fun indexOfChar() = withOneCharSequenceArg("bcedef") { string -> @Test fun indexOfChar() = withOneCharSequenceArg("bcedef") { string ->
assertEquals(-1, string.indexOf('a')) assertEquals(-1, string.indexOf('a'))
assertEquals(2, string.indexOf('e')) assertEquals(2, string.indexOf('e'))
assertEquals(2, string.indexOf('e', 2)) assertEquals(2, string.indexOf('e', 2))
@@ -639,7 +639,7 @@ class StringTest {
} }
@test fun indexOfCharIgnoreCase() = withOneCharSequenceArg("bCEdef") { string -> @Test fun indexOfCharIgnoreCase() = withOneCharSequenceArg("bCEdef") { string ->
assertEquals(-1, string.indexOf('a', ignoreCase = true)) assertEquals(-1, string.indexOf('a', ignoreCase = true))
assertEquals(2, string.indexOf('E', ignoreCase = true)) assertEquals(2, string.indexOf('E', ignoreCase = true))
assertEquals(2, string.indexOf('e', 2, ignoreCase = true)) assertEquals(2, string.indexOf('e', 2, ignoreCase = true))
@@ -654,7 +654,7 @@ class StringTest {
} }
} }
@test fun indexOfString() = withOneCharSequenceArg("bceded") { string -> @Test fun indexOfString() = withOneCharSequenceArg("bceded") { string ->
for (index in string.indices) for (index in string.indices)
assertEquals(index, string.indexOf("", index)) assertEquals(index, string.indexOf("", index))
assertEquals(1, string.indexOf("ced")) assertEquals(1, string.indexOf("ced"))
@@ -662,7 +662,7 @@ class StringTest {
assertEquals(-1, string.indexOf("abcdefgh")) assertEquals(-1, string.indexOf("abcdefgh"))
} }
@test fun indexOfStringIgnoreCase() = withOneCharSequenceArg("bceded") { string -> @Test fun indexOfStringIgnoreCase() = withOneCharSequenceArg("bceded") { string ->
for (index in string.indices) for (index in string.indices)
assertEquals(index, string.indexOf("", index, ignoreCase = true)) assertEquals(index, string.indexOf("", index, ignoreCase = true))
assertEquals(1, string.indexOf("cEd", ignoreCase = true)) assertEquals(1, string.indexOf("cEd", ignoreCase = true))
@@ -671,7 +671,7 @@ class StringTest {
} }
@test fun contains() = withTwoCharSequenceArgs { arg1, arg2 -> @Test fun contains() = withTwoCharSequenceArgs { arg1, arg2 ->
operator fun String.contains(other: String): Boolean = arg1(this).contains(arg2(other)) operator fun String.contains(other: String): Boolean = arg1(this).contains(arg2(other))
operator fun String.contains(other: Char): Boolean = arg1(this).contains(other) operator fun String.contains(other: Char): Boolean = arg1(this).contains(other)
@@ -687,7 +687,7 @@ class StringTest {
assertTrue(arg1("sömple").contains('Ö', ignoreCase = true)) assertTrue(arg1("sömple").contains('Ö', ignoreCase = true))
} }
@test fun equalsIgnoreCase() { @Test fun equalsIgnoreCase() {
assertFalse("sample".equals("Sample", ignoreCase = false)) assertFalse("sample".equals("Sample", ignoreCase = false))
assertTrue("sample".equals("Sample", ignoreCase = true)) assertTrue("sample".equals("Sample", ignoreCase = true))
assertFalse("sample".equals(null, ignoreCase = false)) assertFalse("sample".equals(null, ignoreCase = false))
@@ -697,7 +697,7 @@ class StringTest {
} }
@test fun replace() { @Test fun replace() {
val input = "abbAb" val input = "abbAb"
assertEquals("abb${'$'}b", input.replace('A', '$')) assertEquals("abb${'$'}b", input.replace('A', '$'))
assertEquals("/bb/b", input.replace('A', '/', ignoreCase = true)) assertEquals("/bb/b", input.replace('A', '/', ignoreCase = true))
@@ -708,7 +708,7 @@ class StringTest {
assertEquals("-a-b-b-A-b-", input.replace("", "-")) assertEquals("-a-b-b-A-b-", input.replace("", "-"))
} }
@test fun replaceFirst() { @Test fun replaceFirst() {
val input = "AbbabA" val input = "AbbabA"
assertEquals("Abb${'$'}bA", input.replaceFirst('a','$')) assertEquals("Abb${'$'}bA", input.replaceFirst('a','$'))
assertEquals("${'$'}bbabA", input.replaceFirst('a','$', ignoreCase = true)) assertEquals("${'$'}bbabA", input.replaceFirst('a','$', ignoreCase = true))
@@ -721,12 +721,12 @@ class StringTest {
assertEquals("-test", "test".replaceFirst("", "-")) assertEquals("-test", "test".replaceFirst("", "-"))
} }
@test fun count() = withOneCharSequenceArg("hello there\tfoo\nbar") { text -> @Test fun count() = withOneCharSequenceArg("hello there\tfoo\nbar") { text ->
val whitespaceCount = text.count { it.isWhitespace() } val whitespaceCount = text.count { it.isWhitespace() }
assertEquals(3, whitespaceCount) assertEquals(3, whitespaceCount)
} }
@test fun testSplitByChar() = withOneCharSequenceArg("ab\n[|^$&\\]^cd") { s -> @Test fun testSplitByChar() = withOneCharSequenceArg("ab\n[|^$&\\]^cd") { s ->
s.split('b').let { list -> s.split('b').let { list ->
assertEquals(2, list.size) assertEquals(2, list.size)
assertEquals("a", list[0]) assertEquals("a", list[0])
@@ -742,7 +742,7 @@ class StringTest {
} }
} }
@test fun forEach() = withOneCharSequenceArg("abcd1234") { data -> @Test fun forEach() = withOneCharSequenceArg("abcd1234") { data ->
var count = 0 var count = 0
val sb = StringBuilder() val sb = StringBuilder()
data.forEach { data.forEach {
@@ -754,36 +754,36 @@ class StringTest {
} }
@test fun filter() { @Test fun filter() {
assertEquals("acdca", ("abcdcba").filter { !it.equals('b') }) assertEquals("acdca", ("abcdcba").filter { !it.equals('b') })
assertEquals("1234", ("a1b2c3d4").filter { it.isAsciiDigit() }) assertEquals("1234", ("a1b2c3d4").filter { it.isAsciiDigit() })
} }
@test fun filterCharSequence() = withOneCharSequenceArg { arg1 -> @Test fun filterCharSequence() = withOneCharSequenceArg { arg1 ->
assertContentEquals("acdca", arg1("abcdcba").filter { !it.equals('b') }) assertContentEquals("acdca", arg1("abcdcba").filter { !it.equals('b') })
assertContentEquals("1234", arg1("a1b2c3d4").filter { it.isAsciiDigit() }) assertContentEquals("1234", arg1("a1b2c3d4").filter { it.isAsciiDigit() })
} }
@test fun filterNot() { @Test fun filterNot() {
assertEquals("acdca", ("abcdcba").filterNot { it.equals('b') }) assertEquals("acdca", ("abcdcba").filterNot { it.equals('b') })
assertEquals("abcd", ("a1b2c3d4").filterNot { it.isAsciiDigit() }) assertEquals("abcd", ("a1b2c3d4").filterNot { it.isAsciiDigit() })
} }
@test fun filterNotCharSequence() = withOneCharSequenceArg { arg1 -> @Test fun filterNotCharSequence() = withOneCharSequenceArg { arg1 ->
assertContentEquals("acdca", arg1("abcdcba").filterNot { it.equals('b') }) assertContentEquals("acdca", arg1("abcdcba").filterNot { it.equals('b') })
assertContentEquals("abcd", arg1("a1b2c3d4").filterNot { it.isAsciiDigit() }) assertContentEquals("abcd", arg1("a1b2c3d4").filterNot { it.isAsciiDigit() })
} }
@test fun filterIndexed() { @Test fun filterIndexed() {
val data = "abedcf" val data = "abedcf"
assertEquals("abdf", data.filterIndexed { index, c -> c == 'a' + index }) assertEquals("abdf", data.filterIndexed { index, c -> c == 'a' + index })
} }
@test fun filterIndexedCharSequence() = withOneCharSequenceArg("abedcf") { data -> @Test fun filterIndexedCharSequence() = withOneCharSequenceArg("abedcf") { data ->
assertContentEquals("abdf", data.filterIndexed { index, c -> c == 'a' + index }) assertContentEquals("abdf", data.filterIndexed { index, c -> c == 'a' + index })
} }
@test fun all() = withOneCharSequenceArg("AbCd") { data -> @Test fun all() = withOneCharSequenceArg("AbCd") { data ->
assertTrue { assertTrue {
data.all { it.isAsciiLetter() } data.all { it.isAsciiLetter() }
} }
@@ -792,7 +792,7 @@ class StringTest {
} }
} }
@test fun any() = withOneCharSequenceArg("a1bc") { data -> @Test fun any() = withOneCharSequenceArg("a1bc") { data ->
assertTrue { assertTrue {
data.any() { it.isAsciiDigit() } data.any() { it.isAsciiDigit() }
} }
@@ -801,30 +801,30 @@ class StringTest {
} }
} }
@test fun find() = withOneCharSequenceArg("a1b2c3") { data -> @Test fun find() = withOneCharSequenceArg("a1b2c3") { data ->
assertEquals('1', data.first { it.isAsciiDigit() }) assertEquals('1', data.first { it.isAsciiDigit() })
assertNull(data.firstOrNull { it.isAsciiUpperCase() }) assertNull(data.firstOrNull { it.isAsciiUpperCase() })
} }
@test fun findNot() = withOneCharSequenceArg("1a2b3c") { data -> @Test fun findNot() = withOneCharSequenceArg("1a2b3c") { data ->
assertEquals('a', data.filterNot { it.isAsciiDigit() }.firstOrNull()) assertEquals('a', data.filterNot { it.isAsciiDigit() }.firstOrNull())
assertNull(data.filterNot { it.isAsciiLetter() || it.isAsciiDigit() }.firstOrNull()) assertNull(data.filterNot { it.isAsciiLetter() || it.isAsciiDigit() }.firstOrNull())
} }
@test fun partition() { @Test fun partition() {
val data = "a1b2c3" val data = "a1b2c3"
val pair = data.partition { it.isAsciiDigit() } val pair = data.partition { it.isAsciiDigit() }
assertEquals("123", pair.first, "pair.first") assertEquals("123", pair.first, "pair.first")
assertEquals("abc", pair.second, "pair.second") assertEquals("abc", pair.second, "pair.second")
} }
@test fun partitionCharSequence() = withOneCharSequenceArg("a1b2c3") { data -> @Test fun partitionCharSequence() = withOneCharSequenceArg("a1b2c3") { data ->
val pair = data.partition { it.isAsciiDigit() } val pair = data.partition { it.isAsciiDigit() }
assertContentEquals("123", pair.first, "pair.first") assertContentEquals("123", pair.first, "pair.first")
assertContentEquals("abc", pair.second, "pair.second") assertContentEquals("abc", pair.second, "pair.second")
} }
@test fun map() = withOneCharSequenceArg { arg1 -> @Test fun map() = withOneCharSequenceArg { arg1 ->
assertEquals(listOf('a', 'b', 'c'), arg1("abc").map { it }) assertEquals(listOf('a', 'b', 'c'), arg1("abc").map { it })
assertEquals(listOf(true, false, true), arg1("AbC").map { it.isAsciiUpperCase() }) assertEquals(listOf(true, false, true), arg1("AbC").map { it.isAsciiUpperCase() })
@@ -834,7 +834,7 @@ class StringTest {
assertEquals(listOf(97, 98, 99), arg1("abc").map { it.toInt() }) assertEquals(listOf(97, 98, 99), arg1("abc").map { it.toInt() })
} }
@test fun mapTo() = withOneCharSequenceArg { arg1 -> @Test fun mapTo() = withOneCharSequenceArg { arg1 ->
val result1 = arrayListOf<Char>() val result1 = arrayListOf<Char>()
val return1 = arg1("abc").mapTo(result1, { it }) val return1 = arg1("abc").mapTo(result1, { it })
assertEquals(result1, return1) assertEquals(result1, return1)
@@ -856,12 +856,12 @@ class StringTest {
assertEquals(arrayListOf(97, 98, 99), result4) assertEquals(arrayListOf(97, 98, 99), result4)
} }
@test fun flatMap() = withOneCharSequenceArg("abcd") { data -> @Test fun flatMap() = withOneCharSequenceArg("abcd") { data ->
val result = data.flatMap { ('a'..it) + ' ' } val result = data.flatMap { ('a'..it) + ' ' }
assertEquals("a ab abc abcd ".toList(), result) assertEquals("a ab abc abcd ".toList(), result)
} }
@test fun fold() = withOneCharSequenceArg { arg1 -> @Test fun fold() = withOneCharSequenceArg { arg1 ->
// calculate number of digits in the string // calculate number of digits in the string
val data = arg1("a1b2c3def") val data = arg1("a1b2c3def")
val result = data.fold(0, { digits, c -> if(c.isAsciiDigit()) digits + 1 else digits } ) val result = data.fold(0, { digits, c -> if(c.isAsciiDigit()) digits + 1 else digits } )
@@ -874,7 +874,7 @@ class StringTest {
assertEquals(data.toString(), data.fold("", { s, c -> s + c })) assertEquals(data.toString(), data.fold("", { s, c -> s + c }))
} }
@test fun foldRight() = withOneCharSequenceArg { arg1 -> @Test fun foldRight() = withOneCharSequenceArg { arg1 ->
// calculate number of digits in the string // calculate number of digits in the string
val data = arg1("a1b2c3def") val data = arg1("a1b2c3def")
val result = data.foldRight(0, { c, digits -> if(c.isAsciiDigit()) digits + 1 else digits }) val result = data.foldRight(0, { c, digits -> if(c.isAsciiDigit()) digits + 1 else digits })
@@ -887,7 +887,7 @@ class StringTest {
assertEquals(data.toString(), data.foldRight("", { s, c -> "" + s + c })) assertEquals(data.toString(), data.foldRight("", { s, c -> "" + s + c }))
} }
@test fun reduceIndexed() = withOneCharSequenceArg { arg1 -> @Test fun reduceIndexed() = withOneCharSequenceArg { arg1 ->
// get the 3rd character // get the 3rd character
assertEquals('c', arg1("bacfd").reduceIndexed { index, v, c -> if (index == 2) c else v }) assertEquals('c', arg1("bacfd").reduceIndexed { index, v, c -> if (index == 2) c else v })
@@ -905,7 +905,7 @@ class StringTest {
} }
} }
@test fun reduceRightIndexed() = withOneCharSequenceArg { arg1 -> @Test fun reduceRightIndexed() = withOneCharSequenceArg { arg1 ->
// get the 3rd character // get the 3rd character
assertEquals('c', arg1("bacfd").reduceRightIndexed { index, c, v -> if (index == 2) c else v }) assertEquals('c', arg1("bacfd").reduceRightIndexed { index, c, v -> if (index == 2) c else v })
@@ -923,7 +923,7 @@ class StringTest {
} }
} }
@test fun reduce() = withOneCharSequenceArg { arg1 -> @Test fun reduce() = withOneCharSequenceArg { arg1 ->
// get the smallest character(by char value) // get the smallest character(by char value)
assertEquals('a', arg1("bacfd").reduce { v, c -> if (v > c) c else v }) assertEquals('a', arg1("bacfd").reduce { v, c -> if (v > c) c else v })
@@ -932,7 +932,7 @@ class StringTest {
} }
} }
@test fun reduceRight() = withOneCharSequenceArg { arg1 -> @Test fun reduceRight() = withOneCharSequenceArg { arg1 ->
// get the smallest character(by char value) // get the smallest character(by char value)
assertEquals('a', arg1("bacfd").reduceRight { c, v -> if (v > c) c else v }) assertEquals('a', arg1("bacfd").reduceRight { c, v -> if (v > c) c else v })
@@ -941,7 +941,7 @@ class StringTest {
} }
} }
@test fun groupBy() = withOneCharSequenceArg("abAbaABcD") { data -> @Test fun groupBy() = withOneCharSequenceArg("abAbaABcD") { data ->
// group characters by their case // group characters by their case
val result = data.groupBy { it.isAsciiUpperCase() } val result = data.groupBy { it.isAsciiUpperCase() }
assertEquals(2, result.size) assertEquals(2, result.size)
@@ -949,7 +949,7 @@ class StringTest {
assertEquals(listOf('A','A','B','D'), result[true]) assertEquals(listOf('A','A','B','D'), result[true])
} }
@test fun joinToString() { @Test fun joinToString() {
val data = "abcd".toList() val data = "abcd".toList()
val result = data.joinToString("_", "(", ")") val result = data.joinToString("_", "(", ")")
assertEquals("(a_b_c_d)", result) assertEquals("(a_b_c_d)", result)
@@ -963,7 +963,7 @@ class StringTest {
assertEquals("A, 1, /, B", result3) assertEquals("A, 1, /, B", result3)
} }
@test fun joinTo() { @Test fun joinTo() {
val data = "kotlin".toList() val data = "kotlin".toList()
val sb = StringBuilder() val sb = StringBuilder()
data.joinTo(sb, "^", "<", ">") data.joinTo(sb, "^", "<", ">")
@@ -971,21 +971,21 @@ class StringTest {
} }
@test fun dropWhile() { @Test fun dropWhile() {
val data = "ab1cd2" val data = "ab1cd2"
assertEquals("1cd2", data.dropWhile { it.isAsciiLetter() }) assertEquals("1cd2", data.dropWhile { it.isAsciiLetter() })
assertEquals("", data.dropWhile { true }) assertEquals("", data.dropWhile { true })
assertEquals("ab1cd2", data.dropWhile { false }) assertEquals("ab1cd2", data.dropWhile { false })
} }
@test fun dropWhileCharSequence() = withOneCharSequenceArg("ab1cd2") { data -> @Test fun dropWhileCharSequence() = withOneCharSequenceArg("ab1cd2") { data ->
assertContentEquals("1cd2", data.dropWhile { it.isAsciiLetter() }) assertContentEquals("1cd2", data.dropWhile { it.isAsciiLetter() })
assertContentEquals("", data.dropWhile { true }) assertContentEquals("", data.dropWhile { true })
assertContentEquals("ab1cd2", data.dropWhile { false }) assertContentEquals("ab1cd2", data.dropWhile { false })
} }
@test fun drop() { @Test fun drop() {
val data = "abcd1234" val data = "abcd1234"
assertEquals("d1234", data.drop(3)) assertEquals("d1234", data.drop(3))
assertFails { assertFails {
@@ -994,7 +994,7 @@ class StringTest {
assertEquals("", data.drop(data.length + 5)) assertEquals("", data.drop(data.length + 5))
} }
@test fun dropCharSequence() = withOneCharSequenceArg("abcd1234") { data -> @Test fun dropCharSequence() = withOneCharSequenceArg("abcd1234") { data ->
assertContentEquals("d1234", data.drop(3)) assertContentEquals("d1234", data.drop(3))
assertFails { assertFails {
data.drop(-2) data.drop(-2)
@@ -1002,20 +1002,20 @@ class StringTest {
assertContentEquals("", data.drop(data.length + 5)) assertContentEquals("", data.drop(data.length + 5))
} }
@test fun takeWhile() { @Test fun takeWhile() {
val data = "ab1cd2" val data = "ab1cd2"
assertEquals("ab", data.takeWhile { it.isAsciiLetter() }) assertEquals("ab", data.takeWhile { it.isAsciiLetter() })
assertEquals("", data.takeWhile { false }) assertEquals("", data.takeWhile { false })
assertEquals("ab1cd2", data.takeWhile { true }) assertEquals("ab1cd2", data.takeWhile { true })
} }
@test fun takeWhileCharSequence() = withOneCharSequenceArg("ab1cd2") { data -> @Test fun takeWhileCharSequence() = withOneCharSequenceArg("ab1cd2") { data ->
assertContentEquals("ab", data.takeWhile { it.isAsciiLetter() }) assertContentEquals("ab", data.takeWhile { it.isAsciiLetter() })
assertContentEquals("", data.takeWhile { false }) assertContentEquals("", data.takeWhile { false })
assertContentEquals("ab1cd2", data.takeWhile { true }) assertContentEquals("ab1cd2", data.takeWhile { true })
} }
@test fun take() { @Test fun take() {
val data = "abcd1234" val data = "abcd1234"
assertEquals("abc", data.take(3)) assertEquals("abc", data.take(3))
assertFails { assertFails {
@@ -1024,7 +1024,7 @@ class StringTest {
assertEquals(data, data.take(data.length + 42)) assertEquals(data, data.take(data.length + 42))
} }
@test fun takeCharSequence() = withOneCharSequenceArg("abcd1234") { data -> @Test fun takeCharSequence() = withOneCharSequenceArg("abcd1234") { data ->
assertEquals("abc", data.take(3)) assertEquals("abc", data.take(3))
assertFails { assertFails {
data.take(-7) data.take(-7)
@@ -1033,28 +1033,28 @@ class StringTest {
} }
@test fun testReplaceAllClosure() = withOneCharSequenceArg("test123zzz") { s -> @Test fun testReplaceAllClosure() = withOneCharSequenceArg("test123zzz") { s ->
val result = s.replace("\\d+".toRegex()) { mr -> val result = s.replace("\\d+".toRegex()) { mr ->
"[" + mr.value + "]" "[" + mr.value + "]"
} }
assertEquals("test[123]zzz", result) assertEquals("test[123]zzz", result)
} }
@test fun testReplaceAllClosureAtStart() = withOneCharSequenceArg("123zzz") { s -> @Test fun testReplaceAllClosureAtStart() = withOneCharSequenceArg("123zzz") { s ->
val result = s.replace("\\d+".toRegex()) { mr -> val result = s.replace("\\d+".toRegex()) { mr ->
"[" + mr.value + "]" "[" + mr.value + "]"
} }
assertEquals("[123]zzz", result) assertEquals("[123]zzz", result)
} }
@test fun testReplaceAllClosureAtEnd() = withOneCharSequenceArg("test123") { s -> @Test fun testReplaceAllClosureAtEnd() = withOneCharSequenceArg("test123") { s ->
val result = s.replace("\\d+".toRegex()) { mr -> val result = s.replace("\\d+".toRegex()) { mr ->
"[" + mr.value + "]" "[" + mr.value + "]"
} }
assertEquals("test[123]", result) assertEquals("test[123]", result)
} }
@test fun testReplaceAllClosureEmpty() = withOneCharSequenceArg("") { s -> @Test fun testReplaceAllClosureEmpty() = withOneCharSequenceArg("") { s ->
val result = s.replace("\\d+".toRegex()) { mr -> val result = s.replace("\\d+".toRegex()) { mr ->
"x" "x"
} }
@@ -1062,7 +1062,7 @@ class StringTest {
} }
@test fun trimMargin() { @Test fun trimMargin() {
// WARNING // WARNING
// DO NOT REFORMAT AS TESTS MAY FAIL DUE TO INDENTATION CHANGE // DO NOT REFORMAT AS TESTS MAY FAIL DUE TO INDENTATION CHANGE
@@ -1109,7 +1109,7 @@ class StringTest {
assertEquals("\u0000|ABC", "${"\u0000"}|ABC".trimMargin()) assertEquals("\u0000|ABC", "${"\u0000"}|ABC".trimMargin())
} }
@test fun trimIndent() { @Test fun trimIndent() {
// WARNING // WARNING
// DO NOT REFORMAT AS TESTS MAY FAIL DUE TO INDENTATION CHANGE // DO NOT REFORMAT AS TESTS MAY FAIL DUE TO INDENTATION CHANGE
@@ -1173,7 +1173,7 @@ ${" "}
assertEquals(1, deindented.lines().count { it.isEmpty() }) assertEquals(1, deindented.lines().count { it.isEmpty() })
} }
@test fun testIndent() { @Test fun testIndent() {
assertEquals(" ABC\n 123", "ABC\n123".prependIndent(" ")) assertEquals(" ABC\n 123", "ABC\n123".prependIndent(" "))
assertEquals(" ABC\n \n 123", "ABC\n\n123".prependIndent(" ")) assertEquals(" ABC\n \n 123", "ABC\n\n123".prependIndent(" "))
assertEquals(" ABC\n \n 123", "ABC\n \n123".prependIndent(" ")) assertEquals(" ABC\n \n 123", "ABC\n \n123".prependIndent(" "))
+5 -5
View File
@@ -8,11 +8,11 @@ import java.io.*
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicInteger
import kotlin.concurrent.thread import kotlin.concurrent.thread
import org.junit.Test as test import org.junit.Test
class LazyJVMTest { class LazyJVMTest {
@test fun synchronizedLazy() { @Test fun synchronizedLazy() {
val counter = AtomicInteger(0) val counter = AtomicInteger(0)
val lazy = lazy { val lazy = lazy {
val value = counter.incrementAndGet() val value = counter.incrementAndGet()
@@ -26,7 +26,7 @@ class LazyJVMTest {
assertEquals(1, counter.get()) assertEquals(1, counter.get())
} }
@test fun externallySynchronizedLazy() { @Test fun externallySynchronizedLazy() {
val counter = AtomicInteger(0) val counter = AtomicInteger(0)
var initialized: Boolean = false var initialized: Boolean = false
val runs = ConcurrentHashMap<Int, Boolean>() val runs = ConcurrentHashMap<Int, Boolean>()
@@ -51,7 +51,7 @@ class LazyJVMTest {
} }
} }
@test fun publishOnceLazy() { @Test fun publishOnceLazy() {
val counter = AtomicInteger(0) val counter = AtomicInteger(0)
var initialized: Boolean = false var initialized: Boolean = false
val runs = ConcurrentHashMap<Int, Boolean>() val runs = ConcurrentHashMap<Int, Boolean>()
@@ -75,7 +75,7 @@ class LazyJVMTest {
} }
} }
@test fun lazyInitializationForcedOnSerialization() { @Test fun lazyInitializationForcedOnSerialization() {
for(mode in listOf(LazyThreadSafetyMode.SYNCHRONIZED, LazyThreadSafetyMode.PUBLICATION, LazyThreadSafetyMode.NONE)) { for(mode in listOf(LazyThreadSafetyMode.SYNCHRONIZED, LazyThreadSafetyMode.PUBLICATION, LazyThreadSafetyMode.NONE)) {
val lazy = lazy(mode) { "initialized" } val lazy = lazy(mode) { "initialized" }
assertFalse(lazy.isInitialized()) assertFalse(lazy.isInitialized())
+4 -4
View File
@@ -2,11 +2,11 @@ package test.utils
import kotlin.* import kotlin.*
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class LazyTest { class LazyTest {
@test fun initializationCalledOnce() { @Test fun initializationCalledOnce() {
var callCount = 0 var callCount = 0
val lazyInt = lazy { ++callCount } val lazyInt = lazy { ++callCount }
@@ -20,7 +20,7 @@ class LazyTest {
assertEquals(1, callCount) assertEquals(1, callCount)
} }
@test fun alreadyInitialized() { @Test fun alreadyInitialized() {
val lazyInt = lazyOf(1) val lazyInt = lazyOf(1)
assertTrue(lazyInt.isInitialized()) assertTrue(lazyInt.isInitialized())
@@ -28,7 +28,7 @@ class LazyTest {
} }
@test fun lazyToString() { @Test fun lazyToString() {
var callCount = 0 var callCount = 0
val lazyInt = lazy { ++callCount } val lazyInt = lazy { ++callCount }
@@ -1,12 +1,12 @@
@file:kotlin.jvm.JvmVersion @file:kotlin.jvm.JvmVersion
package test.utils package test.utils
import org.junit.Test as test import org.junit.Test
import kotlin.test.* import kotlin.test.*
class PreconditionsJVMTest() { class PreconditionsJVMTest() {
@test fun passingRequire() { @Test fun passingRequire() {
require(true) require(true)
var called = false var called = false
@@ -14,21 +14,21 @@ class PreconditionsJVMTest() {
assertFalse(called) assertFalse(called)
} }
@test fun failingRequire() { @Test fun failingRequire() {
val error = assertFailsWith(IllegalArgumentException::class) { val error = assertFailsWith(IllegalArgumentException::class) {
require(false) require(false)
} }
assertNotNull(error.message) assertNotNull(error.message)
} }
@test fun failingRequireWithLazyMessage() { @Test fun failingRequireWithLazyMessage() {
val error = assertFailsWith(IllegalArgumentException::class) { val error = assertFailsWith(IllegalArgumentException::class) {
require(false) { "Hello" } require(false) { "Hello" }
} }
assertEquals("Hello", error.message) assertEquals("Hello", error.message)
} }
@test fun passingCheck() { @Test fun passingCheck() {
check(true) check(true)
var called = false var called = false
@@ -36,34 +36,34 @@ class PreconditionsJVMTest() {
assertFalse(called) assertFalse(called)
} }
@test fun failingCheck() { @Test fun failingCheck() {
val error = assertFailsWith(IllegalStateException::class) { val error = assertFailsWith(IllegalStateException::class) {
check(false) check(false)
} }
assertNotNull(error.message) assertNotNull(error.message)
} }
@test fun failingCheckWithLazyMessage() { @Test fun failingCheckWithLazyMessage() {
val error = assertFailsWith(IllegalStateException::class) { val error = assertFailsWith(IllegalStateException::class) {
check(false) { "Hello" } check(false) { "Hello" }
} }
assertEquals("Hello", error.message) assertEquals("Hello", error.message)
} }
@test fun requireNotNull() { @Test fun requireNotNull() {
val s1: String? = "S1" val s1: String? = "S1"
val r1: String = requireNotNull(s1) val r1: String = requireNotNull(s1)
assertEquals("S1", r1) assertEquals("S1", r1)
} }
@test fun requireNotNullFails() { @Test fun requireNotNullFails() {
assertFailsWith(IllegalArgumentException::class) { assertFailsWith(IllegalArgumentException::class) {
val s2: String? = null val s2: String? = null
requireNotNull(s2) requireNotNull(s2)
} }
} }
@test fun requireNotNullWithLazyMessage() { @Test fun requireNotNullWithLazyMessage() {
val error = assertFailsWith(IllegalArgumentException::class) { val error = assertFailsWith(IllegalArgumentException::class) {
val obj: Any? = null val obj: Any? = null
requireNotNull(obj) { "Message" } requireNotNull(obj) { "Message" }
@@ -78,20 +78,20 @@ class PreconditionsJVMTest() {
assertFalse(lazyCalled, "Message is not evaluated if the condition is met") assertFalse(lazyCalled, "Message is not evaluated if the condition is met")
} }
@test fun checkNotNull() { @Test fun checkNotNull() {
val s1: String? = "S1" val s1: String? = "S1"
val r1: String = checkNotNull(s1) val r1: String = checkNotNull(s1)
assertEquals("S1", r1) assertEquals("S1", r1)
} }
@test fun checkNotNullFails() { @Test fun checkNotNullFails() {
assertFailsWith(IllegalStateException::class) { assertFailsWith(IllegalStateException::class) {
val s2: String? = null val s2: String? = null
checkNotNull(s2) checkNotNull(s2)
} }
} }
@test fun passingAssert() { @Test fun passingAssert() {
assert(true) assert(true)
var called = false var called = false
assert(true) { called = true; "some message" } assert(true) { called = true; "some message" }
@@ -100,7 +100,7 @@ class PreconditionsJVMTest() {
} }
@test fun failingAssert() { @Test fun failingAssert() {
val error = assertFails { val error = assertFails {
assert(false) assert(false)
} }
@@ -111,7 +111,7 @@ class PreconditionsJVMTest() {
} }
} }
@test fun error() { @Test fun error() {
val error = assertFails { val error = assertFails {
error("There was a problem") error("There was a problem")
} }
@@ -122,11 +122,11 @@ class PreconditionsJVMTest() {
} }
} }
@test fun passingAssertWithMessage() { @Test fun passingAssertWithMessage() {
assert(true) { "Hello" } assert(true) { "Hello" }
} }
@test fun failingAssertWithMessage() { @Test fun failingAssertWithMessage() {
val error = assertFails { val error = assertFails {
assert(false) { "Hello" } assert(false) { "Hello" }
} }
@@ -137,7 +137,7 @@ class PreconditionsJVMTest() {
} }
} }
@test fun failingAssertWithLazyMessage() { @Test fun failingAssertWithLazyMessage() {
val error = assertFails { val error = assertFails {
assert(false) { "Hello" } assert(false) { "Hello" }
} }
+2 -2
View File
@@ -18,7 +18,7 @@ package test.utils
import kotlin.* import kotlin.*
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test
class TODOTest { class TODOTest {
private class PartiallyImplementedClass { private class PartiallyImplementedClass {
@@ -52,7 +52,7 @@ class TODOTest {
} }
@test fun usage() { @Test fun usage() {
val inst = PartiallyImplementedClass() val inst = PartiallyImplementedClass()
assertNotImplemented { inst.prop } assertNotImplemented { inst.prop }