Skip to content

Fix flaky SharingReferenceTest #2709

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

Merged
merged 1 commit into from
May 14, 2021
Merged
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
23 changes: 20 additions & 3 deletions kotlinx-coroutines-core/jvm/test/flow/SharingReferenceTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package kotlinx.coroutines.flow

import kotlinx.coroutines.*
import kotlinx.coroutines.internal.*
import org.junit.*

/**
Expand All @@ -15,6 +16,15 @@ import org.junit.*
class SharingReferenceTest : TestBase() {
private val token = object {}

/*
* Single-threaded executor that we are using to ensure that the flow being sharing actually
* suspended (spilled its locals, attached to parent), so we can verify reachability.
* Without that, it's possible to have a situation where target flow is still
* being strongly referenced (by its dispatcher), but the test already tries to test reachability and fails.
*/
@get:Rule
val executor = ExecutorRule(1)

private val weakEmitter = flow {
emit(null)
// suspend forever without keeping a strong reference to continuation -- this is a model of
Expand All @@ -26,19 +36,26 @@ class SharingReferenceTest : TestBase() {

@Test
fun testShareInReference() {
val flow = weakEmitter.shareIn(GlobalScope, SharingStarted.Eagerly, 0)
val flow = weakEmitter.shareIn(ContextScope(executor), SharingStarted.Eagerly, 0)
linearize()
FieldWalker.assertReachableCount(1, flow) { it === token }
}

@Test
fun testStateInReference() {
val flow = weakEmitter.stateIn(GlobalScope, SharingStarted.Eagerly, null)
val flow = weakEmitter.stateIn(ContextScope(executor), SharingStarted.Eagerly, null)
linearize()
FieldWalker.assertReachableCount(1, flow) { it === token }
}

@Test
fun testStateInSuspendingReference() = runTest {
val flow = weakEmitter.stateIn(GlobalScope)
linearize()
FieldWalker.assertReachableCount(1, flow) { it === token }
}
}

private fun linearize() {
runBlocking(executor) { }
}
}