Repository: Kotlin/kotlinx.coroutines
File: kotlinx-coroutines-test/common/src/TestCoroutineScope.kt (Kotlin)

Code before:
    private var cleanedUp = false

    override fun reportException(throwable: Throwable) {
        synchronized(lock) {
            if (cleanedUp)
                throw ExceptionReportAfterCleanup(throwable)
            exceptions.add(throwable)
        }
    }

    override val testScheduler: TestCoroutineScheduler
        get() = coroutineContext[TestCoroutineScheduler]!!

    /** These jobs existed before the coroutine scope was used, so it's alright if they don't get cancelled. */
    private val initialJobs = coroutineContext.activeJobs()

    override fun cleanupTestCoroutines() {
        (coroutineContext[CoroutineExceptionHandler] as? UncaughtExceptionCaptor)?.cleanupTestCoroutines()
        val delayController = coroutineContext.delayController
        var hasUncompletedJobs = false
        if (delayController != null) {
            try {
                delayController.cleanupTestCoroutines()
            } catch (e: UncompletedCoroutinesError) {
                hasUncompletedJobs = true
            }
        } else {
            testScheduler.runCurrent()
            if (!testScheduler.isIdle()) {
                hasUncompletedJobs = true
            }
        }
        synchronized(lock) {
            if (cleanedUp)
                throw IllegalStateException("Attempting to clean up a test coroutine scope more than once.")
            cleanedUp = true
        }
        exceptions.apply {
            firstOrNull()?.let {
                val toThrow = it
                drop(1).forEach { toThrow.addSuppressed(it) }
                ownJob?.completeExceptionally(toThrow)
                throw toThrow
            }
        }
        try {
            if (hasUncompletedJobs) {
                throw UncompletedCoroutinesError(
                    "Unfinished coroutines during teardown. Ensure all coroutines are" +
                        " completed or cancelled by your test."
                )

Review comment (suggestion):
And here ISE is used instead of a custom exception.

Code after:
            }
        }

    override val testScheduler: TestCoroutineScheduler
        get() = coroutineContext[TestCoroutineScheduler]!!

    /** These jobs existed before the coroutine scope was used, so it's alright if they don't get cancelled. */
    private val initialJobs = coroutineContext.activeJobs()

    override fun cleanupTestCoroutines() {
        val delayController = coroutineContext.delayController
        val hasUnfinishedJobs = if (delayController != null) {
            try {
                delayController.cleanupTestCoroutines()
                false
            } catch (e: UncompletedCoroutinesError) {
                true
            }
        } else {
            testScheduler.runCurrent()
            !testScheduler.isIdle()
        }
        (coroutineContext[CoroutineExceptionHandler] as? UncaughtExceptionCaptor)?.cleanupTestCoroutines()
        synchronized(lock) {
            if (cleanedUp)
                throw IllegalStateException("Attempting to clean up a test coroutine scope more than once.")
            cleanedUp = true
        }
        exceptions.firstOrNull()?.let { toThrow ->
            exceptions.drop(1).forEach { toThrow.addSuppressed(it) }
            throw toThrow
        }
        if (hasUnfinishedJobs)
            throw UncompletedCoroutinesError(
                "Unfinished coroutines during teardown. Ensure all coroutines are" +
                    " completed or cancelled by your test."
            )
        val jobs = coroutineContext.activeJobs()
        if ((jobs - initialJobs).isNotEmpty())
            throw UncompletedCoroutinesError("Test finished with active jobs: $jobs")
    }
}

private fun CoroutineContext.activeJobs(): Set<Job> {
    return checkNotNull(this[Job]).children.filter { it.isActive }.toSet()
}

/**
 * A coroutine scope for launching test coroutines using [TestCoroutineDispatcher].
 *
 * [createTestCoroutineScope] is a similar function that defaults to [StandardTestDispatcher].