Merge pull request #14 from chirino/KT-1530

For KT-1530
This commit is contained in:
James Strachan
2012-03-07 11:23:30 -08:00
2 changed files with 97 additions and 0 deletions
+48
View File
@@ -0,0 +1,48 @@
package kotlin
object Assertions {
// TODO make private once KT-1528 is fixed.
val _ENABLED = (javaClass<java.lang.System>()).desiredAssertionStatus()
}
/**
* Throws an [[AssertionError]] if the `value` is false and runtime assertions have been
* enabled on the JVM using the `-ea` JVM option.
*/
inline fun assert(value:Boolean):Unit {
if(Assertions._ENABLED) {
if(!value) {
throw AssertionError();
}
}
}
/**
* Throws an [[AssertionError]] with specified `message` if the `value` is false
* and runtime assertions have been enabled on the JVM using the `-ea` JVM option.
*/
inline fun assert<T>(value:Boolean, message:T) {
if(Assertions._ENABLED) {
if(!value) {
throw AssertionError(message);
}
}
}
/**
* Throws an [[IllegalArgumentException]] if the `value` is false.
*/
inline fun require(value:Boolean):Unit {
if(!value) {
throw IllegalArgumentException();
}
}
/**
* Throws an [[IllegalArgumentException]] with specified `message` if the `value` is false.
*/
inline fun require<T>(value:Boolean, message:T) {
if(!value) {
throw IllegalArgumentException(message.toString());
}
}
@@ -0,0 +1,49 @@
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)
}
}
// // Not sure why the assert method is not being resolved.
// fun ignorePassingAssert() {
// assert(true)
// }
//
// fun ignoreFailingAssert() {
// failsWith<AssertionError> {
// assert(false)
// }
// }
}