Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

run-android-e2e.ts

430 lines10.9 KB

1import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
2import { homedir, tmpdir } from 'node:os'
3import { spawn } from 'node:child_process'
4import { dirname, join, resolve } from 'node:path'
5import { fileURLToPath } from 'node:url'
6​
7type RuntimeResultRow = {
8 status: `passed` | `failed`
9 payload: {
10 passed?: number
11 failed?: number
12 skipped?: number
13 total?: number
14 failures?: Array<{
15 name?: string
16 error?: string
17 }>
18 error?: string
19 step?: string
20 runId?: string
21 }
23​
24const packageDirectory = dirname(fileURLToPath(import.meta.url))
25const appDirectory = resolve(packageDirectory, `app`)
26const androidDirectory = resolve(appDirectory, `android`)
27const appId = `com.tanstack.db.capacitorsqlitee2e`
28const runtimeRunId = Date.now().toString(36)
29const resultsDatabaseName = `tanstack_db_capacitor_e2e_results_${runtimeRunId}`
30​
31function runCommand(
32 command: string,
33 args: Array<string>,
34 options: {
35 cwd?: string
36 env?: NodeJS.ProcessEnv
37 stdio?: `inherit` | `pipe`
38 } = {},
39): Promise<string> {
40 return new Promise((resolvePromise, rejectPromise) => {
41 let stdout = ``
42 const child = spawn(command, args, {
43 cwd: options.cwd ?? packageDirectory,
44 env: {
45 ...process.env,
46 ...options.env,
47 },
48 stdio:
49 options.stdio === `pipe` ? [`ignore`, `pipe`, `inherit`] : `inherit`,
50 })
51​
52 if (options.stdio === `pipe`) {
53 if (!child.stdout) {
54 rejectPromise(new Error(`${command} did not expose stdout`))
55 return
56 }
57​
58 child.stdout.on(`data`, (chunk) => {
59 stdout += String(chunk)
60 })
61 }
62​
63 child.on(`exit`, (code) => {
64 if (code === 0) {
65 resolvePromise(stdout)
66 return
67 }
68​
69 rejectPromise(
70 new Error(
71 `${command} ${args.join(` `)} exited with code ${String(code)}`,
72 ),
73 )
74 })
75 child.on(`error`, rejectPromise)
76 })
78​
79function resolveAndroidSdkRoot(): string {
80 const candidates = [
81 process.env.ANDROID_HOME,
82 process.env.ANDROID_SDK_ROOT,
83 resolve(homedir(), `Library/Android/sdk`),
84 ].filter((value): value is string => Boolean(value))
85​
86 const sdkRoot = candidates.find((candidate) => existsSync(candidate))
87 if (!sdkRoot) {
88 throw new Error(`Unable to locate Android SDK root`)
89 }
90​
91 return sdkRoot
93​
94function resolveSdkBinary(relativePath: string): string {
95 const binaryPath = resolve(resolveAndroidSdkRoot(), relativePath)
96 if (!existsSync(binaryPath)) {
97 throw new Error(`Android SDK binary not found: ${binaryPath}`)
98 }
99​
100 return binaryPath
102​
103function createAndroidCommandEnv(): NodeJS.ProcessEnv {
104 const sdkRoot = resolveAndroidSdkRoot()
105 return {
106 ANDROID_HOME: sdkRoot,
107 ANDROID_SDK_ROOT: sdkRoot,
108 }
110​
111async function ensureNativeProject(): Promise<void> {
112 const androidProjectDirectory = resolve(appDirectory, `android`)
113 const androidGradlePath = resolve(androidProjectDirectory, `gradlew`)
114 const androidCommandEnv = createAndroidCommandEnv()
115​
116 if (!existsSync(androidGradlePath)) {
117 await runCommand(`pnpm`, [`run`, `native:add:android`], {
118 cwd: appDirectory,
119 env: androidCommandEnv,
120 })
121 }
122​
123 await runCommand(`pnpm`, [`build`], {
124 cwd: appDirectory,
125 env: {
126 VITE_TANSTACK_DB_CAPACITOR_E2E_RUN_ID: runtimeRunId,
127 },
128 })
129 await runCommand(`pnpm`, [`exec`, `cap`, `sync`, `android`], {
130 cwd: appDirectory,
131 env: androidCommandEnv,
132 })
134​
135async function resolveAndroidDeviceId(adbPath: string): Promise<string> {
136 const requestedId =
137 process.env.TANSTACK_DB_CAPACITOR_ANDROID_DEVICE_ID?.trim()
138 if (requestedId) {
139 return requestedId
140 }
141​
142 const devicesOutput = await runCommand(adbPath, [`devices`], {
143 stdio: `pipe`,
144 })
145 const connectedDevices = devicesOutput
146 .split(`\n`)
147 .map((line) => line.trim())
148 .filter(
149 (line) => line.endsWith(`device`) && !line.startsWith(`List of devices`),
150 )
151 .map((line) => line.split(/\s+/)[0])
152​
153 if (connectedDevices.length > 0) {
154 return connectedDevices[0]!
155 }
156​
157 const emulatorPath = resolveSdkBinary(`emulator/emulator`)
158 const requestedAvd =
159 process.env.TANSTACK_DB_CAPACITOR_ANDROID_AVD_NAME?.trim()
160 const avdName =
161 requestedAvd ||
162 (await runCommand(emulatorPath, [`-list-avds`], { stdio: `pipe` }))
163 .split(`\n`)
164 .map((line) => line.trim())
165 .find((line) => line.length > 0)
166​
167 if (!avdName) {
168 throw new Error(`No Android emulator available`)
169 }
170​
171 const emulator = spawn(emulatorPath, [`-avd`, avdName, `-no-snapshot-save`], {
172 detached: true,
173 stdio: `ignore`,
174 })
175 emulator.unref()
176​
177 const deadline = Date.now() + 180_000
178 while (Date.now() < deadline) {
179 const updatedDevicesOutput = await runCommand(adbPath, [`devices`], {
180 stdio: `pipe`,
181 })
182 const emulatorDevice = updatedDevicesOutput
183 .split(`\n`)
184 .map((line) => line.trim())
185 .find((line) => line.startsWith(`emulator-`) && line.endsWith(`device`))
186​
187 if (emulatorDevice) {
188 return emulatorDevice.split(/\s+/)[0]!
189 }
190​
191 await new Promise((resolvePromise) => setTimeout(resolvePromise, 1000))
192 }
193​
194 throw new Error(`Timed out waiting for Android emulator to appear`)
196​
197async function waitForAndroidBoot(
198 adbPath: string,
199 deviceId: string,
200): Promise<void> {
201 await runCommand(adbPath, [`-s`, deviceId, `wait-for-device`])
202​
203 const deadline = Date.now() + 180_000
204 while (Date.now() < deadline) {
205 const bootCompleted = (
206 await runCommand(
207 adbPath,
208 [`-s`, deviceId, `shell`, `getprop`, `sys.boot_completed`],
209 { stdio: `pipe` },
210 )
211 ).trim()
212​
213 if (bootCompleted === `1`) {
214 return
215 }
216​
217 await new Promise((resolvePromise) => setTimeout(resolvePromise, 1000))
218 }
219​
220 throw new Error(`Timed out waiting for Android emulator boot completion`)
222​
223async function buildDebugApk(): Promise<string> {
224 const gradlewPath = resolve(androidDirectory, `gradlew`)
225 const androidCommandEnv = createAndroidCommandEnv()
226 await runCommand(gradlewPath, [`assembleDebug`], {
227 cwd: androidDirectory,
228 env: androidCommandEnv,
229 })
230​
231 const apkPath = resolve(
232 androidDirectory,
233 `app/build/outputs/apk/debug/app-debug.apk`,
234 )
235 if (!existsSync(apkPath)) {
236 throw new Error(`Debug APK not found at ${apkPath}`)
237 }
238​
239 return apkPath
241​
242async function installAndLaunchApp(
243 adbPath: string,
244 deviceId: string,
245 apkPath: string,
246): Promise<void> {
247 await runCommand(adbPath, [`-s`, deviceId, `install`, `-r`, apkPath])
248 await runCommand(adbPath, [
249 `-s`,
250 deviceId,
251 `shell`,
252 `am`,
253 `force-stop`,
254 appId,
255 ]).catch(() => Promise.resolve(``))
256 await runCommand(adbPath, [
257 `-s`,
258 deviceId,
259 `shell`,
260 `monkey`,
261 `-p`,
262 appId,
263 `-c`,
264 `android.intent.category.LAUNCHER`,
265 `1`,
266 ])
268​
269async function pullResultDatabase(
270 adbPath: string,
271 deviceId: string,
272 destinationPath: string,
273): Promise<boolean> {
274 return new Promise((resolvePromise, rejectPromise) => {
275 const child = spawn(
276 adbPath,
277 [
278 `-s`,
279 deviceId,
280 `exec-out`,
281 `run-as`,
282 appId,
283 `cat`,
284 `databases/${resultsDatabaseName}SQLite.db`,
285 ],
286 {
287 cwd: packageDirectory,
288 stdio: [`ignore`, `pipe`, `ignore`],
289 },
290 )
291​
292 const chunks: Array<Buffer> = []
293 child.stdout.on(`data`, (chunk: Buffer) => {
294 chunks.push(chunk)
295 })
296 child.on(`exit`, (code) => {
297 if (code === 0 && chunks.length > 0) {
298 writeFileSync(destinationPath, Buffer.concat(chunks))
299 resolvePromise(true)
300 return
301 }
302​
303 if (code !== 0) {
304 resolvePromise(false)
305 return
306 }
307​
308 rejectPromise(new Error(`Received empty Android result database payload`))
309 })
310 child.on(`error`, rejectPromise)
311 })
313​
314async function readSqlScalar(
315 databasePath: string,
316 sql: string,
317): Promise<string | null> {
318 const output = await new Promise<string>((resolvePromise, rejectPromise) => {
319 let stdout = ``
320 const child = spawn(`sqlite3`, [databasePath, sql], {
321 cwd: packageDirectory,
322 stdio: [`ignore`, `pipe`, `ignore`],
323 })
324​
325 child.stdout.on(`data`, (chunk) => {
326 stdout += String(chunk)
327 })
328 child.on(`exit`, (code) => {
329 if (code === 0) {
330 resolvePromise(stdout)
331 return
332 }
333​
334 rejectPromise(new Error(`sqlite3 query failed`))
335 })
336 child.on(`error`, rejectPromise)
337 })
338 const trimmed = output.trim()
339 return trimmed.length > 0 ? trimmed : null
341​
342async function waitForResult(
343 adbPath: string,
344 deviceId: string,
345): Promise<RuntimeResultRow> {
346 const tempDirectory = mkdtempSync(
347 join(tmpdir(), `db-capacitor-android-e2e-result-`),
348 )
349 const extractedDatabasePath = resolve(
350 tempDirectory,
351 `${resultsDatabaseName}SQLite.db`,
352 )
353 const deadline = Date.now() + 600_000
354​
355 try {
356 while (Date.now() < deadline) {
357 const hasDatabase = await pullResultDatabase(
358 adbPath,
359 deviceId,
360 extractedDatabasePath,
361 )
362​
363 if (hasDatabase) {
364 let status: string | null = null
365 let payloadJson: string | null = null
366​
367 try {
368 status = await readSqlScalar(
369 extractedDatabasePath,
370 `SELECT status FROM test_run_results ORDER BY id DESC LIMIT 1;`,
371 )
372 payloadJson = await readSqlScalar(
373 extractedDatabasePath,
374 `SELECT payload_json FROM test_run_results ORDER BY id DESC LIMIT 1;`,
375 )
376 } catch {
377 // Android may expose the DB before SQLite has fully finalized writes,
378 // so keep polling until the copied file can be queried cleanly.
379 }
380​
381 if (status && payloadJson) {
382 return {
383 status: status as RuntimeResultRow[`status`],
384 payload: JSON.parse(payloadJson) as RuntimeResultRow[`payload`],
385 }
386 }
387 }
388​
389 await new Promise((resolvePromise) => setTimeout(resolvePromise, 1000))
390 }
391 } finally {
392 rmSync(tempDirectory, { recursive: true, force: true })
393 }
394​
395 throw new Error(`Timed out waiting for native Android e2e result`)
397​
398const adbPath = resolveSdkBinary(`platform-tools/adb`)
399await ensureNativeProject()
400const deviceId = await resolveAndroidDeviceId(adbPath)
401await waitForAndroidBoot(adbPath, deviceId)
402const apkPath = await buildDebugApk()
403await installAndLaunchApp(adbPath, deviceId, apkPath)
404const result = await waitForResult(adbPath, deviceId)
405​
406if (result.status !== `passed`) {
407 const firstFailure = result.payload.failures?.[0]
408 throw new Error(
409 result.payload.error ??
410 (firstFailure
411 ? `${firstFailure.name ?? `Unnamed failure`}: ${firstFailure.error ?? `No error message`}`
412 : `Native Android e2e suite failed`),
413 )
415​
416console.log(
417 JSON.stringify(
418 {
419 runId: runtimeRunId,
420 deviceId,
421 status: result.status,
422 passed: result.payload.passed ?? 0,
423 failed: result.payload.failed ?? 0,
424 skipped: result.payload.skipped ?? 0,
425 total: result.payload.total ?? 0,
426 },
427 null,
428 2,
429 ),