Last active
July 16, 2021 10:10
-
-
Save anton-kapelyushok/dfbf64e092519d8418fb8cf0686a3898 to your computer and use it in GitHub Desktop.
The only sensible thing to do in kotlin
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 com.tngtech.archunit.base.DescribedPredicate | |
import com.tngtech.archunit.core.domain.JavaClass | |
import com.tngtech.archunit.core.importer.ClassFileImporter | |
import com.tngtech.archunit.lang.ArchCondition | |
import com.tngtech.archunit.lang.ConditionEvents | |
import com.tngtech.archunit.lang.SimpleConditionEvent | |
import com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes | |
import org.junit.jupiter.api.Test | |
import org.springframework.stereotype.Component | |
import org.springframework.stereotype.Service | |
class ArchTest { | |
companion object { | |
private val importedClasses = | |
ClassFileImporter().importPackagesOf(ArchTest::class.java)!! | |
} | |
@Test | |
fun `inheritance is prohibited!`() { | |
classes().that() | |
.areAnnotatedWith(Component::class.java) | |
.or() | |
.areAnnotatedWith(Service::class.java) | |
.or(isDataClass()) | |
.should(haveNoSuperclass()) | |
.check(importedClasses) | |
} | |
private fun isDataClass() = IsDataClass() | |
private fun haveNoSuperclass() = HaveNoSuperclass() | |
private class IsDataClass : DescribedPredicate<JavaClass>("is data class") { | |
override fun apply(input: JavaClass): Boolean { | |
return try { | |
input.reflect().kotlin.isData | |
} catch (e: Throwable) { | |
false | |
} | |
} | |
} | |
private class HaveNoSuperclass : ArchCondition<JavaClass>("have no superclass") { | |
override fun check(javaClass: JavaClass, events: ConditionEvents) { | |
var isOk = true | |
var violationClass = "java.lang.Object" | |
if (javaClass.superclass.isPresent) { | |
if (javaClass.superclass.get().name != "java.lang.Object") { | |
isOk = false | |
violationClass = javaClass.superclass.get().name | |
} | |
} | |
events.add(SimpleConditionEvent(javaClass, isOk, "${javaClass.name} inherits $violationClass")) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment