Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
30 changes: 30 additions & 0 deletions app/src/androidTest/kotlin/io/github/dewfallapp/StopPlayback.kt
Original file line number Diff line number Diff line change
@@ -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 } }
}
143 changes: 143 additions & 0 deletions app/src/androidTest/kotlin/io/github/dewfallapp/TryAgainOfflineTest.kt
Original file line number Diff line number Diff line change
@@ -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<MainActivity>(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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
@@ -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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,37 +23,52 @@ 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
@TestInstallIn(components = [SingletonComponent::class], replaces = [YouTubeModule::class])
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
}
}

Expand All @@ -76,11 +91,14 @@ object FakeYouTubeModule {
): YouTubeResult<List<SubtitleLine>> = 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
Expand All @@ -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)
}
26 changes: 20 additions & 6 deletions app/src/androidTest/kotlin/io/github/dewfallapp/fake/TestVideo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
Loading