From b3797c98ff9899c67573eb5e858ee4d5ef20b329 Mon Sep 17 00:00:00 2001 From: Pavel Punegov Date: Mon, 22 Oct 2018 20:44:17 +0300 Subject: [PATCH] Add contracts to assertions --- backend.native/tests/testing/assertions.kt | 18 ++++++++++++++++++ .../src/main/kotlin/kotlin/test/Assertions.kt | 5 +++++ 2 files changed, 23 insertions(+) diff --git a/backend.native/tests/testing/assertions.kt b/backend.native/tests/testing/assertions.kt index 1068549347c..2f927e3e361 100644 --- a/backend.native/tests/testing/assertions.kt +++ b/backend.native/tests/testing/assertions.kt @@ -163,6 +163,24 @@ class BasicAssertionsTest { fun testExpectFails() { checkFailedAssertion { expect(1) { 2 } } } + + @Test + fun testContracts() { + open class S + class P(val str: String = "P") : S() + + val s: S = P() + val p: Any = P("A") + + assertTrue(s is P) + assertEquals("P", s.str) + assertFalse(p !is P) + assertEquals("A", p.str) + + val nullableT: P? = P("N") + assertNotNull(nullableT) + assertEquals("N", nullableT.str) + } } diff --git a/runtime/src/main/kotlin/kotlin/test/Assertions.kt b/runtime/src/main/kotlin/kotlin/test/Assertions.kt index 6eed1b4377a..a53a6259187 100644 --- a/runtime/src/main/kotlin/kotlin/test/Assertions.kt +++ b/runtime/src/main/kotlin/kotlin/test/Assertions.kt @@ -10,6 +10,7 @@ package kotlin.test +import kotlin.contracts.* import kotlin.internal.InlineOnly import kotlin.internal.OnlyInputTypes import kotlin.reflect.KClass @@ -25,6 +26,7 @@ public fun assertTrue(message: String? = null, block: () -> Boolean): Unit = ass /** Asserts that the expression is `true` with an optional [message]. */ public fun assertTrue(actual: Boolean, message: String? = null) { + contract { returns() implies actual } return asserter.assertTrue(message ?: "Expected value to be true.", actual) } @@ -33,6 +35,7 @@ public fun assertFalse(message: String? = null, block: () -> Boolean): Unit = as /** Asserts that the expression is `false` with an optional [message]. */ public fun assertFalse(actual: Boolean, message: String? = null) { + contract { returns() implies (!actual) } return asserter.assertTrue(message ?: "Expected value to be false.", !actual) } @@ -58,12 +61,14 @@ public fun <@OnlyInputTypes T> assertNotSame(illegal: T, actual: T, message: Str /** Asserts that the [actual] value is not `null`, with an optional [message]. */ public fun assertNotNull(actual: T?, message: String? = null): T { + contract { returns() implies (actual != null) } asserter.assertNotNull(message, actual) return actual!! } /** Asserts that the [actual] value is not `null`, with an optional [message] and a function [block] to process the not-null value. */ public fun assertNotNull(actual: T?, message: String? = null, block: (T) -> R) { + contract { returns() implies (actual != null) } asserter.assertNotNull(message, actual) if (actual != null) { block(actual)