Skip to content

Commit 2033ab6

Browse files
authored
ci(tests): fetch test results without adb root (#2098)
Read the results XML through run-as instead of adb root, so runtestsAndVerifyResults works on Play Store images and user-build devices. Delete the previous results after the debug install so a stale XML is never picked up. Pin each run to one device: resolve a serial (ANDROID_SERIAL, else adb -d|-e get-serialno, failing fast when ambiguous), pass it to installDebug, and use -s for every adb call. -PrunOnDevice now actually targets the device. Make the result poller tolerate a loaded host: declare the app dead only after 3 consecutive liveness misses (pidof, with a ps fallback for API 21-23), give every adb call a 30s timeout, and raise the exec output limit to 64 MiB.
1 parent 696bb27 commit 2033ab6

3 files changed

Lines changed: 90 additions & 69 deletions

File tree

‎test-app/runtests.gradle‎

Lines changed: 41 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,32 @@ def isWinOs = System.properties['os.name'].toLowerCase().contains('windows')
22
def runOnDevice = project.hasProperty("runOnDevice")
33
def runOnDeviceOrEmulator = runOnDevice ? "-d" : "-e"
44

5+
// One device for the whole run. Without ANDROID_SERIAL, :app:installDebug installs on every
6+
// connected device, overwriting whatever build of the test app the others are running.
7+
def targetSerial = null
8+
def resolveTargetSerial = { ->
9+
if (targetSerial != null) {
10+
return targetSerial
11+
}
12+
def fromEnv = System.getenv("ANDROID_SERIAL")
13+
if (fromEnv) {
14+
targetSerial = fromEnv
15+
return targetSerial
16+
}
17+
def proc = ["adb", runOnDeviceOrEmulator, "get-serialno"].execute()
18+
def stdout = new StringBuilder()
19+
def stderr = new StringBuilder()
20+
proc.waitForProcessOutput(stdout, stderr)
21+
def serial = stdout.toString().trim()
22+
if (proc.exitValue() != 0 || !serial) {
23+
throw new GradleException("Could not pick a single ${runOnDevice ? 'device' : 'emulator'} " +
24+
"(adb ${runOnDeviceOrEmulator}: ${stderr.toString().trim()}). Set ANDROID_SERIAL to choose one.")
25+
}
26+
targetSerial = serial
27+
return targetSerial
28+
}
29+
def adbTarget = { -> ["-s", resolveTargetSerial()] }
30+
531
def onlyX86 = project.hasProperty("onlyX86")
632
def useCCache = project.hasProperty("useCCache")
733
def selectedAbis = project.hasProperty("abis") ? project.property("abis") : null
@@ -16,10 +42,12 @@ task waitForEmulatorToStart(type: Exec) {
1642
doFirst {
1743
println "Waiting for emulator to start..."
1844

45+
def envSerial = System.getenv("ANDROID_SERIAL")
46+
def selector = envSerial ? ["-s", envSerial] : [runOnDeviceOrEmulator]
1947
if (isWinOs) {
20-
commandLine "cmd", "/c", "node", "$rootDir\\tools\\make_sure_emulator_is_ready.js", runOnDeviceOrEmulator
48+
commandLine(["cmd", "/c", "node", "$rootDir\\tools\\make_sure_emulator_is_ready.js"] + selector)
2149
} else {
22-
commandLine "node", "$rootDir/tools/make_sure_emulator_is_ready.js", runOnDeviceOrEmulator
50+
commandLine(["node", "$rootDir/tools/make_sure_emulator_is_ready.js"] + selector)
2351
}
2452
}
2553
}
@@ -53,32 +81,20 @@ def getBuildArguments = { ->
5381
task installApk(type: Exec) {
5482
doFirst {
5583
println "Attempting to install buit apk"
84+
environment "ANDROID_SERIAL", resolveTargetSerial()
5685
commandLine getBuildArguments()
5786
}
5887
}
5988

60-
task runAdbAsRoot(type: Exec) {
61-
doFirst {
62-
println "Running adb as root"
63-
64-
if (isWinOs) {
65-
commandLine "cmd", "/c", "adb", "-e", "root"
66-
} else {
67-
commandLine "adb", "-e", "root"
68-
}
69-
sleep(10 * 1000) // wait 10s to make sure adb properly restarts, otherwise error: closed might happen on next command
70-
}
71-
}
72-
7389
task deletePreviousResultXml(type: Exec) {
7490
ignoreExitValue = true
7591
doFirst {
7692
println "Removing previous android_unit_test_results.xml"
7793

7894
if (isWinOs) {
79-
commandLine "cmd", "/c", "adb", runOnDeviceOrEmulator, "-e", "shell", "run-as", "com.tns.testapplication", "rm", "-f", "android_unit_test_results.xml"
95+
commandLine(["cmd", "/c", "adb"] + adbTarget() + ["shell", "run-as", "com.tns.testapplication", "rm", "-f", "android_unit_test_results.xml"])
8096
} else {
81-
commandLine "adb", runOnDeviceOrEmulator, "-e", "shell", "run-as", "com.tns.testapplication", "rm", "-f", "android_unit_test_results.xml"
97+
commandLine(["adb"] + adbTarget() + ["shell", "run-as", "com.tns.testapplication", "rm", "-f", "android_unit_test_results.xml"])
8298
}
8399
}
84100
}
@@ -88,9 +104,9 @@ task startInstalledApk(type: Exec) {
88104
println "Starting test application"
89105

90106
if (isWinOs) {
91-
commandLine "cmd", "/c", "adb", runOnDeviceOrEmulator, "-e", "shell", "am", "start", "-n", "com.tns.testapplication/com.tns.NativeScriptActivity", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER"
107+
commandLine(["cmd", "/c", "adb"] + adbTarget() + ["shell", "am", "start", "-n", "com.tns.testapplication/com.tns.NativeScriptActivity", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER"])
92108
} else {
93-
commandLine "adb", runOnDeviceOrEmulator, "-e", "shell", "am", "start", "-n", "com.tns.testapplication/com.tns.NativeScriptActivity", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER"
109+
commandLine(["adb"] + adbTarget() + ["shell", "am", "start", "-n", "com.tns.testapplication/com.tns.NativeScriptActivity", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER"])
94110
}
95111
}
96112
}
@@ -107,9 +123,9 @@ task waitForUnitTestResultFile(type: Exec) {
107123
println "Waiting for tests to finish..."
108124

109125
if (isWinOs) {
110-
commandLine "cmd", "/c", "node", "$rootDir\\tools\\try_to_find_test_result_file.js", runOnDeviceOrEmulator
126+
commandLine(["cmd", "/c", "node", "$rootDir\\tools\\try_to_find_test_result_file.js"] + adbTarget())
111127
} else {
112-
commandLine "node", "$rootDir/tools/try_to_find_test_result_file.js", runOnDeviceOrEmulator
128+
commandLine(["node", "$rootDir/tools/try_to_find_test_result_file.js"] + adbTarget())
113129
}
114130
}
115131
}
@@ -138,10 +154,10 @@ task runtests {
138154
}
139155

140156
// waitForEmulatorToStart.dependsOn(deleteDist)
141-
runAdbAsRoot.dependsOn(waitForEmulatorToStart)
142-
deletePreviousResultXml.dependsOn(runAdbAsRoot)
143-
installApk.dependsOn(deletePreviousResultXml)
144-
startInstalledApk.dependsOn(installApk)
157+
installApk.dependsOn(waitForEmulatorToStart)
158+
// Runs after the install: run-as only works once the debuggable build is on the device.
159+
deletePreviousResultXml.dependsOn(installApk)
160+
startInstalledApk.dependsOn(deletePreviousResultXml)
145161
createDistFolder.dependsOn(startInstalledApk)
146162
waitForUnitTestResultFile.dependsOn(createDistFolder)
147163
copyResultToDist.dependsOn(waitForUnitTestResultFile)

‎test-app/tools/make_sure_emulator_is_ready.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ var checkBootAnimationPropertyExec = require('child_process').exec,
55
processTimeout = 10 * 60 * 1000, // 10 minutes
66
searchInterval = 2 * 1000;
77

8-
var runOnDeviceOrEmulator = process.argv[2];
8+
var runOnDeviceOrEmulator = process.argv.slice(2).join(" ");
99

1010
checkBootAnimationPropertyExec("empty", check)
1111

‎test-app/tools/try_to_find_test_result_file.js‎

Lines changed: 48 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
11
const { exec } = require("child_process");
22

33
const appId = "com.tns.testapplication";
4-
const runOnDeviceOrEmulator = process.argv[2] || "";
5-
const adbPrefix = `adb ${runOnDeviceOrEmulator} -e`;
6-
const resultsPath = `/data/data/${appId}/android_unit_test_results.xml`;
4+
const runOnDeviceOrEmulator = process.argv.slice(2).join(" ") || "-e";
5+
const adbPrefix = `adb ${runOnDeviceOrEmulator}`;
6+
const resultsFileName = "android_unit_test_results.xml";
77

88
const processTimeoutMs = 20 * 60 * 1000; // 20 minutes timeout (empirical constant)
99
const pollIntervalMs = 10 * 1000;
10+
// adb can hang outright on a wedged or overloaded device; a hung call would also stall the
11+
// overall timeout check, which only runs between calls.
12+
const adbCallTimeoutMs = 30 * 1000;
13+
// exec kills the child past maxBuffer (1 MiB by default); the results XML and a full logcat
14+
// dump can both exceed that.
15+
const adbExecOptions = { timeout: adbCallTimeoutMs, maxBuffer: 64 * 1024 * 1024 };
1016
const scriptStartTime = new Date();
1117
const logcatCutoffTime = new Date(scriptStartTime.getTime() - 60 * 1000); // 1 minute before start
1218

@@ -16,7 +22,7 @@ console.error = console.log; // Redirect stderr to stdout for easier logcat capt
1622

1723
function execAndStream(command, streamOutput = false) {
1824
return new Promise((resolve) => {
19-
const child = exec(command, (error, stdout, stderr) => {
25+
const child = exec(command, adbExecOptions, (error, stdout, stderr) => {
2026
resolve({ error, stdout, stderr });
2127
});
2228

@@ -73,15 +79,15 @@ async function readAndFilterLogcat() {
7379
// if we have a PID, filter by it
7480
if (appPID !== -1) {
7581
return new Promise((resolve) => {
76-
exec(`${adbPrefix} logcat -d --pid=${appPID}`, (error, stdout) => {
82+
exec(`${adbPrefix} logcat -d --pid=${appPID}`, adbExecOptions, (error, stdout) => {
7783
resolve(filterLogcatFromCutoff(stdout || ""));
7884
});
7985
});
8086
}
8187
// otherwise, do a general logcat read
8288
return new Promise((resolve) => {
8389
console.log('Reading full logcat since app PID is unknown');
84-
exec(`${adbPrefix} logcat -d`, (error, stdout) => {
90+
exec(`${adbPrefix} logcat -d`, adbExecOptions, (error, stdout) => {
8591
resolve(filterLogcatFromCutoff(stdout || ""));
8692
});
8793
});
@@ -97,27 +103,43 @@ async function exitWithLogcatDump() {
97103
}
98104
}
99105

106+
// A single slow or failed adb call on a loaded host is not a crash; only give up after
107+
// several consecutive misses.
108+
const maxConsecutiveLivenessMisses = 3;
109+
let consecutiveLivenessMisses = 0;
110+
let appPID = -1;
111+
112+
// pidof prints "<pid>". API 21-23 images have no pidof, so fall back to their ps, whose rows
113+
// are "<user> <pid> ...".
114+
function parseAppPid(output) {
115+
const text = (output || "").trim();
116+
const match = /^(\d+)/.exec(text) || /^\S+\s+(\d+)/.exec(text);
117+
return match ? parseInt(match[1], 10) : NaN;
118+
}
119+
100120
async function ensureProcessAlive() {
101121
const { stdout } = await execAndStream(
102-
`${adbPrefix} shell "ps | grep ${appId}"`
122+
`${adbPrefix} shell "pidof ${appId} 2>/dev/null || ps | grep ${appId}"`
103123
);
104-
105-
if (!stdout) {
124+
const pid = parseAppPid(stdout);
125+
126+
if (!Number.isFinite(pid)) {
127+
consecutiveLivenessMisses++;
128+
if (consecutiveLivenessMisses < maxConsecutiveLivenessMisses) {
129+
console.log(
130+
`${appId} process not found (${consecutiveLivenessMisses}/${maxConsecutiveLivenessMisses}), checking again`
131+
);
132+
return;
133+
}
106134
console.error(`${appId} process died or never started!`);
107135
await exitWithLogcatDump();
108136
}
109-
await updateAppPID();
110137

111-
console.log(`${appId} process is running`);
112-
}
113-
let appPID = -1;
114-
async function updateAppPID() {
115-
if (appPID !== -1) {
116-
return appPID;
138+
consecutiveLivenessMisses = 0;
139+
if (appPID === -1) {
140+
appPID = pid;
117141
}
118-
const { stdout } = await execAndStream(`${adbPrefix} shell "pidof ${appId}"`);
119-
appPID = parseInt(stdout.trim(), 10);
120-
return appPID;
142+
console.log(`${appId} process is running`);
121143
}
122144

123145
async function checkForErrorActivity() {
@@ -139,32 +161,15 @@ function isCompleteJunitXml(text) {
139161
return /<testsuites[\s>]/.test(trimmed) && trimmed.includes("</testsuites>");
140162
}
141163

164+
// The app writes into its private data dir. `run-as` reads it without root, as
165+
// long as the installed build is debuggable.
142166
async function tryPullResultsFile() {
143-
const { error } = await execAndStream(`${adbPrefix} pull ${resultsPath}`);
144-
145-
if (!error) {
146-
const fs = require("fs");
147-
try {
148-
const text = fs.readFileSync("android_unit_test_results.xml", "utf8");
149-
if (isCompleteJunitXml(text)) {
150-
console.log("Tests results file found!");
151-
process.exit(0);
152-
}
153-
} catch (e) {
154-
// Missing or unreadable; keep polling.
155-
}
156-
}
157-
158-
// Play Store / userdebug-less images reject `adb root` and cannot pull
159-
// /data/data directly. Debug apps can still read their own files via run-as.
160-
const localPath = "android_unit_test_results.xml";
161-
const { error: runAsError, stdout } = await execAndStream(
162-
`${adbPrefix} exec-out run-as ${appId} cat android_unit_test_results.xml`
167+
const { error, stdout } = await execAndStream(
168+
`${adbPrefix} exec-out run-as ${appId} cat ${resultsFileName}`
163169
);
164-
if (!runAsError && isCompleteJunitXml(stdout)) {
165-
const fs = require("fs");
166-
fs.writeFileSync(localPath, stdout);
167-
console.log("Tests results file found via run-as!");
170+
if (!error && isCompleteJunitXml(stdout)) {
171+
require("fs").writeFileSync(resultsFileName, stdout);
172+
console.log("Tests results file found!");
168173
process.exit(0);
169174
}
170175
}

0 commit comments

Comments
 (0)