CoreShadowRelocationTest.kt 14 KB

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