Files
AudioManagerClient/composeApp/src/commonTest/kotlin/win/taptap/musicmanager/client/ApiClientTest.kt
T
TapTap 43bd9629d3
CI / build (push) Successful in 2m1s
fix: harden playback, sync, downloads and mood state
Playback:
- Persist the playhead in the playback snapshot and resume from it; restored
  longform progress is no longer overwritten with 0 on first play.
- Previous compares elapsed playtime since the track start, so resuming at
  1:00:00 and pressing previous goes back instead of restarting the book.
- Auto-advance no longer overwrites completed=true with false, longform PUTs
  are serialized, and playing rows/search results resume saved positions.
- Pause cancels the 400 ms poll; seek errors are reported instead of crashing.

Sync and state:
- First-sync snapshots keep the first page revision; cached revisions are only
  trusted for the same server/user.
- Refresh re-reads /me, merges local and server longform progress by timestamp,
  replays newer local positions, and keeps cached longform after deltas.
- Logout cancels refresh jobs, suppresses late progress writes, clears after
  playback teardown, and closes the HTTP client on release.
- Failed/racing mood opens clear the previous mood; stale responses cannot
  replace a newer selection. Mood drafts survive background refreshes.

Downloads and storage:
- Stream downloads to a .part file and atomically rename on Android/desktop,
  with a download-specific timeout and no whole-file buffering.
- Cache writes are best-effort and atomic; blocked/full web storage no longer
  leaves the app on the splash screen or blocks playback.
- Artwork failures do not fail audio downloads; failed downloads refresh the
  download index.
- Android queues sleep-timer commands before the controller connects.

UI:
- Music search is wired, debounced and kept separate from mood search.
- Player bar respects navigation-bar insets and hides music-only mood actions
  for longform. Mood gradient handles Int.MIN_VALUE.
2026-11-15 18:18:30 +00:00

139 lines
4.9 KiB
Kotlin

package win.taptap.musicmanager.client
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.engine.mock.respondError
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf
import io.ktor.utils.io.readAvailable
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import win.taptap.musicmanager.client.api.ApiClient
import win.taptap.musicmanager.client.api.ApiException
import win.taptap.musicmanager.client.api.configuredHttpClient
import win.taptap.musicmanager.client.data.AppStorage
import win.taptap.musicmanager.client.data.CachedState
import win.taptap.musicmanager.client.data.LibraryCache
class ApiClientTest {
private val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json")
@Test
fun `login stores the token and parses moods`() = runTest {
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/auth/login" -> respond(
"""
{"token":"abc123","expiresAt":"2027-01-01T00:00:00Z",
"user":{"name":"alice","admin":true,"musicFolders":[1],"longformFolders":[10]}}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods" -> respond(
"""
{"moods":[{"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24,
"ytEnabled":true,"createdAt":"now","changedAt":"now","seedCount":2}]}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val client = ApiClient(configuredHttpClient(engine))
val login = client.login("music.example.com", "alice", "secret", "test", "test")
assertEquals("abc123", login.token)
assertEquals("http://music.example.com", client.baseUrl)
val moods = client.moods()
assertEquals(1, moods.size)
assertEquals("Focus", moods.first().name)
assertEquals(2, moods.first().seedCount)
}
@Test
fun `api errors surface the server message`() = runTest {
val engine = MockEngine {
respond(
"""{"error":{"code":"unauthorized","message":"Missing or invalid token"}}""",
HttpStatusCode.Unauthorized,
jsonHeaders,
)
}
val client = ApiClient(configuredHttpClient(engine))
val error = assertFailsWith<ApiException> { client.moods() }
assertEquals(401, error.status)
assertEquals("unauthorized", error.code)
}
@Test
fun `failed downloads and images do not return error bodies`() = runTest {
val engine = MockEngine {
respond(
"""{"error":{"code":"not_found","message":"Song not found"}}""",
HttpStatusCode.NotFound,
jsonHeaders,
)
}
val client = ApiClient(configuredHttpClient(engine))
client.restore("http://music", "token")
val error = assertFailsWith<ApiException> { client.download("sg-missing") }
assertEquals(404, error.status)
assertNull(client.image("http://music/missing.jpg"))
}
@Test
fun `downloadTo streams bytes into the storage sink`() = runTest {
val payload = ByteArray(100_000) { (it % 251).toByte() }
val engine = MockEngine {
respond(payload, HttpStatusCode.OK, headersOf(HttpHeaders.ContentType, "audio/mpeg"))
}
val client = ApiClient(configuredHttpClient(engine))
client.restore("http://music", "token")
var received = 0
val path = client.downloadTo("sg-1") { channel ->
val buffer = ByteArray(8 * 1024)
while (true) {
val read = channel.readAvailable(buffer)
if (read < 0) break
received += read
}
"saved.mp3"
}
assertEquals("saved.mp3", path)
assertEquals(payload.size, received)
}
@Test
fun `cache round-trips songs and moods`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
assertNull(cache.loadSession())
cache.save(
CachedState(
serverUrl = "http://localhost:8080",
userName = "alice",
revision = "2026-11-14T00:00:00Z",
songs = emptyList(),
moods = emptyList(),
),
)
val loaded = cache.load()
assertEquals("2026-11-14T00:00:00Z", loaded.revision)
assertEquals("alice", loaded.userName)
}
}