New stdlib generators

This commit is contained in:
Ilya Ryzhenkov
2014-03-18 13:45:31 +04:00
committed by Andrey Breslav
parent 0980f5e40a
commit e37d8174c3
109 changed files with 13317 additions and 7735 deletions
@@ -1,35 +0,0 @@
package test.apicheck
import kotlin.util.*
import java.util.*
trait Traversable<T> {
/** Returns true if any elements in the collection match the given predicate */
fun any(predicate: (T)-> Boolean) : Boolean
/** Returns true if all elements in the collection match the given predicate */
fun all(predicate: (T)-> Boolean) : Boolean
/** Returns the first item in the collection which matches the given predicate or null if none matched */
fun find(predicate: (T)-> Boolean) : T?
/** Returns a new collection containing all elements in this collection which match the given predicate */
// TODO using: Collection<T> for the return type - I wonder if this exact type could be
// deduced somewhat from the This.Type; e.g. returning Set on a Set, Array on Array etc
fun filter(predicate: (T)-> Boolean) : Collection<T>
/** Performs the given operation on each element inside the collection */
fun forEach(operation: (element: T)-> Unit)
/** Returns a new collection containing the results of applying the given function to each element in this collection */
fun <T, R> Iterable<T>.map(transform : (T)-> R) : Collection<R>
}
/**
TODO try use delegation here to make sure we implement all the methods in the Traversable API
class ListImpl<T>(coll: ArrayList<out T>) : Traversable<T> by coll {
}
*/
-124
View File
@@ -1,124 +0,0 @@
package test.collections
import kotlin.test.*
import java.util.*
import org.junit.Test as test
class CollectionJVMTest {
test fun flatMap() {
val data = arrayList("", "foo", "bar", "x", "")
val characters = data.flatMap<String,Char>{ it.toCharList() }
println("Got list of characters ${characters}")
assertEquals(7, characters.size())
val text = characters.makeString("")
assertEquals("foobarx", text)
}
// TODO would be nice to avoid the <String>
test fun filterIntoLinkedList() {
val data = arrayList("foo", "bar")
val foo = data.filterTo(linkedList<String>()){it.startsWith("f")}
assertTrue {
foo.all{it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(linkedList("foo"), foo)
assertTrue {
foo is LinkedList<String>
}
}
// TODO would be nice to avoid the <String>
test fun filterNotIntoLinkedList() {
val data = arrayList("foo", "bar")
val foo = data.filterNotTo(linkedList<String>()){it.startsWith("f")}
assertTrue {
foo.all{!it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(linkedList("bar"), foo)
assertTrue {
foo is LinkedList<String>
}
}
// TODO would be nice to avoid the <String>
test fun filterNotNullIntoLinkedList() {
val data = arrayList(null, "foo", null, "bar")
val foo = data.filterNotNullTo(linkedList<String>())
assertEquals(2, foo.size)
assertEquals(linkedList("foo", "bar"), foo)
assertTrue {
foo is LinkedList<String>
}
}
// TODO would be nice to avoid the <String>
test fun filterIntoSortedSet() {
val data = arrayList("foo", "bar")
val sorted = data.filterTo(sortedSet<String>()){it.length == 3}
assertEquals(2, sorted.size)
assertEquals(sortedSet("bar", "foo"), sorted)
assertTrue {
sorted is TreeSet<String>
}
}
//todo after KT-1873 the name might be returned to 'last'
test fun lastElement() {
val data = arrayList("foo", "bar")
assertEquals("bar", data.last())
assertEquals(25, arrayList(15, 19, 20, 25).last())
assertEquals('a', linkedList('a').last())
}
test fun lastException() {
fails { linkedList<String>().last() }
}
test fun contains() {
assertTrue(linkedList(15, 19, 20).contains(15))
}
test fun sortBy() {
expect(arrayList("two" to 2, "three" to 3)) {
arrayList("three" to 3, "two" to 2).sortBy { it.second }
}
expect(arrayList("three" to 3, "two" to 2)) {
arrayList("three" to 3, "two" to 2).sortBy { it.first }
}
expect(arrayList("two" to 2, "three" to 3)) {
arrayList("three" to 3, "two" to 2).sortBy { it.first.length }
}
}
test fun sortFunctionShouldReturnSortedCopyForList() {
// TODO fixme Some sort of in/out variance thing - or an issue with Java interop?
todo {
// val list : List<Int> = arrayList<Int>(2, 3, 1)
// expect(arrayList(1, 2, 3)) { list.sort() }
// expect(arrayList(2, 3, 1)) { list }
}
}
test fun sortFunctionShouldReturnSortedCopyForIterable() {
// TODO fixme Some sort of in/out variance thing - or an issue with Java interop?
todo {
// val list : Iterable<Int> = arrayList(2, 3, 1)
// expect(arrayList(1, 2, 3)) { list.sort() }
// expect(arrayList(2, 3, 1)) { list }
}
}
}
-492
View File
@@ -1,492 +0,0 @@
package test.collections
import kotlin.test.*
import java.util.*
import org.junit.Test as test
class CollectionTest {
test fun all() {
val data = arrayList("foo", "bar")
assertTrue {
data.all{it.length == 3}
}
assertNot {
data.all{s -> s.startsWith("b")}
}
}
test fun any() {
val data = arrayList("foo", "bar")
assertTrue {
data.any{it.startsWith("f")}
}
assertNot {
data.any{it.startsWith("x")}
}
}
test fun appendString() {
val data = arrayList("foo", "bar")
val buffer = StringBuilder()
val text = data.appendString(buffer, "-", "{", "}")
assertEquals("{foo-bar}", buffer.toString())
}
test fun count() {
val data = arrayList("foo", "bar")
assertEquals(1, data.count{it.startsWith("b")})
assertEquals(2, data.count{it.size == 3})
}
test fun filter() {
val data = arrayList("foo", "bar")
val foo = data.filter{it.startsWith("f")}
assertTrue {
foo.all{it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(arrayList("foo"), foo)
}
test fun filterReturnsList() {
val data = arrayList("foo", "bar")
val foo = data.filter{it.startsWith("f")}
assertTrue {
foo is List<String>
}
}
test fun filterNot() {
val data = arrayList("foo", "bar")
val foo = data.filterNot{it.startsWith("b")}
assertTrue {
foo.all{it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(arrayList("foo"), foo)
}
test fun filterNotNull() {
val data = arrayList(null, "foo", null, "bar")
val foo = data.filterNotNull()
assertEquals(2, foo.size)
assertEquals(arrayList("foo", "bar"), foo)
assertTrue {
foo is List<String>
}
}
// TODO would be nice to avoid the <String>
test fun filterIntoSet() {
val data = arrayList("foo", "bar")
val foo = data.filterTo(hashSet<String>()){it.startsWith("f")}
assertTrue {
foo.all{it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(hashSet("foo"), foo)
assertTrue {
foo is HashSet<String>
}
}
test fun find() {
val data = arrayList("foo", "bar")
val x = data.find{it.startsWith("x")}
assertNull(x)
val f = data.find{it.startsWith("f")}
f!!
assertEquals("foo", f)
}
test fun forEach() {
val data = arrayList("foo", "bar")
var count = 0
data.forEach{ count += it.length }
assertEquals(6, count)
}
test fun fold() {
// lets calculate the sum of some numbers
expect(10) {
val numbers = arrayList(1, 2, 3, 4)
numbers.fold(0){ a, b -> a + b}
}
expect(0) {
val numbers = arrayList<Int>()
numbers.fold(0){ a, b -> a + b}
}
// lets concatenate some strings
expect("1234") {
val numbers = arrayList(1, 2, 3, 4)
numbers.map{it.toString()}.fold(""){ a, b -> a + b}
}
}
test fun foldWithDifferentTypes() {
expect(7) {
val numbers = arrayList("a", "ab", "abc")
numbers.fold(1){ a, b -> a + b.size}
}
expect("1234") {
val numbers = arrayList(1, 2, 3, 4)
numbers.fold(""){ a, b -> a + b}
}
}
test fun foldWithNonCommutativeOperation() {
expect(1) {
val numbers = arrayList(1, 2, 3)
numbers.fold(7) {a, b -> a - b}
}
}
test fun foldRight() {
expect("1234") {
val numbers = arrayList(1, 2, 3, 4)
numbers.map{it.toString()}.foldRight(""){ a, b -> a + b}
}
}
test fun foldRightWithDifferentTypes() {
expect("1234") {
val numbers = arrayList(1, 2, 3, 4)
numbers.foldRight(""){ a, b -> "" + a + b}
}
}
test fun foldRightWithNonCommutativeOperation() {
expect(-5) {
val numbers = arrayList(1, 2, 3)
numbers.foldRight(7) {a, b -> a - b}
}
}
test fun partition() {
val data = arrayList("foo", "bar", "something", "xyz")
val pair = data.partition{it.size == 3}
assertEquals(arrayList("foo", "bar", "xyz"), pair.first, "pair.first")
assertEquals(arrayList("something"), pair.second, "pair.second")
}
test fun reduce() {
expect("1234") {
val list = arrayList("1", "2", "3", "4")
list.reduce { a, b -> a + b }
}
failsWith(javaClass<UnsupportedOperationException>()) {
arrayList<Int>().reduce { a, b -> a + b}
}
}
test fun reduceRight() {
expect("1234") {
val list = arrayList("1", "2", "3", "4")
list.reduceRight { a, b -> a + b }
}
failsWith(javaClass<UnsupportedOperationException>()) {
arrayList<Int>().reduceRight { a, b -> a + b}
}
}
test fun groupBy() {
val words = arrayList("a", "ab", "abc", "def", "abcd")
val byLength = words.groupBy{ it.length }
assertEquals(4, byLength.size())
val l3 = byLength.getOrElse(3, {ArrayList<String>()})
assertEquals(2, l3.size)
}
test fun makeString() {
val data = arrayList("foo", "bar")
val text = data.makeString("-", "<", ">")
assertEquals("<foo-bar>", text)
val big = arrayList("a", "b", "c", "d" , "e", "f")
val text2 = big.makeString(limit = 3, truncated = "*")
assertEquals("a, b, c, *", text2)
}
test fun map() {
val data = arrayList("foo", "bar")
val lengths = data.map{ it.length }
assertTrue {
lengths.all{it == 3}
}
assertEquals(2, lengths.size)
assertEquals(arrayList(3, 3), lengths)
}
test fun plus() {
val list = arrayList("foo", "bar")
val list2 = list + "cheese"
assertEquals(arrayList("foo", "bar"), list)
assertEquals(arrayList("foo", "bar", "cheese"), list2)
// lets use a mutable variable
var list3 = arrayList("a", "b")
list3 += "c"
assertEquals(arrayList("a", "b", "c"), list3)
}
test fun plusCollectionBug() {
val list = arrayList("foo", "bar") + arrayList("cheese", "wine")
assertEquals(arrayList("foo", "bar", "cheese", "wine"), list)
}
test fun plusCollection() {
val a = arrayList("foo", "bar")
val b = arrayList("cheese", "wine")
val list = a + b
assertEquals(arrayList("foo", "bar", "cheese", "wine"), list)
// lets use a mutable variable
var ml = a
ml += "beer"
ml += b
ml += "z"
assertEquals(arrayList("foo", "bar", "beer", "cheese", "wine", "z"), ml)
}
test fun requireNoNulls() {
val data = arrayList<String?>("foo", "bar")
val notNull = data.requireNoNulls()
assertEquals(arrayList("foo", "bar"), notNull)
val hasNulls = arrayList("foo", null, "bar")
failsWith(javaClass<IllegalArgumentException>()) {
// should throw an exception as we have a null
hasNulls.requireNoNulls()
}
}
test fun reverse() {
val data = arrayList("foo", "bar")
val rev = data.reverse()
assertEquals(arrayList("bar", "foo"), rev)
}
test fun reverseFunctionShouldReturnReversedCopyForList() {
val list : List<Int> = arrayList(2, 3, 1)
expect(arrayList(1, 3, 2)) { list.reverse() }
expect(arrayList(2, 3, 1)) { list }
}
test fun reverseFunctionShouldReturnReversedCopyForIterable() {
val iterable : Iterable<Int> = arrayList(2, 3, 1)
expect(arrayList(1, 3, 2)) { iterable.reverse() }
expect(arrayList(2, 3, 1)) { iterable }
}
test fun drop() {
val coll = arrayList("foo", "bar", "abc")
assertEquals(arrayList("bar", "abc"), coll.drop(1))
assertEquals(arrayList("abc"), coll.drop(2))
}
test fun dropWhile() {
val coll = arrayList("foo", "bar", "abc")
assertEquals(arrayList("bar", "abc"), coll.dropWhile{ it.startsWith("f") })
}
test fun take() {
val coll = arrayList("foo", "bar", "abc")
assertEquals(arrayList("foo"), coll.take(1))
assertEquals(arrayList("foo", "bar"), coll.take(2))
}
test fun takeWhile() {
val coll = arrayList("foo", "bar", "abc")
assertEquals(arrayList("foo"), coll.takeWhile{ it.startsWith("f") })
assertEquals(arrayList("foo", "bar", "abc"), coll.takeWhile{ it.size == 3 })
}
test fun toArray() {
val data = arrayList("foo", "bar")
val arr = data.toArray()
println("Got array ${arr}")
assertEquals(2, arr.size)
todo {
assertTrue {
arr is Array<String>
}
}
}
test fun simpleCount() {
val data = arrayList("foo", "bar")
assertEquals(2, data.count())
assertEquals(3, hashSet(12, 14, 15).count())
assertEquals(0, ArrayList<Double>().count())
}
//todo after KT-1873 the name might be returned to 'last'
test fun lastElement() {
val data = arrayList("foo", "bar")
assertEquals("bar", data.last())
assertEquals(25, arrayList(15, 19, 20, 25).last())
assertEquals('a', arrayList('a').last())
}
// TODO
// assertEquals(19, TreeSet(arrayList(90, 47, 19)).first())
test fun lastException() {
fails { arrayList<Int>().last() }
}
test fun subscript() {
val list = arrayList("foo", "bar")
assertEquals("foo", list[0])
assertEquals("bar", list[1])
// lists throw an exception if out of range
fails {
assertEquals(null, list[2])
}
// lets try update the list
list[0] = "new"
list[1] = "thing"
// lists don't allow you to set past the end of the list
fails {
list[2] = "works"
}
list.add("works")
assertEquals(arrayList("new", "thing", "works"), list)
}
test fun indices() {
val data = arrayList("foo", "bar")
val indices = data.indices
assertEquals(0, indices.start)
assertEquals(1, indices.end)
assertEquals(indices, data.size. indices)
}
test fun contains() {
val data = arrayList("foo", "bar")
assertTrue(data.contains("foo"))
assertTrue(data.contains("bar"))
assertFalse(data.contains("some"))
// TODO: Problems with generation
// assertTrue(IterableWrapper(data).contains("bar"))
// assertFalse(IterableWrapper(data).contains("some"))
assertFalse(hashSet<Int>().contains(12))
assertTrue(arrayList(15, 19, 20).contains(15))
// assertTrue(IterableWrapper(hashSet(45, 14, 13)).contains(14))
// assertFalse(IterableWrapper(linkedList<Int>()).contains(15))
}
test fun sortForMutableIterable() {
val list : MutableIterable<Int> = arrayList<Int>(2, 3, 1)
expect(arrayList(1, 2, 3)) { list.sort() }
expect(arrayList(2, 3, 1)) { list }
}
test fun sortForIterable() {
val list : Iterable<Int> = listOf(2, 3, 1)
expect(arrayList(1, 2, 3)) { list.sort() }
expect(arrayList(2, 3, 1)) { list }
}
test fun min() {
expect(null, { listOf<Int>().min() })
expect(1, { listOf(1).min() })
expect(2, { listOf(2, 3).min() })
expect(2000000000000, { listOf(3000000000000, 2000000000000).min() })
expect('a', { listOf('a', 'b').min() })
expect("a", { listOf("a", "b").min() })
expect(null, { listOf<Int>().iterator().min() })
expect(2, { listOf(2, 3).iterator().min() })
}
test fun max() {
expect(null, { listOf<Int>().max() })
expect(1, { listOf(1).max() })
expect(3, { listOf(2, 3).max() })
expect(3000000000000, { listOf(3000000000000, 2000000000000).max() })
expect('b', { listOf('a', 'b').max() })
expect("b", { listOf("a", "b").max() })
expect(null, { listOf<Int>().iterator().max() })
expect(3, { listOf(2, 3).iterator().max() })
}
test fun minBy() {
expect(null, { listOf<Int>().minBy { it } })
expect(1, { listOf(1).minBy { it } })
expect(3, { listOf(2, 3).minBy { -it } })
expect('a', { listOf('a', 'b').minBy { "x$it" } })
expect("b", { listOf("b", "abc").minBy { it.length } })
expect(null, { listOf<Int>().iterator().minBy { it } })
expect(3, { listOf(2, 3).iterator().minBy { -it } })
}
test fun maxBy() {
expect(null, { listOf<Int>().maxBy { it } })
expect(1, { listOf(1).maxBy { it } })
expect(2, { listOf(2, 3).maxBy { -it } })
expect('b', { listOf('a', 'b').maxBy { "x$it" } })
expect("abc", { listOf("b", "abc").maxBy { it.length } })
expect(null, { listOf<Int>().iterator().maxBy { it } })
expect(2, { listOf(2, 3).iterator().maxBy { -it } })
}
test fun minByEvaluateOnce() {
var c = 0
expect(1, { listOf(5, 4, 3, 2, 1).minBy { c++; it * it } })
assertEquals(5, c)
c = 0
expect(1, { listOf(5, 4, 3, 2, 1).iterator().minBy { c++; it * it } })
assertEquals(5, c)
}
test fun maxByEvaluateOnce() {
var c = 0
expect(5, { listOf(5, 4, 3, 2, 1).maxBy { c++; it * it } })
assertEquals(5, c)
c = 0
expect(5, { listOf(5, 4, 3, 2, 1).iterator().maxBy { c++; it * it } })
assertEquals(5, c)
}
test fun sum() {
expect(0) { ArrayList<Int>().sum() }
expect(14) { arrayListOf(2, 3, 9).sum() }
expect(3.0) { arrayListOf(1.0, 2.0).sum() }
expect(3000000000000) { arrayListOf<Long>(1000000000000, 2000000000000).sum() }
expect(3.0.toFloat()) { arrayListOf<Float>(1.0.toFloat(), 2.0.toFloat()).sum() }
}
class IterableWrapper<T>(collection : Iterable<T>) : Iterable<T> {
private val collection = collection
override fun iterator(): Iterator<T> {
return collection.iterator()
}
}
}
+4 -4
View File
@@ -42,8 +42,8 @@ class CompareTest {
val diff = c.compare(v1, v2)
assertTrue(diff < 0)
val items = arrayList(v1, v2)
items.sort(c)
val items = arrayListOf(v1, v2)
items.sortBy(c)
println("Sorted list in rating order $items")
}
@@ -60,8 +60,8 @@ class CompareTest {
val diff = c.compare(v1, v2)
assertTrue(diff > 0)
val items = arrayList(v1, v2)
items.sort(c)
val items = arrayListOf(v1, v2)
items.sortBy(c)
println("Sorted list in rating order $items")
}
@@ -1,18 +0,0 @@
import java.util.Vector
import junit.framework.TestCase
import kotlin.test.assertEquals
class EnumerationIteratorTest() : TestCase() {
fun testIteration () {
val v = Vector<Int>()
for(i in 1..5)
v.add(i)
var sum = 0
for(k in v.elements())
sum += k
assertEquals(15, sum)
}
}
-79
View File
@@ -1,79 +0,0 @@
package test.collections
import java.util.ArrayList
import kotlin.test.*
import org.junit.Test as test
class ListTest {
test fun _toString() {
val data = arrayList("foo", "bar")
assertEquals("[foo, bar]", data.toString())
}
test fun emptyHead() {
val data = ArrayList<String>()
assertNull(data.head)
}
test fun head() {
val data = arrayList("foo", "bar")
assertEquals("foo", data.head)
}
test fun tail() {
val data = arrayList("foo", "bar", "whatnot")
val actual = data.tail
val expected = arrayList("bar", "whatnot")
assertEquals(expected, actual)
}
test fun emptyFirst() {
val data = ArrayList<String>()
assertNull(data.first)
}
test fun first() {
val data = arrayList("foo", "bar")
assertEquals("foo", data.first)
}
test fun last() {
val data = arrayList("foo", "bar")
assertEquals("bar", data.last)
}
test fun forEachWithIndex() {
val data = arrayList("foo", "bar")
var index = 0
data.forEachWithIndex { (i, d) ->
assertEquals(i, index)
assertEquals(d, data[index])
index++
}
assertEquals(data.size(), index)
}
test fun withIndices() {
val data = arrayList("foo", "bar")
var index = 0
for ((i, d) in data.withIndices()) {
assertEquals(i, index)
assertEquals(d, data[index])
index++
}
assertEquals(data.size(), index)
}
test fun lastIndex() {
val emptyData = ArrayList<String>()
val data = arrayList("foo", "bar")
assertEquals(-1, emptyData.lastIndex)
assertEquals(1, data.lastIndex)
}
}
-65
View File
@@ -1,65 +0,0 @@
package test.collections
import kotlin.test.*
import java.util.*
import org.junit.Test
class SetTest {
val data = hashSet("foo", "bar")
Test fun any() {
assertTrue {
data.any{it.startsWith("f")}
}
assertNot {
data.any{it.startsWith("x")}
}
}
Test fun all() {
assertTrue {
data.all{it.length == 3}
}
assertNot {
data.all{(s: String) -> s.startsWith("b")}
}
}
Test fun filter() {
val foo = data.filter{it.startsWith("f")}.toSet()
assertTrue {
foo.all{it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(hashSet("foo"), foo)
assertTrue("Filter on a Set should return a Set") {
foo is Set<String>
}
}
Test fun find() {
val x = data.find{it.startsWith("x")}
assertNull(x)
val f = data.find{it.startsWith("f")}
assertEquals("foo", f)
}
Test fun map() {
/**
TODO compiler bug
we should be able to remove the explicit type on the function
http://youtrack.jetbrains.net/issue/KT-849
*/
val lengths = data.map{s -> s.length}
assertTrue {
lengths.all{it == 3}
}
assertEquals(2, lengths.size)
assertEquals(arrayList(3, 3), lengths)
}
}
@@ -1,22 +0,0 @@
package test.collections
import kotlin.*
import kotlin.test.*
import junit.framework.TestCase
class StandardCollectionTest() : TestCase() {
fun testDisabled() {
}
fun testAny() {
val data: Iterable<String> = listOf("foo", "bar")
assertTrue {
data.any{it.startsWith("f")}
}
assertNot {
data.any{it.startsWith("x")}
}
}
}
@@ -1,4 +1,4 @@
package test.arrays
package test.collections
import kotlin.test.*
import org.junit.Test as test
@@ -1,4 +1,4 @@
package test.arrays
package test.collections
import kotlin.test.*
import org.junit.Test as test
@@ -153,8 +153,7 @@ class ArraysTest {
expect(3.0) { array(1.0, 2.0).sum() }
expect(200) { array<Byte>(100, 100).sum() }
expect(50000) { array<Short>(20000, 30000).sum() }
//TODO: uncomment when toLong() will be supported
//expect(3000000000000) { array<Long>(1000000000000, 2000000000000).sum() }
expect(3000000000000) { array<Long>(1000000000000, 2000000000000).sum() }
expect(3.0.toFloat()) { array<Float>(1.0.toFloat(), 2.0.toFloat()).sum() }
}
@@ -165,6 +164,28 @@ class ArraysTest {
expect(2) { array("cat", "dog", "bird").indexOf("bird") }
expect(0) { array(null, "dog", null).indexOf(null)}
}
test fun plus() {
assertEquals(listOf("1","2","3","4"), array("1", "2") + array("3", "4"))
assertEquals(listOf("1","2","3","4"), listOf("1", "2") + array("3", "4"))
}
test fun first() {
expect(1) { array(1,2,3).first() }
expect(2) { array(1,2,3).first { it % 2 == 0 } }
}
test fun last() {
expect(3) { array(1,2,3).last() }
expect(2) { array(1,2,3).last { it % 2 == 0 } }
}
test fun contains() {
assertTrue(array("1","2","3","4").contains("2"))
assertTrue("3" in array("1","2","3","4"))
assertTrue("0" !in array("1","2","3","4"))
}
/*
TODO FIXME ASAP: These currently fail on JS due to missing upto() method on numbers
@@ -0,0 +1,115 @@
package test.collections
import kotlin.test.*
import java.util.*
import org.junit.Test as test
class CollectionJVMTest {
test fun flatMap() {
val data = arrayListOf("", "foo", "bar", "x", "")
val characters = data.flatMap { it.toCharList() }
println("Got list of characters ${characters}")
assertEquals(7, characters.size())
val text = characters.makeString("")
assertEquals("foobarx", text)
}
test fun filterIntolinkedListOf() {
val data = arrayListOf("foo", "bar")
val foo = data.filterTo(linkedListOf<String>()) { it.startsWith("f") }
assertTrue {
foo.all { it.startsWith("f") }
}
assertEquals(1, foo.size)
assertEquals(linkedListOf("foo"), foo)
assertTrue {
foo is LinkedList<String>
}
}
test fun filterNotIntolinkedListOf() {
val data = arrayListOf("foo", "bar")
val foo = data.filterNotTo(linkedListOf<String>()) { it.startsWith("f") }
assertTrue {
foo.all { !it.startsWith("f") }
}
assertEquals(1, foo.size)
assertEquals(linkedListOf("bar"), foo)
assertTrue {
foo is LinkedList<String>
}
}
// TODO would be nice to avoid the <String>
test fun filterNotNullIntolinkedListOf() {
val data = arrayListOf(null, "foo", null, "bar")
val foo = data.filterNotNullTo(linkedListOf<String>())
assertEquals(2, foo.size)
assertEquals(linkedListOf("foo", "bar"), foo)
assertTrue {
foo is LinkedList<String>
}
}
// TODO would be nice to avoid the <String>
test fun filterIntoSortedSet() {
val data = arrayListOf("foo", "bar")
val sorted = data.filterTo(sortedSetOf<String>()) { it.length == 3 }
assertEquals(2, sorted.size)
assertEquals(sortedSetOf("bar", "foo"), sorted)
assertTrue {
sorted is TreeSet<String>
}
}
test fun last() {
val data = arrayListOf("foo", "bar")
assertEquals("bar", data.last())
assertEquals(25, arrayListOf(15, 19, 20, 25).last())
assertEquals('a', linkedListOf('a').last())
}
test fun lastException() {
fails { linkedListOf<String>().last() }
}
test fun contains() {
assertTrue(linkedListOf(15, 19, 20).contains(15))
}
test fun sortBy() {
expect(arrayListOf("two" to 2, "three" to 3)) {
arrayListOf("three" to 3, "two" to 2).sortBy { it.second }
}
expect(arrayListOf("three" to 3, "two" to 2)) {
arrayListOf("three" to 3, "two" to 2).sortBy { it.first }
}
expect(arrayListOf("two" to 2, "three" to 3)) {
arrayListOf("three" to 3, "two" to 2).sortBy { it.first.length }
}
}
test fun sortFunctionShouldReturnSortedCopyForList() {
val list: List<Int> = arrayListOf(2, 3, 1)
expect(arrayListOf(1, 2, 3)) { list.sort() }
expect(arrayListOf(2, 3, 1)) { list }
}
test fun sortFunctionShouldReturnSortedCopyForIterable() {
val list: Iterable<Int> = arrayListOf(2, 3, 1)
expect(arrayListOf(1, 2, 3)) { list.sort() }
expect(arrayListOf(2, 3, 1)) { list }
}
}
@@ -0,0 +1,432 @@
package test.collections
import kotlin.test.*
import java.util.*
import org.junit.Test as test
class CollectionTest {
test fun appendString() {
val data = arrayListOf("foo", "bar")
val buffer = StringBuilder()
val text = data.appendString(buffer, "-", "{", "}")
assertEquals("{foo-bar}", buffer.toString())
}
test fun makeString() {
val data = arrayListOf("foo", "bar")
val text = data.makeString("-", "<", ">")
assertEquals("<foo-bar>", text)
val big = arrayListOf("a", "b", "c", "d", "e", "f")
val text2 = big.makeString(limit = 3, truncated = "*")
assertEquals("a, b, c, *", text2)
}
test fun filterNotNull() {
val data = arrayListOf(null, "foo", null, "bar")
val foo = data.filterNotNull()
assertEquals(2, foo.size)
assertEquals(arrayListOf("foo", "bar"), foo)
assertTrue {
foo is List<String>
}
}
test fun mapNotNull() {
val data = arrayListOf(null, "foo", null, "bar")
val foo = data.mapNotNull { it.length }
assertEquals(2, foo.size)
assertEquals(arrayListOf(3, 3), foo)
assertTrue {
foo is List<Int>
}
}
// TODO would be nice to avoid the <String>
test fun filterIntoSet() {
val data = arrayListOf("foo", "bar")
val foo = data.filterTo(hashSetOf<String>()) { it.startsWith("f") }
assertTrue {
foo.all { it.startsWith("f") }
}
assertEquals(1, foo.size)
assertEquals(hashSetOf("foo"), foo)
assertTrue {
foo is HashSet<String>
}
}
test fun fold() {
// lets calculate the sum of some numbers
expect(10) {
val numbers = arrayListOf(1, 2, 3, 4)
numbers.fold(0) { a, b -> a + b }
}
expect(0) {
val numbers = arrayListOf<Int>()
numbers.fold(0) { a, b -> a + b }
}
// lets concatenate some strings
expect("1234") {
val numbers = arrayListOf(1, 2, 3, 4)
numbers.map { it.toString() }.fold("") { a, b -> a + b }
}
}
test fun foldWithDifferentTypes() {
expect(7) {
val numbers = arrayListOf("a", "ab", "abc")
numbers.fold(1) { a, b -> a + b.size }
}
expect("1234") {
val numbers = arrayListOf(1, 2, 3, 4)
numbers.fold("") { a, b -> a + b }
}
}
test fun foldWithNonCommutativeOperation() {
expect(1) {
val numbers = arrayListOf(1, 2, 3)
numbers.fold(7) { a, b -> a - b }
}
}
test fun foldRight() {
expect("1234") {
val numbers = arrayListOf(1, 2, 3, 4)
numbers.map { it.toString() }.foldRight("") { a, b -> a + b }
}
}
test fun foldRightWithDifferentTypes() {
expect("1234") {
val numbers = arrayListOf(1, 2, 3, 4)
numbers.foldRight("") { a, b -> "" + a + b }
}
}
test fun foldRightWithNonCommutativeOperation() {
expect(-5) {
val numbers = arrayListOf(1, 2, 3)
numbers.foldRight(7) { a, b -> a - b }
}
}
test fun partition() {
val data = arrayListOf("foo", "bar", "something", "xyz")
val pair = data.partition { it.size == 3 }
assertEquals(arrayListOf("foo", "bar", "xyz"), pair.first, "pair.first")
assertEquals(arrayListOf("something"), pair.second, "pair.second")
}
test fun reduce() {
expect("1234") {
val list = arrayListOf("1", "2", "3", "4")
list.reduce { a, b -> a + b }
}
failsWith(javaClass<UnsupportedOperationException>()) {
arrayListOf<Int>().reduce { a, b -> a + b }
}
}
test fun reduceRight() {
expect("1234") {
val list = arrayListOf("1", "2", "3", "4")
list.reduceRight { a, b -> a + b }
}
failsWith(javaClass<UnsupportedOperationException>()) {
arrayListOf<Int>().reduceRight { a, b -> a + b }
}
}
test fun groupBy() {
val words = arrayListOf("a", "ab", "abc", "def", "abcd")
val byLength = words.groupBy { it.length }
assertEquals(4, byLength.size())
val l3 = byLength.getOrElse(3, { ArrayList<String>() })
assertEquals(2, l3.size)
}
test fun plusRanges() {
val range1 = 1..3
val range2 = 4..7
val combined = range1 + range2
assertEquals((1..7).toList(), combined)
}
test fun mapRanges() {
val range = 1..3 map { it * 2}
assertEquals(listOf(2,4,6), range)
}
test fun plus() {
val list = arrayListOf("foo", "bar")
val list2 = list + "cheese"
assertEquals(arrayListOf("foo", "bar"), list)
assertEquals(arrayListOf("foo", "bar", "cheese"), list2)
// lets use a mutable variable
var list3 = arrayListOf("a", "b")
list3 += "c"
assertEquals(arrayListOf("a", "b", "c"), list3)
}
test fun plusCollectionBug() {
val list = arrayListOf("foo", "bar") + arrayListOf("cheese", "wine")
assertEquals(arrayListOf("foo", "bar", "cheese", "wine"), list)
}
test fun plusCollection() {
val a = arrayListOf("foo", "bar")
val b = arrayListOf("cheese", "wine")
val list = a + b
assertEquals(arrayListOf("foo", "bar", "cheese", "wine"), list)
// lets use a mutable variable
var ml = a
ml += "beer"
ml += b
ml += "z"
assertEquals(arrayListOf("foo", "bar", "beer", "cheese", "wine", "z"), ml)
}
test fun requireNoNulls() {
val data = arrayListOf<String?>("foo", "bar")
val notNull = data.requireNoNulls()
assertEquals(arrayListOf("foo", "bar"), notNull)
val hasNulls = arrayListOf("foo", null, "bar")
failsWith(javaClass<IllegalArgumentException>()) {
// should throw an exception as we have a null
hasNulls.requireNoNulls()
}
}
test fun reverse() {
val data = arrayListOf("foo", "bar")
val rev = data.reverse()
assertEquals(arrayListOf("bar", "foo"), rev)
}
test fun reverseFunctionShouldReturnReversedCopyForList() {
val list: List<Int> = arrayListOf(2, 3, 1)
expect(arrayListOf(1, 3, 2)) { list.reverse() }
expect(arrayListOf(2, 3, 1)) { list }
}
test fun reverseFunctionShouldReturnReversedCopyForIterable() {
val iterable: Iterable<Int> = arrayListOf(2, 3, 1)
expect(arrayListOf(1, 3, 2)) { iterable.reverse() }
expect(arrayListOf(2, 3, 1)) { iterable }
}
test fun drop() {
val coll = arrayListOf("foo", "bar", "abc")
assertEquals(arrayListOf("bar", "abc"), coll.drop(1))
assertEquals(arrayListOf("abc"), coll.drop(2))
}
test fun dropWhile() {
val coll = arrayListOf("foo", "bar", "abc")
assertEquals(arrayListOf("bar", "abc"), coll.dropWhile { it.startsWith("f") })
}
test fun take() {
val coll = arrayListOf("foo", "bar", "abc")
assertEquals(arrayListOf("foo"), coll.take(1))
assertEquals(arrayListOf("foo", "bar"), coll.take(2))
}
test fun takeWhile() {
val coll = arrayListOf("foo", "bar", "abc")
assertEquals(arrayListOf("foo"), coll.takeWhile { it.startsWith("f") })
assertEquals(arrayListOf("foo", "bar", "abc"), coll.takeWhile { it.size == 3 })
}
test fun toArray() {
val data = arrayListOf("foo", "bar")
val arr = data.toArray()
println("Got array ${arr}")
assertEquals(2, arr.size)
todo {
assertTrue {
arr is Array<String>
}
}
}
test fun simpleCount() {
val data = arrayListOf("foo", "bar")
assertEquals(2, data.count())
assertEquals(3, hashSetOf(12, 14, 15).count())
assertEquals(0, ArrayList<Double>().count())
}
//todo after KT-1873 the name might be returned to 'last'
test fun lastElement() {
val data = arrayListOf("foo", "bar")
assertEquals("bar", data.last())
assertEquals(25, arrayListOf(15, 19, 20, 25).last())
assertEquals('a', arrayListOf('a').last())
}
// TODO
// assertEquals(19, TreeSet(arrayListOf(90, 47, 19)).first())
test fun lastException() {
fails { arrayListOf<Int>().last() }
}
test fun subscript() {
val list = arrayListOf("foo", "bar")
assertEquals("foo", list[0])
assertEquals("bar", list[1])
// lists throw an exception if out of range
fails {
assertEquals(null, list[2])
}
// lets try update the list
list[0] = "new"
list[1] = "thing"
// lists don't allow you to set past the end of the list
fails {
list[2] = "works"
}
list.add("works")
assertEquals(arrayListOf("new", "thing", "works"), list)
}
test fun indices() {
val data = arrayListOf("foo", "bar")
val indices = data.indices
assertEquals(0, indices.start)
assertEquals(1, indices.end)
assertEquals(indices, data.size. indices)
}
test fun contains() {
val data = arrayListOf("foo", "bar")
assertTrue(data.contains("foo"))
assertTrue(data.contains("bar"))
assertFalse(data.contains("some"))
// TODO: Problems with generation
// assertTrue(IterableWrapper(data).contains("bar"))
// assertFalse(IterableWrapper(data).contains("some"))
assertFalse(hashSetOf<Int>().contains(12))
assertTrue(arrayListOf(15, 19, 20).contains(15))
// assertTrue(IterableWrapper(hashSet(45, 14, 13)).contains(14))
// assertFalse(IterableWrapper(linkedList<Int>()).contains(15))
}
test fun sortForMutableIterable() {
val list: MutableIterable<Int> = arrayListOf(2, 3, 1)
expect(arrayListOf(1, 2, 3)) { list.sort() }
expect(arrayListOf(2, 3, 1)) { list }
}
test fun sortForIterable() {
val list: Iterable<Int> = listOf(2, 3, 1)
expect(arrayListOf(1, 2, 3)) { list.sort() }
expect(arrayListOf(2, 3, 1)) { list }
}
test fun min() {
expect(null, { listOf<Int>().min() })
expect(1, { listOf(1).min() })
expect(2, { listOf(2, 3).min() })
expect(2000000000000, { listOf(3000000000000, 2000000000000).min() })
expect('a', { listOf('a', 'b').min() })
expect("a", { listOf("a", "b").min() })
expect(null, { listOf<Int>().stream().min() })
expect(2, { listOf(2, 3).stream().min() })
}
test fun max() {
expect(null, { listOf<Int>().max() })
expect(1, { listOf(1).max() })
expect(3, { listOf(2, 3).max() })
expect(3000000000000, { listOf(3000000000000, 2000000000000).max() })
expect('b', { listOf('a', 'b').max() })
expect("b", { listOf("a", "b").max() })
expect(null, { listOf<Int>().stream().max() })
expect(3, { listOf(2, 3).stream().max() })
}
test fun minBy() {
expect(null, { listOf<Int>().minBy { it } })
expect(1, { listOf(1).minBy { it } })
expect(3, { listOf(2, 3).minBy { -it } })
expect('a', { listOf('a', 'b').minBy { "x$it" } })
expect("b", { listOf("b", "abc").minBy { it.length } })
expect(null, { listOf<Int>().stream().minBy { it } })
expect(3, { listOf(2, 3).stream().minBy { -it } })
}
test fun maxBy() {
expect(null, { listOf<Int>().maxBy { it } })
expect(1, { listOf(1).maxBy { it } })
expect(2, { listOf(2, 3).maxBy { -it } })
expect('b', { listOf('a', 'b').maxBy { "x$it" } })
expect("abc", { listOf("b", "abc").maxBy { it.length } })
expect(null, { listOf<Int>().stream().maxBy { it } })
expect(2, { listOf(2, 3).stream().maxBy { -it } })
}
test fun minByEvaluateOnce() {
var c = 0
expect(1, { listOf(5, 4, 3, 2, 1).minBy { c++; it * it } })
assertEquals(5, c)
c = 0
expect(1, { listOf(5, 4, 3, 2, 1).stream().minBy { c++; it * it } })
assertEquals(5, c)
}
test fun maxByEvaluateOnce() {
var c = 0
expect(5, { listOf(5, 4, 3, 2, 1).maxBy { c++; it * it } })
assertEquals(5, c)
c = 0
expect(5, { listOf(5, 4, 3, 2, 1).stream().maxBy { c++; it * it } })
assertEquals(5, c)
}
test fun sum() {
expect(0) { arrayListOf<Int>().sum() }
expect(14) { arrayListOf(2, 3, 9).sum() }
expect(3.0) { arrayListOf(1.0, 2.0).sum() }
expect(3000000000000) { arrayListOf<Long>(1000000000000, 2000000000000).sum() }
expect(3.0.toFloat()) { arrayListOf<Float>(1.0.toFloat(), 2.0.toFloat()).sum() }
}
class IterableWrapper<T>(collection: Iterable<T>) : Iterable<T> {
private val collection = collection
override fun iterator(): Iterator<T> {
return collection.iterator()
}
}
}
@@ -1,4 +1,4 @@
package test.collection
package test.collections
import kotlin.test.*
@@ -0,0 +1,9 @@
package test.collections
import org.junit.Test
import kotlin.test.*
import java.util.*
class LinkedSetTest : OrderedIterableTests<Set<String>>(setOf("foo", "bar"), setOf<String>())
class LinkedListTest : OrderedIterableTests<LinkedList<String>>(linkedListOf("foo", "bar"), linkedListOf<String>())
@@ -0,0 +1,203 @@
package test.collections
import org.junit.Test
import kotlin.test.*
import java.util.*
class SetTest : IterableTests<Set<String>>(hashSetOf("foo", "bar"), hashSetOf<String>())
class ListTest : OrderedIterableTests<List<String>>(listOf("foo", "bar"), listOf<String>())
class ArrayListTest : OrderedIterableTests<ArrayList<String>>(arrayListOf("foo", "bar"), arrayListOf<String>())
abstract class OrderedIterableTests<T : Iterable<String>>(data: T, empty: T) : IterableTests<T>(data, empty) {
Test fun indexOf() {
expect(0) { data.indexOf("foo") }
expect(-1) { empty.indexOf("foo") }
expect(1) { data.indexOf("bar") }
expect(-1) { data.indexOf("zap") }
}
Test fun lastIndexOf() {
expect(0) { data.lastIndexOf("foo") }
expect(-1) { empty.lastIndexOf("foo") }
expect(1) { data.lastIndexOf("bar") }
expect(-1) { data.lastIndexOf("zap") }
}
Test fun elementAt() {
expect("foo") { data.elementAt(0) }
expect("bar") { data.elementAt(1) }
fails { data.elementAt(2) }
fails { data.elementAt(-1) }
fails { empty.elementAt(0) }
}
Test fun first() {
expect("foo") { data.first() }
fails {
data.first { it.startsWith("x") }
}
fails {
empty.first()
}
expect("foo") { data.first { it.startsWith("f") } }
}
Test fun firstOrNull() {
expect(null) { data.firstOrNull { it.startsWith("x") } }
expect(null) { empty.firstOrNull() }
val f = data.firstOrNull { it.startsWith("f") }
assertEquals("foo", f)
}
Test fun last() {
assertEquals("bar", data.last())
fails {
data.last { it.startsWith("x") }
}
fails {
empty.last()
}
expect("foo") { data.last { it.startsWith("f") } }
}
Test fun lastOrNull() {
expect(null) { data.lastOrNull { it.startsWith("x") } }
expect(null) { empty.lastOrNull() }
expect("foo") { data.lastOrNull { it.startsWith("f") } }
}
}
abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
Test fun any() {
expect(true) { data.any() }
expect(false) { empty.any() }
expect(true) { data.any { it.startsWith("f") } }
expect(false) { data.any { it.startsWith("x") } }
expect(false) { empty.any { it.startsWith("x") } }
}
Test fun all() {
expect(true) { data.all { it.length == 3 } }
expect(false) { data.all { it.startsWith("b") } }
expect(true) { empty.all { it.startsWith("b") } }
}
Test fun none() {
expect(false) { data.none() }
expect(true) { empty.none() }
expect(false) { data.none { it.length == 3 } }
expect(false) { data.none { it.startsWith("b") } }
expect(true) { data.none { it.startsWith("x") } }
expect(true) { empty.none { it.startsWith("b") } }
}
Test fun filter() {
val foo = data.filter { it.startsWith("f") }
// TODO uncomment this when KT-4651 will be fixed
//expect(true) { foo is List<String> }
expect(true) { foo.all { it.startsWith("f") } }
expect(1) { foo.size }
assertEquals(listOf("foo"), foo)
}
Test fun filterNot() {
val notFoo = data.filterNot { it.startsWith("f") }
// TODO uncomment this when KT-4651 will be fixed
//expect(true) { notFoo is List<String> }
expect(true) { notFoo.none { it.startsWith("f") } }
expect(1) { notFoo.size }
assertEquals(listOf("bar"), notFoo)
}
Test fun forEach() {
var count = 0
data.forEach { count += it.length }
assertEquals(6, count)
}
Test fun contains() {
assertTrue(data.contains("foo"))
assertTrue("bar" in data)
assertTrue("baz" !in data)
assertFalse("baz" in empty)
}
Test fun single() {
fails { data.single() }
fails { empty.single() }
expect("foo") { data.single { it.startsWith("f") } }
expect("bar") { data.single { it.startsWith("b") } }
fails {
data.single { it.length == 3 }
}
}
Test
fun singleOrNull() {
fails { data.singleOrNull() }
fails { empty.singleOrNull() }
expect("foo") { data.singleOrNull { it.startsWith("f") } }
expect("bar") { data.singleOrNull { it.startsWith("b") } }
fails {
data.singleOrNull { it.length == 3 }
}
}
Test
fun map() {
val lengths = data.map { it.length }
assertTrue {
lengths.all { it == 3 }
}
assertEquals(2, lengths.size)
assertEquals(arrayListOf(3, 3), lengths)
}
Test
fun max() {
expect("foo") { data.max() }
expect("bar") { data.maxBy { it.last() } }
}
Test
fun min() {
expect("bar") { data.min() }
expect("foo") { data.minBy { it.last() } }
}
Test
fun count() {
expect(2) { data.count() }
expect(0) { empty.count() }
expect(1) { data.count { it.startsWith("f") } }
expect(0) { empty.count { it.startsWith("f") } }
expect(0) { data.count { it.startsWith("x") } }
expect(0) { empty.count { it.startsWith("x") } }
}
Test
fun withIndices() {
var index = 0
for ((i, d) in data.withIndices()) {
assertEquals(i, index)
assertEquals(d, data.elementAt(index))
index++
}
assertEquals(data.count(), index)
}
Test
fun fold() {
}
Test
fun reduce() {
}
}
@@ -0,0 +1,44 @@
package test.collections
import org.junit.Test as test
import kotlin.test.*
import java.util.*
class IteratorsJVMTest {
test fun testEnumeration() {
val v = Vector<Int>()
for(i in 1..5)
v.add(i)
var sum = 0
for(k in v.elements())
sum += k
assertEquals(15, sum)
}
test fun flatMapAndTakeExtractTheTransformedElements() {
fun intToBinaryDigits() = { (i: Int) ->
val binary = Integer.toBinaryString(i)!!
var index = 0
stream<Char> { if (index < binary.length()) binary.get(index++) else null }
}
val expected = arrayListOf(
'0', // fibonacci(0) = 0
'1', // fibonacci(1) = 1
'1', // fibonacci(2) = 1
'1', '0', // fibonacci(3) = 2
'1', '1', // fibonacci(4) = 3
'1', '0', '1' // fibonacci(5) = 5
)
assertEquals(expected, fibonacci().flatMap<Int, Char>(intToBinaryDigits()).take(10).toList())
}
test fun flatMapOnStream() {
val result = listOf(1, 2).stream().flatMap<Int, Int> { (0..it).stream() }
assertEquals(listOf(0, 1, 0, 1, 2), result.toList())
}
}
@@ -0,0 +1,15 @@
package test.collections
import kotlin.test.*
import org.junit.Test as test
class IteratorsTest {
test fun iterationOverIterator() {
val c = arrayListOf(0, 1, 2, 3, 4, 5)
var s = ""
for (i in c.iterator()) {
s = s + i.toString()
}
assertEquals("012345", s)
}
}
@@ -0,0 +1,33 @@
package test.collections
import java.util.ArrayList
import kotlin.test.*
import org.junit.Test
class ListSpecificTest {
val data = listOf("foo", "bar")
val empty = listOf<String>()
Test fun _toString() {
assertEquals("[foo, bar]", data.toString())
}
Test fun tail() {
val data = arrayListOf("foo", "bar", "whatnot")
val actual = data.tail
val expected = arrayListOf("bar", "whatnot")
assertEquals(expected, actual)
}
Test fun utils() {
assertNull(empty.head)
assertNull(empty.first)
assertNull(empty.last)
assertEquals(-1, empty.lastIndex)
assertEquals("foo", data.head)
assertEquals("foo", data.first)
assertEquals("bar", data.last)
assertEquals(1, data.lastIndex)
}
}
@@ -17,11 +17,11 @@ class MutableCollectionTest {
assertEquals(data, collection)
}
test fun fromIterator() {
test fun fromStream() {
val list = arrayListOf("foo", "bar")
val collection = ArrayList<String>()
collection.addAll(list.iterator())
collection.addAll(list.stream())
assertEquals(list, collection)
}
@@ -0,0 +1,148 @@
package test.collections
import org.junit.Test
import kotlin.test.*
import java.util.*
fun fibonacci(): Stream<Int> {
// fibonacci terms
var index = 0;
var a = 0;
var b = 1
return stream<Int> {
when (index++) { 0 -> a; 1 -> b; else -> {
val result = a + b; a = b; b = result; result
} }
}
}
public class StreamTest {
Test fun requireNoNulls() {
val stream = arrayListOf<String?>("foo", "bar").stream()
val notNull = stream.requireNoNulls()
assertEquals(arrayListOf("foo", "bar"), notNull.toList())
val streamWithNulls = arrayListOf("foo", null, "bar").stream()
val notNull2 = streamWithNulls.requireNoNulls() // shouldn't fail yet
fails {
// should throw an exception as we have a null
notNull2.toList()
}
}
test fun mapNotNull() {
val data = arrayListOf(null, "foo", null, "bar").stream()
val foo = data.mapNotNull { it.length }
assertEquals(arrayListOf(3, 3), foo.toList())
assertTrue {
foo is Stream<Int>
}
}
Test fun filterAndTakeWhileExtractTheElementsWithinRange() {
assertEquals(arrayListOf(144, 233, 377, 610, 987), fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.toList())
}
Test fun foldReducesTheFirstNElements() {
val sum = {(a: Int, b: Int) -> a + b }
assertEquals(arrayListOf(13, 21, 34, 55, 89).fold(0, sum), fibonacci().filter { it > 10 }.take(5).fold(0, sum))
}
Test fun takeExtractsTheFirstNElements() {
assertEquals(arrayListOf(0, 1, 1, 2, 3, 5, 8, 13, 21, 34), fibonacci().take(10).toList())
}
Test fun mapAndTakeWhileExtractTheTransformedElements() {
assertEquals(arrayListOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile {(i: Int) -> i < 20 }.toList())
}
Test fun joinConcatenatesTheFirstNElementsAboveAThreshold() {
assertEquals("13, 21, 34, 55, 89, ...", fibonacci().filter { it > 10 }.makeString(separator = ", ", limit = 5))
}
Test fun skippingIterator() {
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(7).makeString(limit = 10))
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(3).drop(4).makeString(limit = 10))
}
Test fun toStringJoinsNoMoreThanTheFirstTenElements() {
assertEquals("0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...", fibonacci().makeString(limit = 10))
assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().filter { it > 10 }.makeString(limit = 10))
assertEquals("144, 233, 377, 610, 987", fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.makeString())
}
Test fun plus() {
val stream = listOf("foo", "bar").stream()
val streamChease = stream + "cheese"
assertEquals(listOf("foo", "bar", "cheese"), streamChease.toList())
// lets use a mutable variable
var mi = listOf("a", "b").stream()
mi += "c"
assertEquals(listOf("a", "b", "c"), mi.toList())
}
Test fun plusCollection() {
val a = listOf("foo", "bar")
val b = listOf("cheese", "wine")
val stream = a.stream() + b
assertEquals(listOf("foo", "bar", "cheese", "wine"), stream.toList())
// lets use a mutable variable
var ml = listOf("a").stream()
ml += a
ml += "beer"
ml += b
ml += "z"
assertEquals(listOf("a", "foo", "bar", "beer", "cheese", "wine", "z"), ml.toList())
}
Test fun iterationOverStream() {
val c = arrayListOf(0, 1, 2, 3, 4, 5)
var s = ""
for (i in c.stream()) {
s = s + i.toString()
}
assertEquals("012345", s)
}
Test fun streamFromFunction() {
var count = 3
val stream = stream<Int> {
count--
if (count >= 0) count else null
}
val list = stream.toList()
assertEquals(listOf(2, 1, 0), list)
}
Test fun streamFromFunctionWithInitialValue() {
val values = stream<Int>(3) { n -> if (n > 0) n - 1 else null }
assertEquals(arrayListOf(3, 2, 1, 0), values.toList())
}
private fun <T, C : MutableCollection<in T>> Stream<T>.takeWhileTo(result: C, predicate: (T) -> Boolean): C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
Test fun streamExtensions() {
val c = arrayListOf(0, 1, 2, 3, 4, 5)
val d = ArrayList<Int>()
c.stream().takeWhileTo(d, { i -> i < 4 })
assertEquals(4, d.size())
}
/*
Test fun pairIterator() {
val pairStr = (fibonacci() zip fibonacci().map { i -> i*2 }).makeString(limit = 10)
assertEquals("(0, 0), (1, 2), (1, 2), (2, 4), (3, 6), (5, 10), (8, 16), (13, 26), (21, 42), (34, 68), ...", pairStr)
}
*/
}
@@ -1,4 +1,4 @@
package serial
package test.concurrent
import java.io.ObjectOutputStream
import java.io.ByteArrayOutputStream
@@ -1,4 +1,4 @@
package concurrent
package test.concurrent
import kotlin.concurrent.*
import kotlin.test.*
@@ -1,4 +1,4 @@
package concurrent
package test.concurrent
import kotlin.concurrent.*
import kotlin.test.*
+1 -1
View File
@@ -39,7 +39,7 @@ class NextSiblingTest {
val elems = doc["#id3"]
val element = elems.first()
val elements = element.nextElements().toList()
val elements = element.nextElements()
val nodes = element.nextSiblings().toList()
assertEquals(1, elements.size())
@@ -1,4 +1,4 @@
package test.collections
package test.io
import kotlin.test.*
@@ -12,7 +12,7 @@ class IoTest(){
test fun testLineIteratorWithManualClose() {
val reader = sample().buffered()
try {
val list = reader.lineIterator().toArrayList()
val list = reader.lines().toArrayList()
assertEquals(arrayListOf("Hello", "World"), list)
} finally {
reader.close()
+2 -2
View File
@@ -175,14 +175,14 @@ class MapJsTest {
*/
test fun createUsingPairs() {
val map = hashMap(Pair("a", 1), Pair("b", 2))
val map = mapOf(Pair("a", 1), Pair("b", 2))
assertEquals(2, map.size)
assertEquals(1, map.get("a"))
assertEquals(2, map.get("b"))
}
test fun createUsingTo() {
val map = hashMap("a" to 1, "b" to 2)
val map = mapOf("a" to 1, "b" to 2)
assertEquals(2, map.size)
assertEquals(1, map.get("a"))
assertEquals(2, map.get("b"))
+17 -17
View File
@@ -6,7 +6,7 @@ import org.junit.Test
class SetJsTest {
val data: Set<String> = createTestMutableSet()
val empty: Set<String> = hashSet<String>()
val empty: Set<String> = hashSetOf<String>()
Test fun size() {
assertEquals(2, data.size())
@@ -39,10 +39,10 @@ class SetJsTest {
}
Test fun containsAll() {
assertTrue(data.containsAll(arrayList("foo", "bar")))
assertTrue(data.containsAll(arrayList<String>()))
assertFalse(data.containsAll(arrayList("foo", "bar", "baz")))
assertFalse(data.containsAll(arrayList("baz")))
assertTrue(data.containsAll(arrayListOf("foo", "bar")))
assertTrue(data.containsAll(arrayListOf<String>()))
assertFalse(data.containsAll(arrayListOf("foo", "bar", "baz")))
assertFalse(data.containsAll(arrayListOf("baz")))
}
Test fun add() {
@@ -51,7 +51,7 @@ class SetJsTest {
assertEquals(3, data.size())
assertFalse(data.add("baz"))
assertEquals(3, data.size())
assertTrue(data.containsAll(arrayList("foo", "bar", "baz")))
assertTrue(data.containsAll(arrayListOf("foo", "bar", "baz")))
}
Test fun remove() {
@@ -65,36 +65,36 @@ class SetJsTest {
Test fun addAll() {
val data = createTestMutableSet()
assertTrue(data.addAll(arrayList("foo", "bar", "baz", "boo")))
assertTrue(data.addAll(arrayListOf("foo", "bar", "baz", "boo")))
assertEquals(4, data.size())
assertFalse(data.addAll(arrayList("foo", "bar", "baz", "boo")))
assertFalse(data.addAll(arrayListOf("foo", "bar", "baz", "boo")))
assertEquals(4, data.size())
assertTrue(data.containsAll(arrayList("foo", "bar", "baz", "boo")))
assertTrue(data.containsAll(arrayListOf("foo", "bar", "baz", "boo")))
}
Test fun removeAll() {
val data = createTestMutableSet()
assertFalse(data.removeAll(arrayList("baz")))
assertTrue(data.containsAll(arrayList("foo", "bar")))
assertFalse(data.removeAll(arrayListOf("baz")))
assertTrue(data.containsAll(arrayListOf("foo", "bar")))
assertEquals(2, data.size())
assertTrue(data.removeAll(arrayList("foo")))
assertTrue(data.removeAll(arrayListOf("foo")))
assertTrue(data.contains("bar"))
assertEquals(1, data.size())
assertTrue(data.removeAll(arrayList("foo", "bar")))
assertTrue(data.removeAll(arrayListOf("foo", "bar")))
assertEquals(0, data.size())
val data2 = createTestMutableSet()
assertFalse(data.removeAll(arrayList("foo", "bar", "baz")))
assertFalse(data.removeAll(arrayListOf("foo", "bar", "baz")))
assertTrue(data.isEmpty())
}
Test fun retainAll() {
val data1 = createTestMutableSet()
assertTrue(data1.retainAll(arrayList("baz")))
assertTrue(data1.retainAll(arrayListOf("baz")))
assertTrue(data1.isEmpty())
val data2 = createTestMutableSet()
assertTrue(data2.retainAll(arrayList("foo")))
assertTrue(data2.retainAll(arrayListOf("foo")))
assertTrue(data2.contains("foo"))
assertEquals(1, data2.size())
}
@@ -109,5 +109,5 @@ class SetJsTest {
}
//Helpers
fun createTestMutableSet(): MutableSet<String> = hashSet("foo", "bar")
fun createTestMutableSet(): MutableSet<String> = hashSetOf("foo", "bar")
}
@@ -1,4 +1,4 @@
package test.string
package test.text
import kotlin.test.*
@@ -252,7 +252,9 @@ class StringJVMTest {
test fun drop() {
val data = "abcd1234"
assertEquals("d1234", data.drop(3))
assertEquals(data, data.drop(-2))
fails {
data.drop(-2)
}
assertEquals("", data.drop(data.length + 5))
}
@@ -265,7 +267,9 @@ class StringJVMTest {
test fun take() {
val data = "abcd1234"
assertEquals("abc", data.take(3))
assertEquals("", data.take(-7))
fails {
data.take(-7)
}
assertEquals(data, data.take(data.length + 42))
}
@@ -1,4 +1,4 @@
package test
package test.text
import kotlin.test.*
import org.junit.Test as test
@@ -1,4 +1,4 @@
package test.string
package test.text
import kotlin.*
import kotlin.test.*