CmvrControlStation/tests/agvmapeditor_upload_integration_test.cpp

646 lines
33 KiB
C++
Raw Normal View History

#include "agvmapdocument.h"
#include "agvmapeditorwidget.h"
#include "agvmaprasterizer.h"
#include "agvmapviewwidget.h"
#include "robotclient.h"
#include "cmvr/api/agv_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <QApplication>
#include <QCheckBox>
#include <QDateTime>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDoubleSpinBox>
#include <QElapsedTimer>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
#include <QLineEdit>
#include <QPointer>
#include <QPushButton>
#include <QThread>
#include <QTimer>
#include <QVBoxLayout>
#include <chrono>
#include <cmath>
#include <functional>
#include <iostream>
#include <mutex>
#include <vector>
namespace {
void require(bool condition, const char *message)
{
if (!condition)
qFatal("AGV editor upload integration failed: %s", message);
}
void waitFor(const std::function<bool()> &ready, const char *message)
{
QElapsedTimer timer;
timer.start();
while (!ready() && timer.elapsed() < 7000) {
QApplication::processEvents();
QThread::msleep(2);
}
require(ready(), message);
}
void fillDialog(const QString &kind, const std::function<void(QDialog *)> &fill)
{
auto *timer = new QTimer(qApp);
timer->setInterval(5);
QObject::connect(timer, &QTimer::timeout, timer, [timer, kind, fill]() {
auto *dialog = qobject_cast<QDialog *>(QApplication::activeModalWidget());
if (!dialog || dialog->objectName() != kind)
return;
timer->stop();
fill(dialog);
dialog->findChild<QDialogButtonBox *>()->button(QDialogButtonBox::Ok)->click();
timer->deleteLater();
});
timer->start();
QTimer::singleShot(7000, qApp, [guard = QPointer<QTimer>(timer)]() {
if (guard && guard->isActive())
qFatal("AGV editor upload integration failed: expected modal did not open");
});
}
QString rootToken(const QString &content, const QString &key)
{
int start = content.indexOf(QLatin1Char('"') + key + QStringLiteral("\":"));
require(start >= 0, "native map contains a requested root token");
start += key.size() + 3;
while (content.at(start).isSpace())
++start;
int depth = 0;
bool quoted = false;
for (int index = start; index < content.size(); ++index) {
const QChar character = content.at(index);
if (quoted) {
if (character == QLatin1Char('\\'))
++index;
else if (character == QLatin1Char('"'))
quoted = false;
} else if (character == QLatin1Char('"')) {
quoted = true;
} else if (character == QLatin1Char('{') || character == QLatin1Char('[')) {
++depth;
} else if (character == QLatin1Char('}') || character == QLatin1Char(']')) {
if (--depth == 0)
return content.mid(start, index - start + 1);
}
}
qFatal("AGV editor upload integration failed: unbalanced root token");
return QString();
}
struct Upload {
cmvr::api::AgvMapCommand::Request request;
qint64 deadlineMs;
};
// This is the ONLY server used by the test. It binds an ephemeral loopback
// port and never forwards map commands to a controller or external service.
class FakeAgvService final : public cmvr::api::AgvService::Service
{
public:
enum Result { Success, ControllerRejected, TransportFailed, AckBeforePersistence,
AckWithoutPersistence, ReformattedPersistence, PersistenceMissingLastRoute,
PersistenceWrongStationName };
FakeAgvService(QString name, QString content)
: m_name(std::move(name)), m_content(std::move(content)) {}
grpc::Status downloadMap(grpc::ServerContext *,
const cmvr::api::AgvMapCommand::Request *request,
cmvr::api::AgvMapCommand::Feedback *response) override
{
std::lock_guard<std::mutex> guard(m_mutex);
m_events.append(QStringLiteral("download:") + QString::fromStdString(request->map_name()));
m_downloads.push_back(*request);
if (!m_pendingContent.isEmpty() && m_pendingOldReads >= 0) {
if (m_pendingOldReads == 0) {
m_content = m_pendingContent;
m_pendingContent.clear();
} else {
--m_pendingOldReads;
}
}
if (m_failRead || QString::fromStdString(request->map_name()) != m_name) {
m_failRead = false;
response->mutable_header()->set_success(false);
response->mutable_header()->set_error_message("fixture latest map read denied");
} else {
response->mutable_header()->set_success(true);
response->set_content(m_content.toUtf8().toStdString());
}
return grpc::Status::OK;
}
grpc::Status uploadMap(grpc::ServerContext *context,
const cmvr::api::AgvMapCommand::Request *request,
cmvr::api::AgvMapCommand::Feedback *response) override
{
std::lock_guard<std::mutex> guard(m_mutex);
const qint64 deadlineMs = std::chrono::duration_cast<std::chrono::milliseconds>(
context->deadline() - std::chrono::system_clock::now()).count();
m_uploads.push_back({*request, deadlineMs});
m_events.append(QStringLiteral("upload:") + QString::fromStdString(request->map_name()));
const Result result = m_nextResult;
m_nextResult = Success;
if (result == TransportFailed)
return grpc::Status(grpc::StatusCode::UNAVAILABLE, "fixture upload transport failed");
if (result == ControllerRejected) {
response->mutable_header()->set_success(false);
response->mutable_header()->set_error_message("SEER ret_code=40050 err_msg=need map header");
} else {
const QString uploaded = QString::fromUtf8(request->content().data(),
static_cast<int>(request->content().size()));
m_pendingContent.clear();
if (result == AckBeforePersistence || result == AckWithoutPersistence) {
m_pendingContent = uploaded;
m_pendingOldReads = result == AckBeforePersistence ? 2 : -1;
} else if (result == ReformattedPersistence) {
m_content = QString::fromUtf8(QJsonDocument::fromJson(uploaded.toUtf8())
.toJson(QJsonDocument::Indented));
} else if (result == PersistenceMissingLastRoute) {
QJsonObject partial = QJsonDocument::fromJson(uploaded.toUtf8()).object();
QJsonArray curves = partial.value("advancedCurveList").toArray();
require(!curves.isEmpty(), "partial-persistence fixture has a route to omit");
curves.removeLast();
partial.insert("advancedCurveList", curves);
m_content = QString::fromUtf8(QJsonDocument(partial).toJson(QJsonDocument::Compact));
} else if (result == PersistenceWrongStationName) {
QJsonObject partial = QJsonDocument::fromJson(uploaded.toUtf8()).object();
QJsonArray points = partial.value("advancedPointList").toArray();
require(!points.isEmpty(), "wrong-name fixture has a station to alter");
QJsonObject point = points.last().toObject();
point.insert("description", "wrong persisted station name");
points.replace(points.size() - 1, point);
partial.insert("advancedPointList", points);
m_content = QString::fromUtf8(QJsonDocument(partial).toJson(QJsonDocument::Compact));
} else {
m_content = uploaded;
}
response->mutable_header()->set_success(true);
}
return grpc::Status::OK;
}
void replaceLatest(const QString &content)
{
std::lock_guard<std::mutex> guard(m_mutex);
m_content = content;
}
void nextResult(Result result)
{
std::lock_guard<std::mutex> guard(m_mutex);
m_nextResult = result;
}
void denyNextRead()
{
std::lock_guard<std::mutex> guard(m_mutex);
m_failRead = true;
}
int downloads()
{
std::lock_guard<std::mutex> guard(m_mutex);
return static_cast<int>(m_downloads.size());
}
int uploads()
{
std::lock_guard<std::mutex> guard(m_mutex);
return static_cast<int>(m_uploads.size());
}
Upload upload(int index)
{
std::lock_guard<std::mutex> guard(m_mutex);
return m_uploads.at(index);
}
QString stored()
{
std::lock_guard<std::mutex> guard(m_mutex);
return m_content;
}
QStringList events()
{
std::lock_guard<std::mutex> guard(m_mutex);
return m_events;
}
private:
std::mutex m_mutex;
QString m_name;
QString m_content;
QString m_pendingContent;
std::vector<cmvr::api::AgvMapCommand::Request> m_downloads;
std::vector<Upload> m_uploads;
QStringList m_events;
Result m_nextResult = Success;
bool m_failRead = false;
int m_pendingOldReads = -1;
};
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Q_INIT_RESOURCE(resources);
require(argc > 1, "pass an already-downloaded native SMAP path; the test never downloads from a vehicle");
QFile source(QString::fromLocal8Bit(argv[1]));
require(source.open(QIODevice::ReadOnly), "local selected native map opens");
const QString native = QString::fromUtf8(source.readAll());
const QJsonObject original = QJsonDocument::fromJson(native.toUtf8()).object();
const QString mapName = original.value("header").toObject().value("mapName").toString();
const QString originalId = original.value("advancedPointList").toArray().first()
.toObject().value("instanceName").toString();
require(!mapName.isEmpty() && !originalId.isEmpty(), "selected map identifies its native header and stations");
const QString headerToken = rootToken(native, "header");
const QString scanToken = rootToken(native, "normalPosList");
const QString lineToken = original.contains("advancedLineList")
? rootToken(native, "advancedLineList") : QString();
FakeAgvService service(mapName, native);
grpc::ServerBuilder builder;
int port = 0;
builder.AddListeningPort("127.0.0.1:0", grpc::InsecureServerCredentials(), &port);
builder.RegisterService(&service);
const std::unique_ptr<grpc::Server> server = builder.BuildAndStart();
require(server && port > 0, "only an ephemeral loopback fake server is started");
RobotClient client;
bool connected = false;
bool editorBusy = false;
int saved = 0;
int failed = 0;
int uploadAcks = 0;
bool injectStaleReadback = false;
bool staleReadbackInjected = false;
int staleAckBaseline = 0;
int staleSavedBaseline = 0;
QString failure;
QString lastDispatchedContent;
QString lastDispatchedMap;
QObject::connect(&client, &RobotClient::connectionChanged,
[&](bool available, int, const QString &) { connected = available; });
QObject::connect(&client, &RobotClient::agvMapSaveRequested,
[&](quint64, const QString &, const QString &name, const QString &content) {
lastDispatchedMap = name;
lastDispatchedContent = content;
});
QObject::connect(&client, &RobotClient::agvMapSaveFinished,
[&](quint64, const QString &, const QString &, bool success, const QString &detail) {
if (!success) {
++failed;
failure = detail;
} else
++uploadAcks;
});
QObject::connect(&client, &RobotClient::agvMapContentRequested,
[&](quint64 token, const QString &requestDevice, const QString &requestMap) {
if (!injectStaleReadback || uploadAcks <= staleAckBaseline)
return;
injectStaleReadback = false;
staleReadbackInjected = true;
// All three responses carry the exact desired new map so accepting
// any stale identity would falsely commit the still-old fixture.
client.agvMapContentReceived(token - 1, requestDevice, requestMap,
lastDispatchedContent, true, "late prior token");
client.agvMapContentReceived(token, requestDevice + "_old", requestMap,
lastDispatchedContent, true, "wrong device");
client.agvMapContentReceived(token, requestDevice, requestMap + "_old",
lastDispatchedContent, true, "wrong map");
require(saved == staleSavedBaseline && editorBusy,
"stale token/device/map verification replies cannot commit the saved draft or unlock editing");
});
client.connectToServer("127.0.0.1", port, false);
waitFor([&]() { return connected; }, "real RobotClient connects only to this loopback fake service");
QWidget window;
auto *layout = new QVBoxLayout(&window);
auto *view = new AgvMapViewWidget(&window);
auto *editor = new AgvMapEditorWidget(&client, view, &window);
layout->addWidget(editor);
layout->addWidget(view);
window.resize(1050, 750);
QImage image;
QVariantMap metadata;
QString error;
require(renderAgvSmap2d(native, image, metadata, error), "actual downloaded scan builds the editor view");
view->setMapFrame(image, metadata);
const QString device = "fixture_upload_device";
QString selectedMap = mapName;
editor->setContextProvider([&]() {
AgvMapEditorWidget::Context context;
context.endpoint = QStringLiteral("127.0.0.1:%1").arg(port);
context.deviceId = device;
context.mapName = selectedMap;
context.connected = connected;
context.demo = false;
return context;
});
QObject::connect(editor, &AgvMapEditorWidget::mapSaved, [&]() { ++saved; });
QObject::connect(editor, &AgvMapEditorWidget::busyChanged, [&](bool value) { editorBusy = value; });
window.show();
editor->setAutoLoadEnabled(true);
auto *coordinate = editor->findChild<QPushButton *>("agvCoordinateStationButton");
auto *route = editor->findChild<QPushButton *>("agvAddRouteButton");
auto *save = editor->findChild<QPushButton *>("agvSaveMapObjectsButton");
auto *undo = editor->findChild<QPushButton *>("agvUndoMapObjectsButton");
auto *status = editor->findChild<QLabel *>("agvMapEditorStatus");
require(coordinate && route && save && undo && status, "actual editor controls are present");
waitFor([&]() { return service.downloads() == 1 && coordinate->isEnabled()
&& status->text().contains(QStringLiteral("地图已读取")); },
"editor initially reads the complete native selected map through RobotClient/gRPC");
const auto addStation = [&](const QString &id) {
fillDialog("agvStationDialog", [=](QDialog *dialog) {
dialog->findChild<QLineEdit *>("agvNewStationId")->setText(id);
dialog->findChild<QLineEdit *>("agvNewStationName")->setText(QStringLiteral("\"本地工位\""));
dialog->findChild<QDoubleSpinBox *>("agvNewStationX")->setValue(1.25);
dialog->findChild<QDoubleSpinBox *>("agvNewStationY")->setValue(0.5);
});
coordinate->click();
require(save->isEnabled() && undo->isEnabled(), "new station is an unsaved editor draft");
};
addStation("LM9001");
fillDialog("agvRouteDialog", [](QDialog *dialog) {
dialog->findChild<QLineEdit *>("agvNewRouteId")->setText("LOCAL_ROUTE");
dialog->findChild<QCheckBox *>("agvNewRouteBidirectional")->setChecked(true);
});
route->click();
view->stationSelected(originalId);
view->stationSelected("LM9001");
AgvMapDocument concurrent;
require(concurrent.load(native, &error)
&& concurrent.addStation("REMOTE_FROM_LATEST", -1.0, 0.75, 0, &error),
"prepare a concurrent server-side station update after the editor's first read");
QString latest = concurrent.content();
latest.insert(latest.lastIndexOf(QLatin1Char('}')),
QStringLiteral(",\"serverUnknown\":{\"uint64\":18446744073709551615,\"flag\":\"preserve latest\"}"));
service.replaceLatest(latest);
save->click();
waitFor([&]() { return saved == 1 && service.uploads() == 1 && !save->isEnabled(); },
"editor reads latest, merges local additions and receives successful real-client fake-gRPC upload response");
const auto verifyUpload = [&](int index) {
const Upload upload = service.upload(index);
const auto &request = upload.request;
const QString content = QString::fromUtf8(request.content().data(), static_cast<int>(request.content().size()));
const QJsonDocument json = QJsonDocument::fromJson(content.toUtf8());
require(request.map_name() == mapName.toStdString() && request.header().device_id() == device.toStdString()
&& request.header().valid_for_ms() == 10000 && !request.header().command_id().empty()
&& request.header().timestamp().seconds() > 0
&& std::abs(request.header().timestamp().seconds() - QDateTime::currentSecsSinceEpoch()) < 30,
"actual protobuf request retains target map/device and valid upload command header");
// gRPC encodes a rounded relative wire timeout; this bundled Windows
// runtime reports roughly 100 ms beyond the exact client deadline.
// valid_for_ms above remains exactly 10000, and this check excludes
// an unbounded or materially longer transport timeout.
if (!(upload.deadlineMs > 0 && upload.deadlineMs <= 10200))
qWarning("captured upload deadline remaining=%lld ms", static_cast<long long>(upload.deadlineMs));
require(upload.deadlineMs > 0 && upload.deadlineMs <= 10200,
"actual gRPC upload carries the bounded ten-second deadline");
require(json.isObject() && content.trimmed().startsWith('{')
&& json.object().value("header") == original.value("header")
&& content.contains(headerToken) && content.contains(scanToken) && content.contains(lineToken),
"actual request.content has root native header, all scan and advanced-line tokens unchanged");
require(!json.object().contains("map_content") && !json.object().contains("content")
&& !json.object().contains("advanced_point_list")
&& content.contains("18446744073709551615"),
"actual request.content is the complete native camel SMAP, never an escaped wrapper or lossy root reserialization");
AgvMapDocument parsed;
require(parsed.load(content, &error) && parsed.hasStation("REMOTE_FROM_LATEST")
&& parsed.hasStation("LM9001"), "fresh server objects survive alongside local additions");
return content;
};
const QString acceptedContent = verifyUpload(0);
require(acceptedContent == lastDispatchedContent && lastDispatchedMap == mapName,
"editor-dispatched text equals captured protobuf content byte-for-byte");
const QJsonObject accepted = QJsonDocument::fromJson(acceptedContent.toUtf8()).object();
require(accepted.value("normalPosList").toArray().size() == original.value("normalPosList").toArray().size()
&& accepted.value("advancedPointList").toArray().size() == original.value("advancedPointList").toArray().size() + 2
&& accepted.value("advancedCurveList").toArray().size() == original.value("advancedCurveList").toArray().size() + 2,
"native map retains its complete scan and merges the concurrent station plus local station/bidirectional routes");
require(service.events() == QStringList{QStringLiteral("download:") + mapName,
QStringLiteral("download:") + mapName, QStringLiteral("upload:") + mapName,
QStringLiteral("download:") + mapName},
"real save sequence is initial read, read-latest, upload and persistence readback of the same map");
if (argc > 2) {
QFile dump(QString::fromLocal8Bit(argv[2]));
require(dump.open(QIODevice::WriteOnly) && dump.write(acceptedContent.toUtf8()) == acceptedContent.toUtf8().size(),
"captured actual protobuf upload payload is optionally dumped locally");
}
qInfo("PASS: editor -> RobotClient -> loopback AgvService captures complete native selected map and read-latest merge");
addStation("LM9002");
service.nextResult(FakeAgvService::ControllerRejected);
save->click();
waitFor([&]() { return failed == 1 && save->isEnabled() && service.uploads() == 2; },
"business response failure returns to the editor with its draft available for retry");
verifyUpload(1);
require(saved == 1 && undo->isEnabled() && failure.contains("ret_code=40050")
&& status->text().contains("need map header"), "controller rejection is not falsely marked as saved");
AgvMapDocument persisted;
require(persisted.load(service.stored(), &error) && !persisted.hasStation("LM9002"),
"rejected local fake upload has no server-side persistence");
save->click();
waitFor([&]() { return saved == 2 && service.uploads() == 3 && !save->isEnabled(); },
"retry after business rejection re-reads, merges and saves through the actual client");
verifyUpload(2);
require(persisted.load(service.stored(), &error) && persisted.hasStation("LM9002"),
"successful retry persists the originally rejected draft in the fake service");
addStation("LM9003");
service.nextResult(FakeAgvService::TransportFailed);
save->click();
waitFor([&]() { return failed == 2 && service.uploads() == 4 && save->isEnabled(); },
"transport response failure preserves local editing and completes the real client callback");
verifyUpload(3);
require(saved == 2 && failure.contains("fixture upload transport failed") && undo->isEnabled(),
"transport failure never emits editor mapSaved or discards the draft");
addStation("LM9004");
service.denyNextRead();
const int oldUploads = service.uploads();
save->click();
waitFor([&]() { return save->isEnabled() && status->text().contains("fixture latest map read denied"); },
"read-latest failure returns an actionable save failure to the editor");
require(service.uploads() == oldUploads && saved == 2 && undo->isEnabled(),
"failed latest-map read prevents upload and preserves the unsaved local changes");
const int beforeDelayedSaves = saved;
const int beforeDelayedAcks = uploadAcks;
const int beforeDelayedReads = service.downloads();
const int beforeDelayedUploads = service.uploads();
staleAckBaseline = uploadAcks;
staleSavedBaseline = saved;
injectStaleReadback = true;
service.nextResult(FakeAgvService::AckBeforePersistence);
save->click();
waitFor([&]() { return uploadAcks == beforeDelayedAcks + 1
&& service.downloads() >= beforeDelayedReads + 2; },
"upload ACK is delivered before the fake service exposes the saved objects");
require(saved == beforeDelayedSaves && editorBusy && !save->isEnabled()
&& !undo->isEnabled() && !coordinate->isEnabled() && staleReadbackInjected,
"accepted upload with an old readback retains the dirty draft and busy lock rather than reporting saved");
const int uploadsAfterAck = service.uploads();
save->click();
require(service.uploads() == uploadsAfterAck, "repeated save click while verifying does not send another upload");
waitFor([&]() { return saved == beforeDelayedSaves + 1 && !editorBusy; },
"two stale readbacks are retried read-only until the actual updated map is downloadable");
require(service.uploads() == beforeDelayedUploads + 1
&& service.downloads() == beforeDelayedReads + 4
&& !save->isEnabled() && !undo->isEnabled(),
"delayed persistence uses one upload, one fresh pre-save read and exactly three verification reads");
require(persisted.load(service.stored(), &error) && persisted.hasStation("LM9003")
&& persisted.hasStation("LM9004"),
"all retained station drafts were actually persisted before editor mapSaved");
qInfo("PASS: upload ACK precedes persistence; old maps trigger bounded reads, never duplicate uploads or premature saved state");
addStation("LM9005");
const int beforeFormattedSaves = saved;
const int beforeFormattedUploads = service.uploads();
service.nextResult(FakeAgvService::ReformattedPersistence);
save->click();
waitFor([&]() { return saved == beforeFormattedSaves + 1 && !editorBusy; },
"semantically identical persisted objects confirm despite harmless JSON reformatting");
require(service.uploads() == beforeFormattedUploads + 1
&& service.stored() != lastDispatchedContent
&& persisted.load(service.stored(), &error) && persisted.hasStation("LM9005")
&& !save->isEnabled() && !undo->isEnabled(),
"verification compares edited station semantics rather than byte-for-byte full JSON text");
qInfo("PASS: JSON formatting changes do not cause false persistence mismatch");
addStation("LM9006");
const int beforeUnpersistedSaves = saved;
const int beforeUnpersistedAcks = uploadAcks;
const int beforeUnpersistedReads = service.downloads();
const int beforeUnpersistedUploads = service.uploads();
service.nextResult(FakeAgvService::AckWithoutPersistence);
save->click();
waitFor([&]() { return uploadAcks == beforeUnpersistedAcks + 1
&& service.downloads() >= beforeUnpersistedReads + 2; },
"ACK-only fixture starts persistence verification");
require(saved == beforeUnpersistedSaves && editorBusy && !save->isEnabled(),
"ACK-only save has no early mapSaved notification");
waitFor([&]() { return !editorBusy && save->isEnabled(); },
"bounded unchanged readbacks finish with an editable retained draft");
require(saved == beforeUnpersistedSaves && undo->isEnabled()
&& service.uploads() == beforeUnpersistedUploads + 1
&& service.downloads() > beforeUnpersistedReads + 1
&& service.downloads() <= beforeUnpersistedReads + 7,
"unchanged persistence has at most six readbacks, one upload and no draft commit");
require(persisted.load(service.stored(), &error) && !persisted.hasStation("LM9006"),
"fixture proves accepted upload and persisted map are independent");
const int readsAfterVerificationFailure = service.downloads();
const int uploadsAfterVerificationFailure = service.uploads();
for (int i = 0; i < 20; ++i)
editor->refreshContext();
require(service.downloads() == readsAfterVerificationFailure
&& service.uploads() == uploadsAfterVerificationFailure,
"context polling after unconfirmed persistence never starts a hidden upload or another verification loop");
const auto draftFrame = [&]() {
QVariantMap currentMetadata = metadata;
currentMetadata.insert("mapId", selectedMap);
view->setMapFrame(image, currentMetadata);
editor->refreshContext();
};
editor->setAutoLoadEnabled(false);
selectedMap = QStringLiteral("unloaded_other_map");
draftFrame();
selectedMap = mapName;
draftFrame();
require(save->isEnabled() && undo->isEnabled() && saved == beforeUnpersistedSaves
&& service.uploads() == uploadsAfterVerificationFailure,
"switching away and back once retains the unconfirmed draft without implicit persistence");
qInfo("PASS: ACK without persistence times out boundedly and retains draft across one map revisit without re-upload");
const int beforeRetrySaves = saved;
service.nextResult(FakeAgvService::Success);
save->click();
waitFor([&]() { return saved == beforeRetrySaves + 1 && !editorBusy; },
"operator can explicitly retry the retained unconfirmed draft and verify its persistence");
require(service.uploads() == uploadsAfterVerificationFailure + 1
&& persisted.load(service.stored(), &error) && persisted.hasStation("LM9006")
&& !save->isEnabled() && !undo->isEnabled(),
"one explicit retry persists once and only then clears the draft");
addStation("LM9007");
fillDialog("agvRouteDialog", [](QDialog *dialog) {
dialog->findChild<QLineEdit *>("agvNewRouteId")->setText("VERIFY_BOTH_DIRECTIONS");
dialog->findChild<QCheckBox *>("agvNewRouteBidirectional")->setChecked(true);
});
route->click();
view->stationSelected(originalId);
view->stationSelected("LM9007");
const int beforePartialSaves = saved;
const int beforePartialUploads = service.uploads();
service.nextResult(FakeAgvService::PersistenceMissingLastRoute);
save->click();
waitFor([&]() { return service.uploads() == beforePartialUploads + 1
&& !editorBusy && save->isEnabled(); },
"persisted station and forward route cannot confirm a missing requested reverse route");
require(saved == beforePartialSaves && undo->isEnabled()
&& persisted.load(service.stored(), &error) && persisted.hasStation("LM9007"),
"partial persistence retains the station and route draft instead of reporting a complete save");
const auto hasRoute = [](const AgvMapDocument &document, const QString &id) {
for (const QVariant &value : document.routes()) {
if (value.toMap().value("id").toString() == id)
return true;
}
return false;
};
require(hasRoute(persisted, "VERIFY_BOTH_DIRECTIONS")
&& !hasRoute(persisted, "VERIFY_BOTH_DIRECTIONS_reverse"),
"fake persistence independently proves exactly one requested direction is missing");
service.nextResult(FakeAgvService::Success);
save->click();
waitFor([&]() { return saved == beforePartialSaves + 1 && !editorBusy; },
"explicit retry idempotently merges already-persisted matching station and forward route");
require(service.uploads() == beforePartialUploads + 2
&& persisted.load(service.stored(), &error)
&& hasRoute(persisted, "VERIFY_BOTH_DIRECTIONS")
&& hasRoute(persisted, "VERIFY_BOTH_DIRECTIONS_reverse")
&& !save->isEnabled() && !undo->isEnabled(),
"retry adds the missing direction exactly once and confirms the complete map before commit");
qInfo("PASS: partial route persistence cannot masquerade as saved; explicit retry safely reuses matching persisted draft objects");
addStation("LM9008");
const int beforeWrongNameSaves = saved;
const int beforeWrongNameUploads = service.uploads();
service.nextResult(FakeAgvService::PersistenceWrongStationName);
save->click();
waitFor([&]() { return service.uploads() == beforeWrongNameUploads + 1
&& !editorBusy && save->isEnabled(); },
"matching station identity and position cannot confirm a wrong persisted display name");
require(saved == beforeWrongNameSaves && undo->isEnabled()
&& persisted.load(service.stored(), &error) && persisted.hasStation("LM9008"),
"wrong persisted station name retains the requested local name as an unsaved draft");
bool wrongNameActuallyStored = false;
for (const QVariant &value : persisted.stations()) {
const QVariantMap point = value.toMap();
if (point.value("id").toString() == "LM9008")
wrongNameActuallyStored = point.value("description").toString()
== "wrong persisted station name";
}
require(wrongNameActuallyStored && service.uploads() == beforeWrongNameUploads + 1,
"fixture proves mismatched display name is diagnosed without another automatic write");
qInfo("PASS: wrong persisted station display name never clears requested local name or reports saved");
client.disconnectFromServer();
waitFor([&]() { return !connected; }, "test client disconnects from its local fake service");
server->Shutdown();
server->Wait();
qInfo("PASS: real-client upload controller rejection/retry, transport failure and read-latest failure; no vehicle writes");
std::cout << "PASS AGV save readback integration: saved=" << saved
<< " uploads=" << service.uploads() << " downloads=" << service.downloads()
<< "; delayed/absent/partial persistence, stale identities, JSON formatting,"
" route directions, display names and explicit idempotent retry checked;"
" loopback only, no vehicle writes" << std::endl;
return 0;
}