moved the stdlib tests into the same directory as the stdlib, so it works a bit better with maven support in IDEA

This commit is contained in:
James Strachan
2012-03-14 16:14:04 +00:00
parent 9cd21d3a4d
commit 7ef65c0099
35 changed files with 2 additions and 2 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> java.lang.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 {
}
*/
-296
View File
@@ -1,296 +0,0 @@
package test.collections
import kotlin.test.*
// TODO can we avoid importing all this stuff by default I wonder?
// e.g. making println and the collection builder methods public by default?
import kotlin.*
import kotlin.io.*
import kotlin.util.*
import java.util.*
import junit.framework.TestCase
class CollectionTest() : TestCase() {
class IterableWrapper<T>(collection : java.lang.Iterable<T>) : java.lang.Iterable<T> {
private val collection = collection
override fun iterator(): java.util.Iterator<T> {
return collection.iterator().sure()
}
}
val data = arrayList("foo", "bar")
fun testAny() {
assertTrue {
data.any{it.startsWith("f")}
}
assertNot {
data.any{it.startsWith("x")}
}
}
fun testAll() {
assertTrue {
data.all{it.length == 3}
}
assertNot {
data.all{s -> s.startsWith("b")}
}
}
fun testCount() {
assertEquals(1, data.count{it.startsWith("b")})
assertEquals(2, data.count{it.size == 3})
}
fun testFilter() {
val foo = data.filter{it.startsWith("f")}
assertTrue {
foo.all{it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(arrayList("foo"), foo)
}
fun testFilterNot() {
val foo = data.filterNot{it.startsWith("b")}
assertTrue {
foo.all{it.startsWith("f")}
}
assertEquals(1, foo.size)
assertEquals(arrayList("foo"), foo)
}
fun testFilterIntoLinkedList() {
// TODO would be nice to avoid the <String>
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>
}
}
fun testFilterIntoSortedSet() {
// TODO would be nice to avoid the <String>
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>
}
}
fun testFind() {
val x = data.find{it.startsWith("x")}
assertNull(x)
fails {
x.sure()
}
val f = data.find{it.startsWith("f")}
f.sure()
assertEquals("foo", f)
}
fun testFlatMap() {
val characters = arrayList('f', 'o', 'o', 'b', 'a', 'r')
// TODO figure out how to get a line like this to compile :)
/*
val characters = data.flatMap<String,Character>{
it.toCharArray().toList() as Collection<Character>
}
*/
todo {
println("Got list of characters ${characters}")
val text = characters.join("")
assertEquals("foobar", text)
}
}
fun testForeach() {
var count = 0
data.forEach{ count += it.length }
assertEquals(6, count)
}
fun testFold() {
expect(10) {
val numbers = arrayList(1, 2, 3, 4)
// TODO would be nice to be able to write this as this
//numbers.fold(0){it + it2}
numbers.fold(0){(it, it2) -> it + it2}
}
expect(0) {
val numbers = arrayList<Int>()
numbers.fold(0){(it, it2) -> it + it2}
}
expect("1234") {
val numbers = arrayList(1, 2, 3, 4)
// TODO would be nice to be able to write this as this
// numbers.map{it.toString()}.fold(""){it + it2}
numbers.map<Int, String>{it.toString()}.fold(""){(it, it2) -> it + it2}
}
}
fun testFoldRight() {
expect("4321") {
val numbers = arrayList(1, 2, 3, 4)
// TODO would be nice to be able to write this as this
// numbers.map{it.toString()}.foldRight(""){it + it2}
numbers.map<Int, String>{it.toString()}.foldRight(""){(it, it2) -> it + it2}
}
}
fun testGroupBy() {
val words = arrayList("a", "ab", "abc", "def", "abcd")
/*
TODO inference engine should not need this type info?
*/
val byLength = words.groupBy<String, Int>{it.length}
assertEquals(4, byLength.size())
println("Grouped by length is: $byLength")
/*
TODO compiler bug...
val l3 = byLength.getOrElse(3, {ArrayList<String>()})
assertEquals(2, l3.size)
*/
}
fun testJoin() {
val text = data.join("-", "<", ">")
assertEquals("<foo-bar>", text)
}
fun testMap() {
/**
TODO compiler bug
we should be able to remove the explicit type on the function
http://youtrack.jetbrains.net/issue/KT-1145
*/
val lengths = data.map<String, Int>{s -> s.length}
assertTrue {
lengths.all{it == 3}
}
assertEquals(2, lengths.size)
assertEquals(arrayList(3, 3), lengths)
}
fun testReverse() {
val rev = data.reverse()
assertEquals(arrayList("bar", "foo"), rev)
}
fun testSort() {
val coll: List<String> = arrayList("foo", "bar", "abc")
// TODO fixme
// Some sort of in/out variance thing - or an issue with Java interop?
//coll.sort()
todo {
assertEquals(3, coll.size)
assertEquals(arrayList("abc", "bar", "foo"), coll)
}
}
fun testToArray() {
val arr = data.toArray()
println("Got array ${arr}")
todo {
assertTrue {
arr is Array<String>
}
}
}
fun testSimpleCount() {
assertEquals(2, data.count())
assertEquals(3, hashSet(12, 14, 15).count())
assertEquals(0, ArrayList<Double>().count())
}
fun testLast() {
assertEquals("bar", data.last())
assertEquals(25, arrayList(15, 19, 20, 25).last())
// assertEquals(19, TreeSet(arrayList(90, 47, 19)).first())
assertEquals('a', linkedList('a').last())
}
fun testLastException() {
fails { arrayList<Int>().last() }
fails { linkedList<String>().last() }
fails { hashSet<Char>().last() }
}
fun testSubscript() {
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)
}
fun testIndices() {
val indices = data.indices
assertEquals(0, indices.start)
assertEquals(1, indices.end)
assertEquals(2, indices.size)
assertFalse(indices.isReversed)
}
fun testContains() {
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(linkedList(15, 19, 20).contains(15))
// assertTrue(IterableWrapper(hashSet(45, 14, 13)).contains(14))
// assertFalse(IterableWrapper(linkedList<Int>()).contains(15))
}
}
@@ -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)
}
}
@@ -1,83 +0,0 @@
package org.jetbrains.kotlin.tools
import kotlin.*
import kotlin.io.*
import kotlin.util.*
import java.io.*
import java.util.*
fun generateFile(outFile: File, header: String, inputFile: File, f: (String)-> String) {
println("Parsing $inputFile and writing $outFile")
outFile.getParentFile()?.mkdirs()
val writer = PrintWriter(FileWriter(outFile))
try {
writer.println("// NOTE this file is auto-generated from $inputFile")
writer.println(header)
val reader = FileReader(inputFile).buffered()
try {
// TODO ideally we'd use a filterNot() here :)
val iter = reader.lineIterator()
while (iter.hasNext) {
val line = iter.next()
if (line.startsWith("package")) continue
val xform = f(line)
writer.println(xform)
}
} finally {
reader.close()
reader.close()
}
} finally {
writer.close()
}
}
/**
* Generates methods in the standard library which are mostly identical
* but just using a different input kind.
*
* Kinda like mimicking source macros here, but this avoids the inefficiency of type conversions
* at runtime.
*/
fun main(args: Array<String>) {
var stdlib = File("stdlib")
if (!stdlib.exists()) {
stdlib = File("../stdlib")
if (!stdlib.exists()) {
println("Cannot find stdlib!")
return
}
}
val srcDir = File(stdlib, "ktSrc")
val outDir = File(srcDir, "generated")
// JavaIterables - Generic iterable stuff
generateFile(File(outDir, "ArraysFromJavaIterables.kt"), "package kotlin\n\nimport kotlin.util.*", File(srcDir, "JavaIterables.kt")) {
it.replaceAll("java.lang.Iterable<T", "Array<T").replaceAll("java.lang.Iterable<T", "Array<T")
}
generateFile(File(outDir, "StandardFromJavaIterables.kt"), "package kotlin\n\nimport kotlin.util.*", File(srcDir, "JavaIterables.kt")) {
it.replaceAll("java.lang.Iterable<T", "Iterable<T")
}
// JavaCollections - methods returning a collection of the same input size (if its a collection)
generateFile(File(outDir, "ArraysFromJavaCollections.kt"), "package kotlin", File(srcDir, "JavaCollections.kt")) {
it.replaceAll("java.util.Collection<T", "Array<T")
}
generateFile(File(outDir, "JavaUtilIterablesFromJavaCollections.kt"), "package kotlin.util", File(srcDir, "JavaCollections.kt")) {
it.replaceAll("java.util.Collection<T", "java.lang.Iterable<T").replaceAll("(this.size)", "")
}
generateFile(File(outDir, "StandardFromJavaCollections.kt"), "package kotlin", File(srcDir, "JavaCollections.kt")) {
it.replaceAll("java.util.Collection<T", "Iterable<T").replaceAll("(this.size)", "")
}
}
-42
View File
@@ -1,42 +0,0 @@
package test.standard
import kotlin.*
import kotlin.test.*
import junit.framework.TestCase
class GetOrElseTest() : TestCase() {
val v1: String? = "hello"
val v2: String? = null
var counter = 0
fun testDefaultValue() {
assertEquals("hello", v1?: "bar")
expect("hello") {
v1?: "bar"
}
}
fun testDefaultValueOnNull() {
assertEquals("bar", v2?: "bar")
expect("bar") {
v2?: "bar"
}
}
fun calculateBar(): String {
counter++
return "bar"
}
fun testLazyDefaultValue() {
counter = 0
assertEquals("hello", v1?: calculateBar())
assertEquals(counter, 0, "counter should not be incremented yet")
assertEquals("bar", v2?: calculateBar())
assertEquals(counter, 1, "counter should be incremented in the default function")
}
}
-74
View File
@@ -1,74 +0,0 @@
package test.collections
import kotlin.test.*
import kotlin.io.*
import kotlin.util.*
import java.io.*
import java.util.*
import junit.framework.TestCase
class IoTest() : TestCase() {
fun testLineIteratorWithManualClose() {
val reader = sample().buffered()
try {
val list = reader.lineIterator().toArrayList()
assertEquals(arrayList("Hello", "World"), list)
} finally {
reader.close()
}
}
fun sample() : Reader {
return StringReader("Hello\nWorld");
}
fun testLineIterator() {
// TODO we should maybe zap the useLines approach as it encourages
// use of iterators which don't close the underlying stream
val list1 = sample().useLines{it.toArrayList()}
val list2 = sample().useLines<ArrayList<String>>{it.toArrayList()}
assertEquals(arrayList("Hello", "World"), list1)
assertEquals(arrayList("Hello", "World"), list2)
}
fun testForEach() {
val list = ArrayList<String>()
val reader = sample().buffered()
reader.use{
while (true) {
val line = it.readLine()
if (line != null)
list.add(line)
else
break
}
}
assertEquals(arrayList("Hello", "World"), list)
}
fun testForEachLine() {
val list = ArrayList<String>()
val reader = sample()
/* TODO would be nicer maybe to write this as
reader.lines.forEach { ... }
as we could one day maybe one day write that as
for (line in reader.lines)
if the for(elem in thing) {...} statement could act as syntax sugar for
thing.forEach{ elem -> ... }
if thing is not an Iterable/array/Iterator but has a suitable forEach method
*/
reader.forEachLine{
list.add(it)
}
assertEquals(arrayList("Hello", "World"), list)
}
}
-14
View File
@@ -1,14 +0,0 @@
package testjc
import kotlin.test.*
import junit.framework.TestCase
class C()
class JavaClassTest() : TestCase() {
fun testMe () {
assertEquals("java.util.ArrayList", java.util.ArrayList<Any>().javaClass.getName())
assertEquals("java.util.ArrayList", javaClass<java.util.ArrayList<Any>>().getName())
assertEquals("testjc.C", javaClass<C>().getName())
}
}
-42
View File
@@ -1,42 +0,0 @@
package test.collections
import kotlin.test.*
// TODO can we avoid importing all this stuff by default I wonder?
// e.g. making println and the collection builder methods public by default?
import kotlin.*
import kotlin.io.*
import kotlin.util.*
import java.util.*
import junit.framework.TestCase
class ListTest() : TestCase() {
val data = arrayList("foo", "bar")
fun testHeadAndTail() {
val h = data.head
assertEquals("foo", h)
val t = data.tail
assertEquals("bar", t)
}
fun testFirstAndLast() {
val h = data.first
assertEquals("foo", h)
val t = data.last
assertEquals("bar", t)
}
fun testWithIndices() {
val withIndices = data.withIndices()
var index = 0
for (withIndex in withIndices) {
assertEquals(withIndex._1, index)
assertEquals(withIndex._2, data[index])
index++
}
assertEquals(data.size(), index)
}
}
-53
View File
@@ -1,53 +0,0 @@
package test.collections
import kotlin.test.*
// TODO can we avoid importing all this stuff by default I wonder?
// e.g. making println and the collection builder methods public by default?
import kotlin.*
import kotlin.io.*
import kotlin.util.*
import java.util.*
import junit.framework.TestCase
class MapTest() : TestCase() {
val data: java.util.Map<String, Int> = java.util.HashMap<String, Int>()
fun testGetOrElse() {
val a = data.getOrElse("foo"){2}
assertEquals(2, a)
val b = data.getOrElse("foo"){3}
assertEquals(3, b)
assertEquals(0, data.size())
}
fun testGetOrPut() {
val a = data.getOrPut("foo"){2}
assertEquals(2, a)
val b = data.getOrPut("foo"){3}
assertEquals(2, b)
assertEquals(1, data.size())
}
fun testSizeAndEmpty() {
assertTrue{ data.empty }
// TODO using size breaks a test case
assertEquals(data.size(), 0)
}
fun testSetViaIndexOperators() {
val map = java.util.HashMap<String, String>()
assertTrue{ map.empty }
// TODO using size breaks a test case
assertEquals(map.size(), 0)
map["name"] = "James"
assertTrue{ !map.empty }
assertEquals(map.size(), 1)
assertEquals("James", map["name"])
}
}
-40
View File
@@ -1,40 +0,0 @@
package test.collections;
import kotlin.math.*
import java.math.BigInteger
import java.math.BigDecimal
import kotlin.test.*
import junit.framework.TestCase
class MathTest : TestCase() {
fun testBigInteger() {
val a = BigInteger("2")
val b = BigInteger("3")
assertEquals(BigInteger("5"), a + b)
assertEquals(BigInteger("-1"), a - b)
assertEquals(BigInteger("6"), a * b)
assertEquals(BigInteger("0"), a / b)
assertEquals(BigInteger("-2"), -a)
assertEquals(BigInteger("1"), -a % b)
assertEquals(BigInteger("-2"), -a remainder b)
}
fun testBigDecimal() {
val a = BigDecimal("2")
val b = BigDecimal("3")
assertEquals(BigDecimal("5"), a + b)
assertEquals(BigDecimal("-1"), a - b)
assertEquals(BigDecimal("6"), a * b)
assertEquals(BigDecimal("2"), BigDecimal("4") / a)
assertEquals(BigDecimal("-2"), -a)
assertEquals(BigDecimal("-2"), -a % b)
}
}
fun main(args: Array<String>) {
MathTest().testBigInteger()
MathTest().testBigDecimal()
}
-35
View File
@@ -1,35 +0,0 @@
package test.collections
import kotlin.*
import kotlin.io.*
import kotlin.util.*
import kotlin.test.*
import java.util.*
import java.io.*
import junit.framework.TestCase
class OldStdlibTest() : TestCase() {
fun testCollectionEmpty() {
assertNot {
Arrays.asList(0, 1, 2)?.empty ?: false
}
}
fun testCollectionSize() {
assertTrue {
Arrays.asList(0, 1, 2)?.size == 3
}
}
fun testInputStreamIterator() {
val x = ByteArray (10)
for(index in 0..9) {
x [index] = index.toByte()
}
for(b in x.inputStream) {
System.out?.println(b)
}
}
}
-101
View File
@@ -1,101 +0,0 @@
package test.collections
import junit.framework.TestCase
import kotlin.test.*
import java.lang.IllegalArgumentException
class PreconditionsTest() : TestCase() {
fun testPassingRequire() {
require(true)
}
fun testFailingRequire() {
val error = fails {
require(false)
}
if(error is IllegalArgumentException) {
assertNull(error.getMessage())
} else {
fail("Invalid exception type: "+error)
}
}
fun testPassingRequireWithMessage() {
require(true, "Hello")
}
fun testFailingRequireWithMessage() {
val error = fails {
require(false, "Hello")
}
if(error is IllegalArgumentException) {
assertEquals("Hello", error.getMessage())
} else {
fail("Invalid exception type: "+error)
}
}
// TODO: uncomment when KT-1540 is resolved.
// fun testPassingCheck() {
// check1(true)
// }
//
// fun testFailingCheck() {
// val error = fails {
// check1(false)
// }
// if(error is IllegalStateException) {
// assertNull(error.getMessage())
// } else {
// fail("Invalid exception type: "+error)
// }
// }
//
// fun testPassingCheckWithMessage() {
// check2(true, "Hello")
// }
//
// fun testFailingCheckWithMessage() {
// val error = fails {
// check2(false, "Hello")
// }
// if(error is IllegalStateException) {
// assertEquals("Hello", error.getMessage())
// } else {
// fail("Invalid exception type: "+error)
// }
// }
// TODO: uncomment when KT-1540 is resolved.
// fun testPassingAssert() {
// assert1(true)
// }
//
// fun testFailingAssert() {
// val error = fails {
// assert1(false)
// }
// if(error is IllegalStateException) {
// assertNull(error.getMessage())
// } else {
// fail("Invalid exception type: "+error)
// }
// }
//
// fun testPassingAssertWithMessage() {
// assert2(true, "Hello")
// }
//
// fun testFailingAssertWithMessage() {
// val error = fails {
// assert2(false, "Hello")
// }
// if(error is IllegalStateException) {
// assertEquals("Hello", error.getMessage())
// } else {
// fail("Invalid exception type: "+error)
// }
// }
}
-71
View File
@@ -1,71 +0,0 @@
package test.collections
import kotlin.*
import kotlin.io.*
import kotlin.util.*
import kotlin.test.*
import java.util.*
import junit.framework.TestCase
class SetTest() : TestCase() {
val data = hashSet("foo", "bar")
fun testAny() {
assertTrue {
data.any{it.startsWith("f")}
}
assertNot {
data.any{it.startsWith("x")}
}
}
fun testAll() {
assertTrue {
data.all{it.length == 3}
}
assertNot {
data.all{(s: String) -> s.startsWith("b")}
}
}
fun testFilter() {
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>
}
}
fun testFind() {
val x = data.find{it.startsWith("x")}
assertNull(x)
fails {
x.sure()
}
val f = data.find{it.startsWith("f")}
f.sure()
assertEquals("foo", f)
}
fun testMap() {
/**
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<String, Int>{(s: String) -> s.length}
assertTrue {
lengths.all{it == 3}
}
assertEquals(2, lengths.size)
assertEquals(arrayList(3, 3), lengths)
}
}
@@ -1,25 +0,0 @@
package test.collections
import kotlin.*
import kotlin.test.*
import junit.framework.TestCase
class StandardCollectionTest() : TestCase() {
fun testDisabled() {
}
/*
fun testAny() {
// TODO requires KT-924 to be implemented
val data: Iterable<String> = kotlin.util.arrayList("foo", "bar")
assertTrue {
data.any{it.startsWith("f")}
}
assertNot {
data.any{it.startsWith("x")}
}
}
*/
}
@@ -1,25 +0,0 @@
package test.stdlib.issues
import java.util.List
import kotlin.util.*
import kotlin.test.*
import junit.framework.TestCase
private fun listDifference<T>(first : List<T>, second : List<T>) : List<T> {
return first.filter{ !second.contains(it) }.toList()
}
class StdLibIssuesTest() : TestCase() {
fun test_KT_1131() {
val data = arrayList("blah", "foo", "bar")
val filterValues = arrayList("bar", "something", "blah")
expect(arrayList("foo")) {
val answer = listDifference(data, filterValues)
println("Found answer ${answer}")
answer
}
}
}
-49
View File
@@ -1,49 +0,0 @@
package test.string
import kotlin.io.*
import kotlin.test.*
import junit.framework.*
class StringTest() : TestCase() {
fun testStringIterator() {
var sum = 0
for(c in "239")
sum += (c.toInt() - '0'.toInt())
assertTrue(sum == 14)
}
fun testStringBuilderIterator() {
var sum = 0
val sb = StringBuilder()
for(c in "239")
sb.append(c)
println(sb)
for(c in sb)
sum += (c.toInt() - '0'.toInt())
assertTrue(sum == 14)
}
fun testOrEmpty() {
val s: String? = "hey"
val ns: String? = null
assertEquals("hey", s.orEmpty())
assertEquals("", ns.orEmpty())
}
fun testToShort() {
assertEquals(77.toShort(), "77".toShort())
}
fun testToInt() {
assertEquals(77, "77".toInt())
}
fun testToLong() {
assertEquals(77.toLong(), "77".toLong())
}
}
-16
View File
@@ -1,16 +0,0 @@
package test.string
import kotlin.*
import kotlin.test.*
import kotlin.util.*
import junit.framework.*
class StringUtilTest() : TestCase() {
fun testToRegex() {
val re = """foo""".toRegex()
val list = re.split("hellofoobar").filterNotNull()
assertEquals(arrayList("hello", "bar"), list)
}
}
-146
View File
@@ -1,146 +0,0 @@
package kotlinhack.test
import junit.framework.*
import kotlin.io.*
import kotlin.util.*
import java.util.*
import org.junit.*
import org.junit.runner.*
import org.junit.runner.notification.*
protected class TestBuilt<T>(name: String, val builder: TestBuilder<T>, val test: TestBuilt<T>.() -> Unit) : TestCase(name) {
private var myState: T? = null
var state : T
get() = myState.sure()
set(newState: T) { myState = newState }
override fun countTestCases(): Int = 1
override fun setUp() = this.(builder.setUp)()
override fun tearDown() = this.(builder.tearDown)()
override fun runTest() = this.(test)()
}
open class TestBuilder<T>(name: String) {
val mySuite : TestSuite = TestSuite(name)
public var setUp : TestBuilt<T>.() -> Unit = {}
public var tearDown : TestBuilt<T>.() -> Unit = {}
fun String.minus(test: TestBuilt<T>.() -> Unit) {
mySuite.addTest(TestBuilt<T>(this, this@TestBuilder, test))
}
}
private val currentTestBuilder = ThreadLocal<TestSuite> ()
private fun <T> testSuite(builder: TestBuilder<T>, description: TestBuilder<T>.() -> Unit) : TestSuite? {
val currentTestSuite = currentTestBuilder.get()
currentTestBuilder.set(builder.mySuite)
try {
builder.(description)()
return if(currentTestSuite != null) {
currentTestSuite.addTest(builder.mySuite)
null
}
else {
builder.mySuite
}
}
finally {
currentTestBuilder.set(currentTestSuite)
}
}
fun <T> testSuite(name: String, description: TestBuilder<T>.() -> Unit) : TestSuite? =
testSuite(TestBuilder<T>(name), description)
fun assertNot(message: String, block: ()-> Boolean) {
Assert.assertTrue(message, block())
}
fun assertNot(block: ()-> Boolean) = assertNot(block.toString(), block)
fun assertTrue(actual: Boolean, message: String = "") {
return assertEquals(true, actual, message)
}
fun assertFalse(actual: Boolean, message: String = "") {
return assertEquals(false, actual, message)
}
fun assertEquals(expected: Any?, actual: Any?, message: String = "") {
Assert.assertEquals(message, expected, actual)
}
fun assertNotNull(actual: Any?, message: String = "") {
Assert.assertNotNull(message, actual)
}
fun assertNull(actual: Any?, message: String = "") {
Assert.assertNull(message, actual)
}
fun fail(message: String = "") {
Assert.fail(message)
}
fun <T> expect(expected: T, block: ()-> T) {
expect(expected, block.toString(), block)
}
fun <T> expect(expected: T, message: String, block: ()-> T) {
val actual = block()
assertEquals(expected, actual, message)
}
fun fails(block: ()-> Any) {
try {
block()
Assert.fail("Expected an exception to be thrown")
} catch (e: Exception) {
println("Caught excepted exception: $e")
// OK
}
}
fun <T: Exception> failsWith(block: ()-> Any) {
try {
block()
Assert.fail("Expected an exception to be thrown")
} catch (e: T) {
println("Caught excepted exception: $e")
// OK
}
}
fun todo(block: ()-> Any) {
println("TODO at " + (Exception() as java.lang.Throwable).getStackTrace()?.get(1) + " for " + block)
}
/*
TODO we could maybe create our own test runner for JUnit
to avoid a runtime dependency on JUnit for running tests?
class KotlinTestRunner() : Runner() {
override fun getDescription(): Description? {
return null
}
override fun run(notifier: RunNotifier?) {
println("About to run a test case on ${this}")
}
}
*/
// TODO no annotations yet?
//@RunWith(KotlinTestRunner)
abstract class TestSupport() : TestCase() {
}
-60
View File
@@ -1,60 +0,0 @@
package testDslExample
import kotlin.io.*
import kotlinhack.test.*
import junit.framework.*
import junit.textui.TestRunner
public val suite : TestSuite? = testSuite<Int>("test group") {
var staticState = 10
setUp = {
staticState += 10
state = staticState
println("test '${getName()}' started")
}
tearDown = {
println("test '${getName()}' ended")
}
"test 1" - {
Assert.assertEquals(state, 20)
println("test '${getName()}': state: $state")
}
"test 2" - {
assertTrue(state == 31, "message")
println("test '${getName()}': state: $state")
}
"test 3" - {
Assert.assertEquals(state, 40)
println("test '${getName()}': state: $state")
}
testSuite<Any>("nested test suite") {
setUp = {
staticState += 10
state = staticState
println("nested test '${getName()}' started")
}
tearDown = {
println("nested test '${getName()}' ended")
}
"nested test 1" - {
println("test '${getName()}'")
}
"nested test 2" - {
println("test '${getName()}'")
}
"nested test 3" - {
println("test '${getName()}'")
}
}
}
@@ -1,16 +0,0 @@
package test.concurrent
import kotlin.concurrent.*
import junit.framework.*
class FListTest() : TestCase() {
fun testEmpty() {
val empty = FunctionalQueue<Int> ()
Assert.assertTrue(empty.empty)
}
fun testNonEmpty() {
// val empty = FunctionalList.emptyList<Int> ()
// assertTrue(!(empty + 10).empty)
}
}
@@ -1,50 +0,0 @@
package serial
import java.io.ObjectOutputStream
import java.io.ByteArrayOutputStream
import java.io.ByteArrayInputStream
import java.io.ObjectInputStream
import java.io.Serializable
import java.util.HashMap
import junit.framework.TestCase
import junit.framework.Assert
class Serial(val a : String) : java.lang.Object(), Serializable {
override fun toString() = a
}
class SerialTest() : TestCase() {
fun testMe() {
val tuple = #("lala", "bbb", Serial("serial"))
val op = { -> tuple.toString() }
val baos = ByteArrayOutputStream()
val oos = ObjectOutputStream(baos)
oos.writeObject(op)
oos.close()
val bais = ByteArrayInputStream(baos.toByteArray())
val ins = ObjectInputStream(bais)
val ops = ins.readObject() as (() -> String)
Assert.assertEquals(op (), ops())
}
fun testComplex() {
val y = 12
val op = { (x:Int) -> (x + y).toString() }
val op2 : Int.(Int) -> String = { op(this + it) }
val baos = ByteArrayOutputStream()
val oos = ObjectOutputStream(baos)
oos.writeObject(op2)
oos.close()
val bais = ByteArrayInputStream(baos.toByteArray())
val ins = ObjectInputStream(bais)
val ops = ins.readObject() as (Int.(Int) -> String)
Assert.assertEquals("27", 5.ops(10))
}
}
@@ -1,123 +0,0 @@
package test.dom
import kotlin.*
import kotlin.dom.*
import kotlin.util.*
import kotlin.test.*
import org.w3c.dom.*
import junit.framework.TestCase
class DomBuilderTest() : TestCase() {
fun testBuildDocument() {
var doc = createDocument()
assertTrue {
doc["grandchild"].isEmpty()
}
doc.addElement("foo") {
id = "id1"
style = "bold"
classes = "bar"
addElement("child") {
id = "id2"
classes = "another"
addElement("grandChild") {
id = "id3"
classes = " bar tiny"
addText("Hello World!")
// TODO support neater syntax sugar for adding text?
// += "Hello World!"
}
addElement("grandChild2") {
id = "id3"
classes = "tiny thing bar "
addText("Hello World!")
// TODO support neater syntax sugar for adding text?
// += "Hello World!"
}
}
}
println("builder document: ${doc.toXmlString()}")
// test css selections on document
assertEquals(0, doc[".doesNotExist"].size())
assertEquals(1, doc[".another"].size())
assertEquals(3, doc[".bar"].size())
assertEquals(2, doc[".tiny"].size())
// element tag selections
assertEquals(0, doc["doesNotExist"].size())
assertEquals(1, doc["foo"].size())
assertEquals(1, doc["child"].size())
assertEquals(1, doc["grandChild"].size())
// id selections
assertEquals(1, doc["#id1"].size())
assertEquals(1, doc["#id2"].size())
assertEquals(1, doc["#id3"].size())
val root = doc.rootElement
if (root != null) {
assertTrue {
root.hasClass("bar")
}
// test css selections on element
assertEquals(0, root[".doesNotExist"].size())
assertEquals(1, root[".another"].size())
assertEquals(2, root[".bar"].size())
assertEquals(2, root[".tiny"].size())
// element tag selections
assertEquals(0, root["doesNotExist"].size())
assertEquals(0, root["foo"].size())
assertEquals(1, root["child"].size())
assertEquals(1, root["grandChild"].size())
// id selections
assertEquals(1, root["#id1"].size())
assertEquals(1, root["#id2"].size())
assertEquals(1, root["#id3"].size())
} else {
fail("No root!")
}
val grandChild = doc["grandChild"].first
if (grandChild != null) {
println("got element ${grandChild.toXmlString()} with text '${grandChild.text}`")
assertEquals("Hello World!", grandChild.text)
assertEquals(" bar tiny", grandChild.attribute("class"))
// test the classSet
val classSet = grandChild.classSet
assertTrue(classSet.contains("bar"))
assertTrue(classSet.contains("tiny"))
assertTrue(classSet.size == 2 )
assertFalse(classSet.contains("doesNotExist"))
// lets add a new class and some existing classes
grandChild.addClass("bar")
grandChild.addClass("newThingy")
assertEquals("bar tiny newThingy", grandChild.classes)
// remove
grandChild.removeClass("bar")
assertEquals("tiny newThingy", grandChild.classes)
grandChild.removeClass("tiny")
assertEquals("newThingy", grandChild.classes)
} else {
fail("Not an Element $grandChild")
}
val children = doc.rootElement.children()
val xml = children.toXmlString()
println("root element has children: ${xml}")
assertEquals(1, children.size())
}
}
-39
View File
@@ -1,39 +0,0 @@
package test.dom
import kotlin.*
import kotlin.dom.*
import kotlin.test.*
import org.w3c.dom.*
import junit.framework.TestCase
class DomTest() : TestCase() {
fun testCreateDocument() {
var doc = createDocument()
assertNotNull(doc, "Should have created a document")
val e = doc.createElement("foo").sure()
assertCssClass(e, "")
// now lets update the cssClass property
e.classes = "foo"
assertCssClass(e, "foo")
// now using the attribute directly
e.setAttribute("class", "bar")
assertCssClass(e, "bar")
doc += e
println("document ${doc.toXmlString()}")
}
fun assertCssClass(e: Element, value: String?): Unit {
val cl = e.classes
val cl2 = e.getAttribute("class")
println("element ${e.toXmlString()} has cssClass `${cl}` class attr `${cl2}`")
assertEquals(value, cl, "value of element.cssClass")
assertEquals(value, cl2, "value of element.getAttribute(\"class\")")
}
}
@@ -1,23 +0,0 @@
package test.language
import junit.framework.TestCase
import kotlin.test.*
import org.jetbrains.kotlin.support.*
fun localUseWorks(): Unit {
val c = javaClass<Runnable>()
println("class is $c")
}
class JavaClassTest : TestCase() {
fun testJavaClass() {
localUseWorks()
// TODO this function fails!
// see KT-1515
loadAsserter()
}
}
@@ -1,20 +0,0 @@
package test.language
import junit.framework.TestCase
import java.util.Collection
import kotlin.test.*
class NullableCollectionsTest : TestCase() {
fun testIterateOverNullCollectionsThrowsNPE() {
val c: Collection<String>? = null
// TODO currently this will throw a NPE
// should it either be a compile error or handle nulls gracefully?
failsWith<NullPointerException> {
for (e in c) {
println("Hey got $e")
}
}
}
}
@@ -1,38 +0,0 @@
package language
import kotlin.util.*
import java.util.*
import junit.framework.TestCase
class Product(val name: String, val price: Double) {
}
class Customer(val name: String, val products: List<Product>) {
}
fun customerTemplate(customer: Customer) = """
<html>
<body>
<h1>Hello ${customer.name}</h1>
<ul>
${customer.products.map<Product,String>{ productSnippet(it) }.join("\n")}
</ul>
<p>lets do some kool stuff</p>
</body>
"""
fun productSnippet(product: Product) = "<li>${product.name}. Price : ${product.price}</li>"
// TODO support number formatting methods?
// fun productSnippet(product: Product) = "<li>${product.name}. Price : ${product.price.format('## ###,00')} </li>"
class StringExpressionExampleTest : TestCase() {
val customer = Customer("James", arrayList(Product("Beer", 1.99), Product("Wine", 5.99)))
fun testExpressions(): Unit {
println(customerTemplate(customer))
}
}
@@ -1,5 +0,0 @@
package language.main
fun main(args: Array<String>) {
println("Hello world!")
}
@@ -1,51 +0,0 @@
package test.properties
import kotlin.*
import kotlin.properties.*
import kotlin.util.*
import kotlin.test.*
import java.util.*
import junit.framework.TestCase
class Customer() : ChangeSupport() {
// TODO the setter code should be generated
// via KT-1299
var name: String? = null
set(value) {
changeProperty("name", $name, value)
$name = value
}
var city: String? = null
set(value) {
changeProperty("city", $city, value)
$city = value
}
fun toString() = "Customer($name, $city)"
}
class MyChangeListener() : ChangeListener {
val events = ArrayList<ChangeEvent>()
override fun onPropertyChange(event: ChangeEvent): Unit {
println("Property changed: $event")
events.add(event)
}
}
class PropertiesTest() : TestCase() {
fun testModel() {
val c = Customer()
c.name = "James"
c.city = "Mells"
val listener = MyChangeListener()
c.addChangeListener(listener)
c.name = "Andrey"
println("Customer $c and raised change events ${listener.events}")
assertEquals(1, listener.events.size(), "Should have received a change event ${listener.events}")
}
}
@@ -1,23 +0,0 @@
package test.regressions.kt1149
import java.util.ArrayList
import kotlin.util.*
import junit.framework.*
public trait SomeTrait {
fun foo()
}
class Kt1149Test() : TestCase() {
fun testMe() {
val list = ArrayList<SomeTrait>()
var res = ArrayList<String>()
list.add(object : SomeTrait {
override fun foo() {
res.add("anonymous.foo()")
}
})
list.forEach{ it.foo() }
Assert.assertEquals("anonymous.foo()", res[0])
}
}
@@ -1,19 +0,0 @@
package test.regressions.kt1172
import kotlin.concurrent.*
import junit.framework.*
import java.util.*
public fun scheduleRefresh(vararg files : Object) {
// TODO
// java.util.ArrayList<Object>(files.map{ it })
}
fun main(args : Array<String?>?) {
}
class Kt1172Test() : TestCase() {
fun testMe() {
main(null)
}
}
@@ -1,120 +0,0 @@
package testeval
import java.util.*
import junit.framework.TestCase.*
import junit.framework.Assert.* // TODO unnecessary import
trait Expression
class Num(val value : Int) : Expression
class Sum(val left : Expression, val right : Expression) : Expression
class Mult(val left : Expression, val right : Expression) : Expression
fun eval(e : Expression) : Int {
return when (e) {
is Num -> e.value
is Sum -> eval(e.left) + eval (e.right)
is Mult -> eval(e.left) * eval (e.right)
else -> throw AssertionError("Unknown expression")
}
}
trait ParseResult<out T> {
val success : Boolean
val value : T
}
class Success<T>(override val value : T) : ParseResult<T> {
public override val success : Boolean = true
}
class Failure(val message : String) : ParseResult<Nothing> {
override val success = false
override val value : Nothing = throw UnsupportedOperationException("Don't call value on a Failure")
}
open class Token(val text : String) {
fun toString() = text
}
object LPAR : Token("(")
object RPAR : Token(")")
object PLUS : Token("+")
object TIMES : Token("*")
object EOF : Token("EOF")
class Number(text : String) : Token(text)
class Error(text : String) : Token("[Error: $text]")
fun tokenize(text : String) : Deque<Token> {
val result = LinkedList<Token>()
for (c in text) {
result add when (c) {
'(' -> LPAR
')' -> RPAR
'+' -> PLUS
'*' -> TIMES
in '0'..'9' -> Number(c.toString())
else -> Error(c.toString())
}
}
result.add(EOF)
return result
}
fun parseSum(tokens : Deque<Token>) : ParseResult<Expression> {
val left = parseMult(tokens)
if (!left.success) return left
if (tokens.peek() == PLUS) {
tokens.pop()
val right = parseSum(tokens)
if (!right.success) return right
return Success(Sum(left.value, right.value))
}
return left
}
fun parseMult(tokens : Deque<Token>) : ParseResult<Expression> {
val left = parseAtomic(tokens)
if (!left.success) return left
if (tokens.peek() == PLUS) {
tokens.pop()
val right = parseMult(tokens)
if (!right.success) return right
return Success(Mult(left.value, right.value))
}
return left
}
fun parseAtomic(tokens : Deque<Token>) : ParseResult<Expression> {
val token = tokens.poll()
return when (token) {
LPAR -> {
val result = parseSum(tokens)
val rpar = tokens.poll()
if (rpar == RPAR)
result
else
Failure("Expecting ')'")
}
is Number -> Success(Num(Integer.parseInt((token as Token).text).sure()))
else -> Failure("Unexpected EOF")
}
}
fun parse(text : String) : ParseResult<Expression> = parseSum(tokenize(text))
class EvalTest : junit.framework.TestCase() {
fun testEval() {
assertEquals(1, eval(Num(1)))
assertEquals(2, eval(Sum(Num(1), Num(1))))
assertEquals(3, eval(Mult(Num(3), Num(1))))
assertEquals(6, eval(Mult(Num(3), Sum(Num(1), Num(1)))))
}
fun testParse() {
assertEquals(1, eval(parse("1").value))
}
}
@@ -1,23 +0,0 @@
package test.template
import kotlin.template.*
import kotlin.test.assertEquals
import junit.framework.TestCase
class HtmlTemplateTest : TestCase() {
fun testTemplate(): Unit {
val foo = "James"
val bar = "x > 1"
// Code generated by the following template expression:
//
// val actual = "<h1>$foo</h1> <p>hey $bar</p>".toHtml()
// TODO will use a tuple soon
//val actual = StringTemplate(Tuple3<String,String,String>("<h1>", foo, "</h1> <p>hey ", bar, "</p>")).toHtml()
val actual = StringTemplate(array("<h1>", foo, "</h1> <p>hey ", bar, "</p>")).toHtml()
assertEquals("<h1>James</h1> <p>hey x &gt; 1</p>", actual)
}
}
@@ -1,22 +0,0 @@
package test.template
import kotlin.template.*
import kotlin.test.assertEquals
import junit.framework.TestCase
class StringTemplateTest : TestCase() {
fun testTemplate(): Unit {
val name = "James"
// Code generated by the following template expression:
//
// val actual = "hello $name!".toString()
// TODO will use a tuple soon
//val actual = StringTemplate(Tuple3<String,String,String>("hello ", name, "!"))).toString()
val actual = StringTemplate(array("hello ", name, "!")).toString()
assertEquals("hello James!", actual)
}
}