java_test.go 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267
  1. // Copyright 2017 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package java
  15. import (
  16. "fmt"
  17. "os"
  18. "path/filepath"
  19. "reflect"
  20. "regexp"
  21. "strconv"
  22. "strings"
  23. "testing"
  24. "github.com/google/blueprint/proptools"
  25. "android/soong/android"
  26. "android/soong/cc"
  27. "android/soong/dexpreopt"
  28. "android/soong/genrule"
  29. "android/soong/python"
  30. )
  31. // Legacy preparer used for running tests within the java package.
  32. //
  33. // This includes everything that was needed to run any test in the java package prior to the
  34. // introduction of the test fixtures. Tests that are being converted to use fixtures directly
  35. // rather than through the testJava...() methods should avoid using this and instead use the
  36. // various preparers directly, using android.GroupFixturePreparers(...) to group them when
  37. // necessary.
  38. //
  39. // deprecated
  40. var prepareForJavaTest = android.GroupFixturePreparers(
  41. genrule.PrepareForTestWithGenRuleBuildComponents,
  42. // Get the CC build components but not default modules.
  43. cc.PrepareForTestWithCcBuildComponents,
  44. // Include all the default java modules.
  45. PrepareForTestWithJavaDefaultModules,
  46. PrepareForTestWithOverlayBuildComponents,
  47. python.PrepareForTestWithPythonBuildComponents,
  48. android.FixtureRegisterWithContext(func(ctx android.RegistrationContext) {
  49. ctx.RegisterPreSingletonType("sdk_versions", sdkPreSingletonFactory)
  50. }),
  51. PrepareForTestWithDexpreopt,
  52. )
  53. func TestMain(m *testing.M) {
  54. os.Exit(m.Run())
  55. }
  56. // testJavaError is a legacy way of running tests of java modules that expect errors.
  57. //
  58. // See testJava for an explanation as to how to stop using this deprecated method.
  59. //
  60. // deprecated
  61. func testJavaError(t *testing.T, pattern string, bp string) (*android.TestContext, android.Config) {
  62. t.Helper()
  63. result := android.GroupFixturePreparers(
  64. prepareForJavaTest, dexpreopt.PrepareForTestByEnablingDexpreopt).
  65. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(pattern)).
  66. RunTestWithBp(t, bp)
  67. return result.TestContext, result.Config
  68. }
  69. // testJavaErrorWithConfig is a legacy way of running tests of java modules that expect errors.
  70. //
  71. // See testJava for an explanation as to how to stop using this deprecated method.
  72. //
  73. // deprecated
  74. func testJavaErrorWithConfig(t *testing.T, pattern string, config android.Config) (*android.TestContext, android.Config) {
  75. t.Helper()
  76. // This must be done on the supplied config and not as part of the fixture because any changes to
  77. // the fixture's config will be ignored when RunTestWithConfig replaces it.
  78. pathCtx := android.PathContextForTesting(config)
  79. dexpreopt.SetTestGlobalConfig(config, dexpreopt.GlobalConfigForTests(pathCtx))
  80. result := prepareForJavaTest.
  81. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(pattern)).
  82. RunTestWithConfig(t, config)
  83. return result.TestContext, result.Config
  84. }
  85. // testJavaWithFS runs tests using the prepareForJavaTest
  86. //
  87. // See testJava for an explanation as to how to stop using this deprecated method.
  88. //
  89. // deprecated
  90. func testJavaWithFS(t *testing.T, bp string, fs android.MockFS) (*android.TestContext, android.Config) {
  91. t.Helper()
  92. result := android.GroupFixturePreparers(
  93. prepareForJavaTest, fs.AddToFixture()).RunTestWithBp(t, bp)
  94. return result.TestContext, result.Config
  95. }
  96. // testJava runs tests using the prepareForJavaTest
  97. //
  98. // Do not add any new usages of this, instead use the prepareForJavaTest directly as it makes it
  99. // much easier to customize the test behavior.
  100. //
  101. // If it is necessary to customize the behavior of an existing test that uses this then please first
  102. // convert the test to using prepareForJavaTest first and then in a following change add the
  103. // appropriate fixture preparers. Keeping the conversion change separate makes it easy to verify
  104. // that it did not change the test behavior unexpectedly.
  105. //
  106. // deprecated
  107. func testJava(t *testing.T, bp string) (*android.TestContext, android.Config) {
  108. t.Helper()
  109. result := prepareForJavaTest.RunTestWithBp(t, bp)
  110. return result.TestContext, result.Config
  111. }
  112. // defaultModuleToPath constructs a path to the turbine generate jar for a default test module that
  113. // is defined in PrepareForIntegrationTestWithJava
  114. func defaultModuleToPath(name string) string {
  115. switch {
  116. case name == `""`:
  117. return name
  118. case strings.HasSuffix(name, ".jar"):
  119. return name
  120. default:
  121. return filepath.Join("out", "soong", ".intermediates", defaultJavaDir, name, "android_common", "turbine-combined", name+".jar")
  122. }
  123. }
  124. // Test that the PrepareForTestWithJavaDefaultModules provides all the files that it uses by
  125. // running it in a fixture that requires all source files to exist.
  126. func TestPrepareForTestWithJavaDefaultModules(t *testing.T) {
  127. android.GroupFixturePreparers(
  128. PrepareForTestWithJavaDefaultModules,
  129. android.PrepareForTestDisallowNonExistentPaths,
  130. ).RunTest(t)
  131. }
  132. func TestJavaLinkType(t *testing.T) {
  133. testJava(t, `
  134. java_library {
  135. name: "foo",
  136. srcs: ["a.java"],
  137. libs: ["bar"],
  138. static_libs: ["baz"],
  139. }
  140. java_library {
  141. name: "bar",
  142. sdk_version: "current",
  143. srcs: ["b.java"],
  144. }
  145. java_library {
  146. name: "baz",
  147. sdk_version: "system_current",
  148. srcs: ["c.java"],
  149. }
  150. `)
  151. testJavaError(t, "consider adjusting sdk_version: OR platform_apis:", `
  152. java_library {
  153. name: "foo",
  154. srcs: ["a.java"],
  155. libs: ["bar"],
  156. sdk_version: "current",
  157. static_libs: ["baz"],
  158. }
  159. java_library {
  160. name: "bar",
  161. sdk_version: "current",
  162. srcs: ["b.java"],
  163. }
  164. java_library {
  165. name: "baz",
  166. sdk_version: "system_current",
  167. srcs: ["c.java"],
  168. }
  169. `)
  170. testJava(t, `
  171. java_library {
  172. name: "foo",
  173. srcs: ["a.java"],
  174. libs: ["bar"],
  175. sdk_version: "system_current",
  176. static_libs: ["baz"],
  177. }
  178. java_library {
  179. name: "bar",
  180. sdk_version: "current",
  181. srcs: ["b.java"],
  182. }
  183. java_library {
  184. name: "baz",
  185. sdk_version: "system_current",
  186. srcs: ["c.java"],
  187. }
  188. `)
  189. testJavaError(t, "consider adjusting sdk_version: OR platform_apis:", `
  190. java_library {
  191. name: "foo",
  192. srcs: ["a.java"],
  193. libs: ["bar"],
  194. sdk_version: "system_current",
  195. static_libs: ["baz"],
  196. }
  197. java_library {
  198. name: "bar",
  199. sdk_version: "current",
  200. srcs: ["b.java"],
  201. }
  202. java_library {
  203. name: "baz",
  204. srcs: ["c.java"],
  205. }
  206. `)
  207. }
  208. func TestSimple(t *testing.T) {
  209. ctx, _ := testJava(t, `
  210. java_library {
  211. name: "foo",
  212. srcs: ["a.java"],
  213. libs: ["bar"],
  214. static_libs: ["baz"],
  215. }
  216. java_library {
  217. name: "bar",
  218. srcs: ["b.java"],
  219. }
  220. java_library {
  221. name: "baz",
  222. srcs: ["c.java"],
  223. }
  224. `)
  225. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  226. combineJar := ctx.ModuleForTests("foo", "android_common").Description("for javac")
  227. if len(javac.Inputs) != 1 || javac.Inputs[0].String() != "a.java" {
  228. t.Errorf(`foo inputs %v != ["a.java"]`, javac.Inputs)
  229. }
  230. baz := ctx.ModuleForTests("baz", "android_common").Rule("javac").Output.String()
  231. barTurbine := filepath.Join("out", "soong", ".intermediates", "bar", "android_common", "turbine-combined", "bar.jar")
  232. bazTurbine := filepath.Join("out", "soong", ".intermediates", "baz", "android_common", "turbine-combined", "baz.jar")
  233. android.AssertStringDoesContain(t, "foo classpath", javac.Args["classpath"], barTurbine)
  234. android.AssertStringDoesContain(t, "foo classpath", javac.Args["classpath"], bazTurbine)
  235. if len(combineJar.Inputs) != 2 || combineJar.Inputs[1].String() != baz {
  236. t.Errorf("foo combineJar inputs %v does not contain %q", combineJar.Inputs, baz)
  237. }
  238. }
  239. func TestExportedPlugins(t *testing.T) {
  240. type Result struct {
  241. library string
  242. processors string
  243. disableTurbine bool
  244. }
  245. var tests = []struct {
  246. name string
  247. extra string
  248. results []Result
  249. }{
  250. {
  251. name: "Exported plugin is not a direct plugin",
  252. extra: `java_library { name: "exports", srcs: ["a.java"], exported_plugins: ["plugin"] }`,
  253. results: []Result{{library: "exports", processors: "-proc:none"}},
  254. },
  255. {
  256. name: "Exports plugin to dependee",
  257. extra: `
  258. java_library{name: "exports", exported_plugins: ["plugin"]}
  259. java_library{name: "foo", srcs: ["a.java"], libs: ["exports"]}
  260. java_library{name: "bar", srcs: ["a.java"], static_libs: ["exports"]}
  261. `,
  262. results: []Result{
  263. {library: "foo", processors: "-processor com.android.TestPlugin"},
  264. {library: "bar", processors: "-processor com.android.TestPlugin"},
  265. },
  266. },
  267. {
  268. name: "Exports plugin to android_library",
  269. extra: `
  270. java_library{name: "exports", exported_plugins: ["plugin"]}
  271. android_library{name: "foo", srcs: ["a.java"], libs: ["exports"]}
  272. android_library{name: "bar", srcs: ["a.java"], static_libs: ["exports"]}
  273. `,
  274. results: []Result{
  275. {library: "foo", processors: "-processor com.android.TestPlugin"},
  276. {library: "bar", processors: "-processor com.android.TestPlugin"},
  277. },
  278. },
  279. {
  280. name: "Exports plugin is not propagated via transitive deps",
  281. extra: `
  282. java_library{name: "exports", exported_plugins: ["plugin"]}
  283. java_library{name: "foo", srcs: ["a.java"], libs: ["exports"]}
  284. java_library{name: "bar", srcs: ["a.java"], static_libs: ["foo"]}
  285. `,
  286. results: []Result{
  287. {library: "foo", processors: "-processor com.android.TestPlugin"},
  288. {library: "bar", processors: "-proc:none"},
  289. },
  290. },
  291. {
  292. name: "Exports plugin appends to plugins",
  293. extra: `
  294. java_plugin{name: "plugin2", processor_class: "com.android.TestPlugin2"}
  295. java_library{name: "exports", exported_plugins: ["plugin"]}
  296. java_library{name: "foo", srcs: ["a.java"], libs: ["exports"], plugins: ["plugin2"]}
  297. `,
  298. results: []Result{
  299. {library: "foo", processors: "-processor com.android.TestPlugin,com.android.TestPlugin2"},
  300. },
  301. },
  302. {
  303. name: "Exports plugin to with generates_api to dependee",
  304. extra: `
  305. java_library{name: "exports", exported_plugins: ["plugin_generates_api"]}
  306. java_library{name: "foo", srcs: ["a.java"], libs: ["exports"]}
  307. java_library{name: "bar", srcs: ["a.java"], static_libs: ["exports"]}
  308. `,
  309. results: []Result{
  310. {library: "foo", processors: "-processor com.android.TestPlugin", disableTurbine: true},
  311. {library: "bar", processors: "-processor com.android.TestPlugin", disableTurbine: true},
  312. },
  313. },
  314. }
  315. for _, test := range tests {
  316. t.Run(test.name, func(t *testing.T) {
  317. ctx, _ := testJava(t, `
  318. java_plugin {
  319. name: "plugin",
  320. processor_class: "com.android.TestPlugin",
  321. }
  322. java_plugin {
  323. name: "plugin_generates_api",
  324. generates_api: true,
  325. processor_class: "com.android.TestPlugin",
  326. }
  327. `+test.extra)
  328. for _, want := range test.results {
  329. javac := ctx.ModuleForTests(want.library, "android_common").Rule("javac")
  330. if javac.Args["processor"] != want.processors {
  331. t.Errorf("For library %v, expected %v, found %v", want.library, want.processors, javac.Args["processor"])
  332. }
  333. turbine := ctx.ModuleForTests(want.library, "android_common").MaybeRule("turbine")
  334. disableTurbine := turbine.BuildParams.Rule == nil
  335. if disableTurbine != want.disableTurbine {
  336. t.Errorf("For library %v, expected disableTurbine %v, found %v", want.library, want.disableTurbine, disableTurbine)
  337. }
  338. }
  339. })
  340. }
  341. }
  342. func TestSdkVersionByPartition(t *testing.T) {
  343. testJavaError(t, "sdk_version must have a value when the module is located at vendor or product", `
  344. java_library {
  345. name: "foo",
  346. srcs: ["a.java"],
  347. vendor: true,
  348. }
  349. `)
  350. testJava(t, `
  351. java_library {
  352. name: "bar",
  353. srcs: ["b.java"],
  354. }
  355. `)
  356. for _, enforce := range []bool{true, false} {
  357. bp := `
  358. java_library {
  359. name: "foo",
  360. srcs: ["a.java"],
  361. product_specific: true,
  362. }
  363. `
  364. errorHandler := android.FixtureExpectsNoErrors
  365. if enforce {
  366. errorHandler = android.FixtureExpectsAtLeastOneErrorMatchingPattern("sdk_version must have a value when the module is located at vendor or product")
  367. }
  368. android.GroupFixturePreparers(
  369. PrepareForTestWithJavaDefaultModules,
  370. android.FixtureModifyProductVariables(func(variables android.FixtureProductVariables) {
  371. variables.EnforceProductPartitionInterface = proptools.BoolPtr(enforce)
  372. }),
  373. ).
  374. ExtendWithErrorHandler(errorHandler).
  375. RunTestWithBp(t, bp)
  376. }
  377. }
  378. func TestArchSpecific(t *testing.T) {
  379. ctx, _ := testJava(t, `
  380. java_library {
  381. name: "foo",
  382. srcs: ["a.java"],
  383. target: {
  384. android: {
  385. srcs: ["b.java"],
  386. },
  387. },
  388. }
  389. `)
  390. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  391. if len(javac.Inputs) != 2 || javac.Inputs[0].String() != "a.java" || javac.Inputs[1].String() != "b.java" {
  392. t.Errorf(`foo inputs %v != ["a.java", "b.java"]`, javac.Inputs)
  393. }
  394. }
  395. func TestBinary(t *testing.T) {
  396. ctx, _ := testJava(t, `
  397. java_library_host {
  398. name: "foo",
  399. srcs: ["a.java"],
  400. }
  401. java_binary_host {
  402. name: "bar",
  403. srcs: ["b.java"],
  404. static_libs: ["foo"],
  405. jni_libs: ["libjni"],
  406. }
  407. cc_library_shared {
  408. name: "libjni",
  409. host_supported: true,
  410. device_supported: false,
  411. stl: "none",
  412. }
  413. `)
  414. buildOS := android.BuildOs.String()
  415. bar := ctx.ModuleForTests("bar", buildOS+"_common")
  416. barJar := bar.Output("bar.jar").Output.String()
  417. barWrapper := ctx.ModuleForTests("bar", buildOS+"_x86_64")
  418. barWrapperDeps := barWrapper.Output("bar").Implicits.Strings()
  419. libjni := ctx.ModuleForTests("libjni", buildOS+"_x86_64_shared")
  420. libjniSO := libjni.Rule("Cp").Output.String()
  421. // Test that the install binary wrapper depends on the installed jar file
  422. if g, w := barWrapperDeps, barJar; !android.InList(w, g) {
  423. t.Errorf("expected binary wrapper implicits to contain %q, got %q", w, g)
  424. }
  425. // Test that the install binary wrapper depends on the installed JNI libraries
  426. if g, w := barWrapperDeps, libjniSO; !android.InList(w, g) {
  427. t.Errorf("expected binary wrapper implicits to contain %q, got %q", w, g)
  428. }
  429. }
  430. func TestHostBinaryNoJavaDebugInfoOverride(t *testing.T) {
  431. bp := `
  432. java_library {
  433. name: "target_library",
  434. srcs: ["a.java"],
  435. }
  436. java_binary_host {
  437. name: "host_binary",
  438. srcs: ["b.java"],
  439. }
  440. `
  441. result := android.GroupFixturePreparers(
  442. PrepareForTestWithJavaDefaultModules,
  443. android.FixtureModifyProductVariables(func(variables android.FixtureProductVariables) {
  444. variables.MinimizeJavaDebugInfo = proptools.BoolPtr(true)
  445. }),
  446. ).RunTestWithBp(t, bp)
  447. // first, check that the -g flag is added to target modules
  448. targetLibrary := result.ModuleForTests("target_library", "android_common")
  449. targetJavaFlags := targetLibrary.Module().VariablesForTests()["javacFlags"]
  450. if !strings.Contains(targetJavaFlags, "-g:source,lines") {
  451. t.Errorf("target library javac flags %v should contain "+
  452. "-g:source,lines override with MinimizeJavaDebugInfo", targetJavaFlags)
  453. }
  454. // check that -g is not overridden for host modules
  455. buildOS := android.BuildOs.String()
  456. hostBinary := result.ModuleForTests("host_binary", buildOS+"_common")
  457. hostJavaFlags := hostBinary.Module().VariablesForTests()["javacFlags"]
  458. if strings.Contains(hostJavaFlags, "-g:source,lines") {
  459. t.Errorf("java_binary_host javac flags %v should not have "+
  460. "-g:source,lines override with MinimizeJavaDebugInfo", hostJavaFlags)
  461. }
  462. }
  463. func TestPrebuilts(t *testing.T) {
  464. ctx, _ := testJava(t, `
  465. java_library {
  466. name: "foo",
  467. srcs: ["a.java", ":stubs-source"],
  468. libs: ["bar", "sdklib"],
  469. static_libs: ["baz"],
  470. }
  471. java_import {
  472. name: "bar",
  473. jars: ["a.jar"],
  474. }
  475. java_import {
  476. name: "baz",
  477. jars: ["b.jar"],
  478. sdk_version: "current",
  479. compile_dex: true,
  480. }
  481. dex_import {
  482. name: "qux",
  483. jars: ["b.jar"],
  484. }
  485. java_sdk_library_import {
  486. name: "sdklib",
  487. public: {
  488. jars: ["c.jar"],
  489. },
  490. }
  491. prebuilt_stubs_sources {
  492. name: "stubs-source",
  493. srcs: ["stubs/sources"],
  494. }
  495. java_test_import {
  496. name: "test",
  497. jars: ["a.jar"],
  498. test_suites: ["cts"],
  499. test_config: "AndroidTest.xml",
  500. }
  501. `)
  502. fooModule := ctx.ModuleForTests("foo", "android_common")
  503. javac := fooModule.Rule("javac")
  504. combineJar := ctx.ModuleForTests("foo", "android_common").Description("for javac")
  505. barModule := ctx.ModuleForTests("bar", "android_common")
  506. barJar := barModule.Rule("combineJar").Output
  507. bazModule := ctx.ModuleForTests("baz", "android_common")
  508. bazJar := bazModule.Rule("combineJar").Output
  509. sdklibStubsJar := ctx.ModuleForTests("sdklib.stubs", "android_common").Rule("combineJar").Output
  510. fooLibrary := fooModule.Module().(*Library)
  511. assertDeepEquals(t, "foo java sources incorrect",
  512. []string{"a.java"}, fooLibrary.compiledJavaSrcs.Strings())
  513. assertDeepEquals(t, "foo java source jars incorrect",
  514. []string{".intermediates/stubs-source/android_common/stubs-source-stubs.srcjar"},
  515. android.NormalizePathsForTesting(fooLibrary.compiledSrcJars))
  516. if !strings.Contains(javac.Args["classpath"], barJar.String()) {
  517. t.Errorf("foo classpath %v does not contain %q", javac.Args["classpath"], barJar.String())
  518. }
  519. barDexJar := barModule.Module().(*Import).DexJarBuildPath()
  520. if barDexJar != nil {
  521. t.Errorf("bar dex jar build path expected to be nil, got %q", barDexJar)
  522. }
  523. if !strings.Contains(javac.Args["classpath"], sdklibStubsJar.String()) {
  524. t.Errorf("foo classpath %v does not contain %q", javac.Args["classpath"], sdklibStubsJar.String())
  525. }
  526. if len(combineJar.Inputs) != 2 || combineJar.Inputs[1].String() != bazJar.String() {
  527. t.Errorf("foo combineJar inputs %v does not contain %q", combineJar.Inputs, bazJar.String())
  528. }
  529. bazDexJar := bazModule.Module().(*Import).DexJarBuildPath()
  530. expectedDexJar := "out/soong/.intermediates/baz/android_common/dex/baz.jar"
  531. android.AssertPathRelativeToTopEquals(t, "baz dex jar build path", expectedDexJar, bazDexJar)
  532. ctx.ModuleForTests("qux", "android_common").Rule("Cp")
  533. }
  534. func assertDeepEquals(t *testing.T, message string, expected interface{}, actual interface{}) {
  535. if !reflect.DeepEqual(expected, actual) {
  536. t.Errorf("%s: expected %q, found %q", message, expected, actual)
  537. }
  538. }
  539. func TestPrebuiltStubsSources(t *testing.T) {
  540. test := func(t *testing.T, sourcesPath string, expectedInputs []string) {
  541. ctx, _ := testJavaWithFS(t, fmt.Sprintf(`
  542. prebuilt_stubs_sources {
  543. name: "stubs-source",
  544. srcs: ["%s"],
  545. }`, sourcesPath), map[string][]byte{
  546. "stubs/sources/pkg/A.java": nil,
  547. "stubs/sources/pkg/B.java": nil,
  548. })
  549. zipSrc := ctx.ModuleForTests("stubs-source", "android_common").Rule("zip_src")
  550. if expected, actual := expectedInputs, zipSrc.Inputs.Strings(); !reflect.DeepEqual(expected, actual) {
  551. t.Errorf("mismatch of inputs to soong_zip: expected %q, actual %q", expected, actual)
  552. }
  553. }
  554. t.Run("empty/missing directory", func(t *testing.T) {
  555. test(t, "empty-directory", nil)
  556. })
  557. t.Run("non-empty set of sources", func(t *testing.T) {
  558. test(t, "stubs/sources", []string{
  559. "stubs/sources/pkg/A.java",
  560. "stubs/sources/pkg/B.java",
  561. })
  562. })
  563. }
  564. func TestJavaSdkLibraryImport(t *testing.T) {
  565. result := prepareForJavaTest.RunTestWithBp(t, `
  566. java_library {
  567. name: "foo",
  568. srcs: ["a.java"],
  569. libs: ["sdklib"],
  570. sdk_version: "current",
  571. }
  572. java_library {
  573. name: "foo.system",
  574. srcs: ["a.java"],
  575. libs: ["sdklib"],
  576. sdk_version: "system_current",
  577. }
  578. java_library {
  579. name: "foo.test",
  580. srcs: ["a.java"],
  581. libs: ["sdklib"],
  582. sdk_version: "test_current",
  583. }
  584. java_sdk_library_import {
  585. name: "sdklib",
  586. public: {
  587. jars: ["a.jar"],
  588. },
  589. system: {
  590. jars: ["b.jar"],
  591. },
  592. test: {
  593. jars: ["c.jar"],
  594. stub_srcs: ["c.java"],
  595. },
  596. }
  597. `)
  598. for _, scope := range []string{"", ".system", ".test"} {
  599. fooModule := result.ModuleForTests("foo"+scope, "android_common")
  600. javac := fooModule.Rule("javac")
  601. sdklibStubsJar := result.ModuleForTests("sdklib.stubs"+scope, "android_common").Rule("combineJar").Output
  602. android.AssertStringDoesContain(t, "foo classpath", javac.Args["classpath"], sdklibStubsJar.String())
  603. }
  604. CheckModuleDependencies(t, result.TestContext, "sdklib", "android_common", []string{
  605. `prebuilt_sdklib.stubs`,
  606. `prebuilt_sdklib.stubs.source.test`,
  607. `prebuilt_sdklib.stubs.system`,
  608. `prebuilt_sdklib.stubs.test`,
  609. })
  610. }
  611. func TestJavaSdkLibraryImport_WithSource(t *testing.T) {
  612. result := android.GroupFixturePreparers(
  613. prepareForJavaTest,
  614. PrepareForTestWithJavaSdkLibraryFiles,
  615. FixtureWithLastReleaseApis("sdklib"),
  616. ).RunTestWithBp(t, `
  617. java_sdk_library {
  618. name: "sdklib",
  619. srcs: ["a.java"],
  620. sdk_version: "none",
  621. system_modules: "none",
  622. public: {
  623. enabled: true,
  624. },
  625. }
  626. java_sdk_library_import {
  627. name: "sdklib",
  628. public: {
  629. jars: ["a.jar"],
  630. },
  631. }
  632. `)
  633. CheckModuleDependencies(t, result.TestContext, "sdklib", "android_common", []string{
  634. `dex2oatd`,
  635. `prebuilt_sdklib`,
  636. `sdklib.impl`,
  637. `sdklib.stubs`,
  638. `sdklib.stubs.source`,
  639. `sdklib.xml`,
  640. })
  641. CheckModuleDependencies(t, result.TestContext, "prebuilt_sdklib", "android_common", []string{
  642. `prebuilt_sdklib.stubs`,
  643. `sdklib.impl`,
  644. // This should be prebuilt_sdklib.stubs but is set to sdklib.stubs because the
  645. // dependency is added after prebuilts may have been renamed and so has to use
  646. // the renamed name.
  647. `sdklib.xml`,
  648. })
  649. }
  650. func TestJavaSdkLibraryImport_Preferred(t *testing.T) {
  651. result := android.GroupFixturePreparers(
  652. prepareForJavaTest,
  653. PrepareForTestWithJavaSdkLibraryFiles,
  654. FixtureWithLastReleaseApis("sdklib"),
  655. ).RunTestWithBp(t, `
  656. java_sdk_library {
  657. name: "sdklib",
  658. srcs: ["a.java"],
  659. sdk_version: "none",
  660. system_modules: "none",
  661. public: {
  662. enabled: true,
  663. },
  664. }
  665. java_sdk_library_import {
  666. name: "sdklib",
  667. prefer: true,
  668. public: {
  669. jars: ["a.jar"],
  670. },
  671. }
  672. `)
  673. CheckModuleDependencies(t, result.TestContext, "sdklib", "android_common", []string{
  674. `dex2oatd`,
  675. `prebuilt_sdklib`,
  676. `sdklib.impl`,
  677. `sdklib.stubs`,
  678. `sdklib.stubs.source`,
  679. `sdklib.xml`,
  680. })
  681. CheckModuleDependencies(t, result.TestContext, "prebuilt_sdklib", "android_common", []string{
  682. `prebuilt_sdklib.stubs`,
  683. `sdklib.impl`,
  684. `sdklib.xml`,
  685. })
  686. }
  687. func TestJavaSdkLibraryEnforce(t *testing.T) {
  688. partitionToBpOption := func(partition string) string {
  689. switch partition {
  690. case "system":
  691. return ""
  692. case "vendor":
  693. return "soc_specific: true,"
  694. case "product":
  695. return "product_specific: true,"
  696. default:
  697. panic("Invalid partition group name: " + partition)
  698. }
  699. }
  700. type testConfigInfo struct {
  701. libraryType string
  702. fromPartition string
  703. toPartition string
  704. enforceVendorInterface bool
  705. enforceProductInterface bool
  706. enforceJavaSdkLibraryCheck bool
  707. allowList []string
  708. }
  709. createPreparer := func(info testConfigInfo) android.FixturePreparer {
  710. bpFileTemplate := `
  711. java_library {
  712. name: "foo",
  713. srcs: ["foo.java"],
  714. libs: ["bar"],
  715. sdk_version: "current",
  716. %s
  717. }
  718. %s {
  719. name: "bar",
  720. srcs: ["bar.java"],
  721. sdk_version: "current",
  722. %s
  723. }
  724. `
  725. bpFile := fmt.Sprintf(bpFileTemplate,
  726. partitionToBpOption(info.fromPartition),
  727. info.libraryType,
  728. partitionToBpOption(info.toPartition))
  729. return android.GroupFixturePreparers(
  730. PrepareForTestWithJavaSdkLibraryFiles,
  731. FixtureWithLastReleaseApis("bar"),
  732. android.FixtureWithRootAndroidBp(bpFile),
  733. android.FixtureModifyProductVariables(func(variables android.FixtureProductVariables) {
  734. variables.EnforceProductPartitionInterface = proptools.BoolPtr(info.enforceProductInterface)
  735. if info.enforceVendorInterface {
  736. variables.DeviceVndkVersion = proptools.StringPtr("current")
  737. }
  738. variables.EnforceInterPartitionJavaSdkLibrary = proptools.BoolPtr(info.enforceJavaSdkLibraryCheck)
  739. variables.InterPartitionJavaLibraryAllowList = info.allowList
  740. }),
  741. )
  742. }
  743. runTest := func(t *testing.T, info testConfigInfo, expectedErrorPattern string) {
  744. t.Run(fmt.Sprintf("%v", info), func(t *testing.T) {
  745. errorHandler := android.FixtureExpectsNoErrors
  746. if expectedErrorPattern != "" {
  747. errorHandler = android.FixtureExpectsAtLeastOneErrorMatchingPattern(expectedErrorPattern)
  748. }
  749. android.GroupFixturePreparers(
  750. prepareForJavaTest,
  751. createPreparer(info),
  752. ).
  753. ExtendWithErrorHandler(errorHandler).
  754. RunTest(t)
  755. })
  756. }
  757. errorMessage := "is not allowed across the partitions"
  758. runTest(t, testConfigInfo{
  759. libraryType: "java_library",
  760. fromPartition: "product",
  761. toPartition: "system",
  762. enforceVendorInterface: true,
  763. enforceProductInterface: true,
  764. enforceJavaSdkLibraryCheck: false,
  765. }, "")
  766. runTest(t, testConfigInfo{
  767. libraryType: "java_library",
  768. fromPartition: "product",
  769. toPartition: "system",
  770. enforceVendorInterface: true,
  771. enforceProductInterface: false,
  772. enforceJavaSdkLibraryCheck: true,
  773. }, "")
  774. runTest(t, testConfigInfo{
  775. libraryType: "java_library",
  776. fromPartition: "product",
  777. toPartition: "system",
  778. enforceVendorInterface: true,
  779. enforceProductInterface: true,
  780. enforceJavaSdkLibraryCheck: true,
  781. }, errorMessage)
  782. runTest(t, testConfigInfo{
  783. libraryType: "java_library",
  784. fromPartition: "vendor",
  785. toPartition: "system",
  786. enforceVendorInterface: true,
  787. enforceProductInterface: true,
  788. enforceJavaSdkLibraryCheck: true,
  789. }, errorMessage)
  790. runTest(t, testConfigInfo{
  791. libraryType: "java_library",
  792. fromPartition: "vendor",
  793. toPartition: "system",
  794. enforceVendorInterface: true,
  795. enforceProductInterface: true,
  796. enforceJavaSdkLibraryCheck: true,
  797. allowList: []string{"bar"},
  798. }, "")
  799. runTest(t, testConfigInfo{
  800. libraryType: "java_library",
  801. fromPartition: "vendor",
  802. toPartition: "product",
  803. enforceVendorInterface: true,
  804. enforceProductInterface: true,
  805. enforceJavaSdkLibraryCheck: true,
  806. }, errorMessage)
  807. runTest(t, testConfigInfo{
  808. libraryType: "java_sdk_library",
  809. fromPartition: "product",
  810. toPartition: "system",
  811. enforceVendorInterface: true,
  812. enforceProductInterface: true,
  813. enforceJavaSdkLibraryCheck: true,
  814. }, "")
  815. runTest(t, testConfigInfo{
  816. libraryType: "java_sdk_library",
  817. fromPartition: "vendor",
  818. toPartition: "system",
  819. enforceVendorInterface: true,
  820. enforceProductInterface: true,
  821. enforceJavaSdkLibraryCheck: true,
  822. }, "")
  823. runTest(t, testConfigInfo{
  824. libraryType: "java_sdk_library",
  825. fromPartition: "vendor",
  826. toPartition: "product",
  827. enforceVendorInterface: true,
  828. enforceProductInterface: true,
  829. enforceJavaSdkLibraryCheck: true,
  830. }, "")
  831. }
  832. func TestDefaults(t *testing.T) {
  833. ctx, _ := testJava(t, `
  834. java_defaults {
  835. name: "defaults",
  836. srcs: ["a.java"],
  837. libs: ["bar"],
  838. static_libs: ["baz"],
  839. optimize: {enabled: false},
  840. }
  841. java_library {
  842. name: "foo",
  843. defaults: ["defaults"],
  844. }
  845. java_library {
  846. name: "bar",
  847. srcs: ["b.java"],
  848. }
  849. java_library {
  850. name: "baz",
  851. srcs: ["c.java"],
  852. }
  853. android_test {
  854. name: "atestOptimize",
  855. defaults: ["defaults"],
  856. optimize: {enabled: true},
  857. }
  858. android_test {
  859. name: "atestNoOptimize",
  860. defaults: ["defaults"],
  861. }
  862. android_test {
  863. name: "atestDefault",
  864. srcs: ["a.java"],
  865. }
  866. `)
  867. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  868. combineJar := ctx.ModuleForTests("foo", "android_common").Description("for javac")
  869. if len(javac.Inputs) != 1 || javac.Inputs[0].String() != "a.java" {
  870. t.Errorf(`foo inputs %v != ["a.java"]`, javac.Inputs)
  871. }
  872. barTurbine := filepath.Join("out", "soong", ".intermediates", "bar", "android_common", "turbine-combined", "bar.jar")
  873. if !strings.Contains(javac.Args["classpath"], barTurbine) {
  874. t.Errorf("foo classpath %v does not contain %q", javac.Args["classpath"], barTurbine)
  875. }
  876. baz := ctx.ModuleForTests("baz", "android_common").Rule("javac").Output.String()
  877. if len(combineJar.Inputs) != 2 || combineJar.Inputs[1].String() != baz {
  878. t.Errorf("foo combineJar inputs %v does not contain %q", combineJar.Inputs, baz)
  879. }
  880. atestOptimize := ctx.ModuleForTests("atestOptimize", "android_common").MaybeRule("r8")
  881. if atestOptimize.Output == nil {
  882. t.Errorf("atestOptimize should optimize APK")
  883. }
  884. atestNoOptimize := ctx.ModuleForTests("atestNoOptimize", "android_common").MaybeRule("d8")
  885. if atestNoOptimize.Output == nil {
  886. t.Errorf("atestNoOptimize should not optimize APK")
  887. }
  888. atestDefault := ctx.ModuleForTests("atestDefault", "android_common").MaybeRule("r8")
  889. if atestDefault.Output == nil {
  890. t.Errorf("atestDefault should optimize APK")
  891. }
  892. }
  893. func TestResources(t *testing.T) {
  894. var table = []struct {
  895. name string
  896. prop string
  897. extra string
  898. args string
  899. }{
  900. {
  901. // Test that a module with java_resource_dirs includes the files
  902. name: "resource dirs",
  903. prop: `java_resource_dirs: ["java-res"]`,
  904. args: "-C java-res -f java-res/a/a -f java-res/b/b",
  905. },
  906. {
  907. // Test that a module with java_resources includes the files
  908. name: "resource files",
  909. prop: `java_resources: ["java-res/a/a", "java-res/b/b"]`,
  910. args: "-C . -f java-res/a/a -f java-res/b/b",
  911. },
  912. {
  913. // Test that a module with a filegroup in java_resources includes the files with the
  914. // path prefix
  915. name: "resource filegroup",
  916. prop: `java_resources: [":foo-res"]`,
  917. extra: `
  918. filegroup {
  919. name: "foo-res",
  920. path: "java-res",
  921. srcs: ["java-res/a/a", "java-res/b/b"],
  922. }`,
  923. args: "-C java-res -f java-res/a/a -f java-res/b/b",
  924. },
  925. {
  926. // Test that a module with wildcards in java_resource_dirs has the correct path prefixes
  927. name: "wildcard dirs",
  928. prop: `java_resource_dirs: ["java-res/*"]`,
  929. args: "-C java-res/a -f java-res/a/a -C java-res/b -f java-res/b/b",
  930. },
  931. {
  932. // Test that a module exclude_java_resource_dirs excludes the files
  933. name: "wildcard dirs",
  934. prop: `java_resource_dirs: ["java-res/*"], exclude_java_resource_dirs: ["java-res/b"]`,
  935. args: "-C java-res/a -f java-res/a/a",
  936. },
  937. {
  938. // Test wildcards in java_resources
  939. name: "wildcard files",
  940. prop: `java_resources: ["java-res/**/*"]`,
  941. args: "-C . -f java-res/a/a -f java-res/b/b",
  942. },
  943. {
  944. // Test exclude_java_resources with java_resources
  945. name: "wildcard files with exclude",
  946. prop: `java_resources: ["java-res/**/*"], exclude_java_resources: ["java-res/b/*"]`,
  947. args: "-C . -f java-res/a/a",
  948. },
  949. {
  950. // Test exclude_java_resources with java_resource_dirs
  951. name: "resource dirs with exclude files",
  952. prop: `java_resource_dirs: ["java-res"], exclude_java_resources: ["java-res/b/b"]`,
  953. args: "-C java-res -f java-res/a/a",
  954. },
  955. {
  956. // Test exclude_java_resource_dirs with java_resource_dirs
  957. name: "resource dirs with exclude files",
  958. prop: `java_resource_dirs: ["java-res", "java-res2"], exclude_java_resource_dirs: ["java-res2"]`,
  959. args: "-C java-res -f java-res/a/a -f java-res/b/b",
  960. },
  961. }
  962. for _, test := range table {
  963. t.Run(test.name, func(t *testing.T) {
  964. ctx, _ := testJavaWithFS(t, `
  965. java_library {
  966. name: "foo",
  967. srcs: [
  968. "a.java",
  969. "b.java",
  970. "c.java",
  971. ],
  972. `+test.prop+`,
  973. }
  974. `+test.extra,
  975. map[string][]byte{
  976. "java-res/a/a": nil,
  977. "java-res/b/b": nil,
  978. "java-res2/a": nil,
  979. },
  980. )
  981. foo := ctx.ModuleForTests("foo", "android_common").Output("withres/foo.jar")
  982. fooRes := ctx.ModuleForTests("foo", "android_common").Output("res/foo.jar")
  983. if !inList(fooRes.Output.String(), foo.Inputs.Strings()) {
  984. t.Errorf("foo combined jars %v does not contain %q",
  985. foo.Inputs.Strings(), fooRes.Output.String())
  986. }
  987. if fooRes.Args["jarArgs"] != test.args {
  988. t.Errorf("foo resource jar args %q is not %q",
  989. fooRes.Args["jarArgs"], test.args)
  990. }
  991. })
  992. }
  993. }
  994. func TestIncludeSrcs(t *testing.T) {
  995. ctx, _ := testJavaWithFS(t, `
  996. java_library {
  997. name: "foo",
  998. srcs: [
  999. "a.java",
  1000. "b.java",
  1001. "c.java",
  1002. ],
  1003. include_srcs: true,
  1004. }
  1005. java_library {
  1006. name: "bar",
  1007. srcs: [
  1008. "a.java",
  1009. "b.java",
  1010. "c.java",
  1011. ],
  1012. java_resource_dirs: ["java-res"],
  1013. include_srcs: true,
  1014. }
  1015. `, map[string][]byte{
  1016. "java-res/a/a": nil,
  1017. "java-res/b/b": nil,
  1018. "java-res2/a": nil,
  1019. })
  1020. // Test a library with include_srcs: true
  1021. foo := ctx.ModuleForTests("foo", "android_common").Output("withres/foo.jar")
  1022. fooSrcJar := ctx.ModuleForTests("foo", "android_common").Output("foo.srcjar")
  1023. if g, w := fooSrcJar.Output.String(), foo.Inputs.Strings(); !inList(g, w) {
  1024. t.Errorf("foo combined jars %v does not contain %q", w, g)
  1025. }
  1026. if g, w := fooSrcJar.Args["jarArgs"], "-C . -f a.java -f b.java -f c.java"; g != w {
  1027. t.Errorf("foo source jar args %q is not %q", w, g)
  1028. }
  1029. // Test a library with include_srcs: true and resources
  1030. bar := ctx.ModuleForTests("bar", "android_common").Output("withres/bar.jar")
  1031. barResCombined := ctx.ModuleForTests("bar", "android_common").Output("res-combined/bar.jar")
  1032. barRes := ctx.ModuleForTests("bar", "android_common").Output("res/bar.jar")
  1033. barSrcJar := ctx.ModuleForTests("bar", "android_common").Output("bar.srcjar")
  1034. if g, w := barSrcJar.Output.String(), barResCombined.Inputs.Strings(); !inList(g, w) {
  1035. t.Errorf("bar combined resource jars %v does not contain %q", w, g)
  1036. }
  1037. if g, w := barRes.Output.String(), barResCombined.Inputs.Strings(); !inList(g, w) {
  1038. t.Errorf("bar combined resource jars %v does not contain %q", w, g)
  1039. }
  1040. if g, w := barResCombined.Output.String(), bar.Inputs.Strings(); !inList(g, w) {
  1041. t.Errorf("bar combined jars %v does not contain %q", w, g)
  1042. }
  1043. if g, w := barSrcJar.Args["jarArgs"], "-C . -f a.java -f b.java -f c.java"; g != w {
  1044. t.Errorf("bar source jar args %q is not %q", w, g)
  1045. }
  1046. if g, w := barRes.Args["jarArgs"], "-C java-res -f java-res/a/a -f java-res/b/b"; g != w {
  1047. t.Errorf("bar resource jar args %q is not %q", w, g)
  1048. }
  1049. }
  1050. func TestJavaLint(t *testing.T) {
  1051. ctx, _ := testJavaWithFS(t, `
  1052. java_library {
  1053. name: "foo",
  1054. srcs: [
  1055. "a.java",
  1056. "b.java",
  1057. "c.java",
  1058. ],
  1059. min_sdk_version: "29",
  1060. sdk_version: "system_current",
  1061. }
  1062. `, map[string][]byte{
  1063. "lint-baseline.xml": nil,
  1064. })
  1065. foo := ctx.ModuleForTests("foo", "android_common")
  1066. sboxProto := android.RuleBuilderSboxProtoForTests(t, foo.Output("lint.sbox.textproto"))
  1067. if !strings.Contains(*sboxProto.Commands[0].Command, "--baseline lint-baseline.xml") {
  1068. t.Error("did not pass --baseline flag")
  1069. }
  1070. }
  1071. func TestJavaLintWithoutBaseline(t *testing.T) {
  1072. ctx, _ := testJavaWithFS(t, `
  1073. java_library {
  1074. name: "foo",
  1075. srcs: [
  1076. "a.java",
  1077. "b.java",
  1078. "c.java",
  1079. ],
  1080. min_sdk_version: "29",
  1081. sdk_version: "system_current",
  1082. }
  1083. `, map[string][]byte{})
  1084. foo := ctx.ModuleForTests("foo", "android_common")
  1085. sboxProto := android.RuleBuilderSboxProtoForTests(t, foo.Output("lint.sbox.textproto"))
  1086. if strings.Contains(*sboxProto.Commands[0].Command, "--baseline") {
  1087. t.Error("passed --baseline flag for non existent file")
  1088. }
  1089. }
  1090. func TestJavaLintRequiresCustomLintFileToExist(t *testing.T) {
  1091. android.GroupFixturePreparers(
  1092. PrepareForTestWithJavaDefaultModules,
  1093. android.PrepareForTestDisallowNonExistentPaths,
  1094. ).ExtendWithErrorHandler(android.FixtureExpectsAllErrorsToMatchAPattern([]string{`source path "mybaseline.xml" does not exist`})).
  1095. RunTestWithBp(t, `
  1096. java_library {
  1097. name: "foo",
  1098. srcs: [
  1099. ],
  1100. min_sdk_version: "29",
  1101. sdk_version: "system_current",
  1102. lint: {
  1103. baseline_filename: "mybaseline.xml",
  1104. },
  1105. }
  1106. `)
  1107. }
  1108. func TestJavaLintUsesCorrectBpConfig(t *testing.T) {
  1109. ctx, _ := testJavaWithFS(t, `
  1110. java_library {
  1111. name: "foo",
  1112. srcs: [
  1113. "a.java",
  1114. "b.java",
  1115. "c.java",
  1116. ],
  1117. min_sdk_version: "29",
  1118. sdk_version: "system_current",
  1119. lint: {
  1120. error_checks: ["SomeCheck"],
  1121. baseline_filename: "mybaseline.xml",
  1122. },
  1123. }
  1124. `, map[string][]byte{
  1125. "mybaseline.xml": nil,
  1126. })
  1127. foo := ctx.ModuleForTests("foo", "android_common")
  1128. sboxProto := android.RuleBuilderSboxProtoForTests(t, foo.Output("lint.sbox.textproto"))
  1129. if !strings.Contains(*sboxProto.Commands[0].Command, "--baseline mybaseline.xml") {
  1130. t.Error("did not use the correct file for baseline")
  1131. }
  1132. }
  1133. func TestGeneratedSources(t *testing.T) {
  1134. ctx, _ := testJavaWithFS(t, `
  1135. java_library {
  1136. name: "foo",
  1137. srcs: [
  1138. "a*.java",
  1139. ":gen",
  1140. "b*.java",
  1141. ],
  1142. }
  1143. genrule {
  1144. name: "gen",
  1145. tool_files: ["java-res/a"],
  1146. out: ["gen.java"],
  1147. }
  1148. `, map[string][]byte{
  1149. "a.java": nil,
  1150. "b.java": nil,
  1151. })
  1152. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  1153. genrule := ctx.ModuleForTests("gen", "").Rule("generator")
  1154. if filepath.Base(genrule.Output.String()) != "gen.java" {
  1155. t.Fatalf(`gen output file %v is not ".../gen.java"`, genrule.Output.String())
  1156. }
  1157. if len(javac.Inputs) != 3 ||
  1158. javac.Inputs[0].String() != "a.java" ||
  1159. javac.Inputs[1].String() != genrule.Output.String() ||
  1160. javac.Inputs[2].String() != "b.java" {
  1161. t.Errorf(`foo inputs %v != ["a.java", ".../gen.java", "b.java"]`, javac.Inputs)
  1162. }
  1163. }
  1164. func TestTurbine(t *testing.T) {
  1165. result := android.GroupFixturePreparers(
  1166. prepareForJavaTest, FixtureWithPrebuiltApis(map[string][]string{"14": {"foo"}})).
  1167. RunTestWithBp(t, `
  1168. java_library {
  1169. name: "foo",
  1170. srcs: ["a.java"],
  1171. sdk_version: "14",
  1172. }
  1173. java_library {
  1174. name: "bar",
  1175. srcs: ["b.java"],
  1176. static_libs: ["foo"],
  1177. sdk_version: "14",
  1178. }
  1179. java_library {
  1180. name: "baz",
  1181. srcs: ["c.java"],
  1182. libs: ["bar"],
  1183. sdk_version: "14",
  1184. }
  1185. `)
  1186. fooTurbine := result.ModuleForTests("foo", "android_common").Rule("turbine")
  1187. barTurbine := result.ModuleForTests("bar", "android_common").Rule("turbine")
  1188. barJavac := result.ModuleForTests("bar", "android_common").Rule("javac")
  1189. barTurbineCombined := result.ModuleForTests("bar", "android_common").Description("for turbine")
  1190. bazJavac := result.ModuleForTests("baz", "android_common").Rule("javac")
  1191. android.AssertPathsRelativeToTopEquals(t, "foo inputs", []string{"a.java"}, fooTurbine.Inputs)
  1192. fooHeaderJar := filepath.Join("out", "soong", ".intermediates", "foo", "android_common", "turbine-combined", "foo.jar")
  1193. barTurbineJar := filepath.Join("out", "soong", ".intermediates", "bar", "android_common", "turbine", "bar.jar")
  1194. android.AssertStringDoesContain(t, "bar turbine classpath", barTurbine.Args["classpath"], fooHeaderJar)
  1195. android.AssertStringDoesContain(t, "bar javac classpath", barJavac.Args["classpath"], fooHeaderJar)
  1196. android.AssertPathsRelativeToTopEquals(t, "bar turbine combineJar", []string{barTurbineJar, fooHeaderJar}, barTurbineCombined.Inputs)
  1197. android.AssertStringDoesContain(t, "baz javac classpath", bazJavac.Args["classpath"], "prebuilts/sdk/14/public/android.jar")
  1198. }
  1199. func TestSharding(t *testing.T) {
  1200. ctx, _ := testJava(t, `
  1201. java_library {
  1202. name: "bar",
  1203. srcs: ["a.java","b.java","c.java"],
  1204. javac_shard_size: 1
  1205. }
  1206. `)
  1207. barHeaderJar := filepath.Join("out", "soong", ".intermediates", "bar", "android_common", "turbine-combined", "bar.jar")
  1208. for i := 0; i < 3; i++ {
  1209. barJavac := ctx.ModuleForTests("bar", "android_common").Description("javac" + strconv.Itoa(i))
  1210. if !strings.Contains(barJavac.Args["classpath"], barHeaderJar) {
  1211. t.Errorf("bar javac classpath %v does not contain %q", barJavac.Args["classpath"], barHeaderJar)
  1212. }
  1213. }
  1214. }
  1215. func TestJarGenrules(t *testing.T) {
  1216. ctx, _ := testJava(t, `
  1217. java_library {
  1218. name: "foo",
  1219. srcs: ["a.java"],
  1220. }
  1221. java_genrule {
  1222. name: "jargen",
  1223. tool_files: ["b.java"],
  1224. cmd: "$(location b.java) $(in) $(out)",
  1225. out: ["jargen.jar"],
  1226. srcs: [":foo"],
  1227. }
  1228. java_library {
  1229. name: "bar",
  1230. static_libs: ["jargen"],
  1231. srcs: ["c.java"],
  1232. }
  1233. java_library {
  1234. name: "baz",
  1235. libs: ["jargen"],
  1236. srcs: ["c.java"],
  1237. }
  1238. `)
  1239. foo := ctx.ModuleForTests("foo", "android_common").Output("javac/foo.jar")
  1240. jargen := ctx.ModuleForTests("jargen", "android_common").Output("jargen.jar")
  1241. bar := ctx.ModuleForTests("bar", "android_common").Output("javac/bar.jar")
  1242. baz := ctx.ModuleForTests("baz", "android_common").Output("javac/baz.jar")
  1243. barCombined := ctx.ModuleForTests("bar", "android_common").Output("combined/bar.jar")
  1244. if g, w := jargen.Implicits.Strings(), foo.Output.String(); !android.InList(w, g) {
  1245. t.Errorf("expected jargen inputs [%q], got %q", w, g)
  1246. }
  1247. if !strings.Contains(bar.Args["classpath"], jargen.Output.String()) {
  1248. t.Errorf("bar classpath %v does not contain %q", bar.Args["classpath"], jargen.Output.String())
  1249. }
  1250. if !strings.Contains(baz.Args["classpath"], jargen.Output.String()) {
  1251. t.Errorf("baz classpath %v does not contain %q", baz.Args["classpath"], jargen.Output.String())
  1252. }
  1253. if len(barCombined.Inputs) != 2 ||
  1254. barCombined.Inputs[0].String() != bar.Output.String() ||
  1255. barCombined.Inputs[1].String() != jargen.Output.String() {
  1256. t.Errorf("bar combined jar inputs %v is not [%q, %q]",
  1257. barCombined.Inputs.Strings(), bar.Output.String(), jargen.Output.String())
  1258. }
  1259. }
  1260. func TestExcludeFileGroupInSrcs(t *testing.T) {
  1261. ctx, _ := testJava(t, `
  1262. java_library {
  1263. name: "foo",
  1264. srcs: ["a.java", ":foo-srcs"],
  1265. exclude_srcs: ["a.java", ":foo-excludes"],
  1266. }
  1267. filegroup {
  1268. name: "foo-srcs",
  1269. srcs: ["java-fg/a.java", "java-fg/b.java", "java-fg/c.java"],
  1270. }
  1271. filegroup {
  1272. name: "foo-excludes",
  1273. srcs: ["java-fg/a.java", "java-fg/b.java"],
  1274. }
  1275. `)
  1276. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  1277. if len(javac.Inputs) != 1 || javac.Inputs[0].String() != "java-fg/c.java" {
  1278. t.Errorf(`foo inputs %v != ["java-fg/c.java"]`, javac.Inputs)
  1279. }
  1280. }
  1281. func TestJavaLibrary(t *testing.T) {
  1282. testJavaWithFS(t, "", map[string][]byte{
  1283. "libcore/Android.bp": []byte(`
  1284. java_library {
  1285. name: "core",
  1286. sdk_version: "none",
  1287. system_modules: "none",
  1288. }
  1289. filegroup {
  1290. name: "core-jar",
  1291. srcs: [":core{.jar}"],
  1292. }
  1293. `),
  1294. })
  1295. }
  1296. func TestJavaImport(t *testing.T) {
  1297. testJavaWithFS(t, "", map[string][]byte{
  1298. "libcore/Android.bp": []byte(`
  1299. java_import {
  1300. name: "core",
  1301. sdk_version: "none",
  1302. }
  1303. filegroup {
  1304. name: "core-jar",
  1305. srcs: [":core{.jar}"],
  1306. }
  1307. `),
  1308. })
  1309. }
  1310. func TestJavaSdkLibrary(t *testing.T) {
  1311. result := android.GroupFixturePreparers(
  1312. prepareForJavaTest,
  1313. PrepareForTestWithJavaSdkLibraryFiles,
  1314. FixtureWithPrebuiltApis(map[string][]string{
  1315. "28": {"foo"},
  1316. "29": {"foo"},
  1317. "30": {"bar", "barney", "baz", "betty", "foo", "fred", "quuz", "wilma"},
  1318. }),
  1319. ).RunTestWithBp(t, `
  1320. droiddoc_exported_dir {
  1321. name: "droiddoc-templates-sdk",
  1322. path: ".",
  1323. }
  1324. java_sdk_library {
  1325. name: "foo",
  1326. srcs: ["a.java", "b.java"],
  1327. api_packages: ["foo"],
  1328. }
  1329. java_sdk_library {
  1330. name: "bar",
  1331. srcs: ["a.java", "b.java"],
  1332. api_packages: ["bar"],
  1333. }
  1334. java_library {
  1335. name: "baz",
  1336. srcs: ["c.java"],
  1337. libs: ["foo", "bar.stubs"],
  1338. sdk_version: "system_current",
  1339. }
  1340. java_sdk_library {
  1341. name: "barney",
  1342. srcs: ["c.java"],
  1343. api_only: true,
  1344. }
  1345. java_sdk_library {
  1346. name: "betty",
  1347. srcs: ["c.java"],
  1348. shared_library: false,
  1349. }
  1350. java_sdk_library_import {
  1351. name: "quuz",
  1352. public: {
  1353. jars: ["c.jar"],
  1354. },
  1355. }
  1356. java_sdk_library_import {
  1357. name: "fred",
  1358. public: {
  1359. jars: ["b.jar"],
  1360. },
  1361. }
  1362. java_sdk_library_import {
  1363. name: "wilma",
  1364. public: {
  1365. jars: ["b.jar"],
  1366. },
  1367. shared_library: false,
  1368. }
  1369. java_library {
  1370. name: "qux",
  1371. srcs: ["c.java"],
  1372. libs: ["baz", "fred", "quuz.stubs", "wilma", "barney", "betty"],
  1373. sdk_version: "system_current",
  1374. }
  1375. java_library {
  1376. name: "baz-test",
  1377. srcs: ["c.java"],
  1378. libs: ["foo"],
  1379. sdk_version: "test_current",
  1380. }
  1381. java_library {
  1382. name: "baz-29",
  1383. srcs: ["c.java"],
  1384. libs: ["foo"],
  1385. sdk_version: "system_29",
  1386. }
  1387. java_library {
  1388. name: "baz-module-30",
  1389. srcs: ["c.java"],
  1390. libs: ["foo"],
  1391. sdk_version: "module_30",
  1392. }
  1393. `)
  1394. // check the existence of the internal modules
  1395. result.ModuleForTests("foo", "android_common")
  1396. result.ModuleForTests(apiScopePublic.stubsLibraryModuleName("foo"), "android_common")
  1397. result.ModuleForTests(apiScopeSystem.stubsLibraryModuleName("foo"), "android_common")
  1398. result.ModuleForTests(apiScopeTest.stubsLibraryModuleName("foo"), "android_common")
  1399. result.ModuleForTests(apiScopePublic.stubsSourceModuleName("foo"), "android_common")
  1400. result.ModuleForTests(apiScopeSystem.stubsSourceModuleName("foo"), "android_common")
  1401. result.ModuleForTests(apiScopeTest.stubsSourceModuleName("foo"), "android_common")
  1402. result.ModuleForTests("foo"+sdkXmlFileSuffix, "android_common")
  1403. result.ModuleForTests("foo.api.public.28", "")
  1404. result.ModuleForTests("foo.api.system.28", "")
  1405. result.ModuleForTests("foo.api.test.28", "")
  1406. bazJavac := result.ModuleForTests("baz", "android_common").Rule("javac")
  1407. // tests if baz is actually linked to the stubs lib
  1408. android.AssertStringDoesContain(t, "baz javac classpath", bazJavac.Args["classpath"], "foo.stubs.system.jar")
  1409. // ... and not to the impl lib
  1410. android.AssertStringDoesNotContain(t, "baz javac classpath", bazJavac.Args["classpath"], "foo.jar")
  1411. // test if baz is not linked to the system variant of foo
  1412. android.AssertStringDoesNotContain(t, "baz javac classpath", bazJavac.Args["classpath"], "foo.stubs.jar")
  1413. bazTestJavac := result.ModuleForTests("baz-test", "android_common").Rule("javac")
  1414. // tests if baz-test is actually linked to the test stubs lib
  1415. android.AssertStringDoesContain(t, "baz-test javac classpath", bazTestJavac.Args["classpath"], "foo.stubs.test.jar")
  1416. baz29Javac := result.ModuleForTests("baz-29", "android_common").Rule("javac")
  1417. // tests if baz-29 is actually linked to the system 29 stubs lib
  1418. android.AssertStringDoesContain(t, "baz-29 javac classpath", baz29Javac.Args["classpath"], "prebuilts/sdk/29/system/foo.jar")
  1419. bazModule30Javac := result.ModuleForTests("baz-module-30", "android_common").Rule("javac")
  1420. // tests if "baz-module-30" is actually linked to the module 30 stubs lib
  1421. android.AssertStringDoesContain(t, "baz-module-30 javac classpath", bazModule30Javac.Args["classpath"], "prebuilts/sdk/30/module-lib/foo.jar")
  1422. // test if baz has exported SDK lib names foo and bar to qux
  1423. qux := result.ModuleForTests("qux", "android_common")
  1424. if quxLib, ok := qux.Module().(*Library); ok {
  1425. sdkLibs := quxLib.ClassLoaderContexts().UsesLibs()
  1426. android.AssertDeepEquals(t, "qux exports", []string{"foo", "bar", "fred", "quuz"}, sdkLibs)
  1427. }
  1428. }
  1429. func TestJavaSdkLibrary_StubOrImplOnlyLibs(t *testing.T) {
  1430. result := android.GroupFixturePreparers(
  1431. prepareForJavaTest,
  1432. PrepareForTestWithJavaSdkLibraryFiles,
  1433. FixtureWithLastReleaseApis("sdklib"),
  1434. ).RunTestWithBp(t, `
  1435. java_sdk_library {
  1436. name: "sdklib",
  1437. srcs: ["a.java"],
  1438. impl_only_libs: ["foo"],
  1439. stub_only_libs: ["bar"],
  1440. }
  1441. java_library {
  1442. name: "foo",
  1443. srcs: ["a.java"],
  1444. sdk_version: "current",
  1445. }
  1446. java_library {
  1447. name: "bar",
  1448. srcs: ["a.java"],
  1449. sdk_version: "current",
  1450. }
  1451. `)
  1452. for _, implName := range []string{"sdklib", "sdklib.impl"} {
  1453. implJavacCp := result.ModuleForTests(implName, "android_common").Rule("javac").Args["classpath"]
  1454. if !strings.Contains(implJavacCp, "/foo.jar") || strings.Contains(implJavacCp, "/bar.jar") {
  1455. t.Errorf("%v javac classpath %v does not contain foo and not bar", implName, implJavacCp)
  1456. }
  1457. }
  1458. stubName := apiScopePublic.stubsLibraryModuleName("sdklib")
  1459. stubsJavacCp := result.ModuleForTests(stubName, "android_common").Rule("javac").Args["classpath"]
  1460. if strings.Contains(stubsJavacCp, "/foo.jar") || !strings.Contains(stubsJavacCp, "/bar.jar") {
  1461. t.Errorf("stubs javac classpath %v does not contain bar and not foo", stubsJavacCp)
  1462. }
  1463. }
  1464. func TestJavaSdkLibrary_DoNotAccessImplWhenItIsNotBuilt(t *testing.T) {
  1465. result := android.GroupFixturePreparers(
  1466. prepareForJavaTest,
  1467. PrepareForTestWithJavaSdkLibraryFiles,
  1468. FixtureWithLastReleaseApis("foo"),
  1469. ).RunTestWithBp(t, `
  1470. java_sdk_library {
  1471. name: "foo",
  1472. srcs: ["a.java"],
  1473. api_only: true,
  1474. public: {
  1475. enabled: true,
  1476. },
  1477. }
  1478. java_library {
  1479. name: "bar",
  1480. srcs: ["b.java"],
  1481. libs: ["foo"],
  1482. }
  1483. `)
  1484. // The bar library should depend on the stubs jar.
  1485. barLibrary := result.ModuleForTests("bar", "android_common").Rule("javac")
  1486. if expected, actual := `^-classpath .*:out/soong/[^:]*/turbine-combined/foo\.stubs\.jar$`, barLibrary.Args["classpath"]; !regexp.MustCompile(expected).MatchString(actual) {
  1487. t.Errorf("expected %q, found %#q", expected, actual)
  1488. }
  1489. }
  1490. func TestJavaSdkLibrary_UseSourcesFromAnotherSdkLibrary(t *testing.T) {
  1491. android.GroupFixturePreparers(
  1492. prepareForJavaTest,
  1493. PrepareForTestWithJavaSdkLibraryFiles,
  1494. FixtureWithLastReleaseApis("foo"),
  1495. ).RunTestWithBp(t, `
  1496. java_sdk_library {
  1497. name: "foo",
  1498. srcs: ["a.java"],
  1499. api_packages: ["foo"],
  1500. public: {
  1501. enabled: true,
  1502. },
  1503. }
  1504. java_library {
  1505. name: "bar",
  1506. srcs: ["b.java", ":foo{.public.stubs.source}"],
  1507. }
  1508. `)
  1509. }
  1510. func TestJavaSdkLibrary_AccessOutputFiles_MissingScope(t *testing.T) {
  1511. android.GroupFixturePreparers(
  1512. prepareForJavaTest,
  1513. PrepareForTestWithJavaSdkLibraryFiles,
  1514. FixtureWithLastReleaseApis("foo"),
  1515. ).
  1516. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`"foo" does not provide api scope system`)).
  1517. RunTestWithBp(t, `
  1518. java_sdk_library {
  1519. name: "foo",
  1520. srcs: ["a.java"],
  1521. api_packages: ["foo"],
  1522. public: {
  1523. enabled: true,
  1524. },
  1525. }
  1526. java_library {
  1527. name: "bar",
  1528. srcs: ["b.java", ":foo{.system.stubs.source}"],
  1529. }
  1530. `)
  1531. }
  1532. func TestJavaSdkLibrary_Deps(t *testing.T) {
  1533. result := android.GroupFixturePreparers(
  1534. prepareForJavaTest,
  1535. PrepareForTestWithJavaSdkLibraryFiles,
  1536. FixtureWithLastReleaseApis("sdklib"),
  1537. ).RunTestWithBp(t, `
  1538. java_sdk_library {
  1539. name: "sdklib",
  1540. srcs: ["a.java"],
  1541. sdk_version: "none",
  1542. system_modules: "none",
  1543. public: {
  1544. enabled: true,
  1545. },
  1546. }
  1547. `)
  1548. CheckModuleDependencies(t, result.TestContext, "sdklib", "android_common", []string{
  1549. `dex2oatd`,
  1550. `sdklib.impl`,
  1551. `sdklib.stubs`,
  1552. `sdklib.stubs.source`,
  1553. `sdklib.xml`,
  1554. })
  1555. }
  1556. func TestJavaSdkLibraryImport_AccessOutputFiles(t *testing.T) {
  1557. prepareForJavaTest.RunTestWithBp(t, `
  1558. java_sdk_library_import {
  1559. name: "foo",
  1560. public: {
  1561. jars: ["a.jar"],
  1562. stub_srcs: ["a.java"],
  1563. current_api: "api/current.txt",
  1564. removed_api: "api/removed.txt",
  1565. },
  1566. }
  1567. java_library {
  1568. name: "bar",
  1569. srcs: [":foo{.public.stubs.source}"],
  1570. java_resources: [
  1571. ":foo{.public.api.txt}",
  1572. ":foo{.public.removed-api.txt}",
  1573. ],
  1574. }
  1575. `)
  1576. }
  1577. func TestJavaSdkLibraryImport_AccessOutputFiles_Invalid(t *testing.T) {
  1578. bp := `
  1579. java_sdk_library_import {
  1580. name: "foo",
  1581. public: {
  1582. jars: ["a.jar"],
  1583. },
  1584. }
  1585. `
  1586. t.Run("stubs.source", func(t *testing.T) {
  1587. prepareForJavaTest.
  1588. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`stubs.source not available for api scope public`)).
  1589. RunTestWithBp(t, bp+`
  1590. java_library {
  1591. name: "bar",
  1592. srcs: [":foo{.public.stubs.source}"],
  1593. java_resources: [
  1594. ":foo{.public.api.txt}",
  1595. ":foo{.public.removed-api.txt}",
  1596. ],
  1597. }
  1598. `)
  1599. })
  1600. t.Run("api.txt", func(t *testing.T) {
  1601. prepareForJavaTest.
  1602. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`api.txt not available for api scope public`)).
  1603. RunTestWithBp(t, bp+`
  1604. java_library {
  1605. name: "bar",
  1606. srcs: ["a.java"],
  1607. java_resources: [
  1608. ":foo{.public.api.txt}",
  1609. ],
  1610. }
  1611. `)
  1612. })
  1613. t.Run("removed-api.txt", func(t *testing.T) {
  1614. prepareForJavaTest.
  1615. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`removed-api.txt not available for api scope public`)).
  1616. RunTestWithBp(t, bp+`
  1617. java_library {
  1618. name: "bar",
  1619. srcs: ["a.java"],
  1620. java_resources: [
  1621. ":foo{.public.removed-api.txt}",
  1622. ],
  1623. }
  1624. `)
  1625. })
  1626. }
  1627. func TestJavaSdkLibrary_InvalidScopes(t *testing.T) {
  1628. prepareForJavaTest.
  1629. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`module "foo": enabled api scope "system" depends on disabled scope "public"`)).
  1630. RunTestWithBp(t, `
  1631. java_sdk_library {
  1632. name: "foo",
  1633. srcs: ["a.java", "b.java"],
  1634. api_packages: ["foo"],
  1635. // Explicitly disable public to test the check that ensures the set of enabled
  1636. // scopes is consistent.
  1637. public: {
  1638. enabled: false,
  1639. },
  1640. system: {
  1641. enabled: true,
  1642. },
  1643. }
  1644. `)
  1645. }
  1646. func TestJavaSdkLibrary_SdkVersion_ForScope(t *testing.T) {
  1647. android.GroupFixturePreparers(
  1648. prepareForJavaTest,
  1649. PrepareForTestWithJavaSdkLibraryFiles,
  1650. FixtureWithLastReleaseApis("foo"),
  1651. ).RunTestWithBp(t, `
  1652. java_sdk_library {
  1653. name: "foo",
  1654. srcs: ["a.java", "b.java"],
  1655. api_packages: ["foo"],
  1656. system: {
  1657. enabled: true,
  1658. sdk_version: "module_current",
  1659. },
  1660. }
  1661. `)
  1662. }
  1663. func TestJavaSdkLibrary_ModuleLib(t *testing.T) {
  1664. android.GroupFixturePreparers(
  1665. prepareForJavaTest,
  1666. PrepareForTestWithJavaSdkLibraryFiles,
  1667. FixtureWithLastReleaseApis("foo"),
  1668. ).RunTestWithBp(t, `
  1669. java_sdk_library {
  1670. name: "foo",
  1671. srcs: ["a.java", "b.java"],
  1672. api_packages: ["foo"],
  1673. system: {
  1674. enabled: true,
  1675. },
  1676. module_lib: {
  1677. enabled: true,
  1678. },
  1679. }
  1680. `)
  1681. }
  1682. func TestJavaSdkLibrary_SystemServer(t *testing.T) {
  1683. android.GroupFixturePreparers(
  1684. prepareForJavaTest,
  1685. PrepareForTestWithJavaSdkLibraryFiles,
  1686. FixtureWithLastReleaseApis("foo"),
  1687. ).RunTestWithBp(t, `
  1688. java_sdk_library {
  1689. name: "foo",
  1690. srcs: ["a.java", "b.java"],
  1691. api_packages: ["foo"],
  1692. system: {
  1693. enabled: true,
  1694. },
  1695. system_server: {
  1696. enabled: true,
  1697. },
  1698. }
  1699. `)
  1700. }
  1701. func TestJavaSdkLibrary_MissingScope(t *testing.T) {
  1702. prepareForJavaTest.
  1703. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`requires api scope module-lib from foo but it only has \[\] available`)).
  1704. RunTestWithBp(t, `
  1705. java_sdk_library {
  1706. name: "foo",
  1707. srcs: ["a.java"],
  1708. public: {
  1709. enabled: false,
  1710. },
  1711. }
  1712. java_library {
  1713. name: "baz",
  1714. srcs: ["a.java"],
  1715. libs: ["foo"],
  1716. sdk_version: "module_current",
  1717. }
  1718. `)
  1719. }
  1720. func TestJavaSdkLibrary_FallbackScope(t *testing.T) {
  1721. android.GroupFixturePreparers(
  1722. prepareForJavaTest,
  1723. PrepareForTestWithJavaSdkLibraryFiles,
  1724. FixtureWithLastReleaseApis("foo"),
  1725. ).RunTestWithBp(t, `
  1726. java_sdk_library {
  1727. name: "foo",
  1728. srcs: ["a.java"],
  1729. system: {
  1730. enabled: true,
  1731. },
  1732. }
  1733. java_library {
  1734. name: "baz",
  1735. srcs: ["a.java"],
  1736. libs: ["foo"],
  1737. // foo does not have module-lib scope so it should fallback to system
  1738. sdk_version: "module_current",
  1739. }
  1740. `)
  1741. }
  1742. func TestJavaSdkLibrary_DefaultToStubs(t *testing.T) {
  1743. result := android.GroupFixturePreparers(
  1744. prepareForJavaTest,
  1745. PrepareForTestWithJavaSdkLibraryFiles,
  1746. FixtureWithLastReleaseApis("foo"),
  1747. ).RunTestWithBp(t, `
  1748. java_sdk_library {
  1749. name: "foo",
  1750. srcs: ["a.java"],
  1751. system: {
  1752. enabled: true,
  1753. },
  1754. default_to_stubs: true,
  1755. }
  1756. java_library {
  1757. name: "baz",
  1758. srcs: ["a.java"],
  1759. libs: ["foo"],
  1760. // does not have sdk_version set, should fallback to module,
  1761. // which will then fallback to system because the module scope
  1762. // is not enabled.
  1763. }
  1764. `)
  1765. // The baz library should depend on the system stubs jar.
  1766. bazLibrary := result.ModuleForTests("baz", "android_common").Rule("javac")
  1767. if expected, actual := `^-classpath .*:out/soong/[^:]*/turbine-combined/foo\.stubs.system\.jar$`, bazLibrary.Args["classpath"]; !regexp.MustCompile(expected).MatchString(actual) {
  1768. t.Errorf("expected %q, found %#q", expected, actual)
  1769. }
  1770. }
  1771. var compilerFlagsTestCases = []struct {
  1772. in string
  1773. out bool
  1774. }{
  1775. {
  1776. in: "a",
  1777. out: false,
  1778. },
  1779. {
  1780. in: "-a",
  1781. out: true,
  1782. },
  1783. {
  1784. in: "-no-jdk",
  1785. out: false,
  1786. },
  1787. {
  1788. in: "-no-stdlib",
  1789. out: false,
  1790. },
  1791. {
  1792. in: "-kotlin-home",
  1793. out: false,
  1794. },
  1795. {
  1796. in: "-kotlin-home /some/path",
  1797. out: false,
  1798. },
  1799. {
  1800. in: "-include-runtime",
  1801. out: false,
  1802. },
  1803. {
  1804. in: "-Xintellij-plugin-root",
  1805. out: false,
  1806. },
  1807. }
  1808. type mockContext struct {
  1809. android.ModuleContext
  1810. result bool
  1811. }
  1812. func (ctx *mockContext) PropertyErrorf(property, format string, args ...interface{}) {
  1813. // CheckBadCompilerFlags calls this function when the flag should be rejected
  1814. ctx.result = false
  1815. }
  1816. func TestCompilerFlags(t *testing.T) {
  1817. for _, testCase := range compilerFlagsTestCases {
  1818. ctx := &mockContext{result: true}
  1819. CheckKotlincFlags(ctx, []string{testCase.in})
  1820. if ctx.result != testCase.out {
  1821. t.Errorf("incorrect output:")
  1822. t.Errorf(" input: %#v", testCase.in)
  1823. t.Errorf(" expected: %#v", testCase.out)
  1824. t.Errorf(" got: %#v", ctx.result)
  1825. }
  1826. }
  1827. }
  1828. // TODO(jungjw): Consider making this more robust by ignoring path order.
  1829. func checkPatchModuleFlag(t *testing.T, ctx *android.TestContext, moduleName string, expected string) {
  1830. variables := ctx.ModuleForTests(moduleName, "android_common").VariablesForTestsRelativeToTop()
  1831. flags := strings.Split(variables["javacFlags"], " ")
  1832. got := ""
  1833. for _, flag := range flags {
  1834. keyEnd := strings.Index(flag, "=")
  1835. if keyEnd > -1 && flag[:keyEnd] == "--patch-module" {
  1836. got = flag[keyEnd+1:]
  1837. break
  1838. }
  1839. }
  1840. if expected != android.StringPathRelativeToTop(ctx.Config().BuildDir(), got) {
  1841. t.Errorf("Unexpected patch-module flag for module %q - expected %q, but got %q", moduleName, expected, got)
  1842. }
  1843. }
  1844. func TestPatchModule(t *testing.T) {
  1845. t.Run("Java language level 8", func(t *testing.T) {
  1846. // Test with legacy javac -source 1.8 -target 1.8
  1847. bp := `
  1848. java_library {
  1849. name: "foo",
  1850. srcs: ["a.java"],
  1851. java_version: "1.8",
  1852. }
  1853. java_library {
  1854. name: "bar",
  1855. srcs: ["b.java"],
  1856. sdk_version: "none",
  1857. system_modules: "none",
  1858. patch_module: "java.base",
  1859. java_version: "1.8",
  1860. }
  1861. java_library {
  1862. name: "baz",
  1863. srcs: ["c.java"],
  1864. patch_module: "java.base",
  1865. java_version: "1.8",
  1866. }
  1867. `
  1868. ctx, _ := testJava(t, bp)
  1869. checkPatchModuleFlag(t, ctx, "foo", "")
  1870. checkPatchModuleFlag(t, ctx, "bar", "")
  1871. checkPatchModuleFlag(t, ctx, "baz", "")
  1872. })
  1873. t.Run("Java language level 9", func(t *testing.T) {
  1874. // Test with default javac -source 9 -target 9
  1875. bp := `
  1876. java_library {
  1877. name: "foo",
  1878. srcs: ["a.java"],
  1879. }
  1880. java_library {
  1881. name: "bar",
  1882. srcs: ["b.java"],
  1883. sdk_version: "none",
  1884. system_modules: "none",
  1885. patch_module: "java.base",
  1886. }
  1887. java_library {
  1888. name: "baz",
  1889. srcs: [
  1890. "c.java",
  1891. // Tests for b/150878007
  1892. "dir/d.java",
  1893. "dir2/e.java",
  1894. "dir2/f.java",
  1895. "nested/dir/g.java"
  1896. ],
  1897. patch_module: "java.base",
  1898. }
  1899. `
  1900. ctx, _ := testJava(t, bp)
  1901. checkPatchModuleFlag(t, ctx, "foo", "")
  1902. expected := "java.base=.:out/soong"
  1903. checkPatchModuleFlag(t, ctx, "bar", expected)
  1904. expected = "java.base=" + strings.Join([]string{
  1905. ".", "out/soong", "dir", "dir2", "nested", defaultModuleToPath("ext"), defaultModuleToPath("framework")}, ":")
  1906. checkPatchModuleFlag(t, ctx, "baz", expected)
  1907. })
  1908. }
  1909. func TestJavaLibraryWithSystemModules(t *testing.T) {
  1910. ctx, _ := testJava(t, `
  1911. java_library {
  1912. name: "lib-with-source-system-modules",
  1913. srcs: [
  1914. "a.java",
  1915. ],
  1916. sdk_version: "none",
  1917. system_modules: "source-system-modules",
  1918. }
  1919. java_library {
  1920. name: "source-jar",
  1921. srcs: [
  1922. "a.java",
  1923. ],
  1924. }
  1925. java_system_modules {
  1926. name: "source-system-modules",
  1927. libs: ["source-jar"],
  1928. }
  1929. java_library {
  1930. name: "lib-with-prebuilt-system-modules",
  1931. srcs: [
  1932. "a.java",
  1933. ],
  1934. sdk_version: "none",
  1935. system_modules: "prebuilt-system-modules",
  1936. }
  1937. java_import {
  1938. name: "prebuilt-jar",
  1939. jars: ["a.jar"],
  1940. }
  1941. java_system_modules_import {
  1942. name: "prebuilt-system-modules",
  1943. libs: ["prebuilt-jar"],
  1944. }
  1945. `)
  1946. checkBootClasspathForSystemModule(t, ctx, "lib-with-source-system-modules", "/source-jar.jar")
  1947. checkBootClasspathForSystemModule(t, ctx, "lib-with-prebuilt-system-modules", "/prebuilt-jar.jar")
  1948. }
  1949. func checkBootClasspathForSystemModule(t *testing.T, ctx *android.TestContext, moduleName string, expectedSuffix string) {
  1950. javacRule := ctx.ModuleForTests(moduleName, "android_common").Rule("javac")
  1951. bootClasspath := javacRule.Args["bootClasspath"]
  1952. if strings.HasPrefix(bootClasspath, "--system ") && strings.HasSuffix(bootClasspath, expectedSuffix) {
  1953. t.Errorf("bootclasspath of %q must start with --system and end with %q, but was %#v.", moduleName, expectedSuffix, bootClasspath)
  1954. }
  1955. }
  1956. func TestAidlExportIncludeDirsFromImports(t *testing.T) {
  1957. ctx, _ := testJava(t, `
  1958. java_library {
  1959. name: "foo",
  1960. srcs: ["aidl/foo/IFoo.aidl"],
  1961. libs: ["bar"],
  1962. }
  1963. java_import {
  1964. name: "bar",
  1965. jars: ["a.jar"],
  1966. aidl: {
  1967. export_include_dirs: ["aidl/bar"],
  1968. },
  1969. }
  1970. `)
  1971. aidlCommand := ctx.ModuleForTests("foo", "android_common").Rule("aidl").RuleParams.Command
  1972. expectedAidlFlag := "-Iaidl/bar"
  1973. if !strings.Contains(aidlCommand, expectedAidlFlag) {
  1974. t.Errorf("aidl command %q does not contain %q", aidlCommand, expectedAidlFlag)
  1975. }
  1976. }
  1977. func TestAidlFlagsArePassedToTheAidlCompiler(t *testing.T) {
  1978. ctx, _ := testJava(t, `
  1979. java_library {
  1980. name: "foo",
  1981. srcs: ["aidl/foo/IFoo.aidl"],
  1982. aidl: { flags: ["-Werror"], },
  1983. }
  1984. `)
  1985. aidlCommand := ctx.ModuleForTests("foo", "android_common").Rule("aidl").RuleParams.Command
  1986. expectedAidlFlag := "-Werror"
  1987. if !strings.Contains(aidlCommand, expectedAidlFlag) {
  1988. t.Errorf("aidl command %q does not contain %q", aidlCommand, expectedAidlFlag)
  1989. }
  1990. }
  1991. func TestDataNativeBinaries(t *testing.T) {
  1992. ctx, _ := testJava(t, `
  1993. java_test_host {
  1994. name: "foo",
  1995. srcs: ["a.java"],
  1996. data_native_bins: ["bin"]
  1997. }
  1998. python_binary_host {
  1999. name: "bin",
  2000. srcs: ["bin.py"],
  2001. }
  2002. `)
  2003. buildOS := android.BuildOs.String()
  2004. test := ctx.ModuleForTests("foo", buildOS+"_common").Module().(*TestHost)
  2005. entries := android.AndroidMkEntriesForTest(t, ctx, test)[0]
  2006. expected := []string{"out/soong/.intermediates/bin/" + buildOS + "_x86_64_PY3/bin:bin"}
  2007. actual := entries.EntryMap["LOCAL_COMPATIBILITY_SUPPORT_FILES"]
  2008. android.AssertStringPathsRelativeToTopEquals(t, "LOCAL_COMPATIBILITY_SUPPORT_FILES", ctx.Config(), expected, actual)
  2009. }
  2010. func TestDefaultInstallable(t *testing.T) {
  2011. ctx, _ := testJava(t, `
  2012. java_test_host {
  2013. name: "foo"
  2014. }
  2015. `)
  2016. buildOS := android.BuildOs.String()
  2017. module := ctx.ModuleForTests("foo", buildOS+"_common").Module().(*TestHost)
  2018. assertDeepEquals(t, "Default installable value should be true.", proptools.BoolPtr(true),
  2019. module.properties.Installable)
  2020. }