plugin.test.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import path from "node:path";
  4. import { expect, test } from "vitest";
  5. import { pickApk } from "../src/providers/build.js";
  6. import { androidSystemImagePackage } from "../src/providers/config.js";
  7. import { adbShellCommand, parseAdbDevices } from "../src/providers/device.js";
  8. import { parseAvds, startedEmulatorCandidates } from "../src/providers/avd.js";
  9. import { create, discover } from "../src/providers/project.js";
  10. import { preflightOk, type Check } from "../src/providers/preflight.js";
  11. import { inputText, parseUiAutomator } from "../src/providers/ui.js";
  12. test("create validates inputs and refuses accidental overwrites", async () => {
  13. await withCwd(async () => {
  14. const created = await create({
  15. name: "Counter App",
  16. packageName: "com.example.counterapp",
  17. minSdk: 24,
  18. });
  19. expect(created.root).toBe("CounterApp");
  20. expect(created.applicationId).toBe("com.example.counterapp");
  21. expect(created.createdBy).toBe("template");
  22. expect(created.files).toContain(path.join("CounterApp", "gradle.properties"));
  23. expect(created.files).toContain(path.join("CounterApp", "local.properties"));
  24. expect(await readFile(path.join("CounterApp", "gradle.properties"), "utf8")).toContain(
  25. "android.useAndroidX=true",
  26. );
  27. expect(await readFile(path.join("CounterApp", "local.properties"), "utf8")).toContain(
  28. "sdk.dir=",
  29. );
  30. await expect(create({ name: "Counter App" })).rejects.toThrow("Refusing to overwrite");
  31. await expect(create({ name: "Escaped", dir: "../Escaped" })).rejects.toThrow(
  32. "Path escapes project root",
  33. );
  34. await expect(
  35. create({ name: "Bad Package", packageName: "com.example.bad-package" }),
  36. ).rejects.toThrow("Invalid Android package name");
  37. await expect(create({ name: "Bad Sdk", minSdk: 1 })).rejects.toThrow("Invalid minSdk");
  38. });
  39. });
  40. test("discover finds generated Gradle project metadata", async () => {
  41. await withCwd(async () => {
  42. await create({ name: "Demo", packageName: "com.example.demo" });
  43. await mkdir(path.join("Demo", "app", "build", "outputs", "apk", "debug"), { recursive: true });
  44. await writeFile(
  45. path.join("Demo", "app", "build", "outputs", "apk", "debug", "app-debug.apk"),
  46. "",
  47. );
  48. const found = await discover();
  49. expect(found.root).toBe("Demo");
  50. expect(found.modules).toEqual([":app"]);
  51. expect(found.applicationIds).toContain("com.example.demo");
  52. expect(found.manifests.some((item) => item.endsWith("AndroidManifest.xml"))).toBe(true);
  53. expect(found.apks).toEqual([
  54. path.join("Demo", "app", "build", "outputs", "apk", "debug", "app-debug.apk"),
  55. ]);
  56. expect(found.hasGradleProperties).toBe(true);
  57. expect(found.hasLocalProperties).toBe(true);
  58. expect(found.warnings).toEqual([
  59. "Missing Gradle wrapper. Install Gradle or generate ./gradlew before building.",
  60. ]);
  61. });
  62. });
  63. test("plugin config environment controls Android defaults", async () => {
  64. await withEnv(
  65. {
  66. ANDROID_PLUGIN_API_LEVEL: "36",
  67. ANDROID_PLUGIN_SYSTEM_IMAGE_VARIANT: "google_apis",
  68. ANDROID_PLUGIN_SYSTEM_IMAGE_ABI: "x86_64",
  69. },
  70. async () => {
  71. await withCwd(async () => {
  72. await create({ name: "Configured", packageName: "com.example.configured" });
  73. const build = await readFile(path.join("Configured", "app", "build.gradle.kts"), "utf8");
  74. expect(build).toContain("compileSdk = 36");
  75. expect(androidSystemImagePackage()).toBe("system-images;android-36;google_apis;x86_64");
  76. });
  77. },
  78. );
  79. });
  80. test("adb devices parser keeps serial, state, and attributes", () => {
  81. expect(
  82. parseAdbDevices(`List of devices attached
  83. emulator-5554 device product:sdk_gphone64_arm64 model:sdk_gphone64_arm64 device:emu64a transport_id:1
  84. R5CT12345 unauthorized usb:338690048X product:phone model:Pixel_8 device:husky
  85. `),
  86. ).toEqual([
  87. {
  88. serial: "emulator-5554",
  89. state: "device",
  90. kind: "emulator",
  91. product: "sdk_gphone64_arm64",
  92. model: "sdk_gphone64_arm64",
  93. device: "emu64a",
  94. transportId: "1",
  95. raw: "emulator-5554 device product:sdk_gphone64_arm64 model:sdk_gphone64_arm64 device:emu64a transport_id:1",
  96. },
  97. {
  98. serial: "R5CT12345",
  99. state: "unauthorized",
  100. kind: "device",
  101. product: "phone",
  102. model: "Pixel_8",
  103. device: "husky",
  104. transportId: undefined,
  105. raw: "R5CT12345 unauthorized usb:338690048X product:phone model:Pixel_8 device:husky",
  106. },
  107. ]);
  108. });
  109. test("avd parser drops blank lines", () => {
  110. expect(parseAvds("\nPixel_8\nmedium_phone\n\n")).toEqual([
  111. { name: "Pixel_8" },
  112. { name: "medium_phone" },
  113. ]);
  114. });
  115. test("started emulator candidates exclude devices present before launch", () => {
  116. const existing = {
  117. serial: "emulator-5554",
  118. state: "device",
  119. kind: "emulator" as const,
  120. raw: "emulator-5554 device",
  121. };
  122. const fresh = {
  123. serial: "emulator-5556",
  124. state: "device",
  125. kind: "emulator" as const,
  126. raw: "emulator-5556 device",
  127. };
  128. const physical = {
  129. serial: "R5CT12345",
  130. state: "device",
  131. kind: "device" as const,
  132. raw: "R5CT12345 device",
  133. };
  134. expect(startedEmulatorCandidates([existing, fresh, physical], new Set([existing.serial]))).toEqual([
  135. fresh,
  136. ]);
  137. expect(startedEmulatorCandidates([existing, physical], new Set([existing.serial]))).toEqual([]);
  138. });
  139. test("preflight accepts a ready device target without emulator-only setup", () => {
  140. const emulatorOnlyMissing = [
  141. check("emulator", false),
  142. check("avdmanager", false),
  143. check("Android Virtual Devices", false),
  144. check("Emulator acceleration", false),
  145. ];
  146. expect(
  147. preflightOk([...readyRequiredChecks(), ...emulatorOnlyMissing, check("ADB devices", true)], {
  148. hasReadyTarget: true,
  149. }),
  150. ).toBe(true);
  151. expect(
  152. preflightOk([...readyRequiredChecks(), ...emulatorOnlyMissing, check("ADB devices", false)], {
  153. hasReadyTarget: false,
  154. }),
  155. ).toBe(false);
  156. });
  157. test("preflight allows no adb target before starting a configured emulator", () => {
  158. expect(
  159. preflightOk(
  160. [
  161. ...readyRequiredChecks(),
  162. check("emulator", true),
  163. check("avdmanager", true),
  164. check("Android Virtual Devices", true),
  165. check("ADB devices", false),
  166. ],
  167. { hasReadyTarget: false },
  168. ),
  169. ).toBe(true);
  170. });
  171. test("apk selection prefers requested variant", () => {
  172. const debug = path.join("app", "build", "outputs", "apk", "debug", "app-debug.apk");
  173. const release = path.join("app", "build", "outputs", "apk", "release", "app-release.apk");
  174. expect(pickApk([debug, release], "release")).toBe(release);
  175. expect(pickApk([debug], "release")).toBe(debug);
  176. });
  177. test("uiautomator parser returns compact elements with bounds centers", () => {
  178. const elements = parseUiAutomator(`<hierarchy>
  179. <node index="0" text="Increment" content-desc="incrementButton" resource-id="com.example:id/inc" class="android.widget.Button" clickable="true" enabled="true" bounds="[10,20][110,220]" />
  180. </hierarchy>`);
  181. expect(elements).toEqual([
  182. {
  183. index: 0,
  184. text: "Increment",
  185. contentDescription: "incrementButton",
  186. resourceId: "com.example:id/inc",
  187. className: "android.widget.Button",
  188. bounds: { left: 10, top: 20, right: 110, bottom: 220, centerX: 60, centerY: 120 },
  189. clickable: true,
  190. enabled: true,
  191. },
  192. ]);
  193. });
  194. test("adb input text encodes spaces and percent before shell quoting", () => {
  195. expect(inputText('100% ready & go; "ok" (now)')).toBe(
  196. '100%25%sready%s&%sgo;%s"ok"%s(now)',
  197. );
  198. });
  199. test("adb shell command quotes device shell tokens", () => {
  200. expect(
  201. adbShellCommand(["am", "start", "-d", "https://example.com/path?q=one&next='two'"]),
  202. ).toBe("am start -d 'https://example.com/path?q=one&next='\\''two'\\'''");
  203. expect(adbShellCommand(["input", "text", "hello%sworld"])).toBe(
  204. "input text hello%sworld",
  205. );
  206. });
  207. async function withCwd(work: () => Promise<void>) {
  208. const old = process.cwd();
  209. const sdkPath = process.env.ANDROID_PLUGIN_SDK_PATH;
  210. const dir = await mkdtemp(path.join(tmpdir(), "android-plugin-test-"));
  211. const workspace = path.join(dir, "workspace");
  212. await mkdir(workspace);
  213. process.chdir(workspace);
  214. process.env.ANDROID_PLUGIN_SDK_PATH = path.join(dir, "sdk");
  215. try {
  216. await mkdir("fixtures", { recursive: true });
  217. await mkdir(process.env.ANDROID_PLUGIN_SDK_PATH, { recursive: true });
  218. await writeFile(path.join("fixtures", ".keep"), "");
  219. await work();
  220. } finally {
  221. process.chdir(old);
  222. if (sdkPath === undefined) delete process.env.ANDROID_PLUGIN_SDK_PATH;
  223. else process.env.ANDROID_PLUGIN_SDK_PATH = sdkPath;
  224. await rm(dir, { recursive: true, force: true });
  225. }
  226. }
  227. function readyRequiredChecks(): Check[] {
  228. return [
  229. check("Host OS", true),
  230. check("Android SDK root", true),
  231. check("Android plugin defaults", true),
  232. check("adb", true),
  233. check("sdkmanager", true),
  234. check("Java", true),
  235. check("Gradle", true),
  236. ];
  237. }
  238. function check(name: string, ok: boolean): Check {
  239. return { name, ok, detail: ok ? "available" : "missing" };
  240. }
  241. async function withEnv(values: Record<string, string>, work: () => Promise<void>) {
  242. const old = new Map(Object.keys(values).map((key) => [key, process.env[key]]));
  243. for (const [key, value] of Object.entries(values)) process.env[key] = value;
  244. try {
  245. await work();
  246. } finally {
  247. for (const [key, value] of old) {
  248. if (value === undefined) delete process.env[key];
  249. else process.env[key] = value;
  250. }
  251. }
  252. }