package eu.friedcutlet.yokan.services.logging import eu.friedcutlet.yokan.services.files.JvmLocalFileService import eu.friedcutlet.yokan.services.files.LocalFileService import java.nio.file.Files import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class LogSinkAppendTest { @Test fun appendsWithoutReadingHistoryAndRotatesAtTheCap() { val root = Files.createTempDirectory("yokan-log-test-").toFile() try { val disk = JvmLocalFileService(root.absolutePath, root.absolutePath, root.absolutePath) val log = root.resolve("logs/yokan.log") log.parentFile.mkdirs() log.writeText("existing\n") val files = object : LocalFileService by disk { override fun readBytes(path: String): ByteArray = error("Log append must not read history") override fun writeBytes(path: String, bytes: ByteArray) = error("Log append must not replace history") } val lines = (0..99).map { "line $it\n".encodeToByteArray() } // Unknown size first, then the tracked size, exactly as LogSink does. var size = -1L lines.forEach { size = appendRotatingLog(files, log.absolutePath, size, it, maxBytes = 200) } val rotated = root.resolve("logs/yokan.log.1") assertTrue(log.length() <= 200 && rotated.length() <= 200, "each file stays under the cap") assertEquals(log.length(), size) // Nothing between the rotated file and the live file is lost or reordered. val tail = (rotated.readLines() + log.readLines()) assertEquals((100 - tail.size until 100).map { "line $it" }, tail) } finally { root.deleteRecursively() } } @Test fun skipsAnEntryLargerThanTheFileCap() { val root = Files.createTempDirectory("yokan-log-oversized-test-").toFile() try { val disk = JvmLocalFileService(root.absolutePath, root.absolutePath, root.absolutePath) val log = root.resolve("logs/yokan.log") log.parentFile.mkdirs() log.writeBytes(ByteArray(190)) val size = appendRotatingLog(disk, log.absolutePath, 190L, ByteArray(201), maxBytes = 200) assertEquals(190L, size) assertEquals(190L, log.length()) assertTrue(!root.resolve("logs/yokan.log.1").exists()) } finally { root.deleteRecursively() } } @Test fun doesNotAppendWhenRotationPromotionFails() { val root = Files.createTempDirectory("yokan-log-promotion-test-").toFile() try { val disk = JvmLocalFileService(root.absolutePath, root.absolutePath, root.absolutePath) val log = root.resolve("logs/yokan.log") log.parentFile.mkdirs() log.writeBytes(ByteArray(190)) val files = object : LocalFileService by disk { override fun promote(sourcePath: String, targetPath: String): Boolean = false } val size = appendRotatingLog(files, log.absolutePath, 190L, ByteArray(11), maxBytes = 200) assertEquals(190L, size) assertEquals(190L, log.length()) assertTrue(!root.resolve("logs/yokan.log.1").exists()) } finally { root.deleteRecursively() } } }