Skip to content

Commit

Permalink
Improve core tests (#7232)
Browse files Browse the repository at this point in the history
* Don't repeat code

* Improve the rule in the tests of Analyzer
  • Loading branch information
BraisGabin committed Apr 27, 2024
1 parent 537c4fe commit 3b6634a
Showing 1 changed file with 18 additions and 13 deletions.
Expand Up @@ -16,7 +16,11 @@ import io.gitlab.arturbosch.detekt.test.yamlConfigFromContent
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.elementsInRange
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
Expand Down Expand Up @@ -405,31 +409,32 @@ private class NoEmptyFile(config: Config) : Rule(config, "TestDescription") {
}
}

private class MaxLineLength(config: Config) : Rule(config, "TestDescription") {
private open class MaxLineLength(config: Config) : Rule(config, "TestDescription") {
private val lengthThreshold: Int = config.valueOrDefault("maxLineLength", 10)
override fun visitKtFile(file: KtFile) {
super.visitKtFile(file)
var offset = 0
for (line in file.text.lineSequence()) {
if (line.length > lengthThreshold) {
report(CodeSmell(Entity.atPackageOrFirstDecl(file), description))
val ktElement = file.findFirstMeaningfulKtElementInParents(offset..(offset + line.length))
report(CodeSmell(Entity.from(ktElement), description))
}
offset += line.length + 1 // \n
}
}
}

@RequiresTypeResolution
private class RequiresTypeResolutionMaxLineLength(config: Config) : Rule(config, "TestDescription") {
private val lengthThreshold: Int = config.valueOrDefault("maxLineLength", 10)
override fun visitKtFile(file: KtFile) {
super.visitKtFile(file)
for (line in file.text.lineSequence()) {
if (line.length > lengthThreshold) {
report(CodeSmell(Entity.atPackageOrFirstDecl(file), description))
}
}
private fun KtFile.findFirstMeaningfulKtElementInParents(range: IntRange): PsiElement {
return elementsInRange(TextRange.create(range.first, range.last))
.asSequence()
.plus(findElementAt(range.last))
.mapNotNull { it?.getNonStrictParentOfType() }
.first { it.text.isNotBlank() }
}
}

@RequiresTypeResolution
private class RequiresTypeResolutionMaxLineLength(config: Config) : MaxLineLength(config)

private class FaultyRule(config: Config) : Rule(config, "") {
override fun visitKtFile(file: KtFile) {
throw object : IllegalStateException("Deliberately triggered error.") {}
Expand Down

0 comments on commit 3b6634a

Please sign in to comment.