Roman Elizarov | 6d54802 | 2018-01-12 20:21:19 +0300 | [diff] [blame] | 1 | /* |
Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame^] | 2 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | 6d54802 | 2018-01-12 20:21:19 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | package kotlinx.coroutines.experimental |
| 6 | |
| 7 | import kotlin.test.* |
| 8 | |
| 9 | class MessageQueueTest { |
| 10 | private var scheduled = false |
| 11 | private val processed = mutableListOf<Int>() |
| 12 | |
| 13 | private val queue = object : MessageQueue() { |
| 14 | override fun schedule() { |
| 15 | assertFalse(scheduled) |
| 16 | scheduled = true |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | inner class Box(val i: Int): Runnable { |
| 21 | override fun run() { |
| 22 | processed += i |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | inner class ReBox(val i: Int): Runnable { |
| 27 | override fun run() { |
| 28 | processed += i |
| 29 | queue.enqueue(Box(10 + i)) |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | @Test |
| 34 | fun testBasic() { |
| 35 | assertTrue(queue.isEmpty) |
| 36 | queue.enqueue(Box(1)) |
| 37 | assertFalse(queue.isEmpty) |
| 38 | assertTrue(scheduled) |
| 39 | queue.enqueue(Box(2)) |
| 40 | assertFalse(queue.isEmpty) |
| 41 | scheduled = false |
| 42 | queue.process() |
| 43 | assertEquals(listOf(1, 2), processed) |
| 44 | assertFalse(scheduled) |
| 45 | assertTrue(queue.isEmpty) |
| 46 | } |
| 47 | |
| 48 | @Test fun testRescheduleFromProcess() { |
| 49 | assertTrue(queue.isEmpty) |
| 50 | queue.enqueue(ReBox(1)) |
| 51 | assertFalse(queue.isEmpty) |
| 52 | assertTrue(scheduled) |
| 53 | queue.enqueue(ReBox(2)) |
| 54 | assertFalse(queue.isEmpty) |
| 55 | scheduled = false |
| 56 | queue.process() |
| 57 | assertEquals(listOf(1, 2, 11, 12), processed) |
| 58 | assertFalse(scheduled) |
| 59 | assertTrue(queue.isEmpty) |
| 60 | } |
| 61 | |
| 62 | @Test |
| 63 | fun testResizeAndWrap() { |
| 64 | repeat(10) { phase -> |
| 65 | val n = 10 * (phase + 1) |
| 66 | assertTrue(queue.isEmpty) |
| 67 | repeat(n) { |
| 68 | queue.enqueue(Box(it)) |
| 69 | assertFalse(queue.isEmpty) |
| 70 | assertTrue(scheduled) |
| 71 | } |
| 72 | var countYields = 0 |
| 73 | while (scheduled) { |
| 74 | scheduled = false |
| 75 | queue.process() |
| 76 | countYields++ |
| 77 | } |
| 78 | assertEquals(List(n) { it }, processed) |
| 79 | assertEquals((n + queue.yieldEvery - 1) / queue.yieldEvery, countYields) |
| 80 | processed.clear() |
| 81 | } |
| 82 | } |
| 83 | } |