java_test.go 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971
  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. "runtime"
  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. // testJavaWithFS runs tests using the prepareForJavaTest
  70. //
  71. // See testJava for an explanation as to how to stop using this deprecated method.
  72. //
  73. // deprecated
  74. func testJavaWithFS(t *testing.T, bp string, fs android.MockFS) (*android.TestContext, android.Config) {
  75. t.Helper()
  76. result := android.GroupFixturePreparers(
  77. prepareForJavaTest, fs.AddToFixture()).RunTestWithBp(t, bp)
  78. return result.TestContext, result.Config
  79. }
  80. // testJava runs tests using the prepareForJavaTest
  81. //
  82. // Do not add any new usages of this, instead use the prepareForJavaTest directly as it makes it
  83. // much easier to customize the test behavior.
  84. //
  85. // If it is necessary to customize the behavior of an existing test that uses this then please first
  86. // convert the test to using prepareForJavaTest first and then in a following change add the
  87. // appropriate fixture preparers. Keeping the conversion change separate makes it easy to verify
  88. // that it did not change the test behavior unexpectedly.
  89. //
  90. // deprecated
  91. func testJava(t *testing.T, bp string) (*android.TestContext, android.Config) {
  92. t.Helper()
  93. result := prepareForJavaTest.RunTestWithBp(t, bp)
  94. return result.TestContext, result.Config
  95. }
  96. // defaultModuleToPath constructs a path to the turbine generate jar for a default test module that
  97. // is defined in PrepareForIntegrationTestWithJava
  98. func defaultModuleToPath(name string) string {
  99. switch {
  100. case name == `""`:
  101. return name
  102. case strings.HasSuffix(name, ".jar"):
  103. return name
  104. default:
  105. return filepath.Join("out", "soong", ".intermediates", defaultJavaDir, name, "android_common", "turbine-combined", name+".jar")
  106. }
  107. }
  108. // Test that the PrepareForTestWithJavaDefaultModules provides all the files that it uses by
  109. // running it in a fixture that requires all source files to exist.
  110. func TestPrepareForTestWithJavaDefaultModules(t *testing.T) {
  111. android.GroupFixturePreparers(
  112. PrepareForTestWithJavaDefaultModules,
  113. android.PrepareForTestDisallowNonExistentPaths,
  114. ).RunTest(t)
  115. }
  116. func TestJavaLinkType(t *testing.T) {
  117. testJava(t, `
  118. java_library {
  119. name: "foo",
  120. srcs: ["a.java"],
  121. libs: ["bar"],
  122. static_libs: ["baz"],
  123. }
  124. java_library {
  125. name: "bar",
  126. sdk_version: "current",
  127. srcs: ["b.java"],
  128. }
  129. java_library {
  130. name: "baz",
  131. sdk_version: "system_current",
  132. srcs: ["c.java"],
  133. }
  134. `)
  135. testJavaError(t, "consider adjusting sdk_version: OR platform_apis:", `
  136. java_library {
  137. name: "foo",
  138. srcs: ["a.java"],
  139. libs: ["bar"],
  140. sdk_version: "current",
  141. static_libs: ["baz"],
  142. }
  143. java_library {
  144. name: "bar",
  145. sdk_version: "current",
  146. srcs: ["b.java"],
  147. }
  148. java_library {
  149. name: "baz",
  150. sdk_version: "system_current",
  151. srcs: ["c.java"],
  152. }
  153. `)
  154. testJava(t, `
  155. java_library {
  156. name: "foo",
  157. srcs: ["a.java"],
  158. libs: ["bar"],
  159. sdk_version: "system_current",
  160. static_libs: ["baz"],
  161. }
  162. java_library {
  163. name: "bar",
  164. sdk_version: "current",
  165. srcs: ["b.java"],
  166. }
  167. java_library {
  168. name: "baz",
  169. sdk_version: "system_current",
  170. srcs: ["c.java"],
  171. }
  172. `)
  173. testJavaError(t, "consider adjusting sdk_version: OR platform_apis:", `
  174. java_library {
  175. name: "foo",
  176. srcs: ["a.java"],
  177. libs: ["bar"],
  178. sdk_version: "system_current",
  179. static_libs: ["baz"],
  180. }
  181. java_library {
  182. name: "bar",
  183. sdk_version: "current",
  184. srcs: ["b.java"],
  185. }
  186. java_library {
  187. name: "baz",
  188. srcs: ["c.java"],
  189. }
  190. `)
  191. }
  192. func TestSimple(t *testing.T) {
  193. ctx, _ := testJava(t, `
  194. java_library {
  195. name: "foo",
  196. srcs: ["a.java"],
  197. libs: ["bar"],
  198. static_libs: ["baz"],
  199. }
  200. java_library {
  201. name: "bar",
  202. srcs: ["b.java"],
  203. }
  204. java_library {
  205. name: "baz",
  206. srcs: ["c.java"],
  207. }
  208. `)
  209. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  210. combineJar := ctx.ModuleForTests("foo", "android_common").Description("for javac")
  211. if len(javac.Inputs) != 1 || javac.Inputs[0].String() != "a.java" {
  212. t.Errorf(`foo inputs %v != ["a.java"]`, javac.Inputs)
  213. }
  214. baz := ctx.ModuleForTests("baz", "android_common").Rule("javac").Output.String()
  215. barTurbine := filepath.Join("out", "soong", ".intermediates", "bar", "android_common", "turbine-combined", "bar.jar")
  216. bazTurbine := filepath.Join("out", "soong", ".intermediates", "baz", "android_common", "turbine-combined", "baz.jar")
  217. android.AssertStringDoesContain(t, "foo classpath", javac.Args["classpath"], barTurbine)
  218. android.AssertStringDoesContain(t, "foo classpath", javac.Args["classpath"], bazTurbine)
  219. if len(combineJar.Inputs) != 2 || combineJar.Inputs[1].String() != baz {
  220. t.Errorf("foo combineJar inputs %v does not contain %q", combineJar.Inputs, baz)
  221. }
  222. }
  223. func TestExportedPlugins(t *testing.T) {
  224. type Result struct {
  225. library string
  226. processors string
  227. disableTurbine bool
  228. }
  229. var tests = []struct {
  230. name string
  231. extra string
  232. results []Result
  233. }{
  234. {
  235. name: "Exported plugin is not a direct plugin",
  236. extra: `java_library { name: "exports", srcs: ["a.java"], exported_plugins: ["plugin"] }`,
  237. results: []Result{{library: "exports", processors: "-proc:none"}},
  238. },
  239. {
  240. name: "Exports plugin to dependee",
  241. extra: `
  242. java_library{name: "exports", exported_plugins: ["plugin"]}
  243. java_library{name: "foo", srcs: ["a.java"], libs: ["exports"]}
  244. java_library{name: "bar", srcs: ["a.java"], static_libs: ["exports"]}
  245. `,
  246. results: []Result{
  247. {library: "foo", processors: "-processor com.android.TestPlugin"},
  248. {library: "bar", processors: "-processor com.android.TestPlugin"},
  249. },
  250. },
  251. {
  252. name: "Exports plugin to android_library",
  253. extra: `
  254. java_library{name: "exports", exported_plugins: ["plugin"]}
  255. android_library{name: "foo", srcs: ["a.java"], libs: ["exports"]}
  256. android_library{name: "bar", srcs: ["a.java"], static_libs: ["exports"]}
  257. `,
  258. results: []Result{
  259. {library: "foo", processors: "-processor com.android.TestPlugin"},
  260. {library: "bar", processors: "-processor com.android.TestPlugin"},
  261. },
  262. },
  263. {
  264. name: "Exports plugin is not propagated via transitive deps",
  265. extra: `
  266. java_library{name: "exports", exported_plugins: ["plugin"]}
  267. java_library{name: "foo", srcs: ["a.java"], libs: ["exports"]}
  268. java_library{name: "bar", srcs: ["a.java"], static_libs: ["foo"]}
  269. `,
  270. results: []Result{
  271. {library: "foo", processors: "-processor com.android.TestPlugin"},
  272. {library: "bar", processors: "-proc:none"},
  273. },
  274. },
  275. {
  276. name: "Exports plugin appends to plugins",
  277. extra: `
  278. java_plugin{name: "plugin2", processor_class: "com.android.TestPlugin2"}
  279. java_library{name: "exports", exported_plugins: ["plugin"]}
  280. java_library{name: "foo", srcs: ["a.java"], libs: ["exports"], plugins: ["plugin2"]}
  281. `,
  282. results: []Result{
  283. {library: "foo", processors: "-processor com.android.TestPlugin,com.android.TestPlugin2"},
  284. },
  285. },
  286. {
  287. name: "Exports plugin to with generates_api to dependee",
  288. extra: `
  289. java_library{name: "exports", exported_plugins: ["plugin_generates_api"]}
  290. java_library{name: "foo", srcs: ["a.java"], libs: ["exports"]}
  291. java_library{name: "bar", srcs: ["a.java"], static_libs: ["exports"]}
  292. `,
  293. results: []Result{
  294. {library: "foo", processors: "-processor com.android.TestPlugin", disableTurbine: true},
  295. {library: "bar", processors: "-processor com.android.TestPlugin", disableTurbine: true},
  296. },
  297. },
  298. }
  299. for _, test := range tests {
  300. t.Run(test.name, func(t *testing.T) {
  301. ctx, _ := testJava(t, `
  302. java_plugin {
  303. name: "plugin",
  304. processor_class: "com.android.TestPlugin",
  305. }
  306. java_plugin {
  307. name: "plugin_generates_api",
  308. generates_api: true,
  309. processor_class: "com.android.TestPlugin",
  310. }
  311. `+test.extra)
  312. for _, want := range test.results {
  313. javac := ctx.ModuleForTests(want.library, "android_common").Rule("javac")
  314. if javac.Args["processor"] != want.processors {
  315. t.Errorf("For library %v, expected %v, found %v", want.library, want.processors, javac.Args["processor"])
  316. }
  317. turbine := ctx.ModuleForTests(want.library, "android_common").MaybeRule("turbine")
  318. disableTurbine := turbine.BuildParams.Rule == nil
  319. if disableTurbine != want.disableTurbine {
  320. t.Errorf("For library %v, expected disableTurbine %v, found %v", want.library, want.disableTurbine, disableTurbine)
  321. }
  322. }
  323. })
  324. }
  325. }
  326. func TestSdkVersionByPartition(t *testing.T) {
  327. testJavaError(t, "sdk_version must have a value when the module is located at vendor or product", `
  328. java_library {
  329. name: "foo",
  330. srcs: ["a.java"],
  331. vendor: true,
  332. }
  333. `)
  334. testJava(t, `
  335. java_library {
  336. name: "bar",
  337. srcs: ["b.java"],
  338. }
  339. `)
  340. for _, enforce := range []bool{true, false} {
  341. bp := `
  342. java_library {
  343. name: "foo",
  344. srcs: ["a.java"],
  345. product_specific: true,
  346. }
  347. `
  348. errorHandler := android.FixtureExpectsNoErrors
  349. if enforce {
  350. errorHandler = android.FixtureExpectsAtLeastOneErrorMatchingPattern("sdk_version must have a value when the module is located at vendor or product")
  351. }
  352. android.GroupFixturePreparers(
  353. PrepareForTestWithJavaDefaultModules,
  354. android.FixtureModifyProductVariables(func(variables android.FixtureProductVariables) {
  355. variables.EnforceProductPartitionInterface = proptools.BoolPtr(enforce)
  356. }),
  357. ).
  358. ExtendWithErrorHandler(errorHandler).
  359. RunTestWithBp(t, bp)
  360. }
  361. }
  362. func TestArchSpecific(t *testing.T) {
  363. ctx, _ := testJava(t, `
  364. java_library {
  365. name: "foo",
  366. srcs: ["a.java"],
  367. target: {
  368. android: {
  369. srcs: ["b.java"],
  370. },
  371. },
  372. }
  373. `)
  374. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  375. if len(javac.Inputs) != 2 || javac.Inputs[0].String() != "a.java" || javac.Inputs[1].String() != "b.java" {
  376. t.Errorf(`foo inputs %v != ["a.java", "b.java"]`, javac.Inputs)
  377. }
  378. }
  379. func TestBinary(t *testing.T) {
  380. ctx, _ := testJava(t, `
  381. java_library_host {
  382. name: "foo",
  383. srcs: ["a.java"],
  384. }
  385. java_binary_host {
  386. name: "bar",
  387. srcs: ["b.java"],
  388. static_libs: ["foo"],
  389. jni_libs: ["libjni"],
  390. }
  391. cc_library_shared {
  392. name: "libjni",
  393. host_supported: true,
  394. device_supported: false,
  395. stl: "none",
  396. }
  397. `)
  398. buildOS := ctx.Config().BuildOS.String()
  399. bar := ctx.ModuleForTests("bar", buildOS+"_common")
  400. barJar := bar.Output("bar.jar").Output.String()
  401. barWrapper := ctx.ModuleForTests("bar", buildOS+"_x86_64")
  402. barWrapperDeps := barWrapper.Output("bar").Implicits.Strings()
  403. libjni := ctx.ModuleForTests("libjni", buildOS+"_x86_64_shared")
  404. libjniSO := libjni.Rule("Cp").Output.String()
  405. // Test that the install binary wrapper depends on the installed jar file
  406. if g, w := barWrapperDeps, barJar; !android.InList(w, g) {
  407. t.Errorf("expected binary wrapper implicits to contain %q, got %q", w, g)
  408. }
  409. // Test that the install binary wrapper depends on the installed JNI libraries
  410. if g, w := barWrapperDeps, libjniSO; !android.InList(w, g) {
  411. t.Errorf("expected binary wrapper implicits to contain %q, got %q", w, g)
  412. }
  413. }
  414. func TestTest(t *testing.T) {
  415. ctx, _ := testJava(t, `
  416. java_test_host {
  417. name: "foo",
  418. srcs: ["a.java"],
  419. jni_libs: ["libjni"],
  420. }
  421. cc_library_shared {
  422. name: "libjni",
  423. host_supported: true,
  424. device_supported: false,
  425. stl: "none",
  426. }
  427. `)
  428. buildOS := ctx.Config().BuildOS.String()
  429. foo := ctx.ModuleForTests("foo", buildOS+"_common").Module().(*TestHost)
  430. expected := "lib64/libjni.so"
  431. if runtime.GOOS == "darwin" {
  432. expected = "lib64/libjni.dylib"
  433. }
  434. fooTestData := foo.data
  435. if len(fooTestData) != 1 || fooTestData[0].Rel() != expected {
  436. t.Errorf(`expected foo test data relative path [%q], got %q`,
  437. expected, fooTestData.Strings())
  438. }
  439. }
  440. func TestHostBinaryNoJavaDebugInfoOverride(t *testing.T) {
  441. bp := `
  442. java_library {
  443. name: "target_library",
  444. srcs: ["a.java"],
  445. }
  446. java_binary_host {
  447. name: "host_binary",
  448. srcs: ["b.java"],
  449. }
  450. `
  451. result := android.GroupFixturePreparers(
  452. PrepareForTestWithJavaDefaultModules,
  453. android.FixtureModifyProductVariables(func(variables android.FixtureProductVariables) {
  454. variables.MinimizeJavaDebugInfo = proptools.BoolPtr(true)
  455. }),
  456. ).RunTestWithBp(t, bp)
  457. // first, check that the -g flag is added to target modules
  458. targetLibrary := result.ModuleForTests("target_library", "android_common")
  459. targetJavaFlags := targetLibrary.Module().VariablesForTests()["javacFlags"]
  460. if !strings.Contains(targetJavaFlags, "-g:source,lines") {
  461. t.Errorf("target library javac flags %v should contain "+
  462. "-g:source,lines override with MinimizeJavaDebugInfo", targetJavaFlags)
  463. }
  464. // check that -g is not overridden for host modules
  465. buildOS := result.Config.BuildOS.String()
  466. hostBinary := result.ModuleForTests("host_binary", buildOS+"_common")
  467. hostJavaFlags := hostBinary.Module().VariablesForTests()["javacFlags"]
  468. if strings.Contains(hostJavaFlags, "-g:source,lines") {
  469. t.Errorf("java_binary_host javac flags %v should not have "+
  470. "-g:source,lines override with MinimizeJavaDebugInfo", hostJavaFlags)
  471. }
  472. }
  473. func TestPrebuilts(t *testing.T) {
  474. ctx, _ := testJava(t, `
  475. java_library {
  476. name: "foo",
  477. srcs: ["a.java", ":stubs-source"],
  478. libs: ["bar", "sdklib"],
  479. static_libs: ["baz"],
  480. }
  481. java_import {
  482. name: "bar",
  483. jars: ["a.jar"],
  484. }
  485. java_import {
  486. name: "baz",
  487. jars: ["b.jar"],
  488. sdk_version: "current",
  489. compile_dex: true,
  490. }
  491. dex_import {
  492. name: "qux",
  493. jars: ["b.jar"],
  494. }
  495. java_sdk_library_import {
  496. name: "sdklib",
  497. public: {
  498. jars: ["c.jar"],
  499. },
  500. }
  501. prebuilt_stubs_sources {
  502. name: "stubs-source",
  503. srcs: ["stubs/sources"],
  504. }
  505. java_test_import {
  506. name: "test",
  507. jars: ["a.jar"],
  508. test_suites: ["cts"],
  509. test_config: "AndroidTest.xml",
  510. }
  511. `)
  512. fooModule := ctx.ModuleForTests("foo", "android_common")
  513. javac := fooModule.Rule("javac")
  514. combineJar := ctx.ModuleForTests("foo", "android_common").Description("for javac")
  515. barModule := ctx.ModuleForTests("bar", "android_common")
  516. barJar := barModule.Rule("combineJar").Output
  517. bazModule := ctx.ModuleForTests("baz", "android_common")
  518. bazJar := bazModule.Rule("combineJar").Output
  519. sdklibStubsJar := ctx.ModuleForTests("sdklib.stubs", "android_common").Rule("combineJar").Output
  520. fooLibrary := fooModule.Module().(*Library)
  521. assertDeepEquals(t, "foo unique sources incorrect",
  522. []string{"a.java"}, fooLibrary.uniqueSrcFiles.Strings())
  523. assertDeepEquals(t, "foo java source jars incorrect",
  524. []string{".intermediates/stubs-source/android_common/stubs-source-stubs.srcjar"},
  525. android.NormalizePathsForTesting(fooLibrary.compiledSrcJars))
  526. if !strings.Contains(javac.Args["classpath"], barJar.String()) {
  527. t.Errorf("foo classpath %v does not contain %q", javac.Args["classpath"], barJar.String())
  528. }
  529. barDexJar := barModule.Module().(*Import).DexJarBuildPath()
  530. if barDexJar.IsSet() {
  531. t.Errorf("bar dex jar build path expected to be set, got %s", barDexJar)
  532. }
  533. if !strings.Contains(javac.Args["classpath"], sdklibStubsJar.String()) {
  534. t.Errorf("foo classpath %v does not contain %q", javac.Args["classpath"], sdklibStubsJar.String())
  535. }
  536. if len(combineJar.Inputs) != 2 || combineJar.Inputs[1].String() != bazJar.String() {
  537. t.Errorf("foo combineJar inputs %v does not contain %q", combineJar.Inputs, bazJar.String())
  538. }
  539. bazDexJar := bazModule.Module().(*Import).DexJarBuildPath().Path()
  540. expectedDexJar := "out/soong/.intermediates/baz/android_common/dex/baz.jar"
  541. android.AssertPathRelativeToTopEquals(t, "baz dex jar build path", expectedDexJar, bazDexJar)
  542. ctx.ModuleForTests("qux", "android_common").Rule("Cp")
  543. }
  544. func assertDeepEquals(t *testing.T, message string, expected interface{}, actual interface{}) {
  545. if !reflect.DeepEqual(expected, actual) {
  546. t.Errorf("%s: expected %q, found %q", message, expected, actual)
  547. }
  548. }
  549. func TestPrebuiltStubsSources(t *testing.T) {
  550. test := func(t *testing.T, sourcesPath string, expectedInputs []string) {
  551. ctx, _ := testJavaWithFS(t, fmt.Sprintf(`
  552. prebuilt_stubs_sources {
  553. name: "stubs-source",
  554. srcs: ["%s"],
  555. }`, sourcesPath), map[string][]byte{
  556. "stubs/sources/pkg/A.java": nil,
  557. "stubs/sources/pkg/B.java": nil,
  558. })
  559. zipSrc := ctx.ModuleForTests("stubs-source", "android_common").Rule("zip_src")
  560. if expected, actual := expectedInputs, zipSrc.Inputs.Strings(); !reflect.DeepEqual(expected, actual) {
  561. t.Errorf("mismatch of inputs to soong_zip: expected %q, actual %q", expected, actual)
  562. }
  563. }
  564. t.Run("empty/missing directory", func(t *testing.T) {
  565. test(t, "empty-directory", nil)
  566. })
  567. t.Run("non-empty set of sources", func(t *testing.T) {
  568. test(t, "stubs/sources", []string{
  569. "stubs/sources/pkg/A.java",
  570. "stubs/sources/pkg/B.java",
  571. })
  572. })
  573. }
  574. func TestDefaults(t *testing.T) {
  575. ctx, _ := testJava(t, `
  576. java_defaults {
  577. name: "defaults",
  578. srcs: ["a.java"],
  579. libs: ["bar"],
  580. static_libs: ["baz"],
  581. optimize: {enabled: false},
  582. }
  583. java_library {
  584. name: "foo",
  585. defaults: ["defaults"],
  586. }
  587. java_library {
  588. name: "bar",
  589. srcs: ["b.java"],
  590. }
  591. java_library {
  592. name: "baz",
  593. srcs: ["c.java"],
  594. }
  595. android_test {
  596. name: "atestOptimize",
  597. defaults: ["defaults"],
  598. optimize: {enabled: true},
  599. }
  600. android_test {
  601. name: "atestNoOptimize",
  602. defaults: ["defaults"],
  603. }
  604. android_test {
  605. name: "atestDefault",
  606. srcs: ["a.java"],
  607. }
  608. `)
  609. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  610. combineJar := ctx.ModuleForTests("foo", "android_common").Description("for javac")
  611. if len(javac.Inputs) != 1 || javac.Inputs[0].String() != "a.java" {
  612. t.Errorf(`foo inputs %v != ["a.java"]`, javac.Inputs)
  613. }
  614. barTurbine := filepath.Join("out", "soong", ".intermediates", "bar", "android_common", "turbine-combined", "bar.jar")
  615. if !strings.Contains(javac.Args["classpath"], barTurbine) {
  616. t.Errorf("foo classpath %v does not contain %q", javac.Args["classpath"], barTurbine)
  617. }
  618. baz := ctx.ModuleForTests("baz", "android_common").Rule("javac").Output.String()
  619. if len(combineJar.Inputs) != 2 || combineJar.Inputs[1].String() != baz {
  620. t.Errorf("foo combineJar inputs %v does not contain %q", combineJar.Inputs, baz)
  621. }
  622. atestOptimize := ctx.ModuleForTests("atestOptimize", "android_common").MaybeRule("r8")
  623. if atestOptimize.Output == nil {
  624. t.Errorf("atestOptimize should optimize APK")
  625. }
  626. atestNoOptimize := ctx.ModuleForTests("atestNoOptimize", "android_common").MaybeRule("d8")
  627. if atestNoOptimize.Output == nil {
  628. t.Errorf("atestNoOptimize should not optimize APK")
  629. }
  630. atestDefault := ctx.ModuleForTests("atestDefault", "android_common").MaybeRule("d8")
  631. if atestDefault.Output == nil {
  632. t.Errorf("atestDefault should not optimize APK")
  633. }
  634. }
  635. func TestResources(t *testing.T) {
  636. var table = []struct {
  637. name string
  638. prop string
  639. extra string
  640. args string
  641. }{
  642. {
  643. // Test that a module with java_resource_dirs includes the files
  644. name: "resource dirs",
  645. prop: `java_resource_dirs: ["java-res"]`,
  646. args: "-C java-res -f java-res/a/a -f java-res/b/b",
  647. },
  648. {
  649. // Test that a module with java_resources includes the files
  650. name: "resource files",
  651. prop: `java_resources: ["java-res/a/a", "java-res/b/b"]`,
  652. args: "-C . -f java-res/a/a -f java-res/b/b",
  653. },
  654. {
  655. // Test that a module with a filegroup in java_resources includes the files with the
  656. // path prefix
  657. name: "resource filegroup",
  658. prop: `java_resources: [":foo-res"]`,
  659. extra: `
  660. filegroup {
  661. name: "foo-res",
  662. path: "java-res",
  663. srcs: ["java-res/a/a", "java-res/b/b"],
  664. }`,
  665. args: "-C java-res -f java-res/a/a -f java-res/b/b",
  666. },
  667. {
  668. // Test that a module with wildcards in java_resource_dirs has the correct path prefixes
  669. name: "wildcard dirs",
  670. prop: `java_resource_dirs: ["java-res/*"]`,
  671. args: "-C java-res/a -f java-res/a/a -C java-res/b -f java-res/b/b",
  672. },
  673. {
  674. // Test that a module exclude_java_resource_dirs excludes the files
  675. name: "wildcard dirs",
  676. prop: `java_resource_dirs: ["java-res/*"], exclude_java_resource_dirs: ["java-res/b"]`,
  677. args: "-C java-res/a -f java-res/a/a",
  678. },
  679. {
  680. // Test wildcards in java_resources
  681. name: "wildcard files",
  682. prop: `java_resources: ["java-res/**/*"]`,
  683. args: "-C . -f java-res/a/a -f java-res/b/b",
  684. },
  685. {
  686. // Test exclude_java_resources with java_resources
  687. name: "wildcard files with exclude",
  688. prop: `java_resources: ["java-res/**/*"], exclude_java_resources: ["java-res/b/*"]`,
  689. args: "-C . -f java-res/a/a",
  690. },
  691. {
  692. // Test exclude_java_resources with java_resource_dirs
  693. name: "resource dirs with exclude files",
  694. prop: `java_resource_dirs: ["java-res"], exclude_java_resources: ["java-res/b/b"]`,
  695. args: "-C java-res -f java-res/a/a",
  696. },
  697. {
  698. // Test exclude_java_resource_dirs with java_resource_dirs
  699. name: "resource dirs with exclude files",
  700. prop: `java_resource_dirs: ["java-res", "java-res2"], exclude_java_resource_dirs: ["java-res2"]`,
  701. args: "-C java-res -f java-res/a/a -f java-res/b/b",
  702. },
  703. }
  704. for _, test := range table {
  705. t.Run(test.name, func(t *testing.T) {
  706. ctx, _ := testJavaWithFS(t, `
  707. java_library {
  708. name: "foo",
  709. srcs: [
  710. "a.java",
  711. "b.java",
  712. "c.java",
  713. ],
  714. `+test.prop+`,
  715. }
  716. `+test.extra,
  717. map[string][]byte{
  718. "java-res/a/a": nil,
  719. "java-res/b/b": nil,
  720. "java-res2/a": nil,
  721. },
  722. )
  723. foo := ctx.ModuleForTests("foo", "android_common").Output("withres/foo.jar")
  724. fooRes := ctx.ModuleForTests("foo", "android_common").Output("res/foo.jar")
  725. if !inList(fooRes.Output.String(), foo.Inputs.Strings()) {
  726. t.Errorf("foo combined jars %v does not contain %q",
  727. foo.Inputs.Strings(), fooRes.Output.String())
  728. }
  729. if fooRes.Args["jarArgs"] != test.args {
  730. t.Errorf("foo resource jar args %q is not %q",
  731. fooRes.Args["jarArgs"], test.args)
  732. }
  733. })
  734. }
  735. }
  736. func TestIncludeSrcs(t *testing.T) {
  737. ctx, _ := testJavaWithFS(t, `
  738. java_library {
  739. name: "foo",
  740. srcs: [
  741. "a.java",
  742. "b.java",
  743. "c.java",
  744. ],
  745. include_srcs: true,
  746. }
  747. java_library {
  748. name: "bar",
  749. srcs: [
  750. "a.java",
  751. "b.java",
  752. "c.java",
  753. ],
  754. java_resource_dirs: ["java-res"],
  755. include_srcs: true,
  756. }
  757. `, map[string][]byte{
  758. "java-res/a/a": nil,
  759. "java-res/b/b": nil,
  760. "java-res2/a": nil,
  761. })
  762. // Test a library with include_srcs: true
  763. foo := ctx.ModuleForTests("foo", "android_common").Output("withres/foo.jar")
  764. fooSrcJar := ctx.ModuleForTests("foo", "android_common").Output("foo.srcjar")
  765. if g, w := fooSrcJar.Output.String(), foo.Inputs.Strings(); !inList(g, w) {
  766. t.Errorf("foo combined jars %v does not contain %q", w, g)
  767. }
  768. if g, w := fooSrcJar.Args["jarArgs"], "-C . -f a.java -f b.java -f c.java"; g != w {
  769. t.Errorf("foo source jar args %q is not %q", w, g)
  770. }
  771. // Test a library with include_srcs: true and resources
  772. bar := ctx.ModuleForTests("bar", "android_common").Output("withres/bar.jar")
  773. barResCombined := ctx.ModuleForTests("bar", "android_common").Output("res-combined/bar.jar")
  774. barRes := ctx.ModuleForTests("bar", "android_common").Output("res/bar.jar")
  775. barSrcJar := ctx.ModuleForTests("bar", "android_common").Output("bar.srcjar")
  776. if g, w := barSrcJar.Output.String(), barResCombined.Inputs.Strings(); !inList(g, w) {
  777. t.Errorf("bar combined resource jars %v does not contain %q", w, g)
  778. }
  779. if g, w := barRes.Output.String(), barResCombined.Inputs.Strings(); !inList(g, w) {
  780. t.Errorf("bar combined resource jars %v does not contain %q", w, g)
  781. }
  782. if g, w := barResCombined.Output.String(), bar.Inputs.Strings(); !inList(g, w) {
  783. t.Errorf("bar combined jars %v does not contain %q", w, g)
  784. }
  785. if g, w := barSrcJar.Args["jarArgs"], "-C . -f a.java -f b.java -f c.java"; g != w {
  786. t.Errorf("bar source jar args %q is not %q", w, g)
  787. }
  788. if g, w := barRes.Args["jarArgs"], "-C java-res -f java-res/a/a -f java-res/b/b"; g != w {
  789. t.Errorf("bar resource jar args %q is not %q", w, g)
  790. }
  791. }
  792. func TestGeneratedSources(t *testing.T) {
  793. ctx, _ := testJavaWithFS(t, `
  794. java_library {
  795. name: "foo",
  796. srcs: [
  797. "a*.java",
  798. ":gen",
  799. "b*.java",
  800. ],
  801. }
  802. genrule {
  803. name: "gen",
  804. tool_files: ["java-res/a"],
  805. out: ["gen.java"],
  806. }
  807. `, map[string][]byte{
  808. "a.java": nil,
  809. "b.java": nil,
  810. })
  811. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  812. genrule := ctx.ModuleForTests("gen", "").Rule("generator")
  813. if filepath.Base(genrule.Output.String()) != "gen.java" {
  814. t.Fatalf(`gen output file %v is not ".../gen.java"`, genrule.Output.String())
  815. }
  816. if len(javac.Inputs) != 3 ||
  817. javac.Inputs[0].String() != "a.java" ||
  818. javac.Inputs[1].String() != genrule.Output.String() ||
  819. javac.Inputs[2].String() != "b.java" {
  820. t.Errorf(`foo inputs %v != ["a.java", ".../gen.java", "b.java"]`, javac.Inputs)
  821. }
  822. }
  823. func TestTurbine(t *testing.T) {
  824. result := android.GroupFixturePreparers(
  825. prepareForJavaTest, FixtureWithPrebuiltApis(map[string][]string{"14": {"foo"}})).
  826. RunTestWithBp(t, `
  827. java_library {
  828. name: "foo",
  829. srcs: ["a.java"],
  830. sdk_version: "14",
  831. }
  832. java_library {
  833. name: "bar",
  834. srcs: ["b.java"],
  835. static_libs: ["foo"],
  836. sdk_version: "14",
  837. }
  838. java_library {
  839. name: "baz",
  840. srcs: ["c.java"],
  841. libs: ["bar"],
  842. sdk_version: "14",
  843. }
  844. `)
  845. fooTurbine := result.ModuleForTests("foo", "android_common").Rule("turbine")
  846. barTurbine := result.ModuleForTests("bar", "android_common").Rule("turbine")
  847. barJavac := result.ModuleForTests("bar", "android_common").Rule("javac")
  848. barTurbineCombined := result.ModuleForTests("bar", "android_common").Description("for turbine")
  849. bazJavac := result.ModuleForTests("baz", "android_common").Rule("javac")
  850. android.AssertPathsRelativeToTopEquals(t, "foo inputs", []string{"a.java"}, fooTurbine.Inputs)
  851. fooHeaderJar := filepath.Join("out", "soong", ".intermediates", "foo", "android_common", "turbine-combined", "foo.jar")
  852. barTurbineJar := filepath.Join("out", "soong", ".intermediates", "bar", "android_common", "turbine", "bar.jar")
  853. android.AssertStringDoesContain(t, "bar turbine classpath", barTurbine.Args["turbineFlags"], fooHeaderJar)
  854. android.AssertStringDoesContain(t, "bar javac classpath", barJavac.Args["classpath"], fooHeaderJar)
  855. android.AssertPathsRelativeToTopEquals(t, "bar turbine combineJar", []string{barTurbineJar, fooHeaderJar}, barTurbineCombined.Inputs)
  856. android.AssertStringDoesContain(t, "baz javac classpath", bazJavac.Args["classpath"], "prebuilts/sdk/14/public/android.jar")
  857. }
  858. func TestSharding(t *testing.T) {
  859. ctx, _ := testJava(t, `
  860. java_library {
  861. name: "bar",
  862. srcs: ["a.java","b.java","c.java"],
  863. javac_shard_size: 1
  864. }
  865. `)
  866. barHeaderJar := filepath.Join("out", "soong", ".intermediates", "bar", "android_common", "turbine", "bar.jar")
  867. for i := 0; i < 3; i++ {
  868. barJavac := ctx.ModuleForTests("bar", "android_common").Description("javac" + strconv.Itoa(i))
  869. if !strings.HasPrefix(barJavac.Args["classpath"], "-classpath "+barHeaderJar+":") {
  870. t.Errorf("bar javac classpath %v does start with %q", barJavac.Args["classpath"], barHeaderJar)
  871. }
  872. }
  873. }
  874. func TestExcludeFileGroupInSrcs(t *testing.T) {
  875. ctx, _ := testJava(t, `
  876. java_library {
  877. name: "foo",
  878. srcs: ["a.java", ":foo-srcs"],
  879. exclude_srcs: ["a.java", ":foo-excludes"],
  880. }
  881. filegroup {
  882. name: "foo-srcs",
  883. srcs: ["java-fg/a.java", "java-fg/b.java", "java-fg/c.java"],
  884. }
  885. filegroup {
  886. name: "foo-excludes",
  887. srcs: ["java-fg/a.java", "java-fg/b.java"],
  888. }
  889. `)
  890. javac := ctx.ModuleForTests("foo", "android_common").Rule("javac")
  891. if len(javac.Inputs) != 1 || javac.Inputs[0].String() != "java-fg/c.java" {
  892. t.Errorf(`foo inputs %v != ["java-fg/c.java"]`, javac.Inputs)
  893. }
  894. }
  895. func TestJavaLibrary(t *testing.T) {
  896. testJavaWithFS(t, "", map[string][]byte{
  897. "libcore/Android.bp": []byte(`
  898. java_library {
  899. name: "core",
  900. sdk_version: "none",
  901. system_modules: "none",
  902. }
  903. filegroup {
  904. name: "core-jar",
  905. srcs: [":core{.jar}"],
  906. }
  907. `),
  908. })
  909. }
  910. func TestJavaImport(t *testing.T) {
  911. testJavaWithFS(t, "", map[string][]byte{
  912. "libcore/Android.bp": []byte(`
  913. java_import {
  914. name: "core",
  915. sdk_version: "none",
  916. }
  917. filegroup {
  918. name: "core-jar",
  919. srcs: [":core{.jar}"],
  920. }
  921. `),
  922. })
  923. }
  924. var compilerFlagsTestCases = []struct {
  925. in string
  926. out bool
  927. }{
  928. {
  929. in: "a",
  930. out: false,
  931. },
  932. {
  933. in: "-a",
  934. out: true,
  935. },
  936. {
  937. in: "-no-jdk",
  938. out: false,
  939. },
  940. {
  941. in: "-no-stdlib",
  942. out: false,
  943. },
  944. {
  945. in: "-kotlin-home",
  946. out: false,
  947. },
  948. {
  949. in: "-kotlin-home /some/path",
  950. out: false,
  951. },
  952. {
  953. in: "-include-runtime",
  954. out: false,
  955. },
  956. {
  957. in: "-Xintellij-plugin-root",
  958. out: false,
  959. },
  960. }
  961. type mockContext struct {
  962. android.ModuleContext
  963. result bool
  964. }
  965. func (ctx *mockContext) PropertyErrorf(property, format string, args ...interface{}) {
  966. // CheckBadCompilerFlags calls this function when the flag should be rejected
  967. ctx.result = false
  968. }
  969. func TestCompilerFlags(t *testing.T) {
  970. for _, testCase := range compilerFlagsTestCases {
  971. ctx := &mockContext{result: true}
  972. CheckKotlincFlags(ctx, []string{testCase.in})
  973. if ctx.result != testCase.out {
  974. t.Errorf("incorrect output:")
  975. t.Errorf(" input: %#v", testCase.in)
  976. t.Errorf(" expected: %#v", testCase.out)
  977. t.Errorf(" got: %#v", ctx.result)
  978. }
  979. }
  980. }
  981. // TODO(jungjw): Consider making this more robust by ignoring path order.
  982. func checkPatchModuleFlag(t *testing.T, ctx *android.TestContext, moduleName string, expected string) {
  983. variables := ctx.ModuleForTests(moduleName, "android_common").VariablesForTestsRelativeToTop()
  984. flags := strings.Split(variables["javacFlags"], " ")
  985. got := ""
  986. for _, flag := range flags {
  987. keyEnd := strings.Index(flag, "=")
  988. if keyEnd > -1 && flag[:keyEnd] == "--patch-module" {
  989. got = flag[keyEnd+1:]
  990. break
  991. }
  992. }
  993. if expected != android.StringPathRelativeToTop(ctx.Config().SoongOutDir(), got) {
  994. t.Errorf("Unexpected patch-module flag for module %q - expected %q, but got %q", moduleName, expected, got)
  995. }
  996. }
  997. func TestPatchModule(t *testing.T) {
  998. t.Run("Java language level 8", func(t *testing.T) {
  999. // Test with legacy javac -source 1.8 -target 1.8
  1000. bp := `
  1001. java_library {
  1002. name: "foo",
  1003. srcs: ["a.java"],
  1004. java_version: "1.8",
  1005. }
  1006. java_library {
  1007. name: "bar",
  1008. srcs: ["b.java"],
  1009. sdk_version: "none",
  1010. system_modules: "none",
  1011. patch_module: "java.base",
  1012. java_version: "1.8",
  1013. }
  1014. java_library {
  1015. name: "baz",
  1016. srcs: ["c.java"],
  1017. patch_module: "java.base",
  1018. java_version: "1.8",
  1019. }
  1020. `
  1021. ctx, _ := testJava(t, bp)
  1022. checkPatchModuleFlag(t, ctx, "foo", "")
  1023. checkPatchModuleFlag(t, ctx, "bar", "")
  1024. checkPatchModuleFlag(t, ctx, "baz", "")
  1025. })
  1026. t.Run("Java language level 9", func(t *testing.T) {
  1027. // Test with default javac -source 9 -target 9
  1028. bp := `
  1029. java_library {
  1030. name: "foo",
  1031. srcs: ["a.java"],
  1032. }
  1033. java_library {
  1034. name: "bar",
  1035. srcs: ["b.java"],
  1036. sdk_version: "none",
  1037. system_modules: "none",
  1038. patch_module: "java.base",
  1039. }
  1040. java_library {
  1041. name: "baz",
  1042. srcs: [
  1043. "c.java",
  1044. // Tests for b/150878007
  1045. "dir/d.java",
  1046. "dir2/e.java",
  1047. "dir2/f.java",
  1048. "nested/dir/g.java"
  1049. ],
  1050. patch_module: "java.base",
  1051. }
  1052. `
  1053. ctx, _ := testJava(t, bp)
  1054. checkPatchModuleFlag(t, ctx, "foo", "")
  1055. expected := "java.base=.:out/soong"
  1056. checkPatchModuleFlag(t, ctx, "bar", expected)
  1057. expected = "java.base=" + strings.Join([]string{
  1058. ".", "out/soong", "dir", "dir2", "nested", defaultModuleToPath("ext"), defaultModuleToPath("framework")}, ":")
  1059. checkPatchModuleFlag(t, ctx, "baz", expected)
  1060. })
  1061. }
  1062. func TestJavaLibraryWithSystemModules(t *testing.T) {
  1063. ctx, _ := testJava(t, `
  1064. java_library {
  1065. name: "lib-with-source-system-modules",
  1066. srcs: [
  1067. "a.java",
  1068. ],
  1069. sdk_version: "none",
  1070. system_modules: "source-system-modules",
  1071. }
  1072. java_library {
  1073. name: "source-jar",
  1074. srcs: [
  1075. "a.java",
  1076. ],
  1077. }
  1078. java_system_modules {
  1079. name: "source-system-modules",
  1080. libs: ["source-jar"],
  1081. }
  1082. java_library {
  1083. name: "lib-with-prebuilt-system-modules",
  1084. srcs: [
  1085. "a.java",
  1086. ],
  1087. sdk_version: "none",
  1088. system_modules: "prebuilt-system-modules",
  1089. }
  1090. java_import {
  1091. name: "prebuilt-jar",
  1092. jars: ["a.jar"],
  1093. }
  1094. java_system_modules_import {
  1095. name: "prebuilt-system-modules",
  1096. libs: ["prebuilt-jar"],
  1097. }
  1098. `)
  1099. checkBootClasspathForSystemModule(t, ctx, "lib-with-source-system-modules", "/source-jar.jar")
  1100. checkBootClasspathForSystemModule(t, ctx, "lib-with-prebuilt-system-modules", "/prebuilt-jar.jar")
  1101. }
  1102. func checkBootClasspathForSystemModule(t *testing.T, ctx *android.TestContext, moduleName string, expectedSuffix string) {
  1103. javacRule := ctx.ModuleForTests(moduleName, "android_common").Rule("javac")
  1104. bootClasspath := javacRule.Args["bootClasspath"]
  1105. if strings.HasPrefix(bootClasspath, "--system ") && strings.HasSuffix(bootClasspath, expectedSuffix) {
  1106. t.Errorf("bootclasspath of %q must start with --system and end with %q, but was %#v.", moduleName, expectedSuffix, bootClasspath)
  1107. }
  1108. }
  1109. func TestAidlExportIncludeDirsFromImports(t *testing.T) {
  1110. ctx, _ := testJava(t, `
  1111. java_library {
  1112. name: "foo",
  1113. srcs: ["aidl/foo/IFoo.aidl"],
  1114. libs: ["bar"],
  1115. }
  1116. java_import {
  1117. name: "bar",
  1118. jars: ["a.jar"],
  1119. aidl: {
  1120. export_include_dirs: ["aidl/bar"],
  1121. },
  1122. }
  1123. `)
  1124. aidlCommand := ctx.ModuleForTests("foo", "android_common").Rule("aidl").RuleParams.Command
  1125. expectedAidlFlag := "-Iaidl/bar"
  1126. if !strings.Contains(aidlCommand, expectedAidlFlag) {
  1127. t.Errorf("aidl command %q does not contain %q", aidlCommand, expectedAidlFlag)
  1128. }
  1129. }
  1130. func TestAidlIncludeDirFromConvertedFileGroupWithPathPropInMixedBuilds(t *testing.T) {
  1131. // TODO(b/247782695), TODO(b/242847534) Fix mixed builds for filegroups
  1132. t.Skip("Re-enable once filegroups are corrected for mixed builds")
  1133. bp := `
  1134. filegroup {
  1135. name: "foo_aidl",
  1136. srcs: ["aidl/foo/IFoo.aidl"],
  1137. path: "aidl/foo",
  1138. bazel_module: { label: "//:foo_aidl" },
  1139. }
  1140. java_library {
  1141. name: "foo",
  1142. srcs: [":foo_aidl"],
  1143. }
  1144. `
  1145. outBaseDir := "out/bazel/output"
  1146. result := android.GroupFixturePreparers(
  1147. prepareForJavaTest,
  1148. android.PrepareForTestWithFilegroup,
  1149. android.FixtureModifyConfig(func(config android.Config) {
  1150. config.BazelContext = android.MockBazelContext{
  1151. OutputBaseDir: outBaseDir,
  1152. LabelToOutputFiles: map[string][]string{
  1153. "//:foo_aidl": []string{"aidl/foo/IFoo.aidl"},
  1154. },
  1155. }
  1156. }),
  1157. ).RunTestWithBp(t, bp)
  1158. aidlCommand := result.ModuleForTests("foo", "android_common").Rule("aidl").RuleParams.Command
  1159. expectedAidlFlag := "-I" + outBaseDir + "/execroot/__main__/aidl/foo"
  1160. if !strings.Contains(aidlCommand, expectedAidlFlag) {
  1161. t.Errorf("aidl command %q does not contain %q", aidlCommand, expectedAidlFlag)
  1162. }
  1163. }
  1164. func TestAidlFlagsArePassedToTheAidlCompiler(t *testing.T) {
  1165. ctx, _ := testJava(t, `
  1166. java_library {
  1167. name: "foo",
  1168. srcs: ["aidl/foo/IFoo.aidl"],
  1169. aidl: { flags: ["-Werror"], },
  1170. }
  1171. `)
  1172. aidlCommand := ctx.ModuleForTests("foo", "android_common").Rule("aidl").RuleParams.Command
  1173. expectedAidlFlag := "-Werror"
  1174. if !strings.Contains(aidlCommand, expectedAidlFlag) {
  1175. t.Errorf("aidl command %q does not contain %q", aidlCommand, expectedAidlFlag)
  1176. }
  1177. }
  1178. func TestAidlFlagsWithMinSdkVersion(t *testing.T) {
  1179. fixture := android.GroupFixturePreparers(
  1180. prepareForJavaTest, FixtureWithPrebuiltApis(map[string][]string{"14": {"foo"}}))
  1181. for _, tc := range []struct {
  1182. name string
  1183. sdkVersion string
  1184. expected string
  1185. }{
  1186. {"default is current", "", "current"},
  1187. {"use sdk_version", `sdk_version: "14"`, "14"},
  1188. {"system_current", `sdk_version: "system_current"`, "current"},
  1189. } {
  1190. t.Run(tc.name, func(t *testing.T) {
  1191. ctx := fixture.RunTestWithBp(t, `
  1192. java_library {
  1193. name: "foo",
  1194. srcs: ["aidl/foo/IFoo.aidl"],
  1195. `+tc.sdkVersion+`
  1196. }
  1197. `)
  1198. aidlCommand := ctx.ModuleForTests("foo", "android_common").Rule("aidl").RuleParams.Command
  1199. expectedAidlFlag := "--min_sdk_version=" + tc.expected
  1200. if !strings.Contains(aidlCommand, expectedAidlFlag) {
  1201. t.Errorf("aidl command %q does not contain %q", aidlCommand, expectedAidlFlag)
  1202. }
  1203. })
  1204. }
  1205. }
  1206. func TestAidlFlagsMinSdkVersionDroidstubs(t *testing.T) {
  1207. bpTemplate := `
  1208. droidstubs {
  1209. name: "foo-stubs",
  1210. srcs: ["foo.aidl"],
  1211. %s
  1212. system_modules: "none",
  1213. }
  1214. `
  1215. testCases := []struct {
  1216. desc string
  1217. sdkVersionBp string
  1218. minSdkVersionExpected string
  1219. }{
  1220. {
  1221. desc: "sdk_version not set, module compiles against private platform APIs",
  1222. sdkVersionBp: ``,
  1223. minSdkVersionExpected: "10000",
  1224. },
  1225. {
  1226. desc: "sdk_version set to none, module does not build against an SDK",
  1227. sdkVersionBp: `sdk_version: "none",`,
  1228. minSdkVersionExpected: "10000",
  1229. },
  1230. }
  1231. for _, tc := range testCases {
  1232. ctx := prepareForJavaTest.RunTestWithBp(t, fmt.Sprintf(bpTemplate, tc.sdkVersionBp))
  1233. aidlCmd := ctx.ModuleForTests("foo-stubs", "android_common").Rule("aidl").RuleParams.Command
  1234. expected := "--min_sdk_version=" + tc.minSdkVersionExpected
  1235. android.AssertStringDoesContain(t, "aidl command conatins incorrect min_sdk_version for testCse: "+tc.desc, aidlCmd, expected)
  1236. }
  1237. }
  1238. func TestAidlEnforcePermissions(t *testing.T) {
  1239. ctx, _ := testJava(t, `
  1240. java_library {
  1241. name: "foo",
  1242. srcs: ["aidl/foo/IFoo.aidl"],
  1243. aidl: { enforce_permissions: true },
  1244. }
  1245. `)
  1246. aidlCommand := ctx.ModuleForTests("foo", "android_common").Rule("aidl").RuleParams.Command
  1247. expectedAidlFlag := "-Wmissing-permission-annotation -Werror"
  1248. if !strings.Contains(aidlCommand, expectedAidlFlag) {
  1249. t.Errorf("aidl command %q does not contain %q", aidlCommand, expectedAidlFlag)
  1250. }
  1251. }
  1252. func TestAidlEnforcePermissionsException(t *testing.T) {
  1253. ctx, _ := testJava(t, `
  1254. java_library {
  1255. name: "foo",
  1256. srcs: ["aidl/foo/IFoo.aidl", "aidl/foo/IFoo2.aidl"],
  1257. aidl: { enforce_permissions: true, enforce_permissions_exceptions: ["aidl/foo/IFoo2.aidl"] },
  1258. }
  1259. `)
  1260. aidlCommand := ctx.ModuleForTests("foo", "android_common").Rule("aidl").RuleParams.Command
  1261. expectedAidlFlag := "$$FLAGS -Wmissing-permission-annotation -Werror aidl/foo/IFoo.aidl"
  1262. if !strings.Contains(aidlCommand, expectedAidlFlag) {
  1263. t.Errorf("aidl command %q does not contain %q", aidlCommand, expectedAidlFlag)
  1264. }
  1265. expectedAidlFlag = "$$FLAGS aidl/foo/IFoo2.aidl"
  1266. if !strings.Contains(aidlCommand, expectedAidlFlag) {
  1267. t.Errorf("aidl command %q does not contain %q", aidlCommand, expectedAidlFlag)
  1268. }
  1269. }
  1270. func TestDataNativeBinaries(t *testing.T) {
  1271. ctx, _ := testJava(t, `
  1272. java_test_host {
  1273. name: "foo",
  1274. srcs: ["a.java"],
  1275. data_native_bins: ["bin"]
  1276. }
  1277. python_binary_host {
  1278. name: "bin",
  1279. srcs: ["bin.py"],
  1280. }
  1281. `)
  1282. buildOS := ctx.Config().BuildOS.String()
  1283. test := ctx.ModuleForTests("foo", buildOS+"_common").Module().(*TestHost)
  1284. entries := android.AndroidMkEntriesForTest(t, ctx, test)[0]
  1285. expected := []string{"out/soong/.intermediates/bin/" + buildOS + "_x86_64_PY3/bin:bin"}
  1286. actual := entries.EntryMap["LOCAL_COMPATIBILITY_SUPPORT_FILES"]
  1287. android.AssertStringPathsRelativeToTopEquals(t, "LOCAL_COMPATIBILITY_SUPPORT_FILES", ctx.Config(), expected, actual)
  1288. }
  1289. func TestDefaultInstallable(t *testing.T) {
  1290. ctx, _ := testJava(t, `
  1291. java_test_host {
  1292. name: "foo"
  1293. }
  1294. `)
  1295. buildOS := ctx.Config().BuildOS.String()
  1296. module := ctx.ModuleForTests("foo", buildOS+"_common").Module().(*TestHost)
  1297. assertDeepEquals(t, "Default installable value should be true.", proptools.BoolPtr(true),
  1298. module.properties.Installable)
  1299. }
  1300. func TestErrorproneEnabled(t *testing.T) {
  1301. ctx, _ := testJava(t, `
  1302. java_library {
  1303. name: "foo",
  1304. srcs: ["a.java"],
  1305. errorprone: {
  1306. enabled: true,
  1307. },
  1308. }
  1309. `)
  1310. javac := ctx.ModuleForTests("foo", "android_common").Description("javac")
  1311. // Test that the errorprone plugins are passed to javac
  1312. expectedSubstring := "-Xplugin:ErrorProne"
  1313. if !strings.Contains(javac.Args["javacFlags"], expectedSubstring) {
  1314. t.Errorf("expected javacFlags to contain %q, got %q", expectedSubstring, javac.Args["javacFlags"])
  1315. }
  1316. // Modules with errorprone { enabled: true } will include errorprone checks
  1317. // in the main javac build rule. Only when RUN_ERROR_PRONE is true will
  1318. // the explicit errorprone build rule be created.
  1319. errorprone := ctx.ModuleForTests("foo", "android_common").MaybeDescription("errorprone")
  1320. if errorprone.RuleParams.Description != "" {
  1321. t.Errorf("expected errorprone build rule to not exist, but it did")
  1322. }
  1323. }
  1324. func TestErrorproneDisabled(t *testing.T) {
  1325. bp := `
  1326. java_library {
  1327. name: "foo",
  1328. srcs: ["a.java"],
  1329. errorprone: {
  1330. enabled: false,
  1331. },
  1332. }
  1333. `
  1334. ctx := android.GroupFixturePreparers(
  1335. PrepareForTestWithJavaDefaultModules,
  1336. android.FixtureMergeEnv(map[string]string{
  1337. "RUN_ERROR_PRONE": "true",
  1338. }),
  1339. ).RunTestWithBp(t, bp)
  1340. javac := ctx.ModuleForTests("foo", "android_common").Description("javac")
  1341. // Test that the errorprone plugins are not passed to javac, like they would
  1342. // be if enabled was true.
  1343. expectedSubstring := "-Xplugin:ErrorProne"
  1344. if strings.Contains(javac.Args["javacFlags"], expectedSubstring) {
  1345. t.Errorf("expected javacFlags to not contain %q, got %q", expectedSubstring, javac.Args["javacFlags"])
  1346. }
  1347. // Check that no errorprone build rule is created, like there would be
  1348. // if enabled was unset and RUN_ERROR_PRONE was true.
  1349. errorprone := ctx.ModuleForTests("foo", "android_common").MaybeDescription("errorprone")
  1350. if errorprone.RuleParams.Description != "" {
  1351. t.Errorf("expected errorprone build rule to not exist, but it did")
  1352. }
  1353. }
  1354. func TestErrorproneEnabledOnlyByEnvironmentVariable(t *testing.T) {
  1355. bp := `
  1356. java_library {
  1357. name: "foo",
  1358. srcs: ["a.java"],
  1359. }
  1360. `
  1361. ctx := android.GroupFixturePreparers(
  1362. PrepareForTestWithJavaDefaultModules,
  1363. android.FixtureMergeEnv(map[string]string{
  1364. "RUN_ERROR_PRONE": "true",
  1365. }),
  1366. ).RunTestWithBp(t, bp)
  1367. javac := ctx.ModuleForTests("foo", "android_common").Description("javac")
  1368. errorprone := ctx.ModuleForTests("foo", "android_common").Description("errorprone")
  1369. // Check that the errorprone plugins are not passed to javac, because they
  1370. // will instead be passed to the separate errorprone compilation
  1371. expectedSubstring := "-Xplugin:ErrorProne"
  1372. if strings.Contains(javac.Args["javacFlags"], expectedSubstring) {
  1373. t.Errorf("expected javacFlags to not contain %q, got %q", expectedSubstring, javac.Args["javacFlags"])
  1374. }
  1375. // Check that the errorprone plugin is enabled
  1376. if !strings.Contains(errorprone.Args["javacFlags"], expectedSubstring) {
  1377. t.Errorf("expected errorprone to contain %q, got %q", expectedSubstring, javac.Args["javacFlags"])
  1378. }
  1379. }
  1380. func TestDataDeviceBinsBuildsDeviceBinary(t *testing.T) {
  1381. testCases := []struct {
  1382. dataDeviceBinType string
  1383. depCompileMultilib string
  1384. variants []string
  1385. expectedError string
  1386. }{
  1387. {
  1388. dataDeviceBinType: "first",
  1389. depCompileMultilib: "first",
  1390. variants: []string{"android_arm64_armv8-a"},
  1391. },
  1392. {
  1393. dataDeviceBinType: "first",
  1394. depCompileMultilib: "both",
  1395. variants: []string{"android_arm64_armv8-a"},
  1396. },
  1397. {
  1398. // this is true because our testing framework is set up with
  1399. // Targets ~ [<64bit target>, <32bit target>], where 64bit is "first"
  1400. dataDeviceBinType: "first",
  1401. depCompileMultilib: "32",
  1402. expectedError: `Android.bp:2:3: dependency "bar" of "foo" missing variant`,
  1403. },
  1404. {
  1405. dataDeviceBinType: "first",
  1406. depCompileMultilib: "64",
  1407. variants: []string{"android_arm64_armv8-a"},
  1408. },
  1409. {
  1410. dataDeviceBinType: "both",
  1411. depCompileMultilib: "both",
  1412. variants: []string{
  1413. "android_arm_armv7-a-neon",
  1414. "android_arm64_armv8-a",
  1415. },
  1416. },
  1417. {
  1418. dataDeviceBinType: "both",
  1419. depCompileMultilib: "32",
  1420. expectedError: `Android.bp:2:3: dependency "bar" of "foo" missing variant`,
  1421. },
  1422. {
  1423. dataDeviceBinType: "both",
  1424. depCompileMultilib: "64",
  1425. expectedError: `Android.bp:2:3: dependency "bar" of "foo" missing variant`,
  1426. },
  1427. {
  1428. dataDeviceBinType: "both",
  1429. depCompileMultilib: "first",
  1430. expectedError: `Android.bp:2:3: dependency "bar" of "foo" missing variant`,
  1431. },
  1432. {
  1433. dataDeviceBinType: "32",
  1434. depCompileMultilib: "32",
  1435. variants: []string{"android_arm_armv7-a-neon"},
  1436. },
  1437. {
  1438. dataDeviceBinType: "32",
  1439. depCompileMultilib: "first",
  1440. expectedError: `Android.bp:2:3: dependency "bar" of "foo" missing variant`,
  1441. },
  1442. {
  1443. dataDeviceBinType: "32",
  1444. depCompileMultilib: "both",
  1445. variants: []string{"android_arm_armv7-a-neon"},
  1446. },
  1447. {
  1448. dataDeviceBinType: "32",
  1449. depCompileMultilib: "64",
  1450. expectedError: `Android.bp:2:3: dependency "bar" of "foo" missing variant`,
  1451. },
  1452. {
  1453. dataDeviceBinType: "64",
  1454. depCompileMultilib: "64",
  1455. variants: []string{"android_arm64_armv8-a"},
  1456. },
  1457. {
  1458. dataDeviceBinType: "64",
  1459. depCompileMultilib: "both",
  1460. variants: []string{"android_arm64_armv8-a"},
  1461. },
  1462. {
  1463. dataDeviceBinType: "64",
  1464. depCompileMultilib: "first",
  1465. variants: []string{"android_arm64_armv8-a"},
  1466. },
  1467. {
  1468. dataDeviceBinType: "64",
  1469. depCompileMultilib: "32",
  1470. expectedError: `Android.bp:2:3: dependency "bar" of "foo" missing variant`,
  1471. },
  1472. {
  1473. dataDeviceBinType: "prefer32",
  1474. depCompileMultilib: "32",
  1475. variants: []string{"android_arm_armv7-a-neon"},
  1476. },
  1477. {
  1478. dataDeviceBinType: "prefer32",
  1479. depCompileMultilib: "both",
  1480. variants: []string{"android_arm_armv7-a-neon"},
  1481. },
  1482. {
  1483. dataDeviceBinType: "prefer32",
  1484. depCompileMultilib: "first",
  1485. expectedError: `Android.bp:2:3: dependency "bar" of "foo" missing variant`,
  1486. },
  1487. {
  1488. dataDeviceBinType: "prefer32",
  1489. depCompileMultilib: "64",
  1490. expectedError: `Android.bp:2:3: dependency "bar" of "foo" missing variant`,
  1491. },
  1492. }
  1493. bpTemplate := `
  1494. java_test_host {
  1495. name: "foo",
  1496. srcs: ["test.java"],
  1497. data_device_bins_%s: ["bar"],
  1498. }
  1499. cc_binary {
  1500. name: "bar",
  1501. compile_multilib: "%s",
  1502. }
  1503. `
  1504. for _, tc := range testCases {
  1505. bp := fmt.Sprintf(bpTemplate, tc.dataDeviceBinType, tc.depCompileMultilib)
  1506. errorHandler := android.FixtureExpectsNoErrors
  1507. if tc.expectedError != "" {
  1508. errorHandler = android.FixtureExpectsAtLeastOneErrorMatchingPattern(tc.expectedError)
  1509. }
  1510. testName := fmt.Sprintf(`data_device_bins_%s with compile_multilib:"%s"`, tc.dataDeviceBinType, tc.depCompileMultilib)
  1511. t.Run(testName, func(t *testing.T) {
  1512. ctx := android.GroupFixturePreparers(PrepareForIntegrationTestWithJava).
  1513. ExtendWithErrorHandler(errorHandler).
  1514. RunTestWithBp(t, bp)
  1515. if tc.expectedError != "" {
  1516. return
  1517. }
  1518. buildOS := ctx.Config.BuildOS.String()
  1519. fooVariant := ctx.ModuleForTests("foo", buildOS+"_common")
  1520. fooMod := fooVariant.Module().(*TestHost)
  1521. entries := android.AndroidMkEntriesForTest(t, ctx.TestContext, fooMod)[0]
  1522. expectedAutogenConfig := `<option name="push-file" key="bar" value="/data/local/tests/unrestricted/foo/bar" />`
  1523. autogen := fooVariant.Rule("autogen")
  1524. if !strings.Contains(autogen.Args["extraConfigs"], expectedAutogenConfig) {
  1525. t.Errorf("foo extraConfigs %v does not contain %q", autogen.Args["extraConfigs"], expectedAutogenConfig)
  1526. }
  1527. expectedData := []string{}
  1528. for _, variant := range tc.variants {
  1529. barVariant := ctx.ModuleForTests("bar", variant)
  1530. relocated := barVariant.Output("bar")
  1531. expectedInput := fmt.Sprintf("out/soong/.intermediates/bar/%s/unstripped/bar", variant)
  1532. android.AssertPathRelativeToTopEquals(t, "relocation input", expectedInput, relocated.Input)
  1533. expectedData = append(expectedData, fmt.Sprintf("out/soong/.intermediates/bar/%s/bar:bar", variant))
  1534. }
  1535. actualData := entries.EntryMap["LOCAL_COMPATIBILITY_SUPPORT_FILES"]
  1536. android.AssertStringPathsRelativeToTopEquals(t, "LOCAL_TEST_DATA", ctx.Config, expectedData, actualData)
  1537. })
  1538. }
  1539. }
  1540. func TestImportMixedBuild(t *testing.T) {
  1541. bp := `
  1542. java_import {
  1543. name: "baz",
  1544. jars: [
  1545. "test1.jar",
  1546. "test2.jar",
  1547. ],
  1548. bazel_module: { label: "//foo/bar:baz" },
  1549. }
  1550. `
  1551. ctx := android.GroupFixturePreparers(
  1552. prepareForJavaTest,
  1553. android.FixtureModifyConfig(func(config android.Config) {
  1554. config.BazelContext = android.MockBazelContext{
  1555. OutputBaseDir: "outputbase",
  1556. LabelToOutputFiles: map[string][]string{
  1557. "//foo/bar:baz": []string{"test1.jar", "test2.jar"},
  1558. },
  1559. }
  1560. }),
  1561. ).RunTestWithBp(t, bp)
  1562. bazMod := ctx.ModuleForTests("baz", "android_common").Module()
  1563. producer := bazMod.(android.OutputFileProducer)
  1564. expectedOutputFiles := []string{".intermediates/baz/android_common/bazelCombined/baz.jar"}
  1565. outputFiles, err := producer.OutputFiles("")
  1566. if err != nil {
  1567. t.Errorf("Unexpected error getting java_import outputfiles %s", err)
  1568. }
  1569. actualOutputFiles := android.NormalizePathsForTesting(outputFiles)
  1570. android.AssertDeepEquals(t, "Output files are produced", expectedOutputFiles, actualOutputFiles)
  1571. javaInfoProvider := ctx.ModuleProvider(bazMod, JavaInfoProvider)
  1572. javaInfo, ok := javaInfoProvider.(JavaInfo)
  1573. if !ok {
  1574. t.Error("could not get JavaInfo from java_import module")
  1575. }
  1576. android.AssertDeepEquals(t, "Header JARs are produced", expectedOutputFiles, android.NormalizePathsForTesting(javaInfo.HeaderJars))
  1577. android.AssertDeepEquals(t, "Implementation/Resources JARs are produced", expectedOutputFiles, android.NormalizePathsForTesting(javaInfo.ImplementationAndResourcesJars))
  1578. android.AssertDeepEquals(t, "Implementation JARs are produced", expectedOutputFiles, android.NormalizePathsForTesting(javaInfo.ImplementationJars))
  1579. }
  1580. func TestGenAidlIncludeFlagsForMixedBuilds(t *testing.T) {
  1581. bazelOutputBaseDir := filepath.Join("out", "bazel")
  1582. result := android.GroupFixturePreparers(
  1583. PrepareForIntegrationTestWithJava,
  1584. android.FixtureModifyConfig(func(config android.Config) {
  1585. config.BazelContext = android.MockBazelContext{
  1586. OutputBaseDir: bazelOutputBaseDir,
  1587. }
  1588. }),
  1589. ).RunTest(t)
  1590. ctx := &android.TestPathContext{TestResult: result}
  1591. srcDirectory := filepath.Join("frameworks", "base")
  1592. srcDirectoryAlreadyIncluded := filepath.Join("frameworks", "base", "core", "java")
  1593. bazelSrcDirectory := android.PathForBazelOut(ctx, srcDirectory)
  1594. bazelSrcDirectoryAlreadyIncluded := android.PathForBazelOut(ctx, srcDirectoryAlreadyIncluded)
  1595. srcs := android.Paths{
  1596. android.PathForTestingWithRel(bazelSrcDirectory.String(), "bazelAidl.aidl"),
  1597. android.PathForTestingWithRel(bazelSrcDirectory.String(), "bazelAidl2.aidl"),
  1598. android.PathForTestingWithRel(bazelSrcDirectoryAlreadyIncluded.String(), "bazelAidlExclude.aidl"),
  1599. android.PathForTestingWithRel(bazelSrcDirectoryAlreadyIncluded.String(), "bazelAidl2Exclude.aidl"),
  1600. }
  1601. dirsAlreadyIncluded := android.Paths{
  1602. android.PathForTesting(srcDirectoryAlreadyIncluded),
  1603. }
  1604. expectedFlags := " -Iout/bazel/execroot/__main__/frameworks/base"
  1605. flags := genAidlIncludeFlags(ctx, srcs, dirsAlreadyIncluded)
  1606. if flags != expectedFlags {
  1607. t.Errorf("expected flags to be %q; was %q", expectedFlags, flags)
  1608. }
  1609. }
  1610. func TestDeviceBinaryWrapperGeneration(t *testing.T) {
  1611. // Scenario 1: java_binary has main_class property in its bp
  1612. ctx, _ := testJava(t, `
  1613. java_binary {
  1614. name: "foo",
  1615. srcs: ["foo.java"],
  1616. main_class: "foo.bar.jb",
  1617. }
  1618. `)
  1619. wrapperPath := fmt.Sprint(ctx.ModuleForTests("foo", "android_arm64_armv8-a").AllOutputs())
  1620. if !strings.Contains(wrapperPath, "foo.sh") {
  1621. t.Errorf("wrapper file foo.sh is not generated")
  1622. }
  1623. // Scenario 2: java_binary has neither wrapper nor main_class, its build
  1624. // is expected to be failed.
  1625. testJavaError(t, "main_class property is required for device binary if no default wrapper is assigned", `
  1626. java_binary {
  1627. name: "foo",
  1628. srcs: ["foo.java"],
  1629. }`)
  1630. }
  1631. func TestJavaApiLibraryAndProviderLink(t *testing.T) {
  1632. provider_bp_a := `
  1633. java_api_contribution {
  1634. name: "foo1",
  1635. api_file: "foo1.txt",
  1636. }
  1637. `
  1638. provider_bp_b := `java_api_contribution {
  1639. name: "foo2",
  1640. api_file: "foo2.txt",
  1641. }
  1642. `
  1643. ctx, _ := testJavaWithFS(t, `
  1644. java_api_library {
  1645. name: "bar1",
  1646. api_surface: "public",
  1647. api_contributions: ["foo1"],
  1648. }
  1649. java_api_library {
  1650. name: "bar2",
  1651. api_surface: "system",
  1652. api_contributions: ["foo1", "foo2"],
  1653. api_files: ["api1/current.txt", "api2/current.txt"]
  1654. }
  1655. `,
  1656. map[string][]byte{
  1657. "a/Android.bp": []byte(provider_bp_a),
  1658. "b/Android.bp": []byte(provider_bp_b),
  1659. })
  1660. testcases := []struct {
  1661. moduleName string
  1662. sourceTextFileDirs []string
  1663. }{
  1664. {
  1665. moduleName: "bar1",
  1666. sourceTextFileDirs: []string{"a/foo1.txt"},
  1667. },
  1668. {
  1669. moduleName: "bar2",
  1670. sourceTextFileDirs: []string{"a/foo1.txt", "b/foo2.txt", "api1/current.txt", "api2/current.txt"},
  1671. },
  1672. }
  1673. for _, c := range testcases {
  1674. m := ctx.ModuleForTests(c.moduleName, "android_common")
  1675. manifest := m.Output("metalava.sbox.textproto")
  1676. sboxProto := android.RuleBuilderSboxProtoForTests(t, manifest)
  1677. manifestCommand := sboxProto.Commands[0].GetCommand()
  1678. sourceFilesFlag := "--source-files " + strings.Join(c.sourceTextFileDirs, " ")
  1679. android.AssertStringDoesContain(t, "source text files not present", manifestCommand, sourceFilesFlag)
  1680. }
  1681. }
  1682. func TestJavaApiLibraryJarGeneration(t *testing.T) {
  1683. provider_bp_a := `
  1684. java_api_contribution {
  1685. name: "foo1",
  1686. api_file: "foo1.txt",
  1687. }
  1688. `
  1689. provider_bp_b := `java_api_contribution {
  1690. name: "foo2",
  1691. api_file: "foo2.txt",
  1692. }
  1693. `
  1694. ctx, _ := testJavaWithFS(t, `
  1695. java_api_library {
  1696. name: "bar1",
  1697. api_surface: "public",
  1698. api_contributions: ["foo1"],
  1699. }
  1700. java_api_library {
  1701. name: "bar2",
  1702. api_surface: "system",
  1703. api_contributions: ["foo1", "foo2"],
  1704. }
  1705. `,
  1706. map[string][]byte{
  1707. "a/Android.bp": []byte(provider_bp_a),
  1708. "b/Android.bp": []byte(provider_bp_b),
  1709. })
  1710. testcases := []struct {
  1711. moduleName string
  1712. outputJarName string
  1713. }{
  1714. {
  1715. moduleName: "bar1",
  1716. outputJarName: "bar1/android.jar",
  1717. },
  1718. {
  1719. moduleName: "bar2",
  1720. outputJarName: "bar2/android.jar",
  1721. },
  1722. }
  1723. for _, c := range testcases {
  1724. m := ctx.ModuleForTests(c.moduleName, "android_common")
  1725. outputs := fmt.Sprint(m.AllOutputs())
  1726. if !strings.Contains(outputs, c.outputJarName) {
  1727. t.Errorf("Module output does not contain expected jar %s", c.outputJarName)
  1728. }
  1729. }
  1730. }
  1731. func TestTradefedOptions(t *testing.T) {
  1732. result := PrepareForTestWithJavaBuildComponents.RunTestWithBp(t, `
  1733. java_test_host {
  1734. name: "foo",
  1735. test_options: {
  1736. tradefed_options: [
  1737. {
  1738. name: "exclude-path",
  1739. value: "org/apache"
  1740. }
  1741. ]
  1742. }
  1743. }
  1744. `)
  1745. buildOS := result.Config.BuildOS.String()
  1746. args := result.ModuleForTests("foo", buildOS+"_common").
  1747. Output("out/soong/.intermediates/foo/" + buildOS + "_common/foo.config").Args
  1748. expected := proptools.NinjaAndShellEscape("<option name=\"exclude-path\" value=\"org/apache\" />")
  1749. if args["extraConfigs"] != expected {
  1750. t.Errorf("Expected args[\"extraConfigs\"] to equal %q, was %q", expected, args["extraConfigs"])
  1751. }
  1752. }