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

Commonize lifecycle tests #1330

Open
wants to merge 3 commits into
base: jb-main
Choose a base branch
from
Open
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 lifecycle/lifecycle-runtime/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ kotlin {
implementation(libs.kotlinCoroutinesTest)
implementation(libs.kotlinTest)
implementation(project(":kruth:kruth"))
implementation(libs.atomicFu)
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package androidx.lifecycle

import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlinx.coroutines.CloseableCoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.MainCoroutineDispatcher
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestResult
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain

/**
* Android Unit Tests target doesn't provide a Main dispatcher.
* Lifecycle internals rely on Main & Main.immediate dispatchers heavily,
* so we need to re-create their behavior in tests.
*/
@OptIn(ExperimentalCoroutinesApi::class, DelicateCoroutinesApi::class)
private class SurrogateMainCoroutineDispatcher : MainCoroutineDispatcher() {
private val isMainThread: ThreadLocal<Boolean> = ThreadLocal()

private val mainThreadSurrogate = newSingleThreadContext("UI thread")

init {
mainThreadSurrogate.dispatch(EmptyCoroutineContext, Runnable { isMainThread.set(true) })
}

override val immediate: MainCoroutineDispatcher = ImmediateMainCoroutineDispatcher(isMainThread, mainThreadSurrogate)

override fun dispatch(context: CoroutineContext, block: Runnable) {
mainThreadSurrogate.dispatch(context, block)
}

fun close() {
mainThreadSurrogate.close()
}
}

private class ImmediateMainCoroutineDispatcher(
private val isMainThread: ThreadLocal<Boolean>,
private val mainThreadSurrogate: CloseableCoroutineDispatcher,
) : MainCoroutineDispatcher() {
override val immediate: MainCoroutineDispatcher get() = this

override fun dispatch(context: CoroutineContext, block: Runnable) {
mainThreadSurrogate.dispatch(context, block)
}

override fun isDispatchNeeded(context: CoroutineContext): Boolean {
return !isMainThread.get()
}
}

@OptIn(ExperimentalCoroutinesApi::class)
actual fun runLifecycleTest(block: suspend CoroutineScope.() -> Unit): TestResult {
val mainThreadSurrogate = SurrogateMainCoroutineDispatcher()
Dispatchers.setMain(mainThreadSurrogate)

try {
runBlocking(mainThreadSurrogate, block = block)
} finally {
Dispatchers.resetMain()
mainThreadSurrogate.close()
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2019 The Android Open Source Project
* Copyright 2024 The Android Open Source Project
Copy link
Member

Choose a reason for hiding this comment

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

Please revert updating years in header comments

*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,27 +16,28 @@

package androidx.lifecycle

import com.google.common.truth.Truth
import java.util.concurrent.atomic.AtomicInteger
import androidx.kruth.assertThat
import kotlinx.atomicfu.atomic

Copy link
Member

Choose a reason for hiding this comment

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

Suggested change


/**
* Partial copy from
* https://github.com/Kotlin/kotlinx.coroutines/blob/master/core/kotlinx-coroutines-core/test/TestBase.kt
* to track execution order.
*/
class Expectations {
private val counter = AtomicInteger(0)
private val counter = atomic(0)

fun expect(expected: Int) {
val order = counter.incrementAndGet()
Truth.assertThat(order).isEqualTo(expected)
assertThat(order).isEqualTo(expected)
}

fun expectUnreached() {
throw AssertionError("should've not reached here")
}

fun expectTotal(total: Int) {
Truth.assertThat(counter.get()).isEqualTo(total)
assertThat(counter.value).isEqualTo(total)
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2021 The Android Open Source Project
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,33 +16,27 @@

package androidx.lifecycle

import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import androidx.kruth.assertThat
import kotlin.test.Test
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
import org.junit.Test

@SmallTest
@OptIn(ExperimentalCoroutinesApi::class)
class FlowWithLifecycleTest {
private val owner = FakeLifecycleOwner()
private val owner = TestLifecycleOwner()

@Test
fun testFiniteFlowCompletes() = runBlocking(Dispatchers.Main) {
fun testFiniteFlowCompletes() = runLifecycleTest {
owner.setState(Lifecycle.State.CREATED)
val result = flowOf(1, 2, 3)
.flowWithLifecycle(owner.lifecycle, Lifecycle.State.CREATED)
Expand All @@ -53,7 +47,7 @@ class FlowWithLifecycleTest {
}

@Test
fun testFlowStartsInSubsequentLifecycleState() = runBlocking(Dispatchers.Main) {
fun testFlowStartsInSubsequentLifecycleState() = runLifecycleTest {
owner.setState(Lifecycle.State.RESUMED)
val result = flowOf(1, 2, 3)
.flowWithLifecycle(owner.lifecycle, Lifecycle.State.CREATED)
Expand All @@ -64,7 +58,7 @@ class FlowWithLifecycleTest {
}

@Test
fun testFlowDoesNotCollectIfLifecycleIsDestroyed() = runBlocking(Dispatchers.Main) {
fun testFlowDoesNotCollectIfLifecycleIsDestroyed() = runLifecycleTest {
owner.setState(Lifecycle.State.CREATED)
owner.setState(Lifecycle.State.DESTROYED)
val result = flowOf(1, 2, 3)
Expand All @@ -75,7 +69,7 @@ class FlowWithLifecycleTest {
}

@Test
fun testCollectionRestartsWithFlowThatCompletes() = runBlocking(Dispatchers.Main) {
fun testCollectionRestartsWithFlowThatCompletes() = runLifecycleTest {
assertFlowCollectsAgainOnRestart(
flowOf(1, 2),
expectedItemsBeforeRestarting = listOf(1, 2),
Expand All @@ -84,7 +78,7 @@ class FlowWithLifecycleTest {
}

@Test
fun testCollectionRestartsWithFlowThatDoesNotComplete() = runBlocking(Dispatchers.Main) {
fun testCollectionRestartsWithFlowThatDoesNotComplete() = runLifecycleTest {
assertFlowCollectsAgainOnRestart(
flow {
emit(1)
Expand All @@ -97,7 +91,7 @@ class FlowWithLifecycleTest {
}

@Test
fun testCollectionRestartsWithAHotFlow() = runBlocking(Dispatchers.Main) {
fun testCollectionRestartsWithAHotFlow() = runLifecycleTest {
val sharedFlow = MutableSharedFlow<Int>()
assertFlowCollectsAgainOnRestart(
sharedFlow,
Expand All @@ -113,7 +107,7 @@ class FlowWithLifecycleTest {
}

@Test
fun testCancellingCoroutineDoesNotGetUpdates() = runBlocking(Dispatchers.Main) {
fun testCancellingCoroutineDoesNotGetUpdates() = runLifecycleTest {
owner.setState(Lifecycle.State.STARTED)
val sharedFlow = MutableSharedFlow<Int>()
val resultList = mutableListOf<Int>()
Expand All @@ -138,7 +132,7 @@ class FlowWithLifecycleTest {
}

@Test
fun testDestroyedLifecycleDoesNotGetUpdates() = runBlocking(Dispatchers.Main) {
fun testDestroyedLifecycleDoesNotGetUpdates() = runLifecycleTest {
owner.setState(Lifecycle.State.STARTED)
val sharedFlow = MutableSharedFlow<Int>()
val resultList = mutableListOf<Int>()
Expand All @@ -161,7 +155,7 @@ class FlowWithLifecycleTest {
}

@Test
fun testWithLaunchIn() = runBlocking(Dispatchers.Main) {
fun testWithLaunchIn() = runLifecycleTest {
owner.setState(Lifecycle.State.STARTED)
val resultList = mutableListOf<Int>()
flowOf(1, 2, 3)
Expand All @@ -174,7 +168,7 @@ class FlowWithLifecycleTest {
}

@Test
fun testOnEachBeforeOperatorOnlyExecutesInTheRightState() = runBlocking(Dispatchers.Main) {
fun testOnEachBeforeOperatorOnlyExecutesInTheRightState() = runLifecycleTest {
owner.setState(Lifecycle.State.RESUMED)
val sharedFlow = MutableSharedFlow<Int>()
val resultList = mutableListOf<Int>()
Expand Down Expand Up @@ -207,7 +201,7 @@ class FlowWithLifecycleTest {
}

@Test
fun testExtensionFailsWithInitializedState() = runBlocking(Dispatchers.Main) {
fun testExtensionFailsWithInitializedState() = runLifecycleTest {
try {
flowOf(1, 2, 3)
.flowWithLifecycle(owner.lifecycle, Lifecycle.State.INITIALIZED)
Expand All @@ -220,7 +214,7 @@ class FlowWithLifecycleTest {
}

@Test
fun testExtensionDoesNotCollectInDestroyedState() = runBlocking(Dispatchers.Main) {
fun testExtensionDoesNotCollectInDestroyedState() = runLifecycleTest {
owner.setState(Lifecycle.State.STARTED)
val resultList = mutableListOf<Int>()
launch(Dispatchers.Main.immediate) {
Expand Down
Loading
Loading