qt_clean_probe.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. // This harness instantiates the actual MainWindow and clicks its real buttons.
  2. // Default mode is read-only. Only --mode start invokes physical host controls.
  3. #include "mainwindow.h"
  4. #include "backendlink.h"
  5. #include "stationdata.h"
  6. #include "localplans.h"
  7. #include <QAbstractButton>
  8. #include <QCheckBox>
  9. #include <QApplication>
  10. #include <QCommandLineParser>
  11. #include <QDateTime>
  12. #include <QDir>
  13. #include <QFile>
  14. #include <QFontDatabase>
  15. #include <QJsonArray>
  16. #include <QJsonDocument>
  17. #include <QJsonObject>
  18. #include <QLabel>
  19. #include <QLineEdit>
  20. #include <QPointer>
  21. #include <QPlainTextEdit>
  22. #include <QSaveFile>
  23. #include <QTemporaryDir>
  24. #include <QTimer>
  25. #include <QWebSocket>
  26. #include <QWebSocketServer>
  27. #include <functional>
  28. static bool writeJson(const QString &path, const QJsonObject &value)
  29. {
  30. QSaveFile file(path);
  31. const QByteArray bytes = QJsonDocument(value).toJson(QJsonDocument::Indented);
  32. return file.open(QIODevice::WriteOnly) && file.write(bytes) == bytes.size() && file.commit();
  33. }
  34. class Fixture : public QObject
  35. {
  36. public:
  37. QWebSocketServer server{QStringLiteral("Qt clean contract fixture"), QWebSocketServer::NonSecureMode};
  38. QPointer<QWebSocket> socket;
  39. int connections = 0;
  40. int starts = 0;
  41. int actions = 0;
  42. bool duplicate = false;
  43. bool unexpected = false;
  44. bool correctParams = true;
  45. bool disconnectTest = false;
  46. bool silentMode = false;
  47. bool runAmt = false;
  48. bool amtResultsReady = false;
  49. bool earlyAmtExit = false;
  50. int amtLaunches = 0;
  51. bool failAtEnd = false;
  52. bool unexpectedBootMode = false;
  53. bool changedBoot = false;
  54. bool oldFailedSnapshotSent = false;
  55. int uartReplays = 0;
  56. QStringList methods;
  57. QSet<QString> inputIds;
  58. QJsonObject command;
  59. QJsonArray events;
  60. int step = -1;
  61. qint64 started = 0;
  62. quint64 sequence = 0;
  63. explicit Fixture(bool testAmt = false) : runAmt(testAmt)
  64. {
  65. server.listen(QHostAddress::LocalHost, 0);
  66. connect(&server, &QWebSocketServer::newConnection, this, [this] {
  67. socket = server.nextPendingConnection();
  68. ++connections;
  69. QWebSocket *client = socket;
  70. connect(client, &QWebSocket::textMessageReceived, this, [this](const QString &text) { receive(text); });
  71. connect(client, &QWebSocket::disconnected, client, &QObject::deleteLater);
  72. pushState();
  73. if (silentMode) return; // Deliberately silent TCP peer: exercise client watchdog.
  74. // A fresh socket starts from byte zero. BackendLink must suppress
  75. // already displayed bytes and recover anything missed offline.
  76. for (const QJsonValue &row : events) send(row.toObject());
  77. ++uartReplays;
  78. });
  79. }
  80. QString url() const { return QStringLiteral("ws://127.0.0.1:%1/ws?view=qt-clean").arg(server.serverPort()); }
  81. void send(const QJsonObject &frame)
  82. {
  83. if (socket && socket->state() == QAbstractSocket::ConnectedState)
  84. socket->sendTextMessage(QString::fromUtf8(QJsonDocument(frame).toJson(QJsonDocument::Compact)));
  85. }
  86. QJsonObject station() const
  87. {
  88. QString stage, phase = QStringLiteral("uefi"), action;
  89. int cpu = 0;
  90. if (step == 0 || step == 1) { stage = "uip1"; phase = "uip"; action = "continue_uip"; cpu = step; }
  91. else if (step == 2 || step == 3) { stage = "amt"; phase = "amt"; action = runAmt ? "start_amt" : "skip_amt"; cpu = step - 2; }
  92. else if (runAmt && (step == 4 || step == 5)) { stage = "amt"; phase = "amt"; action = "skip_amt"; cpu = step - 4; }
  93. else if (step == (runAmt ? 6 : 4)) { stage = "uip2"; phase = "uefi"; action = "continue_uip"; }
  94. else if (step >= (runAmt ? 7 : 5)) { stage = "uefi"; phase = "uefi"; action = "start_mt"; }
  95. else { stage = "uefi"; phase = "uefi"; action = "start_mt"; }
  96. const QJsonObject input{{"id", QStringLiteral("fixture-input-%1").arg(step)}, {"stage", stage},
  97. {"cpu", cpu}, {"ready", true}, {"test_complete", amtResultsReady}, {"actions", QJsonArray{action}}};
  98. return QJsonObject{{"station_id", "S1"}, {"connection", "online"}, {"power", "on"}, {"can_start", true},
  99. {"phase", phase}, {"run_state", changedBoot || (failAtEnd && step >= 5)
  100. || (step < 0 && command.value("state").toString() == "succeeded")
  101. ? "failed" : (step >= 0 ? "waiting_input" : "idle")},
  102. {"started_unix_ms", QString::number(started)},
  103. {"boot_id", changedBoot ? "fixture-boot-2" : (step >= 0 ? "fixture-boot-1" : "fixture-boot-0")},
  104. {"verdict", failAtEnd && step >= 5 ? "fail" : "not_tested"},
  105. {"input", input}, {"command", command},
  106. {"channels", QJsonArray{QJsonObject{{"name", "CPU0_CHA"}, {"present", false}, {"state", "idle"}, {"temperature_c", 48.0}}}}};
  107. }
  108. QJsonObject state() const
  109. {
  110. return QJsonObject{{"version", "0.8.0-fixture"}, {"mode", "fixture"}, {"server_id", "qt-clean-fixture"},
  111. {"stations", QJsonArray{station()}}};
  112. }
  113. void pushState() { send(QJsonObject{{"v", 1}, {"event", "state"}, {"result", state()}}); }
  114. void log(const QString &message)
  115. {
  116. const QByteArray bytes = (message + QLatin1Char('\n')).toUtf8();
  117. const quint64 first = sequence;
  118. sequence += static_cast<quint64>(bytes.size());
  119. const QJsonObject frame{{"v", 1}, {"event", "bios_uart"}, {"result", QJsonObject{
  120. {"station_id", "S1"}, {"session_id", "fixture-uart-session"},
  121. {"offset", QString::number(first)}, {"next_offset", QString::number(sequence)},
  122. {"data_base64", QString::fromLatin1(bytes.toBase64())}}}};
  123. events.append(frame);
  124. send(frame);
  125. }
  126. void receive(const QString &text)
  127. {
  128. const QJsonObject request = QJsonDocument::fromJson(text.toUtf8()).object();
  129. const QString method = request.value("method").toString();
  130. const QJsonObject params = request.value("params").toObject();
  131. methods << method;
  132. auto respond = [this, request](const QJsonObject &result) {
  133. send(QJsonObject{{"v", 1}, {"id", request.value("id")}, {"ok", true}, {"result", result}});
  134. };
  135. if (method == "GetState") {
  136. if (step < 0 && command.value("state").toString() == "succeeded") oldFailedSnapshotSent = true;
  137. respond(state()); return;
  138. }
  139. if (method == "GetCommand") { respond(command); return; }
  140. if (method == "StartTest") {
  141. ++starts;
  142. command = QJsonObject{{"command_id", params.value("command_id")}, {"state", "queued"}, {"error", ""}};
  143. // Reply succeeds before the asynchronously refreshed state. The old
  144. // UEFI input must never finish the new client's local plan.
  145. QTimer::singleShot(250, this, [this, respond] {
  146. const qint64 confirmedStarted = QDateTime::currentMSecsSinceEpoch();
  147. command.insert("state", "succeeded");
  148. command.insert("result", QJsonObject{{"boot_id", "fixture-boot-1"},
  149. {"started_unix_ms", QString::number(confirmedStarted)}});
  150. respond(command);
  151. QTimer::singleShot(200, this, [this, confirmedStarted] {
  152. started = confirmedStarted;
  153. step = 0;
  154. log(QStringLiteral("Fixture: fresh BIOS boot confirmed"));
  155. pushState();
  156. });
  157. });
  158. return;
  159. }
  160. if (method == "StageAction") {
  161. ++actions;
  162. const QString input = params.value("input_id").toString();
  163. if (inputIds.contains(input)) duplicate = true;
  164. inputIds.insert(input);
  165. const QJsonObject memory = params.value("memory_params").toObject();
  166. if (step < 2) correctParams = correctParams && memory.value("tCL").toInt() == 45;
  167. if (step == (runAmt ? 6 : 4)) correctParams = correctParams && memory.isEmpty();
  168. const QString action = params.value("action").toString();
  169. if (action == "start_amt") ++amtLaunches;
  170. if ((step == 2 || step == 3) && action != (runAmt ? "start_amt" : "skip_amt")) unexpected = true;
  171. if (runAmt && (step == 4 || step == 5) && action == "skip_amt" && !amtResultsReady) earlyAmtExit = true;
  172. command = QJsonObject{{"command_id", params.value("command_id")}, {"state", "running"}, {"error", ""}};
  173. respond(command);
  174. if (unexpectedBootMode && step == 0) {
  175. // A new BIOS boot is observed while a submitted stage command
  176. // remains running. Failure must not be hidden by either guard.
  177. QTimer::singleShot(90, this, [this] {
  178. changedBoot = true;
  179. log(QStringLiteral("Fixture: unexpected BIOS restart during pending stage"));
  180. pushState();
  181. });
  182. return;
  183. }
  184. if (step == 0 && socket) {
  185. disconnectTest = true;
  186. socket->close();
  187. }
  188. QTimer::singleShot(90, this, [this] {
  189. ++step;
  190. command.insert("state", "succeeded");
  191. log(QStringLiteral("Fixture: stage action %1 completed").arg(actions));
  192. pushState();
  193. if (runAmt && step == 4) {
  194. QTimer::singleShot(300, this, [this] {
  195. amtResultsReady = true;
  196. log(QStringLiteral("Fixture: actual AMT algorithm results completed"));
  197. pushState();
  198. });
  199. }
  200. });
  201. return;
  202. }
  203. unexpected = true;
  204. send(QJsonObject{{"v", 1}, {"id", request.value("id")}, {"ok", false},
  205. {"error", QJsonObject{{"code", "UNEXPECTED_METHOD"}, {"message", method}}}});
  206. }
  207. };
  208. int main(int argc, char **argv)
  209. {
  210. QApplication app(argc, argv);
  211. QCommandLineParser parser;
  212. parser.addHelpOption();
  213. parser.addOption({"mode", "read-only, start, fixture, fixture-amt, fixture-fail, fixture-unexpected-boot, fixture-silent. start physically starts/reboots one host.", "mode", "read-only"});
  214. parser.addOption({"url", "Clean backend WebSocket URL", "url"});
  215. parser.addOption({"report", "Write JSON verification evidence", "path", "qt-clean-probe.json"});
  216. parser.addOption({"screenshot", "Write actual Qt window PNG", "path"});
  217. parser.addOption({"station", "Station number 1..4", "number", "1"});
  218. parser.addOption({"expect-phase", "Required final phase for a real Start", "phase", "uefi"});
  219. parser.addOption({"timeout", "Maximum seconds", "seconds", "90"});
  220. parser.process(app);
  221. const QString mode = parser.value("mode");
  222. if (mode != "read-only" && mode != "start" && mode != "fixture" && mode != "fixture-amt"
  223. && mode != "fixture-fail" && mode != "fixture-unexpected-boot" && mode != "fixture-silent") return 2;
  224. const int station = parser.value("station").toInt() - 1;
  225. if (station < 0 || station > 3) return 2;
  226. qputenv("STL_QT_DISABLE_SERIAL", "1");
  227. if (!parser.value("url").isEmpty()) qputenv("STL_QT_BACKEND_URL", parser.value("url").toUtf8());
  228. QFile style(":/style/app.qss");
  229. if (style.open(QIODevice::ReadOnly)) app.setStyleSheet(QString::fromUtf8(style.readAll()));
  230. const QStringList families = QFontDatabase().families();
  231. for (const QString &family : QStringList{"Noto Sans CJK SC", "WenQuanYi Micro Hei", "DejaVu Sans"}) {
  232. if (families.contains(family)) { app.setFont(QFont(family, 9)); break; }
  233. }
  234. QJsonObject checks;
  235. QTemporaryDir selfTestDir;
  236. const QByteArray oldPlans = qgetenv("STL_QT_PLANS_FILE");
  237. qputenv("STL_QT_PLANS_FILE", selfTestDir.filePath("local-plans.json").toUtf8());
  238. LocalPlans plans;
  239. QString planError;
  240. const bool saved = plans.saveMemoryParams(0, QJsonObject{{"tCL", 45}}, &planError);
  241. const LocalPlans reloaded;
  242. checks.insert("local_plan_saved_and_reloaded", saved && reloaded.memoryParams(0).value("tCL").toInt() == 45);
  243. checks.insert("saved_plan_arms_uip_only_for_station", reloaded.plan(0).value("uip").toObject().value("apply_memory_params").toBool()
  244. && reloaded.memoryParams(1).value("tCL").toInt() != 45);
  245. if (oldPlans.isEmpty()) qunsetenv("STL_QT_PLANS_FILE"); else qputenv("STL_QT_PLANS_FILE", oldPlans);
  246. StationStore probeStore(1);
  247. StationData data;
  248. for (const QString &name : channelNames()) data.channels.append(ChannelInfo(name, -1, ChannelInfo::Idle));
  249. probeStore.initStation(0, data);
  250. probeStore.applyChannelTemperatures(0, QByteArray(24, char(48)));
  251. checks.insert("temperature_never_implies_pass", probeStore.countState(0, ChannelInfo::Pass) == 0
  252. && probeStore.station(0).channels.first().temperature == 48.0);
  253. probeStore.setChannelState(0, 0, ChannelInfo::Fail, 48);
  254. probeStore.applyChannelTemperatures(0, QByteArray(24, char(0xff)));
  255. checks.insert("missing_temperature_preserves_fail", probeStore.station(0).channels.first().state == ChannelInfo::Fail
  256. && probeStore.station(0).channels.first().temperature < 0.0);
  257. QTemporaryDir fixtureDir;
  258. Fixture *fixture = nullptr;
  259. if (mode.startsWith("fixture")) {
  260. fixture = new Fixture(mode == "fixture-amt");
  261. fixture->failAtEnd = mode == "fixture-fail";
  262. fixture->unexpectedBootMode = mode == "fixture-unexpected-boot";
  263. fixture->silentMode = mode == "fixture-silent";
  264. if (!fixture->server.isListening()) return 2;
  265. qputenv("STL_QT_BACKEND_URL", fixture->url().toUtf8());
  266. qputenv("STL_QT_CONFIG_DIR", fixtureDir.path().toUtf8());
  267. qputenv("STL_QT_PLANS_FILE", fixtureDir.filePath("qt-plans.json").toUtf8());
  268. writeJson(fixtureDir.filePath("config.json"), QJsonObject{{"memoryParams", QJsonObject{{"tCL", 44}}},
  269. {"qtPlan", QJsonObject{{"uip", QJsonObject{{"action", "continue_uip"}, {"apply_memory_params", false}}},
  270. {"amt", QJsonObject{{"action", mode == "fixture-amt" ? "start_amt" : "skip_amt"}, {"exit_after", true}}},
  271. {"uefi", QJsonObject{{"action", "hold"}}}}}});
  272. }
  273. MainWindow window;
  274. window.resize(1920, 1080);
  275. window.show();
  276. BackendLink *backend = window.findChild<BackendLink *>();
  277. if (!backend) return 2;
  278. const qint64 begin = QDateTime::currentMSecsSinceEpoch();
  279. QJsonArray states, phases;
  280. QJsonObject latest;
  281. int snapshots = 0;
  282. int logs = 0;
  283. bool clicked = false;
  284. bool startedSuccessfully = false;
  285. bool finished = false;
  286. qint64 fixtureCompletedAt = 0;
  287. QString failure;
  288. QObject::connect(backend, &BackendLink::stationState, &app, [&](int index, const QJsonObject &state) {
  289. if (index != station) return;
  290. ++snapshots;
  291. latest = state;
  292. const QString phase = state.value("phase").toString();
  293. if (phases.isEmpty() || phases.last().toString() != phase) phases.append(phase);
  294. if (states.isEmpty() || states.last().toObject() != state) states.append(state);
  295. });
  296. QObject::connect(backend, &BackendLink::logLine, &app, [&](int index, const QString &) { if (index == station) ++logs; });
  297. QObject::connect(backend, &BackendLink::commandFinished, &app,
  298. [&](int index, const QString &method, bool success, const QString &error) {
  299. if (index != station) return;
  300. if (!success) failure = error.isEmpty() ? QStringLiteral("command failed") : error;
  301. if (method == "StartTest" && success) startedSuccessfully = true;
  302. });
  303. if (fixture && mode != "fixture-silent") {
  304. // Calling the real Start slot while offline must neither send nor start timing.
  305. QMetaObject::invokeMethod(&window, "startTest", Qt::DirectConnection, Q_ARG(int, 0));
  306. checks.insert("offline_start_does_not_start_timer", !window.store()->station(0).startTime.isValid() && fixture->starts == 0);
  307. window.findChild<QAbstractButton *>("cardDetail_0")->click();
  308. window.findChild<QLineEdit *>("paramEdit_0_2")->setText("45");
  309. window.findChild<QLineEdit *>("paramEdit_0_0")->setText("1070");
  310. window.findChild<QAbstractButton *>("btnParamSubmit")->click();
  311. checks.insert("actual_form_save_is_local", LocalPlans().memoryParams(0).value("tCL").toInt() == 45 && fixture->methods.isEmpty());
  312. window.findChild<QLineEdit *>("paramEdit_0_0")->setText("invalid");
  313. window.findChild<QAbstractButton *>("btnParamSubmit")->click();
  314. checks.insert("invalid_parameter_not_coerced_to_zero", LocalPlans().memoryParams(0).value("mem vdd").toInt() == 1070);
  315. checks.insert("param_actions_do_not_pollute_bios_uart_log", window.store()->station(0).logs.isEmpty());
  316. window.store()->appendLog(0, QStringLiteral("fixture-unique-live-log"));
  317. window.findChild<QAbstractButton *>("btnBackMonitor")->click();
  318. window.findChild<QAbstractButton *>("cardDetail_1")->click();
  319. checks.insert("partial_plan_clears_other_station_form", window.findChild<QLineEdit *>("paramEdit_0_0")->text().isEmpty()
  320. && window.findChild<QLineEdit *>("paramEdit_0_2")->text() == "44");
  321. window.findChild<QAbstractButton *>("btnBackMonitor")->click();
  322. window.findChild<QAbstractButton *>("cardDetail_0")->click();
  323. checks.insert("detail_reopen_does_not_duplicate_live_log", window.findChild<QPlainTextEdit *>("detailLog")
  324. ->toPlainText().count(QStringLiteral("fixture-unique-live-log")) == 1);
  325. window.findChild<QAbstractButton *>("btnBackMonitor")->click();
  326. }
  327. auto complete = [&](const QString &reason) {
  328. if (finished) return;
  329. finished = true;
  330. checks.insert("actual_mainwindow_created", true);
  331. checks.insert("stage_toggle_checkboxes_present",
  332. window.findChild<QCheckBox *>("paramCheck_rmt") != nullptr
  333. && window.findChild<QCheckBox *>("paramCheck_amt") != nullptr
  334. && window.findChild<QCheckBox *>("paramCheck_mt") != nullptr);
  335. checks.insert("live_websocket_connected", backend->isConnected());
  336. checks.insert("clean_station_snapshot_received", snapshots > 0);
  337. checks.insert("no_command_error", failure.isEmpty());
  338. if (mode != "read-only" && mode != "fixture-silent") {
  339. checks.insert("actual_start_button_clicked", clicked);
  340. checks.insert("fresh_bios_start_confirmed", startedSuccessfully
  341. && latest.value("started_unix_ms").toVariant().toLongLong() >= begin);
  342. checks.insert("fresh_boot_id_matches_command", !backend->bootId(station).isEmpty()
  343. && latest.value("boot_id").toVariant().toString() == backend->bootId(station));
  344. checks.insert("no_firmware_execution_failure", latest.value("run_state").toString() != "failed"
  345. && latest.value("verdict").toString() != "fail");
  346. checks.insert("expected_phase_reached", latest.value("phase").toString().compare(parser.value("expect-phase"), Qt::CaseInsensitive) == 0);
  347. checks.insert("local_plan_finished_or_waiting", !backend->isBusy(station));
  348. }
  349. if (fixture && mode != "fixture-silent") {
  350. checks.insert("old_failed_snapshot_after_start_ignored", fixture->oldFailedSnapshotSent && startedSuccessfully);
  351. checks.insert("exactly_one_host_start", fixture->starts == 1);
  352. checks.insert("all_expected_prompt_actions", fixture->actions == (fixture->runAmt ? 7 : 5));
  353. checks.insert("no_duplicate_prompt_action", !fixture->duplicate);
  354. checks.insert("only_clean_methods", !fixture->unexpected);
  355. checks.insert("parameters_and_uip2_separation", fixture->correctParams);
  356. checks.insert("reconnected_without_reboot_replay", fixture->disconnectTest && fixture->connections >= 2 && fixture->starts == 1);
  357. checks.insert("unknown_channel_remains_idle", window.store()->station(0).channels.first().state == ChannelInfo::Idle);
  358. checks.insert("raw_uart_replayed_after_reconnect", fixture->uartReplays >= 2);
  359. checks.insert("missed_uart_bytes_displayed_once", window.store()->station(0).logs.join("\n")
  360. .count(QStringLiteral("Fixture: stage action 1 completed")) == 1);
  361. checks.insert("no_event_log_rpc", !fixture->methods.contains(QStringLiteral("ReadEventQueue")));
  362. if (fixture->runAmt) {
  363. checks.insert("amt_launched_once_per_cpu", fixture->amtLaunches == 2);
  364. checks.insert("amt_exits_only_after_real_result", fixture->amtResultsReady && !fixture->earlyAmtExit);
  365. }
  366. if (fixture->unexpectedBootMode) {
  367. checks.insert("unexpected_boot_failure_is_prompt", !failure.isEmpty()
  368. && reason != QStringLiteral("verification timeout")
  369. && QDateTime::currentMSecsSinceEpoch() - begin < 10000);
  370. checks.insert("unexpected_boot_stopped_with_pending_stage", fixture->changedBoot
  371. && fixture->command.value("state").toString() == "running" && !backend->isBusy(station));
  372. }
  373. }
  374. if (mode == "fixture-silent") {
  375. checks.insert("silent_websocket_was_reconnected", fixture && fixture->connections >= 2);
  376. checks.insert("state_received_after_reconnect", snapshots >= 2);
  377. checks.insert("watchdog_never_issued_host_start", fixture && fixture->starts == 0);
  378. }
  379. if (!parser.value("screenshot").isEmpty())
  380. checks.insert("screenshot_saved", window.grab().save(parser.value("screenshot")));
  381. bool pass = reason.isEmpty();
  382. for (auto i = checks.begin(); i != checks.end(); ++i) pass = pass && i.value().toBool();
  383. QJsonArray methods;
  384. if (fixture) for (const QString &method : fixture->methods) methods.append(method);
  385. const QJsonObject report{{"pass", pass}, {"mode", mode}, {"reason", reason}, {"command_error", failure},
  386. {"checks", checks}, {"url", backend->url()}, {"phase_history", phases}, {"snapshots", states},
  387. {"snapshot_count", snapshots}, {"log_count", logs}, {"fixture_methods", methods},
  388. {"command_boot_id", backend->bootId(station)}, {"elapsed_ms", QDateTime::currentMSecsSinceEpoch() - begin}};
  389. const bool written = writeJson(parser.value("report"), report);
  390. qInfo().noquote() << QJsonDocument(report).toJson(QJsonDocument::Compact);
  391. app.exit(pass && written ? 0 : 1);
  392. };
  393. QTimer poll;
  394. poll.setInterval(100);
  395. QObject::connect(&poll, &QTimer::timeout, &app, [&] {
  396. if (!failure.isEmpty()) { complete(failure); return; }
  397. if (mode == "read-only" || mode == "fixture-silent") {
  398. if (mode == "fixture-silent") {
  399. if (fixture->connections >= 2 && snapshots >= 2) complete({});
  400. return;
  401. }
  402. if (snapshots > 0 && QDateTime::currentMSecsSinceEpoch() - begin >= 3000) complete({});
  403. return;
  404. }
  405. if (!clicked && snapshots > 0) {
  406. QAbstractButton *button = window.findChild<QAbstractButton *>(QStringLiteral("startTest_%1").arg(station));
  407. if (!button || !button->isEnabled()) return;
  408. clicked = true;
  409. button->click();
  410. if (fixture) button->click(); // Duplicate immediate click must not issue a second StartTest.
  411. }
  412. if (clicked && startedSuccessfully && !backend->isBusy(station)
  413. && latest.value("phase").toString().compare(parser.value("expect-phase"), Qt::CaseInsensitive) == 0) {
  414. if (parser.value("expect-phase").compare("mt", Qt::CaseInsensitive) == 0
  415. && latest.value("run_state").toString() != "completed") return;
  416. if (fixture) {
  417. if (!fixtureCompletedAt) fixtureCompletedAt = QDateTime::currentMSecsSinceEpoch();
  418. if (QDateTime::currentMSecsSinceEpoch() - fixtureCompletedAt < 2000) return;
  419. }
  420. complete({});
  421. }
  422. });
  423. poll.start();
  424. QTimer::singleShot(qMax(5, parser.value("timeout").toInt()) * 1000, &app,
  425. [&] { complete(QStringLiteral("verification timeout")); });
  426. const int code = app.exec();
  427. // These app-context lambdas capture locals declared after window; remove
  428. // them before stack unwinding can destroy those captured variables.
  429. QObject::disconnect(backend, nullptr, &app, nullptr);
  430. delete fixture;
  431. return code;
  432. }