package android.os object SystemClock { fun elapsedRealtime() = TestScheduler.now } class Looper { companion object { private val main = Looper(); fun getMainLooper() = main } } class HandlerThread(name: String) { val looper = Looper(); fun start() {} ; fun quitSafely() {} } class Handler(val looper: Looper = Looper.getMainLooper()) { fun post(action: Runnable): Boolean = postDelayed(action,0) fun postDelayed(action: Runnable, delay: Long): Boolean { TestScheduler.add(this,action,delay); return true } fun removeCallbacks(action: Runnable) { TestScheduler.remove(this,action) } fun removeCallbacksAndMessages(token: Any?) { TestScheduler.remove(this,null) } } object TestScheduler { var now = 0L; private set private var serial = 0L private data class Task(val handler: Handler,val action: Runnable,val due: Long,val serial: Long) private val tasks = java.util.PriorityQueue(compareBy { it.due }.thenBy { it.serial }) fun add(handler: Handler,action: Runnable,delay: Long) { tasks.add(Task(handler,action,now+delay,++serial)) } fun remove(handler: Handler,action: Runnable?) { tasks.removeIf { it.handler === handler && (action == null || it.action === action) } } fun reset() { tasks.clear(); now=0; serial=0 } fun until(limitMs: Long = 10_000,condition: () -> Boolean) { val end=now+limitMs var count=0 while (!condition()) { val task=tasks.poll() ?: error("No scheduled task before condition") check(task.due <= end && ++count <= 100_000) { "Scheduler bound exceeded" } now=task.due; task.action.run() } } fun advanceBy(ms: Long) { val end=now+ms; var count=0 while (tasks.peek()?.due?.let { it <= end } == true) { val task=tasks.poll(); now=task.due; task.action.run(); check(++count < 100_000) } now=end } }