105 std::chrono::milliseconds timeout = std::chrono::milliseconds(-1))
107 const auto command = program +
" "_L1 + args.join(u' ');
110 fprintf(stdout,
"Execute %s.\n", command.toUtf8().constData());
113 process.start(program, args);
114 if (!process.waitForStarted()) {
115 qCritical(
"Cannot execute command %s.", qPrintable(command));
119 const bool finished = timeout.count() < 0
120 ? process.waitForFinished()
121 : process.waitForFinished(
static_cast<
int>(timeout.count()));
123 qCritical(
"Execution of command %s timed out.", qPrintable(command));
125 process.waitForFinished();
127 const QByteArray stdErr = process.readAllStandardError();
128 if (!stdErr.isEmpty())
129 qWarning().noquote() << stdErr.trimmed();
133 const auto stdOut = process.readAllStandardOutput();
134 const auto stdErr = process.readAllStandardError();
136 if (process.exitCode() != 0) {
138 if (verbose && !stdOut.isEmpty())
139 qWarning().noquote() << stdOut.trimmed();
140 if (!stdErr.isEmpty())
141 qWarning().noquote() << stdErr.trimmed();
146 fprintf(stdout,
"%s\n", stdOut.constData());
149 return stdOut.isNull() ? QByteArray(
"") : stdOut;
282 QCommandLineParser parser;
283 parser.setApplicationDescription(
284 "Runs a Qt for Android test on an emulator or a device. Specify a "
285 "device via --serial, ANDROID_SERIAL or ANDROID_DEVICE_SERIAL.\n"
288 " 0-127 QTest exit code (number of failed test functions)\n"
289 " 250 EXIT_DEVICE_GONE device disconnected\n"
290 " 251 EXIT_NORESULTS result files could not be pulled\n"
291 " 252 EXIT_ANR Android Not Responding\n"
292 " 253 EXIT_NOEXITCODE exit code could not be read from device\n"
293 " 254 EXIT_ERROR generic runner failure"_L1);
295 QCommandLineOption pathOpt(
296 "path"_L1,
"Path where the Android Gradle package is built."_L1,
"path"_L1);
297 QCommandLineOption makeOpt(
298 "make"_L1,
"make command to build the APK."_L1,
"command"_L1);
299 QCommandLineOption apkOpt(
300 "apk"_L1,
"Test APK path. Built via --make if absent."_L1,
"path"_L1);
301 QCommandLineOption aabOpt(
302 "aab"_L1,
"Test AAB path. Built via --make if absent."_L1,
"path"_L1);
303 QCommandLineOption bundletoolOpt(
304 "bundletool"_L1,
"Path to Android bundletool jar."_L1,
"path"_L1);
305 QCommandLineOption manifestOpt(
306 "manifest"_L1,
"Custom AndroidManifest.xml path."_L1,
"path"_L1);
307 QCommandLineOption adbOpt(
308 "adb"_L1,
"Path to adb. Falls back to $PATH."_L1,
"command"_L1,
"adb"_L1);
309 QCommandLineOption serialOpt(
311 "Android device serial. Overrides ANDROID_SERIAL / ANDROID_DEVICE_SERIAL."_L1,
313 QCommandLineOption activityOpt(
314 "activity"_L1,
"Activity to run. Defaults to the first in the manifest."_L1,
"name"_L1);
315 QCommandLineOption timeoutOpt(
316 "timeout"_L1,
"Test timeout in seconds (default 600)."_L1,
"seconds"_L1,
"600"_L1);
317 QCommandLineOption preTestAdbOpt(
"pre-test-adb-command"_L1,
318 "adb command to run after install, before test."_L1,
"command"_L1);
319 QCommandLineOption skipInstallRootOpt(
320 "skip-install-root"_L1,
321 "Don't append INSTALL_ROOT=... to --make. Only honored for make-family "
322 "tools (make, gmake, nmake, mingw32-make, jom)."_L1);
323 QCommandLineOption ndkStackOpt(
324 "ndk-stack"_L1,
"Path to ndk-stack (default: ndk-stack under $ANDROID_NDK_ROOT "
325 "or $ANDROID_NDK_HOME)."_L1,
"path"_L1);
326 QCommandLineOption showLogcatOpt(
327 "show-logcat"_L1,
"Print logcat output (+ system_server on ANR)."_L1);
328 QCommandLineOption verboseOpt(
329 "verbose"_L1,
"Print extra information."_L1);
330 QCommandLineOption helpOpt(
"help"_L1,
"Show this help message."_L1);
332 const QList<QCommandLineOption> ourOptions = {
333 pathOpt, makeOpt, apkOpt, aabOpt,
334 bundletoolOpt, manifestOpt,
336 activityOpt, timeoutOpt, preTestAdbOpt,
338 ndkStackOpt, showLogcatOpt, verboseOpt,
341 parser.addOptions(ourOptions);
342 parser.addPositionalArgument(
"testargs"_L1,
"Arguments forwarded to the test."_L1,
345 QSet<QString> knownOpts;
346 QSet<QString> valueOpts;
347 for (
const QCommandLineOption &opt : ourOptions) {
348 const bool takesValue = !opt.valueName().isEmpty();
349 for (
const QString &name : opt.names()) {
350 knownOpts.insert(name);
352 valueOpts.insert(name);
356 const QStringList processedArgs =
357 splitOwnAndTestArgs(QCoreApplication::arguments(), knownOpts, valueOpts);
358 if (processedArgs.isEmpty())
360 if (!parser.parse(processedArgs)) {
361 qCritical(
"%s", qPrintable(parser.errorText()));
364 if (parser.isSet(helpOpt))
367 g_options.buildPath = parser.value(pathOpt);
368 g_options.makeCommand = parser.value(makeOpt);
369 if (!collectPackagePaths(parser.values(apkOpt), parser.values(aabOpt)))
371 g_options.adbCommand = parser.value(adbOpt);
372 g_options.activity = parser.value(activityOpt);
373 g_options.serial = parser.value(serialOpt);
374 bool timeoutOk =
false;
377 qCritical(
"--timeout must be a positive integer (got '%s').",
378 qPrintable(parser.value(timeoutOpt)));
383 g_options.ndkStackPath = parser.value(ndkStackOpt);
385 g_options.manifestPath = parser.value(manifestOpt);
386 g_options.bundletoolPath = parser.value(bundletoolOpt);
388 for (
const QString &cmd : parser.values(preTestAdbOpt))
389 g_options.preTestRunAdbCommands += QProcess::splitCommand(cmd);
390 g_options.testArgsList = parser.positionalArguments();
392 static const QStringList makeNames = {
393 "make"_L1,
"gmake"_L1,
"nmake"_L1,
"mingw32-make"_L1,
"jom"_L1,
395 const QStringList makeParts = QProcess::splitCommand(g_options.makeCommand);
396 const QString makeBaseName = QFileInfo(makeParts.value(0)).baseName();
397 const bool makeIsGnuMakeFamily = makeNames.contains(makeBaseName, Qt::CaseInsensitive);
399 g_options.makeCommand =
"%1 INSTALL_ROOT=%2 install"_L1
400 .arg(g_options.makeCommand, QDir::toNativeSeparators(g_options.buildPath));
404 qCritical(
"--path and --apk (or --aab) are required.");
405 fputs(qPrintable(parser.helpText()), stderr);
409 if (!
g_options.packagePath.endsWith(
".apk"_L1)
410 && !
g_options.packagePath.endsWith(
".aab"_L1)) {
411 qCritical(
"Package path '%s' must end with .apk or .aab.",
416 if (
g_options.packagePath.endsWith(
".aab"_L1)) {
417 if (
g_options.bundletoolPath.isEmpty()) {
418 qCritical(
"--aab requires --bundletool to locate the bundletool jar.");
421 if (!QFile::exists(g_options.bundletoolPath)) {
422 qCritical(
"--bundletool path '%s' does not exist.",
429 g_options.serial = qEnvironmentVariable(
"ANDROID_SERIAL");
431 g_options.serial = qEnvironmentVariable(
"ANDROID_DEVICE_SERIAL");
471 QString gradlew = androidBuildDir +
"/gradlew.bat"_L1;
473 QString gradlew = androidBuildDir +
"/gradlew"_L1;
475 if (!QFile::exists(gradlew))
478 const QString scriptPath = gradleInitScriptPath();
479 if (scriptPath.isEmpty())
483 process.setWorkingDirectory(androidBuildDir);
484 process.start(gradlew, {
"-q"_L1,
"--init-script"_L1, scriptPath,
485 "-Pproperty="_L1 + property,
"printProjectProperty"_L1 });
487 if (!process.waitForFinished()) {
488 qWarning(
"gradlew '%s' timed out.", qPrintable(property));
490 process.waitForFinished();
493 if (process.exitCode() != 0) {
494 qWarning(
"gradlew '%s' exited with %d:\n%s", qPrintable(property),
495 process.exitCode(), process.readAllStandardError().constData());
498 return QString::fromUtf8(process.readAllStandardOutput()).trimmed();
504 if (!QFile::exists(g_options.manifestPath)) {
505 qCritical(
"--manifest path '%s' does not exist.",
510 const QStringList candidates = {
511 g_options.buildPath +
"/AndroidManifest.xml"_L1,
512 g_options.buildPath +
"/app/AndroidManifest.xml"_L1
514 for (
const QString &candidate : candidates) {
515 if (QFile::exists(candidate)) {
516 g_options.manifestPath = candidate;
522 qCritical(
"Unable to find AndroidManifest.xml at '%s'.", qPrintable(
g_options.buildPath));
525 QFile androidManifestXml(
g_options.manifestPath);
526 if (!androidManifestXml.open(QIODevice::ReadOnly)) {
527 qCritical(
"Unable to read android manifest '%s'", qPrintable(
g_options.manifestPath));
531 QXmlStreamReader reader(&androidManifestXml);
532 while (!reader.atEnd()) {
534 if (!reader.isStartElement())
537 if (reader.name() ==
"activity"_L1 && g_options.activity.isEmpty())
538 g_options.activity = reader.attributes().value(
"android:name"_L1).toString();
539 else if (reader.name() ==
"uses-permission"_L1)
540 g_options.permissions.append(reader.attributes().value(
"android:name"_L1).toString());
547 const QStringList args({
"shell"_L1,
"dumpsys"_L1,
"package"_L1,
"permissions"_L1 });
548 const QByteArray output = execAdbCommand(args,
false);
549 if (output.isNull()) {
550 qWarning(
"Failed to query permissions via dumpsys");
555
556
557
558
559
560
561
562
563 const static QRegularExpression regex(
"^\\s*Permission\\s+\\[([^\\]]+)\\]\\s+\\([^)]+\\):"_L1);
564 QStringList dangerousPermissions;
567 const QStringList lines = QString::fromUtf8(output).split(u'\n');
568 for (
const QString &line : lines) {
569 QRegularExpressionMatch match = regex.match(line);
570 if (match.hasMatch()) {
571 currentPerm = match.captured(1);
575 if (currentPerm.isEmpty())
578 int protIndex = line.indexOf(
"prot="_L1);
582 QString protectionTypes = line.mid(protIndex + 5).trimmed();
583 if (protectionTypes.contains(
"dangerous"_L1, Qt::CaseInsensitive))
584 dangerousPermissions.append(currentPerm);
588 return dangerousPermissions;
614 QRegularExpression oldFormats{
"^-(txt|csv|xunitxml|junitxml|xml|lightxml|teamcity|tap)$"_L1};
615 QRegularExpression newLoggingFormat{
"^(.*),(txt|csv|xunitxml|junitxml|xml|lightxml|teamcity|tap)$"_L1};
619 QStringList unhandledArgs;
620 for (
int i = 0; i <
g_options.testArgsList.size(); ++i) {
621 const QString &arg =
g_options.testArgsList[i].trimmed();
624 if (arg ==
"-o"_L1 || arg ==
"--output"_L1) {
625 if (i >=
g_options.testArgsList.size() - 1)
628 const auto &filePath =
g_options.testArgsList[++i];
629 const auto match = newLoggingFormat.match(filePath);
630 if (!match.hasMatch()) {
633 const auto capturedTexts = match.capturedTexts();
634 setOutputFile(capturedTexts.at(1), capturedTexts.at(2));
637 auto match = oldFormats.match(arg);
638 if (match.hasMatch()) {
639 logType = match.capturedTexts().at(1);
643 QString quotedArg = QString(arg).replace(
"\""_L1,
"\\\"\\\"\\\""_L1);
645 unhandledArgs <<
" \\\"%1\\\""_L1.arg(quotedArg);
649 if (
g_options.outFiles.isEmpty() || !file.isEmpty() || !logType.isEmpty())
650 setOutputFile(file, logType);
653 for (
auto it =
g_options.outFiles.constBegin(); it !=
g_options.outFiles.constEnd(); ++it)
654 testAppArgs +=
"-o %1,%2 "_L1.arg(deviceOutputFileName(it.key(), it.value()), it.key());
656 testAppArgs += unhandledArgs.join(u' ').trimmed();
657 testAppArgs =
"\"%1\""_L1.arg(testAppArgs.trimmed());
658 const QString activityName =
"%1/%2"_L1.arg(g_options.package).arg(g_options.activity);
661 QStringList testEnvVarArgs;
662 const QStringList envVarsList = QProcessEnvironment::systemEnvironment().toStringList();
663 for (
const QString &var : envVarsList) {
664 if (!var.startsWith(
"QTEST_"_L1) && !var.startsWith(
"QT_"_L1))
666 const qsizetype index = var.indexOf(u'=');
669 const QString key = var.left(index);
670 QString escapedValue = var.mid(index + 1);
671 escapedValue.replace(
"'"_L1,
"'\\''"_L1);
672 const QString value =
"'%1'"_L1.arg(escapedValue);
673 testEnvVarArgs <<
"-e"_L1 << (
"extraenvvars_"_L1 + key) << value;
676 g_options.amStarttestArgs = {
"shell"_L1,
"am"_L1,
"start"_L1,
"-W"_L1,
677 "-n"_L1, activityName,
678 "-e"_L1,
"applicationArguments"_L1, testAppArgs };
679 g_options.amStarttestArgs.append(testEnvVarArgs);
945 if (logcat.isEmpty())
948 QByteArray crashLogcat(logcat);
950 qWarning() <<
"Warning: ndk-stack path not provided and couldn't be deduced "
951 "using the ANDROID_NDK_ROOT or ANDROID_NDK_HOME environment "
953 }
else if (
const QString libsPath = getAbiLibsPath(); libsPath.isEmpty()) {
954 qWarning() <<
"Warning: could not determine the device ABI, "
955 "skipping ndk-stack and printing the raw dump.";
957 QProcess ndkStackProc;
958 ndkStackProc.start(
g_options.ndkStackPath, {
"-sym"_L1, libsPath });
960 if (ndkStackProc.waitForStarted()) {
961 ndkStackProc.write(crashLogcat);
962 ndkStackProc.closeWriteChannel();
965 if (ndkStackProc.waitForFinished()) {
967 const QByteArray ndkOutput = ndkStackProc.readAllStandardOutput();
968 if (!ndkOutput.trimmed().isEmpty())
969 crashLogcat = ndkOutput;
971 qCritical() <<
"Error: ndk-stack command timed out.";
973 ndkStackProc.waitForFinished();
976 qCritical() <<
"Error: failed to run ndk-stack command.";
980 if (crashLogcat.startsWith(
"********** Crash dump")) {
981 qDebug().noquote() << crashLogcat.trimmed();
983 qDebug() <<
"[androidtestrunner] ********** BEGIN crash dump **********";
984 qDebug().noquote() << crashLogcat.trimmed();
985 qDebug() <<
"[androidtestrunner] ********** END crash dump **********";
995 using namespace std::chrono_literals;
998 QStringList logcatArgs = {
"shell"_L1,
"logcat"_L1,
999 "-b"_L1,
"main,system,crash"_L1,
1000 "-v"_L1,
"brief"_L1 };
1002 if (!timeStamp.isEmpty())
1003 logcatArgs <<
"-t"_L1 <<
"'%1'"_L1.arg(timeStamp);
1005 logcatArgs <<
"-t"_L1 <<
"5000"_L1;
1006 const bool useColor = !QTestCiDetect::ciInTestEnvironment();
1008 logcatArgs <<
"-v"_L1 <<
"color"_L1;
1010 QByteArray logcat = execAdbCommand(logcatArgs,
false);
1011 if (logcat.isNull())
1012 qWarning() <<
"Warning: failed to fetch logcat of the test";
1014 if (!waitForDiagnostics)
1017 const QByteArray anrMarker =
"ANR in " +
g_options.package.toUtf8();
1023 constexpr auto timeout = 15s;
1025 polled = execAdbCommand(logcatArgs,
false);
1026 return !polled.isNull()
1027 && (polled.contains(crashBannerMarker) || polled.contains(anrMarker));
1028 }, QDeadlineTimer(timeout), 250ms);
1029 if (!polled.isEmpty())
1030 logcat =
std::move(polled);
1031 if (!found && !
g_testInfo.isTestRunnerInterrupted.load()) {
1032 qWarning().noquote() << QString::fromLatin1(
"[androidtestrunner] No crash banner or "
1033 "ANR marker found in logcat within %1s; output below may be incomplete.")
1034 .arg(timeout.count());
1055 static const QRegularExpression logcatRegEx{
1056 "(?:^\\x1B\\[[0-9;]*m)?"
1059 "(\\(\\s*\\d*\\)):"
1062 "(?:\\x1B\\[[0-9;]*m)?"
1065 QByteArrayList kept;
1066 for (
const QByteArray &line : logcat.split(u'\n')) {
1067 QRegularExpressionMatch match = logcatRegEx.match(QString::fromUtf8(line));
1068 if (!match.hasMatch()) {
1073 const QString msgType = match.captured(1);
1074 const QString pidStr = match.captured(2);
1075 const int capturedPid = pidStr.mid(1, pidStr.size() - 2).trimmed().toInt();
1076 const bool isFatal = msgType == u'F';
1077 const bool isOurTest = capturedPid == testPid;
1078 const bool isAnrSource = systemServerPid > 0 && capturedPid == systemServerPid;
1079 if (isOurTest || isFatal || isAnrSource)
1082 return kept.join(
'\n');
1088 && !
g_testInfo.isTestRunnerInterrupted.load();
1089 QByteArray logcat = fetchLogcat(timeStamp, wasAbnormal);
1090 if (logcat.isEmpty()) {
1092 qWarning() <<
"The retrieved logcat is empty";
1096 const QByteArray crashDump = takeCrashDump(&logcat);
1098 const bool anrOccurred = logcat.contains(
1099 "ANR in %1"_L1.arg(g_options.package).toUtf8());
1105 qCritical(
"[androidtestrunner] An ANR has occurred while running the test '%s';"
1106 " consult logcat for additional logs from the system_server process",
1110 const int systemServerPid = anrOccurred ? getPid(
"system_server"_L1) : -1;
1111 const QByteArray filtered = filterTestLogcat(logcat, g_testInfo.pid, systemServerPid);
1116 && !
g_testInfo.isTestRunnerInterrupted.load();
1118 qDebug() <<
"[androidtestrunner] ********** BEGIN logcat dump **********";
1119 qDebug().noquote() << filtered.trimmed();
1120 qDebug() <<
"[androidtestrunner] ********** END logcat dump **********";
1122 if (testCrashed && !crashDump.isEmpty())
1123 printLogcatCrash(crashDump);
1184 using namespace std::chrono_literals;
1188 QCoreApplication a(argc, argv);
1193 qCritical() <<
"It is required to provide a make command with the \"--make\" parameter "
1194 "to generate the apk.";
1198 if (execCommand(
g_options.makeCommand,
true, g_options.timeoutSecs * 1s).isNull()) {
1199 qCritical(
"The APK build command \"%s\" failed.", qPrintable(
g_options.makeCommand));
1203 if (!QFile::exists(g_options.packagePath)) {
1204 qCritical(
"No package \"%s\" found after running the make command. "
1205 "Check the provided path and the make command.",
1210 const std::optional<QStringList> devices = runningDevices();
1212 qCritical(
"Failed to query connected devices via 'adb devices'.");
1214 }
else if (devices->isEmpty()) {
1215 qCritical(
"No connected devices or running emulators can be found.");
1218 qCritical(
"No connected device or running emulator with serial '%s' can be found.",
1221 }
else if (
g_options.serial.isEmpty() && devices->size() == 1) {
1223 }
else if (
g_options.serial.isEmpty()) {
1224 qCritical(
"Multiple devices connected, set ANDROID_SERIAL or ANDROID_DEVICE_SERIAL.");
1235 const QString ns = getGradleProjectProperty(g_options.buildPath,
"android.namespace"_L1);
1240 qCritical(
"Unable to get package name for '%s'", qPrintable(
g_options.packagePath));
1249 const QString user = qEnvironmentVariable(
"USER",
1250 qEnvironmentVariable(
"USERNAME", u"default"_s));
1251 const QString lockName = u"androidtestrunner-%1-%2.lock"_s.arg(user, g_options.serial);
1252 const QDir tempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
1253 QLockFile testRunnerLock(tempDir.absoluteFilePath(lockName));
1254 testRunnerLock.setStaleLockTime(0);
1255 if (!testRunnerLock.lock()) {
1256 qCritical(
"Failed to acquire test runner lock for '%s'.", qPrintable(
g_options.serial));
1260 if (
g_options.packagePath.endsWith(
".apk"_L1)) {
1261 const QStringList installArgs = {
"install"_L1,
"-r"_L1, g_options.packagePath };
1262 if (execAdbCommand(installArgs,
true, 5min).isNull())
1264 }
else if (
g_options.packagePath.endsWith(
".aab"_L1)) {
1266 const auto apksFilePath = aab.absoluteDir().absoluteFilePath(aab.baseName() +
".apks"_L1);
1267 QStringList installApksArgs = {
"install-apks"_L1,
"--apks"_L1, apksFilePath };
1268 if (!g_options.serial.isEmpty())
1269 installApksArgs <<
"--device-id"_L1 << g_options.serial;
1270 if (execBundletoolCommand({
"build-apks"_L1,
"--bundle"_L1, g_options.packagePath,
1271 "--output"_L1, apksFilePath,
"--local-testing"_L1,
1272 "--overwrite"_L1 }).isNull()
1273 || execBundletoolCommand(installApksArgs).isNull())
1278 const QStringList dangerousPermissions = queryDangerousPermissions();
1279 for (
const auto &permission : g_options.permissions) {
1280 if (!dangerousPermissions.contains(permission))
1283 if (execAdbCommand({
"shell"_L1,
"pm"_L1,
"grant"_L1,
"--user"_L1, g_testInfo.userId,
1284 g_options.package, permission }).isNull()) {
1285 qWarning(
"Unable to grant '%s' to '%s'. Probably the Android version mismatch.",
1286 qPrintable(permission), qPrintable(g_options.package));
1291 for (
const auto &command : g_options.preTestRunAdbCommands) {
1292 if (execAdbCommand(command).isNull()) {
1293 qCritical(
"The pre test ADB command \"%s\" failed.",
1294 qUtf8Printable(command.join(u' ')));
1300 const QString formattedStartTime = getCurrentTimeString();
1303 if (execAdbCommand(
g_options.amStarttestArgs).isNull()) {
1307 analyseLogcat(formattedStartTime, &exitCode);
1314 qWarning(
"Continuing without live stdout streaming; result files are still pulled.");
1319 qCritical(
"[androidtestrunner] Device '%s' became unreachable during the test, "
1320 "result transfer and uninstall skipped.", qPrintable(
g_options.serial));
1332 analyseLogcat(formattedStartTime, &exitCode);
1336 qCritical(
"[androidtestrunner] Device '%s' became unreachable during cleanup, "
1337 "uninstall skipped.", qPrintable(
g_options.serial));
1344 qWarning(
"Failed to uninstall test package '%s'. The test exit code is preserved.",
1348 if (
g_testInfo.isTestRunnerInterrupted.load()) {
1349 qCritical() <<
"The androidtestrunner was interrupted and the test was cleaned up.";