| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432 |
- // This harness instantiates the actual MainWindow and clicks its real buttons.
- // Default mode is read-only. Only --mode start invokes physical host controls.
- #include "mainwindow.h"
- #include "backendlink.h"
- #include "stationdata.h"
- #include "localplans.h"
- #include <QAbstractButton>
- #include <QApplication>
- #include <QCommandLineParser>
- #include <QDateTime>
- #include <QDir>
- #include <QFile>
- #include <QFontDatabase>
- #include <QJsonArray>
- #include <QJsonDocument>
- #include <QJsonObject>
- #include <QLabel>
- #include <QLineEdit>
- #include <QPointer>
- #include <QPlainTextEdit>
- #include <QSaveFile>
- #include <QTemporaryDir>
- #include <QTimer>
- #include <QWebSocket>
- #include <QWebSocketServer>
- #include <functional>
- static bool writeJson(const QString &path, const QJsonObject &value)
- {
- QSaveFile file(path);
- const QByteArray bytes = QJsonDocument(value).toJson(QJsonDocument::Indented);
- return file.open(QIODevice::WriteOnly) && file.write(bytes) == bytes.size() && file.commit();
- }
- class Fixture : public QObject
- {
- public:
- QWebSocketServer server{QStringLiteral("Qt clean contract fixture"), QWebSocketServer::NonSecureMode};
- QPointer<QWebSocket> socket;
- int connections = 0;
- int starts = 0;
- int actions = 0;
- bool duplicate = false;
- bool unexpected = false;
- bool correctParams = true;
- bool disconnectTest = false;
- bool silentMode = false;
- bool runAmt = false;
- bool amtResultsReady = false;
- bool earlyAmtExit = false;
- int amtLaunches = 0;
- bool failAtEnd = false;
- bool unexpectedBootMode = false;
- bool changedBoot = false;
- bool oldFailedSnapshotSent = false;
- int uartReplays = 0;
- QStringList methods;
- QSet<QString> inputIds;
- QJsonObject command;
- QJsonArray events;
- int step = -1;
- qint64 started = 0;
- quint64 sequence = 0;
- explicit Fixture(bool testAmt = false) : runAmt(testAmt)
- {
- server.listen(QHostAddress::LocalHost, 0);
- connect(&server, &QWebSocketServer::newConnection, this, [this] {
- socket = server.nextPendingConnection();
- ++connections;
- QWebSocket *client = socket;
- connect(client, &QWebSocket::textMessageReceived, this, [this](const QString &text) { receive(text); });
- connect(client, &QWebSocket::disconnected, client, &QObject::deleteLater);
- pushState();
- if (silentMode) return; // Deliberately silent TCP peer: exercise client watchdog.
- // A fresh socket starts from byte zero. BackendLink must suppress
- // already displayed bytes and recover anything missed offline.
- for (const QJsonValue &row : events) send(row.toObject());
- ++uartReplays;
- });
- }
- QString url() const { return QStringLiteral("ws://127.0.0.1:%1/ws?view=qt-clean").arg(server.serverPort()); }
- void send(const QJsonObject &frame)
- {
- if (socket && socket->state() == QAbstractSocket::ConnectedState)
- socket->sendTextMessage(QString::fromUtf8(QJsonDocument(frame).toJson(QJsonDocument::Compact)));
- }
- QJsonObject station() const
- {
- QString stage, phase = QStringLiteral("uefi"), action;
- int cpu = 0;
- if (step == 0 || step == 1) { stage = "uip1"; phase = "uip"; action = "continue_uip"; cpu = step; }
- else if (step == 2 || step == 3) { stage = "amt"; phase = "amt"; action = runAmt ? "start_amt" : "skip_amt"; cpu = step - 2; }
- else if (runAmt && (step == 4 || step == 5)) { stage = "amt"; phase = "amt"; action = "skip_amt"; cpu = step - 4; }
- else if (step == (runAmt ? 6 : 4)) { stage = "uip2"; phase = "uefi"; action = "continue_uip"; }
- else if (step >= (runAmt ? 7 : 5)) { stage = "uefi"; phase = "uefi"; action = "start_mt"; }
- else { stage = "uefi"; phase = "uefi"; action = "start_mt"; }
- const QJsonObject input{{"id", QStringLiteral("fixture-input-%1").arg(step)}, {"stage", stage},
- {"cpu", cpu}, {"ready", true}, {"test_complete", amtResultsReady}, {"actions", QJsonArray{action}}};
- return QJsonObject{{"station_id", "S1"}, {"connection", "online"}, {"power", "on"}, {"can_start", true},
- {"phase", phase}, {"run_state", changedBoot || (failAtEnd && step >= 5)
- || (step < 0 && command.value("state").toString() == "succeeded")
- ? "failed" : (step >= 0 ? "waiting_input" : "idle")},
- {"started_unix_ms", QString::number(started)},
- {"boot_id", changedBoot ? "fixture-boot-2" : (step >= 0 ? "fixture-boot-1" : "fixture-boot-0")},
- {"verdict", failAtEnd && step >= 5 ? "fail" : "not_tested"},
- {"input", input}, {"command", command},
- {"channels", QJsonArray{QJsonObject{{"name", "CPU0_CHA"}, {"state", "unknown"}, {"temperature_c", 48.0}}}}};
- }
- QJsonObject state() const
- {
- return QJsonObject{{"version", "0.8.0-fixture"}, {"mode", "fixture"}, {"server_id", "qt-clean-fixture"},
- {"stations", QJsonArray{station()}}};
- }
- void pushState() { send(QJsonObject{{"v", 1}, {"event", "state"}, {"result", state()}}); }
- void log(const QString &message)
- {
- const QByteArray bytes = (message + QLatin1Char('\n')).toUtf8();
- const quint64 first = sequence;
- sequence += static_cast<quint64>(bytes.size());
- const QJsonObject frame{{"v", 1}, {"event", "bios_uart"}, {"result", QJsonObject{
- {"station_id", "S1"}, {"session_id", "fixture-uart-session"},
- {"offset", QString::number(first)}, {"next_offset", QString::number(sequence)},
- {"data_base64", QString::fromLatin1(bytes.toBase64())}}}};
- events.append(frame);
- send(frame);
- }
- void receive(const QString &text)
- {
- const QJsonObject request = QJsonDocument::fromJson(text.toUtf8()).object();
- const QString method = request.value("method").toString();
- const QJsonObject params = request.value("params").toObject();
- methods << method;
- auto respond = [this, request](const QJsonObject &result) {
- send(QJsonObject{{"v", 1}, {"id", request.value("id")}, {"ok", true}, {"result", result}});
- };
- if (method == "GetState") {
- if (step < 0 && command.value("state").toString() == "succeeded") oldFailedSnapshotSent = true;
- respond(state()); return;
- }
- if (method == "GetCommand") { respond(command); return; }
- if (method == "StartTest") {
- ++starts;
- command = QJsonObject{{"command_id", params.value("command_id")}, {"state", "queued"}, {"error", ""}};
- // Reply succeeds before the asynchronously refreshed state. The old
- // UEFI input must never finish the new client's local plan.
- QTimer::singleShot(250, this, [this, respond] {
- const qint64 confirmedStarted = QDateTime::currentMSecsSinceEpoch();
- command.insert("state", "succeeded");
- command.insert("result", QJsonObject{{"boot_id", "fixture-boot-1"},
- {"started_unix_ms", QString::number(confirmedStarted)}});
- respond(command);
- QTimer::singleShot(200, this, [this, confirmedStarted] {
- started = confirmedStarted;
- step = 0;
- log(QStringLiteral("Fixture: fresh BIOS boot confirmed"));
- pushState();
- });
- });
- return;
- }
- if (method == "StageAction") {
- ++actions;
- const QString input = params.value("input_id").toString();
- if (inputIds.contains(input)) duplicate = true;
- inputIds.insert(input);
- const QJsonObject memory = params.value("memory_params").toObject();
- if (step < 2) correctParams = correctParams && memory.value("tCL").toInt() == 45;
- if (step == (runAmt ? 6 : 4)) correctParams = correctParams && memory.isEmpty();
- const QString action = params.value("action").toString();
- if (action == "start_amt") ++amtLaunches;
- if ((step == 2 || step == 3) && action != (runAmt ? "start_amt" : "skip_amt")) unexpected = true;
- if (runAmt && (step == 4 || step == 5) && action == "skip_amt" && !amtResultsReady) earlyAmtExit = true;
- command = QJsonObject{{"command_id", params.value("command_id")}, {"state", "running"}, {"error", ""}};
- respond(command);
- if (unexpectedBootMode && step == 0) {
- // A new BIOS boot is observed while a submitted stage command
- // remains running. Failure must not be hidden by either guard.
- QTimer::singleShot(90, this, [this] {
- changedBoot = true;
- log(QStringLiteral("Fixture: unexpected BIOS restart during pending stage"));
- pushState();
- });
- return;
- }
- if (step == 0 && socket) {
- disconnectTest = true;
- socket->close();
- }
- QTimer::singleShot(90, this, [this] {
- ++step;
- command.insert("state", "succeeded");
- log(QStringLiteral("Fixture: stage action %1 completed").arg(actions));
- pushState();
- if (runAmt && step == 4) {
- QTimer::singleShot(300, this, [this] {
- amtResultsReady = true;
- log(QStringLiteral("Fixture: actual AMT algorithm results completed"));
- pushState();
- });
- }
- });
- return;
- }
- unexpected = true;
- send(QJsonObject{{"v", 1}, {"id", request.value("id")}, {"ok", false},
- {"error", QJsonObject{{"code", "UNEXPECTED_METHOD"}, {"message", method}}}});
- }
- };
- int main(int argc, char **argv)
- {
- QApplication app(argc, argv);
- QCommandLineParser parser;
- parser.addHelpOption();
- 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"});
- parser.addOption({"url", "Clean backend WebSocket URL", "url"});
- parser.addOption({"report", "Write JSON verification evidence", "path", "qt-clean-probe.json"});
- parser.addOption({"screenshot", "Write actual Qt window PNG", "path"});
- parser.addOption({"station", "Station number 1..4", "number", "1"});
- parser.addOption({"expect-phase", "Required final phase for a real Start", "phase", "uefi"});
- parser.addOption({"timeout", "Maximum seconds", "seconds", "90"});
- parser.process(app);
- const QString mode = parser.value("mode");
- if (mode != "read-only" && mode != "start" && mode != "fixture" && mode != "fixture-amt"
- && mode != "fixture-fail" && mode != "fixture-unexpected-boot" && mode != "fixture-silent") return 2;
- const int station = parser.value("station").toInt() - 1;
- if (station < 0 || station > 3) return 2;
- qputenv("STL_QT_DISABLE_SERIAL", "1");
- if (!parser.value("url").isEmpty()) qputenv("STL_QT_BACKEND_URL", parser.value("url").toUtf8());
- QFile style(":/style/app.qss");
- if (style.open(QIODevice::ReadOnly)) app.setStyleSheet(QString::fromUtf8(style.readAll()));
- const QStringList families = QFontDatabase().families();
- for (const QString &family : QStringList{"Noto Sans CJK SC", "WenQuanYi Micro Hei", "DejaVu Sans"}) {
- if (families.contains(family)) { app.setFont(QFont(family, 9)); break; }
- }
- QJsonObject checks;
- QTemporaryDir selfTestDir;
- const QByteArray oldPlans = qgetenv("STL_QT_PLANS_FILE");
- qputenv("STL_QT_PLANS_FILE", selfTestDir.filePath("local-plans.json").toUtf8());
- LocalPlans plans;
- QString planError;
- const bool saved = plans.saveMemoryParams(0, QJsonObject{{"tCL", 45}}, &planError);
- const LocalPlans reloaded;
- checks.insert("local_plan_saved_and_reloaded", saved && reloaded.memoryParams(0).value("tCL").toInt() == 45);
- checks.insert("saved_plan_arms_uip_only_for_station", reloaded.plan(0).value("uip").toObject().value("apply_memory_params").toBool()
- && reloaded.memoryParams(1).value("tCL").toInt() != 45);
- if (oldPlans.isEmpty()) qunsetenv("STL_QT_PLANS_FILE"); else qputenv("STL_QT_PLANS_FILE", oldPlans);
- StationStore probeStore(1);
- StationData data;
- for (const QString &name : channelNames()) data.channels.append(ChannelInfo(name, -1, ChannelInfo::Idle));
- probeStore.initStation(0, data);
- probeStore.applyChannelTemperatures(0, QByteArray(24, char(48)));
- checks.insert("temperature_never_implies_pass", probeStore.countState(0, ChannelInfo::Pass) == 0
- && probeStore.station(0).channels.first().temperature == 48.0);
- probeStore.setChannelState(0, 0, ChannelInfo::Fail, 48);
- probeStore.applyChannelTemperatures(0, QByteArray(24, char(0xff)));
- checks.insert("missing_temperature_preserves_fail", probeStore.station(0).channels.first().state == ChannelInfo::Fail
- && probeStore.station(0).channels.first().temperature < 0.0);
- QTemporaryDir fixtureDir;
- Fixture *fixture = nullptr;
- if (mode.startsWith("fixture")) {
- fixture = new Fixture(mode == "fixture-amt");
- fixture->failAtEnd = mode == "fixture-fail";
- fixture->unexpectedBootMode = mode == "fixture-unexpected-boot";
- fixture->silentMode = mode == "fixture-silent";
- if (!fixture->server.isListening()) return 2;
- qputenv("STL_QT_BACKEND_URL", fixture->url().toUtf8());
- qputenv("STL_QT_CONFIG_DIR", fixtureDir.path().toUtf8());
- qputenv("STL_QT_PLANS_FILE", fixtureDir.filePath("qt-plans.json").toUtf8());
- writeJson(fixtureDir.filePath("config.json"), QJsonObject{{"memoryParams", QJsonObject{{"tCL", 44}}},
- {"qtPlan", QJsonObject{{"uip", QJsonObject{{"action", "continue_uip"}, {"apply_memory_params", false}}},
- {"amt", QJsonObject{{"action", mode == "fixture-amt" ? "start_amt" : "skip_amt"}, {"exit_after", true}}},
- {"uefi", QJsonObject{{"action", "hold"}}}}}});
- }
- MainWindow window;
- window.resize(1920, 1080);
- window.show();
- BackendLink *backend = window.findChild<BackendLink *>();
- if (!backend) return 2;
- const qint64 begin = QDateTime::currentMSecsSinceEpoch();
- QJsonArray states, phases;
- QJsonObject latest;
- int snapshots = 0;
- int logs = 0;
- bool clicked = false;
- bool startedSuccessfully = false;
- bool finished = false;
- qint64 fixtureCompletedAt = 0;
- QString failure;
- QObject::connect(backend, &BackendLink::stationState, &app, [&](int index, const QJsonObject &state) {
- if (index != station) return;
- ++snapshots;
- latest = state;
- const QString phase = state.value("phase").toString();
- if (phases.isEmpty() || phases.last().toString() != phase) phases.append(phase);
- if (states.isEmpty() || states.last().toObject() != state) states.append(state);
- });
- QObject::connect(backend, &BackendLink::logLine, &app, [&](int index, const QString &) { if (index == station) ++logs; });
- QObject::connect(backend, &BackendLink::commandFinished, &app,
- [&](int index, const QString &method, bool success, const QString &error) {
- if (index != station) return;
- if (!success) failure = error.isEmpty() ? QStringLiteral("command failed") : error;
- if (method == "StartTest" && success) startedSuccessfully = true;
- });
- if (fixture && mode != "fixture-silent") {
- // Calling the real Start slot while offline must neither send nor start timing.
- QMetaObject::invokeMethod(&window, "startTest", Qt::DirectConnection, Q_ARG(int, 0));
- checks.insert("offline_start_does_not_start_timer", !window.store()->station(0).startTime.isValid() && fixture->starts == 0);
- window.findChild<QAbstractButton *>("cardDetail_0")->click();
- window.findChild<QLineEdit *>("paramEdit_0_2")->setText("45");
- window.findChild<QLineEdit *>("paramEdit_0_0")->setText("1070");
- window.findChild<QAbstractButton *>("btnParamSubmit")->click();
- checks.insert("actual_form_save_is_local", LocalPlans().memoryParams(0).value("tCL").toInt() == 45 && fixture->methods.isEmpty());
- window.findChild<QLineEdit *>("paramEdit_0_0")->setText("invalid");
- window.findChild<QAbstractButton *>("btnParamSubmit")->click();
- checks.insert("invalid_parameter_not_coerced_to_zero", LocalPlans().memoryParams(0).value("mem vdd").toInt() == 1070);
- window.store()->appendLog(0, QStringLiteral("fixture-unique-live-log"));
- window.findChild<QAbstractButton *>("btnBackMonitor")->click();
- window.findChild<QAbstractButton *>("cardDetail_1")->click();
- checks.insert("partial_plan_clears_other_station_form", window.findChild<QLineEdit *>("paramEdit_0_0")->text().isEmpty()
- && window.findChild<QLineEdit *>("paramEdit_0_2")->text() == "44");
- window.findChild<QAbstractButton *>("btnBackMonitor")->click();
- window.findChild<QAbstractButton *>("cardDetail_0")->click();
- checks.insert("detail_reopen_does_not_duplicate_live_log", window.findChild<QPlainTextEdit *>("detailLog")
- ->toPlainText().count(QStringLiteral("fixture-unique-live-log")) == 1);
- window.findChild<QAbstractButton *>("btnBackMonitor")->click();
- }
- auto complete = [&](const QString &reason) {
- if (finished) return;
- finished = true;
- checks.insert("actual_mainwindow_created", true);
- checks.insert("live_websocket_connected", backend->isConnected());
- checks.insert("clean_station_snapshot_received", snapshots > 0);
- checks.insert("no_command_error", failure.isEmpty());
- if (mode != "read-only" && mode != "fixture-silent") {
- checks.insert("actual_start_button_clicked", clicked);
- checks.insert("fresh_bios_start_confirmed", startedSuccessfully
- && latest.value("started_unix_ms").toVariant().toLongLong() >= begin);
- checks.insert("fresh_boot_id_matches_command", !backend->bootId(station).isEmpty()
- && latest.value("boot_id").toVariant().toString() == backend->bootId(station));
- checks.insert("no_firmware_execution_failure", latest.value("run_state").toString() != "failed"
- && latest.value("verdict").toString() != "fail");
- checks.insert("expected_phase_reached", latest.value("phase").toString().compare(parser.value("expect-phase"), Qt::CaseInsensitive) == 0);
- checks.insert("local_plan_finished_or_waiting", !backend->isBusy(station));
- }
- if (fixture && mode != "fixture-silent") {
- checks.insert("old_failed_snapshot_after_start_ignored", fixture->oldFailedSnapshotSent && startedSuccessfully);
- checks.insert("exactly_one_host_start", fixture->starts == 1);
- checks.insert("all_expected_prompt_actions", fixture->actions == (fixture->runAmt ? 7 : 5));
- checks.insert("no_duplicate_prompt_action", !fixture->duplicate);
- checks.insert("only_clean_methods", !fixture->unexpected);
- checks.insert("parameters_and_uip2_separation", fixture->correctParams);
- checks.insert("reconnected_without_reboot_replay", fixture->disconnectTest && fixture->connections >= 2 && fixture->starts == 1);
- checks.insert("unknown_channel_remains_idle", window.store()->station(0).channels.first().state == ChannelInfo::Idle);
- checks.insert("raw_uart_replayed_after_reconnect", fixture->uartReplays >= 2);
- checks.insert("missed_uart_bytes_displayed_once", window.store()->station(0).logs.join("\n")
- .count(QStringLiteral("Fixture: stage action 1 completed")) == 1);
- checks.insert("no_event_log_rpc", !fixture->methods.contains(QStringLiteral("ReadEventQueue")));
- if (fixture->runAmt) {
- checks.insert("amt_launched_once_per_cpu", fixture->amtLaunches == 2);
- checks.insert("amt_exits_only_after_real_result", fixture->amtResultsReady && !fixture->earlyAmtExit);
- }
- if (fixture->unexpectedBootMode) {
- checks.insert("unexpected_boot_failure_is_prompt", !failure.isEmpty()
- && reason != QStringLiteral("verification timeout")
- && QDateTime::currentMSecsSinceEpoch() - begin < 10000);
- checks.insert("unexpected_boot_stopped_with_pending_stage", fixture->changedBoot
- && fixture->command.value("state").toString() == "running" && !backend->isBusy(station));
- }
- }
- if (mode == "fixture-silent") {
- checks.insert("silent_websocket_was_reconnected", fixture && fixture->connections >= 2);
- checks.insert("state_received_after_reconnect", snapshots >= 2);
- checks.insert("watchdog_never_issued_host_start", fixture && fixture->starts == 0);
- }
- if (!parser.value("screenshot").isEmpty())
- checks.insert("screenshot_saved", window.grab().save(parser.value("screenshot")));
- bool pass = reason.isEmpty();
- for (auto i = checks.begin(); i != checks.end(); ++i) pass = pass && i.value().toBool();
- QJsonArray methods;
- if (fixture) for (const QString &method : fixture->methods) methods.append(method);
- const QJsonObject report{{"pass", pass}, {"mode", mode}, {"reason", reason}, {"command_error", failure},
- {"checks", checks}, {"url", backend->url()}, {"phase_history", phases}, {"snapshots", states},
- {"snapshot_count", snapshots}, {"log_count", logs}, {"fixture_methods", methods},
- {"command_boot_id", backend->bootId(station)}, {"elapsed_ms", QDateTime::currentMSecsSinceEpoch() - begin}};
- const bool written = writeJson(parser.value("report"), report);
- qInfo().noquote() << QJsonDocument(report).toJson(QJsonDocument::Compact);
- app.exit(pass && written ? 0 : 1);
- };
- QTimer poll;
- poll.setInterval(100);
- QObject::connect(&poll, &QTimer::timeout, &app, [&] {
- if (!failure.isEmpty()) { complete(failure); return; }
- if (mode == "read-only" || mode == "fixture-silent") {
- if (mode == "fixture-silent") {
- if (fixture->connections >= 2 && snapshots >= 2) complete({});
- return;
- }
- if (snapshots > 0 && QDateTime::currentMSecsSinceEpoch() - begin >= 3000) complete({});
- return;
- }
- if (!clicked && snapshots > 0) {
- QAbstractButton *button = window.findChild<QAbstractButton *>(QStringLiteral("startTest_%1").arg(station));
- if (!button || !button->isEnabled()) return;
- clicked = true;
- button->click();
- if (fixture) button->click(); // Duplicate immediate click must not issue a second StartTest.
- }
- if (clicked && startedSuccessfully && !backend->isBusy(station)
- && latest.value("phase").toString().compare(parser.value("expect-phase"), Qt::CaseInsensitive) == 0) {
- if (fixture) {
- if (!fixtureCompletedAt) fixtureCompletedAt = QDateTime::currentMSecsSinceEpoch();
- if (QDateTime::currentMSecsSinceEpoch() - fixtureCompletedAt < 2000) return;
- }
- complete({});
- }
- });
- poll.start();
- QTimer::singleShot(qMax(5, parser.value("timeout").toInt()) * 1000, &app,
- [&] { complete(QStringLiteral("verification timeout")); });
- const int code = app.exec();
- // These app-context lambdas capture locals declared after window; remove
- // them before stack unwinding can destroy those captured variables.
- QObject::disconnect(backend, nullptr, &app, nullptr);
- delete fixture;
- return code;
- }
|