MockBotTestBase.kt 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 net.mamoe.mirai.event.Event
  11. import net.mamoe.mirai.event.GlobalEventChannel
  12. import net.mamoe.mirai.mock.MockBotFactory
  13. import net.mamoe.mirai.mock.internal.MockBotImpl
  14. import net.mamoe.mirai.mock.utils.MockActionsScope
  15. import net.mamoe.mirai.mock.utils.broadcastMockEvents
  16. import org.junit.jupiter.api.AfterEach
  17. import org.junit.jupiter.api.TestInstance
  18. import kotlin.contracts.InvocationKind
  19. import kotlin.contracts.contract
  20. @TestInstance(TestInstance.Lifecycle.PER_METHOD)
  21. internal open class MockBotTestBase : TestBase() {
  22. internal val bot = MockBotFactory.newMockBotBuilder()
  23. .id((100000000L..321111111L).random())
  24. .nick("Kafusumi")
  25. .create()
  26. @AfterEach
  27. internal fun `$$bot dispose`() {
  28. bot.close()
  29. }
  30. internal suspend fun runAndReceiveEventBroadcast(
  31. action: suspend MockActionsScope.() -> Unit
  32. ): List<Event> {
  33. contract {
  34. callsInPlace(action, InvocationKind.EXACTLY_ONCE)
  35. }
  36. val result = mutableListOf<Event>()
  37. val listener = GlobalEventChannel.subscribeAlways<Event> {
  38. result.add(this)
  39. }
  40. broadcastMockEvents {
  41. action()
  42. }
  43. (bot as MockBotImpl).joinEventBroadcast()
  44. listener.cancel()
  45. return result
  46. }
  47. }