Skip to content

Instantly share code, notes, and snippets.

@drawers
Created March 30, 2023 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drawers/cea01848c241620a9e23f4690938b8ff to your computer and use it in GitHub Desktop.
Save drawers/cea01848c241620a9e23f4690938b8ff to your computer and use it in GitHub Desktop.
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