CmvrControlStation/tests/application_shell_test.cpp

346 lines
18 KiB
C++

#include "mainwindow.h"
#include "applicationstyle.h"
#include "urdfviewerwidget.h"
#include "taskorchestrationwidget.h"
#include "bioheadoperations.h"
#include "bioheadwidget.h"
#include "robotclient.h"
#include <QApplication>
#include <QCheckBox>
#include <QComboBox>
#include <QAbstractItemView>
#include <QDialog>
#include <QPushButton>
#include <QTimer>
#include <QDebug>
#include <QFile>
#include <QLabel>
#include <QTextStream>
#include <QTreeWidget>
#include <QListWidget>
#include <QEventLoop>
#include <QTabWidget>
#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QGraphicsView>
#include <QMouseEvent>
struct TaskFlowTestAccess
{
static bool verify()
{
TaskOrchestrationWidget w;
w.m_tree->clear(); w.m_insertionParent = nullptr; w.m_insertionIndex = -1;
auto task = [&](const QString &name) {
return w.itemFromJson(QJsonObject{{"kind", "task"}, {"name", name},
{"deviceType", QStringLiteral("仿生头")}, {"deviceId", "bio_head"},
{"action", QStringLiteral("高兴")}, {"waitMs", 0}});
};
auto *a = task("A"); auto *b = task("B"); auto *d = task("D"); auto *c = task("C");
auto *loop = w.itemFromJson(QJsonObject{{"kind", "loop"}, {"name", "Outer"}, {"count", 2}});
auto *nested = w.itemFromJson(QJsonObject{{"kind", "loop"}, {"name", "Inner"}, {"count", 2}});
w.m_tree->addTopLevelItems({a, loop, c});
loop->addChildren({b, nested}); nested->addChild(d);
loop->setExpanded(true); nested->setExpanded(true);
w.rebuildFlowScene();
int edges = 0, memberships = 0;
QList<QRectF> cards;
for (auto *g : w.m_flowScene->items()) {
edges += g->data(0).toString() == "sequence";
memberships += g->data(0).toString() == "membership";
if (g->data(0).toString() == "taskNode") cards.append(g->sceneBoundingRect());
}
if (edges != 3 || memberships != 3) return false;
for (int i = 0; i < cards.size(); ++i) for (int j = i + 1; j < cards.size(); ++j)
if (cards[i].intersects(cards[j])) return false;
auto select = [&](const QString &name) {
w.m_flowScene->clearSelection();
for (auto *g : w.m_flowScene->items())
if (g->data(0).toString() == "taskNode" && g->data(1).toString() == name) {
g->setSelected(true); return true;
}
return false;
};
if (!select("Outer") || w.m_insertionParent || w.m_insertionIndex != 2) return false;
auto *x = task("X"); w.insertNode(x);
if (w.m_tree->topLevelItem(2) != x || loop->childCount() != 2) return false;
if (!select("B") || w.m_insertionParent != loop || w.m_insertionIndex != 1) return false;
if (!w.m_insertionHint->text().contains("Outer")) return false;
auto *y = task("Y"); w.insertNode(y);
if (loop->child(1) != y || nested->childCount() != 1) return false;
if (!select("Outer") || !w.useSelectedLoopAsInsertionParent()) return false;
if (w.m_insertionParent != loop || w.m_tree->currentItem()) return false;
auto *z = task("Z"); w.insertNode(z);
if (loop->child(3) != z) return false;
w.moveFlowItem(z, QPointF(-100000, 0));
if (z->parent() != loop || loop->child(0) != z) return false;
w.moveFlowItem(z, QPointF(100000, 0));
if (z->parent() != loop || loop->child(3) != z) return false;
w.setInsertionAtRoot();
if (w.m_insertionParent || w.m_tree->currentItem()
|| !w.m_insertionHint->text().contains(QStringLiteral("根流程(末尾)"))) return false;
// A click does not pass through the drag code; moving preserves nesting.
w.m_tree->setCurrentItem(loop); w.moveSelected(1);
if (!loop->isExpanded() || !nested->isExpanded() || d->parent() != nested) return false;
QList<TaskOrchestrationWidget::RunStep> steps; QString error;
if (!w.appendRunSteps(loop, steps, &error) || steps.size() != 10) return false;
const QStringList expected{"B", "Y", "D", "D", "Z", "B", "Y", "D", "D", "Z"};
for (int i = 0; i < steps.size(); ++i) if (steps[i].name != expected[i]) return false;
nested->setExpanded(false); w.save();
TaskOrchestrationWidget loaded;
QTreeWidgetItem *loadedLoop = nullptr;
for (int i = 0; i < loaded.m_tree->topLevelItemCount(); ++i)
if (loaded.m_tree->topLevelItem(i)->text(0) == "Outer") loadedLoop = loaded.m_tree->topLevelItem(i);
if (!loadedLoop || loadedLoop->child(2)->isExpanded()) return false;
auto *empty = w.itemFromJson(QJsonObject{{"kind", "loop"}, {"name", "Empty"}, {"count", 2}});
steps.clear(); bool rejected = !w.appendRunSteps(empty, steps, &error); delete empty;
if (!rejected || error.isEmpty()) return false;
w.resize(1500, 900); w.show(); qApp->processEvents();
QGraphicsItem *cardA = nullptr;
for (auto *g : w.m_flowScene->items())
if (g->data(0).toString() == "taskNode" && g->data(1).toString() == "A") cardA = g;
if (!cardA) return false;
w.m_flowView->ensureVisible(cardA);
const QPoint point = w.m_flowView->mapFromScene(cardA->sceneBoundingRect().center());
const QPoint global = w.m_flowView->viewport()->mapToGlobal(point);
const quint64 revision = w.m_sceneRevision;
QMouseEvent press(QEvent::MouseButtonPress, point, global, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QMouseEvent release(QEvent::MouseButtonRelease, point, global, Qt::LeftButton, Qt::NoButton, Qt::NoModifier);
QApplication::sendEvent(w.m_flowView->viewport(), &press);
QApplication::sendEvent(w.m_flowView->viewport(), &release);
qApp->processEvents();
if (w.m_sceneRevision != revision || w.m_tree->currentItem() != a
|| w.m_insertionParent || w.m_insertionIndex != 1) return false;
const QJsonObject beforeFold = w.itemToJson(loop);
QGraphicsItem *loopCard = nullptr;
for (auto *g : w.m_flowScene->items())
if (g->data(0).toString() == "taskNode" && g->data(1).toString() == "Outer") loopCard = g;
if (!loopCard) return false;
w.m_flowView->ensureVisible(loopCard);
const QPoint toggle = w.m_flowView->mapFromScene(loopCard->scenePos() + QPointF(246, 21));
const QPoint toggleGlobal = w.m_flowView->viewport()->mapToGlobal(toggle);
QMouseEvent foldPress(QEvent::MouseButtonPress, toggle, toggleGlobal, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QMouseEvent foldRelease(QEvent::MouseButtonRelease, toggle, toggleGlobal, Qt::LeftButton, Qt::NoButton, Qt::NoModifier);
QApplication::sendEvent(w.m_flowView->viewport(), &foldPress);
QApplication::sendEvent(w.m_flowView->viewport(), &foldRelease);
qApp->processEvents();
QJsonObject afterFold = w.itemToJson(loop);
afterFold.insert("collapsed", beforeFold.value("collapsed"));
if (loop->isExpanded() || afterFold != beforeFold) return false;
loop->setExpanded(true); w.rebuildFlowScene();
w.grab().save(QStringLiteral("task-flow-interactions.png"));
qInfo() << "Task flow: insertion contexts, nested order, edges, drag scope and persistence PASS";
return true;
}
};
static bool verifyBioheadPage()
{
RobotClient client;
// Prevent any dispatch to the real worker; inspect requests and inject replies.
QObject::disconnect(&client, &RobotClient::rpcRequested, nullptr, nullptr);
BioHeadWidget page(&client);
page.resize(1250, 850);
page.show();
auto *devices = page.findChild<QComboBox *>(QStringLiteral("bioheadDeviceCombo"));
auto *status = page.findChild<QLabel *>(QStringLiteral("bioheadStatus"));
auto *tabs = page.findChild<QTabWidget *>();
if (!devices || !status || !tabs || tabs->count() != 2) return false;
QPushButton *happy = nullptr;
int count = 0;
for (auto *button : page.findChildren<QPushButton *>()) {
if (button->property("bioheadAction").isValid()) {
++count;
if (button->isEnabled()) return false;
if (button->property("bioheadAction") == QStringLiteral("高兴")) happy = button;
}
}
if (count != 10 || !happy) return false;
const QVariantList list{QVariantMap{{"deviceId", "bio_head"}, {"type", 8}},
QVariantMap{{"deviceId", "usb_cam1"}, {"type", 2}}};
page.setAvailableDevices(list);
emit client.connectionChanged(true, 0, QString());
if (devices->count() != 1 || !happy->isEnabled()) return false;
bool dispatched = false;
QObject::connect(&client, &RobotClient::rpcRequested, &page,
[&](const QString &service, const QString &method, const QString &json, const QString &id) {
dispatched = service == QStringLiteral("cmvr.api.BioHeadService") && method == QStringLiteral("Happy")
&& id == QStringLiteral("bio_head") && QJsonDocument::fromJson(json.toUtf8()).object()
.value(QStringLiteral("header")).toObject().value(QStringLiteral("deviceId")).toString() == id;
});
happy->click();
if (!dispatched || happy->isEnabled()) return false;
emit client.rpcFinished(QStringLiteral("cmvr.api.BioHeadService"), QStringLiteral("Happy"), true,
QStringLiteral("{\"header\":{\"errorMessage\":\"device rejected\"}}"));
if (!happy->isEnabled() || !status->text().contains(QStringLiteral("device rejected"))) return false;
page.setAvailableDevices(list);
if (!status->text().contains(QStringLiteral("device rejected"))) return false;
page.grab().save(QStringLiteral("biohead-page.png"));
emit client.connectionChanged(false, 0, QString());
if (happy->isEnabled()) return false;
return true;
}
static bool verifyBioheadTaskRun()
{
// Isolated from MainWindow/RobotClient: no real connection or hardware calls.
TaskOrchestrationWidget tasks;
auto *tree = tasks.findChild<QTreeWidget *>();
if (!tree) return false;
tree->clear();
for (const QString &action : {QStringLiteral("开始说话"), QStringLiteral("停止说话"),
QStringLiteral("高兴")}) {
auto *item = new QTreeWidgetItem(tree);
item->setText(0, action);
item->setData(0, Qt::UserRole, QStringLiteral("task"));
item->setData(0, Qt::UserRole + 1, QStringLiteral("仿生头"));
item->setData(0, Qt::UserRole + 2, QStringLiteral("bio_head"));
item->setData(0, Qt::UserRole + 3, action);
item->setData(0, Qt::UserRole + 4, QStringLiteral("{}"));
item->setData(0, Qt::UserRole + 5, 40);
}
QPushButton *run = nullptr;
for (auto *button : tasks.findChildren<QPushButton *>())
if (button->text() == QStringLiteral("执行任务编排")) run = button;
if (!run) return false;
int requests = 0;
bool valid = true;
QEventLoop loop;
QObject::connect(&tasks, &TaskOrchestrationWidget::taskRequested, &tasks,
[&](const QString &type, const QString &id, const QString &action, const QJsonObject &) {
++requests;
valid = valid && type == QStringLiteral("仿生头") && id == QStringLiteral("bio_head");
const QString method = BioHeadOperations::method(action);
tasks.completeRpcTask(QStringLiteral("wrong.service"), method, true,
QStringLiteral("{\"header\":{\"success\":true}}"));
QTimer::singleShot(10, &tasks, [&, method]() {
const bool first = requests == 1;
tasks.completeRpcTask(QStringLiteral("cmvr.api.BioHeadService"), method, true,
first ? QStringLiteral("{\"header\":{\"success\":true}}")
: QStringLiteral("{\"header\":{\"errorMessage\":\"test rejection\"}}"));
});
});
run->click();
QTimer::singleShot(300, &loop, &QEventLoop::quit);
loop.exec();
auto *history = tasks.findChild<QListWidget *>();
bool failureShown = false;
if (history) for (int i = 0; i < history->count(); ++i)
failureShown |= history->item(i)->text().contains(QStringLiteral("test rejection"));
return valid && requests == 2 && run->isEnabled() && failureShown;
}
int main(int argc, char **argv)
{
QApplication application(argc, argv);
application.setApplicationName(QStringLiteral("CMVR Theme Verification"));
application.setOrganizationName(QStringLiteral("CMVR Tests"));
ApplicationStyle::install(application);
if (!TaskFlowTestAccess::verify()) return 11;
if (!verifyBioheadPage()) return 10;
if (!verifyBioheadTaskRun()) return 9;
if (application.windowIcon().pixmap(32, 32).isNull()) return 1;
MainWindow window;
if (auto *demo = window.findChild<QCheckBox *>(QStringLiteral("demoCheck")))
demo->setChecked(false);
window.resize(1600, 1000);
window.show();
QTimer::singleShot(150, &window, [&]() {
int comboCount = 0;
QStringList audit;
for (QComboBox *combo : window.findChildren<QComboBox *>()) {
combo->ensurePolished();
if (!combo->view()->styleSheet().contains(QStringLiteral("#e8f1ff"))) {
qCritical() << "Unthemed combo:" << combo->objectName(); application.exit(6); return;
}
++comboCount;
audit.append(QStringLiteral("PASS %1 / %2").arg(combo->metaObject()->className(), combo->objectName()));
}
QFile report(QStringLiteral("combo-audit.txt"));
if (report.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream stream(&report);
stream << "Main-window combos: " << comboCount << '\n' << audit.join('\n') << '\n';
}
report.close();
qInfo() << "Themed main-window combo count:" << comboCount;
window.grab().save(QStringLiteral("application-system.png"));
QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 1));
application.processEvents();
const auto viewers = window.findChildren<UrdfViewerWidget *>();
for (const auto *viewer : viewers) if (viewer->modelPreviewEnabled()) { application.exit(2); return; }
window.grab().save(QStringLiteral("application-arm.png"));
QMetaObject::invokeMethod(&window, "selectPage", Qt::DirectConnection, Q_ARG(int, 16));
application.processEvents();
window.grab().save(QStringLiteral("application-tasks.png"));
if (auto *tasks = window.findChild<TaskOrchestrationWidget *>()) {
tasks->setAvailableDevices({QVariantMap{{"deviceId", "usb_cam1"}, {"type", 2}},
QVariantMap{{"deviceId", "mic1"}, {"type", 5}},
QVariantMap{{"deviceId", "bio_head"}, {"type", 8}}});
QPushButton *add = nullptr;
for (auto *button : tasks->findChildren<QPushButton *>())
if (button->text().contains(QStringLiteral("任务节点"))) { add = button; break; }
if (!add) { application.exit(7); return; }
bool taskInspected = false;
QTimer::singleShot(100, &window, [&]() {
auto *dialog = qobject_cast<QDialog *>(QApplication::activeModalWidget());
if (!dialog) return;
auto *title = dialog->findChild<QLabel *>(QStringLiteral("jointFlowDialogTitle"));
taskInspected = title && title->text() == QStringLiteral("任务节点参数");
int count = 0;
for (QComboBox *combo : dialog->findChildren<QComboBox *>()) {
combo->ensurePolished();
taskInspected = taskInspected && combo->view()->styleSheet().contains(QStringLiteral("#e8f1ff"));
++count;
}
QComboBox *devices = nullptr;
for (auto *combo : dialog->findChildren<QComboBox *>())
for (int i = 0; i < combo->count(); ++i)
if (combo->itemData(i).toMap().value(QStringLiteral("deviceId"))
== QStringLiteral("bio_head")) {
devices = combo;
combo->setCurrentIndex(i);
break;
}
bool bioheadActions = false;
for (auto *combo : dialog->findChildren<QComboBox *>())
if (combo->findText(QStringLiteral("开始说话")) >= 0)
bioheadActions = combo->count() == BioHeadOperations::actions().size()
&& combo->findText(QStringLiteral("紧急停止")) >= 0;
taskInspected = taskInspected && devices && bioheadActions;
if (report.open(QIODevice::Append | QIODevice::Text)) {
QTextStream stream(&report);
stream << "Task-node dialog combos: " << count << " / " << (taskInspected ? "PASS" : "FAIL") << '\n';
report.close();
}
dialog->grab().save(QStringLiteral("task-node-dialog.png"));
dialog->reject();
});
add->click();
if (!taskInspected) { application.exit(8); return; }
}
QPushButton *settings = nullptr;
for (QPushButton *button : window.findChildren<QPushButton *>())
if (button->text() == QStringLiteral("软件设置")) settings = button;
if (!settings) { application.exit(3); return; }
bool inspected = false;
QTimer::singleShot(100, &window, [&]() {
auto *dialog = qobject_cast<QDialog *>(QApplication::activeModalWidget());
if (dialog && dialog->objectName() == QStringLiteral("applicationSettingsDialog")) {
inspected = dialog->property("applicationChrome").toBool()
&& !(dialog->windowFlags() & Qt::WindowStaysOnTopHint);
for (QComboBox *combo : dialog->findChildren<QComboBox *>()) {
combo->ensurePolished();
inspected = inspected && combo->view()->styleSheet().contains(QStringLiteral("#e8f1ff"));
}
dialog->grab().save(QStringLiteral("application-settings.png"));
dialog->reject();
}
});
settings->click();
qInfo() << "Theme shell: navigation, disabled model default, icon and settings verified";
application.exit(inspected ? 0 : 4);
});
QTimer::singleShot(12000, &application, [&]() { application.exit(5); });
return application.exec();
}