diff --git a/app/src/androidTest/kotlin/io/github/dewfallapp/SearchThenPlayTest.kt b/app/src/androidTest/kotlin/io/github/dewfallapp/SearchThenPlayTest.kt index ae83e7f..34236cf 100644 --- a/app/src/androidTest/kotlin/io/github/dewfallapp/SearchThenPlayTest.kt +++ b/app/src/androidTest/kotlin/io/github/dewfallapp/SearchThenPlayTest.kt @@ -17,6 +17,7 @@ import io.github.dewfallapp.core.playback.PlaybackConnection import io.github.dewfallapp.fake.AssetMedia import io.github.dewfallapp.fake.TestVideo import javax.inject.Inject +import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals @@ -75,6 +76,12 @@ class SearchThenPlayTest { hilt.inject() } + /** So the next test starts the service with its own objects. */ + @AfterTest + fun stop() { + compose.stopPlayback(playback) + } + @Test fun searchThenPlay() { // Search YouTube has one text field. diff --git a/app/src/androidTest/kotlin/io/github/dewfallapp/StopPlayback.kt b/app/src/androidTest/kotlin/io/github/dewfallapp/StopPlayback.kt new file mode 100644 index 0000000..606a002 --- /dev/null +++ b/app/src/androidTest/kotlin/io/github/dewfallapp/StopPlayback.kt @@ -0,0 +1,30 @@ +package io.github.dewfallapp + +import android.content.Intent +import androidx.compose.ui.test.junit4.AndroidComposeTestRule +import androidx.test.platform.app.InstrumentationRegistry +import io.github.dewfallapp.core.playback.PlaybackConnection +import io.github.dewfallapp.core.playback.PlaybackService + +/** How long a test waits for PlaybackService to end after it stops it. */ +private const val STOP_TIMEOUT_MS = 10_000L + +/** + * Ends PlaybackService at the end of a test. The emulator tests share one process, and Hilt makes + * new objects for each test, but a service that still runs keeps the objects of the test that + * started it. The next test's PlaybackConnection would then wait for a session that its own objects + * never get. So this stops the player and the service, and waits until [playback] has lost its + * player, which happens when the service releases its session in onDestroy. See + * docs/testing.md#emulator-tests. + */ +internal fun AndroidComposeTestRule<*, *>.stopPlayback(playback: PlaybackConnection) { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val connected = runOnUiThread { + val player = playback.player.value + player?.stop() + player?.clearMediaItems() + context.stopService(Intent(context, PlaybackService::class.java)) + player != null + } + if (connected) waitUntil(STOP_TIMEOUT_MS) { runOnUiThread { playback.player.value == null } } +} diff --git a/app/src/androidTest/kotlin/io/github/dewfallapp/TryAgainOfflineTest.kt b/app/src/androidTest/kotlin/io/github/dewfallapp/TryAgainOfflineTest.kt new file mode 100644 index 0000000..8e9d0fc --- /dev/null +++ b/app/src/androidTest/kotlin/io/github/dewfallapp/TryAgainOfflineTest.kt @@ -0,0 +1,143 @@ +package io.github.dewfallapp + +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performImeAction +import androidx.compose.ui.test.performTextInput +import androidx.media3.common.Player +import androidx.test.espresso.Espresso +import androidx.test.ext.junit.runners.AndroidJUnit4 +import dagger.hilt.android.testing.HiltAndroidRule +import dagger.hilt.android.testing.HiltAndroidTest +import io.github.dewfallapp.core.model.PlaybackFailure +import io.github.dewfallapp.core.model.VideoId +import io.github.dewfallapp.core.playback.PlaybackConnection +import io.github.dewfallapp.fake.FakeNetwork +import io.github.dewfallapp.fake.TestVideo +import io.github.dewfallapp.feature.player.ui.R as PlayerR +import javax.inject.Inject +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import org.junit.Rule +import org.junit.runner.RunWith + +/** How long the test waits for a screen to show what it expects. */ +private const val SCREEN_TIMEOUT_MS = 10_000L + +/** + * How long the test waits for the player: the service's start and ExoPlayer's retries of a failed + * load, with their growing delays, or the links and the first frames, on a cold emulator that draws + * in software. + */ +private const val PLAYER_TIMEOUT_MS = 60_000L + +/** How far the video must have played, well past its start and short of its 30 seconds. */ +private const val PLAYED_MS = 3_000L + +/** + * A video opened with the network off plays after the one "Try again", even when the player still + * held an earlier video's error, as #212 found with a live stream in the mini player. The first + * video's files fail, so the player holds a network error, and the mini player shows it. Then the + * second video opens with the network off. Its details and its links fail, and the screen says so + * once, because both failed the same way. With the network back, its one "Try again" retries both, + * as openspec/specs/player/spec.md's "Details and playback both fail" scenario says. See + * docs/testing.md#emulator-tests. + */ +@HiltAndroidTest +@RunWith(AndroidJUnit4::class) +class TryAgainOfflineTest { + @get:Rule(order = 0) val hilt = HiltAndroidRule(this) + + /** An UnconfinedTestDispatcher, for the reason that SearchThenPlayTest gives. */ + // UnconfinedTestDispatcher is still marked experimental. + @OptIn(ExperimentalCoroutinesApi::class) + @get:Rule(order = 1) + val compose = createAndroidComposeRule(UnconfinedTestDispatcher()) + + @Inject lateinit var playback: PlaybackConnection + + @Inject lateinit var network: FakeNetwork + + @BeforeTest + fun inject() { + hilt.inject() + } + + /** So the next test starts the service with its own objects. */ + @AfterTest + fun stop() { + compose.stopPlayback(playback) + } + + @Test + fun tryAgainRetriesBothAfterAnEarlierPlayerError() { + val unreachable = compose.activity.getString(PlayerR.string.player_failed_network) + val tryAgain = compose.activity.getString(PlayerR.string.player_try_again) + + // The first video's details and links load, and its files fail. + network.mediaReachable = false + compose.onNode(hasSetTextAction()).performTextInput(TestVideo.QUERY) + compose.onNode(hasSetTextAction()).performImeAction() + waitForNode(hasText(TestVideo.TITLE)) + compose.onNodeWithText(TestVideo.TITLE).performClick() + waitForNode(hasText(TestVideo.DESCRIPTION)) + compose.waitUntil(PLAYER_TIMEOUT_MS) { playback.failure.value == PlaybackFailure.NETWORK } + + // The back gesture minimizes it. It stays the player's item, with its error. + Espresso.pressBack() + waitForNode(hasText(TestVideo.OTHER_TITLE)) + + // The second video opens with the network off. + network.setReachable(false) + compose.onNodeWithText(TestVideo.OTHER_TITLE).performClick() + waitForNode(hasText(unreachable)) + // The player is ended with no item only once the session's prepare has run on the empty + // player that the failed links left. Before #212's fix, that prepare cleared the earlier + // error and with it the second video's failure. + compose.waitUntil(PLAYER_TIMEOUT_MS) { + compose.runOnUiThread { + val player = playback.player.value + player != null && + player.currentMediaItem == null && + player.playbackState == Player.STATE_ENDED + } + } + assertEquals(PlaybackFailure.NETWORK, playback.failure.value) + + // The screen says it once, so there is one "Try again", which retries both. + network.setReachable(true) + compose.onNodeWithText(tryAgain).performClick() + waitForNode(hasText(TestVideo.DESCRIPTION)) + compose.waitUntil(PLAYER_TIMEOUT_MS) { compose.runOnUiThread { playsOtherPast(PLAYED_MS) } } + } + + /** + * Waits until a node matches [matcher], for up to [SCREEN_TIMEOUT_MS]. Compose's own + * waitUntilAtLeastOneExists does the same, but is still an experimental API. + */ + private fun waitForNode(matcher: SemanticsMatcher) { + compose.waitUntil(SCREEN_TIMEOUT_MS) { + compose.onAllNodes(matcher).fetchSemanticsNodes().isNotEmpty() + } + } + + /** + * Whether the player plays the second video past [positionMs]. Call it on the main thread, as + * Media3's Player asks. + */ + private fun playsOtherPast(positionMs: Long): Boolean { + val player = playback.player.value ?: return false + val videoId: VideoId? = player.currentMediaItem?.mediaId?.let(playback::videoOf) + return videoId == TestVideo.otherId && + player.isPlaying && + player.currentPosition >= positionMs + } +} diff --git a/app/src/androidTest/kotlin/io/github/dewfallapp/fake/AssetMedia.kt b/app/src/androidTest/kotlin/io/github/dewfallapp/fake/AssetMedia.kt index 6ead4ca..dbed30c 100644 --- a/app/src/androidTest/kotlin/io/github/dewfallapp/fake/AssetMedia.kt +++ b/app/src/androidTest/kotlin/io/github/dewfallapp/fake/AssetMedia.kt @@ -32,10 +32,11 @@ private val singleRange = Regex("""bytes=(\d+)-(\d*)""") * of the input when it starts at the end. * * Its [calls] never reach the network: the interceptor answers every request itself and never calls - * `chain.proceed`, and any other link fails with an IOException. It counts the requests for each - * file, so a test can check that the player read both. + * `chain.proceed`, and any other link fails with an IOException, as does every request while + * [network] has the media off. It counts the requests for each file that it answers, so a test can + * check that the player read both. */ -class AssetMedia(private val assets: AssetManager) { +class AssetMedia(private val assets: AssetManager, private val network: FakeNetwork) { private val files = mapOf( TestVideo.VIDEO_URL to TestVideo.VIDEO_ASSET, @@ -66,6 +67,7 @@ class AssetMedia(private val assets: AssetManager) { private fun answer(chain: Interceptor.Chain): Response { val request = chain.request() + if (!network.mediaReachable) throw IOException("The fake network is off") val url = request.url.toString() val bytes = bytes(url) requests.getOrPut(url) { AtomicInteger() }.incrementAndGet() diff --git a/app/src/androidTest/kotlin/io/github/dewfallapp/fake/FakeNetwork.kt b/app/src/androidTest/kotlin/io/github/dewfallapp/fake/FakeNetwork.kt new file mode 100644 index 0000000..6509a3c --- /dev/null +++ b/app/src/androidTest/kotlin/io/github/dewfallapp/fake/FakeNetwork.kt @@ -0,0 +1,20 @@ +package io.github.dewfallapp.fake + +/** + * Stands in for the network in the emulator tests. While [youTubeReachable] is off, the fake + * YouTube layer answers the details and the stream links with NETWORK, as the real layer does with + * the network off. While [mediaReachable] is off, AssetMedia fails every request with an + * IOException, which Media3 reports as a network error. Both start on, so a test that never touches + * them runs as with a network. Hilt makes one for each test. See docs/testing.md#the-fakes. + */ +class FakeNetwork { + @Volatile var youTubeReachable: Boolean = true + + @Volatile var mediaReachable: Boolean = true + + /** Turns both off, or both on. */ + fun setReachable(reachable: Boolean) { + youTubeReachable = reachable + mediaReachable = reachable + } +} diff --git a/app/src/androidTest/kotlin/io/github/dewfallapp/fake/FakeYouTubeModule.kt b/app/src/androidTest/kotlin/io/github/dewfallapp/fake/FakeYouTubeModule.kt index e3f2902..7597a21 100644 --- a/app/src/androidTest/kotlin/io/github/dewfallapp/fake/FakeYouTubeModule.kt +++ b/app/src/androidTest/kotlin/io/github/dewfallapp/fake/FakeYouTubeModule.kt @@ -23,9 +23,10 @@ import javax.inject.Singleton import okhttp3.Call /** - * Replaces the YouTube layer in every emulator test with fakes that know only [TestVideo], and the - * player's media clients with [AssetMedia]. Nothing builds NewPipeYouTube, so no request reaches - * YouTube or googlevideo.com. The repositories in `:core:data` are the real ones. See + * Replaces the YouTube layer in every emulator test with fakes that know only [TestVideo]'s two + * videos, and the player's media clients with [AssetMedia]. Nothing builds NewPipeYouTube, so no + * request reaches YouTube or googlevideo.com. The repositories in `:core:data` are the real ones. + * While [FakeNetwork] has YouTube off, the details and the stream links answer NETWORK. See * docs/testing.md#emulator-tests. */ @Module @@ -33,27 +34,41 @@ import okhttp3.Call object FakeYouTubeModule { @Provides fun provideSearch(): SearchRemoteDataSource = SearchRemoteDataSource { query -> - val videos = if (query == TestVideo.QUERY) listOf(TestVideo.summary) else emptyList() + val videos = + if (query == TestVideo.QUERY) { + listOf(TestVideo.summary, TestVideo.otherSummary) + } else { + emptyList() + } YouTubeResult.Success(SearchResults(channels = emptyList(), videos = videos)) } @Provides - fun provideVideoDetails(): VideoDetailsRemoteDataSource = VideoDetailsRemoteDataSource { id -> - if (id == TestVideo.id) YouTubeResult.Success(TestVideo.details) else unavailable - } + fun provideVideoDetails(network: FakeNetwork): VideoDetailsRemoteDataSource = + VideoDetailsRemoteDataSource { id -> + when { + !network.youTubeReachable -> unreachable + id == TestVideo.id -> YouTubeResult.Success(TestVideo.details) + id == TestVideo.otherId -> YouTubeResult.Success(TestVideo.otherDetails) + else -> unavailable + } + } @Provides - fun provideStreamLinks(media: AssetMedia): StreamLinksRemoteDataSource = + fun provideStreamLinks(network: FakeNetwork, media: AssetMedia): StreamLinksRemoteDataSource = StreamLinksRemoteDataSource { id -> - if (id == TestVideo.id) { - YouTubeResult.Success( - TestVideo.streamLinks( - videoLength = media.length(TestVideo.VIDEO_URL), - audioLength = media.length(TestVideo.AUDIO_URL), - ), - ) - } else { - unavailable + when { + !network.youTubeReachable -> unreachable + id == TestVideo.id || id == TestVideo.otherId -> { + YouTubeResult.Success( + TestVideo.streamLinks( + videoId = id, + videoLength = media.length(TestVideo.VIDEO_URL), + audioLength = media.length(TestVideo.AUDIO_URL), + ), + ) + } + else -> unavailable } } @@ -76,11 +91,14 @@ object FakeYouTubeModule { ): YouTubeResult> = unavailable } + /** One for the whole test, so the test can turn it off and on. */ + @Provides @Singleton fun provideFakeNetwork(): FakeNetwork = FakeNetwork() + /** One for the whole test, so the test can read its request counts. */ @Provides @Singleton - fun provideAssetMedia(): AssetMedia = - AssetMedia(InstrumentationRegistry.getInstrumentation().context.assets) + fun provideAssetMedia(network: FakeNetwork): AssetMedia = + AssetMedia(InstrumentationRegistry.getInstrumentation().context.assets, network) @Provides @ProgressiveMediaCalls @@ -92,4 +110,6 @@ object FakeYouTubeModule { fun provideLiveMediaCalls(media: AssetMedia): Call.Factory = media.calls private val unavailable = YouTubeResult.Failure(YouTubeError.UNAVAILABLE) + + private val unreachable = YouTubeResult.Failure(YouTubeError.NETWORK) } diff --git a/app/src/androidTest/kotlin/io/github/dewfallapp/fake/TestVideo.kt b/app/src/androidTest/kotlin/io/github/dewfallapp/fake/TestVideo.kt index a34ac1f..f335199 100644 --- a/app/src/androidTest/kotlin/io/github/dewfallapp/fake/TestVideo.kt +++ b/app/src/androidTest/kotlin/io/github/dewfallapp/fake/TestVideo.kt @@ -13,9 +13,9 @@ import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.seconds /** - * The one video that the fake YouTube layer knows. Everything here is made up for the emulator - * tests, and its files are the test pattern and the tone in the test APK's assets. See - * docs/testing.md#emulator-tests. + * The video that the fake YouTube layer knows, and a second one with the same files, [otherId]. + * Everything here is made up for the emulator tests, and the files are the test pattern and the + * tone in the test APK's assets. See docs/testing.md#emulator-tests. */ object TestVideo { /** What the test types into the search field. Any other search finds nothing. */ @@ -46,6 +46,13 @@ object TestVideo { val id = VideoId("dewfallTest") val channelId = ChannelId("UCdewfallTestChannel0000") + /** + * The second video, which the same search finds, so a test can open it while the first one is + * the player's item, in the mini player. + */ + const val OTHER_TITLE = "Dewfall second test pattern" + val otherId = VideoId("dewfallTes2") + private val length = 30.seconds val summary: VideoSummary @@ -76,13 +83,20 @@ object TestVideo { isLive = false, ) + val otherSummary: VideoSummary + get() = summary.copy(id = otherId, title = OTHER_TITLE) + + val otherDetails: VideoDetails + get() = details.copy(id = otherId, title = OTHER_TITLE) + /** * A video-only and an audio-only format, as most YouTube videos have, so the player merges two - * files, as it does for real videos. [videoLength] and [audioLength] are the files' sizes. + * files, as it does for real videos. [videoLength] and [audioLength] are the files' sizes, and + * [videoId] is [id] or [otherId]. */ - fun streamLinks(videoLength: Long, audioLength: Long): StreamLinks = + fun streamLinks(videoId: VideoId, videoLength: Long, audioLength: Long): StreamLinks = StreamLinks( - videoId = id, + videoId = videoId, audioFormats = listOf( AudioFormat( diff --git a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackErrors.kt b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackErrors.kt index 07907a8..e425e60 100644 --- a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackErrors.kt +++ b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackErrors.kt @@ -83,6 +83,16 @@ internal fun httpStatusOf(error: Throwable): Int? = internal fun refusedInChain(error: Throwable): Boolean = causeChain(error).any { it is MediaRequestRefused } +/** + * Whether the player's error going away, [errorGone], clears the session's failure: only while the + * player [hasItem], which plays again, such as after play in the notification. ExoPlayer clears an + * error only in prepare. A video whose links failed leaves the player empty, and the session's + * prepare then clears the error of the item before it, such as a live stream that failed in the + * mini player meanwhile. That error isn't the empty player's, so the failure that the links + * reported stays, and the screen's one "Try again" retries both, as #212 found. + */ +internal fun clearsFailure(errorGone: Boolean, hasItem: Boolean): Boolean = errorGone && hasItem + /** The error that the media session sees in place of the player's own. */ internal data class CleanedError(val message: String, val errorCode: Int) diff --git a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackService.kt b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackService.kt index 00c1d96..7afed4f 100644 --- a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackService.kt +++ b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackService.kt @@ -252,9 +252,14 @@ class PlaybackService : MediaSessionService() { limitLiveVariants(tracks) } - /** A player that plays again, such as after play in the notification, has no failure. */ + /** + * A player that plays again, such as after play in the notification, has no failure. An + * empty player keeps it, as [clearsFailure] says. + */ override fun onPlayerErrorChanged(error: PlaybackException?) { - if (error == null) sessions.clearFailure() + if (clearsFailure(error == null, player.currentMediaItem != null)) { + sessions.clearFailure() + } } override fun onPlayerError(error: PlaybackException) { diff --git a/core/playback/src/test/kotlin/io/github/dewfallapp/core/playback/PlaybackErrorsTest.kt b/core/playback/src/test/kotlin/io/github/dewfallapp/core/playback/PlaybackErrorsTest.kt index f118bc9..636c443 100644 --- a/core/playback/src/test/kotlin/io/github/dewfallapp/core/playback/PlaybackErrorsTest.kt +++ b/core/playback/src/test/kotlin/io/github/dewfallapp/core/playback/PlaybackErrorsTest.kt @@ -31,6 +31,16 @@ class PlaybackErrorsTest { ) } + @Test + fun `an error that goes clears the failure only while the player has an item`() { + // Play after a failure prepares the same item again. + assertTrue(clearsFailure(errorGone = true, hasItem = true)) + // #212: the prepare after failed links clears the earlier item's error on an empty player. + assertFalse(clearsFailure(errorGone = true, hasItem = false)) + assertFalse(clearsFailure(errorGone = false, hasItem = true)) + assertFalse(clearsFailure(errorGone = false, hasItem = false)) + } + @Test fun `the cause-chain walk ends on a loop`() { val first = IOException() diff --git a/docs/architecture.md b/docs/architecture.md index c691366..5b244be 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -869,7 +869,7 @@ The playback commands are play and pause, prepare, stop, seeking within the item - **The picture.** MainActivity calls `PlaybackConnection.appStarted()` in `onStart`, and `appStopped(isChangingConfigurations)` in `onStop`. A video screen holds the picture with `holdPicture()` while its ViewModel exists, so a configuration change, such as turning to landscape for fullscreen, never lets go of it. PlaybackSessions keeps whether the app can be seen and how many holds there are, and PlaybackService turns the video track off while the app can't be seen or nothing holds the picture, as while a video is minimized, building on its track selection parameters, so a live stream's variant override stays. So it decodes no picture, and a ProgressiveMediaPeriod with no selected track cancels its loading ([ProgressiveMediaPeriod at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/ProgressiveMediaPeriod.java)), so a video-only file isn't fetched. A combined format, and a live stream's HLS segments, which carry both, keep loading. For a live stream, HLS keeps its last variant selection, which the override limited ([HlsSampleStreamWrapper at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/exoplayer_hls/src/main/java/androidx/media3/exoplayer/hls/HlsSampleStreamWrapper.java)). Coming back to the video screen loads the video file from the current position, so the sound may pause for a moment. The maintainer chose to turn the picture off while minimized on November 21, 2026, because it saves the data of a video-only file. - **Leaving the app.** A video that has played keeps playing in the background. `appStopped` acts on the pure function `leaveDecision`: a configuration change does nothing, and otherwise a start that still waits for the connection won't play, and the player pauses its item unless it is the playback ID that last played. The connection keeps that ID from a listener on its controller. A video that hasn't played would start its foreground service from the background, which Android refuses, so it waits, paused, on the video screen or in the mini player. -- **Failures.** A playback that failed keeps its notification, and its play button prepares the player again from the same position. When the service reports a failure, it turns play off. On Android 10 to 12, Media3's notification shows a play button for a failed player, because it is idle ([Util.shouldShowPlayButton at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/common/src/main/java/androidx/media3/common/util/Util.java)), but the button sends the play and pause toggle key ([PlaybackPendingIntentBuilder at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/session/src/main/java/androidx/media3/session/PlaybackPendingIntentBuilder.java)), and Media3 pauses a player whose play is on ([MediaSessionImpl at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/session/src/main/java/androidx/media3/session/MediaSessionImpl.java), `applyMediaButtonKeyEvent`). A failure leaves play on, so the first tap did nothing until the service turned it off, as hand checks on Android 10 and 12L showed on November 21, 2026. PlaybackService clears the failure in `onPlayerErrorChanged(null)`, so the video screen shows no old failure over a video that plays again. +- **Failures.** A playback that failed keeps its notification, and its play button prepares the player again from the same position. When the service reports a failure, it turns play off. On Android 10 to 12, Media3's notification shows a play button for a failed player, because it is idle ([Util.shouldShowPlayButton at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/common/src/main/java/androidx/media3/common/util/Util.java)), but the button sends the play and pause toggle key ([PlaybackPendingIntentBuilder at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/session/src/main/java/androidx/media3/session/PlaybackPendingIntentBuilder.java)), and Media3 pauses a player whose play is on ([MediaSessionImpl at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/session/src/main/java/androidx/media3/session/MediaSessionImpl.java), `applyMediaButtonKeyEvent`). A failure leaves play on, so the first tap did nothing until the service turned it off, as hand checks on Android 10 and 12L showed on November 21, 2026. PlaybackService clears the failure in `onPlayerErrorChanged(null)`, so the video screen shows no old failure over a video that plays again. It clears it only while the player has an item. ExoPlayer clears an error only in `prepare()` ([ExoPlayerImpl at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/ExoPlayerImpl.java)). A video whose links failed leaves the player empty, and the session's prepare then clears the error of the item before it, such as a live stream that failed in the mini player while the links loaded. Clearing the failure then would erase the one that the links reported, and the video screen's one "Try again" would retry only the details, as #212 found. - **The end.** When a video ends, the service turns play off too. Media3 shows a play button for an ended player too ([Util.shouldShowPlayButton at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/common/src/main/java/androidx/media3/common/util/Util.java)), and a headset's play and pause button sends the same toggle as the notification's on every Android version, which Media3 turns into a pause while play is on ([MediaSessionImpl at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/session/src/main/java/androidx/media3/session/MediaSessionImpl.java), `applyMediaButtonKeyEvent`). With play off, one press plays the video again from the start, as a hand check on Android 10 showed on November 21, 2026. So after the end, seeking back on the video screen leaves the video paused there until the user presses play. ### Opaque playback IDs diff --git a/docs/testing.md b/docs/testing.md index a59f77d..de5ea69 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -540,7 +540,7 @@ Record the sets again: ## Emulator tests -Emulator tests are the [slow tests](#slow-tests). They run the app on an emulator or a phone, and live in app/src/androidTest/. Today there is one, SearchThenPlayTest (#46). +Emulator tests are the [slow tests](#slow-tests). They run the app on an emulator or a phone, and live in app/src/androidTest/. Today there are two: SearchThenPlayTest (#46) and TryAgainOfflineTest (#212). ### What search then play checks @@ -562,12 +562,26 @@ It doesn't check: - the YouTube layer, which the [saved responses](#saved-youtube-responses), the [daily check](#the-daily-youtube-check) and the [debug screen](#checking-the-youtube-layer-on-a-phone) cover; - background play, the notification and media buttons, which [Checking the player by hand](#checking-the-player-by-hand) covers. +### What try again offline checks + +TryAgainOfflineTest checks #212's bug: a video opened with the network off stayed stopped after "Try again" when the player still held an earlier video's error. It goes like this: + +1. With FakeNetwork's media off, it opens the first test video. The details and the links load, the files fail, and the test waits until PlaybackConnection reports a NETWORK failure. +2. The back gesture minimizes it, so it stays the player's item, with its error, in the mini player. +3. With FakeNetwork all off, it opens the second test video. Its details and its links fail. The test waits until the player is ended with no item, which it is only once the session's prepare has run on the empty player that the failed links left, and then checks that the failure is still NETWORK. Before the fix, that prepare cleared the earlier video's error, and PlaybackService then cleared the second video's failure too. +4. With FakeNetwork back on, it taps the one "Try again", and waits until the second video plays past 3 seconds. + +Both tests end with `stopPlayback`, which stops the player and PlaybackService and waits until the connection has lost its player. The tests share one process, and Hilt makes new objects for each test, but a service that still runs keeps the objects of the test that started it, so the next test's connection would wait for a session that never comes. On November 22, 2026, TryAgainOfflineTest timed out that way whenever it ran after SearchThenPlayTest. + +It finds "Try again" and the network message by their text from `:feature:player-ui`'s resources. The details and the playback both failed with NETWORK, so the screen shows one "Try again", and the test's tap would fail if there were two. The waits for the player take up to 60 seconds, because ExoPlayer retries a failed load a few times, with growing delays, before it reports the error. + ### The fakes -- **FakeYouTubeModule** replaces YouTubeModule in every emulator test, through Hilt's `@TestInstallIn` ([Hilt testing guide](https://developer.android.com/training/dependency-injection/hilt-testing)). It binds the YouTube layer's five interfaces to fakes that know one made-up video, TestVideo, and the player's two media clients to AssetMedia. Nothing builds NewPipeYouTube, so the tests send nothing to YouTube or googlevideo.com, locally or in CI. The repositories in `:core:data` are the real ones, as in [Fast tests](#fast-tests)' "repositories with fake data sources". +- **FakeYouTubeModule** replaces YouTubeModule in every emulator test, through Hilt's `@TestInstallIn` ([Hilt testing guide](https://developer.android.com/training/dependency-injection/hilt-testing)). It binds the YouTube layer's five interfaces to fakes that know TestVideo's two made-up videos, and the player's two media clients to AssetMedia. Nothing builds NewPipeYouTube, so the tests send nothing to YouTube or googlevideo.com, locally or in CI. The repositories in `:core:data` are the real ones, as in [Fast tests](#fast-tests)' "repositories with fake data sources". - **YouTubeModule is public** for this, because `@TestInstallIn` names the module that it replaces, and Kotlin's `internal` would hide it from `:app`'s tests. `:app`'s androidTest depends on `:core:youtube` for the five interfaces only. NewPipeExtractor stays off its compile classpath. -- **AssetMedia** answers the player's requests from the test APK's assets, as a real server does: 200 with the whole file for a request with no Range header, 206 with the bytes that a Range header asks for, and 416 for a range that starts at or past the end. Its OkHttp interceptor answers every request itself and never calls `chain.proceed`, and any other link fails with an IOException. TestVideo's links use the reserved .invalid domain, which never resolves ([RFC 2606](https://www.rfc-editor.org/rfc/rfc2606#section-2)). It counts the requests for each file, so the test checks that the player read both. -- **TestVideo** has a video-only and an audio-only format, as most YouTube videos do, so the player merges two files, as it does for real videos. +- **AssetMedia** answers the player's requests from the test APK's assets, as a real server does: 200 with the whole file for a request with no Range header, 206 with the bytes that a Range header asks for, and 416 for a range that starts at or past the end. Its OkHttp interceptor answers every request itself and never calls `chain.proceed`, and any other link fails with an IOException. TestVideo's links use the reserved .invalid domain, which never resolves ([RFC 2606](https://www.rfc-editor.org/rfc/rfc2606#section-2)). It counts the requests for each file, so SearchThenPlayTest checks that the player read both. +- **FakeNetwork** stands in for the network, one for each test. While its YouTube switch is off, the fake details and stream links answer NETWORK. While its media switch is off, AssetMedia fails every request with an IOException, which Media3 reports as a network error, errorCode 2001. Both start on, so SearchThenPlayTest runs as with a network. +- **TestVideo** has a video-only and an audio-only format, as most YouTube videos do, so the player merges two files, as it does for real videos. Its second video, with its own ID and title, uses the same files, so a test can open one video while the other is in the mini player. The same search finds both. - **HiltTestRunner** starts HiltTestApplication in place of DewfallApplication, which has no code of its own. Once DewfallApplication gets some, such as WorkManager's Configuration.Provider, the tests need Hilt's `@CustomTestApplication` instead, or they run without that code. `:app`'s build names it as the test runner, and passes it `disableAnalytics=true`. AndroidX Test's runner has a usage tracker that sends to Google Analytics only when a test turns it on, and that argument keeps it off. ### The media files