2
0

CoreShadowRelocationTest.kt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. 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")
  113. exclude("net.mamoe", "mirai-core-utils")
  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. -both(`ktor-io`)
  125. -both(`ktor-client-core`)
  126. -both(`ktor-client-okhttp`)
  127. -both(`okhttp3-okhttp`)
  128. -both(okio)
  129. -both(`kt-bignum`)
  130. // +relocated(`ExternalResource-input`) // Will fail with no class def found error because there is no runtime ktor-io
  131. }
  132. applyCodeFragment(fragment)
  133. buildFile.appendText(
  134. """
  135. dependencies {
  136. implementation("net.mamoe:mirai-core-api:$miraiLocalVersion") {
  137. exclude("net.mamoe", "mirai-core-utils")
  138. }
  139. }
  140. """.trimIndent()
  141. )
  142. runGradle("check")
  143. }
  144. @Test
  145. @EnabledIf("isMiraiLocalAvailable", disabledReason = REASON_LOCAL_ARTIFACT_NOT_AVAILABLE)
  146. fun `test mirai-core-all`() {
  147. val fragment = buildTestCases {
  148. +relocated(`ktor-io`)
  149. +relocated(`ktor-client-core`)
  150. +relocated(`ktor-client-okhttp`)
  151. +relocated(`okhttp3-okhttp`)
  152. +relocated(okio)
  153. +relocated(`ExternalResource-input`)
  154. +relocated(`kt-bignum`)
  155. }
  156. applyCodeFragment(fragment)
  157. // mirai-core-all-2.99.0-deps-test-all.jar
  158. val miraiCoreAllJar =
  159. mavenLocalDir.resolve("net/mamoe/mirai-core-all/$miraiLocalVersion/mirai-core-all-$miraiLocalVersion-all.jar")
  160. val path = miraiCoreAllJar.absolutePath.replace("\\", "/") // overcome string escape in source files.
  161. assertTrue("'$path' does not exist") { miraiCoreAllJar.exists() }
  162. buildFile.appendText(
  163. """
  164. dependencies {
  165. implementation(fileTree("$path"))
  166. }
  167. """.trimIndent()
  168. )
  169. runGradle("check")
  170. }
  171. @Suppress("PropertyName")
  172. private class TestBuilder {
  173. private val result = StringBuilder(
  174. """
  175. package test
  176. import org.junit.jupiter.api.*
  177. import java.lang.reflect.Method
  178. import kotlin.reflect.jvm.kotlinFunction
  179. import kotlin.test.assertTrue
  180. import kotlin.test.assertFalse
  181. private val Method.signature: String
  182. get() = buildString {
  183. append(kotlinFunction?.toString())
  184. return@buildString
  185. append(kotlinFunction?.visibility?.name?.lowercase())
  186. append(kotlinFunction?.visibility?.name?.lowercase())
  187. append(' ')
  188. append(returnType.canonicalName)
  189. append(' ')
  190. append(name)
  191. append('(')
  192. for (parameter in parameters) {
  193. append(parameter.type.canonicalName)
  194. append(' ')
  195. append(parameter.name)
  196. append(", ")
  197. }
  198. if (parameterCount != 0) {
  199. deleteAt(lastIndex)
  200. deleteAt(lastIndex)
  201. }
  202. append(')')
  203. }
  204. class MyTest {
  205. """.trimIndent()
  206. ).append("\n").append("\n")
  207. class ClassTestCase(
  208. val name: String,
  209. val qualifiedClassName: String,
  210. )
  211. class FunctionTestCase(
  212. val name: String,
  213. val qualifiedClassName: String,
  214. val signature: String,
  215. val relocated: (FunctionTestCase.() -> FunctionTestCase)? = null,
  216. )
  217. val `ktor-io` = ClassTestCase("ktor-io ByteBufferChannel", ByteBufferChannel)
  218. val `ktor-client-core` = ClassTestCase("ktor-client-core HttpClient", HttpClient)
  219. val `ktor-client-okhttp` = ClassTestCase("ktor-client-core OkHttp", KtorOkHttp)
  220. val `okhttp3-okhttp` = ClassTestCase("okhttp3 OkHttp", OkHttp)
  221. val okio = ClassTestCase("okio ByteString", OkIO)
  222. val `kt-bignum` = ClassTestCase("kt-bignum BigInteger", BigInteger)
  223. val `ExternalResource-input` =
  224. FunctionTestCase(
  225. "ExternalResource_input",
  226. "net.mamoe.mirai.utils.ExternalResource",
  227. "fun net.mamoe.mirai.utils.ExternalResource.input(): io.ktor.utils.io.core.Input"
  228. ) original@{
  229. FunctionTestCase(
  230. "relocated ExternalResource_input",
  231. "net.mamoe.mirai.utils.ExternalResource",
  232. "fun net.mamoe.mirai.utils.ExternalResource.input(): ${relocated("io.ktor.utils.io.core.Input")}"
  233. ) {
  234. this@original
  235. }
  236. }
  237. class RelocatedClassTestCase(
  238. val testCase: ClassTestCase
  239. )
  240. class BothClassTestCase(
  241. val testCase: ClassTestCase
  242. )
  243. private fun appendHasClass(name: String, qualifiedClassName: String) {
  244. result.append(
  245. """
  246. @Test
  247. fun `has ${name}`() {
  248. Class.forName("$qualifiedClassName")
  249. }
  250. """.trimIndent()
  251. ).append("\n")
  252. }
  253. fun appendClassHasMethod(name: String, qualifiedClassName: String, methodSignature: String) {
  254. result.append(
  255. """
  256. @Test
  257. fun `has ${name}`() {
  258. val signatures = Class.forName("$qualifiedClassName").declaredMethods.map { it.signature }
  259. assertTrue("All signatures: " + signatures.joinToString("\n")) { signatures.any { it == "$methodSignature" } }
  260. }
  261. """.trimIndent()
  262. ).append("\n")
  263. }
  264. fun appendClassMethodNotFound(name: String, qualifiedClassName: String, methodSignature: String) {
  265. result.append(
  266. """
  267. @Test
  268. fun `has ${name}`() {
  269. val signatures = Class.forName("$qualifiedClassName").declaredMethods.map { it.signature }
  270. assertFalse("All signatures: " + signatures.joinToString("\n")) { signatures.any { it == "$methodSignature" } }
  271. }
  272. """.trimIndent()
  273. ).append("\n")
  274. }
  275. private fun appendNotFound(name: String, qualifiedClassName: String) {
  276. result.append(
  277. """
  278. @Test
  279. fun `no relocated ${name}`() {
  280. assertThrows<ClassNotFoundException> { Class.forName("$qualifiedClassName") }
  281. }
  282. """.trimIndent()
  283. ).append("\n")
  284. }
  285. /**
  286. * Asserts a class exists. Also asserts its relocated class does not exist.
  287. */
  288. operator fun FunctionTestCase.unaryPlus() {
  289. appendClassHasMethod(name, qualifiedClassName, signature)
  290. relocated?.invoke(this)?.let { inverted ->
  291. appendClassMethodNotFound(inverted.name, inverted.qualifiedClassName, inverted.signature)
  292. }
  293. }
  294. /**
  295. * Asserts a class exists. Also asserts its relocated class does not exist.
  296. */
  297. operator fun ClassTestCase.unaryPlus() {
  298. appendHasClass(name, qualifiedClassName)
  299. appendNotFound("relocated $name", Companion.relocated(qualifiedClassName))
  300. }
  301. /**
  302. * Asserts a class does not exist.
  303. */
  304. operator fun ClassTestCase.unaryMinus() {
  305. appendNotFound(name, qualifiedClassName)
  306. }
  307. /**
  308. * Asserts a relocated class exists. Also asserts the original class does not exist.
  309. */
  310. operator fun RelocatedClassTestCase.unaryPlus() {
  311. this.testCase.run {
  312. appendHasClass("relocated $name", Companion.relocated(qualifiedClassName))
  313. appendNotFound(name, qualifiedClassName)
  314. }
  315. }
  316. /**
  317. * Asserts a relocated class does not exist.
  318. */
  319. operator fun RelocatedClassTestCase.unaryMinus() {
  320. this.testCase.run {
  321. appendNotFound("relocated $name", Companion.relocated(qualifiedClassName))
  322. }
  323. }
  324. /**
  325. * Asserts both the class and its relocated one do not exist.
  326. */
  327. operator fun BothClassTestCase.unaryMinus() {
  328. -this.testCase
  329. -relocated(this.testCase)
  330. }
  331. fun relocated(testCase: ClassTestCase): RelocatedClassTestCase = RelocatedClassTestCase(testCase)
  332. fun relocated(testCase: FunctionTestCase): FunctionTestCase = testCase.relocated!!(testCase)
  333. fun both(testCase: ClassTestCase) = BothClassTestCase(testCase)
  334. fun build(): String = result.append("\n}\n").toString()
  335. }
  336. private inline fun buildTestCases(action: TestBuilder.() -> Unit): String {
  337. return TestBuilder().apply(action).build()
  338. }
  339. private fun applyCodeFragment(fragment: String) {
  340. println("Applying code fragment: \n\n$fragment\n\n\n===========End of Fragment===========")
  341. testDir.resolve("test.kt").writeText(fragment)
  342. }
  343. }