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 kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertNull import kotlin.test.assertTrue import win.taptap.musicmanager.client.api.ApiClient import win.taptap.musicmanager.client.api.ApiException import win.taptap.musicmanager.client.api.Mood import win.taptap.musicmanager.client.api.configuredHttpClient import win.taptap.musicmanager.client.data.AppCache import win.taptap.musicmanager.client.data.CachedState 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}} """.trimIndent(), HttpStatusCode.OK, jsonHeaders, ) "/api/v1/moods" -> respond( """ {"moods":[{"id":"mo-1","name":"Focus","source":"deezer","collectionPercent":60, "recommendationPercent":40,"recommendationCount":10,"refreshHours":24, "createdAt":"now","changedAt":"now","songCount":2,"recommendationReady":3}]} """.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().songCount) assertEquals(3, moods.first().recommendationReady) } @Test fun `search returns badges and adding a video queues a download`() = runTest { val engine = MockEngine { request -> when (request.url.encodedPath) { "/api/v1/search" -> respond( """ {"results":[ {"source":"deezer","externalId":"v1","title":"Fresh","artist":"Artist", "duration":180,"downloaded":false}, {"source":"deezer","externalId":"v2","title":"Old","artist":"Artist", "duration":200,"songId":"sg-2","downloaded":true} ]} """.trimIndent(), HttpStatusCode.OK, jsonHeaders, ) "/api/v1/moods/mo-1/songs" -> respond( """ {"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now", "changedAt":"now","songCount":1},"songs":[],"recommendations":[]}, "added":false,"downloading":true} """.trimIndent(), HttpStatusCode.Accepted, jsonHeaders, ) else -> respondError(HttpStatusCode.NotFound) } } val client = ApiClient(configuredHttpClient(engine)) client.restore("http://music", "token") val results = client.search("fresh") assertEquals(2, results.size) assertNull(results[0].songId) assertEquals("sg-2", results[1].songId) assertTrue(results[1].downloaded) assertEquals("v2", results[1].externalId) val added = client.addSong("mo-1", source = "deezer", externalId = "v1") assertTrue(added.downloading) assertEquals(1, added.detail.mood.songCount) } @Test fun `adding and rejecting recommendations parse the decision`() = runTest { val engine = MockEngine { request -> when (request.url.encodedPath) { "/api/v1/moods/mo-1/recommendations/v1/add" -> respond( """ {"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now", "changedAt":"now","songCount":2},"songs":[],"recommendations":[]}, "recommendation":{"source":"deezer","externalId":"v1","title":"Pick", "artist":"Artist","state":"added"}} """.trimIndent(), HttpStatusCode.OK, jsonHeaders, ) "/api/v1/moods/mo-1/recommendations/v2/reject" -> respond( """ {"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now", "changedAt":"now","songCount":2},"songs":[],"recommendations":[]}, "recommendation":{"source":"deezer","externalId":"v2","title":"Other", "artist":"Artist","state":"rejected"}} """.trimIndent(), HttpStatusCode.OK, jsonHeaders, ) else -> respondError(HttpStatusCode.NotFound) } } val client = ApiClient(configuredHttpClient(engine)) client.restore("http://music", "token") assertEquals("added", client.addRecommendation("mo-1", "v1").recommendation.state) assertEquals("rejected", client.rejectRecommendation("mo-1", "v2").recommendation.state) } @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 { 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 { 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 moods and discards the old cache version`() = runTest { val storage = MemoryStorage() val cache = AppCache(storage) assertNull(cache.loadSession()) val mood = Mood( id = "mo-1", name = "Focus", createdAt = "now", changedAt = "now", songCount = 2, ) cache.save( CachedState( serverUrl = "http://localhost:8080", userName = "alice", moods = listOf(mood), ), ) val loaded = cache.load() assertEquals(listOf("mo-1"), loaded.moods.map { it.id }) assertEquals("alice", loaded.userName) storage.write("mood-cache.json", """{"version":1,"songs":[{"id":"old"}]}""") val invalidated = cache.load() assertTrue(invalidated.moods.isEmpty()) assertEquals(3, invalidated.version) } }