MockBotTestBase.kt 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.message.data.MessageSource
  13. import net.mamoe.mirai.mock.MockBotFactory
  14. import net.mamoe.mirai.mock.database.queryMessageInfo
  15. import net.mamoe.mirai.mock.internal.MockBotImpl
  16. import net.mamoe.mirai.mock.utils.MockActionsScope
  17. import net.mamoe.mirai.mock.utils.broadcastMockEvents
  18. import org.junit.jupiter.api.AfterEach
  19. import org.junit.jupiter.api.TestInstance
  20. import kotlin.contracts.InvocationKind
  21. import kotlin.contracts.contract
  22. import kotlin.test.fail
  23. @TestInstance(TestInstance.Lifecycle.PER_METHOD)
  24. internal open class MockBotTestBase : TestBase() {
  25. internal val bot = MockBotFactory.newMockBotBuilder()
  26. .id((100000000L..321111111L).random())
  27. .nick("Kafusumi")
  28. .create()
  29. @AfterEach
  30. internal fun `$$bot dispose`() {
  31. bot.close()
  32. }
  33. internal suspend fun runAndReceiveEventBroadcast(
  34. action: suspend MockActionsScope.() -> Unit
  35. ): List<Event> {
  36. contract {
  37. callsInPlace(action, InvocationKind.EXACTLY_ONCE)
  38. }
  39. val result = mutableListOf<Event>()
  40. val listener = GlobalEventChannel.subscribeAlways<Event> {
  41. result.add(this)
  42. }
  43. broadcastMockEvents {
  44. action()
  45. }
  46. (bot as MockBotImpl).joinEventBroadcast()
  47. listener.cancel()
  48. return result
  49. }
  50. internal fun assertMessageNotAvailable(source: MessageSource) {
  51. if (bot.msgDatabase.queryMessageInfo(source.ids, source.internalIds) != null) {
  52. fail("Require message $source no longer available.")
  53. }
  54. }
  55. internal fun assertMessageAvailable(source: MessageSource) {
  56. if (bot.msgDatabase.queryMessageInfo(source.ids, source.internalIds) == null) {
  57. fail("Require message $source available.")
  58. }
  59. }
  60. }