package eu.friedcutlet.yokan.services.files import java.io.ByteArrayInputStream import java.util.concurrent.atomic.AtomicInteger import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.async import kotlinx.coroutines.test.runTest import kotlin.test.* class JvmLocalMediaInputTest { @Test fun readerWaitsForDestinationAndNeverReadsMoreThanOneBoundedChunkAhead() = runTest { val bytes = ByteArray(LOCAL_IMPORT_CHUNK_BYTES * 3 + 3) { it.toByte() } val reads = AtomicInteger() val closes = AtomicInteger() val stream = object : ByteArrayInputStream(bytes) { override fun read(b: ByteArray, off: Int, len: Int): Int { reads.incrementAndGet(); return super.read(b, off, len) } override fun close() { closes.incrementAndGet(); super.close() } } val first = CompletableDeferred() val resume = CompletableDeferred() val chunks = mutableListOf() val reader = JvmLocalMediaInput("clip.mp4", bytes.size.toLong()) { stream } val work = async { reader.readChunks { chunks += it if (chunks.size == 1) { first.complete(Unit); resume.await() } } } first.await() assertEquals(1, reads.get()) assertEquals(0, closes.get()) resume.complete(Unit) work.await() assertEquals(listOf(65536, 65536, 65536, 3), chunks.map { it.size }) assertContentEquals(bytes, chunks.reduce { a, b -> a + b }) assertEquals(1, closes.get()) } @Test fun cancellationClosesTheSourceWithoutReadingTheRemainingFile() = runTest { val closes = AtomicInteger() val stream = object : ByteArrayInputStream(ByteArray(LOCAL_IMPORT_CHUNK_BYTES * 3)) { override fun close() { closes.incrementAndGet(); super.close() } } val reader = JvmLocalMediaInput("clip.mp4", null) { stream } assertFailsWith { reader.readChunks { throw CancellationException("Cancelled") } } assertEquals(1, closes.get()) assertEquals(LOCAL_IMPORT_CHUNK_BYTES * 2, stream.available()) } }