java_test.go 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262
  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. prepareForJavaTest.ExtendWithErrorHandler(errorHandler).RunTest(t, createPreparer(info))
  750. })
  751. }
  752. errorMessage := "is not allowed across the partitions"
  753. runTest(t, testConfigInfo{
  754. libraryType: "java_library",
  755. fromPartition: "product",
  756. toPartition: "system",
  757. enforceVendorInterface: true,
  758. enforceProductInterface: true,
  759. enforceJavaSdkLibraryCheck: false,
  760. }, "")
  761. runTest(t, testConfigInfo{
  762. libraryType: "java_library",
  763. fromPartition: "product",
  764. toPartition: "system",
  765. enforceVendorInterface: true,
  766. enforceProductInterface: false,
  767. enforceJavaSdkLibraryCheck: true,
  768. }, "")
  769. runTest(t, testConfigInfo{
  770. libraryType: "java_library",
  771. fromPartition: "product",
  772. toPartition: "system",
  773. enforceVendorInterface: true,
  774. enforceProductInterface: true,
  775. enforceJavaSdkLibraryCheck: true,
  776. }, errorMessage)
  777. runTest(t, testConfigInfo{
  778. libraryType: "java_library",
  779. fromPartition: "vendor",
  780. toPartition: "system",
  781. enforceVendorInterface: true,
  782. enforceProductInterface: true,
  783. enforceJavaSdkLibraryCheck: true,
  784. }, errorMessage)
  785. runTest(t, testConfigInfo{
  786. libraryType: "java_library",
  787. fromPartition: "vendor",
  788. toPartition: "system",
  789. enforceVendorInterface: true,
  790. enforceProductInterface: true,
  791. enforceJavaSdkLibraryCheck: true,
  792. allowList: []string{"bar"},
  793. }, "")
  794. runTest(t, testConfigInfo{
  795. libraryType: "java_library",
  796. fromPartition: "vendor",
  797. toPartition: "product",
  798. enforceVendorInterface: true,
  799. enforceProductInterface: true,
  800. enforceJavaSdkLibraryCheck: true,
  801. }, errorMessage)
  802. runTest(t, testConfigInfo{
  803. libraryType: "java_sdk_library",
  804. fromPartition: "product",
  805. toPartition: "system",
  806. enforceVendorInterface: true,
  807. enforceProductInterface: true,
  808. enforceJavaSdkLibraryCheck: true,
  809. }, "")
  810. runTest(t, testConfigInfo{
  811. libraryType: "java_sdk_library",
  812. fromPartition: "vendor",
  813. toPartition: "system",
  814. enforceVendorInterface: true,
  815. enforceProductInterface: true,
  816. enforceJavaSdkLibraryCheck: true,
  817. }, "")
  818. runTest(t, testConfigInfo{
  819. libraryType: "java_sdk_library",
  820. fromPartition: "vendor",
  821. toPartition: "product",
  822. enforceVendorInterface: true,
  823. enforceProductInterface: true,
  824. enforceJavaSdkLibraryCheck: true,
  825. }, "")
  826. }
  827. func TestDefaults(t *testing.T) {
  828. ctx, _ := testJava(t, `
  829. java_defaults {
  830. name: "defaults",
  831. srcs: ["a.java"],
  832. libs: ["bar"],
  833. static_libs: ["baz"],
  834. optimize: {enabled: false},
  835. }
  836. java_library {
  837. name: "foo",
  838. defaults: ["defaults"],
  839. }
  840. java_library {
  841. name: "bar",
  842. srcs: ["b.java"],
  843. }
  844. java_library {
  845. name: "baz",
  846. srcs: ["c.java"],
  847. }
  848. android_test {
  849. name: "atestOptimize",
  850. defaults: ["defaults"],
  851. optimize: {enabled: true},
  852. }
  853. android_test {
  854. name: "atestNoOptimize",
  855. defaults: ["defaults"],
  856. }
  857. android_test {
  858. name: "atestDefault",
  859. srcs: ["a.java"],
  860. }
  861. `)
  862. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  863. combineJar := ctx.ModuleForTests("foo", "android_common").Description("for javac")
  864. if len(javac.Inputs) != 1 || javac.Inputs[0].String() != "a.java" {
  865. t.Errorf(`foo inputs %v != ["a.java"]`, javac.Inputs)
  866. }
  867. barTurbine := filepath.Join("out", "soong", ".intermediates", "bar", "android_common", "turbine-combined", "bar.jar")
  868. if !strings.Contains(javac.Args["classpath"], barTurbine) {
  869. t.Errorf("foo classpath %v does not contain %q", javac.Args["classpath"], barTurbine)
  870. }
  871. baz := ctx.ModuleForTests("baz", "android_common").Rule("javac").Output.String()
  872. if len(combineJar.Inputs) != 2 || combineJar.Inputs[1].String() != baz {
  873. t.Errorf("foo combineJar inputs %v does not contain %q", combineJar.Inputs, baz)
  874. }
  875. atestOptimize := ctx.ModuleForTests("atestOptimize", "android_common").MaybeRule("r8")
  876. if atestOptimize.Output == nil {
  877. t.Errorf("atestOptimize should optimize APK")
  878. }
  879. atestNoOptimize := ctx.ModuleForTests("atestNoOptimize", "android_common").MaybeRule("d8")
  880. if atestNoOptimize.Output == nil {
  881. t.Errorf("atestNoOptimize should not optimize APK")
  882. }
  883. atestDefault := ctx.ModuleForTests("atestDefault", "android_common").MaybeRule("r8")
  884. if atestDefault.Output == nil {
  885. t.Errorf("atestDefault should optimize APK")
  886. }
  887. }
  888. func TestResources(t *testing.T) {
  889. var table = []struct {
  890. name string
  891. prop string
  892. extra string
  893. args string
  894. }{
  895. {
  896. // Test that a module with java_resource_dirs includes the files
  897. name: "resource dirs",
  898. prop: `java_resource_dirs: ["java-res"]`,
  899. args: "-C java-res -f java-res/a/a -f java-res/b/b",
  900. },
  901. {
  902. // Test that a module with java_resources includes the files
  903. name: "resource files",
  904. prop: `java_resources: ["java-res/a/a", "java-res/b/b"]`,
  905. args: "-C . -f java-res/a/a -f java-res/b/b",
  906. },
  907. {
  908. // Test that a module with a filegroup in java_resources includes the files with the
  909. // path prefix
  910. name: "resource filegroup",
  911. prop: `java_resources: [":foo-res"]`,
  912. extra: `
  913. filegroup {
  914. name: "foo-res",
  915. path: "java-res",
  916. srcs: ["java-res/a/a", "java-res/b/b"],
  917. }`,
  918. args: "-C java-res -f java-res/a/a -f java-res/b/b",
  919. },
  920. {
  921. // Test that a module with wildcards in java_resource_dirs has the correct path prefixes
  922. name: "wildcard dirs",
  923. prop: `java_resource_dirs: ["java-res/*"]`,
  924. args: "-C java-res/a -f java-res/a/a -C java-res/b -f java-res/b/b",
  925. },
  926. {
  927. // Test that a module exclude_java_resource_dirs excludes the files
  928. name: "wildcard dirs",
  929. prop: `java_resource_dirs: ["java-res/*"], exclude_java_resource_dirs: ["java-res/b"]`,
  930. args: "-C java-res/a -f java-res/a/a",
  931. },
  932. {
  933. // Test wildcards in java_resources
  934. name: "wildcard files",
  935. prop: `java_resources: ["java-res/**/*"]`,
  936. args: "-C . -f java-res/a/a -f java-res/b/b",
  937. },
  938. {
  939. // Test exclude_java_resources with java_resources
  940. name: "wildcard files with exclude",
  941. prop: `java_resources: ["java-res/**/*"], exclude_java_resources: ["java-res/b/*"]`,
  942. args: "-C . -f java-res/a/a",
  943. },
  944. {
  945. // Test exclude_java_resources with java_resource_dirs
  946. name: "resource dirs with exclude files",
  947. prop: `java_resource_dirs: ["java-res"], exclude_java_resources: ["java-res/b/b"]`,
  948. args: "-C java-res -f java-res/a/a",
  949. },
  950. {
  951. // Test exclude_java_resource_dirs with java_resource_dirs
  952. name: "resource dirs with exclude files",
  953. prop: `java_resource_dirs: ["java-res", "java-res2"], exclude_java_resource_dirs: ["java-res2"]`,
  954. args: "-C java-res -f java-res/a/a -f java-res/b/b",
  955. },
  956. }
  957. for _, test := range table {
  958. t.Run(test.name, func(t *testing.T) {
  959. ctx, _ := testJavaWithFS(t, `
  960. java_library {
  961. name: "foo",
  962. srcs: [
  963. "a.java",
  964. "b.java",
  965. "c.java",
  966. ],
  967. `+test.prop+`,
  968. }
  969. `+test.extra,
  970. map[string][]byte{
  971. "java-res/a/a": nil,
  972. "java-res/b/b": nil,
  973. "java-res2/a": nil,
  974. },
  975. )
  976. foo := ctx.ModuleForTests("foo", "android_common").Output("withres/foo.jar")
  977. fooRes := ctx.ModuleForTests("foo", "android_common").Output("res/foo.jar")
  978. if !inList(fooRes.Output.String(), foo.Inputs.Strings()) {
  979. t.Errorf("foo combined jars %v does not contain %q",
  980. foo.Inputs.Strings(), fooRes.Output.String())
  981. }
  982. if fooRes.Args["jarArgs"] != test.args {
  983. t.Errorf("foo resource jar args %q is not %q",
  984. fooRes.Args["jarArgs"], test.args)
  985. }
  986. })
  987. }
  988. }
  989. func TestIncludeSrcs(t *testing.T) {
  990. ctx, _ := testJavaWithFS(t, `
  991. java_library {
  992. name: "foo",
  993. srcs: [
  994. "a.java",
  995. "b.java",
  996. "c.java",
  997. ],
  998. include_srcs: true,
  999. }
  1000. java_library {
  1001. name: "bar",
  1002. srcs: [
  1003. "a.java",
  1004. "b.java",
  1005. "c.java",
  1006. ],
  1007. java_resource_dirs: ["java-res"],
  1008. include_srcs: true,
  1009. }
  1010. `, map[string][]byte{
  1011. "java-res/a/a": nil,
  1012. "java-res/b/b": nil,
  1013. "java-res2/a": nil,
  1014. })
  1015. // Test a library with include_srcs: true
  1016. foo := ctx.ModuleForTests("foo", "android_common").Output("withres/foo.jar")
  1017. fooSrcJar := ctx.ModuleForTests("foo", "android_common").Output("foo.srcjar")
  1018. if g, w := fooSrcJar.Output.String(), foo.Inputs.Strings(); !inList(g, w) {
  1019. t.Errorf("foo combined jars %v does not contain %q", w, g)
  1020. }
  1021. if g, w := fooSrcJar.Args["jarArgs"], "-C . -f a.java -f b.java -f c.java"; g != w {
  1022. t.Errorf("foo source jar args %q is not %q", w, g)
  1023. }
  1024. // Test a library with include_srcs: true and resources
  1025. bar := ctx.ModuleForTests("bar", "android_common").Output("withres/bar.jar")
  1026. barResCombined := ctx.ModuleForTests("bar", "android_common").Output("res-combined/bar.jar")
  1027. barRes := ctx.ModuleForTests("bar", "android_common").Output("res/bar.jar")
  1028. barSrcJar := ctx.ModuleForTests("bar", "android_common").Output("bar.srcjar")
  1029. if g, w := barSrcJar.Output.String(), barResCombined.Inputs.Strings(); !inList(g, w) {
  1030. t.Errorf("bar combined resource jars %v does not contain %q", w, g)
  1031. }
  1032. if g, w := barRes.Output.String(), barResCombined.Inputs.Strings(); !inList(g, w) {
  1033. t.Errorf("bar combined resource jars %v does not contain %q", w, g)
  1034. }
  1035. if g, w := barResCombined.Output.String(), bar.Inputs.Strings(); !inList(g, w) {
  1036. t.Errorf("bar combined jars %v does not contain %q", w, g)
  1037. }
  1038. if g, w := barSrcJar.Args["jarArgs"], "-C . -f a.java -f b.java -f c.java"; g != w {
  1039. t.Errorf("bar source jar args %q is not %q", w, g)
  1040. }
  1041. if g, w := barRes.Args["jarArgs"], "-C java-res -f java-res/a/a -f java-res/b/b"; g != w {
  1042. t.Errorf("bar resource jar args %q is not %q", w, g)
  1043. }
  1044. }
  1045. func TestJavaLint(t *testing.T) {
  1046. ctx, _ := testJavaWithFS(t, `
  1047. java_library {
  1048. name: "foo",
  1049. srcs: [
  1050. "a.java",
  1051. "b.java",
  1052. "c.java",
  1053. ],
  1054. min_sdk_version: "29",
  1055. sdk_version: "system_current",
  1056. }
  1057. `, map[string][]byte{
  1058. "lint-baseline.xml": nil,
  1059. })
  1060. foo := ctx.ModuleForTests("foo", "android_common")
  1061. sboxProto := android.RuleBuilderSboxProtoForTests(t, foo.Output("lint.sbox.textproto"))
  1062. if !strings.Contains(*sboxProto.Commands[0].Command, "--baseline lint-baseline.xml") {
  1063. t.Error("did not pass --baseline flag")
  1064. }
  1065. }
  1066. func TestJavaLintWithoutBaseline(t *testing.T) {
  1067. ctx, _ := testJavaWithFS(t, `
  1068. java_library {
  1069. name: "foo",
  1070. srcs: [
  1071. "a.java",
  1072. "b.java",
  1073. "c.java",
  1074. ],
  1075. min_sdk_version: "29",
  1076. sdk_version: "system_current",
  1077. }
  1078. `, map[string][]byte{})
  1079. foo := ctx.ModuleForTests("foo", "android_common")
  1080. sboxProto := android.RuleBuilderSboxProtoForTests(t, foo.Output("lint.sbox.textproto"))
  1081. if strings.Contains(*sboxProto.Commands[0].Command, "--baseline") {
  1082. t.Error("passed --baseline flag for non existent file")
  1083. }
  1084. }
  1085. func TestJavaLintRequiresCustomLintFileToExist(t *testing.T) {
  1086. android.GroupFixturePreparers(
  1087. PrepareForTestWithJavaDefaultModules,
  1088. android.PrepareForTestDisallowNonExistentPaths,
  1089. ).ExtendWithErrorHandler(android.FixtureExpectsAllErrorsToMatchAPattern([]string{`source path "mybaseline.xml" does not exist`})).
  1090. RunTestWithBp(t, `
  1091. java_library {
  1092. name: "foo",
  1093. srcs: [
  1094. ],
  1095. min_sdk_version: "29",
  1096. sdk_version: "system_current",
  1097. lint: {
  1098. baseline_filename: "mybaseline.xml",
  1099. },
  1100. }
  1101. `)
  1102. }
  1103. func TestJavaLintUsesCorrectBpConfig(t *testing.T) {
  1104. ctx, _ := testJavaWithFS(t, `
  1105. java_library {
  1106. name: "foo",
  1107. srcs: [
  1108. "a.java",
  1109. "b.java",
  1110. "c.java",
  1111. ],
  1112. min_sdk_version: "29",
  1113. sdk_version: "system_current",
  1114. lint: {
  1115. error_checks: ["SomeCheck"],
  1116. baseline_filename: "mybaseline.xml",
  1117. },
  1118. }
  1119. `, map[string][]byte{
  1120. "mybaseline.xml": nil,
  1121. })
  1122. foo := ctx.ModuleForTests("foo", "android_common")
  1123. sboxProto := android.RuleBuilderSboxProtoForTests(t, foo.Output("lint.sbox.textproto"))
  1124. if !strings.Contains(*sboxProto.Commands[0].Command, "--baseline mybaseline.xml") {
  1125. t.Error("did not use the correct file for baseline")
  1126. }
  1127. }
  1128. func TestGeneratedSources(t *testing.T) {
  1129. ctx, _ := testJavaWithFS(t, `
  1130. java_library {
  1131. name: "foo",
  1132. srcs: [
  1133. "a*.java",
  1134. ":gen",
  1135. "b*.java",
  1136. ],
  1137. }
  1138. genrule {
  1139. name: "gen",
  1140. tool_files: ["java-res/a"],
  1141. out: ["gen.java"],
  1142. }
  1143. `, map[string][]byte{
  1144. "a.java": nil,
  1145. "b.java": nil,
  1146. })
  1147. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  1148. genrule := ctx.ModuleForTests("gen", "").Rule("generator")
  1149. if filepath.Base(genrule.Output.String()) != "gen.java" {
  1150. t.Fatalf(`gen output file %v is not ".../gen.java"`, genrule.Output.String())
  1151. }
  1152. if len(javac.Inputs) != 3 ||
  1153. javac.Inputs[0].String() != "a.java" ||
  1154. javac.Inputs[1].String() != genrule.Output.String() ||
  1155. javac.Inputs[2].String() != "b.java" {
  1156. t.Errorf(`foo inputs %v != ["a.java", ".../gen.java", "b.java"]`, javac.Inputs)
  1157. }
  1158. }
  1159. func TestTurbine(t *testing.T) {
  1160. result := android.GroupFixturePreparers(
  1161. prepareForJavaTest, FixtureWithPrebuiltApis(map[string][]string{"14": {"foo"}})).
  1162. RunTestWithBp(t, `
  1163. java_library {
  1164. name: "foo",
  1165. srcs: ["a.java"],
  1166. sdk_version: "14",
  1167. }
  1168. java_library {
  1169. name: "bar",
  1170. srcs: ["b.java"],
  1171. static_libs: ["foo"],
  1172. sdk_version: "14",
  1173. }
  1174. java_library {
  1175. name: "baz",
  1176. srcs: ["c.java"],
  1177. libs: ["bar"],
  1178. sdk_version: "14",
  1179. }
  1180. `)
  1181. fooTurbine := result.ModuleForTests("foo", "android_common").Rule("turbine")
  1182. barTurbine := result.ModuleForTests("bar", "android_common").Rule("turbine")
  1183. barJavac := result.ModuleForTests("bar", "android_common").Rule("javac")
  1184. barTurbineCombined := result.ModuleForTests("bar", "android_common").Description("for turbine")
  1185. bazJavac := result.ModuleForTests("baz", "android_common").Rule("javac")
  1186. android.AssertPathsRelativeToTopEquals(t, "foo inputs", []string{"a.java"}, fooTurbine.Inputs)
  1187. fooHeaderJar := filepath.Join("out", "soong", ".intermediates", "foo", "android_common", "turbine-combined", "foo.jar")
  1188. barTurbineJar := filepath.Join("out", "soong", ".intermediates", "bar", "android_common", "turbine", "bar.jar")
  1189. android.AssertStringDoesContain(t, "bar turbine classpath", barTurbine.Args["classpath"], fooHeaderJar)
  1190. android.AssertStringDoesContain(t, "bar javac classpath", barJavac.Args["classpath"], fooHeaderJar)
  1191. android.AssertPathsRelativeToTopEquals(t, "bar turbine combineJar", []string{barTurbineJar, fooHeaderJar}, barTurbineCombined.Inputs)
  1192. android.AssertStringDoesContain(t, "baz javac classpath", bazJavac.Args["classpath"], "prebuilts/sdk/14/public/android.jar")
  1193. }
  1194. func TestSharding(t *testing.T) {
  1195. ctx, _ := testJava(t, `
  1196. java_library {
  1197. name: "bar",
  1198. srcs: ["a.java","b.java","c.java"],
  1199. javac_shard_size: 1
  1200. }
  1201. `)
  1202. barHeaderJar := filepath.Join("out", "soong", ".intermediates", "bar", "android_common", "turbine-combined", "bar.jar")
  1203. for i := 0; i < 3; i++ {
  1204. barJavac := ctx.ModuleForTests("bar", "android_common").Description("javac" + strconv.Itoa(i))
  1205. if !strings.Contains(barJavac.Args["classpath"], barHeaderJar) {
  1206. t.Errorf("bar javac classpath %v does not contain %q", barJavac.Args["classpath"], barHeaderJar)
  1207. }
  1208. }
  1209. }
  1210. func TestJarGenrules(t *testing.T) {
  1211. ctx, _ := testJava(t, `
  1212. java_library {
  1213. name: "foo",
  1214. srcs: ["a.java"],
  1215. }
  1216. java_genrule {
  1217. name: "jargen",
  1218. tool_files: ["b.java"],
  1219. cmd: "$(location b.java) $(in) $(out)",
  1220. out: ["jargen.jar"],
  1221. srcs: [":foo"],
  1222. }
  1223. java_library {
  1224. name: "bar",
  1225. static_libs: ["jargen"],
  1226. srcs: ["c.java"],
  1227. }
  1228. java_library {
  1229. name: "baz",
  1230. libs: ["jargen"],
  1231. srcs: ["c.java"],
  1232. }
  1233. `)
  1234. foo := ctx.ModuleForTests("foo", "android_common").Output("javac/foo.jar")
  1235. jargen := ctx.ModuleForTests("jargen", "android_common").Output("jargen.jar")
  1236. bar := ctx.ModuleForTests("bar", "android_common").Output("javac/bar.jar")
  1237. baz := ctx.ModuleForTests("baz", "android_common").Output("javac/baz.jar")
  1238. barCombined := ctx.ModuleForTests("bar", "android_common").Output("combined/bar.jar")
  1239. if g, w := jargen.Implicits.Strings(), foo.Output.String(); !android.InList(w, g) {
  1240. t.Errorf("expected jargen inputs [%q], got %q", w, g)
  1241. }
  1242. if !strings.Contains(bar.Args["classpath"], jargen.Output.String()) {
  1243. t.Errorf("bar classpath %v does not contain %q", bar.Args["classpath"], jargen.Output.String())
  1244. }
  1245. if !strings.Contains(baz.Args["classpath"], jargen.Output.String()) {
  1246. t.Errorf("baz classpath %v does not contain %q", baz.Args["classpath"], jargen.Output.String())
  1247. }
  1248. if len(barCombined.Inputs) != 2 ||
  1249. barCombined.Inputs[0].String() != bar.Output.String() ||
  1250. barCombined.Inputs[1].String() != jargen.Output.String() {
  1251. t.Errorf("bar combined jar inputs %v is not [%q, %q]",
  1252. barCombined.Inputs.Strings(), bar.Output.String(), jargen.Output.String())
  1253. }
  1254. }
  1255. func TestExcludeFileGroupInSrcs(t *testing.T) {
  1256. ctx, _ := testJava(t, `
  1257. java_library {
  1258. name: "foo",
  1259. srcs: ["a.java", ":foo-srcs"],
  1260. exclude_srcs: ["a.java", ":foo-excludes"],
  1261. }
  1262. filegroup {
  1263. name: "foo-srcs",
  1264. srcs: ["java-fg/a.java", "java-fg/b.java", "java-fg/c.java"],
  1265. }
  1266. filegroup {
  1267. name: "foo-excludes",
  1268. srcs: ["java-fg/a.java", "java-fg/b.java"],
  1269. }
  1270. `)
  1271. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  1272. if len(javac.Inputs) != 1 || javac.Inputs[0].String() != "java-fg/c.java" {
  1273. t.Errorf(`foo inputs %v != ["java-fg/c.java"]`, javac.Inputs)
  1274. }
  1275. }
  1276. func TestJavaLibrary(t *testing.T) {
  1277. testJavaWithFS(t, "", map[string][]byte{
  1278. "libcore/Android.bp": []byte(`
  1279. java_library {
  1280. name: "core",
  1281. sdk_version: "none",
  1282. system_modules: "none",
  1283. }
  1284. filegroup {
  1285. name: "core-jar",
  1286. srcs: [":core{.jar}"],
  1287. }
  1288. `),
  1289. })
  1290. }
  1291. func TestJavaImport(t *testing.T) {
  1292. testJavaWithFS(t, "", map[string][]byte{
  1293. "libcore/Android.bp": []byte(`
  1294. java_import {
  1295. name: "core",
  1296. sdk_version: "none",
  1297. }
  1298. filegroup {
  1299. name: "core-jar",
  1300. srcs: [":core{.jar}"],
  1301. }
  1302. `),
  1303. })
  1304. }
  1305. func TestJavaSdkLibrary(t *testing.T) {
  1306. result := android.GroupFixturePreparers(
  1307. prepareForJavaTest,
  1308. PrepareForTestWithJavaSdkLibraryFiles,
  1309. FixtureWithPrebuiltApis(map[string][]string{
  1310. "28": {"foo"},
  1311. "29": {"foo"},
  1312. "30": {"bar", "barney", "baz", "betty", "foo", "fred", "quuz", "wilma"},
  1313. }),
  1314. ).RunTestWithBp(t, `
  1315. droiddoc_exported_dir {
  1316. name: "droiddoc-templates-sdk",
  1317. path: ".",
  1318. }
  1319. java_sdk_library {
  1320. name: "foo",
  1321. srcs: ["a.java", "b.java"],
  1322. api_packages: ["foo"],
  1323. }
  1324. java_sdk_library {
  1325. name: "bar",
  1326. srcs: ["a.java", "b.java"],
  1327. api_packages: ["bar"],
  1328. }
  1329. java_library {
  1330. name: "baz",
  1331. srcs: ["c.java"],
  1332. libs: ["foo", "bar.stubs"],
  1333. sdk_version: "system_current",
  1334. }
  1335. java_sdk_library {
  1336. name: "barney",
  1337. srcs: ["c.java"],
  1338. api_only: true,
  1339. }
  1340. java_sdk_library {
  1341. name: "betty",
  1342. srcs: ["c.java"],
  1343. shared_library: false,
  1344. }
  1345. java_sdk_library_import {
  1346. name: "quuz",
  1347. public: {
  1348. jars: ["c.jar"],
  1349. },
  1350. }
  1351. java_sdk_library_import {
  1352. name: "fred",
  1353. public: {
  1354. jars: ["b.jar"],
  1355. },
  1356. }
  1357. java_sdk_library_import {
  1358. name: "wilma",
  1359. public: {
  1360. jars: ["b.jar"],
  1361. },
  1362. shared_library: false,
  1363. }
  1364. java_library {
  1365. name: "qux",
  1366. srcs: ["c.java"],
  1367. libs: ["baz", "fred", "quuz.stubs", "wilma", "barney", "betty"],
  1368. sdk_version: "system_current",
  1369. }
  1370. java_library {
  1371. name: "baz-test",
  1372. srcs: ["c.java"],
  1373. libs: ["foo"],
  1374. sdk_version: "test_current",
  1375. }
  1376. java_library {
  1377. name: "baz-29",
  1378. srcs: ["c.java"],
  1379. libs: ["foo"],
  1380. sdk_version: "system_29",
  1381. }
  1382. java_library {
  1383. name: "baz-module-30",
  1384. srcs: ["c.java"],
  1385. libs: ["foo"],
  1386. sdk_version: "module_30",
  1387. }
  1388. `)
  1389. // check the existence of the internal modules
  1390. result.ModuleForTests("foo", "android_common")
  1391. result.ModuleForTests(apiScopePublic.stubsLibraryModuleName("foo"), "android_common")
  1392. result.ModuleForTests(apiScopeSystem.stubsLibraryModuleName("foo"), "android_common")
  1393. result.ModuleForTests(apiScopeTest.stubsLibraryModuleName("foo"), "android_common")
  1394. result.ModuleForTests(apiScopePublic.stubsSourceModuleName("foo"), "android_common")
  1395. result.ModuleForTests(apiScopeSystem.stubsSourceModuleName("foo"), "android_common")
  1396. result.ModuleForTests(apiScopeTest.stubsSourceModuleName("foo"), "android_common")
  1397. result.ModuleForTests("foo"+sdkXmlFileSuffix, "android_common")
  1398. result.ModuleForTests("foo.api.public.28", "")
  1399. result.ModuleForTests("foo.api.system.28", "")
  1400. result.ModuleForTests("foo.api.test.28", "")
  1401. bazJavac := result.ModuleForTests("baz", "android_common").Rule("javac")
  1402. // tests if baz is actually linked to the stubs lib
  1403. android.AssertStringDoesContain(t, "baz javac classpath", bazJavac.Args["classpath"], "foo.stubs.system.jar")
  1404. // ... and not to the impl lib
  1405. android.AssertStringDoesNotContain(t, "baz javac classpath", bazJavac.Args["classpath"], "foo.jar")
  1406. // test if baz is not linked to the system variant of foo
  1407. android.AssertStringDoesNotContain(t, "baz javac classpath", bazJavac.Args["classpath"], "foo.stubs.jar")
  1408. bazTestJavac := result.ModuleForTests("baz-test", "android_common").Rule("javac")
  1409. // tests if baz-test is actually linked to the test stubs lib
  1410. android.AssertStringDoesContain(t, "baz-test javac classpath", bazTestJavac.Args["classpath"], "foo.stubs.test.jar")
  1411. baz29Javac := result.ModuleForTests("baz-29", "android_common").Rule("javac")
  1412. // tests if baz-29 is actually linked to the system 29 stubs lib
  1413. android.AssertStringDoesContain(t, "baz-29 javac classpath", baz29Javac.Args["classpath"], "prebuilts/sdk/29/system/foo.jar")
  1414. bazModule30Javac := result.ModuleForTests("baz-module-30", "android_common").Rule("javac")
  1415. // tests if "baz-module-30" is actually linked to the module 30 stubs lib
  1416. android.AssertStringDoesContain(t, "baz-module-30 javac classpath", bazModule30Javac.Args["classpath"], "prebuilts/sdk/30/module-lib/foo.jar")
  1417. // test if baz has exported SDK lib names foo and bar to qux
  1418. qux := result.ModuleForTests("qux", "android_common")
  1419. if quxLib, ok := qux.Module().(*Library); ok {
  1420. sdkLibs := quxLib.ClassLoaderContexts().UsesLibs()
  1421. android.AssertDeepEquals(t, "qux exports", []string{"foo", "bar", "fred", "quuz"}, sdkLibs)
  1422. }
  1423. }
  1424. func TestJavaSdkLibrary_StubOrImplOnlyLibs(t *testing.T) {
  1425. result := android.GroupFixturePreparers(
  1426. prepareForJavaTest,
  1427. PrepareForTestWithJavaSdkLibraryFiles,
  1428. FixtureWithLastReleaseApis("sdklib"),
  1429. ).RunTestWithBp(t, `
  1430. java_sdk_library {
  1431. name: "sdklib",
  1432. srcs: ["a.java"],
  1433. impl_only_libs: ["foo"],
  1434. stub_only_libs: ["bar"],
  1435. }
  1436. java_library {
  1437. name: "foo",
  1438. srcs: ["a.java"],
  1439. sdk_version: "current",
  1440. }
  1441. java_library {
  1442. name: "bar",
  1443. srcs: ["a.java"],
  1444. sdk_version: "current",
  1445. }
  1446. `)
  1447. for _, implName := range []string{"sdklib", "sdklib.impl"} {
  1448. implJavacCp := result.ModuleForTests(implName, "android_common").Rule("javac").Args["classpath"]
  1449. if !strings.Contains(implJavacCp, "/foo.jar") || strings.Contains(implJavacCp, "/bar.jar") {
  1450. t.Errorf("%v javac classpath %v does not contain foo and not bar", implName, implJavacCp)
  1451. }
  1452. }
  1453. stubName := apiScopePublic.stubsLibraryModuleName("sdklib")
  1454. stubsJavacCp := result.ModuleForTests(stubName, "android_common").Rule("javac").Args["classpath"]
  1455. if strings.Contains(stubsJavacCp, "/foo.jar") || !strings.Contains(stubsJavacCp, "/bar.jar") {
  1456. t.Errorf("stubs javac classpath %v does not contain bar and not foo", stubsJavacCp)
  1457. }
  1458. }
  1459. func TestJavaSdkLibrary_DoNotAccessImplWhenItIsNotBuilt(t *testing.T) {
  1460. result := android.GroupFixturePreparers(
  1461. prepareForJavaTest,
  1462. PrepareForTestWithJavaSdkLibraryFiles,
  1463. FixtureWithLastReleaseApis("foo"),
  1464. ).RunTestWithBp(t, `
  1465. java_sdk_library {
  1466. name: "foo",
  1467. srcs: ["a.java"],
  1468. api_only: true,
  1469. public: {
  1470. enabled: true,
  1471. },
  1472. }
  1473. java_library {
  1474. name: "bar",
  1475. srcs: ["b.java"],
  1476. libs: ["foo"],
  1477. }
  1478. `)
  1479. // The bar library should depend on the stubs jar.
  1480. barLibrary := result.ModuleForTests("bar", "android_common").Rule("javac")
  1481. if expected, actual := `^-classpath .*:out/soong/[^:]*/turbine-combined/foo\.stubs\.jar$`, barLibrary.Args["classpath"]; !regexp.MustCompile(expected).MatchString(actual) {
  1482. t.Errorf("expected %q, found %#q", expected, actual)
  1483. }
  1484. }
  1485. func TestJavaSdkLibrary_UseSourcesFromAnotherSdkLibrary(t *testing.T) {
  1486. android.GroupFixturePreparers(
  1487. prepareForJavaTest,
  1488. PrepareForTestWithJavaSdkLibraryFiles,
  1489. FixtureWithLastReleaseApis("foo"),
  1490. ).RunTestWithBp(t, `
  1491. java_sdk_library {
  1492. name: "foo",
  1493. srcs: ["a.java"],
  1494. api_packages: ["foo"],
  1495. public: {
  1496. enabled: true,
  1497. },
  1498. }
  1499. java_library {
  1500. name: "bar",
  1501. srcs: ["b.java", ":foo{.public.stubs.source}"],
  1502. }
  1503. `)
  1504. }
  1505. func TestJavaSdkLibrary_AccessOutputFiles_MissingScope(t *testing.T) {
  1506. android.GroupFixturePreparers(
  1507. prepareForJavaTest,
  1508. PrepareForTestWithJavaSdkLibraryFiles,
  1509. FixtureWithLastReleaseApis("foo"),
  1510. ).
  1511. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`"foo" does not provide api scope system`)).
  1512. RunTestWithBp(t, `
  1513. java_sdk_library {
  1514. name: "foo",
  1515. srcs: ["a.java"],
  1516. api_packages: ["foo"],
  1517. public: {
  1518. enabled: true,
  1519. },
  1520. }
  1521. java_library {
  1522. name: "bar",
  1523. srcs: ["b.java", ":foo{.system.stubs.source}"],
  1524. }
  1525. `)
  1526. }
  1527. func TestJavaSdkLibrary_Deps(t *testing.T) {
  1528. result := android.GroupFixturePreparers(
  1529. prepareForJavaTest,
  1530. PrepareForTestWithJavaSdkLibraryFiles,
  1531. FixtureWithLastReleaseApis("sdklib"),
  1532. ).RunTestWithBp(t, `
  1533. java_sdk_library {
  1534. name: "sdklib",
  1535. srcs: ["a.java"],
  1536. sdk_version: "none",
  1537. system_modules: "none",
  1538. public: {
  1539. enabled: true,
  1540. },
  1541. }
  1542. `)
  1543. CheckModuleDependencies(t, result.TestContext, "sdklib", "android_common", []string{
  1544. `dex2oatd`,
  1545. `sdklib.impl`,
  1546. `sdklib.stubs`,
  1547. `sdklib.stubs.source`,
  1548. `sdklib.xml`,
  1549. })
  1550. }
  1551. func TestJavaSdkLibraryImport_AccessOutputFiles(t *testing.T) {
  1552. prepareForJavaTest.RunTestWithBp(t, `
  1553. java_sdk_library_import {
  1554. name: "foo",
  1555. public: {
  1556. jars: ["a.jar"],
  1557. stub_srcs: ["a.java"],
  1558. current_api: "api/current.txt",
  1559. removed_api: "api/removed.txt",
  1560. },
  1561. }
  1562. java_library {
  1563. name: "bar",
  1564. srcs: [":foo{.public.stubs.source}"],
  1565. java_resources: [
  1566. ":foo{.public.api.txt}",
  1567. ":foo{.public.removed-api.txt}",
  1568. ],
  1569. }
  1570. `)
  1571. }
  1572. func TestJavaSdkLibraryImport_AccessOutputFiles_Invalid(t *testing.T) {
  1573. bp := `
  1574. java_sdk_library_import {
  1575. name: "foo",
  1576. public: {
  1577. jars: ["a.jar"],
  1578. },
  1579. }
  1580. `
  1581. t.Run("stubs.source", func(t *testing.T) {
  1582. prepareForJavaTest.
  1583. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`stubs.source not available for api scope public`)).
  1584. RunTestWithBp(t, bp+`
  1585. java_library {
  1586. name: "bar",
  1587. srcs: [":foo{.public.stubs.source}"],
  1588. java_resources: [
  1589. ":foo{.public.api.txt}",
  1590. ":foo{.public.removed-api.txt}",
  1591. ],
  1592. }
  1593. `)
  1594. })
  1595. t.Run("api.txt", func(t *testing.T) {
  1596. prepareForJavaTest.
  1597. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`api.txt not available for api scope public`)).
  1598. RunTestWithBp(t, bp+`
  1599. java_library {
  1600. name: "bar",
  1601. srcs: ["a.java"],
  1602. java_resources: [
  1603. ":foo{.public.api.txt}",
  1604. ],
  1605. }
  1606. `)
  1607. })
  1608. t.Run("removed-api.txt", func(t *testing.T) {
  1609. prepareForJavaTest.
  1610. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`removed-api.txt not available for api scope public`)).
  1611. RunTestWithBp(t, bp+`
  1612. java_library {
  1613. name: "bar",
  1614. srcs: ["a.java"],
  1615. java_resources: [
  1616. ":foo{.public.removed-api.txt}",
  1617. ],
  1618. }
  1619. `)
  1620. })
  1621. }
  1622. func TestJavaSdkLibrary_InvalidScopes(t *testing.T) {
  1623. prepareForJavaTest.
  1624. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`module "foo": enabled api scope "system" depends on disabled scope "public"`)).
  1625. RunTestWithBp(t, `
  1626. java_sdk_library {
  1627. name: "foo",
  1628. srcs: ["a.java", "b.java"],
  1629. api_packages: ["foo"],
  1630. // Explicitly disable public to test the check that ensures the set of enabled
  1631. // scopes is consistent.
  1632. public: {
  1633. enabled: false,
  1634. },
  1635. system: {
  1636. enabled: true,
  1637. },
  1638. }
  1639. `)
  1640. }
  1641. func TestJavaSdkLibrary_SdkVersion_ForScope(t *testing.T) {
  1642. android.GroupFixturePreparers(
  1643. prepareForJavaTest,
  1644. PrepareForTestWithJavaSdkLibraryFiles,
  1645. FixtureWithLastReleaseApis("foo"),
  1646. ).RunTestWithBp(t, `
  1647. java_sdk_library {
  1648. name: "foo",
  1649. srcs: ["a.java", "b.java"],
  1650. api_packages: ["foo"],
  1651. system: {
  1652. enabled: true,
  1653. sdk_version: "module_current",
  1654. },
  1655. }
  1656. `)
  1657. }
  1658. func TestJavaSdkLibrary_ModuleLib(t *testing.T) {
  1659. android.GroupFixturePreparers(
  1660. prepareForJavaTest,
  1661. PrepareForTestWithJavaSdkLibraryFiles,
  1662. FixtureWithLastReleaseApis("foo"),
  1663. ).RunTestWithBp(t, `
  1664. java_sdk_library {
  1665. name: "foo",
  1666. srcs: ["a.java", "b.java"],
  1667. api_packages: ["foo"],
  1668. system: {
  1669. enabled: true,
  1670. },
  1671. module_lib: {
  1672. enabled: true,
  1673. },
  1674. }
  1675. `)
  1676. }
  1677. func TestJavaSdkLibrary_SystemServer(t *testing.T) {
  1678. android.GroupFixturePreparers(
  1679. prepareForJavaTest,
  1680. PrepareForTestWithJavaSdkLibraryFiles,
  1681. FixtureWithLastReleaseApis("foo"),
  1682. ).RunTestWithBp(t, `
  1683. java_sdk_library {
  1684. name: "foo",
  1685. srcs: ["a.java", "b.java"],
  1686. api_packages: ["foo"],
  1687. system: {
  1688. enabled: true,
  1689. },
  1690. system_server: {
  1691. enabled: true,
  1692. },
  1693. }
  1694. `)
  1695. }
  1696. func TestJavaSdkLibrary_MissingScope(t *testing.T) {
  1697. prepareForJavaTest.
  1698. ExtendWithErrorHandler(android.FixtureExpectsAtLeastOneErrorMatchingPattern(`requires api scope module-lib from foo but it only has \[\] available`)).
  1699. RunTestWithBp(t, `
  1700. java_sdk_library {
  1701. name: "foo",
  1702. srcs: ["a.java"],
  1703. public: {
  1704. enabled: false,
  1705. },
  1706. }
  1707. java_library {
  1708. name: "baz",
  1709. srcs: ["a.java"],
  1710. libs: ["foo"],
  1711. sdk_version: "module_current",
  1712. }
  1713. `)
  1714. }
  1715. func TestJavaSdkLibrary_FallbackScope(t *testing.T) {
  1716. android.GroupFixturePreparers(
  1717. prepareForJavaTest,
  1718. PrepareForTestWithJavaSdkLibraryFiles,
  1719. FixtureWithLastReleaseApis("foo"),
  1720. ).RunTestWithBp(t, `
  1721. java_sdk_library {
  1722. name: "foo",
  1723. srcs: ["a.java"],
  1724. system: {
  1725. enabled: true,
  1726. },
  1727. }
  1728. java_library {
  1729. name: "baz",
  1730. srcs: ["a.java"],
  1731. libs: ["foo"],
  1732. // foo does not have module-lib scope so it should fallback to system
  1733. sdk_version: "module_current",
  1734. }
  1735. `)
  1736. }
  1737. func TestJavaSdkLibrary_DefaultToStubs(t *testing.T) {
  1738. result := android.GroupFixturePreparers(
  1739. prepareForJavaTest,
  1740. PrepareForTestWithJavaSdkLibraryFiles,
  1741. FixtureWithLastReleaseApis("foo"),
  1742. ).RunTestWithBp(t, `
  1743. java_sdk_library {
  1744. name: "foo",
  1745. srcs: ["a.java"],
  1746. system: {
  1747. enabled: true,
  1748. },
  1749. default_to_stubs: true,
  1750. }
  1751. java_library {
  1752. name: "baz",
  1753. srcs: ["a.java"],
  1754. libs: ["foo"],
  1755. // does not have sdk_version set, should fallback to module,
  1756. // which will then fallback to system because the module scope
  1757. // is not enabled.
  1758. }
  1759. `)
  1760. // The baz library should depend on the system stubs jar.
  1761. bazLibrary := result.ModuleForTests("baz", "android_common").Rule("javac")
  1762. if expected, actual := `^-classpath .*:out/soong/[^:]*/turbine-combined/foo\.stubs.system\.jar$`, bazLibrary.Args["classpath"]; !regexp.MustCompile(expected).MatchString(actual) {
  1763. t.Errorf("expected %q, found %#q", expected, actual)
  1764. }
  1765. }
  1766. var compilerFlagsTestCases = []struct {
  1767. in string
  1768. out bool
  1769. }{
  1770. {
  1771. in: "a",
  1772. out: false,
  1773. },
  1774. {
  1775. in: "-a",
  1776. out: true,
  1777. },
  1778. {
  1779. in: "-no-jdk",
  1780. out: false,
  1781. },
  1782. {
  1783. in: "-no-stdlib",
  1784. out: false,
  1785. },
  1786. {
  1787. in: "-kotlin-home",
  1788. out: false,
  1789. },
  1790. {
  1791. in: "-kotlin-home /some/path",
  1792. out: false,
  1793. },
  1794. {
  1795. in: "-include-runtime",
  1796. out: false,
  1797. },
  1798. {
  1799. in: "-Xintellij-plugin-root",
  1800. out: false,
  1801. },
  1802. }
  1803. type mockContext struct {
  1804. android.ModuleContext
  1805. result bool
  1806. }
  1807. func (ctx *mockContext) PropertyErrorf(property, format string, args ...interface{}) {
  1808. // CheckBadCompilerFlags calls this function when the flag should be rejected
  1809. ctx.result = false
  1810. }
  1811. func TestCompilerFlags(t *testing.T) {
  1812. for _, testCase := range compilerFlagsTestCases {
  1813. ctx := &mockContext{result: true}
  1814. CheckKotlincFlags(ctx, []string{testCase.in})
  1815. if ctx.result != testCase.out {
  1816. t.Errorf("incorrect output:")
  1817. t.Errorf(" input: %#v", testCase.in)
  1818. t.Errorf(" expected: %#v", testCase.out)
  1819. t.Errorf(" got: %#v", ctx.result)
  1820. }
  1821. }
  1822. }
  1823. // TODO(jungjw): Consider making this more robust by ignoring path order.
  1824. func checkPatchModuleFlag(t *testing.T, ctx *android.TestContext, moduleName string, expected string) {
  1825. variables := ctx.ModuleForTests(moduleName, "android_common").VariablesForTestsRelativeToTop()
  1826. flags := strings.Split(variables["javacFlags"], " ")
  1827. got := ""
  1828. for _, flag := range flags {
  1829. keyEnd := strings.Index(flag, "=")
  1830. if keyEnd > -1 && flag[:keyEnd] == "--patch-module" {
  1831. got = flag[keyEnd+1:]
  1832. break
  1833. }
  1834. }
  1835. if expected != android.StringPathRelativeToTop(ctx.Config().BuildDir(), got) {
  1836. t.Errorf("Unexpected patch-module flag for module %q - expected %q, but got %q", moduleName, expected, got)
  1837. }
  1838. }
  1839. func TestPatchModule(t *testing.T) {
  1840. t.Run("Java language level 8", func(t *testing.T) {
  1841. // Test with legacy javac -source 1.8 -target 1.8
  1842. bp := `
  1843. java_library {
  1844. name: "foo",
  1845. srcs: ["a.java"],
  1846. java_version: "1.8",
  1847. }
  1848. java_library {
  1849. name: "bar",
  1850. srcs: ["b.java"],
  1851. sdk_version: "none",
  1852. system_modules: "none",
  1853. patch_module: "java.base",
  1854. java_version: "1.8",
  1855. }
  1856. java_library {
  1857. name: "baz",
  1858. srcs: ["c.java"],
  1859. patch_module: "java.base",
  1860. java_version: "1.8",
  1861. }
  1862. `
  1863. ctx, _ := testJava(t, bp)
  1864. checkPatchModuleFlag(t, ctx, "foo", "")
  1865. checkPatchModuleFlag(t, ctx, "bar", "")
  1866. checkPatchModuleFlag(t, ctx, "baz", "")
  1867. })
  1868. t.Run("Java language level 9", func(t *testing.T) {
  1869. // Test with default javac -source 9 -target 9
  1870. bp := `
  1871. java_library {
  1872. name: "foo",
  1873. srcs: ["a.java"],
  1874. }
  1875. java_library {
  1876. name: "bar",
  1877. srcs: ["b.java"],
  1878. sdk_version: "none",
  1879. system_modules: "none",
  1880. patch_module: "java.base",
  1881. }
  1882. java_library {
  1883. name: "baz",
  1884. srcs: [
  1885. "c.java",
  1886. // Tests for b/150878007
  1887. "dir/d.java",
  1888. "dir2/e.java",
  1889. "dir2/f.java",
  1890. "nested/dir/g.java"
  1891. ],
  1892. patch_module: "java.base",
  1893. }
  1894. `
  1895. ctx, _ := testJava(t, bp)
  1896. checkPatchModuleFlag(t, ctx, "foo", "")
  1897. expected := "java.base=.:out/soong"
  1898. checkPatchModuleFlag(t, ctx, "bar", expected)
  1899. expected = "java.base=" + strings.Join([]string{
  1900. ".", "out/soong", "dir", "dir2", "nested", defaultModuleToPath("ext"), defaultModuleToPath("framework")}, ":")
  1901. checkPatchModuleFlag(t, ctx, "baz", expected)
  1902. })
  1903. }
  1904. func TestJavaLibraryWithSystemModules(t *testing.T) {
  1905. ctx, _ := testJava(t, `
  1906. java_library {
  1907. name: "lib-with-source-system-modules",
  1908. srcs: [
  1909. "a.java",
  1910. ],
  1911. sdk_version: "none",
  1912. system_modules: "source-system-modules",
  1913. }
  1914. java_library {
  1915. name: "source-jar",
  1916. srcs: [
  1917. "a.java",
  1918. ],
  1919. }
  1920. java_system_modules {
  1921. name: "source-system-modules",
  1922. libs: ["source-jar"],
  1923. }
  1924. java_library {
  1925. name: "lib-with-prebuilt-system-modules",
  1926. srcs: [
  1927. "a.java",
  1928. ],
  1929. sdk_version: "none",
  1930. system_modules: "prebuilt-system-modules",
  1931. }
  1932. java_import {
  1933. name: "prebuilt-jar",
  1934. jars: ["a.jar"],
  1935. }
  1936. java_system_modules_import {
  1937. name: "prebuilt-system-modules",
  1938. libs: ["prebuilt-jar"],
  1939. }
  1940. `)
  1941. checkBootClasspathForSystemModule(t, ctx, "lib-with-source-system-modules", "/source-jar.jar")
  1942. checkBootClasspathForSystemModule(t, ctx, "lib-with-prebuilt-system-modules", "/prebuilt-jar.jar")
  1943. }
  1944. func checkBootClasspathForSystemModule(t *testing.T, ctx *android.TestContext, moduleName string, expectedSuffix string) {
  1945. javacRule := ctx.ModuleForTests(moduleName, "android_common").Rule("javac")
  1946. bootClasspath := javacRule.Args["bootClasspath"]
  1947. if strings.HasPrefix(bootClasspath, "--system ") && strings.HasSuffix(bootClasspath, expectedSuffix) {
  1948. t.Errorf("bootclasspath of %q must start with --system and end with %q, but was %#v.", moduleName, expectedSuffix, bootClasspath)
  1949. }
  1950. }
  1951. func TestAidlExportIncludeDirsFromImports(t *testing.T) {
  1952. ctx, _ := testJava(t, `
  1953. java_library {
  1954. name: "foo",
  1955. srcs: ["aidl/foo/IFoo.aidl"],
  1956. libs: ["bar"],
  1957. }
  1958. java_import {
  1959. name: "bar",
  1960. jars: ["a.jar"],
  1961. aidl: {
  1962. export_include_dirs: ["aidl/bar"],
  1963. },
  1964. }
  1965. `)
  1966. aidlCommand := ctx.ModuleForTests("foo", "android_common").Rule("aidl").RuleParams.Command
  1967. expectedAidlFlag := "-Iaidl/bar"
  1968. if !strings.Contains(aidlCommand, expectedAidlFlag) {
  1969. t.Errorf("aidl command %q does not contain %q", aidlCommand, expectedAidlFlag)
  1970. }
  1971. }
  1972. func TestAidlFlagsArePassedToTheAidlCompiler(t *testing.T) {
  1973. ctx, _ := testJava(t, `
  1974. java_library {
  1975. name: "foo",
  1976. srcs: ["aidl/foo/IFoo.aidl"],
  1977. aidl: { flags: ["-Werror"], },
  1978. }
  1979. `)
  1980. aidlCommand := ctx.ModuleForTests("foo", "android_common").Rule("aidl").RuleParams.Command
  1981. expectedAidlFlag := "-Werror"
  1982. if !strings.Contains(aidlCommand, expectedAidlFlag) {
  1983. t.Errorf("aidl command %q does not contain %q", aidlCommand, expectedAidlFlag)
  1984. }
  1985. }
  1986. func TestDataNativeBinaries(t *testing.T) {
  1987. ctx, _ := testJava(t, `
  1988. java_test_host {
  1989. name: "foo",
  1990. srcs: ["a.java"],
  1991. data_native_bins: ["bin"]
  1992. }
  1993. python_binary_host {
  1994. name: "bin",
  1995. srcs: ["bin.py"],
  1996. }
  1997. `)
  1998. buildOS := android.BuildOs.String()
  1999. test := ctx.ModuleForTests("foo", buildOS+"_common").Module().(*TestHost)
  2000. entries := android.AndroidMkEntriesForTest(t, ctx, test)[0]
  2001. expected := []string{"out/soong/.intermediates/bin/" + buildOS + "_x86_64_PY3/bin:bin"}
  2002. actual := entries.EntryMap["LOCAL_COMPATIBILITY_SUPPORT_FILES"]
  2003. android.AssertStringPathsRelativeToTopEquals(t, "LOCAL_COMPATIBILITY_SUPPORT_FILES", ctx.Config(), expected, actual)
  2004. }
  2005. func TestDefaultInstallable(t *testing.T) {
  2006. ctx, _ := testJava(t, `
  2007. java_test_host {
  2008. name: "foo"
  2009. }
  2010. `)
  2011. buildOS := android.BuildOs.String()
  2012. module := ctx.ModuleForTests("foo", buildOS+"_common").Module().(*TestHost)
  2013. assertDeepEquals(t, "Default installable value should be true.", proptools.BoolPtr(true),
  2014. module.properties.Installable)
  2015. }