Best Kotest code snippet using io.kotest.matchers.paths.paths.Path.shouldExist
GitHubFSIntegTest.kt
Source:GitHubFSIntegTest.kt  
1/*2 * This file is part of bowler-kernel.3 *4 * bowler-kernel is free software: you can redistribute it and/or modify5 * it under the terms of the GNU Lesser General Public License as published by6 * the Free Software Foundation, either version 3 of the License, or7 * (at your option) any later version.8 *9 * bowler-kernel is distributed in the hope that it will be useful,10 * but WITHOUT ANY WARRANTY; without even the implied warranty of11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12 * GNU Lesser General Public License for more details.13 *14 * You should have received a copy of the GNU Lesser General Public License15 * along with bowler-kernel.  If not, see <https://www.gnu.org/licenses/>.16 */17package com.commonwealthrobotics.bowlerkernel.gitfs18import com.commonwealthrobotics.bowlerkernel.authservice.AnonymousCredentialsProvider19import com.commonwealthrobotics.bowlerkernel.util.runAndPrintOutput20import io.kotest.assertions.throwables.shouldThrow21import io.kotest.matchers.collections.shouldContainAll22import io.kotest.matchers.file.shouldExist23import io.kotest.matchers.file.shouldNotExist24import io.kotest.matchers.shouldBe25import kotlinx.coroutines.runBlocking26import org.junit.jupiter.api.Test27import org.junit.jupiter.api.Timeout28import org.junit.jupiter.api.io.TempDir29import java.io.File30import java.nio.file.Path31import java.nio.file.Paths32import java.util.concurrent.TimeUnit33import kotlin.random.Random34@Timeout(value = 30, unit = TimeUnit.SECONDS)35class GitHubFSIntegTest {36    private val orgName = "CommonWealthRobotics"37    private val repoName = "bowler-kernel-test-repo"38    @Test39    fun `test gitUrlToDirectory with git repo`(@TempDir tempDir: File) {40        val expected = Paths.get(tempDir.absolutePath, orgName, repoName)41        val actual = GitHubFS.gitUrlToDirectory(42            tempDir.toPath(),43            testRepoUrlHTTPS44        )45        expected.toString().shouldBe(actual.absolutePath)46    }47    @Test48    fun `cannot clone over http`() {49        runBlocking {50            // Don't use a TempDir because jgit leaves something open so Windows builds fail51            val tmpCachePath = getRandomTempFile()52            val fs = GitHubFS(AnonymousCredentialsProvider, tmpCachePath)53            shouldThrow<UnsupportedOperationException> {54                fs.cloneRepo(testRepoUrlHTTP, "HEAD")55            }56        }57    }58    @Test59    fun `test cloning test repo over https`() {60        runBlocking {61            // Don't use a TempDir because jgit leaves something open so Windows builds fail62            val tmpCachePath = getRandomTempFile()63            val fs = GitHubFS(AnonymousCredentialsProvider, tmpCachePath)64            val repoPath = fs.gitHubCacheDirectory.resolve(orgName).resolve(repoName)65            val files = cloneAndGetFileSet(fs, testRepoUrlHTTPS)66            assertTestRepoContents(files, repoPath)67        }68    }69    @Test70    fun `test pulling in a repo already in the cache`() {71        runBlocking {72            // Don't use a TempDir because jgit leaves something open so Windows builds fail73            val tmpCachePath = getRandomTempFile()74            val fs = GitHubFS(AnonymousCredentialsProvider, tmpCachePath)75            val repoPath = fs.gitHubCacheDirectory.resolve(orgName).resolve(repoName)76            // Start with a cloned repo77            val files = cloneAndGetFileSet(fs, testRepoUrlHTTPS)78            assertTestRepoContents(files, repoPath)79            // Clone again; should pull80            assertTestRepoContents(cloneAndGetFileSet(fs, testRepoUrlHTTPS), repoPath)81        }82    }83    @Test84    fun `test cloning with corrupted git folder`() {85        runBlocking {86            // Don't use a TempDir because jgit leaves something open so Windows builds fail87            val tmpCachePath = getRandomTempFile()88            val fs = GitHubFS(AnonymousCredentialsProvider, tmpCachePath)89            val repoPath = fs.gitHubCacheDirectory.resolve(orgName).resolve(repoName)90            // Make an empty .git directory so it appears corrupted91            repoPath.toFile().apply { mkdirs() }92            Paths.get(repoPath.toString(), ".git").toFile().apply { mkdirs() }93            val files = cloneAndGetFileSet(fs, testRepoUrlHTTPS)94            assertTestRepoContents(files, repoPath)95        }96    }97    @Test98    fun `test cloning with some local changes`() {99        runBlocking {100            // Don't use a TempDir because jgit leaves something open so Windows builds fail101            val tmpCachePath = getRandomTempFile()102            val fs = GitHubFS(AnonymousCredentialsProvider, tmpCachePath)103            val repoPath = fs.gitHubCacheDirectory.resolve(orgName).resolve(repoName)104            // Clone the test repo and make sure it worked -- this is our baseline105            var files = cloneAndGetFileSet(fs, testRepoUrlHTTPS)106            assertTestRepoContents(files, repoPath)107            // Reset the test repo back one commit so that there is something to pull108            runAndPrintOutput(repoPath.toFile(), "git", "reset", "--hard", "HEAD^")109            // Make some changes that will need to be reset110            fs.getFilesInRepo(repoPath.toFile()).forEach { it.deleteRecursively() }111            // Try to clone again. The repo should be reset and then pulled. Because we deleted all the files in the112            // previous commit, git may be able to fast-forward this pull; however, those files will still be deleted. A113            // correct GitFS implementation will reset the repo.114            files = cloneAndGetFileSet(fs, testRepoUrlHTTPS)115            assertTestRepoContents(files, repoPath)116        }117    }118    @Test119    fun `test cloning a different branch than the currently checked out branch`() {120        runBlocking {121            // Don't use a TempDir because jgit leaves something open so Windows builds fail122            val tmpCachePath = getRandomTempFile()123            val fs = GitHubFS(AnonymousCredentialsProvider, tmpCachePath)124            val repoPath = fs.gitHubCacheDirectory.resolve(orgName).resolve(repoName)125            val repoFile = repoPath.toFile()126            fs.cloneRepo(testRepoUrlHTTPS, "master")127            // Checkout a new branch and make some changes128            runAndPrintOutput(repoFile, "git", "checkout", "-b", "new_branch")129            val file1 = repoPath.resolve("fileA.groovy").toFile()130            file1.writeText("2")131            runAndPrintOutput(repoFile, "git", "add", file1.path)132            runAndPrintOutput(repoFile, "git", "commit", "-m", "a")133            // Clone the repo on master again134            fs.cloneRepo(testRepoUrlHTTPS, "master")135            // Ensure that file does not exist136            file1.shouldNotExist()137        }138    }139    @Test140    fun `test deleteCache`(@TempDir tempDir: File) {141        val fs = GitHubFS(AnonymousCredentialsProvider, tempDir.toPath())142        val repoPath = Paths.get(tempDir.absolutePath, orgName, repoName)143        val repo = repoPath.toFile().apply { mkdirs() }144        val fileInRepo = Paths.get(repoPath.toString(), "fileA.txt").toFile().apply {145            writeText("")146        }147        fileInRepo.shouldExist()148        fs.deleteCache()149        fileInRepo.shouldNotExist()150        repo.shouldNotExist()151    }152    private suspend fun cloneAndGetFileSet(fs: GitHubFS, repoURL: String): Set<String> {153        return fs.getFilesInRepo(fs.cloneRepo(repoURL, "master"))154            .map { it.toString() }155            .toSet()156    }157    private fun assertTestRepoContents(files: Set<String>, repoPath: Path) {158        files.shouldContainAll(159            Paths.get(repoPath.toString(), "fileA.txt").toString(),160            Paths.get(repoPath.toString(), "dirA").toString(),161            Paths.get(repoPath.toString(), "dirA", "fileB.txt").toString()162        )163    }164    private fun getRandomTempFile() = Paths.get(165        System.getProperty("java.io.tmpdir"),166        Random.nextBytes(15).joinToString(separator = "").replace("-", "")167    )168    companion object {169        @Suppress("HttpUrlsUsage")170        private const val testRepoUrlHTTP = "http://github.com/CommonWealthRobotics/bowler-kernel-test-repo.git"171        private const val testRepoUrlHTTPS = "https://github.com/CommonWealthRobotics/bowler-kernel-test-repo.git"172    }173}...CandidKtPluginSpec.kt
Source:CandidKtPluginSpec.kt  
1package com.github.seniorjoinu.candid.plugin2import io.kotest.core.spec.IsolationMode3import io.kotest.core.spec.style.FreeSpec4import io.kotest.matchers.file.shouldExist5import io.kotest.matchers.file.shouldNotHaveFileSize6import io.kotest.matchers.shouldBe7import io.kotest.matchers.string.shouldContain8import org.gradle.internal.impldep.org.junit.rules.TemporaryFolder9import org.gradle.testkit.runner.BuildResult10import org.gradle.testkit.runner.GradleRunner11import org.gradle.testkit.runner.TaskOutcome12import java.io.File13import java.io.PrintWriter14import java.nio.file.Paths15import java.util.Locale16/**17 * System under specification: {@link CandidKtPlugin}; strictly speaking this a functional test, although it was added to the unit test source set.18 */19class CandidKtPluginSpec : FreeSpec({20    isolationMode = IsolationMode.InstancePerLeaf21    val didName = "greet"22    val packageName = "tld.d.etc"23    "given a project dir" - {24        val projectDir = TemporaryFolder()25        projectDir.create()26        "and the plugin is applied" - {27            val buildFile = projectDir.newFile("build.gradle")28            buildFile.writeText("""29                plugins {30                    id 'com.github.seniorjoinu.candid'31                }32                candid {33                    sourceSets {34                        test35                    }36                }37            """.trimIndent())38            buildFile.appendText(System.lineSeparator())39            "positive executing 'gradle tasks'" {40                val taskName = "tasks"41                val arguments = listOf(taskName)42                val result = build(projectDir.root, arguments)43                result.task(":$taskName")?.outcome shouldBe TaskOutcome.SUCCESS44                result.output shouldContain "${CANDID_GROUP_NAME.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }} tasks"45                result.output shouldContain "$CANDID_TASK_NAME - Generates Kotlin sources from Candid language files resolved from the 'main' Candid source set."46                result.output shouldContain "generateTestCandid - Generates Kotlin sources from Candid language files resolved from the 'test' Candid source set."47            }48            "positive executing 'gradle help --task generateCandid'" {49                val taskName = "help"50                val arguments = listOf(taskName, "--task", CANDID_TASK_NAME)51                val result = build(projectDir.root, arguments)52                result.task(":$taskName")?.outcome shouldBe TaskOutcome.SUCCESS53                result.output shouldContain "Detailed task information for $CANDID_TASK_NAME"54                result.output shouldContain "Path${System.lineSeparator()}     :$CANDID_TASK_NAME"55                result.output shouldContain "Description${System.lineSeparator()}     Generates Kotlin sources from Candid language files resolved from the 'main' Candid source set."56                result.output shouldContain "Group${System.lineSeparator()}     $CANDID_GROUP_NAME"57            }58            "positive executing 'gradle generateCandid' with defaults" {59                val didFile = createDidFile(projectDir.root, didName, "src", "main", "candid")60                val ktFile = Paths.get(projectDir.root.canonicalPath, "build/$CANDID_DESTINATION_PREFIX_KOTLIN/main", "${didName}.did.kt").toFile()61                val arguments = listOf(CANDID_TASK_NAME, "--info", "--warning-mode", "all")62                val result = build(projectDir.root, arguments)63                result.task(":$CANDID_TASK_NAME")?.outcome shouldBe TaskOutcome.SUCCESS64                ktFile.shouldExist()65                ktFile.shouldNotHaveFileSize(0)66                didFile.delete()67            }68            "positive executing 'gradle generateCandid' with reconfigured destination directory" {69                val didFile = createDidFile(projectDir.root, didName, "src", "main", "candid")70                val ktFile = Paths.get(projectDir.root.canonicalPath, "build/output", packageName.replace('.', '/'), "${didName}.did.kt").toFile()71                buildFile.appendText("""72                    candid {73                        sourceSets.main.candid.destinationDirectory.fileValue(project.file('build/output'))74                        genPackage = "$packageName"75                    }76                """.trimIndent())77                val arguments = listOf(CANDID_TASK_NAME, "--info", "--warning-mode", "all")78                val result = build(projectDir.root, arguments)79                result.task(":$CANDID_TASK_NAME")?.outcome shouldBe TaskOutcome.SUCCESS80                ktFile.shouldExist()81                ktFile.shouldNotHaveFileSize(0)82                didFile.delete()83            }84            "positive executing 'gradle generateCandid' with nested did files under different source directories" {85                val didFile = createDidFile(projectDir.root, didName, "src", "main", "candid", "tld", "d", "etc")86                val otherDidFile = createDidFile(projectDir.root, "other-greet", "src", "other", "candid", "tld", "d", "etc")87                val ktFile = Paths.get(projectDir.root.canonicalPath, "build/$CANDID_DESTINATION_PREFIX_KOTLIN/main", "tld/d/etc", "${didName}.did.kt").toFile()88                val otherKtFile = Paths.get(projectDir.root.canonicalPath, "build/$CANDID_DESTINATION_PREFIX_KOTLIN/main", "tld/d/etc", "other-greet.did.kt").toFile()89                buildFile.appendText("""90                    candid {91                        sourceSets.main.candid.srcDir 'src/other/candid'92                    }93                """.trimIndent())94                val arguments = listOf(CANDID_TASK_NAME, "--info", "--warning-mode", "all")95                val result = build(projectDir.root, arguments)96                result.task(":$CANDID_TASK_NAME")?.outcome shouldBe TaskOutcome.SUCCESS97                ktFile.shouldExist()98                otherKtFile.shouldExist()99                ktFile.shouldNotHaveFileSize(0)100                otherKtFile.shouldNotHaveFileSize(0)101                didFile.delete()102                otherDidFile.delete()103            }104            "positive executing 'gradle generateIntegTestCandid'" {105                val taskName = "generateIntegTestCandid"106                val didFile = createDidFile(projectDir.root, didName, "src", "integTest", "candid")107                val ktFile = Paths.get(projectDir.root.canonicalPath, "build/$CANDID_DESTINATION_PREFIX_KOTLIN/integTest", "${didName}.did.kt").toFile()108                buildFile.appendText("""109                    candid {110                        sourceSets {111                            integTest112                        }113                    }114                """.trimIndent())115                val arguments = listOf(taskName, "--info", "--warning-mode", "all")116                val result = build(projectDir.root, arguments)117                result.task(":$taskName")?.outcome shouldBe TaskOutcome.SUCCESS118                ktFile.shouldExist()119                ktFile.shouldNotHaveFileSize(0)120                didFile.delete()121            }122            buildFile.delete()123        }124        projectDir.delete()125    }126})127fun createDidFile(projectDir: File, didName: String, vararg folderNames: String): File {128    val sourceSetDir = File(projectDir, folderNames.joinToString("/"))129    sourceSetDir.mkdirs()130    val didFile = File(sourceSetDir, "${didName}.did")131    didFile.writeText("""132            service : {133              "greet": (text) -> (text);134            }135        """.trimIndent())136    return didFile137}138fun build(projectDir: File, arguments: List<String>): BuildResult {139    return GradleRunner.create().withProjectDir(projectDir).forwardStdOutput(PrintWriter(System.out)).forwardStdError(PrintWriter(System.err)).withPluginClasspath().withArguments(arguments).build()140}...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}...MetadataGeneration.kt
Source:MetadataGeneration.kt  
1// Copyright 2021 Strixpyrr2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//     http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14package strixpyrr.launchpad.test15import io.kotest.core.spec.style.FunSpec16import io.kotest.matchers.paths.shouldExist17import io.kotest.matchers.shouldBe18import org.gradle.testkit.runner.GradleRunner19import org.gradle.testkit.runner.TaskOutcome20import strixpyrr.launchpad.metadata.fabric.*21import java.nio.file.Path22import kotlin.io.path.*23@OptIn(ExperimentalPathApi::class)24class MetadataGeneration : FunSpec()25{26	private val gradle get() = GradleRunner.create()27	28	private val populatedMetadata =29		FabricMod(30			id = "test",31			version = "3.14",32			environment = Environment.Either,33			entryPoints =34				run()35				{36					val entryPoints =37						listOf(38							EntryPoint(value = "test.package.TestClass::init", adapter = "kotlin")39						)40					41					EntryPoints(42						common = entryPoints,43						server = entryPoints,44						client = entryPoints,45						additional = mapOf("custom" to entryPoints)46					)47				},48			jars = listOf(NestedJar(file = Path("Cookie.jar"))),49			languageAdapters = mapOf(/* Todo */),50			mixins = Mixins(config = Path("mixin.json")),51			depends = mapOf("Dependency" to ">=7.13"),52			recommends = mapOf("Recommended" to ">=7.13"),53			suggests = mapOf("Suggests" to ">=7.13"),54			conflicts = mapOf("Conflicts" to ">=7.13"),55			breaks = mapOf("Breaks" to ">=7.13"),56			name = "Totally descriptive test name.",57			description = "Totally descriptive... description.",58			authors =59				listOf(60					Person(61						"Anonymous",62						ContactInfo(63							additional = mapOf("discord" to "Anonymous#----")64						)65					)66				),67			contributors =68			listOf(69				Person(70					"TotallyNotAnonymous",71					ContactInfo(72						additional = mapOf("discord" to "TotallyNotAnonymous#----")73					)74				)75			),76			contact =77				ContactInfo(78					email = "convincing@email.com",79					issues = "https://github.com/Anonymous/Test/issues",80					sources = "https://github.com/Anonymous/Test"81				),82			license = listOf("All rights reserved"),83			icon = Icon(path = Path.of("icon.png")),84			//custom = mapOf("Boop" to "Ow, that hurt!")85		)86	87	init88	{89		context("Metadata")90		{91			val root = Path("testbed")92			93			context("Generate Populated Metadata")94			{95				test("Fabric")96				{97					val testDirectory = "Generate Populated Metadata/Fabric"98					99					generateBuild(root, testDirectory)100					101					val fabricModJson = root / "build" / "generated-sources" / "fabric-mod-metadata" / "fabric.mod.json"102					103					val build = gradle.withGradleVersion("6.8.3")104									   .withProjectDir(root.toFile())105									   .withPluginClasspath()106									   .withArguments("generateFabricMetadata")107									   .forwardOutput()108									   .build()109					110					val outcome = build.task("generateFabricMetadata")?.outcome111					112					if (outcome != null)113						outcome shouldBe TaskOutcome.SUCCESS114					115					fabricModJson.shouldExist()116				}117			}118		}119	}120	121	private fun generateBuild(root: Path, testDirectory: String)122	{123		if (root.notExists()) root.createDirectory()124		125		resource(path = "/$testDirectory/build.gradle.kts") copyIfNewerTo root / "build.gradle.kts"126		127		resource(path = "/$testDirectory/settings.gradle.kts") copyIfNewerTo root / "settings.gradle.kts"128	}129}...QueueDownloaderTest.kt
Source:QueueDownloaderTest.kt  
1// Copyright 2021 Strixpyrr2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//     http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14package dev.strixpyrr.powerLoomTest15import com.github.ajalt.mordant.terminal.Terminal16import dev.strixpyrr.powerLoom.tasks.QueueDownloader17import dev.strixpyrr.powerLoom.tasks.QueueDownloader.IProgressUpdater18import dev.strixpyrr.powerLoomTest.QueueDownloaderTest.RootPath19import dev.strixpyrr.powerLoomTest.QueueDownloaderTest.SodiumJar20import dev.strixpyrr.powerLoomTest.QueueDownloaderTest.SodiumUrl21import io.kotest.core.spec.style.StringSpec22import io.kotest.matchers.booleans.shouldBeTrue23import io.kotest.matchers.paths.shouldExist24import io.kotest.matchers.shouldBe25import okhttp3.HttpUrl.Companion.toHttpUrl26import kotlin.io.path.Path27import kotlin.io.path.deleteExisting28import kotlin.io.path.div29import kotlin.io.path.name30@Suppress("BlockingMethodInNonBlockingContext")31object QueueDownloaderTest : StringSpec(32{33	"Single download"()34	{35		val directory = Path("$RootPath/singleNonOverwriting")36		37		(directory / SodiumJar).deleteExisting()38		39		val (wasSuccessful, source, code, target) = QueueDownloader.download(40			SodiumUrl.toHttpUrl(),41			directory,42			progress = IProgressUpdater.create(Terminal())43		)44		45		wasSuccessful.shouldBeTrue()46		"$source" shouldBe SodiumUrl47		code      shouldBe 20048		target.shouldExist()49		target.name shouldBe SodiumJar50	}51})52{53	private const val RootPath = "run/downloader"54	55	private const val SodiumJar =56		"sodium-fabric-mc1.17.1-0.3.2+build.7.jar"57	58	private const val SodiumUrl =59		"https://cdn.modrinth.com/data/AANobbMI/versions/mc1.17.1-0.3.2/$SodiumJar"60}...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})...VideoRecordingWebDriverManagerSpec.kt
Source:VideoRecordingWebDriverManagerSpec.kt  
1package org.fluentlenium.example.kotest2import io.github.bonigarcia.wdm.WebDriverManager3import io.kotest.core.spec.Spec4import io.kotest.matchers.paths.shouldExist5import io.kotest.matchers.string.shouldContain6import org.fluentlenium.adapter.kotest.FluentFreeSpec7import org.openqa.selenium.WebDriver8import kotlin.io.path.Path9import kotlin.io.path.createDirectory10import kotlin.io.path.exists11/**12 * This test demonstrates how to use Fluentlenium in combination13 * with a Docker/Chrome container (managed by WebDriverManager)14 * that hosts the browser.15 *16 * check https://github.com/bonigarcia/webdrivermanager#browsers-in-docker17 */18class VideoRecordingWebDriverManagerSpec : FluentFreeSpec() {19    /**20     * directory to save the videos to21     */22    private val videoDirectory = Path("build/videos")23    private val wdm =24        WebDriverManager.chromedriver()25            .browserInDocker()26            .enableVnc()27            .dockerRecordingOutput(videoDirectory)28            .enableRecording()29    override suspend fun beforeSpec(spec: Spec) {30        if (!videoDirectory.exists()) {31            videoDirectory.createDirectory()32        }33        videoDirectory.shouldExist()34    }35    override fun newWebDriver(): WebDriver =36        wdm.create()37    private val SEARCH_TEXT = "FluentLenium"38    init {39        "Title of duck duck go" {40            goTo("https://duckduckgo.com")41            el("#search_form_input_homepage").fill().with(SEARCH_TEXT)42            el("#search_button_homepage").submit()43            await().untilWindow(SEARCH_TEXT)44            window().title() shouldContain SEARCH_TEXT45        }46    }47}...TaskOutputs.kt
Source:TaskOutputs.kt  
1// Copyright 2021 Strixpyrr2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//     http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14package dev.strixpyrr.powerLoomTest15import dev.strixpyrr.powerLoom.metadata.FabricMod16import dev.strixpyrr.powerLoomTest.Gradle.rootPath17import io.kotest.matchers.paths.shouldExist18import okio.buffer19import okio.source20import okio.use21import java.nio.file.Path22import kotlin.io.path.Path23import kotlin.io.path.deleteIfExists24import kotlin.io.path.div25private val MetadataOutputPath =26	Path(27		"build",28		"generated-resources",29		"power-loom-main",30		"fabric.mod.json"31	)32internal fun deleteMetadataOutput(projectRoot: Path) =33	(rootPath / projectRoot / MetadataOutputPath).deleteIfExists()34internal fun metadataOutput(projectRoot: Path) =35	(rootPath / projectRoot / MetadataOutputPath).let()36	{ path ->37		path.shouldExist()38		39		path.source().buffer().use { FabricMod.decode(it) }40	}...Path.shouldExist
Using AI Code Generation
1Path( "/tmp" ).shouldExist()2Path( "/tmp" ).shouldBeReadable()3Path( "/tmp" ).shouldBeWritable()4Path( "/tmp" ).shouldBeExecutable()5Path( "/tmp" ).shouldBeAbsolute()6Path( "/tmp" ).shouldBeRelative()7Path( "/tmp" ).shouldBeDirectory()8Path( "/tmp" ).shouldBeRegularFile()9Path( "/tmp" ).shouldBeSymbolicLink()10Path( "/tmp" ).shouldBeHidden()11Path( "/tmp" ).shouldHaveSameTextualContentAs( "/tmp" )12Path( "/tmp" ).shouldHaveSameBinaryContentAs( "/tmp" )13Path( "/tmp" ).shouldHaveSameContentAs( "/tmp" )14Path( "/tmp" ).shouldHaveParent( "/tmp" )15Path( "/tmp" ).shouldHaveName( "tmp" )16Path( "/tmp" ).shouldHaveExtension( "tmp" )Path.shouldExist
Using AI Code Generation
1Path("some/path").shouldExist()2Path("some/path").shouldNotBeADirectory()3Path("some/path").shouldBeADirectory()4Path("some/path").shouldBeARegularFile()5Path("some/path").shouldHaveExtension("txt")6Path("some/path").shouldHaveFileName("path")7Path("some/path").shouldHaveParent("some")8Path("some/path").shouldHaveParents("some", "path")9Path("some/path").shouldHaveSameTextualContentAs("some/path")10Path("some/path").shouldHaveSameBinaryContentAs("some/path")11Path("some/path").shouldHaveSameContentAs("some/path")12Path("some/path").shouldHaveSize(1)13Path("some/path").shouldHaveTheSameTextualContentAs("some/path")14Path("some/path").shouldHaveTheSameBinaryContentAs("some/path")15Path("some/path").shouldHaveTheSameContentAs("some/path")Path.shouldExist
Using AI Code Generation
1Path("kotest").shouldExist()2Path("kotest").shouldBeAReadableFile()3Path("kotest").shouldBeAReadableDirectory()4Path("kotest").shouldBeAReadableSymbolicLink()5Path("kotest").shouldBeAReadableOther()6Path("kotest").shouldBeAReadableRegularFile()7Path("kotest").shouldBeAReadableSymbolicLink()8Path("kotest").shouldBeAReadableOther()9Path("kotest").shouldBeAReadableRegularFile()10Path("kotest").shouldBeAReadableSymbolicLink()11Path("kotest").shouldBeAReadableOther()12Path("kotest").shouldBeAReadableRegularFile()13Path("kotest").shouldBeAWritableFile()14Path("kotest").shouldBeAWritableDirectory()15Path("kotest").shouldBeAWritableSymbolicLink()Path.shouldExist
Using AI Code Generation
1Path(“/tmp/xyz”).shouldExist()2Path(“/tmp/xyz”).shouldNotBeEmpty()3Path(“/tmp/xyz”).shouldBeReadable()4Path(“/tmp/xyz”).shouldBeWritable()5Path(“/tmp/xyz”).shouldBeExecutable()6Path(“/tmp/xyz”).shouldBeAbsolute()7Path(“/tmp/xyz”).shouldBeRelative()8Path(“/tmp/xyz”).shouldBeHidden()9Path(“/tmp/xyz”).shouldBeRegularFile()10Path(“/tmp/xyz”).shouldBeDirectory()11Path(“/tmp/xyz”).shouldBeSymbolicLink()12Path(“/tmp/xyz”).shouldBeSamePathAs(Path(“/tmp/abc”))13Path(“/tmp/xyz”).shouldHaveSameTextualContentAs(Path(“/tmp/abc”))14Path(“/tmp/xyz”).shouldHaveSameBinaryContentAs(Path(“/tmp/abc”))15Path(“/tmp/xyz”).shouldHaveExtensionPath.shouldExist
Using AI Code Generation
1    import io.kotest.matchers.paths.shouldExist2    import java.nio.file.Path3    import java.nio.file.Paths4    fun main() {5        val path: Path = Paths.get("path/to/file")6        path.shouldExist()7    }8import io.kotest.matchers.paths.shouldExist9import java.io.File10fun main() {11    val file: File = File("path/to/file")12    file.shouldExist()13}14import io.kotest.matchers.paths.shouldNotExist15import java.io.File16fun main() {17    val file: File = File("path/to/file")18    file.shouldNotExist()19}20import io.kotest.matchers.paths.shouldBeADirectory21import java.io.File22fun main() {23    val file: File = File("path/to/directory")24    file.shouldBeADirectory()25}26import io.kotest.matchers.paths.shouldBeAFile27import java.io.File28fun main() {29    val file: File = File("path/to/file")30    file.shouldBeAFile()31}32import io.kotest.matchers.paths.shouldHaveExtension33import java.io.File34fun main() {35    val file: File = File("path/to/file.txt")36    file.shouldHaveExtension("txt")37}38import io.kotest.matchers.paths.shouldHaveName39import java.io.File40fun main() {Path.shouldExist
Using AI Code Generation
1    Path("some/file/path").shouldExist()2    Path("some/file/path").shouldNotExist()3    Path("some/file/path").shouldBeADirectory()4    Path("some/file/path").shouldBeAFile()5    Path("some/file/path").shouldBeRelative()6    Path("some/file/path").shouldBeAbsolute()7    Path("some/file/path").shouldBeReadable()8    Path("some/file/path").shouldBeWritable()9    Path("some/file/path").shouldHaveExtension("txt")10    Path("some/file/path").shouldNotHaveExtension("txt")11    Path("some/file/path").shouldHaveFileName("path")12    Path("some/file/path").shouldNotHaveFileName("path")13    Path("some/file/path").shouldHaveParent("some/file")14    Path("some/file/path").shouldNotHaveParent("some/file")15    Path("some/file/path").shouldHaveTheSameTextualContentAs("some/other/file/path")Path.shouldExist
Using AI Code Generation
1Path(“/some/path”).shouldExist()2Path(“/some/path”).shouldNotExist()3Path(“/some/path”).shouldExist()4Path(“/some/path”).shouldNotExist()5Path(“/some/path”).shouldHaveExtension(“txt”)6Path(“/some/path”).shouldHaveFileName(“file.txt”)7Path(“/some/path”).shouldHaveParent(“/some”)8Path(“/some/path”).shouldHaveName(“path”)9Path(“/some/path”).shouldHaveSameTextualContentAs(“some text”)10Path(“/some/path”).shouldHaveSameBinaryContentAs(“some text”)Path.shouldExist
Using AI Code Generation
1Path("C:\\Users\\mohit\\Desktop\\kotest").shouldExist()2Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldExist()3Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldNotBeADirectory()4Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldHaveExtension("txt")5Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldHaveFileName("test.txt")6Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldHaveParent("C:\\Users\\mohit\\Desktop\\kotest")7Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldHaveName("test")8Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldHaveSize(0)9Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldHaveSameTextualContentAs("C:\\Users\\mohit\\Desktop\\kotest\\test.txt")10Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldHaveSameBinaryContentAs("C:\\Users\\mohit\\Desktop\\kotest\\test.txt")11Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldHaveSameTextualContentAs("C:\\Users\\mohit\\Desktop\\kotest\\test.txt")12Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldHaveSameBinaryContentAs("C:\\Users\\mohit\\Desktop\\kotest\\test.txt")13Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldHaveSameTextualContentAs("C:\\Users\\mohit\\Desktop\\kotest\\test.txt")14Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldHaveSameBinaryContentAs("C:\\Users\\mohit\\Desktop\\kotest\\test.txt")15Path("C:\\Users\\mohit\\Desktop\\kotest\\test.txt").shouldHaveSameTextualContentAs("C:\\Users\\mohLearn 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!!
