Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throw unconsumed events if the scope is cancelled #248

Merged
merged 1 commit into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/commonMain/kotlin/app/cash/turbine/Turbine.kt
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ internal class ChannelTurbine<T>(
var cause: Throwable? = null
while (true) {
val event = channel.takeEventUnsafe() ?: break
if (event is Event.Error && event.throwable is CancellationException) break
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really like the idea of just eating these at the source. I had dealt with CancellationException in an ad-hoc manner when implementing turbineScope, and this is much cleaner

if (!(ignoreTerminalEvents && event.isTerminal)) unconsumed += event
if (event is Event.Error) {
cause = event.throwable
Expand Down
3 changes: 2 additions & 1 deletion src/commonMain/kotlin/app/cash/turbine/flow.kt
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,8 @@ private fun <T> testInInternal(flow: Flow<T>, timeout: Duration?, scope: Corouti
if (debug) println("Scope ending ${exception ?: ""}")

// Only validate events were consumed if the scope is exiting normally.
if (exception == null) {
// CancellationException also indicates _normal_ cancellation of a coroutine.
if (exception == null || exception is CancellationException) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can actually get rid of this whole invokeOnCompletion; turbineScope now has the code to run this validation, so we don't need it here. I'm kinda surprised it works, actually

Does not need to be changed before merge, I'll clean it up in a followup PR

turbine.ensureAllEventsConsumed()
}
}
Expand Down
27 changes: 27 additions & 0 deletions src/commonTest/kotlin/app/cash/turbine/FlowInScopeTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletionHandlerException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers.Default
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
Expand Down Expand Up @@ -96,6 +98,31 @@ class FlowInScopeTest {
assertFalse(collecting)
}

@Test fun unconsumedItemThrowsWhenCancelledExternally() = runTestTurbine {
// We have to use an exception handler rather than assertFailsWith because runTest also uses
// one which defers throwing until its block completes.
val exceptionHandler = RecordingExceptionHandler()
launch(start = CoroutineStart.UNDISPATCHED) {
withContext(exceptionHandler) {
flow {
emit("item!")
emitAll(neverFlow()) // Avoid emitting complete
}.testIn(this)
}
}.cancel()
val exception = exceptionHandler.exceptions.removeFirst()
assertTrue(exception is CompletionHandlerException)
val cause = exception.cause
assertTrue(cause is AssertionError)
assertEquals(
"""
|Unconsumed events found:
| - Item(item!)
""".trimMargin(),
cause.message,
)
}

@Test fun unconsumedItemThrows() = runTestTurbine {
// We have to use an exception handler rather than assertFailsWith because runTest also uses
// one which defers throwing until its block completes.
Expand Down