1 /* <lambda>null2 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 */ 4 5 package kotlinx.coroutines 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 override fun reschedule() { 20 schedule() 21 } 22 } 23 24 inner class Box(val i: Int): Runnable { 25 override fun run() { 26 processed += i 27 } 28 } 29 30 inner class ReBox(val i: Int): Runnable { 31 override fun run() { 32 processed += i 33 queue.enqueue(Box(10 + i)) 34 } 35 } 36 37 @Test 38 fun testBasic() { 39 assertTrue(queue.isEmpty) 40 queue.enqueue(Box(1)) 41 assertFalse(queue.isEmpty) 42 assertTrue(scheduled) 43 queue.enqueue(Box(2)) 44 assertFalse(queue.isEmpty) 45 scheduled = false 46 queue.process() 47 assertEquals(listOf(1, 2), processed) 48 assertFalse(scheduled) 49 assertTrue(queue.isEmpty) 50 } 51 52 @Test fun testRescheduleFromProcess() { 53 assertTrue(queue.isEmpty) 54 queue.enqueue(ReBox(1)) 55 assertFalse(queue.isEmpty) 56 assertTrue(scheduled) 57 queue.enqueue(ReBox(2)) 58 assertFalse(queue.isEmpty) 59 scheduled = false 60 queue.process() 61 assertEquals(listOf(1, 2, 11, 12), processed) 62 assertFalse(scheduled) 63 assertTrue(queue.isEmpty) 64 } 65 66 @Test 67 fun testResizeAndWrap() { 68 repeat(10) { phase -> 69 val n = 10 * (phase + 1) 70 assertTrue(queue.isEmpty) 71 repeat(n) { 72 queue.enqueue(Box(it)) 73 assertFalse(queue.isEmpty) 74 assertTrue(scheduled) 75 } 76 var countYields = 0 77 while (scheduled) { 78 scheduled = false 79 queue.process() 80 countYields++ 81 } 82 assertEquals(List(n) { it }, processed) 83 assertEquals((n + queue.yieldEvery - 1) / queue.yieldEvery, countYields) 84 processed.clear() 85 } 86 } 87 }