Created
March 30, 2023 15:39
-
-
Save drawers/cea01848c241620a9e23f4690938b8ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io.gitlab.arturbosch.detekt.api.Config | |
import io.gitlab.arturbosch.detekt.test.assertThat | |
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext | |
import io.gitlab.arturbosch.detekt.test.setupKotlinEnvironment | |
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment | |
import org.junit.jupiter.api.BeforeAll | |
import org.junit.jupiter.api.Test | |
class DoubleNegativeTakeUnlessTest { | |
private val env: KotlinCoreEnvironment by lazy { setupKotlinEnvironment() } | |
private val rule by lazy { DoubleNegativeTakeUnless(Config.empty) } | |
companion object { | |
@BeforeAll | |
@JvmStatic | |
fun setUp() { | |
setupKotlinEnvironment() | |
} | |
} | |
@Test | |
fun `detects double negative with takeUnless`() { | |
val code = """ | |
fun main() { | |
val list = listOf("a", "b", "c") | |
val result = list.takeUnless { !it.isEmpty() } | |
} | |
""" | |
val findings = rule.compileAndLintWithContext(env, code) | |
assertThat(findings).hasSize(1) | |
} | |
@Test | |
fun `does not report takeIf`() { | |
val code = """ | |
fun main() { | |
val list = listOf("a", "b", "c") | |
val result = list.takeIf { it.isEmpty() } | |
} | |
""" | |
val findings = rule.compileAndLintWithContext(env, code) | |
assertThat(findings).isEmpty() | |
} | |
@Test | |
fun `detects double negative with takeUnless and complex condition`() { | |
val code = """ | |
class Weather { | |
fun isRaining(): Boolean = true | |
fun goingOutside(): Boolean = false | |
} | |
fun main() { | |
val weather = Weather() | |
val result = weather.takeUnless { !it.isRaining() && it.goingOutside() } | |
} | |
""" | |
val findings = rule.compileAndLintWithContext(env, code) | |
assertThat(findings).hasSize(1) | |
} | |
@Test | |
fun `does not report takeUnless with no double negative`() { | |
val code = """ | |
fun main() { | |
val list = listOf("a", "b", "c") | |
val result = list.takeUnless { it.isEmpty() } | |
} | |
""" | |
val findings = rule.compileAndLintWithContext(env, code) | |
assertThat(findings).isEmpty() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment