Best Kotest code snippet using io.kotest.matchers.paths.paths.Path.shouldBeAFile
FileMatchersTest.kt
Source:FileMatchersTest.kt
1package com.sksamuel.kotest.matchers.file2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.core.spec.style.FunSpec4import io.kotest.matchers.file.aDirectory5import io.kotest.matchers.file.aFile6import io.kotest.matchers.file.beAbsolute7import io.kotest.matchers.file.beRelative8import io.kotest.matchers.file.exist9import io.kotest.matchers.file.haveExtension10import io.kotest.matchers.file.shouldBeADirectory11import io.kotest.matchers.file.shouldBeAFile12import io.kotest.matchers.file.shouldBeAbsolute13import io.kotest.matchers.file.shouldBeEmptyDirectory14import io.kotest.matchers.file.shouldBeRelative15import io.kotest.matchers.file.shouldBeSymbolicLink16import io.kotest.matchers.file.shouldExist17import io.kotest.matchers.file.shouldHaveExtension18import io.kotest.matchers.file.shouldHaveParent19import io.kotest.matchers.file.shouldHaveSameStructureAs20import io.kotest.matchers.file.shouldHaveSameStructureAndContentAs21import io.kotest.matchers.file.shouldNotBeADirectory22import io.kotest.matchers.file.shouldNotBeAFile23import io.kotest.matchers.file.shouldNotBeEmptyDirectory24import io.kotest.matchers.file.shouldNotBeSymbolicLink25import io.kotest.matchers.file.shouldNotExist26import io.kotest.matchers.file.shouldNotHaveExtension27import io.kotest.matchers.file.shouldNotHaveParent28import io.kotest.matchers.file.shouldStartWithPath29import io.kotest.matchers.file.startWithPath30import io.kotest.matchers.paths.shouldBeLarger31import io.kotest.matchers.paths.shouldBeSmaller32import io.kotest.matchers.paths.shouldBeSymbolicLink33import io.kotest.matchers.paths.shouldContainFile34import io.kotest.matchers.paths.shouldContainFileDeep35import io.kotest.matchers.paths.shouldContainFiles36import io.kotest.matchers.paths.shouldHaveParent37import io.kotest.matchers.paths.shouldNotBeSymbolicLink38import io.kotest.matchers.paths.shouldNotContainFile39import io.kotest.matchers.paths.shouldNotContainFileDeep40import io.kotest.matchers.paths.shouldNotContainFiles41import io.kotest.matchers.paths.shouldNotHaveParent42import io.kotest.matchers.should43import io.kotest.matchers.shouldBe44import io.kotest.matchers.shouldNot45import io.kotest.matchers.string.shouldEndWith46import io.kotest.matchers.string.shouldMatch47import java.io.File48import java.nio.file.Files49import java.nio.file.Paths50import org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS51@Suppress("BlockingMethodInNonBlockingContext")52class FileMatchersTest : FunSpec() {53 init {54 test("relative() should match only relative files") {55 File("sammy/boy") shouldBe beRelative()56 File("sammy/boy").shouldBeRelative()57 }58 test("absolute() should match only absolute files") {59 val root = if (IS_OS_WINDOWS) "C:/" else "/"60 File("${root}sammy/boy") shouldBe beAbsolute()61 File("${root}sammy/boy").shouldBeAbsolute()62 }63 test("startWithPath() should only match files that start with the given path") {64 File("sammy/boy") should startWithPath("sammy")65 File("sammy/boy") should startWithPath(Paths.get("sammy"))66 File("/sammy/boy") should startWithPath("${File.separator}sammy")67 File("/sammy/boy") should startWithPath(Paths.get("/sammy"))68 File("/sammy/boy").shouldStartWithPath("${File.separator}sammy")69 File("/sammy/boy").shouldStartWithPath(Paths.get("/sammy"))70 }71 test("exist() file matcher") {72 val file = Files.createTempFile("test", "test").toFile()73 file should exist()74 shouldThrow<AssertionError> {75 File("qweqwewqewqewee") should exist()76 }.message shouldBe "File qweqwewqewqewee should exist"77 file.shouldExist()78 shouldThrow<AssertionError> {79 file.shouldNotExist()80 }81 file.delete()82 }83 test("haveExtension") {84 val file = Files.createTempFile("test", ".test").toFile()85 file should haveExtension(".test")86 file shouldNot haveExtension(".wibble")87 shouldThrow<AssertionError> {88 file should haveExtension(".jpeg")89 }.message.shouldEndWith("with one of .jpeg")90 shouldThrow<AssertionError> {91 file.shouldHaveExtension(".jpeg")92 }.message.shouldEndWith("with one of .jpeg")93 file.shouldHaveExtension(".test")94 file.shouldNotHaveExtension(".wibble")95 file.delete()96 }97 test("aFile() file matcher") {98 val file = Files.createTempFile("test", "test").toFile()99 file shouldBe aFile()100 file.shouldBeAFile()101 shouldThrow<AssertionError> {102 file shouldBe aDirectory()103 }104 shouldThrow<AssertionError> {105 file.shouldNotBeAFile()106 }107 shouldThrow<AssertionError> {108 file.shouldBeADirectory()109 }110 file.delete()111 }112 test("aDirectory() file matcher") {113 val dir = Files.createTempDirectory("testdir").toFile()114 dir shouldBe aDirectory()115 dir.shouldBeADirectory()116 shouldThrow<AssertionError> {117 dir shouldBe aFile()118 }119 shouldThrow<AssertionError> {120 dir.shouldNotBeADirectory()121 }122 shouldThrow<AssertionError> {123 dir shouldBe aFile()124 }125 }126 test("directory should be empty (deprecated)") {127 val dir = Files.createTempDirectory("testdir").toFile()128 dir.shouldBeEmptyDirectory()129 dir.resolve("testfile.txt").writeBytes(byteArrayOf(1, 2, 3))130 dir.shouldNotBeEmptyDirectory()131 }132 test("directory should be empty") {133 val dir = Files.createTempDirectory("testdir").toFile()134 dir.shouldBeEmptyDirectory()135 dir.resolve("testfile.txt").writeBytes(byteArrayOf(1, 2, 3))136 dir.shouldNotBeEmptyDirectory()137 }138 test("directory contains file matching predicate") {139 val dir = Files.createTempDirectory("testdir")140 dir.resolve("a").toFile().createNewFile()141 dir.resolve("b").toFile().createNewFile()142 dir.shouldContainFile("a")143 dir.shouldNotContainFile("c")144 shouldThrow<AssertionError> {145 dir.shouldContainFile("c")146 }.message?.shouldMatch("^Directory .+ should contain a file with filename c \\(detected 2 other files\\)$".toRegex())147 }148 test("beSmaller should compare file sizes") {149 val dir = Files.createTempDirectory("testdir")150 Files.write(dir.resolve("a"), byteArrayOf(1, 2))151 Files.write(dir.resolve("b"), byteArrayOf(1, 2, 3))152 dir.resolve("a").shouldBeSmaller(dir.resolve("b"))153 shouldThrow<AssertionError> {154 dir.resolve("b").shouldBeSmaller(dir.resolve("a"))155 }.message shouldBe "Path ${dir.resolve("b")} (3 bytes) should be smaller than ${dir.resolve("a")} (2 bytes)"156 }157 test("beLarger should compare file sizes") {158 val dir = Files.createTempDirectory("testdir")159 Files.write(dir.resolve("a"), byteArrayOf(1, 2, 3))160 Files.write(dir.resolve("b"), byteArrayOf(1, 2))161 dir.resolve("a").shouldBeLarger(dir.resolve("b"))162 shouldThrow<AssertionError> {163 dir.resolve("b").shouldBeLarger(dir.resolve("a"))164 }.message shouldBe "File ${dir.resolve("b")} (2 bytes) should be larger than ${dir.resolve("a")} (3 bytes)"165 }166 test("containsFileDeep should find file deep") {167 val rootFileName = "super_dooper_hyper_file_root"168 val innerFileName = "super_dooper_hyper_file_inner"169 val nonExistentFileName = "super_dooper_hyper_non_existent_file"170 val rootDir = Files.createTempDirectory("testdir")171 val innerDir = Files.createDirectories(rootDir.resolve("innerfolder"))172 Files.write(rootDir.resolve(rootFileName), byteArrayOf(1, 2, 3))173 Files.write(innerDir.resolve(innerFileName), byteArrayOf(1, 2, 3))174 rootDir.shouldContainFileDeep(rootFileName)175 rootDir.shouldContainFileDeep(innerFileName)176 shouldThrow<AssertionError> {177 rootDir.shouldContainFileDeep(nonExistentFileName)178 }.message shouldBe "Path $nonExistentFileName should exist in $rootDir"179 shouldThrow<AssertionError> {180 rootDir.shouldNotContainFileDeep(rootFileName)181 }.message shouldBe "Path $rootFileName should not exist in $rootDir"182 }183 test("shouldContainFiles should check if files exists") {184 val testDir = Files.createTempDirectory("testdir")185 Files.write(testDir.resolve("a.txt"), byteArrayOf(1, 2, 3))186 Files.write(testDir.resolve("b.gif"), byteArrayOf(1, 2, 3))187 Files.write(testDir.resolve("c.doc"), byteArrayOf(1, 2, 3))188 testDir.shouldContainFiles("a.txt", "b.gif", "c.doc")189 testDir.shouldNotContainFiles("d.txt", "e.gif", "f.doc")190 shouldThrow<AssertionError> {191 testDir.shouldContainFiles("d.txt")192 }.message shouldBe "File d.txt should exist in $testDir"193 shouldThrow<AssertionError> {194 testDir.shouldContainFiles("d.txt", "e.gif")195 }.message shouldBe "Files d.txt, e.gif should exist in $testDir"196 shouldThrow<AssertionError> {197 testDir.shouldNotContainFiles("a.txt")198 }.message shouldBe "File a.txt should not exist in $testDir"199 shouldThrow<AssertionError> {200 testDir.shouldNotContainFiles("a.txt", "b.gif")201 }.message shouldBe "Files a.txt, b.gif should not exist in $testDir"202 }203 test("shouldBeSymbolicLink should check if file is symbolic link").config(enabled = isNotWindowsOrIsWindowsElevated()) {204 val testDir = Files.createTempDirectory("testdir")205 val existingFile = Files.write(testDir.resolve("original.txt"), byteArrayOf(1, 2, 3, 4))206 val existingFileAsFile = existingFile.toFile()207 val link = Files.createSymbolicLink(testDir.resolve("a.txt"), existingFile)208 val linkAsFile = link.toFile()209 link.shouldBeSymbolicLink()210 linkAsFile.shouldBeSymbolicLink()211 existingFile.shouldNotBeSymbolicLink()212 existingFileAsFile.shouldNotBeSymbolicLink()213 }214 test("shouldHaveParent should check if file has any parent with given name") {215 val testDir = Files.createTempDirectory("testdir")216 val subdir = Files.createDirectory(testDir.resolve("sub_testdir"))217 val file = Files.write(subdir.resolve("a.txt"), byteArrayOf(1, 2, 3, 4))218 val fileAsFile = file.toFile()219 file.shouldHaveParent(testDir.toFile().name)220 file.shouldHaveParent(subdir.toFile().name)221 file.shouldNotHaveParent("super_hyper_long_random_file_name")222 fileAsFile.shouldHaveParent(testDir.toFile().name)223 fileAsFile.shouldHaveParent(subdir.toFile().name)224 fileAsFile.shouldNotHaveParent("super_hyper_long_random_file_name")225 }226 test("shouldHaveSameStructureAs and shouldHaveSameStructureAndContentAs two file trees") {227 val testDir = Files.createTempDirectory("testdir")228 val expectDir = File("$testDir/expect").apply {229 File("$this/a.txt").createWithContent(byteArrayOf(1, 2, 3))230 File("$this/b.txt").createWithContent(byteArrayOf(1, 2, 3, 4))231 File("$this/subfolder/b.txt").createWithContent(byteArrayOf(1, 2, 3, 4))232 File("$this/subfolder/subfolder-two/c.txt").createWithContent(byteArrayOf(1, 2))233 }234 val actualDir = File("$testDir/actual").apply {235 File("$this/a.txt").createWithContent(byteArrayOf(1, 2, 3))236 File("$this/b.txt").createWithContent(byteArrayOf(1, 2, 3, 4))237 File("$this/subfolder/b.txt").createWithContent(byteArrayOf(1, 2, 3, 4))238 File("$this/subfolder/subfolder-two/c.txt").createWithContent(byteArrayOf(1, 2))239 }240 expectDir shouldHaveSameStructureAs actualDir241 expectDir shouldHaveSameStructureAndContentAs actualDir242 File("$expectDir/z.txt").createWithContent(byteArrayOf(1, 2, 3))243 shouldThrow<AssertionError> { expectDir shouldHaveSameStructureAs actualDir }244 shouldThrow<AssertionError> { expectDir shouldHaveSameStructureAndContentAs actualDir }245 File("$actualDir/z.txt").createWithContent(byteArrayOf(1, 2, 3, 4))246 expectDir shouldHaveSameStructureAs actualDir247 shouldThrow<AssertionError> { expectDir shouldHaveSameStructureAndContentAs actualDir }248 }249 test("shouldHaveSameStructureAs with filter should check if two file trees are the same and files have the same content") {250 val testDir = Files.createTempDirectory("testdir")251 val expectDir = File("$testDir/expect").apply {252 File("$this/a.txt").createWithContent("a/b")253 File("$this/b.txt").createWithContent("b/c")254 File("$this/subfolder/b.txt").createWithContent("b/c")255 File("$this/subfolder/subfolder-two/c.txt").createWithContent("c/d")256 File("$this/z.txt").createWithContent("z")257 }258 val actualDir = File("$testDir/actual").apply {259 File("$this/a.txt").createWithContent("a/b")260 File("$this/b.txt").createWithContent("b/c")261 File("$this/subfolder/b.txt").createWithContent("b/c")262 File("$this/subfolder/subfolder-two/c.txt").createWithContent("c/d")263 File("$this/z.txt").createWithContent("zz")264 }265 expectDir.shouldHaveSameStructureAs(actualDir, filterLhs = { it.name == "z.txt" })266 expectDir.shouldHaveSameStructureAs(actualDir, filterRhs = { it.name == "z.txt" })267 }268 test("shouldHaveSameStructureAndContentAs with compare and filter should check if two file trees are the same and files have the same content") {269 val testDir = Files.createTempDirectory("testdir")270 val expectDir = File("$testDir/expect").apply {271 File("$this/a.txt").createWithContent("a/b")272 File("$this/b.txt").createWithContent("b/c")273 File("$this/subfolder/b.txt").createWithContent("b/c")274 File("$this/subfolder/subfolder-two/c.txt").createWithContent("c/d")275 }276 val actualDir = File("$testDir/actual").apply {277 File("$this/a.txt").createWithContent("a/b")278 File("$this/b.txt").createWithContent("b\\c")279 File("$this/subfolder/b.txt").createWithContent("b\\c")280 File("$this/subfolder/subfolder-two/c.txt").createWithContent("c\\d")281 }282 expectDir.shouldHaveSameStructureAs(actualDir) { a, b ->283 a.isFile && b.isFile && a.readText() == b.readText().replace("\\", "/")284 }285 expectDir.shouldHaveSameStructureAndContentAs(actualDir, filterLhs = { it.name != "a.txt" })286 expectDir.shouldHaveSameStructureAndContentAs(actualDir, filterRhs = { it.name != "a.txt" })287 }288 }289}290private fun File.createWithContent(content: String) {291 this.parentFile.mkdirs()292 createNewFile()293 writeText(content)294}295private fun File.createWithContent(content: ByteArray) {296 this.parentFile.mkdirs()297 createNewFile()298 writeBytes(content)299}300private fun isNotWindowsOrIsWindowsElevated(): Boolean {301 return if (!IS_OS_WINDOWS) {302 true303 } else {304 try {305 val p = Runtime.getRuntime().exec("""reg query "HKU\S-1-5-19"""")306 p.waitFor()307 0 == p.exitValue()308 } catch (ex: Exception) {309 println("Failed to determine if process had elevated permissions, assuming it does not.")310 false311 }312 }313}...
executeTests.kt
Source:executeTests.kt
1package org.jetbrains.kotlinx.jupyter.test2import ch.qos.logback.classic.Level.DEBUG3import ch.qos.logback.classic.Level.OFF4import io.kotest.matchers.paths.shouldBeAFile5import io.kotest.matchers.shouldBe6import jupyter.kotlin.providers.UserHandlesProvider7import kotlinx.serialization.json.Json8import kotlinx.serialization.json.JsonNull9import kotlinx.serialization.json.JsonObject10import kotlinx.serialization.json.JsonPrimitive11import kotlinx.serialization.json.decodeFromJsonElement12import org.jetbrains.kotlinx.jupyter.JupyterSockets13import org.jetbrains.kotlinx.jupyter.LoggingManagement.mainLoggerLevel14import org.jetbrains.kotlinx.jupyter.api.Notebook15import org.jetbrains.kotlinx.jupyter.api.SessionOptions16import org.jetbrains.kotlinx.jupyter.compiler.util.EvaluatedSnippetMetadata17import org.jetbrains.kotlinx.jupyter.messaging.ExecuteReply18import org.jetbrains.kotlinx.jupyter.messaging.ExecuteRequest19import org.jetbrains.kotlinx.jupyter.messaging.ExecutionResult20import org.jetbrains.kotlinx.jupyter.messaging.InputReply21import org.jetbrains.kotlinx.jupyter.messaging.IsCompleteReply22import org.jetbrains.kotlinx.jupyter.messaging.IsCompleteRequest23import org.jetbrains.kotlinx.jupyter.messaging.KernelStatus24import org.jetbrains.kotlinx.jupyter.messaging.Message25import org.jetbrains.kotlinx.jupyter.messaging.MessageType26import org.jetbrains.kotlinx.jupyter.messaging.StatusReply27import org.jetbrains.kotlinx.jupyter.messaging.StreamResponse28import org.jetbrains.kotlinx.jupyter.messaging.jsonObject29import org.junit.jupiter.api.Assertions.assertEquals30import org.junit.jupiter.api.Assertions.assertNull31import org.junit.jupiter.api.Test32import org.junit.jupiter.api.Timeout33import org.junit.jupiter.api.parallel.Execution34import org.junit.jupiter.api.parallel.ExecutionMode35import org.zeromq.ZMQ36import java.io.File37import java.net.URLClassLoader38import java.nio.file.Files39import java.util.concurrent.TimeUnit40import kotlin.io.path.readText41import kotlin.reflect.KProperty142import kotlin.reflect.full.memberProperties43import kotlin.test.assertNotNull44import kotlin.test.assertTrue45fun JsonObject.string(key: String): String {46 return (get(key) as JsonPrimitive).content47}48@Timeout(100, unit = TimeUnit.SECONDS)49@Execution(ExecutionMode.SAME_THREAD)50class ExecuteTests : KernelServerTestsBase() {51 private var context: ZMQ.Context? = null52 private var shell: ClientSocket? = null53 private var ioPub: ClientSocket? = null54 private var stdin: ClientSocket? = null55 override fun beforeEach() {56 try {57 context = ZMQ.context(1)58 shell = ClientSocket(context!!, JupyterSockets.SHELL)59 ioPub = ClientSocket(context!!, JupyterSockets.IOPUB)60 stdin = ClientSocket(context!!, JupyterSockets.STDIN)61 ioPub?.subscribe(byteArrayOf())62 shell?.connect()63 ioPub?.connect()64 stdin?.connect()65 } catch (e: Throwable) {66 afterEach()67 throw e68 }69 }70 override fun afterEach() {71 shell?.close()72 shell = null73 ioPub?.close()74 ioPub = null75 stdin?.close()76 stdin = null77 context?.term()78 context = null79 }80 private fun doExecute(81 code: String,82 hasResult: Boolean = true,83 ioPubChecker: (ZMQ.Socket) -> Unit = {},84 executeReplyChecker: (Message) -> Unit = {},85 inputs: List<String> = emptyList(),86 allowStdin: Boolean = true,87 storeHistory: Boolean = true88 ): Any? {89 try {90 val shell = this.shell!!91 val ioPub = this.ioPub!!92 val stdin = this.stdin!!93 shell.sendMessage(MessageType.EXECUTE_REQUEST, content = ExecuteRequest(code, allowStdin = allowStdin, storeHistory = storeHistory))94 inputs.forEach {95 stdin.sendMessage(MessageType.INPUT_REPLY, InputReply(it))96 }97 var msg = shell.receiveMessage()98 assertEquals(MessageType.EXECUTE_REPLY, msg.type)99 executeReplyChecker(msg)100 msg = ioPub.receiveMessage()101 assertEquals(MessageType.STATUS, msg.type)102 assertEquals(KernelStatus.BUSY, (msg.content as StatusReply).status)103 msg = ioPub.receiveMessage()104 assertEquals(MessageType.EXECUTE_INPUT, msg.type)105 ioPubChecker(ioPub)106 var response: Any? = null107 if (hasResult) {108 msg = ioPub.receiveMessage()109 val content = msg.content as ExecutionResult110 assertEquals(MessageType.EXECUTE_RESULT, msg.type)111 response = content.data112 }113 msg = ioPub.receiveMessage()114 assertEquals(MessageType.STATUS, msg.type)115 assertEquals(KernelStatus.IDLE, (msg.content as StatusReply).status)116 return response117 } catch (e: Throwable) {118 afterEach()119 throw e120 }121 }122 private fun executeWithNoStdin(code: String) {123 doExecute(124 code,125 hasResult = false,126 allowStdin = false,127 ioPubChecker = {128 val msg = it.receiveMessage()129 assertEquals(MessageType.STREAM, msg.type)130 assertStartsWith("Input from stdin is unsupported by the client", (msg.content as StreamResponse).text)131 }132 )133 }134 private fun doIsComplete(code: String): String {135 try {136 val shell = this.shell!!137 shell.sendMessage(MessageType.IS_COMPLETE_REQUEST, content = IsCompleteRequest(code))138 val responseMsg = shell.receiveMessage()139 assertEquals(MessageType.IS_COMPLETE_REPLY, responseMsg.type)140 val content = responseMsg.content as IsCompleteReply141 return content.status142 } catch (e: Throwable) {143 afterEach()144 throw e145 }146 }147 @Test148 fun testExecute() {149 val res = doExecute("2+2") as JsonObject150 assertEquals("4", res.string("text/plain"))151 }152 @Test153 fun testOutput() {154 val code =155 """156 for (i in 1..5) {157 Thread.sleep(200)158 print(i)159 }160 """.trimIndent()161 fun checker(ioPub: ZMQ.Socket) {162 for (i in 1..5) {163 val msg = ioPub.receiveMessage()164 assertEquals(MessageType.STREAM, msg.type)165 assertEquals(i.toString(), (msg.content as StreamResponse).text)166 }167 }168 val res = doExecute(code, false, ::checker)169 assertNull(res)170 }171 @Test172 fun testOutputMagic() {173 val code =174 """175 %output --max-buffer=2 --max-time=10000176 for (i in 1..5) {177 print(i)178 }179 """.trimIndent()180 val expected = arrayOf("12", "34", "5")181 fun checker(ioPub: ZMQ.Socket) {182 for (el in expected) {183 val msg = ioPub.receiveMessage()184 val content = msg.content185 assertEquals(MessageType.STREAM, msg.type)186 assertTrue(content is StreamResponse)187 assertEquals(el, content.text)188 }189 }190 val res = doExecute(code, false, ::checker)191 assertNull(res)192 }193 @Test194 fun testOutputStrings() {195 val code =196 """197 for (i in 1..5) {198 Thread.sleep(200)199 println("text" + i)200 }201 """.trimIndent()202 fun checker(ioPub: ZMQ.Socket) {203 for (i in 1..5) {204 val msg = ioPub.receiveMessage()205 assertEquals(MessageType.STREAM, msg.type)206 assertEquals("text$i" + System.lineSeparator(), (msg.content as StreamResponse).text)207 }208 }209 val res = doExecute(code, false, ::checker)210 assertNull(res)211 }212 // TODO: investigate, why this test is hanging213 @Test214 fun testReadLine() {215 val code =216 """217 val answer = readLine()218 answer219 """.trimIndent()220 val res = doExecute(code, inputs = listOf("42"))221 assertEquals(jsonObject("text/plain" to "42"), res)222 }223 @Test224 fun testCompiledData() {225 doExecute(226 """227 SessionOptions.serializeScriptData = true228 """.trimIndent(),229 hasResult = false230 )231 val code =232 """233 val xyz = 42234 """.trimIndent()235 val res = doExecute(236 code,237 hasResult = false,238 executeReplyChecker = { message ->239 val metadata = message.data.metadata240 assertTrue(metadata is JsonObject)241 val snippetMetadata = Json.decodeFromJsonElement<EvaluatedSnippetMetadata?>(242 metadata["eval_metadata"] ?: JsonNull243 )244 val compiledData = snippetMetadata?.compiledData245 assertNotNull(compiledData)246 val deserializer = org.jetbrains.kotlinx.jupyter.compiler.CompiledScriptsSerializer()247 val dir = Files.createTempDirectory("kotlin-jupyter-exec-test")248 dir.toFile().deleteOnExit()249 val classesDir = dir.resolve("classes")250 val sourcesDir = dir.resolve("sources")251 val names = deserializer.deserializeAndSave(compiledData, classesDir, sourcesDir)252 val kClassName = names.single()253 val classLoader = URLClassLoader(arrayOf(classesDir.toUri().toURL()), ClassLoader.getSystemClassLoader())254 val loadedClass = classLoader.loadClass(kClassName).kotlin255 @Suppress("UNCHECKED_CAST")256 val xyzProperty = loadedClass.memberProperties.single { it.name == "xyz" } as KProperty1<Any, Int>257 val constructor = loadedClass.constructors.single()258 val userHandlesProvider = object : UserHandlesProvider {259 override val host: Nothing? = null260 override val notebook: Notebook = NotebookMock261 override val sessionOptions: SessionOptions262 get() = throw NotImplementedError()263 }264 val instance = constructor.call(emptyArray<Any>(), userHandlesProvider)265 xyzProperty.get(instance) shouldBe 42266 val sourceFile = sourcesDir.resolve("Line_1.kts")267 sourceFile.shouldBeAFile()268 sourceFile.readText() shouldBe "val xyz = 42"269 }270 )271 assertNull(res)272 }273 @Test274 fun testLibraryLoadingErrors() {275 doExecute(276 """277 USE {278 import("xyz.ods")279 }280 """.trimIndent(),281 false,282 ioPubChecker = {283 val msg = it.receiveMessage()284 assertEquals(MessageType.STREAM, msg.type)285 val msgText = (msg.content as StreamResponse).text286 assertTrue("The problem is found in one of the loaded libraries" in msgText)287 }288 )289 }290 @Test291 fun testCounter() {292 fun checkCounter(message: Message, expectedCounter: Long) {293 val data = message.data.content as ExecuteReply294 assertEquals(expectedCounter, data.executionCount)295 }296 val res1 = doExecute("41", executeReplyChecker = { checkCounter(it, 1) })297 val res2 = doExecute("42", executeReplyChecker = { checkCounter(it, 2) })298 val res3 = doExecute(299 " \"\${Out[1]} \${Out[2]}\" ",300 storeHistory = false,301 executeReplyChecker = { checkCounter(it, 3) }302 )303 val res4 = doExecute(304 "try { Out[3] } catch(e: ArrayIndexOutOfBoundsException) { null }",305 storeHistory = false,306 executeReplyChecker = { checkCounter(it, 3) }307 )308 assertEquals(jsonObject("text/plain" to "41"), res1)309 assertEquals(jsonObject("text/plain" to "42"), res2)310 assertEquals(jsonObject("text/plain" to "41 42"), res3)311 assertEquals(jsonObject("text/plain" to "null"), res4)312 }313 @Test314 fun testReadLineWithNoStdin() {315 executeWithNoStdin("readLine() ?: \"blah\"")316 }317 @Test318 fun testStdinReadWithNoStdin() {319 executeWithNoStdin("System.`in`.read()")320 }321 @Test322 fun testIsComplete() {323 assertEquals("complete", doIsComplete("2 + 2"))324 assertEquals("incomplete", doIsComplete("fun f() : Int { return 1"))325 assertEquals(if (runInSeparateProcess) DEBUG else OFF, mainLoggerLevel())326 }327 @Test328 fun testLoggerAppender() {329 val file = File.createTempFile("kotlin-jupyter-logger-appender-test", ".txt")330 doExecute("%logHandler add f1 --file ${file.absolutePath}", false)331 val result1 = doExecute("2 + 2")332 assertEquals(jsonObject("text/plain" to "4"), result1)333 doExecute("%logHandler remove f1", false)334 val result2 = doExecute("3 + 4")335 assertEquals(jsonObject("text/plain" to "7"), result2)336 val logText = file.readText()337 assertTrue("2 + 2" in logText)338 assertTrue("3 + 4" !in logText)339 file.delete()340 }341}...
matchers.kt
Source:matchers.kt
1package io.kotest.matchers.file2import io.kotest.matchers.Matcher3import io.kotest.matchers.MatcherResult4import io.kotest.matchers.collections.shouldBeSameSizeAs5import io.kotest.matchers.paths.beSymbolicLink6import io.kotest.matchers.should7import io.kotest.matchers.shouldBe8import io.kotest.matchers.shouldNot9import io.kotest.matchers.shouldNotBe10import java.io.File11import java.io.FileFilter12import java.nio.file.Path13private fun File.safeList(): List<String> = this.list()?.toList() ?: emptyList()14private fun File.safeListFiles(): List<File> = this.listFiles()?.toList() ?: emptyList()15private fun File.safeListFiles(filter: FileFilter): List<File> = this.listFiles(filter)?.toList() ?: emptyList()16fun File.shouldBeEmptyDirectory() = this should beEmptyDirectory()17fun File.shouldNotBeEmptyDirectory() = this shouldNot beEmptyDirectory()18fun beEmptyDirectory(): Matcher<File> = object : Matcher<File> {19 override fun test(value: File): MatcherResult {20 val contents = if (value.isDirectory) value.safeList() else emptyList()21 return MatcherResult(22 contents.isEmpty(),23 { "$value should be an empty directory but contained ${contents.size} file(s) [${contents.joinToString(", ")}]" },24 { "$value should not be a non empty directory" }25 )26 }27}28infix fun File.shouldContainNFiles(n: Int) = this shouldBe containNFiles(n)29infix fun File.shouldNotContainNFiles(n: Int) = this shouldNotBe containNFiles(n)30fun containNFiles(n: Int): Matcher<File> = object : Matcher<File> {31 override fun test(value: File): MatcherResult = MatcherResult(32 value.isDirectory && value.safeList().size == n,33 { "$value should be a directory and contain $n files" },34 { "$value should not be a directory containing $n files" }35 )36}37fun File.shouldBeEmpty() = this shouldBe emptyFile()38fun File.shouldNotBeEmpty() = this shouldNotBe emptyFile()39fun emptyFile(): Matcher<File> = object : Matcher<File> {40 override fun test(value: File): MatcherResult =41 MatcherResult(42 value.length() == 0L,43 { "File $value should be empty" },44 { "File $value should not be empty" }45 )46}47fun File.shouldExist() = this should exist()48fun File.shouldNotExist() = this shouldNot exist()49fun exist() = object : Matcher<File> {50 override fun test(value: File) =51 MatcherResult(52 value.exists(),53 { "File $value should exist" },54 { "File $value should not exist" }55 )56}57infix fun File.shouldContainFile(name: String) = this should containFile(name)58infix fun File.shouldNotContainFile(name: String) = this shouldNot containFile(name)59fun containFile(name: String) = object : Matcher<File> {60 override fun test(value: File): MatcherResult {61 val contents = value.safeList()62 val passed = value.isDirectory && contents.contains(name)63 return MatcherResult(64 passed,65 { "Directory $value should contain a file with filename $name (detected ${contents.size} other files)" },66 { "Directory $value should not contain a file with filename $name" }67 )68 }69}70fun File.shouldBeSymbolicLink() = this.toPath() should beSymbolicLink()71fun File.shouldNotBeSymbolicLink() = this.toPath() shouldNot beSymbolicLink()72infix fun File.shouldHaveParent(name: String) = this should haveParent(name)73infix fun File.shouldNotHaveParent(name: String) = this shouldNot haveParent(name)74fun haveParent(name: String) = object : Matcher<File> {75 private fun isParentEqualExpected(parent: File?): Boolean =76 parent != null && (parent.name == name || isParentEqualExpected(parent.parentFile))77 override fun test(value: File) = MatcherResult(78 isParentEqualExpected(value.parentFile),79 { "File $value should have parent $name" },80 { "File $value should not have parent $name" }81 )82}83fun File.shouldBeADirectory() = this should aDirectory()84fun File.shouldNotBeADirectory() = this shouldNot aDirectory()85fun aDirectory(): Matcher<File> = object : Matcher<File> {86 override fun test(value: File): MatcherResult = MatcherResult(87 value.isDirectory,88 { "File $value should be a directory" },89 { "File $value should not be a directory" }90 )91}92fun File.shouldBeAFile() = this should aFile()93fun File.shouldNotBeAFile() = this shouldNot aFile()94fun aFile(): Matcher<File> = object : Matcher<File> {95 override fun test(value: File): MatcherResult =96 MatcherResult(97 value.isFile,98 { "File $value should be a file" },99 { "File $value should not be a file" })100}101infix fun File.shouldBeSmaller(other: Path) = this should beSmaller(other.toFile())102infix fun File.shouldBeSmaller(other: File) = this should beSmaller(other)103infix fun File.shouldNotBeSmaller(other: Path) = this shouldNot beSmaller(other.toFile())104infix fun File.shouldNotBeSmaller(other: File) = this shouldNot beSmaller(other)105fun beSmaller(other: File): Matcher<File> = object : Matcher<File> {106 override fun test(value: File): MatcherResult {107 val sizea = value.length()108 val sizeb = other.length()109 return MatcherResult(110 value.length() < other.length(),111 { "File $value ($sizea bytes) should be smaller than $other ($sizeb bytes)" },112 { "File $value ($sizea bytes) should not be smaller than $other ($sizeb bytes)" }113 )114 }115}116infix fun File.shouldBeLarger(other: Path) = this should beLarger(other.toFile())117infix fun File.shouldBeLarger(other: File) = this should beLarger(other)118infix fun File.shouldNotBeLarger(other: Path) = this shouldNot beLarger(other.toFile())119infix fun File.shouldNotBeLarger(other: File) = this shouldNot beLarger(other)120fun beLarger(other: File): Matcher<File> = object : Matcher<File> {121 override fun test(value: File): MatcherResult {122 val sizea = value.length()123 val sizeb = other.length()124 return MatcherResult(125 value.length() > other.length(),126 { "File $value ($sizea bytes) should be larger than $other ($sizeb bytes)" },127 { "File $value ($sizea bytes) should not be larger than $other ($sizeb bytes)" }128 )129 }130}131fun File.shouldBeCanonical() = this should beCanonicalPath()132fun File.shouldNotBeCanonical() = this shouldNot beCanonicalPath()133fun beCanonicalPath(): Matcher<File> = object : Matcher<File> {134 override fun test(value: File): MatcherResult = MatcherResult(135 value.canonicalPath == value.path,136 { "File $value should be canonical" },137 { "File $value should not be canonical" }138 )139}140fun File.shouldBeAbsolute() = this should beAbsolute()141fun File.shouldNotBeAbsolute() = this shouldNot beAbsolute()142fun beAbsolute(): Matcher<File> = object : Matcher<File> {143 override fun test(value: File): MatcherResult =144 MatcherResult(145 value.isAbsolute,146 { "File $value should be absolute" },147 { "File $value should not be absolute" })148}149fun File.shouldBeRelative() = this should beRelative()150fun File.shouldNotBeRelative() = this shouldNot beRelative()151fun beRelative(): Matcher<File> = object : Matcher<File> {152 override fun test(value: File): MatcherResult =153 MatcherResult(154 !value.isAbsolute,155 { "File $value should be relative" },156 { "File $value should not be relative" })157}158infix fun File.shouldHaveFileSize(size: Long) = this should haveFileSize(size)159infix fun File.shouldNotHaveFileSize(size: Long) = this shouldNot haveFileSize(size)160fun haveFileSize(size: Long): Matcher<File> = object : Matcher<File> {161 override fun test(value: File): MatcherResult = MatcherResult(162 value.length() == size,163 { "File $value should have size $size" },164 { "File $value should not have size $size" }165 )166}167fun File.shouldBeWriteable() = this should beWriteable()168fun File.shouldNotBeWriteable() = this shouldNot beWriteable()169fun beWriteable(): Matcher<File> = object : Matcher<File> {170 override fun test(value: File): MatcherResult =171 MatcherResult(172 value.canWrite(),173 { "File $value should be writeable" },174 { "File $value should not be writeable" })175}176fun File.shouldBeExecutable() = this should beExecutable()177fun File.shouldNotBeExecutable() = this shouldNot beExecutable()178fun beExecutable(): Matcher<File> = object : Matcher<File> {179 override fun test(value: File): MatcherResult = MatcherResult(180 value.canExecute(),181 { "File $value should be executable" },182 { "File $value should not be executable" }183 )184}185fun File.shouldBeHidden() = this should beHidden()186fun File.shouldNotBeHidden() = this shouldNot beHidden()187fun beHidden(): Matcher<File> = object : Matcher<File> {188 override fun test(value: File): MatcherResult =189 MatcherResult(190 value.isHidden,191 { "File $value should be hidden" },192 { "File $value should not be hidden" })193}194fun File.shouldBeReadable() = this should beReadable()195fun File.shouldNotBeReadable() = this shouldNot beReadable()196fun beReadable(): Matcher<File> = object : Matcher<File> {197 override fun test(value: File): MatcherResult =198 MatcherResult(199 value.canRead(),200 { "File $value should be readable" },201 { "File $value should not be readable" })202}203infix fun File.shouldStartWithPath(path: Path) = this should startWithPath(path)204infix fun File.shouldNotStartWithPath(path: Path) = this shouldNot startWithPath(path)205infix fun File.shouldStartWithPath(prefix: String) = this should startWithPath(prefix)206infix fun File.shouldNotStartWithPath(prefix: String) = this shouldNot startWithPath(prefix)207infix fun File.shouldStartWithPath(file: File) = this should startWithPath(file)208infix fun File.shouldNotStartWithPath(file: File) = this shouldNot startWithPath(file)209infix fun Path.shouldStartWithPath(path: Path) = this.toFile() should startWithPath(path)210infix fun Path.shouldNotStartWithPath(path: Path) = this.toFile() shouldNot startWithPath(path)211fun startWithPath(path: Path) = startWithPath(path.toFile())212fun startWithPath(file: File) = startWithPath(file.toString())213fun startWithPath(prefix: String) = object : Matcher<File> {214 override fun test(value: File): MatcherResult = MatcherResult(215 value.toString().startsWith(prefix),216 { "File $value should start with $prefix" },217 { "File $value should not start with $prefix" }218 )219}220infix fun File.shouldHaveSameStructureAs(file: File) {221 this.shouldHaveSameStructureAs(file) { _, _ -> false }222}223fun File.shouldHaveSameStructureAs(224 file: File,225 compare: (expect: File, actual: File) -> Boolean,226) {227 val expectFiles = this.walkTopDown().toList()228 val actualFiles = file.walkTopDown().toList()229 val expectParentPath = this.path230 val actualParentPath = file.path231 expectFiles shouldBeSameSizeAs actualFiles232 expectFiles.zip(actualFiles) { expect, actual ->233 when {234 compare(expect, actual) -> {}235 expect.isDirectory -> actual.shouldBeADirectory()236 expect.isFile -> {237 expect.path.removePrefix(expectParentPath)238 .shouldBe(actual.path.removePrefix(actualParentPath))239 }240 else -> error("There is an unexpected error analyzing file trees")241 }242 }243}244fun File.shouldHaveSameStructureAs(245 file: File,246 filterLhs: (File) -> Boolean = { false },247 filterRhs: (File) -> Boolean = { false },248) {249 this.shouldHaveSameStructureAs(file) { expect, actual ->250 filterLhs(expect) || filterRhs(actual)251 }252}253infix fun File.shouldHaveSameStructureAndContentAs(file: File) {254 this.shouldHaveSameStructureAndContentAs(file) { _, _ -> false }255}256fun File.shouldHaveSameStructureAndContentAs(257 file: File,258 compare: (expect: File, actual: File) -> Boolean,259) {260 val expectFiles = this.walkTopDown().toList()261 val actualFiles = file.walkTopDown().toList()262 val expectParentPath = this.path263 val actualParentPath = file.path264 expectFiles shouldBeSameSizeAs actualFiles265 expectFiles.zip(actualFiles) { expect, actual ->266 when {267 compare(expect, actual) -> {}268 expect.isDirectory -> actual.shouldBeADirectory()269 expect.isFile -> {270 expect.path.removePrefix(expectParentPath)271 .shouldBe(actual.path.removePrefix(actualParentPath))272 expect.shouldHaveSameContentAs(actual)273 }274 else -> error("There is an unexpected error analyzing file trees")275 }276 }277}278fun File.shouldHaveSameStructureAndContentAs(279 file: File,280 filterLhs: (File) -> Boolean = { false },281 filterRhs: (File) -> Boolean = { false },282) {283 this.shouldHaveSameStructureAndContentAs(file) { expect, actual ->284 filterLhs(expect) || filterRhs(actual)285 }286}...
paths.kt
Source:paths.kt
1package io.kotest.matchers.paths2import io.kotest.matchers.Matcher3import io.kotest.matchers.MatcherResult4import io.kotest.matchers.file.beLarger5import io.kotest.matchers.file.beEmptyDirectory6import io.kotest.matchers.file.containNFiles7import io.kotest.matchers.should8import io.kotest.matchers.shouldBe9import io.kotest.matchers.shouldNot10import io.kotest.matchers.shouldNotBe11import java.io.File12import java.nio.file.Files13import java.nio.file.Path14import kotlin.streams.toList15infix fun Path.shouldStartWithPath(file: File) = this should startWithPath(file)16infix fun Path.shouldNotStartWithPath(file: File) = this shouldNot startWithPath(file)17infix fun Path.shouldStartWithPath(prefix: String) = this should startWithPath(prefix)18infix fun Path.shouldNotStartWithPath(prefix: String) = this shouldNot startWithPath(prefix)19infix fun Path.shouldStartWithPath(path: Path) = this should startWithPath(path)20infix fun Path.shouldNotStartWithPath(path: Path) = this shouldNot startWithPath(path)21fun startWithPath(path: Path) = startWithPath(path.toString())22fun startWithPath(file: File) = startWithPath(file.toPath())23fun startWithPath(prefix: String) = object : Matcher<Path> {24 override fun test(value: Path): MatcherResult = MatcherResult(25 value.toString().startsWith(prefix),26 { "Path $value should start with $prefix" },27 { "Path $value should not start with $prefix" })28}29fun Path.shouldExist() = this should exist()30fun Path.shouldNotExist() = this shouldNot exist()31fun exist() = object : Matcher<Path> {32 override fun test(value: Path) =33 MatcherResult(34 Files.exists(value),35 { "Path $value should exist" },36 { "Path $value should not exist" })37}38infix fun Path.shouldHaveFileSize(size: Long) = this should haveFileSize(size)39infix fun Path.shouldNotHaveFileSize(size: Long) = this shouldNot haveFileSize(size)40fun haveFileSize(size: Long): Matcher<Path> = object : Matcher<Path> {41 override fun test(value: Path): MatcherResult = MatcherResult(42 Files.size(value) == size,43 { "Path $value should have size $size" },44 { "Path $value should not have size $size" })45}46fun Path.shouldBeADirectory() = this should aDirectory()47fun Path.shouldNotBeADirectory() = this shouldNot aDirectory()48fun aDirectory(): Matcher<Path> = object : Matcher<Path> {49 override fun test(value: Path): MatcherResult = MatcherResult(50 Files.isDirectory(value),51 { "File $value should be a directory" },52 { "File $value should not be a directory" })53}54fun Path.shouldBeAFile() = this should aFile()55fun Path.shouldNotBeAFile() = this shouldNot aFile()56fun aFile(): Matcher<Path> = object : Matcher<Path> {57 override fun test(value: Path): MatcherResult = MatcherResult(58 !Files.isDirectory(value),59 { "File $value should be a directory" },60 { "File $value should not be a directory" })61}62fun Path.shouldBeAbsolute() = this should beAbsolute()63fun Path.shouldNotBeAbsolute() = this shouldNot beAbsolute()64fun beAbsolute(): Matcher<Path> = object : Matcher<Path> {65 override fun test(value: Path): MatcherResult =66 MatcherResult(67 value.isAbsolute,68 { "Path $value should be absolute" },69 { "Path $value should not be absolute" })70}71fun Path.shouldBeRelative() = this should beRelative()72fun Path.shouldNotBeRelative() = this shouldNot beRelative()73fun beRelative(): Matcher<Path> = object : Matcher<Path> {74 override fun test(value: Path): MatcherResult =75 MatcherResult(76 !value.isAbsolute,77 { "Path $value should be relative" },78 { "Path $value should not be relative" })79}80fun Path.shouldBeReadable() = this should beReadable()81fun Path.shouldNotBeReadable() = this shouldNot beReadable()82fun beReadable(): Matcher<Path> = object : Matcher<Path> {83 override fun test(value: Path): MatcherResult =84 MatcherResult(85 Files.isReadable(value),86 { "Path $value should be readable" },87 { "Path $value should not be readable" }88 )89}90fun Path.shouldBeWriteable() = this should beWriteable()91fun Path.shouldNotBeWriteable() = this shouldNot beWriteable()92fun beWriteable(): Matcher<Path> = object : Matcher<Path> {93 override fun test(value: Path): MatcherResult =94 MatcherResult(95 Files.isWritable(value),96 { "Path $value should be writeable" },97 { "Path $value should not be writeable" }98 )99}100fun Path.shouldBeExecutable() = this should beExecutable()101fun Path.shouldNotBeExecutable() = this shouldNot beExecutable()102fun beExecutable(): Matcher<Path> = object : Matcher<Path> {103 override fun test(value: Path): MatcherResult = MatcherResult(104 Files.isExecutable(value),105 { "Path $value should be executable" },106 { "Path $value should not be executable" }107 )108}109infix fun Path.shouldContainNFiles(n: Int) = this.toFile() shouldBe containNFiles(n)110infix fun Path.shouldNotContainNFiles(n: Int) = this.toFile() shouldNotBe containNFiles(n)111@Deprecated(message ="checks if a directory is empty. Deprecated since 4.3.", replaceWith = ReplaceWith("shouldBeEmptyDirectory()"))112fun Path.shouldBeNonEmptyDirectory() = this.toFile() shouldNot beEmptyDirectory()113@Deprecated(message ="checks if a directory is not empty. Deprecated since 4.3.", replaceWith = ReplaceWith("shouldBeNonEmptyDirectory()"))114fun Path.shouldNotBeNonEmptyDirectory() = this.toFile() should beEmptyDirectory()115fun Path.shouldBeEmptyDirectory() = this.toFile() should beEmptyDirectory()116fun Path.shouldNotBeEmptyDirectory() = this.toFile() shouldNot beEmptyDirectory()117fun Path.shouldBeHidden() = this should beHidden()118fun Path.shouldNotBeHidden() = this shouldNot beHidden()119fun beHidden(): Matcher<Path> = object : Matcher<Path> {120 override fun test(value: Path): MatcherResult =121 MatcherResult(122 Files.isHidden(value),123 { "Path $value should be hidden" },124 { "Path $value should not be hidden" })125}126fun Path.shouldBeCanonical() = this should beCanonicalPath()127fun Path.shouldNotBeCanonical() = this shouldNot beCanonicalPath()128fun beCanonicalPath(): Matcher<Path> = object : Matcher<Path> {129 override fun test(value: Path): MatcherResult = MatcherResult(130 value.toFile().canonicalPath == value.toFile().path,131 { "File $value should be canonical" },132 { "File $value should not be canonical" })133}134infix fun Path.shouldContainFile(name: String) = this should containFile(name)135infix fun Path.shouldNotContainFile(name: String) = this shouldNot containFile(name)136fun containFile(name: String) = object : Matcher<Path> {137 override fun test(value: Path): MatcherResult {138 val contents = Files.list(value).map { it.fileName.toString() }.toList()139 val passed = Files.isDirectory(value) && contents.contains(name)140 return MatcherResult(141 passed,142 { "Directory $value should contain a file with filename $name (detected ${contents.size} other files)" },143 { "Directory $value should not contain a file with filename $name" })144 }145}146infix fun Path.shouldBeLarger(other: Path) = this.toFile() should beLarger(other.toFile())147infix fun Path.shouldBeLarger(other: File) = this.toFile() should beLarger(other)148infix fun Path.shouldNotBeLarger(other: Path) = this.toFile() shouldNot beLarger(other.toFile())149infix fun Path.shouldNotBeLarger(other: File) = this.toFile() shouldNot beLarger(other)150fun beLarger(other: Path): Matcher<Path> = object : Matcher<Path> {151 override fun test(value: Path): MatcherResult {152 val sizea = Files.size(value)153 val sizeb = Files.size(other)154 return MatcherResult(155 sizea > sizeb,156 { "Path $value ($sizea bytes) should be larger than $other ($sizeb bytes)" },157 { "Path $value ($sizea bytes) should not be larger than $other ($sizeb bytes)"})158 }159}160infix fun Path.shouldBeSmaller(other: Path) = this should beSmaller(other)161infix fun Path.shouldBeSmaller(other: File) = this should beSmaller(other.toPath())162infix fun Path.shouldNotBeSmaller(other: Path) = this shouldNot beSmaller(other)163infix fun Path.shouldNotBeSmaller(other: File) = this shouldNot beSmaller(other.toPath())164fun beSmaller(other: Path): Matcher<Path> = object : Matcher<Path> {165 override fun test(value: Path): MatcherResult {166 val sizea = Files.size(value)167 val sizeb = Files.size(other)168 return MatcherResult(169 sizea < sizeb,170 { "Path $value ($sizea bytes) should be smaller than $other ($sizeb bytes)" },171 { "Path $value ($sizea bytes) should not be smaller than $other ($sizeb bytes)" })172 }173}174infix fun Path.shouldContainFileDeep(name: String) = this should containFileDeep(name)175infix fun Path.shouldNotContainFileDeep(name: String) = this shouldNot containFileDeep(name)176fun containFileDeep(name: String): Matcher<Path> = object : Matcher<Path> {177 private fun fileExists(dir: Path): Boolean {178 val contents = Files.list(dir).toList()179 val (dirs, files) = contents.partition { Files.isDirectory(it) }180 return files.map { it.fileName.toString() }.contains(name) || dirs.any(::fileExists)181 }182 override fun test(value: Path): MatcherResult = MatcherResult(183 fileExists(value),184 { "Path $name should exist in $value" },185 { "Path $name should not exist in $value" }186 )187}188fun Path.shouldContainFiles(vararg files: String) = this should containFiles(files.asList())189fun Path.shouldNotContainFiles(vararg files: String) = this shouldNot containFiles(files.asList())190fun containFiles(names: List<String>) = object : Matcher<Path> {191 override fun test(value: Path): MatcherResult {192 val files = Files.list(value).toList().map { it.fileName.toString() }193 val existingFiles = names.intersect(files)194 val nonExistingFiles = names.subtract(existingFiles)195 return MatcherResult(196 nonExistingFiles.isEmpty(),197 { buildMessage(value, nonExistingFiles, false) },198 {199 buildMessage(value, existingFiles, true)200 })201 }202 private fun buildMessage(path: Path, fileList: Set<String>, isNegative: Boolean): String {203 val fileString = if (fileList.size > 1) "Files" else "File"204 val negativeWord = if (isNegative) " not" else ""205 val filesString = fileList.sorted().joinToString(", ")206 return "$fileString $filesString should$negativeWord exist in $path"207 }208}209fun Path.shouldBeSymbolicLink() = this should beSymbolicLink()210fun Path.shouldNotBeSymbolicLink() = this shouldNot beSymbolicLink()211fun beSymbolicLink() = object : Matcher<Path> {212 override fun test(value: Path) = MatcherResult(213 Files.isSymbolicLink(value),214 { "Path $value should be a symbolic link" },215 { "Path $value should not be a symbolic link" }216 )217}218infix fun Path.shouldHaveParent(name: String) = this should haveParent(name)219infix fun Path.shouldNotHaveParent(name: String) = this shouldNot haveParent(name)220fun haveParent(name: String) = object : Matcher<Path> {221 private fun isParentEqualExpected(parent: Path?): Boolean {222 if (parent == null) return false223 return parent.fileName?.toString() == name || isParentEqualExpected(parent.parent)224 }225 override fun test(value: Path) = MatcherResult(226 isParentEqualExpected(value.parent),227 { "Path $value should have parent $name" },228 { "Path $value should not have parent $name" }229 )230}...
Tests.kt
Source:Tests.kt
1package org.danilopianini.gradle.git.hooks.test2import com.uchuhimo.konf.Config3import com.uchuhimo.konf.source.yaml4import io.github.classgraph.ClassGraph5import io.kotest.core.spec.style.StringSpec6import io.kotest.matchers.file.shouldBeAFile7import io.kotest.matchers.file.shouldExist8import io.kotest.matchers.shouldBe9import io.kotest.matchers.string.shouldContain10import org.gradle.internal.hash.Hashing11import org.gradle.internal.impldep.org.junit.rules.TemporaryFolder12import org.gradle.testkit.runner.BuildResult13import org.gradle.testkit.runner.GradleRunner14import org.gradle.testkit.runner.TaskOutcome15import org.slf4j.LoggerFactory16import java.io.File17import java.util.concurrent.TimeUnit18import java.util.regex.Pattern19class Tests : StringSpec(20 {21 val pluginClasspathResource = ClassLoader.getSystemClassLoader()22 .getResource("plugin-classpath.txt")23 ?: throw IllegalStateException("Did not find plugin classpath resource, run \"testClasses\" build task.")24 val classpath = pluginClasspathResource.openStream().bufferedReader().use { reader ->25 reader.readLines().map { File(it) }26 }27 val scan = ClassGraph()28 .enableAllInfo()29 .acceptPackages(Tests::class.java.`package`.name)30 .scan()31 scan.getResourcesWithLeafName("test.yaml")32 .flatMap {33 log.debug("Found test list in $it")34 val yamlFile = File(it.classpathElementFile.absolutePath + "/" + it.path)35 val testConfiguration = Config {36 addSpec(Root)37 }.from.yaml.inputStream(it.open())38 testConfiguration[Root.tests].map { it to yamlFile.parentFile }39 }40 .forEach { (test, location) ->41 log.debug("Test to be executed: $test from $location")42 val testFolder = folder {43 location.copyRecursively(this.root)44 }45 log.debug("Test has been copied into $testFolder and is ready to get executed")46 test.description {47 val result = GradleRunner.create()48 .withProjectDir(testFolder.root)49 .withPluginClasspath(classpath)50 .withArguments(test.configuration.tasks + test.configuration.options)51 .run { if (test.expectation.failure.isEmpty()) build() else buildAndFail() }52 println(result.tasks)53 println(result.output)54 test.expectation.output_contains.forEach {55 result.output shouldContain it56 }57 test.expectation.success.forEach {58 result.outcomeOf(it) shouldBe TaskOutcome.SUCCESS59 }60 test.expectation.failure.forEach {61 result.outcomeOf(it) shouldBe TaskOutcome.FAILED62 }63 test.expectation.file_exists.forEach {64 val file = File("${testFolder.root.absolutePath}/${it.name}").apply {65 shouldExist()66 shouldBeAFile()67 }68 it.validate(file)69 }70 test.expectation.post_run_script.takeIf { it.isNotEmpty() }?.also { postRuns ->71 findShell()?.also { shell ->72 postRuns.forEach { postRun ->73 val hash = Hashing.sha512().hashString(postRun)74 val fileName = "post-run-$hash.sh"75 with(File(testFolder.root, fileName)) {76 writeText(postRun)77 setExecutable(true)78 }79 val process = ProcessBuilder()80 .directory(testFolder.root)81 .command(shell, fileName)82 .start()83 val finished = process.waitFor(10, TimeUnit.SECONDS)84 finished shouldBe true85 log.debug(process.inputStream.bufferedReader().use { it.readText() })86 process.exitValue() shouldBe 087 }88 } ?: log.warn(89 "No known Unix shell available on this system! Tests with scripts won't be executed"90 )91 }92 }93 }94 }95) {96 companion object {97 val log = LoggerFactory.getLogger(Tests::class.java)98 private val shells = listOf("sh", "bash", "zsh", "fish", "csh", "ksh")99 private fun BuildResult.outcomeOf(name: String) = task(":$name")100 ?.outcome101 ?: throw IllegalStateException("Task $name was not present among the executed tasks")102 private fun folder(closure: TemporaryFolder.() -> Unit) = TemporaryFolder().apply {103 create()104 closure()105 }106 private fun findShell(): String? {107 val paths = System.getenv("PATH").split(Regex(Pattern.quote(File.pathSeparator)))108 return shells.find { shell ->109 paths.any { path ->110 val executable = File(File(path), shell)111 executable.exists() && executable.canExecute()112 }113 }114 }115 }116}...
IOSpec.kt
Source:IOSpec.kt
1package com.github.rougsig.core2import io.kotest.core.datatest.forAll3import io.kotest.core.spec.style.FunSpec4import io.kotest.matchers.file.shouldBeADirectory5import io.kotest.matchers.file.shouldBeAFile6import io.kotest.matchers.file.shouldExist7import io.kotest.matchers.shouldBe8import kotlinx.coroutines.runBlocking9import java.io.ByteArrayInputStream10import java.io.ByteArrayOutputStream11import java.io.File12import java.io.PrintStream13import java.nio.file.Paths14abstract class IOSpec(15 private val resourcesPath: String,16 private val testFun: IOEnvironment.() -> Unit17) : FunSpec({18 val projectRoot = File(".").absoluteFile.parent19 val resourcesDir = Paths.get(projectRoot, "src/test/resources", resourcesPath).toFile()20 context("File IO tests") {21 val inputDir = File("${resourcesDir.absoluteFile}/input")22 inputDir.shouldExist()23 inputDir.shouldBeADirectory()24 val outputDir = File("${resourcesDir.absoluteFile}/output")25 outputDir.shouldExist()26 val testNames = inputDir.listFiles()27 .map { it.nameWithoutExtension.removePrefix("input") }28 forAll(testNames) { testName: String ->29 val input = File("${inputDir.absoluteFile}/input${testName}.txt")30 input.shouldExist()31 input.shouldBeAFile()32 val output = File("${outputDir.absoluteFile}/output${testName}.txt")33 output.shouldExist()34 output.shouldBeAFile()35 val baos = ByteArrayOutputStream()36 runBlocking {37 // Set the same as hackerrank timeout limit38 // https://www.hackerrank.com/environment/languages39 withTimeoutOrInterrupt(4000L) {40 IOEnvironment(ByteArrayInputStream(input.readBytes()), PrintStream(baos)).testFun()41 }42 }43 val actual = baos.toString().trim().trimIndent()44 val expected = output.readText().trim().trimIndent()45 actual.shouldBe(expected)46 }47 }48})...
ScenarioTest.kt
Source:ScenarioTest.kt
1package uk.nhs.riskscore2import io.kotest.core.spec.style.StringSpec3import io.kotest.matchers.doubles.shouldBeLessThan4import io.kotest.matchers.paths.*5import uk.nhs.riskscore.RiskScoreCalculatorConfiguration.Companion.exampleConfiguration6import uk.nhs.support.InstanceName7import uk.nhs.support.RiskScoreResultsCSVDecoder8import uk.nhs.support.ScanInstanceCSVDecoder9import java.nio.file.Paths10import kotlin.math.abs11internal class ScenarioTest: StringSpec({12 "computed riskscores are within 5% of the python computed riskscores" {13 val rootPath = Paths.get("src","test","resources", "TestData").toAbsolutePath()14 val expectedRiskScoresPath = rootPath.resolve("pythonRiskScores.csv")15 expectedRiskScoresPath.shouldBeAFile()16 val scanInstanceDirectoryPath = Paths.get(rootPath.toString(), "ScanInstances")17 scanInstanceDirectoryPath.shouldBeADirectory()18 val calculator = RiskScoreCalculator(exampleConfiguration)19 val expectedScores = RiskScoreResultsCSVDecoder.decode(expectedRiskScoresPath.toFile().path)20 scanInstanceDirectoryPath.toFile().listFiles()!!.forEach { scanInstanceFile ->21 val instances = ScanInstanceCSVDecoder.decode(scanInstanceFile.path)22 val actualScore = calculator.calculate(instances)23 val expectedScore = expectedScores[InstanceName(scanInstanceFile.name)]!!.score24 abs(expectedScore - actualScore) shouldBeLessThan (actualScore * 0.05)25 }26 }27})...
Path.shouldBeAFile
Using AI Code Generation
1Path( "C:\\test\\test.txt" ).shouldBeAFile()2Path( "C:\\test" ).shouldBeADirectory()3Path( "test.txt" ).shouldBeRelative()4Path( "C:\\test\\test.txt" ).shouldBeAbsolute()5Path( "C:\\test\\test.txt" ).shouldHaveExtension( "txt" )6Path( "C:\\test\\.hidden.txt" ).shouldBeHidden()7Path( "C:\\test\\test.txt" ).shouldBeReadable()8Path( "C:\\test\\test.txt" ).shouldBeWritable()9Path( "C:\\test\\test.txt" ).shouldBeExecutable()10Path( "C:\\test\\test.txt" ).shouldBeSymbolicLink()11Path( "C:\\test\\test.txt" ).shouldBeRegularFile()12Path( "C:\\test\\test.txt" ).shouldBeSameFileAs( "C:\\test\\test.txt" )13Path( "C:\\test\\test.txt" ).shouldBeReadable()14Path( "C:\\test\\test.txt" ).shouldBeWritable()15Path(
Path.shouldBeAFile
Using AI Code Generation
1 import io.kotest.matchers.paths.shouldBeAFile2 import java.nio.file.Paths3 import org.junit.jupiter.api.Test4 import org.junit.jupiter.api.assertThrows5 import org.junit.jupiter.api.condition.EnabledOnOs6 import org.junit.jupiter.api.condition.OS7 import org.junit.jupiter.api.io.TempDir8 import java.io.File9 import java.io.IOException10 import java.nio.file.Files11 import java.nio.file.Path12 import java.nio.file.StandardCopyOption13 import java.nio.file.StandardOpenOption14 import kotlin.io.path.createDirectory15 import kotlin.io.path.createFile16 import kotlin.io.path.exists17 import kotlin.io.path.isDirectory18 import kotlin.io.path.isRegularFile19 import kotlin.io.path.listDirectoryEntries20 import kotlin.io.path.name21 import kotlin.io.path.notExists22 import kotlin.io.path.readText23 import kotlin.io.path.toPath24 import kotlin.test.assertTrue25 import kotlin.test.assertFalse26 import kotlin.test.assertEquals27 import kotlin.test.assertFailsWith28 import kotlin.test.assertNotEquals29 import kotlin.test.assertNotNull30 import kotlin.test.assertNull31 import kotlin.test.assertSame32 import kotlin.test.assertNotSame33 import kotlin.test.expect34 import kotlin.test.asserter35 import kotlin.test.assertAll36 import kotlin.test.assertFails37 import kotlin.test.assertFailsWith38 import kotlin.test.fail39 import org.junit.jupiter.api.Assertions.assertThrows40 import org.junit.jupiter.api.Assertions.assertDoesNotThrow41 import org.junit.jupiter.api.Assertions.assertEquals42 import org.junit.jupiter.api.Assertions.assertNotEquals43 import org.junit.jupiter.api.Assertions.assertNotNull44 import org.junit.jupiter.api.Assertions.assertNull45 import org.junit.jupiter.api.Assertions.assertSame46 import org.junit.jupiter.api.Assertions.assertNotSame47 import org.junit.jupiter.api.Assertions.assertTrue48 import org.junit.jupiter.api.Assertions.assertFalse49 import org.junit.jupiter.api.Assertions.assertAll50 import org.junit.jupiter.api.Assertions.assertTimeout51 import org.junit.jupiter.api.Assertions.assertTimeoutPreemptively52 import org.junit.jupiter.api.Assertions.assertThrows53 import org.junit.jupiter.api.Assertions.assertDoesNotThrow54 import org.junit.jupiter.api.Assertions.fail55 import org.junit.jupiter.api.Assertions.assertArrayEquals56 import org.junit.jupiter.api.Assertions.assertArrayNotEquals57 import org.junit.jupiter.api.Assertions.assertLinesMatch58 import org
Path.shouldBeAFile
Using AI Code Generation
1Path("src/test/resources/testFile.txt").shouldBeAFile()2Path("src/test/resources/testFolder").shouldBeADirectory()3Path("src/test/resources/testFolder").shouldContainFile("testFile.txt")4Path("src/test/resources/testFolder").shouldContainDirectory("testFolder")5Path("src/test/resources/testFile.txt").shouldHaveExtension("txt")6Path("src/test/resources/testFile.txt").shouldHaveFileName("testFile.txt")7Path("src/test/resources/testFile.txt").shouldHaveName("testFile")8Path("src/test/resources/testFile.txt").shouldHaveParent("resources")9Path("src/test/resources/testFile.txt").shouldHaveSize(17)10Path("src/test/resources/testFile.txt").shouldHaveSameTextualContentAs("src/test/resources/testFile.txt")11Path("src/test/resources/testFile.txt").shouldHaveSameBinaryContentAs("src/test/resources/testFile.txt")12Path("src/test/resources/testFile.txt").shouldBeRelative()
Path.shouldBeAFile
Using AI Code Generation
1fun `should be a file`() {2 Path("src/test/kotlin/should_be_a_file.txt").shouldBeAFile()3}4fun `should be a directory`() {5 Path("src/test/kotlin").shouldBeADirectory()6}7fun `should be relative`() {8 Path("src/test/kotlin").shouldBeRelative()9}10fun `should be absolute`() {11 Path("src/test/kotlin").shouldBeAbsolute()12}13fun `should have the same textual content as`() {14 Path("src/test/kotlin/should_have_the_same_textual_content_as.txt").shouldHaveTheSameTextualContentAs(15 Path("src/test/kotlin/should_have_the_same_textual_content_as.txt")16}17fun `should have the same binary content as`() {18 Path("src/test/kotlin/should_have_the_same_binary_content_as.txt").shouldHaveTheSameBinaryContentAs(19 Path("src/test/kotlin/should_have_the_same_binary_content_as.txt")20}21fun `should have the same normalized path as`() {22 Path("src/test/kotlin/should_have_the_same_normalized_path_as.txt").shouldHaveTheSameNormalizedPathAs(23 Path("src/test/kotlin/should_have_the_same_normalized_path_as.txt")24}25fun `should have the same parent path as`() {26 Path("src/test/kotlin/should_have_the_same_parent_path_as.txt").shouldHaveTheSameParentPathAs(27 Path("src/test/kotlin/should_have_the_same_parent_path_as.txt")28}
Path.shouldBeAFile
Using AI Code Generation
1fun `should return true for file`() {2val file = File("src/test/resources/should_be_a_file.txt")3file.shouldBeAFile()4}5fun `should return true for directory`() {6val directory = File("src/test/resources")7directory.shouldBeADirectory()8}9fun `should return true for readable`() {10val file = File("src/test/resources/should_be_readable.txt")11file.shouldBeReadable()12}13fun `should return true for writable`() {14val file = File("src/test/resources/should_be_writable.txt")15file.shouldBeWritable()16}17fun `should return true for executable`() {18val file = File("src/test/resources/should_be_executable.txt")19file.shouldBeExecutable()20}21}
Path.shouldBeAFile
Using AI Code Generation
1 "file should exist" {2 val path = Paths.get("src/test/resources/empty.txt")3 path.shouldBeAFile()4 }5 "directory should exist" {6 val path = Paths.get("src/test/resources")7 path.shouldBeADirectory()8 }9 "file should be readable" {10 val path = Paths.get("src/test/resources/empty.txt")11 path.shouldBeReadable()12 }13 "file should be writable" {14 val path = Paths.get("src/test/resources/empty.txt")15 path.shouldBeWritable()16 }17 "file should be executable" {18 val path = Paths.get("src/test/resources/empty.txt")19 path.shouldBeExecutable()20 }21 "path should be absolute" {22 val path = Paths.get("src/test/resources/empty.txt")23 path.shouldBeAbsolute()24 }25 "path should be relative" {26 val path = Paths.get("src/test/resources/empty.txt")27 path.shouldBeRelative()28 }29 "file should be hidden" {30 val path = Paths.get("src/test/resources/empty.txt")31 path.shouldBeHidden()32 }
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!