@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) package eu.friedcutlet.yokan.services.files import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest import platform.Foundation.NSFileManager import platform.Foundation.NSURL import kotlin.random.Random import kotlin.test.* class IosLocalMediaInputTest { @Test fun minimalBookmarksAndCoordinatedReadsPreserveTheSourceAndBoundChunks() = runTest { val root = "${IosLocalFileService.cacheRoot}/test-import-${Random.nextLong().toULong()}" val path = "$root/clip.mp4" val bytes = ByteArray(3 * LOCAL_IMPORT_CHUNK_BYTES + 3) { it.toByte() } try { IosLocalFileService.writeBytes(path, bytes) assertContentEquals(bytes, IosLocalFileService.readBytes(path)) assertEquals(path, IosSecurityScopedBookmarks.persist(NSURL.fileURLWithPath(path))) val chunks = mutableListOf() IosLocalMediaInput("clip.mp4", bytes.size.toLong(), path).readChunks { chunks += it } assertEquals(listOf(65536, 65536, 65536, 3), chunks.map { it.size }) assertContentEquals(bytes, chunks.reduce { a, b -> a + b }) assertContentEquals(bytes, IosLocalFileService.readBytes(path)) } finally { NSFileManager.defaultManager.removeItemAtPath(root, error = null) } } @Test fun cancellationInsideACoordinatedReadStopsBeforeAnotherChunk() = runTest { val root = "${IosLocalFileService.cacheRoot}/test-import-${Random.nextLong().toULong()}" val path = "$root/clip.mp4" val bytes = ByteArray(3 * LOCAL_IMPORT_CHUNK_BYTES) { it.toByte() } try { IosLocalFileService.writeBytes(path, bytes) assertContentEquals(bytes, IosLocalFileService.readBytes(path)) val first = CompletableDeferred() var chunks = 0 val work = launch { IosLocalMediaInput("clip.mp4", bytes.size.toLong(), path).readChunks { chunks++ first.complete(Unit) awaitCancellation() } } first.await() work.cancelAndJoin() assertEquals(1, chunks) assertContentEquals(bytes, IosLocalFileService.readBytes(path)) } finally { NSFileManager.defaultManager.removeItemAtPath(root, error = null) } } }