|
| 1 | +/* |
| 2 | + * Copyright 2016-2020 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 kotlinx.coroutines.exceptions.* |
| 8 | +import kotlin.test.* |
| 9 | + |
| 10 | +class ConcurrentExceptionsStressTest : TestBase() { |
| 11 | + private val nWorkers = 4 |
| 12 | + private val nRepeat = 1000 * stressTestMultiplier |
| 13 | + |
| 14 | + private val workers = Array(nWorkers) { index -> |
| 15 | + newSingleThreadContext("JobExceptionsStressTest-$index") |
| 16 | + } |
| 17 | + |
| 18 | + @AfterTest |
| 19 | + fun tearDown() { |
| 20 | + workers.forEach { |
| 21 | + it.close() |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + @Test |
| 26 | + fun testStress() = runTest { |
| 27 | + repeat(nRepeat) { |
| 28 | + testOnce() |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + @Suppress("SuspendFunctionOnCoroutineScope") // workaround native inline fun stacktraces |
| 33 | + private suspend fun CoroutineScope.testOnce() { |
| 34 | + val deferred = async(NonCancellable) { |
| 35 | + repeat(nWorkers) { index -> |
| 36 | + // Always launch a coroutine even if parent job was already cancelled (atomic start) |
| 37 | + launch(workers[index], start = CoroutineStart.ATOMIC) { |
| 38 | + randomWait() |
| 39 | + throw StressException(index) |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + deferred.join() |
| 44 | + assertTrue(deferred.isCancelled) |
| 45 | + val completionException = deferred.getCompletionExceptionOrNull() |
| 46 | + val cause = completionException as? StressException |
| 47 | + ?: unexpectedException("completion", completionException) |
| 48 | + val suppressed = cause.suppressed |
| 49 | + val indices = listOf(cause.index) + suppressed.mapIndexed { index, e -> |
| 50 | + (e as? StressException)?.index ?: unexpectedException("suppressed $index", e) |
| 51 | + } |
| 52 | + repeat(nWorkers) { index -> |
| 53 | + assertTrue(index in indices, "Exception $index is missing: $indices") |
| 54 | + } |
| 55 | + assertEquals(nWorkers, indices.size, "Duplicated exceptions in list: $indices") |
| 56 | + } |
| 57 | + |
| 58 | + private fun unexpectedException(msg: String, e: Throwable?): Nothing { |
| 59 | + e?.printStackTrace() |
| 60 | + throw IllegalStateException("Unexpected $msg exception", e) |
| 61 | + } |
| 62 | + |
| 63 | + private class StressException(val index: Int) : SuppressSupportingThrowable() |
| 64 | +} |
| 65 | + |
0 commit comments