File size: 16,020 Bytes
bad179a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | // Offscreen click test: drives the real main window through its widgets. Scratch config only; every confirmation is answered "No".
#include "ui/Widgets.h"
#include "ui/Windows.h"
#include <QtWidgets>
#include <cstdio>
static int fails = 0;
static void wait(int ms) { QEventLoop l; QTimer::singleShot(ms, &l, &QEventLoop::quit); l.exec(); }
static bool waitFor(const std::function<bool()> &c, int ms) { QElapsedTimer t; t.start(); while (!c() && t.elapsed() < ms) wait(100); return c(); }
static void check(bool ok, const QString &what) { printf("%s %s\n", ok ? "PASS" : "FAIL", qPrintable(what)); fflush(stdout); fails += !ok; }
static void note(const QString &s) { printf(" %s\n", qPrintable(s)); fflush(stdout); }
static QAbstractButton *btn(QWidget *root, const QString &text)
{
for (auto *b : root->findChildren<QAbstractButton *>()) if (b->text() == text) return b;
printf("FAIL button '%s' not found\n", qPrintable(text)); ++fails;
return nullptr;
}
// answers the next modal dialog
static void onModal(const std::function<void(QWidget *)> &f, int ms = 500) { QTimer::singleShot(ms, qApp, [f] { f(QApplication::activeModalWidget()); }); }
static QString asked; // text of the last question that was answered "No"
static void sayNo()
{
asked.clear();
onModal([](QWidget *m) {
if (auto *box = qobject_cast<QMessageBox *>(m)) asked = box->text(), (box->button(QMessageBox::No) ? box->button(QMessageBox::No) : box->button(QMessageBox::Cancel))->click();
else if (auto *d = qobject_cast<QDialog *>(m)) asked = "dialog: " + d->windowTitle(), d->reject();
});
}
static QJsonObject serverJson(int i)
{
QFile f(ServerManager::configDir() + "/servers.json");
f.open(QIODevice::ReadOnly);
return QJsonDocument::fromJson(f.readAll())["servers"].toArray()[i].toObject();
}
static int visibleRows(QTableWidget *t) { int n = 0; for (int r = 0; r < t->rowCount(); ++r) n += !t->isRowHidden(r); return n; }
static int rowOf(QTableWidget *t, const QString &key) { for (int r = 0; r < t->rowCount(); ++r) if (t->item(r, 0) && t->item(r, 0)->text() == key) return r; return -1; }
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QApplication::setApplicationName("ServerMonitor"), QApplication::setOrganizationName("ServerMonitor"), QApplication::setQuitOnLastWindowClosed(false);
app.setStyleSheet(C::styleSheet());
QElapsedTimer run; run.start();
if (!ServerManager::configDir().contains("/review-cpp/")) return puts("refusing to run: XDG_CONFIG_HOME is not a scratch dir"), 2;
ServerManager mgr;
MainWindow w(&mgr);
mgr.load();
w.show();
auto *tabs = w.findChild<QTabWidget *>();
auto *sideW = w.findChild<QWidget *>("Sidebar");
auto *side = sideW->findChild<QListWidget *>();
auto *stack = w.findChild<QStackedWidget *>();
auto tab = [&](const QString &n) -> QWidget * {
for (int i = 0; i < tabs->count(); ++i) if (tabs->tabText(i).startsWith(n)) { tabs->setCurrentIndex(i), wait(400); return tabs->widget(i); }
return nullptr;
};
auto open = [&](int row) { side->setCurrentRow(row); emit side->itemClicked(side->item(row)); wait(400); };
check(mgr.sessions().size() == 2 && mgr.sessions()[0]->config().autopilot.dryRun && mgr.sessions()[1]->config().autopilot.dryRun, "scratch config loaded: 2 servers, autopilot in dry run");
ServerSession *local = mgr.sessions()[0];
const bool on = waitFor([&] { return local->online(); }, 20000);
check(on, QString("local server online after %1 ms (needs 2 frames)").arg(run.elapsed()));
check(local->analysis().when > 0 && !local->analysis().healthReasons.join(' ').contains("unreachable"), "analyzed with the first sample: health " + QString::number(local->analysis().health));
// ---- open a server, visit every tab
open(0);
check(tabs->isVisible() && stack->currentWidget()->findChild<QLabel *>("H1")->text() == "This computer", "open server: detail page shows 'This computer'");
QStringList names;
for (int i = 0; i < tabs->count(); ++i) tabs->setCurrentIndex(i), wait(300), names << tabs->tabText(i);
check(names.size() == 11, "all tabs opened: " + names.join(", "));
// ---- processes: filter, hidden selection, question answered No
QWidget *pt = tab("Processes");
auto *ptbl = pt->findChild<QTableWidget *>();
auto *flt = pt->findChild<QLineEdit *>();
auto status = [](QWidget *t) { QStringList l; for (auto *x : t->findChildren<QLabel *>()) if (x->text().startsWith("Select") || x->text().startsWith("Running") || x->text().startsWith(u8"✓") || x->text().startsWith(u8"✗")) l << x->text(); return l.join(" / "); };
const int total = ptbl->rowCount();
pt->findChild<QCheckBox *>()->setChecked(true); // freeze so the rows hold still
const QString word = ptbl->item(0, 1)->text().left(5);
flt->setText(word), wait(100);
bool all = visibleRows(ptbl) > 0;
for (int r = 0; r < ptbl->rowCount(); ++r) {
bool hit = false;
for (int c = 0; c < ptbl->columnCount(); ++c) hit |= ptbl->item(r, c)->text().contains(word, Qt::CaseInsensitive);
all &= hit == !ptbl->isRowHidden(r);
}
check(total > 3 && all, QString("process filter '%1': %2 of %3 rows shown, exactly the matching ones").arg(word).arg(visibleRows(ptbl)).arg(total));
flt->setText("zz-no-such-process"), wait(100);
check(visibleRows(ptbl) == 0, "process filter without match hides all rows");
ptbl->setCurrentCell(0, 0);
sayNo(), btn(pt, "Kill")->click(), wait(700);
check(asked.isEmpty() && status(pt) == "Select a process first.", "Kill with the selected row filtered out: no question, status '" + status(pt) + "'");
flt->clear(), wait(100);
check(visibleRows(ptbl) == total, "clearing the filter shows all rows again");
ptbl->setCurrentCell(1, 0);
const QString pid = ptbl->item(1, 0)->text(), pname = ptbl->item(1, 1)->text();
sayNo(), btn(pt, "Kill")->click(), wait(700);
check(asked.contains(pid) && asked.contains(pname) && asked.contains("This computer") && !status(pt).contains("Running"), "Kill asks first (answered No, nothing ran): '" + asked + "'");
sayNo(), btn(pt, u8"Priority…")->click(), wait(700);
check(asked == "dialog: Change priority" && !status(pt).contains("Running"), "Priority… opens its dialog (cancelled)");
open(1), open(0), pt = tab("Processes");
check(!pt->findChild<QCheckBox *>()->isChecked(), "Freeze list is switched off when another server is opened");
pt->findChild<QCheckBox *>()->setChecked(false);
if (P::posixCpu) { // a selected process that ends must not hand its selection to another row
QProcess child;
child.start("sleep", {"600"});
child.waitForStarted();
const QString cp = QString::number(child.processId());
check(waitFor([&] { return rowOf(ptbl, cp) >= 0; }, 10000), "test's own 'sleep' child (PID " + cp + ") appears in the list");
ptbl->setCurrentCell(rowOf(ptbl, cp), 0), wait(2500);
check(ptbl->currentRow() == rowOf(ptbl, cp) && ptbl->currentRow() >= 0, "selection follows the process across refreshes");
child.kill(), child.waitForFinished();
waitFor([&] { return rowOf(ptbl, cp) < 0; }, 10000), wait(300);
const QString now = ptbl->currentRow() >= 0 ? ptbl->item(ptbl->currentRow(), 0)->text() + " " + ptbl->item(ptbl->currentRow(), 1)->text() : "nothing";
check(ptbl->currentRow() < 0 && ptbl->selectedItems().isEmpty(), "after the selected process ended the selection is: " + now);
sayNo(), btn(pt, "Terminate")->click(), wait(700);
check(asked.isEmpty(), "Terminate afterwards asks nothing" + (asked.isEmpty() ? QString() : " - BUT ASKED: " + asked));
}
// ---- services: logs dialog, question answered No
QWidget *st = tab("Services");
auto *stbl = st->findChild<QTableWidget *>();
check(stbl->rowCount() > 0, QString("services listed: %1").arg(stbl->rowCount()));
QPointer<QDialog> logs;
if (stbl->rowCount()) {
stbl->setCurrentCell(0, 0);
const QString unit = stbl->item(0, 0)->text();
btn(st, "Logs")->click(), wait(200);
logs = st->findChild<QDialog *>();
auto *txt = logs ? logs->findChild<QPlainTextEdit *>() : nullptr;
check(txt && logs->isVisible() && waitFor([&] { return txt->toPlainText() != u8"Loading…"; }, 20000), "logs dialog for " + unit + " loaded");
if (txt) note(txt->toPlainText().left(160).replace('\n', " | "));
sayNo(), btn(st, "Stop")->click(), wait(700);
check(asked.contains("Stop " + unit) && !status(st).contains("Running"), "Stop asks first (answered No, nothing ran): '" + asked + "'");
}
// ---- alert rules: add and delete
QWidget *rt = tab("Alert rules");
QTableWidget *rules = nullptr;
for (auto *t : rt->findChildren<QTableWidget *>()) if (t->columnCount() == 6) rules = t;
const int n0 = rules->rowCount();
onModal([](QWidget *m) {
for (auto *c : m->findChildren<QComboBox *>()) if (c->findData("notify") >= 0) c->setCurrentIndex(c->findData("notify")); // never an action
m->findChild<QDialogButtonBox *>()->button(QDialogButtonBox::Ok)->click();
});
btn(rt, "+ Add rule")->click(), wait(200);
check(n0 == 7 && rules->rowCount() == 8 && serverJson(0)["rules"].toArray().size() == 8 && serverJson(0)["rules"].toArray()[7].toObject()["action"] == "notify", "rule added: table 8 rows, servers.json 8 rules, new one is notify-only: " + rules->item(7, 1)->text());
rules->setCurrentCell(7, 1), btn(rt, "Delete")->click(), wait(200);
check(rules->rowCount() == 7 && serverJson(0)["rules"].toArray().size() == 7, "rule deleted: table 7 rows, servers.json 7 rules");
// ---- autopilot setting
QWidget *it = tab("Insights");
for (auto *sp : it->findChildren<QSpinBox *>()) if (sp->suffix() == " / hour max") sp->setValue(5);
wait(200);
check(serverJson(0)["autopilot"].toObject()["maxRestartsPerHour"].toInt() == 5 && serverJson(0)["autopilot"].toObject()["dryRun"].toBool() && local->config().autopilot.maxRestartsPerHour == 5, "autopilot 'max restarts per hour' = 5 saved to servers.json, dry run still on");
btn(it, "Analyze now")->click(), wait(300);
check(local->analysis().when > 0, QString("Analyze now ran: health %1, %2 finding(s)").arg(local->analysis().health).arg(local->analysis().findings.size()));
// ---- console
QWidget *ct = tab("Console");
auto *in = ct->findChild<QLineEdit *>();
auto *out = ct->findChild<QPlainTextEdit *>();
in->setText("echo sm-click-test"), emit in->returnPressed();
check(waitFor([&] { return out->toPlainText().contains("[exit"); }, 15000) && out->toPlainText().contains(QRegularExpression("\\n.*sm-click-test.*\\n(.|\\n)*\\[exit 0")), "console 'echo sm-click-test' printed its output and exit 0");
note(out->toPlainText().section('\n', -3).replace('\n', " | "));
btn(ct, "Disk usage")->click();
check(waitFor([&] { return out->toPlainText().count("[exit") == 2; }, 20000), "quick diagnostic 'Disk usage' finished");
const int blocks = out->document()->blockCount();
sayNo(), btn(ct, "Reboot")->click(), wait(700);
check(asked.contains("Reboot on This computer?") && out->document()->blockCount() == blocks, "Reboot asks first (answered No, nothing ran): '" + asked.section('\n', 0, 0) + "'");
in->setText(P::posixCpu ? "sleep 30" : "Start-Sleep 30"), emit in->returnPressed();
wait(1000), btn(&w, u8"⟳ Reconnect")->click();
const bool told = waitFor([&] { return out->toPlainText().contains("[exit -1"); }, 4000);
check(told || !P::posixCpu, // the stand-in powershell returns at once, so nothing is pending there
"Reconnect while a command runs: the console is told (" + out->toPlainText().section('\n', -2).replace('\n', " | ") + ")");
check(waitFor([&] { return local->online(); }, 20000) && !local->analysis().healthReasons.join(' ').contains("unreachable"), "online again after Reconnect, analysis is fresh: " + local->analysis().healthReasons.join(", "));
open(0), tab("Console");
check(out->toPlainText().count("Console for") == 1, QString("opening the same server again: 'Console for' header appears %1 time(s)").arg(out->toPlainText().count("Console for")));
// ---- add-server dialog with Test connection (cancelled)
onModal([](QWidget *m) {
auto *d = qobject_cast<QDialog *>(m);
QComboBox *via = nullptr;
for (auto *c : d->findChildren<QComboBox *>()) if (!c->isEditable()) via = c;
auto result = [d] { for (auto *l : d->findChildren<QLabel *>()) if (l->text().startsWith(u8"✓") || l->text().startsWith(u8"✗")) return l->text(); return QString(); };
via->setCurrentIndex(0);
btn(d, "Test connection")->click();
waitFor([&] { return !result().isEmpty(); }, 15000);
check(result().startsWith(u8"✓"), "Test connection, this machine: " + result());
via->setCurrentIndex(1);
for (auto *e : d->findChildren<QLineEdit *>()) if (e->placeholderText().startsWith("hostname")) e->setText("127.0.0.1");
for (auto *sp : d->findChildren<QSpinBox *>()) if (sp->prefix() == "port ") sp->setValue(1);
btn(d, "Test connection")->click(), wait(200);
waitFor([&] { return result().startsWith(u8"✗"); }, 25000);
check(result().startsWith(u8"✗"), "Test connection, SSH to a closed port: " + result());
d->reject();
});
btn(sideW, "+ Add")->click(), wait(300);
check(mgr.sessions().size() == 2, "add-server dialog cancelled: still 2 servers");
// ---- offline host: every tab, downtime samples
open(1);
for (int i = 0; i < tabs->count(); ++i) tabs->setCurrentIndex(i), wait(250);
ServerSession *off = mgr.sessions()[1];
btn(tab("Insights"), "Analyze now")->click(), wait(800), w.grab().save(qEnvironmentVariable("SM_SHOTS") + "/offline-insights.png");
tab("History"), wait(500), w.grab().save(qEnvironmentVariable("SM_SHOTS") + "/offline-history.png");
const int down = off->store().tier(Tier::Raw).size();
check(off->status() != Status::Online && down >= run.elapsed() / 2000 * 0.6, QString("offline host: all tabs opened; %1 downtime samples in %2 s at a 2 s interval").arg(down).arg(run.elapsed() / 1000));
// ---- events page
for (auto *b : sideW->findChildren<QAbstractButton *>()) if (b->text().contains("Events")) b->click();
wait(300);
QTableWidget *ev = stack->currentWidget()->findChild<QTableWidget *>();
check(ev && ev->columnCount() == 4 && ev->rowCount() > 0, QString("events page lists %1 event(s)").arg(ev ? ev->rowCount() : -1));
for (int r = 0; ev && r < qMin(4, ev->rowCount()); ++r) note(ev->item(r, 2)->text() + " " + ev->item(r, 1)->text() + " " + ev->item(r, 3)->text().left(110));
auto *ef = stack->currentWidget()->findChild<QComboBox *>();
ef->setCurrentIndex(ef->findText("critical")), wait(100);
bool crit = true;
for (int r = 0; r < ev->rowCount(); ++r) crit &= ev->item(r, 2)->text() == "CRITICAL";
check(crit, QString("event filter 'critical': %1 row(s), all critical").arg(ev->rowCount()));
// ---- remove the server while its logs dialog is open (scratch config)
open(0);
check(!logs.isNull() && logs->isVisible(), "logs dialog still open");
onModal([](QWidget *m) { btn(m, "Remove + delete history")->click(); });
side->setCurrentRow(0), btn(sideW, "Remove")->click(), wait(500);
check(mgr.sessions().size() == 1 && !tabs->isVisible() && !QDir(ServerManager::configDir() + "/history/local1").exists(), "server removed with its history folder, dashboard shown");
if (logs) btn(logs, "Reload")->click(), wait(500), btn(logs, "Close")->click(), wait(200);
check(logs.isNull(), "Reload + Close in the orphaned logs dialog: no crash");
wait(500);
printf("%s (%d failed) in %lld s\n", fails ? "FAILED" : "ALL PASSED", fails, run.elapsed() / 1000);
return fails != 0;
}
|