plugin.test.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import path from "node:path";
  4. import { afterEach, expect, test, vi } from "vitest";
  5. import * as commands from "../src/lib/run.js";
  6. import * as simulators from "../src/providers/sim.js";
  7. import { app, pickAppProduct } from "../src/providers/build.js";
  8. import { create, discover, source } from "../src/providers/project.js";
  9. import { isIosRuntime, parseSimulators } from "../src/providers/sim.js";
  10. const found = {
  11. projects: ["Explicit.xcodeproj"],
  12. workspaces: ["Auto.xcworkspace"],
  13. schemes: ["AutoScheme"],
  14. bundleIds: [],
  15. };
  16. afterEach(() => {
  17. vi.restoreAllMocks();
  18. vi.unstubAllEnvs();
  19. });
  20. test("discovery reads shared and user schemes without executing project code", async () => {
  21. const execute = vi.spyOn(commands, "run").mockResolvedValue({
  22. cmd: [],
  23. code: 0,
  24. stdout: JSON.stringify({ workspace: { schemes: ["ZCODE_ID_UID_EXECUTED"] } }),
  25. stderr: "",
  26. timed: false,
  27. });
  28. await withCwd(async () => {
  29. await fixtureFile(
  30. "Project/Probe.xcodeproj/project.pbxproj",
  31. "PRODUCT_BUNDLE_IDENTIFIER = com.example.probe;",
  32. );
  33. await fixtureFile("Project/Probe.xcodeproj/xcshareddata/xcschemes/Shared.xcscheme");
  34. await fixtureFile(
  35. "Project/Probe.xcodeproj/xcuserdata/dev.xcuserdatad/xcschemes/Personal.xcscheme",
  36. );
  37. await fixtureFile("Project/Probe.xcworkspace/xcshareddata/xcschemes/Workspace.xcscheme");
  38. await fixtureFile("Project/Probe.xcworkspace/xcshareddata/xcschemes/Shared.xcscheme");
  39. await fixtureFile("Project/Probe.xcworkspace/xcshareddata/xcschemes/ignored.txt");
  40. await mkdir("Project/Probe.xcworkspace/xcshareddata/xcschemes/Directory.xcscheme");
  41. await fixtureFile(
  42. "Project/LocalPkg/Package.swift",
  43. 'fatalError("discovery must not evaluate manifests")',
  44. );
  45. expect(await discover(path.join(process.cwd(), "Project"))).toEqual({
  46. projects: ["Probe.xcodeproj"],
  47. workspaces: ["Probe.xcworkspace"],
  48. schemes: ["Personal", "Shared", "Workspace"],
  49. bundleIds: ["com.example.probe"],
  50. });
  51. expect(execute).not.toHaveBeenCalled();
  52. });
  53. });
  54. test("discovery leaves generated schemes unknown and works without Xcode", async () => {
  55. const execute = vi.spyOn(commands, "run").mockRejectedValue(new Error("Xcode unavailable"));
  56. await withCwd(async () => {
  57. expect(await discover()).toEqual({ projects: [], workspaces: [], schemes: [], bundleIds: [] });
  58. await fixtureFile(
  59. "Probe.xcodeproj/project.pbxproj",
  60. "PRODUCT_BUNDLE_IDENTIFIER = com.example.probe;",
  61. );
  62. await fixtureFile(
  63. "LocalPkg/Package.swift",
  64. 'fatalError("discovery must not evaluate manifests")',
  65. );
  66. expect(await discover()).toEqual({
  67. projects: ["Probe.xcodeproj"],
  68. workspaces: [],
  69. schemes: [],
  70. bundleIds: ["com.example.probe"],
  71. });
  72. expect(execute).not.toHaveBeenCalled();
  73. });
  74. });
  75. test.each([undefined, "ExplicitScheme"])(
  76. "build resolves schemes only when none was supplied (%s)",
  77. async (scheme) => {
  78. const execute = vi.spyOn(commands, "run").mockImplementation(async (cmd) => ({
  79. cmd,
  80. code: cmd.includes("-list") ? 0 : 1,
  81. stdout: cmd.includes("-list")
  82. ? JSON.stringify({ project: { schemes: ["GeneratedScheme"] } })
  83. : "build stopped by fixture",
  84. stderr: "",
  85. timed: false,
  86. }));
  87. vi.spyOn(simulators, "boot").mockResolvedValue({
  88. name: "Test iPhone",
  89. udid: "TEST",
  90. state: "Booted",
  91. runtime: "iOS",
  92. available: true,
  93. });
  94. await withCwd(async () => {
  95. vi.stubEnv("IOS_SIM_PLUGIN_DATA", path.join(process.cwd(), "plugin-data"));
  96. await fixtureFile("Probe.xcodeproj/project.pbxproj");
  97. await mkdir("Auto.xcworkspace");
  98. const result = await app({
  99. project: "Probe.xcodeproj",
  100. scheme,
  101. bundleId: "com.example.probe",
  102. derivedDataPath: "DerivedData",
  103. });
  104. const expectedScheme = scheme ?? "GeneratedScheme";
  105. expect(result.source).toEqual({
  106. flag: "-project",
  107. file: "Probe.xcodeproj",
  108. scheme: expectedScheme,
  109. });
  110. const listCalls = execute.mock.calls.filter(([cmd]) => cmd.includes("-list"));
  111. expect(listCalls).toHaveLength(scheme ? 0 : 1);
  112. if (!scheme)
  113. expect(listCalls[0]?.[0]).toEqual([
  114. "xcodebuild",
  115. "-list",
  116. "-json",
  117. "-project",
  118. "Probe.xcodeproj",
  119. ]);
  120. expect(execute.mock.calls.find(([cmd]) => cmd.includes("build"))?.[0]).toEqual(
  121. expect.arrayContaining(["-scheme", expectedScheme]),
  122. );
  123. });
  124. },
  125. );
  126. async function fixtureFile(file: string, text = "") {
  127. await mkdir(path.dirname(file), { recursive: true });
  128. await writeFile(file, text);
  129. }
  130. test.each([true, false])(
  131. "build resolves the auto workspace and keeps its fallback local (%s)",
  132. async (listed) => {
  133. const execute = vi.spyOn(commands, "run").mockImplementation(async (cmd) => ({
  134. cmd,
  135. code: cmd.includes("-list") && listed ? 0 : 1,
  136. stdout: cmd.includes("-list")
  137. ? JSON.stringify({ workspace: { schemes: ["WorkspaceScheme"] } })
  138. : "build stopped by fixture",
  139. stderr: "",
  140. timed: false,
  141. }));
  142. vi.spyOn(simulators, "boot").mockResolvedValue({
  143. name: "Test iPhone",
  144. udid: "TEST",
  145. state: "Booted",
  146. runtime: "iOS",
  147. available: true,
  148. });
  149. await withCwd(async () => {
  150. vi.stubEnv("IOS_SIM_PLUGIN_DATA", path.join(process.cwd(), "plugin-data"));
  151. await fixtureFile("Unrelated.xcodeproj/xcshareddata/xcschemes/Unrelated.xcscheme");
  152. await mkdir("Auto.xcworkspace");
  153. const result = await app({ bundleId: "com.example.probe", derivedDataPath: "DerivedData" });
  154. expect(result.source).toEqual({
  155. flag: "-workspace",
  156. file: "Auto.xcworkspace",
  157. scheme: listed ? "WorkspaceScheme" : "Auto",
  158. });
  159. expect(execute.mock.calls[0]?.[0]).toEqual([
  160. "xcodebuild",
  161. "-list",
  162. "-json",
  163. "-workspace",
  164. "Auto.xcworkspace",
  165. ]);
  166. });
  167. },
  168. );
  169. test("source prefers explicit project over auto workspace", () => {
  170. expect(source({ project: "Explicit.xcodeproj" }, found)).toEqual({
  171. flag: "-project",
  172. file: "Explicit.xcodeproj",
  173. scheme: "Explicit",
  174. });
  175. });
  176. test("create validates inputs and refuses accidental overwrites", async () => {
  177. await withCwd(async () => {
  178. const created = await create({ name: "Counter App", deployment: "17.0" });
  179. expect(created.project).toBe(path.join("CounterApp", "CounterApp.xcodeproj"));
  180. expect(created.bundle).toBe("com.example.counterapp");
  181. await expect(create({ name: "Counter App" })).rejects.toThrow("Refusing to overwrite");
  182. await expect(create({ name: "Escaped", dir: "../Escaped" })).rejects.toThrow(
  183. "Path escapes project root",
  184. );
  185. await expect(create({ name: "BadDeploy", deployment: "17.0; BAD=1" })).rejects.toThrow(
  186. "Invalid deployment",
  187. );
  188. await expect(create({ name: "BadBundle", bundleId: "com.example.bad_bundle" })).rejects.toThrow(
  189. "Invalid bundle id",
  190. );
  191. });
  192. });
  193. test("build product selection prefers the requested configuration", () => {
  194. const debug = path.join("DerivedData", "Build", "Products", "Debug-iphonesimulator", "Demo.app");
  195. const release = path.join(
  196. "DerivedData",
  197. "Build",
  198. "Products",
  199. "Release-iphonesimulator",
  200. "Demo.app",
  201. );
  202. expect(pickAppProduct([debug, release], "Release")).toBe(release);
  203. expect(pickAppProduct([debug], "Release")).toBe(debug);
  204. });
  205. test("runtime filtering keeps only iOS simulator runtimes", () => {
  206. expect(isIosRuntime("com.apple.CoreSimulator.SimRuntime.iOS-18-2")).toBe(true);
  207. expect(isIosRuntime("com.apple.CoreSimulator.SimRuntime.iPadOS-18-2")).toBe(true);
  208. expect(isIosRuntime("com.apple.CoreSimulator.SimRuntime.tvOS-18-2")).toBe(false);
  209. expect(isIosRuntime("com.apple.CoreSimulator.SimRuntime.watchOS-11-2")).toBe(false);
  210. expect(isIosRuntime("com.apple.CoreSimulator.SimRuntime.visionOS-2-2")).toBe(false);
  211. });
  212. test("simulator parsing drops non-iOS runtimes and unavailable devices", () => {
  213. const sims = parseSimulators(
  214. JSON.stringify({
  215. devices: {
  216. "com.apple.CoreSimulator.SimRuntime.tvOS-18-2": [
  217. { name: "Apple TV", udid: "TV-1", state: "Shutdown", isAvailable: true },
  218. ],
  219. "com.apple.CoreSimulator.SimRuntime.iOS-18-2": [
  220. { name: "iPhone 16", udid: "IOS-1", state: "Shutdown", isAvailable: true },
  221. {
  222. name: "iPhone 15",
  223. udid: "IOS-2",
  224. state: "Shutdown",
  225. availabilityError: "runtime unavailable",
  226. },
  227. ],
  228. },
  229. }),
  230. );
  231. expect(sims).toEqual([
  232. {
  233. name: "iPhone 16",
  234. udid: "IOS-1",
  235. state: "Shutdown",
  236. runtime: "com.apple.CoreSimulator.SimRuntime.iOS-18-2",
  237. available: true,
  238. },
  239. {
  240. name: "iPhone 15",
  241. udid: "IOS-2",
  242. state: "Shutdown",
  243. runtime: "com.apple.CoreSimulator.SimRuntime.iOS-18-2",
  244. available: false,
  245. },
  246. ]);
  247. expect(sims.filter((item) => item.available)).toHaveLength(1);
  248. });
  249. async function withCwd(work: () => Promise<void>) {
  250. const old = process.cwd();
  251. const dir = await mkdtemp(path.join(tmpdir(), "ios-plugin-test-"));
  252. process.chdir(dir);
  253. try {
  254. await work();
  255. } finally {
  256. process.chdir(old);
  257. await rm(dir, { recursive: true, force: true });
  258. }
  259. }