245int main(
int argc,
char *argv[])
250 QCoreApplication app(argc, argv);
251 app.setApplicationName(u"harmonyostestrunner"_s);
252 app.setApplicationVersion(QString::fromLatin1(QT_VERSION_STR));
254 QCommandLineParser parser;
255 parser.setApplicationDescription(
256 u"Runs a single Qt auto test from an installed HarmonyOS test bundle HAP."_s);
257 parser.addHelpOption();
258 parser.addVersionOption();
260 parser.addPositionalArgument(
262 u"Path to the test shared library (e.g. /path/to/libtst_qobject.so)"_s);
264 QCommandLineOption bundleNameOpt(
266 u"HarmonyOS bundle name of the installed test HAP (env: QT_HARMONYOS_BUNDLE_NAME)"_s,
268 qEnvironmentVariable(
"QT_HARMONYOS_BUNDLE_NAME", u"org.qtproject.autotests"_s));
269 parser.addOption(bundleNameOpt);
271 QCommandLineOption abilityNameOpt(
273 u"HarmonyOS ability name inside the test HAP (env: QT_HARMONYOS_ABILITY_NAME)"_s,
275 qEnvironmentVariable(
"QT_HARMONYOS_ABILITY_NAME", u"QAbility"_s));
276 parser.addOption(abilityNameOpt);
278 QCommandLineOption hdcOpt(
280 u"Path to the hdc tool (env: QT_HARMONYOS_HDC)"_s,
282 qEnvironmentVariable(
"QT_HARMONYOS_HDC", u"hdc"_s));
283 parser.addOption(hdcOpt);
285 QCommandLineOption timeoutOpt(
287 u"Seconds to wait for a test to complete before aborting (env: QT_HARMONYOS_TEST_TIMEOUT)"_s,
289 qEnvironmentVariable(
"QT_HARMONYOS_TEST_TIMEOUT", u"300"_s));
290 parser.addOption(timeoutOpt);
292 QCommandLineOption noProgressTimeoutOpt(
293 u"no-progress-timeout"_s,
294 u"Seconds without a PASS/FAIL test case result before declaring the test hung "
295 u"(env: QT_HARMONYOS_NO_PROGRESS_TIMEOUT, 0 = disabled)"_s,
297 qEnvironmentVariable(
"QT_HARMONYOS_NO_PROGRESS_TIMEOUT", u"60"_s));
298 parser.addOption(noProgressTimeoutOpt);
300 QCommandLineOption deviceOpt(
302 u"hdc connect key (-t) for the target device — required when multiple devices "
303 u"are attached (env: QT_HARMONYOS_DEVICE)"_s,
305 qEnvironmentVariable(
"QT_HARMONYOS_DEVICE"));
306 parser.addOption(deviceOpt);
308 QCommandLineOption testConfigOpt(
310 u"Generated test bundle deployment settings, read for the system dialogs the runner has "
311 u"to answer (env: QT_HARMONYOS_TEST_CONFIG)"_s,
313 qEnvironmentVariable(
"QT_HARMONYOS_TEST_CONFIG"));
314 parser.addOption(testConfigOpt);
316 QCommandLineOption testEnvOpt(
318 u"Semicolon-separated NAME=VALUE pairs to set in the test environment "
319 u"(env: QT_HARMONYOS_TEST_ENV)"_s,
321 qEnvironmentVariable(
"QT_HARMONYOS_TEST_ENV"));
322 parser.addOption(testEnvOpt);
327 const QStringList positional = parser.positionalArguments();
328 if (positional.isEmpty()) {
329 fprintf(stderr,
"harmonyostestrunner: no test binary specified\n");
333 const QString testBinaryPath = positional.first();
334 const QString testLibName = QFileInfo(testBinaryPath).fileName();
336 const QStringList testArgs = positional.mid(1);
337 const QString bundleName = parser.value(bundleNameOpt);
338 const QString abilityName = parser.value(abilityNameOpt);
339 const Hdc hdc(parser.value(hdcOpt), parser.value(deviceOpt));
340 if (hdc.version().isEmpty()) {
341 fprintf(stderr,
"harmonyostestrunner: cannot run hdc '%s', set --hdc or "
342 "QT_HARMONYOS_HDC\n", qPrintable(parser.value(hdcOpt)));
345 const std::chrono::seconds timeout{ parser.value(timeoutOpt).toInt() };
346 const std::chrono::seconds noProgressTimeout{ parser.value(noProgressTimeoutOpt).toInt() };
350 const QString runId = QString::number(QDateTime::currentMSecsSinceEpoch());
352 const QString stdoutFilePrefix = u"qt_stdout_"_s;
353 const QString exitCodeFilePrefix = u"qt_exitcode_"_s;
355 const QString appBase = u"/data/storage/el2/base/files"_s;
356 const QString appStdoutPath = appBase + u"/"_s + stdoutFilePrefix + runId + u".txt"_s;
357 const QString appExitCodePath = appBase + u"/"_s + exitCodeFilePrefix + runId + u".txt"_s;
359 const QString shellBase = u"/data/app/el2/100/base/"_s + bundleName + u"/files"_s;
360 const QString shellStdoutPath = shellBase + u"/"_s + stdoutFilePrefix + runId + u".txt"_s;
361 const QString shellExitCodePath = shellBase + u"/"_s + exitCodeFilePrefix + runId + u".txt"_s;
363 const QTemporaryDir localCopyDir;
364 if (!localCopyDir.isValid()) {
365 fprintf(stderr,
"harmonyostestrunner: cannot create a local directory for the test "
366 "output: %s\n", qPrintable(localCopyDir.errorString()));
370 hdc, shellStdoutPath, localCopyDir.filePath(u"stdout.txt"_s));
372 const BundleState bundleState = queryBundleState(hdc, bundleName);
374 fprintf(stderr,
"harmonyostestrunner: warning: hdc did not answer the bundle check, "
375 "continuing without it\n");
379 "harmonyostestrunner: bundle '%s' is not installed on the device.\n"
380 " Build and sign the test HAP, then install it with:\n"
381 " hdc install <path/to/autotests-signed.hap>\n",
382 qPrintable(bundleName));
386#if QT_CONFIG(systemsemaphore)
387 TestRunnerSystemSemaphore runnerLock(runnerLockKey(hdc.connectKey(), bundleName));
388 g_runnerLock = &runnerLock;
389 runnerLock.acquire();
392 forceStopBundle(hdc, bundleName);
393 waitForProcessDeath(hdc, bundleName);
395 removeFilesByName(hdc, shellBase,
396 { stdoutFilePrefix + u"*.txt"_s, exitCodeFilePrefix + u"*.txt"_s });
399 QStringList aaStartCommand = {
402 u"-a"_s, abilityName,
403 u"--ps"_s, u"io.qt.appSharedLibNameOverride"_s, testLibName,
404 u"--ps"_s, u"io.qt.debug.redirectedStdoutPath"_s, appStdoutPath,
405 u"--ps"_s, u"io.qt.debug.exitCodePath"_s, appExitCodePath,
407 u"--pb"_s, u"io.qt.useDefaultUiAbilityInstanceInQt"_s, u"false"_s,
410 aaStartCommand << u"--pb"_s << u"io.qt.watchdogEnabled"_s << u"false"_s;
412 if (!testArgs.isEmpty()) {
413 const QString json = QString::fromUtf8(
414 QJsonDocument(QJsonArray::fromStringList(testArgs)).toJson(QJsonDocument::Compact));
415 aaStartCommand += {u"--ps"_s, u"io.qt.appArgsJson"_s, shellSingleQuote(json)};
418 const QString testEnv = parser.value(testEnvOpt);
419 if (!testEnv.isEmpty()) {
420 QJsonObject envVarsObject;
421 for (
const QString &pair : testEnv.split(u';', Qt::SkipEmptyParts)) {
422 const qsizetype eq = pair.indexOf(u'=');
424 fprintf(stderr,
"harmonyostestrunner: ignoring malformed --test-env entry "
425 "(expected NAME=VALUE): %s\n", qPrintable(pair));
428 envVarsObject.insert(pair.left(eq), pair.mid(eq + 1));
430 const QString json = QString::fromUtf8(
431 QJsonDocument(envVarsObject).toJson(QJsonDocument::Compact));
432 aaStartCommand += {u"--ps"_s, u"io.qt.envVarsJson"_s, shellSingleQuote(json)};
435 const q23::expected<
void, QString> started =
436 startAbility(hdc, aaStartCommand, bundleName, shellExitCodePath);
438 fprintf(stderr,
"harmonyostestrunner: %s: %s\n", qPrintable(testLibName),
439 qPrintable(started.error()));
440#if QT_CONFIG(systemsemaphore)
441 runnerLock.release();
446 waitForStdoutFile(hdc, shellStdoutPath);
450 constexpr auto pollInterval = 500ms;
451 constexpr auto loopStallThreshold = 30s;
452 constexpr auto heartbeatInterval = 30s;
454 QElapsedTimer elapsed;
456 int testExitCode = -1;
457 bool completed =
false;
458 int aliveCheckCounter = 0;
459 std::optional<
std::chrono::nanoseconds> lastTestProgressAt;
460 std::chrono::nanoseconds lastSuccessfulCopyAt {};
461 std::chrono::seconds lastHeartbeatAt {};
462 std::chrono::nanoseconds lastLoopPassAt {};
463 BlockingTestDialogs blockingTestDialogs(parser.value(testConfigOpt), hdc);
464 std::chrono::nanoseconds lastOutputAt {};
466 while (!
g_interrupted.load() && elapsed.durationElapsed() < timeout) {
467 const std::chrono::nanoseconds loopPassAt = elapsed.durationElapsed();
468 if (loopPassAt - lastLoopPassAt > loopStallThreshold) {
469 fprintf(stderr,
"harmonyostestrunner: %s: poll loop stalled for %lld ms\n",
470 qPrintable(testLibName),
471 static_cast<
long long>((loopPassAt - lastLoopPassAt) / 1ms));
473 lastLoopPassAt = loopPassAt;
476 const q23::expected<QByteArray, QString> chunk = outputForwarder.forwardAvailable();
478 lastSuccessfulCopyAt = elapsed.durationElapsed();
480 fprintf(stderr,
"harmonyostestrunner: warning: could not copy the test output "
481 "(%s)\n", qPrintable(chunk.error()));
483 if (chunk && !chunk->isEmpty()) {
487 lastOutputAt = elapsed.durationElapsed();
488 if (chunk->contains(
"PASS :") || chunk->contains(
"FAIL! :")
489 || chunk->contains(
"Totals:"))
490 lastTestProgressAt = elapsed.durationElapsed();
496 const QString exitContent =
497 readDeviceFile(hdc, shellExitCodePath);
499 const int code = exitContent.trimmed().toInt(&ok);
507 answerBlockingDialogsIfStalled(blockingTestDialogs, elapsed, lastOutputAt);
511 if (++aliveCheckCounter % 3 == 0
512 && queryProcessState(hdc, bundleName) == ProcessState::NotRunning) {
513 const QString exitContent =
514 readDeviceFile(hdc, shellExitCodePath);
516 const int code = exitContent.trimmed().toInt(&ok);
523 fprintf(stderr,
"harmonyostestrunner: %s: process exited without writing "
524 "exit code — likely crashed\n", qPrintable(testLibName));
530 if (noProgressTimeout > 0s && lastTestProgressAt
531 && lastSuccessfulCopyAt - *lastTestProgressAt > noProgressTimeout)
534 "harmonyostestrunner: %s: no test case progress for %lld seconds (limit %lld) "
535 "— main thread likely deadlocked, force-stopping\n",
536 qPrintable(testLibName),
537 static_cast<
long long>((lastSuccessfulCopyAt - *lastTestProgressAt) / 1s),
538 static_cast<
long long>(noProgressTimeout.count()));
539 forceStopBundle(hdc, bundleName);
545 const auto elapsedSeconds =
546 std::chrono::duration_cast<std::chrono::seconds>(elapsed.durationElapsed());
547 if (elapsedSeconds >= lastHeartbeatAt + heartbeatInterval) {
548 fprintf(stderr,
"harmonyostestrunner: %s still running (%lld s elapsed)\n",
549 qPrintable(testLibName),
static_cast<
long long>(elapsedSeconds.count()));
550 lastHeartbeatAt = elapsedSeconds;
553 QThread::sleep(pollInterval);
561 "harmonyostestrunner: TIMEOUT — %s did not complete within %lld seconds\n",
562 qPrintable(testLibName),
static_cast<
long long>(timeout.count()));
564 forceStopBundle(hdc, bundleName);
567 const bool outputComplete = outputForwarder.forwardRemaining(
572#if QT_CONFIG(systemsemaphore)
573 runnerLock.release();
578 if (testExitCode == 0 && !outputComplete)