diff --git a/mirai-core/src/commonTest/kotlin/test/events.kt b/mirai-core/src/commonTest/kotlin/test/events.kt new file mode 100644 index 000000000..dd063d420 --- /dev/null +++ b/mirai-core/src/commonTest/kotlin/test/events.kt @@ -0,0 +1,57 @@ +/* + * Copyright 2019-2021 Mamoe Technologies and contributors. + * + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证. + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link. + * + * https://github.com/mamoe/mirai/blob/master/LICENSE + */ + +package net.mamoe.mirai.internal.test + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import net.mamoe.mirai.event.Event +import net.mamoe.mirai.event.GlobalEventChannel +import java.util.concurrent.atomic.AtomicInteger +import kotlin.test.assertEquals + +@OptIn(ExperimentalCoroutinesApi::class) +internal inline fun assertEventBroadcasts(times: Int = 1, block: () -> R): R { + val receivedEvents = AtomicInteger(0) + val listener = GlobalEventChannel.subscribeAlways { + receivedEvents.incrementAndGet() + } + try { + return block() + } finally { + listener.complete() + assertEquals( + times, + receivedEvents.get(), + "Expected event ${T::class.simpleName} broadcast $times time(s). But actual is ${receivedEvents.get()}." + ) + } +} + +@OptIn(ExperimentalCoroutinesApi::class) +internal inline fun assertEventBroadcasts(times: Int = 1, block: () -> Unit) { + val receivedEvents = AtomicInteger(0) + val listener = GlobalEventChannel.subscribeAlways { + receivedEvents.incrementAndGet() + } + try { + return block() + } finally { + listener.complete() + assertEquals( + times, + receivedEvents.get(), + "Expected event ${T::class.simpleName} broadcast $times time(s). But actual is ${receivedEvents.get()}." + ) + } +} + +@OptIn(ExperimentalCoroutinesApi::class) +internal inline fun assertEventNotBroadcast(block: () -> R): R { + return assertEventBroadcasts(0, block) +} \ No newline at end of file diff --git a/mirai-core/src/commonTest/kotlin/test/utils.kt b/mirai-core/src/commonTest/kotlin/test/utils.kt index ef765f5b1..2c4e1ab20 100644 --- a/mirai-core/src/commonTest/kotlin/test/utils.kt +++ b/mirai-core/src/commonTest/kotlin/test/utils.kt @@ -16,12 +16,17 @@ import kotlinx.coroutines.withTimeout import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext import kotlin.time.Duration +import kotlin.time.seconds fun runBlockingUnit( context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> Unit ) { - return runBlocking(context, block) + return runBlocking(context) { + withTimeout(60.seconds) { // always checks for infinite runs. + block() + } + } } fun runBlockingUnit(