2
0

TestBase.kt 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright 2019-2022 Mamoe Technologies and contributors.
  3. *
  4. * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
  5. * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
  6. *
  7. * https://github.com/mamoe/mirai/blob/dev/LICENSE
  8. */
  9. package net.mamoe.mirai.mock.test
  10. import kotlinx.coroutines.CoroutineScope
  11. import kotlinx.coroutines.runBlocking
  12. import net.mamoe.mirai.event.Event
  13. import net.mamoe.mirai.event.events.MessageEvent
  14. import net.mamoe.mirai.event.events.MessagePostSendEvent
  15. import net.mamoe.mirai.event.events.MessagePreSendEvent
  16. import org.junit.jupiter.api.DynamicContainer
  17. import org.junit.jupiter.api.DynamicNode
  18. import org.junit.jupiter.api.DynamicTest
  19. import org.junit.jupiter.api.fail
  20. import java.net.URL
  21. import kotlin.reflect.jvm.jvmName
  22. import kotlin.test.assertFails
  23. internal open class TestBase {
  24. internal inline fun <reified T> assertIsInstance(value: Any?, block: T.() -> Unit = {}) {
  25. if (value !is T) {
  26. fail { "Actual value $value (${value?.javaClass}) is not instanceof ${T::class.jvmName}" }
  27. }
  28. block(value)
  29. }
  30. internal fun runTest(action: suspend CoroutineScope.() -> Unit) {
  31. runBlocking(block = action)
  32. }
  33. internal fun List<Event>.dropMessagePrePost() = filterNot {
  34. it is MessagePreSendEvent || it is MessagePostSendEvent<*>
  35. }
  36. internal fun List<Event>.dropMsgChat() = filterNot {
  37. it is MessageEvent || it is MessagePreSendEvent || it is MessagePostSendEvent<*>
  38. }
  39. internal fun String.toUrl(): URL = URL(this)
  40. internal inline fun <T> T.runAndAssertFails(block: T.() -> Unit) {
  41. assertFails { block() }
  42. }
  43. internal fun dynamicTest(displayName: String, action: suspend CoroutineScope.() -> Unit): DynamicTest {
  44. return DynamicTest.dynamicTest(displayName) { runBlocking(block = action) }
  45. }
  46. internal fun dynamicContainer(
  47. displayName: String,
  48. action: suspend CoroutineScope.() -> Iterable<DynamicNode>
  49. ): DynamicContainer {
  50. return DynamicContainer.dynamicContainer(displayName, runBlocking(block = action))
  51. }
  52. }