Browse Source

Add a message handler

tags/v0.1.0
Chris Smith 5 years ago
parent
commit
2a707a728a

+ 16
- 0
src/main/kotlin/com/dmdirc/ktirc/io/MessageHandler.kt View File

@@ -0,0 +1,16 @@
1
+package com.dmdirc.ktirc.io
2
+
3
+import com.dmdirc.ktirc.messages.MessageProcessor
4
+import kotlinx.coroutines.channels.ReceiveChannel
5
+import kotlinx.coroutines.channels.consumeEach
6
+
7
+class MessageHandler(private val processors: Collection<MessageProcessor>) {
8
+
9
+    suspend fun processMessages(messages: ReceiveChannel<IrcMessage>) {
10
+        messages.consumeEach { it.process() }
11
+    }
12
+
13
+    private fun IrcMessage.process() = this.getProcessor()?.process(this)
14
+    private fun IrcMessage.getProcessor() = processors.firstOrNull { it.commands.contains(this.command) }
15
+
16
+}

+ 57
- 0
src/test/kotlin/com/dmdirc/ktirc/io/MessageHandlerTest.kt View File

@@ -0,0 +1,57 @@
1
+package com.dmdirc.ktirc.io
2
+
3
+import com.dmdirc.ktirc.messages.MessageProcessor
4
+import com.nhaarman.mockitokotlin2.doReturn
5
+import com.nhaarman.mockitokotlin2.inOrder
6
+import com.nhaarman.mockitokotlin2.mock
7
+import com.nhaarman.mockitokotlin2.verify
8
+import kotlinx.coroutines.channels.Channel
9
+import kotlinx.coroutines.runBlocking
10
+import org.junit.jupiter.api.Test
11
+
12
+internal class MessageHandlerTest {
13
+
14
+    private val nickProcessor = mock<MessageProcessor> {
15
+        on { commands } doReturn arrayOf("FOO", "NICK")
16
+    }
17
+
18
+    private val joinProcessor = mock<MessageProcessor> {
19
+        on { commands } doReturn arrayOf("BAR", "JOIN")
20
+    }
21
+
22
+    @Test
23
+    fun `MessageHandler passes message on to correct processor`() = runBlocking {
24
+        val handler = MessageHandler(listOf(joinProcessor, nickProcessor))
25
+        val message = IrcMessage(null, null, "JOIN", emptyList())
26
+
27
+        with(Channel<IrcMessage>(1)) {
28
+            send(message)
29
+            close()
30
+            handler.processMessages(this)
31
+        }
32
+
33
+        verify(joinProcessor).process(message)
34
+    }
35
+
36
+    @Test
37
+    fun `MessageHandler reads multiple messages`() = runBlocking {
38
+        val handler = MessageHandler(listOf(joinProcessor, nickProcessor))
39
+        val joinMessage = IrcMessage(null, null, "JOIN", emptyList())
40
+        val nickMessage = IrcMessage(null, null, "NICK", emptyList())
41
+        val otherMessage = IrcMessage(null, null, "OTHER", emptyList())
42
+
43
+        with(Channel<IrcMessage>(3)) {
44
+            send(joinMessage)
45
+            send(nickMessage)
46
+            send(otherMessage)
47
+            close()
48
+            handler.processMessages(this)
49
+        }
50
+
51
+        with(inOrder(joinProcessor, nickProcessor)) {
52
+            verify(joinProcessor).process(joinMessage)
53
+            verify(nickProcessor).process(nickMessage)
54
+        }
55
+    }
56
+
57
+}

Loading…
Cancel
Save