Best Kotest code snippet using io.kotest.matchers.file.matchers.File.shouldNotExist
OptionFactoryTaskSpec.kt
Source:OptionFactoryTaskSpec.kt
1package io.mehow.laboratory.gradle2import io.kotest.core.spec.style.StringSpec3import io.kotest.matchers.file.shouldExist4import io.kotest.matchers.file.shouldNotExist5import io.kotest.matchers.shouldBe6import io.kotest.matchers.string.shouldContain7import org.gradle.testkit.runner.GradleRunner8import org.gradle.testkit.runner.TaskOutcome.FAILED9import org.gradle.testkit.runner.TaskOutcome.SUCCESS10internal class OptionFactoryTaskSpec : StringSpec({11 lateinit var gradleRunner: GradleRunner12 cleanBuildDirs()13 beforeTest {14 gradleRunner = GradleRunner.create()15 .withPluginClasspath()16 .withArguments("generateOptionFactory", "--stacktrace")17 }18 "generates factory without any feature flags" {19 val fixture = "option-factory-generate-empty".toFixture()20 val result = gradleRunner.withProjectDir(fixture).build()21 result.task(":generateOptionFactory")!!.outcome shouldBe SUCCESS22 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")23 factory.shouldExist()24 factory.readText() shouldContain """25 |fun OptionFactory.Companion.generated(): OptionFactory = GeneratedOptionFactory26 |27 |private object GeneratedOptionFactory : OptionFactory {28 | public override fun create(key: String, name: String): Feature<*>? = null29 |}30 """.trimMargin()31 }32 "generates factory using feature flag fqcns" {33 val fixture = "option-factory-generate-fqcn".toFixture()34 val result = gradleRunner.withProjectDir(fixture).build()35 result.task(":generateOptionFactory")!!.outcome shouldBe SUCCESS36 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")37 factory.shouldExist()38 factory.readText() shouldContain """39 |fun OptionFactory.Companion.generated(): OptionFactory = GeneratedOptionFactory40 |41 |private object GeneratedOptionFactory : OptionFactory {42 | public override fun create(key: String, name: String): Feature<*>? = when (key) {43 | "io.mehow.first.FeatureA" -> when (name) {44 | "FirstA" -> FeatureA.FirstA45 | "SecondA" -> FeatureA.SecondA46 | else -> null47 | }48 | "io.mehow.second.FeatureB" -> when (name) {49 | "FirstB" -> FeatureB.FirstB50 | else -> null51 | }52 | else -> null53 | }54 |}55 """.trimMargin()56 }57 "generates factory using feature flag keys" {58 val fixture = "option-factory-generate-key".toFixture()59 val result = gradleRunner.withProjectDir(fixture).build()60 result.task(":generateOptionFactory")!!.outcome shouldBe SUCCESS61 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")62 factory.shouldExist()63 factory.readText() shouldContain """64 |fun OptionFactory.Companion.generated(): OptionFactory = GeneratedOptionFactory65 |66 |private object GeneratedOptionFactory : OptionFactory {67 | public override fun create(key: String, name: String): Feature<*>? = when (key) {68 | "Key A" -> when (name) {69 | "FirstA" -> FeatureA.FirstA70 | "SecondA" -> FeatureA.SecondA71 | else -> null72 | }73 | "Key B" -> when (name) {74 | "FirstB" -> FeatureB.FirstB75 | else -> null76 | }77 | else -> null78 | }79 |}80 """.trimMargin()81 }82 "fails to generate factory for feature flags with duplicate keys" {83 val fixture = "option-factory-duplicate-key".toFixture()84 val result = gradleRunner.withProjectDir(fixture).buildAndFail()85 result.task(":generateOptionFactory")!!.outcome shouldBe FAILED86 result.output shouldContain """87 |Feature flags must have unique keys. Found following duplicates:88 | - Some Key: [io.mehow.first.FeatureA, io.mehow.second.FeatureB]89 """.trimMargin()90 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")91 factory.shouldNotExist()92 }93 "fails to generate factory for key duplicating another fqcn" {94 val fixture = "option-factory-duplicate-key-fqcn".toFixture()95 val result = gradleRunner.withProjectDir(fixture).buildAndFail()96 result.task(":generateOptionFactory")!!.outcome shouldBe FAILED97 result.output shouldContain """98 |Feature flags must have unique keys. Found following duplicates:99 | - io.mehow.first.FeatureA: [io.mehow.first.FeatureA, io.mehow.second.FeatureB]100 """.trimMargin()101 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")102 factory.shouldNotExist()103 }104 "fails to generate factory for feature flags with no options" {105 val fixture = "option-factory-no-option".toFixture()106 val result = gradleRunner.withProjectDir(fixture).buildAndFail()107 result.task(":generateOptionFactory")!!.outcome shouldBe FAILED108 result.output shouldContain "Feature must have at least one option"109 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")110 factory.shouldNotExist()111 }112 "uses implicit package name" {113 val fixture = "option-factory-package-name-implicit".toFixture()114 gradleRunner.withProjectDir(fixture).build()115 val factory = fixture.optionFactoryFile("io.mehow.implicit.GeneratedOptionFactory")116 factory.shouldExist()117 factory.readText() shouldContain "package io.mehow.implicit"118 }119 "uses explicit package name" {120 val fixture = "option-factory-package-name-explicit".toFixture()121 gradleRunner.withProjectDir(fixture).build()122 val factory = fixture.optionFactoryFile("io.mehow.explicit.GeneratedOptionFactory")123 factory.shouldExist()124 factory.readText() shouldContain "package io.mehow.explicit"125 }126 "overrides implicit package name" {127 val fixture = "option-factory-package-name-explicit-override".toFixture()128 gradleRunner.withProjectDir(fixture).build()129 val factory = fixture.optionFactoryFile("io.mehow.explicit.GeneratedOptionFactory")130 factory.shouldExist()131 factory.readText() shouldContain "package io.mehow.explicit"132 }133 "generates internal factory" {134 val fixture = "option-factory-generate-internal".toFixture()135 gradleRunner.withProjectDir(fixture).build()136 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")137 factory.shouldExist()138 factory.readText() shouldContain "internal fun OptionFactory.Companion.generated()"139 }140 "generates public factory" {141 val fixture = "option-factory-generate-public".toFixture()142 gradleRunner.withProjectDir(fixture).build()143 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")144 factory.shouldExist()145 factory.readText() shouldContain "public fun OptionFactory.Companion.generated()"146 }147 "generates factory with feature flags from all modules" {148 val fixture = "option-factory-multi-module-generate-all".toFixture()149 val result = gradleRunner.withProjectDir(fixture).build()150 result.task(":generateOptionFactory")!!.outcome shouldBe SUCCESS151 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")152 factory.shouldExist()153 factory.readText() shouldContain """154 |fun OptionFactory.Companion.generated(): OptionFactory = GeneratedOptionFactory155 |156 |private object GeneratedOptionFactory : OptionFactory {157 | public override fun create(key: String, name: String): Feature<*>? = when (key) {158 | "Key A" -> when (name) {159 | "First" -> FeatureA.First160 | else -> null161 | }162 | "Key B" -> when (name) {163 | "First" -> FeatureB.First164 | else -> null165 | }166 | "Key Root" -> when (name) {167 | "First" -> RootFeature.First168 | else -> null169 | }170 | else -> null171 | }172 |}173 """.trimMargin()174 }175 "generates factory with feature flags only from included modules" {176 val fixture = "option-factory-multi-module-generate-filtered".toFixture()177 val result = gradleRunner.withProjectDir(fixture).build()178 result.task(":generateOptionFactory")!!.outcome shouldBe SUCCESS179 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")180 factory.shouldExist()181 factory.readText() shouldContain """182 |fun OptionFactory.Companion.generated(): OptionFactory = GeneratedOptionFactory183 |184 |private object GeneratedOptionFactory : OptionFactory {185 | public override fun create(key: String, name: String): Feature<*>? = when (key) {186 | "Key B" -> when (name) {187 | "First" -> FeatureB.First188 | else -> null189 | }190 | "Key Root" -> when (name) {191 | "First" -> RootFeature.First192 | else -> null193 | }194 | else -> null195 | }196 |}197 """.trimMargin()198 }199 "generates factory for Android project" {200 val fixture = "option-factory-android-smoke".toFixture()201 val result = gradleRunner.withProjectDir(fixture).build()202 result.task(":generateOptionFactory")!!.outcome shouldBe SUCCESS203 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")204 factory.shouldExist()205 factory.readText() shouldContain """206 |fun OptionFactory.Companion.generated(): OptionFactory = GeneratedOptionFactory207 |208 |private object GeneratedOptionFactory : OptionFactory {209 | public override fun create(key: String, name: String): Feature<*>? = null210 |}211 """.trimMargin()212 }213 "fails to generate factory for feature flags with duplicate keys in different modules" {214 val fixture = "option-factory-multi-module-duplicate-key".toFixture()215 val result = gradleRunner.withProjectDir(fixture).buildAndFail()216 result.task(":generateOptionFactory")!!.outcome shouldBe FAILED217 result.output shouldContain """218 |Feature flags must have unique keys. Found following duplicates:219 | - Some Key: [FeatureA, FeatureB]220 """.trimMargin()221 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")222 factory.shouldNotExist()223 }224 "generates factory for feature flags with duplicate keys in filtered modules" {225 val fixture = "option-factory-multi-module-filtered-duplicate-key".toFixture()226 val result = gradleRunner.withProjectDir(fixture).build()227 result.task(":generateOptionFactory")!!.outcome shouldBe SUCCESS228 val factory = fixture.optionFactoryFile("GeneratedOptionFactory")229 factory.shouldExist()230 factory.readText() shouldContain """231 |fun OptionFactory.Companion.generated(): OptionFactory = GeneratedOptionFactory232 |233 |private object GeneratedOptionFactory : OptionFactory {234 | public override fun create(key: String, name: String): Feature<*>? = when (key) {235 | "Key Root" -> when (name) {236 | "First" -> RootFeature.First237 | else -> null238 | }239 | "Some Key" -> when (name) {240 | "First" -> FeatureB.First241 | else -> null242 | }243 | else -> null244 | }245 |}246 """.trimMargin()247 }248})...
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}...
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}...
AaptRulesTest.kt
Source:AaptRulesTest.kt
1/*2 * ProGuard -- shrinking, optimization, obfuscation, and preverification3 * of Java bytecode.4 *5 * Copyright (c) 2002-2021 Guardsquare NV6 */7package proguard.gradle.plugin.android.dsl8import io.kotest.core.spec.style.FreeSpec9import io.kotest.matchers.file.shouldExist10import io.kotest.matchers.file.shouldNotExist11import io.kotest.matchers.shouldBe12import io.kotest.matchers.string.shouldContain13import java.io.File14import org.gradle.testkit.runner.TaskOutcome15import testutils.AndroidProject16import testutils.applicationModule17import testutils.createGradleRunner18import testutils.createTestKitDir19class AaptRulesTest : FreeSpec({20 val testKitDir = createTestKitDir()21 "Given a project with a configuration for a variant" - {22 val project = autoClose(AndroidProject().apply {23 addModule(applicationModule("app", buildDotGradle = """24 plugins {25 id 'com.android.application'26 id 'proguard'27 }28 android {29 compileSdkVersion 3030 buildTypes {31 release {32 minifyEnabled false33 }34 }35 }36 proguard {37 configurations {38 debug {39 defaultConfiguration 'proguard-android-debug.txt'40 }41 }42 }""".trimIndent()))43 }.create())44 "When the project is evaluated" - {45 val result = createGradleRunner(project.rootDir, testKitDir, "assembleDebug", "--info").build()46 val aaptRules = File("${project.moduleBuildDir("app")}/intermediates/proguard/configs/aapt_rules.pro")47 "The build should succeed" {48 result.task(":app:assembleDebug")?.outcome shouldBe TaskOutcome.SUCCESS49 }50 "The rules file should be passed to ProGuard" {51 result.output shouldContain "Loading configuration file ${aaptRules.absolutePath}"52 }53 "The the AAPT rules should be generated" {54 aaptRules.shouldExist()55 aaptRules.readText() shouldContain "-keep class com.example.app.MainActivity { <init>(); }"56 }57 }58 }59 "Given a project with a configuration for a variant and existing aaptOptions" - {60 val project = autoClose(AndroidProject().apply {61 addModule(applicationModule("app", buildDotGradle = """62 plugins {63 id 'com.android.application'64 id 'proguard'65 }66 android {67 compileSdkVersion 3068 buildTypes {69 release {70 minifyEnabled false71 }72 }73 aaptOptions.additionalParameters = ["--proguard", "${rootDir.absolutePath}/test.pro"]74 }75 proguard {76 configurations {77 debug {78 defaultConfiguration 'proguard-android-debug.txt'79 }80 }81 }""".trimIndent()))82 }.create())83 "When the project is evaluated" - {84 val result = createGradleRunner(project.rootDir, testKitDir, "assembleDebug", "--info").build()85 val aaptRules = File("${project.rootDir}/test.pro")86 "The build should succeed" {87 result.task(":app:assembleDebug")?.outcome shouldBe TaskOutcome.SUCCESS88 }89 "The rules file should be passed to ProGuard" {90 result.output shouldContain "Loading configuration file ${aaptRules.absolutePath}"91 }92 "The AAPT rules file should be re-used" {93 aaptRules.shouldExist()94 aaptRules.readText() shouldContain "-keep class com.example.app.MainActivity { <init>(); }"95 }96 "The AAPT rules file should not be generated" {97 val generatedAaptRules = File("${project.moduleBuildDir("app")}/intermediates/proguard/configs/aapt_rules.pro")98 generatedAaptRules.shouldNotExist()99 }100 }101 }102})...
ConsumerRulesCollectionTest.kt
Source:ConsumerRulesCollectionTest.kt
1package proguard.gradle2/*3 * ProGuard -- shrinking, optimization, obfuscation, and preverification4 * of Java bytecode.5 *6 * Copyright (c) 2002-2020 Guardsquare NV7 */8import io.kotest.core.spec.style.FreeSpec9import io.kotest.matchers.file.shouldExist10import io.kotest.matchers.file.shouldNotExist11import io.kotest.matchers.shouldBe12import io.kotest.matchers.string.shouldContain13import io.kotest.matchers.string.shouldNotContain14import java.io.File15import org.gradle.testkit.runner.TaskOutcome16import testutils.AndroidProject17import testutils.applicationModule18import testutils.createGradleRunner19import testutils.createTestKitDir20class ConsumerRulesCollectionTest : FreeSpec({21 val testKitDir = createTestKitDir()22 "Given an Android project with one configured variant" - {23 val project = autoClose(AndroidProject().apply {24 addModule(applicationModule("app", buildDotGradle = """25 plugins {26 id 'com.android.application'27 id 'com.guardsquare.proguard'28 }29 android {30 compileSdkVersion 3031 buildTypes {32 release {33 minifyEnabled false34 }35 debug {36 minifyEnabled false37 }38 }39 }40 proguard {41 configurations {42 release {}43 }44 }45 """.trimIndent()))46 }.create())47 "When the tasks 'clean' and 'assembleDebug' are executed in a dry run" - {48 val result = createGradleRunner(project.rootDir, testKitDir, "--dry-run", "clean", "assembleDebug").build()49 "Then the 'collectConsumerRulesDebug' task would not be executed" {50 result.output.shouldNotContain("collectConsumerRulesDebug")51 }52 }53 "When the tasks 'clean' and 'assembleRelease' are executed in a dry run" - {54 val result = createGradleRunner(project.rootDir, testKitDir, "--dry-run", "clean", "assembleRelease").build()55 "Then the 'collectConsumerRulesRelease' task would be executed" {56 result.output.shouldContain("collectConsumerRulesRelease")57 }58 }59 "When the tasks 'clean' and 'collectConsumerRulesDebug' are executed " - {60 val result = createGradleRunner(project.rootDir, testKitDir, "clean", "collectConsumerRulesDebug").buildAndFail()61 "Then the task 'collectConsumerRulesDebug' is not executed" {62 result.task(":app:collectConsumerRulesDebug")?.outcome shouldBe null63 }64 "Then a subdirectory of the build directory should not contain the consumer rules" {65 File("${project.rootDir}/app/build/intermediates/proguard/configs/debug/consumer-rules.pro").shouldNotExist()66 }67 }68 "When the tasks 'clean' and 'collectConsumerRulesRelease' are executed " - {69 val result = createGradleRunner(project.rootDir, testKitDir, "clean", "collectConsumerRulesRelease").build()70 "Then the task 'collectConsumerRulesRelease' is successful" {71 result.task(":app:collectConsumerRulesRelease")?.outcome shouldBe TaskOutcome.SUCCESS72 }73 "Then a subdirectory of the build directory should contain the consumer rules" {74 File("${project.rootDir}/app/build/intermediates/proguard/configs/release/consumer-rules.pro").shouldExist()75 }76 }77 }78})...
FunSpecTest.kt
Source:FunSpecTest.kt
1package com.sksamuel.kotest.engine.spec.style2import io.kotest.assertions.assertSoftly3import io.kotest.core.spec.Spec4import io.kotest.core.spec.style.FunSpec5import io.kotest.matchers.paths.shouldNotExist6import io.kotest.matchers.shouldBe7import io.kotest.matchers.string.shouldHaveLength8import io.kotest.matchers.string.shouldNotBeBlank9import io.kotest.matchers.string.shouldStartWith10import kotlinx.coroutines.delay11import kotlinx.coroutines.launch12import java.nio.file.Paths13import kotlin.time.Duration14import kotlin.time.Duration.Companion.hours15import kotlin.time.Duration.Companion.milliseconds16class FunSpecTest : FunSpec() {17 var count = 018 init {19 test("test without config") {20 "hello world".shouldStartWith("hello")21 }22 test("test with config").config(enabled = true) {23 assertSoftly {24 val path = Paths.get(".password")25 path.shouldNotExist()26 }27 }28 test("test with timeout").config(timeout = 1234.milliseconds) {29 count += 130 }31 xtest("a disabled test") {32 error("boom")33 }34 context("a context can hold tests") {35 test("foo") {36 "a".shouldNotBeBlank()37 }38 xtest("a disabled test inside the context") {39 error("boom")40 }41 xtest("a disabled test with config").config(timeout = 1231.hours) {42 error("boom")43 }44 context("and even other contexts!") {45 test("wibble") {46 "hello".shouldHaveLength(5)47 }48 }49 }50 context("a context with coroutine in fun spec context scope") {51 launch { delay(1) }52 test("a dummy test") {53 }54 }55 xcontext("a disabled context!") {56 error("boom")57 }58 }59 override suspend fun afterSpec(spec: Spec) {60 count.shouldBe(1)61 }62}...
UtilRoboTest.kt
Source:UtilRoboTest.kt
1package io.github.shadow578.yodel.util2import com.bumptech.glide.util.Util3import io.github.shadow578.yodel.LocaleOverride4import io.github.shadow578.yodel.RoboTest5import io.github.shadow578.yodel.util.preferences.Prefs6import io.kotest.assertions.withClue7import io.kotest.matchers.file.shouldNotExist8import io.kotest.matchers.file.shouldStartWithPath9import io.kotest.matchers.nulls.shouldNotBeNull10import io.kotest.matchers.shouldBe11import org.junit.Test12import java.io.File13/**14 * robolectric test for [Util]15 */16class UtilRoboTest : RoboTest() {17 /**18 * [getTempFile]19 */20 @Test21 fun shouldGetTempFile() {22 withClue("getTempFile() should return a file in the parent directory that does not exist") {23 val cache = context.cacheDir24 val temp: File = cache.getTempFile("foo", "bar")25 temp.shouldNotBeNull()26 temp.shouldNotExist()27 temp.shouldStartWithPath(cache)28 }29 }30 /**31 * [wrapLocale]32 */33 @Test34 fun testWrapLocale() {35 Prefs.AppLocaleOverride.set(LocaleOverride.German)36 Prefs.AppLocaleOverride.get() shouldBe LocaleOverride.German37 val wrapped = context.wrapLocale()38 wrapped.shouldNotBeNull()39 // .locales was only added in SDK 2440 // before that, we have to use .locale (which is now deprecated)41 untilSDK(23) {42 wrapped.resources.configuration.locale shouldBe LocaleOverride.German.locale43 }44 aboveSDK(23) {45 wrapped.resources.configuration.locales.get(0) shouldBe LocaleOverride.German.locale46 }47 }48}...
TempFileTest.kt
Source:TempFileTest.kt
1package com.sksamuel.kotest.engine.spec2import io.kotest.core.spec.style.FunSpec3import io.kotest.engine.spec.tempfile4import io.kotest.matchers.file.shouldExist5import io.kotest.matchers.file.shouldNotExist6class TempFileTest : FunSpec({7 val file = tempfile()8 test("temp file should be deleted after spec") {9 file.shouldExist()10 }11 afterProject {12 file.shouldNotExist()13 }14})...
File.shouldNotExist
Using AI Code Generation
1 import io.kotest.matchers.file.shouldNotExist2 import io.kotest.matchers.shouldBe3 import io.kotest.matchers.shouldNotBe4 import io.kotest.core.spec.style.StringSpec5 import io.kotest.matchers.file.shouldBeAFile6 import io.kotest.matchers.file.shouldBeADirectory7 import io.kotest.matchers.file.shouldBeReadable8 import io.kotest.matchers.file.shouldBeWritable9 import io.kotest.matchers.file.shouldBeHidden10 import io.kotest.matchers.file.shouldBeRelative11 import io.kotest.matchers.file.shouldBeAbsolute12 import io.kotest.matchers.file.shouldBeSymlink13 import java.nio.file.Files14 import java.nio.file.Paths15 class FileMatchersTest : StringSpec({16 "should be a file" {17 val file = Paths.get("test.txt")18 Files.createFile(file)19 file.shouldBeAFile()20 }21 "should be a directory" {22 val dir = Paths.get("test-dir")23 Files.createDirectory(dir)24 dir.shouldBeADirectory()25 }26 "should be readable" {27 val file = Paths.get("test.txt")28 Files.createFile(file)29 file.shouldBeReadable()30 }31 "should be writable" {32 val file = Paths.get("test.txt")33 Files.createFile(file)34 file.shouldBeWritable()35 }36 "should be hidden" {37 val file = Paths.get(".test.txt")38 Files.createFile(file)39 file.shouldBeHidden()40 }41 "should be relative" {42 val file = Paths.get("test.txt")43 file.shouldBeRelative()44 }45 "should be absolute" {46 val file = Paths.get("/test.txt")47 file.shouldBeAbsolute()48 }49 "should be symlink" {50 val file = Paths.get("test.txt")51 val symlink = Paths.get("test-symlink.txt")52 Files.createFile(file)53 Files.createSymbolicLink(symlink, file)54 symlink.shouldBeSymlink()55 }56 "should not exist" {57 val file = Paths.get("test.txt")58 file.shouldNotExist()59 }60 })
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!!