Skip to content

Native Android client for Spotify, built with Jetpack Compose

Characterization tests before the player is refactored: of two songs picked during the same ad only the last is played after it, once; a reload ends on the new page's ready, not on the old page's last one; a pause during an ad is not undone when the ad is over (and a song the ad left paused with nobody pausing still is resumed); the queue sync never removes a song another device queued; and a late state of a song the mirror sent is sent again, not followed as a remote skip [skip ci]

kota-zoa8adf93dfc21
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyPlayerCharacterizationTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyPlayerCharacterizationTest.kt
new file mode 100644
index 00000000..8e908e5a
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyPlayerCharacterizationTest.kt
@@ -0,0 +1,152 @@
+package app.myspoti.spotify
+
+import app.myspoti.spotify.bridge.AdBlock
+import app.myspoti.spotify.bridge.Bridge
+import app.myspoti.spotify.bridge.BridgeHost
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import org.junit.jupiter.api.AfterEach
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.BeforeEach
+import org.junit.jupiter.api.Test
+import java.util.concurrent.CopyOnWriteArrayList
+
+/**
+ * What the player does today around ads, picks and reloads, pinned down before any refactoring:
+ * the last of two picks made during an ad is the one played after it, a reload ends on the new
+ * page's "ready" only, and a pause made during an ad is not undone when the ad is over.
+ */
+class SpotifyPlayerCharacterizationTest {
+ private class FakeHost : BridgeHost {
+ override val messages = MutableSharedFlow<String>(extraBufferCapacity = 64)
+ /** Every call the player made: method, its arguments (json text) and when it was sent. */
+ val calls = CopyOnWriteArrayList<Triple<String, String, Long>>()
+ override suspend fun evaluate(script: String) {
+ val m = Regex("""Myspoti\.call\((\d+), "([^"]+)", (.*)\)\.catch""", RegexOption.DOT_MATCHES_ALL).find(script) ?: return
+ calls += Triple(m.groupValues[2], m.groupValues[3], System.currentTimeMillis())
+ messages.emit("""{"type":"result","id":${m.groupValues[1]},"ok":true,"value":null}""")
+ }
+ suspend fun post(json: String) = messages.emit(json)
+ }
+
+ private lateinit var scope: CoroutineScope
+ private lateinit var host: FakeHost
+ private lateinit var bridge: Bridge
+ private lateinit var player: SpotifyPlayer
+
+ @BeforeEach fun up() {
+ AdBlock.ahead.value = null
+ scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ host = FakeHost()
+ bridge = Bridge(host, scope)
+ player = SpotifyPlayer(bridge, scope)
+ // A message posted before the bridge listens is lost (a slow CI machine): wait for it.
+ waitFor("bridge listening") { host.messages.subscriptionCount.value > 0 }
+ }
+
+ @AfterEach fun down() {
+ AdBlock.ahead.value = null
+ scope.cancel()
+ }
+
+ private fun track(name: String) =
+ """{"kind":"track","uri":"spotify:track:$name","uid":"u$name","name":"$name","durationMs":200000}"""
+
+ private fun state(item: String, next: String? = null, paused: Boolean = false) =
+ """{"type":"state","state":{"track":$item,"contextUri":"spotify:playlist:C","next":${next ?: "null"},"isPaused":$paused,
+ |"isBuffering":false,"positionMs":0,"timestamp":${System.currentTimeMillis()},"restrictions":{}}}""".trimMargin()
+
+ private val ad = """{"kind":"ad","uri":"spotify:ad:1","name":"ad","durationMs":30000}"""
+
+ private fun waitFor(what: String, ms: Long = 10_000, cond: () -> Boolean) = runBlocking {
+ val end = System.currentTimeMillis() + ms
+ while (!cond()) {
+ check(System.currentTimeMillis() < end) { "timed out: $what" }
+ delay(20)
+ }
+ }
+
+ private fun sent(method: String) = host.calls.filter { it.first == method }
+
+ private suspend fun adBreak() {
+ host.post("""{"type":"ready"}""")
+ waitFor("page ready") { bridge.ready.value }
+ host.post(state(track("A"), track("B")))
+ waitFor("song state") { player.state.value?.item?.uri == "spotify:track:A" }
+ host.post(state(ad))
+ waitFor("ad flag") { player.adPlaying.value }
+ }
+
+ @Test fun `of two picks made during the same ad only the last is played after it, once`() = runBlocking {
+ adBreak()
+ player.play("spotify:playlist:C", trackUri = "spotify:track:P1")
+ player.play("spotify:playlist:C", trackUri = "spotify:track:P2", order = listOf("spotify:track:P2", "spotify:track:Q"))
+ assertTrue(sent("player.play").isEmpty(), "nothing sent during the ad: ${sent("player.play")}")
+ // The break ends on the old queue's next song: the held pick is asked for again. (Were the
+ // break to outlast the watcher's skip delay on a loaded machine, the recovery plays the held
+ // pick instead: one play of the last pick either way.)
+ host.post(state(track("B"), track("C2")))
+ waitFor("the held pick played") { sent("player.play").isNotEmpty() }
+ host.post(state(track("P2"), track("Q")))
+ delay(2_000)
+ val plays = sent("player.play").map { it.second }
+ assertEquals(1, plays.size, "one play after the ad: $plays")
+ assertTrue("spotify:track:P2" in plays.single() && "spotify:track:Q" in plays.single(), "the last pick, in its order: ${plays.single()}")
+ assertTrue(plays.none { "spotify:track:P1" in it }, "the first pick is never played: $plays")
+ }
+
+ @Test fun `a reload does not end on the old page's ready but on the new page's after it went away`() = runBlocking {
+ var goneAt = 0L
+ var newReadyAt = 0L
+ player.reloadHost = {
+ scope.launch {
+ // The old page goes on saying "ready" for a while after the reload was asked for.
+ delay(1_700)
+ host.post("""{"type":"ready"}""")
+ delay(1_500)
+ goneAt = System.currentTimeMillis()
+ bridge.pageGone()
+ delay(300)
+ newReadyAt = System.currentTimeMillis()
+ host.post("""{"type":"ready"}""")
+ }
+ }
+ host.post("""{"type":"ready"}""")
+ waitFor("old page ready") { bridge.ready.value }
+ assertTrue(player.reloadPage(), "the new page came")
+ val back = System.currentTimeMillis()
+ assertTrue(goneAt > 0, "returned before the old page went away")
+ assertTrue(newReadyAt in goneAt..back, "returned ${back - goneAt} ms after the old page went away, before the new page's ready")
+ assertTrue(bridge.ready.value)
+ }
+
+ @Test fun `a pause during an ad stays paused once the ad is over`() = runBlocking {
+ adBreak()
+ player.pause()
+ waitFor("pause sent") { sent("player.pause").isNotEmpty() }
+ val pausedAt = System.currentTimeMillis()
+ // The break ends before the watcher gets past it, on the next song left paused.
+ host.post(state(track("B"), paused = true))
+ waitFor("break over") { !player.adPlaying.value }
+ // Well past the settle delay after which a song left paused by the break is resumed.
+ delay(SpotifyPlayer.AD_END_SETTLE_MS + 2_500)
+ assertTrue(host.calls.none { it.first == "player.resume" && it.third >= pausedAt }, "resumed after the user's pause: ${host.calls.map { it.first }}")
+ assertTrue(host.calls.none { it.first == "player.play" }, "something played after the user's pause: ${sent("player.play")}")
+ assertEquals(true, player.state.value?.isPaused)
+ }
+
+ /** The other side of the test above: without the user's pause, a song the break left paused is resumed. */
+ @Test fun `a song left paused by an ad nobody paused is resumed after the settle delay`() = runBlocking {
+ adBreak()
+ host.post(state(track("B"), paused = true))
+ waitFor("break over") { !player.adPlaying.value }
+ waitFor("resume sent", ms = SpotifyPlayer.AD_END_SETTLE_MS + 8_000) { sent("player.resume").isNotEmpty() }
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/di/PlayerOrchestrationCharacterizationTest.kt b/base/app/src/test/java/com/music/spotui/di/PlayerOrchestrationCharacterizationTest.kt
new file mode 100644
index 00000000..676e2a2d
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/di/PlayerOrchestrationCharacterizationTest.kt
@@ -0,0 +1,56 @@
+package com.music.spotui.di
+
+import com.music.spotui.di.MirrorRules.Follow
+import com.music.spotui.di.MirrorRules.Local
+import com.music.spotui.di.MirrorRules.Want
+import com.music.spotui.di.MirrorRules.Web
+import com.music.spotui.di.QueueSyncRules.Insert
+import com.music.spotui.di.QueueSyncRules.Plan
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+/**
+ * What the queue sync and the Connect mirror decide today when another device or a late answer
+ * of the page is involved, pinned down before any refactoring.
+ */
+class PlayerOrchestrationCharacterizationTest {
+ private val a = "spotify:track:4uLU6hMCjMI75M1A2tKUQC"
+ private val b = "spotify:track:7ouMYWpwJ422jRcDASZB7P"
+ private val c = "spotify:track:0VjIjW4GlUZAMYd2vXMi3b"
+ private val d = "spotify:track:1301WleyT98MSxVHPZCA6M"
+ private val foreign = "spotify:track:3n3Ppam7vgaVa1iaRUc9Lp"
+
+ private fun owns(vararg uris: String) = uris.groupingBy { it }.eachCount()
+
+ @Test fun `the queue sync never removes a song another device queued`() {
+ // Spotify's queue: the sync's a and b, a song queued from another device between them.
+ val page = listOf(a, foreign, b)
+ // The local queue lost b and gained c: b goes, c is added, the other device's song stays.
+ val plan = QueueSyncRules.plan(listOf(a, c), page, owns(a, b))
+ assertEquals(Plan(listOf(2), listOf(Insert(listOf(c), null))), plan)
+ // The local queue cleared: only what the sync queued goes.
+ assertEquals(listOf(0, 2), QueueSyncRules.plan(emptyList(), page, owns(a, b)).remove)
+ // The other device queued a copy of a song the sync queued once: one copy is the sync's, one stays.
+ val twice = QueueSyncRules.plan(emptyList(), listOf(a, a), owns(a))
+ assertEquals(1, twice.remove.size)
+ }
+
+ @Test fun `a late state of a song the mirror sent is not taken for a remote skip`() {
+ // The mirror sent c, then b (fast skips); the local player is on b, whose previous song is c.
+ val local = Local(b, playing = true, positionMs = 3_000, durationMs = 200_000, nextUri = d, previousUri = c)
+ val want = Want(b, paused = false)
+ val late = Web(c, paused = false, positionMs = 6_000)
+ // Past the echo window, c landing late is the mirror's own answer: b is sent again, never
+ // followed as "Previous" (the local player's neighbour) or as a pick from another device.
+ assertEquals(Follow.Resend, MirrorRules.onWeb(late, want, local, quiet = false, landed = true, predictedMs = null,
+ previousUri = c, recentUris = listOf(c, b)))
+ // A song the mirror sent that is not the local neighbour: still sent again, not followed as a remote pick.
+ assertEquals(Follow.Resend, MirrorRules.onWeb(Web(a, paused = false, positionMs = 0), want, local, quiet = false, landed = true,
+ predictedMs = null, previousUri = c, recentUris = listOf(a, c)))
+ // During the echo window it is not followed either.
+ assertEquals(Follow.Nothing, MirrorRules.onWeb(late, want, local, quiet = true, landed = true, predictedMs = null,
+ previousUri = c, recentUris = listOf(c, b)))
+ // The same state of a song the mirror did not send lately is a remote move, followed.
+ assertEquals(Follow.Previous, MirrorRules.onWeb(late, want, local, quiet = false, landed = true, predictedMs = null, previousUri = c))
+ }
+}