Best Kotest code snippet using io.kotest.matchers.file.matchers.File.shouldBeAFile
ManagePlaylistActionTest.kt
Source:ManagePlaylistActionTest.kt  
1/*2 * Copyright 2021 Thibault Seisel3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *     http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package fr.nihilus.music.core.ui.actions17import androidx.core.net.toUri18import androidx.test.ext.junit.runners.AndroidJUnit419import fr.nihilus.music.core.context.AppDispatchers20import fr.nihilus.music.core.database.playlists.Playlist21import fr.nihilus.music.core.database.playlists.PlaylistDao22import fr.nihilus.music.core.database.playlists.PlaylistTrack23import fr.nihilus.music.core.media.MediaId24import fr.nihilus.music.core.media.MediaId.Builder.CATEGORY_ALL25import fr.nihilus.music.core.media.MediaId.Builder.TYPE_ALBUMS26import fr.nihilus.music.core.media.MediaId.Builder.TYPE_ARTISTS27import fr.nihilus.music.core.media.MediaId.Builder.TYPE_PLAYLISTS28import fr.nihilus.music.core.media.MediaId.Builder.TYPE_TRACKS29import fr.nihilus.music.core.test.coroutines.CoroutineTestRule30import fr.nihilus.music.core.test.os.TestClock31import io.kotest.assertions.assertSoftly32import io.kotest.assertions.extracting33import io.kotest.assertions.throwables.shouldThrow34import io.kotest.inspectors.forAll35import io.kotest.inspectors.forNone36import io.kotest.matchers.collections.shouldBeEmpty37import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder38import io.kotest.matchers.collections.shouldHaveSize39import io.kotest.matchers.collections.shouldNotContain40import io.kotest.matchers.file.shouldBeAFile41import io.kotest.matchers.file.shouldContainFile42import io.kotest.matchers.file.shouldNotBeEmpty43import io.kotest.matchers.file.shouldNotExist44import io.kotest.matchers.shouldBe45import kotlinx.coroutines.test.runTest46import org.junit.Rule47import org.junit.rules.RuleChain48import org.junit.rules.TemporaryFolder49import org.junit.runner.RunWith50import java.io.File51import kotlin.test.Test52private const val TEST_TIME = 1585662510L53private const val NEW_PLAYLIST_NAME = "My favorites"54private const val BASE_ICON_URI = "content://fr.nihilus.music.test.provider/icons"55private val SAMPLE_PLAYLIST = Playlist(56    id = 1L,57    title = "Zen",58    created = 0L,59    iconUri = "content://fr.nihilus.music.test.provider/icons/zen.png".toUri()60)61@RunWith(AndroidJUnit4::class)62internal class ManagePlaylistActionTest {63    private val test = CoroutineTestRule()64    private val iconDir = TemporaryFolder()65    @get:Rule66    val rules: RuleChain = RuleChain67        .outerRule(test)68        .around(iconDir)69    private val clock = TestClock(TEST_TIME)70    private val dispatchers = AppDispatchers(test.dispatcher)71    @Test72    fun `When creating a playlist without tracks then record it to PlaylistDao`() = test {73        val dao = InMemoryPlaylistDao()74        val action = ManagePlaylistAction(dao)75        action.createPlaylist(NEW_PLAYLIST_NAME, emptyList())76        val playlists = dao.savedPlaylists77        playlists shouldHaveSize 178        assertSoftly(playlists[0]) {79            title shouldBe NEW_PLAYLIST_NAME80            created shouldBe TEST_TIME81            iconUri shouldBe "content://fr.nihilus.music.test.provider/icons/My_favorites.png".toUri()82        }83        dao.savedTracks.shouldBeEmpty()84    }85    @Test86    fun `When creating a playlist then generate and save its icon`() = test {87        val action = ManagePlaylistAction(InMemoryPlaylistDao())88        action.createPlaylist(NEW_PLAYLIST_NAME, emptyList())89        iconDir.root shouldContainFile "My_favorites.png"90        val iconFile = File(iconDir.root, "My_favorites.png")91        iconFile.shouldBeAFile()92        iconFile.shouldNotBeEmpty()93    }94    @Test95    fun `Given blank name, when creating a playlist then fail with IAE`() = test {96        val action = ManagePlaylistAction(InMemoryPlaylistDao())97        shouldThrow<IllegalArgumentException> {98            action.createPlaylist("", emptyList())99        }100        shouldThrow<IllegalArgumentException> {101            action.createPlaylist("  \t\n\r", emptyList())102        }103    }104    @Test105    fun `When creating a playlist with tracks then record them to PlaylistDao`() = test {106        val dao = InMemoryPlaylistDao()107        val action = ManagePlaylistAction(dao)108        action.createPlaylist(109            name = NEW_PLAYLIST_NAME,110            members = listOf(111                MediaId(TYPE_TRACKS, CATEGORY_ALL, 16L),112                MediaId(TYPE_TRACKS, CATEGORY_ALL, 42L)113            )114        )115        val playlists = dao.savedPlaylists116        playlists shouldHaveSize 1117        val newPlaylist = playlists[0]118        newPlaylist.title shouldBe NEW_PLAYLIST_NAME119        newPlaylist.created shouldBe TEST_TIME120        val tracks = dao.savedTracks121        tracks shouldHaveSize 2122        tracks.forAll { it.playlistId shouldBe newPlaylist.id }123        extracting(tracks) { trackId }.shouldContainExactlyInAnyOrder(16L, 42L)124    }125    @Test126    fun `When creating a playlist with non-track members them fail with IAE`() = test {127        val action = ManagePlaylistAction(InMemoryPlaylistDao())128        for (mediaId in invalidTrackIds()) {129            shouldThrow<IllegalArgumentException> {130                action.createPlaylist(131                    name = NEW_PLAYLIST_NAME,132                    members = listOf(mediaId)133                )134            }135        }136    }137    @Test138    fun `When appending members then add tracks to that playlist`() = test {139        val dao = InMemoryPlaylistDao(initialPlaylists = listOf(SAMPLE_PLAYLIST))140        val action = ManagePlaylistAction(dao)141        action.appendMembers(142            targetPlaylist = MediaId(TYPE_PLAYLISTS, SAMPLE_PLAYLIST.id.toString()),143            members = listOf(144                MediaId(TYPE_TRACKS, CATEGORY_ALL, 16L),145                MediaId(TYPE_TRACKS, CATEGORY_ALL, 42L)146            )147        )148        val tracks = dao.savedTracks149        tracks shouldHaveSize 2150        tracks.forAll { it.playlistId shouldBe SAMPLE_PLAYLIST.id }151        extracting(tracks) { trackId }.shouldContainExactlyInAnyOrder(16L, 42L)152    }153    @Test154    fun `Given invalid target media id, when appending members then fail with IAE`() = test {155        val dao = InMemoryPlaylistDao(initialPlaylists = listOf(SAMPLE_PLAYLIST))156        val action = ManagePlaylistAction(dao)157        val newMemberIds = listOf(158            MediaId(TYPE_TRACKS, CATEGORY_ALL, 16L),159            MediaId(TYPE_TRACKS, CATEGORY_ALL, 42L)160        )161        for (mediaId in invalidPlaylistIds()) {162            shouldThrow<IllegalArgumentException> {163                action.appendMembers(164                    targetPlaylist = mediaId,165                    members = newMemberIds166                )167            }168        }169    }170    @Test171    fun `When deleting a playlist then remove corresponding record from PlaylistDao`() = test {172        val dao = InMemoryPlaylistDao(173            initialPlaylists = listOf(SAMPLE_PLAYLIST),174            initialMembers = listOf(PlaylistTrack(SAMPLE_PLAYLIST.id, 16L))175        )176        val action = ManagePlaylistAction(dao)177        action.deletePlaylist(MediaId(TYPE_PLAYLISTS, SAMPLE_PLAYLIST.id.toString()))178        dao.savedPlaylists shouldNotContain SAMPLE_PLAYLIST179        dao.savedTracks.forNone { it.playlistId shouldBe SAMPLE_PLAYLIST.id }180    }181    @Test182    fun `Given invalid playlist id, when deleting a playlist then fail with IAE`() = test {183        val dao = InMemoryPlaylistDao(initialPlaylists = listOf(SAMPLE_PLAYLIST))184        val action = ManagePlaylistAction(dao)185        for (mediaId in invalidPlaylistIds()) {186            shouldThrow<IllegalArgumentException> {187                action.deletePlaylist(mediaId)188            }189        }190    }191    @Test192    fun `When deleting a playlist then delete its associated icon`() = runTest {193        val dao = InMemoryPlaylistDao(initialPlaylists = listOf(SAMPLE_PLAYLIST))194        val existingIconFile = iconDir.newFile("zen.png")195        val action = ManagePlaylistAction(dao)196        action.deletePlaylist(MediaId(TYPE_PLAYLISTS, SAMPLE_PLAYLIST.id.toString()))197        existingIconFile.shouldNotExist()198    }199    private fun invalidTrackIds() = listOf(200        MediaId(TYPE_TRACKS, CATEGORY_ALL),201        MediaId(TYPE_ALBUMS, "16"),202        MediaId(TYPE_ARTISTS, "42"),203        MediaId(TYPE_PLAYLISTS, "77")204    )205    private fun invalidPlaylistIds() = listOf(206        MediaId(TYPE_TRACKS, CATEGORY_ALL),207        MediaId(TYPE_ALBUMS, "43"),208        MediaId(TYPE_ARTISTS, "89"),209        MediaId(TYPE_PLAYLISTS, "1", 16L)210    )211    private fun ManagePlaylistAction(dao: PlaylistDao) = ManagePlaylistAction(212        playlistDao = dao,213        iconDir = { iconDir.root },214        baseIconUri = BASE_ICON_URI.toUri(),215        clock = clock,216        dispatchers = dispatchers217    )218}...AttachmentServiceTest.kt
Source:AttachmentServiceTest.kt  
1package com.github.njuro.jard.attachment2import com.github.njuro.jard.TEST_ATTACHMENT_AVI3import com.github.njuro.jard.TEST_ATTACHMENT_DOCX4import com.github.njuro.jard.TEST_ATTACHMENT_PNG5import com.github.njuro.jard.TEST_FOLDER_NAME6import com.github.njuro.jard.TestDataRepository7import com.github.njuro.jard.WithContainerDatabase8import com.github.njuro.jard.attachment9import com.github.njuro.jard.attachment.storage.RemoteStorageService10import com.github.njuro.jard.attachmentPath11import com.github.njuro.jard.common.Constants.DEFAULT_THUMBNAIL_EXTENSION12import com.github.njuro.jard.common.Constants.THUMBNAIL_FOLDER_NAME13import com.github.njuro.jard.embedData14import com.github.njuro.jard.metadata15import com.github.njuro.jard.multipartFile16import com.ninjasquad.springmockk.MockkBean17import io.kotest.matchers.booleans.shouldBeTrue18import io.kotest.matchers.file.shouldBeAFile19import io.kotest.matchers.file.shouldBeReadable20import io.kotest.matchers.file.shouldExist21import io.kotest.matchers.file.shouldHaveExtension22import io.kotest.matchers.file.shouldHaveNameWithoutExtension23import io.kotest.matchers.file.shouldNotBeEmpty24import io.kotest.matchers.file.shouldNotExist25import io.kotest.matchers.nulls.shouldBeNull26import io.kotest.matchers.nulls.shouldNotBeNull27import io.kotest.matchers.optional.shouldNotBePresent28import io.kotest.matchers.should29import io.kotest.matchers.shouldBe30import io.kotest.matchers.string.shouldNotBeBlank31import io.mockk.Runs32import io.mockk.every33import io.mockk.just34import org.junit.jupiter.api.AfterEach35import org.junit.jupiter.api.BeforeEach36import org.junit.jupiter.api.DisplayName37import org.junit.jupiter.api.Nested38import org.junit.jupiter.api.Test39import org.springframework.beans.factory.annotation.Autowired40import org.springframework.boot.test.context.SpringBootTest41import org.springframework.transaction.annotation.Transactional42import java.io.File43@SpringBootTest44@WithContainerDatabase45@Transactional46internal class AttachmentServiceTest {47    @Autowired48    private lateinit var attachmentService: AttachmentService49    @MockkBean50    private lateinit var remoteStorageService: RemoteStorageService51    @Autowired52    private lateinit var db: TestDataRepository53    @BeforeEach54    @AfterEach55    fun `delete test folder`() {56        val testFolder = attachmentPath(TEST_FOLDER_NAME).toFile()57        if (testFolder.exists()) {58            testFolder.deleteRecursively().shouldBeTrue()59        }60    }61    @Nested62    @DisplayName("save attachment")63    inner class SaveAttachment {64        private fun getRemoteUrl(folder: String, filename: String) = "https://remote-storage.com/$folder-$filename"65        @BeforeEach66        fun setUpMocks() {67            every {68                remoteStorageService.uploadFile(69                    ofType(String::class),70                    ofType(String::class),71                    ofType(File::class)72                )73            } answers { getRemoteUrl(firstArg(), secondArg()) }74        }75        @Test76        fun `save image attachment with thumbnail`() {77            val file = multipartFile("attachment.png", TEST_ATTACHMENT_PNG)78            val attachment =79                attachment(80                    category = AttachmentCategory.IMAGE,81                    filename = file.name,82                    folder = TEST_FOLDER_NAME,83                    metadata = metadata(mimeType = "image/png")84                )85            attachmentService.saveAttachment(attachment, file).should {86                it.metadata.shouldNotBeNull()87                it.remoteStorageUrl shouldBe getRemoteUrl(attachment.folder, attachment.filename)88                it.file.shouldMatchFile("attachment", "png")89                it.remoteStorageThumbnailUrl shouldBe getRemoteUrl(90                    "$TEST_FOLDER_NAME/$THUMBNAIL_FOLDER_NAME",91                    attachment.filename92                )93                it.thumbnailFile.shouldMatchFile("attachment", "png")94            }95        }96        @Test97        fun `save non-image attachment with thumbnail`() {98            val file = multipartFile("attachment.avi", TEST_ATTACHMENT_AVI)99            val attachment =100                attachment(101                    category = AttachmentCategory.VIDEO,102                    filename = file.name,103                    folder = TEST_FOLDER_NAME,104                    metadata = metadata(mimeType = "video/avi")105                )106            attachmentService.saveAttachment(attachment, file).should {107                it.remoteStorageUrl.shouldNotBeBlank()108                it.file.shouldMatchFile("attachment", "avi")109                it.thumbnailFile.shouldMatchFile("attachment", DEFAULT_THUMBNAIL_EXTENSION)110                it.remoteStorageThumbnailUrl.shouldNotBeBlank()111            }112        }113        @Test114        fun `save non-image attachment without thumbnail`() {115            val file = multipartFile("attachment.docx", TEST_ATTACHMENT_DOCX)116            val attachment =117                attachment(118                    category = AttachmentCategory.TEXT,119                    filename = file.name,120                    folder = TEST_FOLDER_NAME,121                    metadata = metadata(mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document")122                )123            attachmentService.saveAttachment(attachment, file).should {124                it.file.shouldMatchFile("attachment", "docx")125                it.remoteStorageUrl.shouldNotBeBlank()126                it.thumbnailFile.shouldBeNull()127                it.remoteStorageThumbnailUrl.shouldBeNull()128            }129        }130        @Test131        fun `save embedded attachment`() {132            val attachment =133                attachment(category = AttachmentCategory.EMBED, embedData = embedData(embedUrl = "some-url"))134            attachmentService.saveEmbeddedAttachment(attachment).shouldNotBeNull()135        }136    }137    @Test138    fun `delete attachment`() {139        every { remoteStorageService.uploadFile(any(), any(), any()) } returns null140        every { remoteStorageService.deleteFile(ofType(String::class), ofType(String::class)) } just Runs141        val file = multipartFile("attachment.png", TEST_ATTACHMENT_PNG)142        val attachment =143            attachment(144                category = AttachmentCategory.IMAGE,145                filename = file.name,146                folder = TEST_FOLDER_NAME,147                metadata = metadata(mimeType = "image/png")148            )149        val saved = attachmentService.saveAttachment(attachment, file)150        attachmentService.deleteAttachment(saved)151        db.select(saved).shouldNotBePresent()152        attachment.file.shouldNotExist()153        attachment.thumbnailFile.shouldNotExist()154    }155    private fun File.shouldMatchFile(name: String, extension: String) = should {156        it.shouldExist()157        it.shouldBeAFile()158        it.shouldHaveNameWithoutExtension(name)159        it.shouldHaveExtension(extension)160        it.shouldBeReadable()161        it.shouldNotBeEmpty()162    }163}...BuildDocsTest.kt
Source:BuildDocsTest.kt  
1package com.javiersc.gradle.plugins.docs2import com.javiersc.gradle.plugins.core.test.arguments3import com.javiersc.gradle.plugins.core.test.getResource4import com.javiersc.gradle.plugins.core.test.taskFromArguments5import com.javiersc.gradle.plugins.core.test.testSandbox6import io.kotest.matchers.file.shouldBeADirectory7import io.kotest.matchers.file.shouldBeAFile8import io.kotest.matchers.file.shouldHaveSameStructureAndContentAs9import io.kotest.matchers.nulls.shouldNotBeNull10import io.kotest.matchers.shouldBe11import io.kotest.matchers.string.shouldContain12import java.io.File13import kotlin.test.Ignore14import kotlin.test.Test15import org.gradle.testkit.runner.BuildResult16import org.gradle.testkit.runner.TaskOutcome17class BuildDocsTest {18    @Test19    fun `build docs`() {20        val docsDir: File = getResource("docs")21        val sandboxDirs: List<File> =22            checkNotNull(docsDir.listFiles()).toList().filterNot {23                it.isFile || (it.isDirectory && it.name.endsWith("-actual"))24            }25        for (dir in sandboxDirs) {26            val sandboxPath = dir.toRelativeString(docsDir.parentFile).replace("\\", "/")27            val actualPath = "$sandboxPath-actual/.docs"28            testSandbox(29                sandboxPath = sandboxPath,30                test = { _: BuildResult, testProjectDir: File ->31                    val expect = File("$testProjectDir/build/.docs/")32                    val actual: File = getResource(actualPath)33                    expect shouldHaveSameStructureAndContentAs actual34                    File("$testProjectDir/build/.docs/").shouldBeADirectory()35                    File("$testProjectDir/build/docs/").shouldBeADirectory()36                    val siteDir = File("$testProjectDir/build/docs/_site/")37                    File("$siteDir/index.html").shouldBeAFile()38                    File("$siteDir/api/").shouldBeADirectory()39                    if (sandboxPath.contains("snapshot")) {40                        File("$siteDir/api/snapshot/").shouldBeADirectory()41                    } else {42                        File("$siteDir/api/versions/").shouldBeADirectory()43                    }44                }45            )46        }47    }48    @Test49    fun `build cache docs`() {50        // to simulate IDEA sync the task is run three times51        val (runner, testProjectDir) =52            testSandbox(53                sandboxPath = "docs-gradle-features/build-cache-1",54                isBuildCacheTest = true,55                test = { result: BuildResult, testProjectDir: File ->56                    result57                        .task(":${testProjectDir.taskFromArguments}")58                        .shouldNotBeNull()59                        .outcome.shouldBe(TaskOutcome.SUCCESS)60                }61            )62        File("$testProjectDir/build").deleteRecursively()63        runner.withArguments(testProjectDir.arguments).build()64        File("$testProjectDir/build").deleteRecursively()65        val result = runner.withArguments(testProjectDir.arguments).build()66        result67            .task(":${testProjectDir.taskFromArguments}")68            .shouldNotBeNull()69            .outcome.shouldBe(TaskOutcome.FROM_CACHE)70    }71    @Ignore("MkDocs Gradle plugin needs to be compatible with Configuration cache (grgit issue)")72    @Test73    fun `configuration cache docs`() {74        val (runner, testProjectDir) =75            testSandbox(76                sandboxPath = "docs-gradle-features/configuration-cache-1",77                test = { result: BuildResult, testProjectDir: File ->78                    result79                        .task(":${testProjectDir.taskFromArguments}")80                        .shouldNotBeNull()81                        .outcome.shouldBe(TaskOutcome.SUCCESS)82                }83            )84        val result = runner.withArguments(testProjectDir.arguments + "--info").build()85        println("----------------")86        println(result.output)87        println("----------------")88        result.output.shouldContain("Reusing configuration cache")89        result90            .task(":${testProjectDir.taskFromArguments}")91            .shouldNotBeNull()92            .outcome.shouldBe(TaskOutcome.UP_TO_DATE)93    }94}...Tests.kt
Source:Tests.kt  
1package org.enrignagna.template.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.impldep.org.junit.rules.TemporaryFolder11import org.gradle.testkit.runner.BuildResult12import org.gradle.testkit.runner.GradleRunner13import org.gradle.testkit.runner.TaskOutcome14import org.slf4j.LoggerFactory15import java.io.File16class Tests : StringSpec(17    {18        val pluginClasspathResource = ClassLoader.getSystemClassLoader()19            .getResource("plugin-classpath.txt")20            ?: throw IllegalStateException("Did not find plugin classpath resource, run \"testClasses\" build task.")21        val classpath = pluginClasspathResource.openStream().bufferedReader().use { reader ->22            reader.readLines().map { File(it) }23        }24        val scan = ClassGraph()25            .enableAllInfo()26            .acceptPackages(Tests::class.java.`package`.name)27            .scan()28        scan.getResourcesWithLeafName("test.yaml")29            .flatMap {30                log.debug("Found test list in $it")31                val yamlFile = File(it.classpathElementFile.absolutePath + "/" + it.path)32                val testConfiguration = Config {33                    addSpec(Root)34                }.from.yaml.inputStream(it.open())35                testConfiguration[Root.tests].map { it to yamlFile.parentFile }36            }37            .forEach { (test, location) ->38                log.debug("Test to be executed: $test from $location")39                val testFolder = folder {40                    location.copyRecursively(this.root)41                }42                log.debug("Test has been copied into $testFolder and is ready to get executed")43                test.description {44                    val result = GradleRunner.create()45                        .withProjectDir(testFolder.root)46                        .withPluginClasspath(classpath)47                        .withArguments(test.configuration.tasks + test.configuration.options)48                        .build()49                    println(result.tasks)50                    println(result.output)51                    test.expectation.output_contains.forEach {52                        result.output shouldContain it53                    }54                    test.expectation.success.forEach {55                        result.outcomeOf(it) shouldBe TaskOutcome.SUCCESS56                    }57                    test.expectation.failure.forEach {58                        result.outcomeOf(it) shouldBe TaskOutcome.FAILED59                    }60                    test.expectation.file_exists.forEach {61                        with(File("${testFolder.root.absolutePath}/$it")) {62                            shouldExist()63                            shouldBeAFile()64                        }65                    }66                }67            }68    }69) {70    companion object {71        val log = LoggerFactory.getLogger(Tests::class.java)72        private fun BuildResult.outcomeOf(name: String) = task(":$name")73            ?.outcome74            ?: throw IllegalStateException("Task $name was not present among the executed tasks")75        private fun folder(closure: TemporaryFolder.() -> Unit) = TemporaryFolder().apply {76            create()77            closure()78        }79    }80}...PublishToMavenCentralTest.kt
Source:PublishToMavenCentralTest.kt  
1package it.nicolasfarabegoli.gradle.central2import io.kotest.core.spec.style.WordSpec3import io.kotest.matchers.file.shouldBeAFile4import io.kotest.matchers.file.shouldExist5import io.kotest.matchers.shouldBe6import io.kotest.matchers.string.shouldContain7import org.gradle.testkit.runner.GradleRunner8import org.gradle.testkit.runner.TaskOutcome9import java.io.File10class PublishToMavenCentralTest : WordSpec({11    val projectDir = File("build/gradleTest")12    fun setupTest() {13        projectDir.mkdirs()14        projectDir.resolve("settings.gradle.kts").writeText("")15        projectDir.resolve("build.gradle.kts").writeText(16            """17            plugins {18                `java-library`19                `java-gradle-plugin`20                id("it.nicolasfarabegoli.publish-to-maven-central")21            }22            23            publishOnMavenCentral {24                projectDescription.set("foo bar")25                repository("https://maven.pkg.github.com/foo/bar", "github") {26                    username.set("foo")27                    password.set("bar")28                }29            }30            """.trimIndent()31        )32    }33    val taskName = "generatePomFileForJavaMavenPublication"34    "The plugin" should {35        "create the correct tasks" {36            setupTest()37            val tasks = GradleRunner.create()38                .forwardOutput()39                .withPluginClasspath()40                .withProjectDir(projectDir)41                .withArguments("tasks")42                .build()43            tasks.output shouldContain "publishJavaMavenPublication"44            tasks.output shouldContain "publishPluginMavenPublicationToMavenCentralRepository"45            tasks.output shouldContain "publishJavaMavenPublicationToGithubRepository"46            tasks.output shouldContain "releaseJavaMavenOnMavenCentralNexus"47            tasks.output shouldContain "publishPluginMavenPublicationToGithubRepository"48            tasks.output shouldContain "releasePlugin"49        }50        "generate the pom correctly" {51            setupTest()52            val result = GradleRunner.create()53                .forwardOutput()54                .withPluginClasspath()55                .withArguments(taskName, "sourcesJar", "javadocJar", "--stacktrace")56                .withProjectDir(projectDir)57                .build()58            result.task(":$taskName")?.outcome shouldBe TaskOutcome.SUCCESS59            with(File("$projectDir/build/publications/javaMaven/pom-default.xml")) {60                shouldExist()61                shouldBeAFile()62                val content = readText(Charsets.UTF_8)63                content shouldContain "artifactId"64                content shouldContain "groupId"65                content shouldContain "name"66                content shouldContain "url"67                content shouldContain "license"68            }69        }70    }71})...LogWriterTest.kt
Source:LogWriterTest.kt  
1package chaperone.writer2import chaperone.CheckResult3import chaperone.CheckStatus4import chaperone.LogOutputConfig5import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper6import com.fasterxml.jackson.module.kotlin.readValue7import io.kotest.matchers.file.shouldBeAFile8import io.kotest.matchers.file.shouldBeEmpty9import io.kotest.matchers.file.shouldNotBeEmpty10import io.kotest.matchers.shouldBe11import org.junit.jupiter.api.Test12import java.io.File13class LogWriterTest {14    private val okResult = CheckResult(15        name = "check",16        status = CheckStatus.OK,17        tags = mapOf("env" to "dev"),18        output = "all is ok"19    )20    @Test21    fun `pretty stdout`() {22        val logWriter = LogWriter(LogOutputConfig(destination = "stdout", format = OutputFormat.pretty))23        // this is a weak test. so far just used for visually examining the output when the test is run24        logWriter.write(okResult)25    }26    @Test27    fun `logstash file`() {28        val file = File("/tmp/logstashfile.log")29        file.delete()30        val logWriter = LogWriter(LogOutputConfig(destination = file.absolutePath, format = OutputFormat.logstash))31        logWriter.write(okResult)32        file.shouldBeAFile()33        val line = file.readText()34        val jsonMap = jacksonObjectMapper().readValue<Map<String, String>>(line)35        jsonMap["message"].shouldBe(okResult.output)36        jsonMap["logger"].shouldBe("logwriter")37        jsonMap["level"].shouldBe("INFO")38        jsonMap["name"].shouldBe("check")39        jsonMap["tags"].shouldBe("{env=dev}")40        jsonMap["status"].shouldBe("OK")41    }42    @Test43    fun `only write errors`() {44        val file = File("/tmp/onlywriteerrors.log")45        file.delete()46        val logWriter = LogWriter(LogOutputConfig(47            destination = file.absolutePath,48            format = OutputFormat.logstash,49            onlyWriteFailures = true50        ))51        logWriter.write(okResult)52        file.shouldBeEmpty()53        logWriter.write(okResult.copy(status = CheckStatus.FAIL))54        file.shouldNotBeEmpty()55    }56}...TestEffectLoading.kt
Source:TestEffectLoading.kt  
1/*2 * Copyright (C) 2010-2022, Danilo Pianini and contributors3 * listed, for each module, in the respective subproject's build.gradle.kts file.4 *5 * This file is part of Alchemist, and is distributed under the terms of the6 * GNU General Public License, with a linking exception,7 * as described in the file LICENSE in the Alchemist distribution's top directory.8 */9@file:Suppress("DEPRECATION")10package it.unibo.alchemist.test11import io.kotest.core.spec.style.StringSpec12import io.kotest.engine.spec.tempfile13import io.kotest.matchers.file.shouldBeAFile14import io.kotest.matchers.file.shouldExist15import io.kotest.matchers.file.shouldNotBeEmpty16import io.kotest.matchers.nulls.beNull17import io.kotest.matchers.nulls.shouldNotBeNull18import io.kotest.matchers.shouldBe19import io.kotest.matchers.shouldNot20import it.unibo.alchemist.boundary.gui.effects.DrawBidimensionalGaussianLayersGradient21import it.unibo.alchemist.boundary.gui.effects.EffectSerializationFactory22import org.kaikikm.threadresloader.ResourceLoader23import java.io.File24class TestEffectLoading : StringSpec(25    {26        "effects with layers should be (de)serializable" {27            val target = DrawBidimensionalGaussianLayersGradient()28            val tempFile = tempfile()29            EffectSerializationFactory.effectToFile(tempFile, target)30            println(tempFile.readText())31            tempFile.shouldExist()32            tempFile.shouldBeAFile()33            tempFile.shouldNotBeEmpty()34            EffectSerializationFactory.effectsFromFile(tempFile).shouldNotBeNull()35        }36        "legacy effects with layers should be deserializable" {37            val target = ResourceLoader.getResource("layer.json")38            target shouldNot beNull()39            val file = File(target.file)40            file.shouldExist()41            file.shouldNotBeEmpty()42            file.shouldBeAFile()43            val effects = EffectSerializationFactory.effectsFromFile(file)44            effects.shouldNotBeNull()45            effects.size shouldBe 446        }47    }48)...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})...File.shouldBeAFile
Using AI Code Generation
1File("c:\test.txt").shouldBeAFile()2File("c:\test.txt").shouldBeADirectory()3File("c:\test.txt").shouldBeAnExistingFile()4File("c:\test.txt").shouldBeAnExistingDirectory()5File("c:\test.txt").shouldBeAnExistingFileOrDirectory()6File("c:\test.txt").shouldBeAnEmptyFile()7File("c:\test.txt").shouldHaveExtension("txt")8File("c:\test.txt").shouldHaveName("test")9File("c:\test.txt").shouldHavePath("c:\test.txt")10File("c:\test.txt").shouldHaveParent("c:\test")11File("c:\test.txt").shouldHaveParentFile(File("c:\test"))12File("c:\test.txt").shouldHaveSize(1024)13File("c:\test.txt").shouldHaveText("some text")14File("c:\test.txt").shouldHaveText("some text", Charsets.UTF_8)File.shouldBeAFile
Using AI Code Generation
1import io.kotest.matchers.file.shouldBeAFile2import org.junit.jupiter.api.Test3import java.io.File4class FileTest {5    fun `should check if file exists`() {6        val file = File("src/test/resources/test.txt")7        file.shouldBeAFile()8    }9}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!!
