CoreShadowRelocationTest.kt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. /*
  2. * Copyright 2019-2022 Mamoe Technologies and contributors.
  3. *
  4. * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
  5. * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
  6. *
  7. * https://github.com/mamoe/mirai/blob/dev/LICENSE
  8. */
  9. package net.mamoe.mirai.deps.test
  10. import org.junit.jupiter.api.Test
  11. import org.junit.jupiter.api.condition.EnabledIf
  12. import kotlin.test.assertTrue
  13. /**
  14. * 为每个模块测试 relocated 的依赖是否存在于运行时
  15. */
  16. class CoreShadowRelocationTest : AbstractTest() {
  17. companion object {
  18. private const val ByteBufferChannel = "io.ktor.utils.io.ByteBufferChannel"
  19. private const val HttpClient = "io.ktor.client.HttpClient"
  20. private const val KtorOkHttp = "io.ktor.client.engine.okhttp.OkHttp"
  21. private const val OkHttp = "okhttp3.OkHttp"
  22. private const val OkIO = "okio.ByteString"
  23. fun relocated(string: String): String {
  24. return "net.mamoe.mirai.internal.deps.$string"
  25. }
  26. }
  27. @Test
  28. @EnabledIf("isMiraiLocalAvailable", disabledReason = REASON_LOCAL_ARTIFACT_NOT_AVAILABLE)
  29. fun `test mirai-core-utils`() {
  30. val fragment = buildTestCases {
  31. +relocated(`ktor-io`)
  32. -both(`ktor-client-core`)
  33. -both(`ktor-client-okhttp`)
  34. -both(`okhttp3-okhttp`)
  35. -both(okio)
  36. }
  37. applyCodeFragment(fragment)
  38. buildFile.appendText(
  39. """
  40. dependencies {
  41. implementation("net.mamoe:mirai-core-utils:$miraiLocalVersion")
  42. }
  43. """.trimIndent()
  44. )
  45. runGradle("check")
  46. }
  47. @Test
  48. @EnabledIf("isMiraiLocalAvailable", disabledReason = REASON_LOCAL_ARTIFACT_NOT_AVAILABLE)
  49. fun `test mirai-core-api with transitive mirai-core-utils`() {
  50. val fragment = buildTestCases {
  51. +relocated(`ktor-io`)
  52. -both(`ktor-client-core`)
  53. -both(`ktor-client-okhttp`)
  54. -both(`okhttp3-okhttp`)
  55. -both(okio)
  56. +relocated(`ExternalResource-input`)
  57. }
  58. applyCodeFragment(fragment)
  59. buildFile.appendText(
  60. """
  61. dependencies {
  62. implementation("net.mamoe:mirai-core-api:$miraiLocalVersion")
  63. }
  64. """.trimIndent()
  65. )
  66. runGradle("check")
  67. }
  68. @Test
  69. @EnabledIf("isMiraiLocalAvailable", disabledReason = REASON_LOCAL_ARTIFACT_NOT_AVAILABLE)
  70. fun `test mirai-core with transitive mirai-core-api and mirai-core-utils`() {
  71. val fragment = buildTestCases {
  72. +relocated(`ktor-io`)
  73. +relocated(`ktor-client-core`)
  74. +relocated(`ktor-client-okhttp`)
  75. +relocated(`okhttp3-okhttp`)
  76. +relocated(okio)
  77. +relocated(`ExternalResource-input`)
  78. }
  79. applyCodeFragment(fragment)
  80. buildFile.appendText(
  81. """
  82. dependencies {
  83. implementation("net.mamoe:mirai-core:$miraiLocalVersion")
  84. }
  85. """.trimIndent()
  86. )
  87. runGradle("check")
  88. }
  89. // ktor-io is shadowed into runtime in mirai-core-utils. So without mirai-core-utils,
  90. // we should expect no relocated ktor-io found, otherwise there will be duplicated classes on Android.
  91. // https://github.com/mamoe/mirai/issues/2291
  92. @Test
  93. @EnabledIf("isMiraiLocalAvailable", disabledReason = REASON_LOCAL_ARTIFACT_NOT_AVAILABLE)
  94. fun `test mirai-core without transitive mirai-core-api and mirai-core-utils`() {
  95. val fragment = buildTestCases {
  96. -both(`ktor-io`)
  97. +relocated(`ktor-client-core`)
  98. +relocated(`ktor-client-okhttp`)
  99. +relocated(`okhttp3-okhttp`)
  100. +relocated(okio)
  101. }
  102. applyCodeFragment(fragment)
  103. buildFile.appendText(
  104. """
  105. dependencies {
  106. implementation("net.mamoe:mirai-core:$miraiLocalVersion") {
  107. exclude("net.mamoe", "mirai-core-api")
  108. exclude("net.mamoe", "mirai-core-utils")
  109. }
  110. }
  111. """.trimIndent()
  112. )
  113. runGradle("check")
  114. }
  115. @Test
  116. @EnabledIf("isMiraiLocalAvailable", disabledReason = REASON_LOCAL_ARTIFACT_NOT_AVAILABLE)
  117. fun `test mirai-core-api without transitive mirai-core-utils`() {
  118. val fragment = buildTestCases {
  119. -both(`ktor-io`)
  120. -both(`ktor-client-core`)
  121. -both(`ktor-client-okhttp`)
  122. -both(`okhttp3-okhttp`)
  123. -both(okio)
  124. // +relocated(`ExternalResource-input`) // Will fail with no class def found error because there is no runtime ktor-io
  125. }
  126. applyCodeFragment(fragment)
  127. buildFile.appendText(
  128. """
  129. dependencies {
  130. implementation("net.mamoe:mirai-core-api:$miraiLocalVersion") {
  131. exclude("net.mamoe", "mirai-core-utils")
  132. }
  133. }
  134. """.trimIndent()
  135. )
  136. runGradle("check")
  137. }
  138. @Test
  139. @EnabledIf("isMiraiLocalAvailable", disabledReason = REASON_LOCAL_ARTIFACT_NOT_AVAILABLE)
  140. fun `test mirai-core-all`() {
  141. val fragment = buildTestCases {
  142. +relocated(`ktor-io`)
  143. +relocated(`ktor-client-core`)
  144. +relocated(`ktor-client-okhttp`)
  145. +relocated(`okhttp3-okhttp`)
  146. +relocated(okio)
  147. +relocated(`ExternalResource-input`)
  148. }
  149. applyCodeFragment(fragment)
  150. // mirai-core-all-2.99.0-deps-test-all.jar
  151. val miraiCoreAllJar =
  152. mavenLocalDir.resolve("net/mamoe/mirai-core-all/$miraiLocalVersion/mirai-core-all-$miraiLocalVersion-all.jar")
  153. val path = miraiCoreAllJar.absolutePath.replace("\\", "/") // overcome string escape in source files.
  154. assertTrue("'$path' does not exist") { miraiCoreAllJar.exists() }
  155. buildFile.appendText(
  156. """
  157. dependencies {
  158. implementation(fileTree("$path"))
  159. }
  160. """.trimIndent()
  161. )
  162. runGradle("check")
  163. }
  164. @Suppress("PropertyName")
  165. private class TestBuilder {
  166. private val result = StringBuilder(
  167. """
  168. package test
  169. import org.junit.jupiter.api.*
  170. import java.lang.reflect.Method
  171. import kotlin.reflect.jvm.kotlinFunction
  172. import kotlin.test.assertTrue
  173. import kotlin.test.assertFalse
  174. private val Method.signature: String
  175. get() = buildString {
  176. append(kotlinFunction?.toString())
  177. return@buildString
  178. append(kotlinFunction?.visibility?.name?.lowercase())
  179. append(kotlinFunction?.visibility?.name?.lowercase())
  180. append(' ')
  181. append(returnType.canonicalName)
  182. append(' ')
  183. append(name)
  184. append('(')
  185. for (parameter in parameters) {
  186. append(parameter.type.canonicalName)
  187. append(' ')
  188. append(parameter.name)
  189. append(", ")
  190. }
  191. if (parameterCount != 0) {
  192. deleteAt(lastIndex)
  193. deleteAt(lastIndex)
  194. }
  195. append(')')
  196. }
  197. class MyTest {
  198. """.trimIndent()
  199. ).append("\n").append("\n")
  200. class ClassTestCase(
  201. val name: String,
  202. val qualifiedClassName: String,
  203. )
  204. class FunctionTestCase(
  205. val name: String,
  206. val qualifiedClassName: String,
  207. val signature: String,
  208. val relocated: (FunctionTestCase.() -> FunctionTestCase)? = null,
  209. )
  210. val `ktor-io` = ClassTestCase("ktor-io ByteBufferChannel", ByteBufferChannel)
  211. val `ktor-client-core` = ClassTestCase("ktor-client-core HttpClient", HttpClient)
  212. val `ktor-client-okhttp` = ClassTestCase("ktor-client-core OkHttp", KtorOkHttp)
  213. val `okhttp3-okhttp` = ClassTestCase("okhttp3 OkHttp", OkHttp)
  214. val okio = ClassTestCase("okio ByteString", OkIO)
  215. val `ExternalResource-input` =
  216. FunctionTestCase(
  217. "ExternalResource_input",
  218. "net.mamoe.mirai.utils.ExternalResource",
  219. "fun net.mamoe.mirai.utils.ExternalResource.input(): io.ktor.utils.io.core.Input"
  220. ) original@{
  221. FunctionTestCase(
  222. "relocated ExternalResource_input",
  223. "net.mamoe.mirai.utils.ExternalResource",
  224. "fun net.mamoe.mirai.utils.ExternalResource.input(): ${relocated("io.ktor.utils.io.core.Input")}"
  225. ) {
  226. this@original
  227. }
  228. }
  229. class RelocatedClassTestCase(
  230. val testCase: ClassTestCase
  231. )
  232. class BothClassTestCase(
  233. val testCase: ClassTestCase
  234. )
  235. private fun appendHasClass(name: String, qualifiedClassName: String) {
  236. result.append(
  237. """
  238. @Test
  239. fun `has ${name}`() {
  240. Class.forName("$qualifiedClassName")
  241. }
  242. """.trimIndent()
  243. ).append("\n")
  244. }
  245. fun appendClassHasMethod(name: String, qualifiedClassName: String, methodSignature: String) {
  246. result.append(
  247. """
  248. @Test
  249. fun `has ${name}`() {
  250. val signatures = Class.forName("$qualifiedClassName").declaredMethods.map { it.signature }
  251. assertTrue("All signatures: " + signatures.joinToString("\n")) { signatures.any { it == "$methodSignature" } }
  252. }
  253. """.trimIndent()
  254. ).append("\n")
  255. }
  256. fun appendClassMethodNotFound(name: String, qualifiedClassName: String, methodSignature: String) {
  257. result.append(
  258. """
  259. @Test
  260. fun `has ${name}`() {
  261. val signatures = Class.forName("$qualifiedClassName").declaredMethods.map { it.signature }
  262. assertFalse("All signatures: " + signatures.joinToString("\n")) { signatures.any { it == "$methodSignature" } }
  263. }
  264. """.trimIndent()
  265. ).append("\n")
  266. }
  267. private fun appendNotFound(name: String, qualifiedClassName: String) {
  268. result.append(
  269. """
  270. @Test
  271. fun `no relocated ${name}`() {
  272. assertThrows<ClassNotFoundException> { Class.forName("$qualifiedClassName") }
  273. }
  274. """.trimIndent()
  275. ).append("\n")
  276. }
  277. /**
  278. * Asserts a class exists. Also asserts its relocated class does not exist.
  279. */
  280. operator fun FunctionTestCase.unaryPlus() {
  281. appendClassHasMethod(name, qualifiedClassName, signature)
  282. relocated?.invoke(this)?.let { inverted ->
  283. appendClassMethodNotFound(inverted.name, inverted.qualifiedClassName, inverted.signature)
  284. }
  285. }
  286. /**
  287. * Asserts a class exists. Also asserts its relocated class does not exist.
  288. */
  289. operator fun ClassTestCase.unaryPlus() {
  290. appendHasClass(name, qualifiedClassName)
  291. appendNotFound("relocated $name", Companion.relocated(qualifiedClassName))
  292. }
  293. /**
  294. * Asserts a class does not exist.
  295. */
  296. operator fun ClassTestCase.unaryMinus() {
  297. appendNotFound(name, qualifiedClassName)
  298. }
  299. /**
  300. * Asserts a relocated class exists. Also asserts the original class does not exist.
  301. */
  302. operator fun RelocatedClassTestCase.unaryPlus() {
  303. this.testCase.run {
  304. appendHasClass("relocated $name", Companion.relocated(qualifiedClassName))
  305. appendNotFound(name, qualifiedClassName)
  306. }
  307. }
  308. /**
  309. * Asserts a relocated class does not exist.
  310. */
  311. operator fun RelocatedClassTestCase.unaryMinus() {
  312. this.testCase.run {
  313. appendNotFound("relocated $name", Companion.relocated(qualifiedClassName))
  314. }
  315. }
  316. /**
  317. * Asserts both the class and its relocated one do not exist.
  318. */
  319. operator fun BothClassTestCase.unaryMinus() {
  320. -this.testCase
  321. -relocated(this.testCase)
  322. }
  323. fun relocated(testCase: ClassTestCase): RelocatedClassTestCase = RelocatedClassTestCase(testCase)
  324. fun relocated(testCase: FunctionTestCase): FunctionTestCase = testCase.relocated!!(testCase)
  325. fun both(testCase: ClassTestCase) = BothClassTestCase(testCase)
  326. fun build(): String = result.append("\n}\n").toString()
  327. }
  328. private inline fun buildTestCases(action: TestBuilder.() -> Unit): String {
  329. return TestBuilder().apply(action).build()
  330. }
  331. private fun applyCodeFragment(fragment: String) {
  332. println("Applying code fragment: \n\n$fragment\n\n\n===========End of Fragment===========")
  333. testDir.resolve("test.kt").writeText(fragment)
  334. }
  335. }