diff --git a/README.md b/README.md index 3495b8b..28fda65 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ ui/stage 3D stage: scene graph, joints, meshes, STL, materials, view — n ui/backend/recording records draw calls — the test harness — no Qt ui/backend/qt QtCanvas, QtPaintedWidget, QtTheme — Qt6 Widgets +ui/backend/qt/update release check, verified download, installer, issue log — Qt6 Network ``` Still to come: `ui/model` (FormSpec, TableModel), `ui/sim`, diff --git a/doc/portability.md b/doc/portability.md index bb4ac45..60e9d4f 100644 --- a/doc/portability.md +++ b/doc/portability.md @@ -70,6 +70,29 @@ Qt code. | `AxisTriad` | QML: x, y and z axes as red, green and blue cylinders | | `StatusBadge` | QML: a toned label over the 3-D view, announced as an alert | +### Updates and issue reports — `ui/backend/qt/update` + +`ui.backend.qt.update` lets a desktop tool update itself from its GitHub releases and open a prefilled +issue. It is built with the Qt backend and links Qt Core and Network only, no Widgets, so a tool draws its own +banner and dialogs. Nothing in it names a product: the caller passes the release feed URL, its user agent, +its current version, its issue page and its log file name. It is Qt-only because it is HTTP, files, processes and +JSON, which Qt already does on every desktop platform the tools ship on. + +| Component | What it does | +|----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------| +| `ReleaseVersion` | Parses and orders `vMAJOR.MINOR.PATCH` tags | +| `ReleaseFeed` | Reads a GitHub "latest release": its version, page, every asset downloadable over HTTPS with its SHA-256, and the installer for this platform | +| `UpdateChecker` | Fetches the feed and says whether a newer release exists | +| `UpdateDownloader` | Downloads an installer next to a `.part` file, checks its size and SHA-256, and refuses an asset without a published checksum or with a path | +| `UpdateInstallation` | Tells a packaged install from a portable one and builds the command that installs an update (`apt-get` through `pkexec`, or the NSIS setup) | +| `UpdateInstaller` | Runs that command and reports whether the tool must exit first | +| `UpdateSession` | Offer, download, install, cancel and dismiss as one state machine; `SetBlocked` holds the install back while the tool is busy with hardware | +| `IssueLog` | A rotating log file plus the recent lines in memory, optionally capturing Qt's own messages | +| `IssueReport` | Builds the new-issue URL with the product, version, platform and recent log, trimmed to fit a URL | + +The installer asset is found by its name's suffix: `-linux-x86_64.deb` on Linux and `-windows-x86_64-setup.exe` +on Windows, so a release attaches one of each per tool. + ## What degrades rather than breaks Some input has no equivalent on a touch-first backend. `InputHandler` gives every event an empty diff --git a/ui/backend/qt/CMakeLists.txt b/ui/backend/qt/CMakeLists.txt index 3549b7b..515842d 100644 --- a/ui/backend/qt/CMakeLists.txt +++ b/ui/backend/qt/CMakeLists.txt @@ -25,3 +25,4 @@ ui_add_library(ui.backend.qt QT ) add_subdirectory(test) +add_subdirectory(update) diff --git a/ui/backend/qt/update/CMakeLists.txt b/ui/backend/qt/update/CMakeLists.txt new file mode 100644 index 0000000..bf00009 --- /dev/null +++ b/ui/backend/qt/update/CMakeLists.txt @@ -0,0 +1,28 @@ +find_package(Qt6 6.2 REQUIRED COMPONENTS Core Network) + +ui_add_library(ui.backend.qt.update QT + SOURCES + IssueLog.cpp + IssueLog.hpp + IssueReport.cpp + IssueReport.hpp + ReleaseFeed.cpp + ReleaseFeed.hpp + ReleaseVersion.cpp + ReleaseVersion.hpp + UpdateChecker.cpp + UpdateChecker.hpp + UpdateDownloader.cpp + UpdateDownloader.hpp + UpdateInstallation.cpp + UpdateInstallation.hpp + UpdateInstaller.cpp + UpdateInstaller.hpp + UpdateSession.cpp + UpdateSession.hpp + LINK + Qt6::Core + Qt6::Network +) + +add_subdirectory(test) diff --git a/ui/backend/qt/update/IssueLog.cpp b/ui/backend/qt/update/IssueLog.cpp new file mode 100644 index 0000000..183b9ba --- /dev/null +++ b/ui/backend/qt/update/IssueLog.cpp @@ -0,0 +1,167 @@ +#include "ui/backend/qt/update/IssueLog.hpp" +#include +#include +#include +#include + +namespace ui::backend::qt::update +{ + namespace + { + struct Capture + { + std::atomic log{ nullptr }; + QtMessageHandler previousHandler{ nullptr }; + }; + + Capture& CaptureState() + { + constinit static Capture capture; + return capture; + } + + bool& WritingOnThisThread() + { + constinit thread_local bool writing{ false }; + return writing; + } + + void ForwardQtMessage(QtMsgType type, const QMessageLogContext& context, const QString& message) + { + const auto& capture = CaptureState(); + auto* log = capture.log.load(); + if (log != nullptr && !WritingOnThisThread() && type != QtDebugMsg && type != QtInfoMsg) + log->Write(type == QtWarningMsg ? IssueSeverity::warning : IssueSeverity::error, "Qt: " + message); + + if (capture.previousHandler != nullptr) + capture.previousHandler(type, context, message); + } + } + + QString ToString(IssueSeverity severity) + { + switch (severity) + { + case IssueSeverity::warning: + return "WARN "; + case IssueSeverity::error: + return "ERROR"; + default: + return "INFO "; + } + } + + IssueLog::IssueLog(const Config& config) + : config(config) + { + this->config.keptFiles = std::max(this->config.keptFiles, 1); + QDir{}.mkpath(config.directory); + Open(); + } + + IssueLog::~IssueLog() + { + if (capturing) + { + auto& capture = CaptureState(); + capture.log = nullptr; + qInstallMessageHandler(capture.previousHandler); + capture.previousHandler = nullptr; + } + } + + void IssueLog::Write(IssueSeverity severity, const QString& message) + { + auto line = QString("%1 [%2] %3") + .arg(QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs), ToString(severity), message.simplified()); + + std::scoped_lock lock{ mutex }; + WritingOnThisThread() = true; + Remember(line); + + if (file.isOpen()) + RotateIfNeeded(); + + if (file.isOpen()) + { + file.write(line.append('\n').toUtf8()); + file.flush(); + } + + WritingOnThisThread() = false; + } + + bool IssueLog::IsWritable() const + { + return file.isOpen(); + } + + QString IssueLog::FilePath() const + { + return RotatedPath(0); + } + + QString IssueLog::Directory() const + { + return config.directory; + } + + QStringList IssueLog::RecentLines(std::size_t count) const + { + std::scoped_lock lock{ mutex }; + QStringList lines; + const auto skip = recent.size() > count ? recent.size() - count : 0; + for (auto it = recent.begin() + static_cast(skip); it != recent.end(); ++it) + lines.append(*it); + return lines; + } + + void IssueLog::CaptureQtMessages() + { + auto& capture = CaptureState(); + if (capturing || capture.log.load() != nullptr) + return; + + capturing = true; + capture.previousHandler = qInstallMessageHandler(ForwardQtMessage); + capture.log = this; + } + + QString IssueLog::RotatedPath(int index) const + { + const auto name = index == 0 ? QString("%1.log").arg(config.baseName) : QString("%1.%2.log").arg(config.baseName).arg(index); + return QDir{ config.directory }.filePath(name); + } + + void IssueLog::Open() + { + file.setFileName(FilePath()); + if (OpenForAppend()) + RotateIfNeeded(); + } + + bool IssueLog::OpenForAppend() + { + return file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text); + } + + void IssueLog::RotateIfNeeded() + { + if (file.size() < config.maxFileBytes) + return; + + file.close(); + QFile::remove(RotatedPath(config.keptFiles - 1)); + for (int index = config.keptFiles - 2; index >= 0; --index) + QFile::rename(RotatedPath(index), RotatedPath(index + 1)); + + OpenForAppend(); + } + + void IssueLog::Remember(const QString& line) + { + recent.push_back(line); + while (recent.size() > config.recentCapacity) + recent.pop_front(); + } +} diff --git a/ui/backend/qt/update/IssueLog.hpp b/ui/backend/qt/update/IssueLog.hpp new file mode 100644 index 0000000..252ae87 --- /dev/null +++ b/ui/backend/qt/update/IssueLog.hpp @@ -0,0 +1,62 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace ui::backend::qt::update +{ + enum class IssueSeverity + { + info, + warning, + error + }; + + class IssueLog + { + public: + struct Config + { + QString directory; + QString baseName{ "application" }; + qint64 maxFileBytes{ 1024 * 1024 }; + int keptFiles{ 3 }; + std::size_t recentCapacity{ 200 }; + }; + + explicit IssueLog(const Config& config); + ~IssueLog(); + + IssueLog(const IssueLog&) = delete; + IssueLog& operator=(const IssueLog&) = delete; + + void Write(IssueSeverity severity, const QString& message); + + bool IsWritable() const; + QString FilePath() const; + QString Directory() const; + QStringList RecentLines(std::size_t count) const; + + void CaptureQtMessages(); + + private: + QString RotatedPath(int index) const; + void Open(); + bool OpenForAppend(); + void RotateIfNeeded(); + void Remember(const QString& line); + + Config config; + QFile file; + std::deque recent; + mutable std::mutex mutex; + bool capturing{ false }; + }; + + QString ToString(IssueSeverity severity); +} diff --git a/ui/backend/qt/update/IssueReport.cpp b/ui/backend/qt/update/IssueReport.cpp new file mode 100644 index 0000000..eea0b03 --- /dev/null +++ b/ui/backend/qt/update/IssueReport.cpp @@ -0,0 +1,72 @@ +#include "ui/backend/qt/update/IssueReport.hpp" +#include +#include +#include + +namespace ui::backend::qt::update +{ + namespace + { + QString IssueBody(const IssueEnvironment& environment, const QStringList& logLines) + { + auto body = QString("### What happened?\n\n" + "\n\n" + "### Environment\n\n" + "| | |\n|---|---|\n" + "| %1 | %2 |\n" + "| Operating system | %3 |\n" + "| Architecture | %4 |\n" + "| Qt | %5 |\n\n") + .arg(environment.product.displayName, environment.applicationVersion, environment.operatingSystem, environment.cpuArchitecture, environment.qtVersion); + + body += "### Recent log\n\n```text\n"; + body += logLines.isEmpty() ? QString("(no entries)") : logLines.join('\n'); + body += "\n```\n"; + + if (!environment.logFilePath.isEmpty()) + body += QString("\nFull log: `%1` — attach it if more context helps.\n").arg(environment.logFilePath); + + return body; + } + + QString Encoded(const QString& text) + { + return QString::fromLatin1(QUrl::toPercentEncoding(text)); + } + + QUrl IssueUrl(const QUrl& newIssueUrl, const IssueEnvironment& environment, const QStringList& logLines) + { + QUrlQuery query; + query.addQueryItem("title", Encoded(QString("[%1] ").arg(environment.product.tag))); + query.addQueryItem("body", Encoded(IssueBody(environment, logLines))); + + QUrl url{ newIssueUrl }; + url.setQuery(query); + return url; + } + } + + IssueEnvironment CurrentIssueEnvironment(const IssueProduct& product, const QString& applicationVersion, const QString& logFilePath) + { + auto shownPath = QDir::toNativeSeparators(logFilePath); + const auto home = QDir::toNativeSeparators(QDir::homePath()); + if (!home.isEmpty() && shownPath.startsWith(home)) + shownPath.replace(0, home.size(), "~"); + + return IssueEnvironment{ product, applicationVersion, QSysInfo::prettyProductName(), QSysInfo::currentCpuArchitecture(), QString::fromUtf8(qVersion()), shownPath }; + } + + QUrl BuildIssueUrl(const QUrl& newIssueUrl, const IssueEnvironment& environment, const QStringList& recentLog, int maxUrlLength) + { + auto lines = recentLog; + auto url = IssueUrl(newIssueUrl, environment, lines); + + while (!lines.isEmpty() && url.toEncoded().size() > maxUrlLength) + { + lines.removeFirst(); + url = IssueUrl(newIssueUrl, environment, lines); + } + + return url; + } +} diff --git a/ui/backend/qt/update/IssueReport.hpp b/ui/backend/qt/update/IssueReport.hpp new file mode 100644 index 0000000..07845d0 --- /dev/null +++ b/ui/backend/qt/update/IssueReport.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include +#include +#include + +namespace ui::backend::qt::update +{ + struct IssueProduct + { + QString displayName; + QString tag; + }; + + struct IssueEnvironment + { + IssueProduct product; + QString applicationVersion; + QString operatingSystem; + QString cpuArchitecture; + QString qtVersion; + QString logFilePath; + }; + + IssueEnvironment CurrentIssueEnvironment(const IssueProduct& product, const QString& applicationVersion, const QString& logFilePath); + + QUrl BuildIssueUrl(const QUrl& newIssueUrl, const IssueEnvironment& environment, const QStringList& recentLog, int maxUrlLength = 7000); +} diff --git a/ui/backend/qt/update/ReleaseFeed.cpp b/ui/backend/qt/update/ReleaseFeed.cpp new file mode 100644 index 0000000..2f0d12b --- /dev/null +++ b/ui/backend/qt/update/ReleaseFeed.cpp @@ -0,0 +1,114 @@ +#include "ui/backend/qt/update/ReleaseFeed.hpp" +#include +#include +#include + +namespace ui::backend::qt::update +{ + namespace + { + constexpr qsizetype sha256Bytes{ 32 }; + + std::optional DownloadableAsset(const QJsonValue& asset) + { + const auto object = asset.toObject(); + const QUrl url{ object.value("browser_download_url").toString() }; + if (!url.isValid() || url.scheme() != "https") + return std::nullopt; + + return InstallerAsset{ object.value("name").toString(), url, object.value("size").toInteger(), ParseSha256Digest(object.value("digest").toString()) }; + } + + std::optional FindInstaller(const QJsonArray& assets, InstallerPlatform platform) + { + const auto suffix = InstallerAssetSuffix(platform); + if (suffix.isEmpty()) + return std::nullopt; + + for (const auto& asset : assets) + if (auto installer = DownloadableAsset(asset); installer && installer->fileName.endsWith(suffix)) + return installer; + + return std::nullopt; + } + + std::vector DownloadableAssets(const QJsonArray& assets) + { + std::vector downloadable; + for (const auto& asset : assets) + if (auto found = DownloadableAsset(asset); found) + downloadable.push_back(*found); + + return downloadable; + } + } + + InstallerPlatform CurrentInstallerPlatform() + { +#if defined(_WIN32) + return InstallerPlatform::windowsX64; +#elif defined(__linux__) + return InstallerPlatform::linuxX64; +#else + return InstallerPlatform::unsupported; +#endif + } + + QString InstallerAssetSuffix(InstallerPlatform platform) + { + switch (platform) + { + case InstallerPlatform::windowsX64: + return "-windows-x86_64-setup.exe"; + case InstallerPlatform::linuxX64: + return "-linux-x86_64.deb"; + default: + return {}; + } + } + + std::optional ParseSha256Digest(const QString& digest) + { + static const QString prefix{ "sha256:" }; + if (!digest.startsWith(prefix)) + return std::nullopt; + + const auto hex = digest.mid(prefix.size()); + if (hex.size() != sha256Bytes * 2) + return std::nullopt; + + for (const auto character : hex) + if (!character.isDigit() && !QStringLiteral("abcdefABCDEF").contains(character)) + return std::nullopt; + + return QByteArray::fromHex(hex.toLatin1()); + } + + std::optional ParseLatestRelease(const QByteArray& json, InstallerPlatform platform) + { + const auto document = QJsonDocument::fromJson(json); + if (!document.isObject()) + return std::nullopt; + + const auto root = document.object(); + const auto tag = root.value("tag_name").toString(); + const auto version = ReleaseVersion::Parse(tag.toStdString()); + const QUrl pageUrl{ root.value("html_url").toString() }; + + if (!version || !pageUrl.isValid() || pageUrl.scheme() != "https") + return std::nullopt; + + const auto assets = root.value("assets").toArray(); + return ReleaseInfo{ *version, tag, pageUrl, FindInstaller(assets, platform), DownloadableAssets(assets) }; + } + + UpdateEvaluation EvaluateLatestRelease(const QByteArray& json, const ReleaseVersion& current, InstallerPlatform platform) + { + auto latest = ParseLatestRelease(json, platform); + if (!latest) + return {}; + + const auto status = latest->version > current ? UpdateStatus::updateAvailable : UpdateStatus::upToDate; + return UpdateEvaluation{ status, std::move(latest) }; + } +} diff --git a/ui/backend/qt/update/ReleaseFeed.hpp b/ui/backend/qt/update/ReleaseFeed.hpp new file mode 100644 index 0000000..05152cc --- /dev/null +++ b/ui/backend/qt/update/ReleaseFeed.hpp @@ -0,0 +1,55 @@ +#pragma once + +#include "ui/backend/qt/update/ReleaseVersion.hpp" +#include +#include +#include +#include +#include + +namespace ui::backend::qt::update +{ + enum class InstallerPlatform + { + windowsX64, + linuxX64, + unsupported + }; + + struct InstallerAsset + { + QString fileName; + QUrl url; + qint64 size{ 0 }; + std::optional sha256; + }; + + struct ReleaseInfo + { + ReleaseVersion version; + QString tag; + QUrl pageUrl; + std::optional installer; + std::vector assets; + }; + + enum class UpdateStatus + { + updateAvailable, + upToDate, + invalidResponse + }; + + struct UpdateEvaluation + { + UpdateStatus status{ UpdateStatus::invalidResponse }; + std::optional latest; + }; + + InstallerPlatform CurrentInstallerPlatform(); + QString InstallerAssetSuffix(InstallerPlatform platform); + + std::optional ParseSha256Digest(const QString& digest); + std::optional ParseLatestRelease(const QByteArray& json, InstallerPlatform platform); + UpdateEvaluation EvaluateLatestRelease(const QByteArray& json, const ReleaseVersion& current, InstallerPlatform platform); +} diff --git a/ui/backend/qt/update/ReleaseVersion.cpp b/ui/backend/qt/update/ReleaseVersion.cpp new file mode 100644 index 0000000..f4dccf5 --- /dev/null +++ b/ui/backend/qt/update/ReleaseVersion.cpp @@ -0,0 +1,59 @@ +#include "ui/backend/qt/update/ReleaseVersion.hpp" +#include +#include + +namespace ui::backend::qt::update +{ + namespace + { + std::optional ParseComponent(std::string_view& text, bool last) + { + uint32_t value{ 0 }; + const auto* begin = text.data(); + const auto* end = text.data() + text.size(); + const auto [next, error] = std::from_chars(begin, end, value); + + if (error != std::errc{} || next == begin) + return std::nullopt; + + if (next - begin > 1 && *begin == '0') + return std::nullopt; + + text.remove_prefix(static_cast(next - begin)); + + if (last) + return text.empty() ? std::optional{ value } : std::nullopt; + + if (text.empty() || text.front() != '.') + return std::nullopt; + + text.remove_prefix(1); + return value; + } + } + + std::optional ReleaseVersion::Parse(std::string_view text) + { + if (!text.empty() && (text.front() == 'v' || text.front() == 'V')) + text.remove_prefix(1); + + const auto major = ParseComponent(text, false); + if (!major.has_value()) + return std::nullopt; + + const auto minor = ParseComponent(text, false); + if (!minor.has_value()) + return std::nullopt; + + const auto patch = ParseComponent(text, true); + if (!patch.has_value()) + return std::nullopt; + + return ReleaseVersion{ *major, *minor, *patch }; + } + + std::string ReleaseVersion::ToString() const + { + return std::format("{}.{}.{}", major, minor, patch); + } +} diff --git a/ui/backend/qt/update/ReleaseVersion.hpp b/ui/backend/qt/update/ReleaseVersion.hpp new file mode 100644 index 0000000..1e16330 --- /dev/null +++ b/ui/backend/qt/update/ReleaseVersion.hpp @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include +#include + +namespace ui::backend::qt::update +{ + struct ReleaseVersion + { + uint32_t major{ 0 }; + uint32_t minor{ 0 }; + uint32_t patch{ 0 }; + + static std::optional Parse(std::string_view text); + + std::string ToString() const; + + friend auto operator<=>(const ReleaseVersion& lhs, const ReleaseVersion& rhs) = default; + }; +} diff --git a/ui/backend/qt/update/UpdateChecker.cpp b/ui/backend/qt/update/UpdateChecker.cpp new file mode 100644 index 0000000..0175fb2 --- /dev/null +++ b/ui/backend/qt/update/UpdateChecker.cpp @@ -0,0 +1,67 @@ +#include "ui/backend/qt/update/UpdateChecker.hpp" +#include +#include + +namespace ui::backend::qt::update +{ + namespace + { + constexpr int transferTimeoutMs{ 10000 }; + } + + UpdateChecker::UpdateChecker(const ReleaseVersion& current, const QUrl& feedUrl, const QByteArray& userAgent, QObject* parent) + : QObject(parent) + , current(current) + , feedUrl(feedUrl) + , userAgent(userAgent) + {} + + void UpdateChecker::Check() + { + if (IsChecking()) + return; + + QNetworkRequest request{ feedUrl }; + request.setRawHeader("Accept", "application/vnd.github+json"); + request.setHeader(QNetworkRequest::UserAgentHeader, userAgent); + request.setTransferTimeout(transferTimeoutMs); + + pending = network.get(request); + connect(pending, &QNetworkReply::finished, this, [this, reply = pending.data()]() + { + OnFinished(reply); + }); + } + + bool UpdateChecker::IsChecking() const + { + return !pending.isNull(); + } + + void UpdateChecker::OnFinished(QNetworkReply* reply) + { + reply->deleteLater(); + pending.clear(); + + if (reply->error() != QNetworkReply::NoError) + { + emit CheckFailed(reply->errorString()); + return; + } + + const auto evaluation = EvaluateLatestRelease(reply->readAll(), current, CurrentInstallerPlatform()); + + switch (evaluation.status) + { + case UpdateStatus::updateAvailable: + emit UpdateAvailable(*evaluation.latest); + break; + case UpdateStatus::upToDate: + emit UpToDate(*evaluation.latest); + break; + default: + emit CheckFailed("the release feed did not contain a valid release"); + break; + } + } +} diff --git a/ui/backend/qt/update/UpdateChecker.hpp b/ui/backend/qt/update/UpdateChecker.hpp new file mode 100644 index 0000000..c1cbfcb --- /dev/null +++ b/ui/backend/qt/update/UpdateChecker.hpp @@ -0,0 +1,37 @@ +#pragma once + +#include "ui/backend/qt/update/ReleaseFeed.hpp" +#include +#include +#include + +class QNetworkReply; + +namespace ui::backend::qt::update +{ + class UpdateChecker + : public QObject + { + Q_OBJECT + + public: + UpdateChecker(const ReleaseVersion& current, const QUrl& feedUrl, const QByteArray& userAgent, QObject* parent = nullptr); + + void Check(); + bool IsChecking() const; + + signals: + void UpdateAvailable(const ui::backend::qt::update::ReleaseInfo& release); + void UpToDate(const ui::backend::qt::update::ReleaseInfo& latest); + void CheckFailed(const QString& reason); + + private: + void OnFinished(QNetworkReply* reply); + + ReleaseVersion current; + QUrl feedUrl; + QByteArray userAgent; + QNetworkAccessManager network; + QPointer pending; + }; +} diff --git a/ui/backend/qt/update/UpdateDownloader.cpp b/ui/backend/qt/update/UpdateDownloader.cpp new file mode 100644 index 0000000..53025ef --- /dev/null +++ b/ui/backend/qt/update/UpdateDownloader.cpp @@ -0,0 +1,175 @@ +#include "ui/backend/qt/update/UpdateDownloader.hpp" +#include +#include +#include +#include + +namespace ui::backend::qt::update +{ + namespace + { + constexpr int inactivityTimeoutMs{ 30000 }; + } + + UpdateDownloader::UpdateDownloader(const QByteArray& userAgent, QObject* parent) + : QObject(parent) + , userAgent(userAgent) + {} + + void UpdateDownloader::Start(const InstallerAsset& installer, const QString& directory) + { + if (IsDownloading()) + return; + + asset = installer; + cancelled = false; + hash.reset(); + + if (!asset.sha256) + { + FailLater(QString("the release publishes no checksum for %1, so it cannot be installed automatically").arg(asset.fileName)); + return; + } + + if (asset.fileName.isEmpty() || asset.fileName.contains('/') || asset.fileName.contains('\\')) + { + FailLater(QString("the release names its installer \"%1\", which is not a plain file name").arg(asset.fileName)); + return; + } + + if (!QDir{}.mkpath(directory)) + { + FailLater(QString("cannot create the download folder %1").arg(QDir::toNativeSeparators(directory))); + return; + } + + targetPath = QDir{ directory }.filePath(asset.fileName); + file = std::make_unique(targetPath + ".part"); + if (!file->open(QIODevice::WriteOnly | QIODevice::Truncate)) + { + FailLater(QString("cannot write %1: %2").arg(QDir::toNativeSeparators(file->fileName()), file->errorString())); + file.reset(); + return; + } + + QNetworkRequest request{ asset.url }; + request.setHeader(QNetworkRequest::UserAgentHeader, userAgent); + request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); + request.setTransferTimeout(inactivityTimeoutMs); + + reply = network.get(request); + connect(reply, &QNetworkReply::readyRead, this, &UpdateDownloader::OnReadyRead); + connect(reply, &QNetworkReply::downloadProgress, this, [this](qint64 received, qint64 total) + { + emit Progress(received, total > 0 ? total : asset.size); + }); + connect(reply, &QNetworkReply::finished, this, &UpdateDownloader::OnFinished); + } + + void UpdateDownloader::Cancel() + { + if (!IsDownloading()) + return; + + cancelled = true; + reply->abort(); + } + + bool UpdateDownloader::IsDownloading() const + { + return !reply.isNull(); + } + + void UpdateDownloader::FailLater(const QString& reason) + { + QTimer::singleShot(0, this, [this, reason]() + { + emit Failed(reason); + }); + } + + void UpdateDownloader::OnReadyRead() + { + if (!Append(reply->readAll())) + reply->abort(); + } + + bool UpdateDownloader::Append(const QByteArray& data) + { + hash.addData(data); + return file->write(data) == data.size(); + } + + void UpdateDownloader::OnFinished() + { + auto* finished = reply.data(); + finished->deleteLater(); + reply.clear(); + + if (cancelled) + { + Discard(); + return; + } + + if (finished->error() == QNetworkReply::NoError) + Append(finished->readAll()); + + if (file->error() != QFileDevice::NoError) + { + const auto reason = QString("cannot write %1: %2").arg(QDir::toNativeSeparators(file->fileName()), file->errorString()); + Discard(); + emit Failed(reason); + return; + } + + if (finished->error() != QNetworkReply::NoError) + { + const auto reason = finished->errorString(); + Discard(); + emit Failed(reason); + return; + } + + file->close(); + if (const auto mismatch = Verify(); !mismatch.isEmpty()) + { + Discard(); + emit Failed(mismatch); + return; + } + + QFile::remove(targetPath); + if (!file->rename(targetPath)) + { + const auto reason = QString("cannot move the download to %1: %2").arg(QDir::toNativeSeparators(targetPath), file->errorString()); + Discard(); + emit Failed(reason); + return; + } + + file.reset(); + emit Downloaded(targetPath); + } + + QString UpdateDownloader::Verify() const + { + if (asset.size > 0 && file->size() != asset.size) + return QString("the download is %1 bytes, but the release lists %2").arg(file->size()).arg(asset.size); + + if (hash.result() != *asset.sha256) + return "the download does not match the checksum published with the release"; + + return {}; + } + + void UpdateDownloader::Discard() + { + if (!file) + return; + + file->close(); + file->remove(); + file.reset(); + } +} diff --git a/ui/backend/qt/update/UpdateDownloader.hpp b/ui/backend/qt/update/UpdateDownloader.hpp new file mode 100644 index 0000000..6327964 --- /dev/null +++ b/ui/backend/qt/update/UpdateDownloader.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include "ui/backend/qt/update/ReleaseFeed.hpp" +#include +#include +#include +#include +#include +#include + +class QNetworkReply; + +namespace ui::backend::qt::update +{ + class UpdateDownloader + : public QObject + { + Q_OBJECT + + public: + explicit UpdateDownloader(const QByteArray& userAgent, QObject* parent = nullptr); + + void Start(const InstallerAsset& asset, const QString& directory); + void Cancel(); + bool IsDownloading() const; + + signals: + void Progress(qint64 received, qint64 total); + void Downloaded(const QString& filePath); + void Failed(const QString& reason); + + private: + void FailLater(const QString& reason); + void OnReadyRead(); + bool Append(const QByteArray& data); + void OnFinished(); + QString Verify() const; + void Discard(); + + QByteArray userAgent; + QNetworkAccessManager network; + QPointer reply; + std::unique_ptr file; + QCryptographicHash hash{ QCryptographicHash::Sha256 }; + InstallerAsset asset; + QString targetPath; + bool cancelled{ false }; + }; +} diff --git a/ui/backend/qt/update/UpdateInstallation.cpp b/ui/backend/qt/update/UpdateInstallation.cpp new file mode 100644 index 0000000..2f8b848 --- /dev/null +++ b/ui/backend/qt/update/UpdateInstallation.cpp @@ -0,0 +1,79 @@ +#include "ui/backend/qt/update/UpdateInstallation.hpp" +#include +#include +#include + +namespace ui::backend::qt::update +{ + namespace + { + QString PowerShellLiteral(const QString& text) + { + return "'" + QString{ text }.replace("'", "''") + "'"; + } + + QString EncodedPowerShellCommand(const QString& script) + { + QByteArray utf16LittleEndian; + utf16LittleEndian.reserve(script.size() * 2); + for (const auto character : script) + { + const auto unit = character.unicode(); + utf16LittleEndian.append(static_cast(unit & 0xffu)); + utf16LittleEndian.append(static_cast(unit >> 8u)); + } + return QString::fromLatin1(utf16LittleEndian.toBase64()); + } + } + + InstallationKind DetectInstallation(InstallerPlatform platform, const QString& applicationFilePath) + { + switch (platform) + { + case InstallerPlatform::windowsX64: + return QFileInfo::exists(QDir{ WindowsInstallDirectory(applicationFilePath) }.filePath("Uninstall.exe")) ? InstallationKind::package : InstallationKind::portable; + case InstallerPlatform::linuxX64: + return QDir::cleanPath(applicationFilePath).startsWith("/usr/") ? InstallationKind::package : InstallationKind::portable; + default: + return InstallationKind::portable; + } + } + + QString WindowsInstallDirectory(const QString& applicationFilePath) + { + return QDir::cleanPath(QFileInfo{ applicationFilePath }.absolutePath() + "/.."); + } + + InstallCommand WindowsUpdateCommand(const QString& installerPath, const QString& installDirectory, qint64 processId, const QString& applicationFilePath) + { + const auto arguments = "/S /RELAUNCH /D=" + QDir::toNativeSeparators(installDirectory); + const auto script = QString("Wait-Process -Id %1 -ErrorAction SilentlyContinue\n" + "try { Start-Process -FilePath %2 -ArgumentList %3 -Verb RunAs -ErrorAction Stop }\n" + "catch { Start-Process -FilePath %4 }\n") + .arg(processId) + .arg(PowerShellLiteral(QDir::toNativeSeparators(installerPath)), PowerShellLiteral(arguments), PowerShellLiteral(QDir::toNativeSeparators(applicationFilePath))); + + return InstallCommand{ "powershell.exe", { "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-EncodedCommand", EncodedPowerShellCommand(script) }, true }; + } + + InstallCommand LinuxUpdateCommand(const QString& elevationProgram, const QString& packageManager, const QString& packagePath) + { + return InstallCommand{ elevationProgram, { packageManager, "install", "-y", QFileInfo{ packagePath }.absoluteFilePath() }, false }; + } + + std::optional DefaultUpdateCommand(InstallerPlatform platform, const QString& installerPath, const QString& applicationFilePath, qint64 processId) + { + if (DetectInstallation(platform, applicationFilePath) != InstallationKind::package) + return std::nullopt; + + if (platform == InstallerPlatform::windowsX64) + return WindowsUpdateCommand(installerPath, WindowsInstallDirectory(applicationFilePath), processId, applicationFilePath); + + const auto elevation = QStandardPaths::findExecutable("pkexec"); + const auto packageManager = QStandardPaths::findExecutable("apt-get"); + if (elevation.isEmpty() || packageManager.isEmpty()) + return std::nullopt; + + return LinuxUpdateCommand(elevation, packageManager, installerPath); + } +} diff --git a/ui/backend/qt/update/UpdateInstallation.hpp b/ui/backend/qt/update/UpdateInstallation.hpp new file mode 100644 index 0000000..490f47f --- /dev/null +++ b/ui/backend/qt/update/UpdateInstallation.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include "ui/backend/qt/update/ReleaseFeed.hpp" +#include +#include +#include + +namespace ui::backend::qt::update +{ + enum class InstallationKind + { + package, + portable + }; + + struct InstallCommand + { + QString program; + QStringList arguments; + bool exitsBeforeInstalling{ false }; + }; + + InstallationKind DetectInstallation(InstallerPlatform platform, const QString& applicationFilePath); + QString WindowsInstallDirectory(const QString& applicationFilePath); + + InstallCommand WindowsUpdateCommand(const QString& installerPath, const QString& installDirectory, qint64 processId, const QString& applicationFilePath); + InstallCommand LinuxUpdateCommand(const QString& elevationProgram, const QString& packageManager, const QString& packagePath); + + std::optional DefaultUpdateCommand(InstallerPlatform platform, const QString& installerPath, const QString& applicationFilePath, qint64 processId); +} diff --git a/ui/backend/qt/update/UpdateInstaller.cpp b/ui/backend/qt/update/UpdateInstaller.cpp new file mode 100644 index 0000000..95d499b --- /dev/null +++ b/ui/backend/qt/update/UpdateInstaller.cpp @@ -0,0 +1,65 @@ +#include "ui/backend/qt/update/UpdateInstaller.hpp" + +namespace ui::backend::qt::update +{ + namespace + { + constexpr int authenticationDismissed{ 126 }; + constexpr int notAuthorized{ 127 }; + } + + UpdateInstaller::UpdateInstaller(QObject* parent) + : QObject(parent) + { + process.setProcessChannelMode(QProcess::MergedChannels); + connect(&process, &QProcess::finished, this, &UpdateInstaller::OnFinished); + connect(&process, &QProcess::errorOccurred, this, [this](QProcess::ProcessError error) + { + if (error == QProcess::FailedToStart) + emit Failed(QString("could not start %1: %2").arg(process.program(), process.errorString())); + }); + } + + void UpdateInstaller::Install(const InstallCommand& command) + { + if (IsInstalling()) + return; + + if (command.exitsBeforeInstalling) + { + if (QProcess::startDetached(command.program, command.arguments)) + emit HandedOver(); + else + emit Failed(QString("could not start %1").arg(command.program)); + return; + } + + process.start(command.program, command.arguments); + } + + bool UpdateInstaller::IsInstalling() const + { + return process.state() != QProcess::NotRunning; + } + + void UpdateInstaller::OnFinished(int exitCode, QProcess::ExitStatus status) + { + if (status == QProcess::NormalExit && exitCode == 0) + { + emit Installed(); + return; + } + + if (status == QProcess::CrashExit) + emit Failed(QString("%1 stopped unexpectedly").arg(process.program())); + else if (exitCode == authenticationDismissed) + emit Failed("the password prompt was dismissed"); + else if (exitCode == notAuthorized) + emit Failed("this account may not install software"); + else + { + const auto output = QString::fromLocal8Bit(process.readAll()).trimmed().split('\n').last(); + emit Failed(QString("the installation failed (exit code %1)%2").arg(exitCode).arg(output.isEmpty() ? QString{} : ": " + output)); + } + } +} diff --git a/ui/backend/qt/update/UpdateInstaller.hpp b/ui/backend/qt/update/UpdateInstaller.hpp new file mode 100644 index 0000000..eb5b5b0 --- /dev/null +++ b/ui/backend/qt/update/UpdateInstaller.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include "ui/backend/qt/update/UpdateInstallation.hpp" +#include +#include + +namespace ui::backend::qt::update +{ + class UpdateInstaller + : public QObject + { + Q_OBJECT + + public: + explicit UpdateInstaller(QObject* parent = nullptr); + + void Install(const InstallCommand& command); + bool IsInstalling() const; + + signals: + void HandedOver(); + void Installed(); + void Failed(const QString& reason); + + private: + void OnFinished(int exitCode, QProcess::ExitStatus status); + + QProcess process; + }; +} diff --git a/ui/backend/qt/update/UpdateSession.cpp b/ui/backend/qt/update/UpdateSession.cpp new file mode 100644 index 0000000..49ca593 --- /dev/null +++ b/ui/backend/qt/update/UpdateSession.cpp @@ -0,0 +1,138 @@ +#include "ui/backend/qt/update/UpdateSession.hpp" +#include + +namespace ui::backend::qt::update +{ + UpdateSession::UpdateSession(const QString& downloadDirectory, const QByteArray& userAgent, CommandFactory commandFor, QObject* parent) + : QObject(parent) + , downloadDirectory(downloadDirectory) + , commandFor(std::move(commandFor)) + , downloader(userAgent) + { + connect(&downloader, &UpdateDownloader::Progress, this, [this](qint64 received, qint64 total) + { + state.received = received; + state.total = total; + emit StateChanged(state); + }); + connect(&downloader, &UpdateDownloader::Downloaded, this, [this](const QString& path) + { + downloadedPath = path; + if (state.blocked) + Enter(UpdatePhase::ready); + else + StartInstall(); + }); + connect(&downloader, &UpdateDownloader::Failed, this, &UpdateSession::Fail); + connect(&installer, &UpdateInstaller::HandedOver, this, &UpdateSession::RestartRequested); + connect(&installer, &UpdateInstaller::Installed, this, &UpdateSession::Relaunch); + connect(&installer, &UpdateInstaller::Failed, this, &UpdateSession::Fail); + } + + void UpdateSession::Offer(const ReleaseInfo& release) + { + if (Busy()) + return; + + state.release = release; + state.automaticInstall = release.installer && release.installer->sha256 && commandFor(InstallerPath(*release.installer)).has_value(); + state.failure.clear(); + Enter(UpdatePhase::available); + } + + void UpdateSession::Install() + { + switch (state.phase) + { + case UpdatePhase::available: + case UpdatePhase::failed: + if (state.automaticInstall) + StartDownload(); + break; + case UpdatePhase::ready: + if (!state.blocked) + StartInstall(); + break; + default: + break; + } + } + + void UpdateSession::Cancel() + { + if (state.phase == UpdatePhase::downloading) + downloader.Cancel(); + + if (state.phase == UpdatePhase::downloading || state.phase == UpdatePhase::ready) + Enter(UpdatePhase::available); + } + + void UpdateSession::Dismiss() + { + if (state.phase == UpdatePhase::installing) + return; + + if (state.phase == UpdatePhase::downloading) + downloader.Cancel(); + + Enter(UpdatePhase::idle); + } + + void UpdateSession::SetBlocked(bool blocked) + { + if (state.blocked == blocked) + return; + + state.blocked = blocked; + emit StateChanged(state); + } + + const UpdateState& UpdateSession::State() const + { + return state; + } + + bool UpdateSession::Busy() const + { + return state.phase == UpdatePhase::downloading || state.phase == UpdatePhase::ready || state.phase == UpdatePhase::installing; + } + + QString UpdateSession::InstallerPath(const InstallerAsset& asset) const + { + return QDir{ downloadDirectory }.filePath(asset.fileName); + } + + void UpdateSession::StartDownload() + { + state.received = 0; + state.total = state.release->installer->size; + state.failure.clear(); + Enter(UpdatePhase::downloading); + downloader.Start(*state.release->installer, downloadDirectory); + } + + void UpdateSession::StartInstall() + { + const auto command = commandFor(downloadedPath); + if (!command) + { + Fail("this installation cannot be updated automatically"); + return; + } + + Enter(UpdatePhase::installing); + installer.Install(*command); + } + + void UpdateSession::Fail(const QString& reason) + { + state.failure = reason; + Enter(UpdatePhase::failed); + } + + void UpdateSession::Enter(UpdatePhase phase) + { + state.phase = phase; + emit StateChanged(state); + } +} diff --git a/ui/backend/qt/update/UpdateSession.hpp b/ui/backend/qt/update/UpdateSession.hpp new file mode 100644 index 0000000..fd496f2 --- /dev/null +++ b/ui/backend/qt/update/UpdateSession.hpp @@ -0,0 +1,71 @@ +#pragma once + +#include "ui/backend/qt/update/ReleaseFeed.hpp" +#include "ui/backend/qt/update/UpdateDownloader.hpp" +#include "ui/backend/qt/update/UpdateInstaller.hpp" +#include +#include +#include + +namespace ui::backend::qt::update +{ + enum class UpdatePhase + { + idle, + available, + downloading, + ready, + installing, + failed + }; + + struct UpdateState + { + UpdatePhase phase{ UpdatePhase::idle }; + std::optional release; + bool automaticInstall{ false }; + bool blocked{ false }; + qint64 received{ 0 }; + qint64 total{ 0 }; + QString failure; + }; + + class UpdateSession + : public QObject + { + Q_OBJECT + + public: + using CommandFactory = std::function(const QString& installerPath)>; + + UpdateSession(const QString& downloadDirectory, const QByteArray& userAgent, CommandFactory commandFor, QObject* parent = nullptr); + + void Offer(const ReleaseInfo& release); + void Install(); + void Cancel(); + void Dismiss(); + void SetBlocked(bool blocked); + + const UpdateState& State() const; + + signals: + void StateChanged(const ui::backend::qt::update::UpdateState& state); + void RestartRequested(); + void Relaunch(); + + private: + bool Busy() const; + QString InstallerPath(const InstallerAsset& asset) const; + void StartDownload(); + void StartInstall(); + void Fail(const QString& reason); + void Enter(UpdatePhase phase); + + QString downloadDirectory; + CommandFactory commandFor; + UpdateDownloader downloader; + UpdateInstaller installer; + UpdateState state; + QString downloadedPath; + }; +} diff --git a/ui/backend/qt/update/test/CMakeLists.txt b/ui/backend/qt/update/test/CMakeLists.txt new file mode 100644 index 0000000..c205428 --- /dev/null +++ b/ui/backend/qt/update/test/CMakeLists.txt @@ -0,0 +1,14 @@ +ui_add_test(ui.backend.qt.update_test + SOURCES + TestIssueLog.cpp + TestIssueReport.cpp + TestReleaseFeed.cpp + TestReleaseVersion.cpp + TestUpdateChecker.cpp + TestUpdateDownloader.cpp + TestUpdateInstallation.cpp + TestUpdateInstaller.cpp + TestUpdateSession.cpp + LINK + ui.backend.qt.update +) diff --git a/ui/backend/qt/update/test/TestIssueLog.cpp b/ui/backend/qt/update/test/TestIssueLog.cpp new file mode 100644 index 0000000..1c67c26 --- /dev/null +++ b/ui/backend/qt/update/test/TestIssueLog.cpp @@ -0,0 +1,226 @@ +#include "ui/backend/qt/update/IssueLog.hpp" +#include "gtest/gtest.h" +#include +#include +#include +#include + +namespace +{ + using ui::backend::qt::update::IssueLog; + using ui::backend::qt::update::IssueSeverity; + + int& ForwardedMessages() + { + static int forwarded{ 0 }; + return forwarded; + } + + void CountingHandler(QtMsgType, const QMessageLogContext&, const QString&) + { + ++ForwardedMessages(); + } + + class TestIssueLog + : public testing::Test + { + public: + IssueLog::Config Config() const + { + IssueLog::Config config; + config.directory = QDir{ temporary.path() }.filePath("logs"); + return config; + } + + static QStringList FileLines(const QString& path) + { + QFile file{ path }; + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + return {}; + return QString::fromUtf8(file.readAll()).split('\n', Qt::SkipEmptyParts); + } + + QTemporaryDir temporary; + }; +} + +TEST_F(TestIssueLog, writes_utc_timestamped_line_with_severity) +{ + IssueLog log{ Config() }; + log.Write(IssueSeverity::warning, "Timeout: no response to Start Motor"); + + const auto lines = FileLines(log.FilePath()); + ASSERT_EQ(1, lines.size()); + const QRegularExpression format{ R"(^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \[WARN \] Timeout: no response to Start Motor$)" }; + EXPECT_TRUE(format.match(lines.front()).hasMatch()) << lines.front().toStdString(); +} + +TEST_F(TestIssueLog, creates_missing_log_directory) +{ + IssueLog log{ Config() }; + + EXPECT_TRUE(log.IsWritable()); + EXPECT_TRUE(QDir{ Config().directory }.exists()); + EXPECT_EQ(QDir{ Config().directory }.filePath("application.log"), log.FilePath()); +} + +TEST_F(TestIssueLog, keeps_each_entry_on_one_line) +{ + IssueLog log{ Config() }; + log.Write(IssueSeverity::error, "first\nsecond\r\nthird"); + + const auto lines = FileLines(log.FilePath()); + ASSERT_EQ(1, lines.size()); + EXPECT_TRUE(lines.front().endsWith("[ERROR] first second third")); +} + +TEST_F(TestIssueLog, appends_across_sessions) +{ + { + IssueLog log{ Config() }; + log.Write(IssueSeverity::info, "session one"); + } + IssueLog log{ Config() }; + log.Write(IssueSeverity::info, "session two"); + + const auto lines = FileLines(log.FilePath()); + ASSERT_EQ(2, lines.size()); + EXPECT_TRUE(lines[0].endsWith("session one")); + EXPECT_TRUE(lines[1].endsWith("session two")); +} + +TEST_F(TestIssueLog, rotates_and_keeps_configured_number_of_files) +{ + auto config = Config(); + config.maxFileBytes = 256; + config.keptFiles = 3; + IssueLog log{ config }; + + for (int index = 0; index < 100; ++index) + log.Write(IssueSeverity::info, QString("entry %1").arg(index)); + + const QDir directory{ config.directory }; + EXPECT_TRUE(directory.exists("application.log")); + EXPECT_TRUE(directory.exists("application.1.log")); + EXPECT_TRUE(directory.exists("application.2.log")); + EXPECT_FALSE(directory.exists("application.3.log")); + EXPECT_TRUE(FileLines(log.FilePath()).back().endsWith("entry 99")); + + for (const auto& name : directory.entryList(QDir::Files)) + EXPECT_LT(QFileInfo{ directory.filePath(name) }.size(), config.maxFileBytes + 100) << name.toStdString(); +} + +TEST_F(TestIssueLog, remembers_only_the_most_recent_lines) +{ + auto config = Config(); + config.recentCapacity = 3; + IssueLog log{ config }; + + for (int index = 0; index < 5; ++index) + log.Write(IssueSeverity::info, QString("entry %1").arg(index)); + + const auto all = log.RecentLines(10); + ASSERT_EQ(3, all.size()); + EXPECT_TRUE(all[0].endsWith("entry 2")); + EXPECT_TRUE(all[2].endsWith("entry 4")); + + const auto newest = log.RecentLines(2); + ASSERT_EQ(2, newest.size()); + EXPECT_TRUE(newest[0].endsWith("entry 3")); +} + +TEST_F(TestIssueLog, keeps_recent_lines_when_directory_is_not_writable) +{ + const auto blocker = QDir{ temporary.path() }.filePath("blocker"); + QFile file{ blocker }; + ASSERT_TRUE(file.open(QIODevice::WriteOnly)); + file.close(); + + auto config = Config(); + config.directory = QDir{ blocker }.filePath("logs"); + IssueLog log{ config }; + log.Write(IssueSeverity::error, "adapter lost"); + + EXPECT_FALSE(log.IsWritable()); + ASSERT_EQ(1, log.RecentLines(10).size()); + EXPECT_TRUE(log.RecentLines(10).front().endsWith("adapter lost")); +} + +TEST_F(TestIssueLog, captures_qt_warnings_while_alive) +{ + { + IssueLog log{ Config() }; + log.CaptureQtMessages(); + qWarning("tls backend missing"); + + const auto lines = log.RecentLines(10); + ASSERT_EQ(1, lines.size()); + EXPECT_TRUE(lines.front().endsWith("[WARN ] Qt: tls backend missing")); + } + + IssueLog later{ Config() }; + qWarning("after the first log is gone"); + EXPECT_TRUE(later.RecentLines(10).isEmpty()); +} + +TEST_F(TestIssueLog, keeps_running_when_the_log_folder_disappears_while_capturing_qt_messages) +{ + auto config = Config(); + config.maxFileBytes = 64; + IssueLog log{ config }; + log.CaptureQtMessages(); + log.Write(IssueSeverity::info, "first entry fills the file past its limit"); + + ASSERT_TRUE(QDir{ config.directory }.removeRecursively()); + log.Write(IssueSeverity::error, "written after the folder vanished"); + + EXPECT_TRUE(log.RecentLines(10).back().endsWith("written after the folder vanished")); +} + +TEST_F(TestIssueLog, captures_qt_critical_messages_as_errors_and_skips_debug_and_info) +{ + IssueLog log{ Config() }; + log.CaptureQtMessages(); + qDebug("debug chatter"); + qInfo("info chatter"); + qCritical("socket lost"); + + const auto lines = log.RecentLines(10); + ASSERT_EQ(1, lines.size()); + EXPECT_TRUE(lines.front().endsWith("[ERROR] Qt: socket lost")); +} + +TEST_F(TestIssueLog, a_second_log_does_not_take_the_capture_from_the_first) +{ + IssueLog first{ Config() }; + first.CaptureQtMessages(); + first.CaptureQtMessages(); + + auto secondConfig = Config(); + secondConfig.directory = QDir{ temporary.path() }.filePath("second"); + IssueLog second{ secondConfig }; + second.CaptureQtMessages(); + + qWarning("only the first log hears this"); + + EXPECT_EQ(1, first.RecentLines(10).size()); + EXPECT_TRUE(second.RecentLines(10).isEmpty()); +} + +TEST_F(TestIssueLog, forwards_qt_messages_to_the_handler_installed_before_it) +{ + const auto original = qInstallMessageHandler(CountingHandler); + ForwardedMessages() = 0; + { + IssueLog log{ Config() }; + log.CaptureQtMessages(); + qWarning("seen by both"); + + EXPECT_EQ(1, ForwardedMessages()); + EXPECT_EQ(1, log.RecentLines(10).size()); + } + + qWarning("seen by the restored handler only"); + EXPECT_EQ(2, ForwardedMessages()); + qInstallMessageHandler(original); +} diff --git a/ui/backend/qt/update/test/TestIssueReport.cpp b/ui/backend/qt/update/test/TestIssueReport.cpp new file mode 100644 index 0000000..3a84c25 --- /dev/null +++ b/ui/backend/qt/update/test/TestIssueReport.cpp @@ -0,0 +1,88 @@ +#include "ui/backend/qt/update/IssueReport.hpp" +#include "gtest/gtest.h" +#include +#include + +namespace +{ + using namespace ui::backend::qt::update; + + class TestIssueReport + : public testing::Test + { + public: + static QString Item(const QUrl& url, const QString& key) + { + return QUrlQuery{ url }.queryItemValue(key, QUrl::FullyDecoded); + } + + const QUrl newIssue{ "https://github.com/example/project/issues/new" }; + const IssueProduct commander{ "Example Tool", "Example" }; + const IssueEnvironment environment{ commander, "1.2.3", "Ubuntu 24.04 LTS", "x86_64", "6.4.2", "~/.local/share/example/Example/logs/example.log" }; + }; +} + +TEST_F(TestIssueReport, opens_new_issue_page_with_prefixed_title) +{ + const auto url = BuildIssueUrl(newIssue, environment, {}); + + EXPECT_EQ("https", url.scheme()); + EXPECT_EQ("github.com", url.host()); + EXPECT_EQ("/example/project/issues/new", url.path()); + EXPECT_EQ("[Example] ", Item(url, "title")); +} + +TEST_F(TestIssueReport, title_and_environment_name_the_product_that_reports) +{ + auto virtualMotor = environment; + virtualMotor.product = IssueProduct{ "Example Viewer", "Viewer" }; + const auto url = BuildIssueUrl(newIssue, virtualMotor, {}); + + EXPECT_EQ("[Viewer] ", Item(url, "title")); + EXPECT_TRUE(Item(url, "body").contains("| Example Viewer | 1.2.3 |")); +} + +TEST_F(TestIssueReport, body_lists_environment_and_log_file) +{ + const auto body = Item(BuildIssueUrl(newIssue, environment, {}), "body"); + + EXPECT_TRUE(body.contains("| Example Tool | 1.2.3 |")); + EXPECT_TRUE(body.contains("| Operating system | Ubuntu 24.04 LTS |")); + EXPECT_TRUE(body.contains("| Architecture | x86_64 |")); + EXPECT_TRUE(body.contains("| Qt | 6.4.2 |")); + EXPECT_TRUE(body.contains("~/.local/share/example/Example/logs/example.log")); + EXPECT_TRUE(body.contains("(no entries)")); +} + +TEST_F(TestIssueReport, log_lines_survive_reserved_characters) +{ + const QStringList log{ "duty 50% + offset & #3 = done?", "path C:\\temp\\a b" }; + const auto body = Item(BuildIssueUrl(newIssue, environment, log), "body"); + + EXPECT_TRUE(body.contains("duty 50% + offset & #3 = done?\npath C:\\temp\\a b")); +} + +TEST_F(TestIssueReport, drops_oldest_lines_to_fit_url_limit) +{ + QStringList log; + for (int index = 0; index < 500; ++index) + log.append(QString("2026-10-24T10:00:00.000Z [WARN ] timeout number %1").arg(index)); + + const auto url = BuildIssueUrl(newIssue, environment, log, 3000); + const auto body = Item(url, "body"); + + EXPECT_LE(url.toEncoded().size(), 3000); + EXPECT_TRUE(body.contains("timeout number 499")); + EXPECT_FALSE(body.contains("timeout number 0\n")); +} + +TEST_F(TestIssueReport, environment_hides_home_directory) +{ + const auto current = CurrentIssueEnvironment(commander, "1.2.3", QDir::homePath() + "/logs/example.log"); + + EXPECT_EQ("1.2.3", current.applicationVersion); + EXPECT_EQ("Example", current.product.tag); + EXPECT_TRUE(current.logFilePath.startsWith("~")); + EXPECT_FALSE(current.logFilePath.contains(QDir::toNativeSeparators(QDir::homePath()))); + EXPECT_FALSE(current.qtVersion.isEmpty()); +} diff --git a/ui/backend/qt/update/test/TestReleaseFeed.cpp b/ui/backend/qt/update/test/TestReleaseFeed.cpp new file mode 100644 index 0000000..2a9f562 --- /dev/null +++ b/ui/backend/qt/update/test/TestReleaseFeed.cpp @@ -0,0 +1,166 @@ +#include "ui/backend/qt/update/ReleaseFeed.hpp" +#include "gtest/gtest.h" + +namespace +{ + using namespace ui::backend::qt::update; + + class TestReleaseFeed + : public testing::Test + { + public: + static QByteArray Release(const QString& tag, const QString& assets) + { + return QString(R"({ + "tag_name": "%1", + "html_url": "https://github.com/example/project/releases/tag/%1", + "assets": [%2] + })") + .arg(tag, assets) + .toUtf8(); + } + + static QString Asset(const QString& name, const QString& digest = sha256Digest) + { + return QString(R"({ "name": "%1", "size": 4096, "digest": "%2", "browser_download_url": "https://github.com/example/project/releases/download/v1.1.0/%1" })").arg(name, digest); + } + + static inline const QString sha256Hex{ "d02c96fe999b3b2bbab16cd745a0a94c269609a26269cc171764ebb48670a83e" }; + static inline const QString sha256Digest{ "sha256:" + sha256Hex }; + + const QString assets{ Asset("example-tool-v1.1.0-linux-x86_64.tar.gz") + "," + + Asset("example-tool-v1.1.0-linux-x86_64.deb") + "," + + Asset("example-tool-v1.1.0-windows-x86_64.zip") + "," + + Asset("example-tool-v1.1.0-windows-x86_64-setup.exe") }; + }; +} + +TEST_F(TestReleaseFeed, reads_version_tag_and_release_page) +{ + const auto release = ParseLatestRelease(Release("v1.1.0", assets), InstallerPlatform::linuxX64); + + ASSERT_TRUE(release.has_value()); + EXPECT_EQ((ReleaseVersion{ 1, 1, 0 }), release->version); + EXPECT_EQ("v1.1.0", release->tag); + EXPECT_EQ(QUrl("https://github.com/example/project/releases/tag/v1.1.0"), release->pageUrl); +} + +TEST_F(TestReleaseFeed, picks_debian_package_on_linux) +{ + const auto release = ParseLatestRelease(Release("v1.1.0", assets), InstallerPlatform::linuxX64); + + ASSERT_TRUE(release.has_value()); + ASSERT_TRUE(release->installer.has_value()); + EXPECT_EQ("example-tool-v1.1.0-linux-x86_64.deb", release->installer->fileName); + EXPECT_TRUE(release->installer->url.path().endsWith("example-tool-v1.1.0-linux-x86_64.deb")); +} + +TEST_F(TestReleaseFeed, picks_setup_executable_on_windows) +{ + const auto release = ParseLatestRelease(Release("v1.1.0", assets), InstallerPlatform::windowsX64); + + ASSERT_TRUE(release.has_value()); + ASSERT_TRUE(release->installer.has_value()); + EXPECT_TRUE(release->installer->url.path().endsWith("example-tool-v1.1.0-windows-x86_64-setup.exe")); +} + +TEST_F(TestReleaseFeed, has_no_installer_when_release_lacks_one) +{ + const auto release = ParseLatestRelease(Release("v1.1.0", Asset("example-viewer-v1.1.0-linux-x86_64.tar.gz")), InstallerPlatform::linuxX64); + + ASSERT_TRUE(release.has_value()); + EXPECT_FALSE(release->installer.has_value()); +} + +TEST_F(TestReleaseFeed, has_no_installer_on_unsupported_platform) +{ + const auto release = ParseLatestRelease(Release("v1.1.0", assets), InstallerPlatform::unsupported); + + ASSERT_TRUE(release.has_value()); + EXPECT_FALSE(release->installer.has_value()); +} + +TEST_F(TestReleaseFeed, ignores_installer_not_served_over_https) +{ + const auto insecure = QString(R"({ "name": "example-tool-v1.1.0-linux-x86_64.deb", "browser_download_url": "http://example.com/example-tool-v1.1.0-linux-x86_64.deb" })"); + const auto release = ParseLatestRelease(Release("v1.1.0", insecure), InstallerPlatform::linuxX64); + + ASSERT_TRUE(release.has_value()); + EXPECT_FALSE(release->installer.has_value()); +} + +TEST_F(TestReleaseFeed, reads_installer_size_and_sha256_digest) +{ + const auto release = ParseLatestRelease(Release("v1.1.0", assets), InstallerPlatform::linuxX64); + + ASSERT_TRUE(release.has_value()); + ASSERT_TRUE(release->installer.has_value()); + EXPECT_EQ(4096, release->installer->size); + ASSERT_TRUE(release->installer->sha256.has_value()); + EXPECT_EQ(QByteArray::fromHex(sha256Hex.toLatin1()), *release->installer->sha256); + EXPECT_EQ(32, release->installer->sha256->size()); +} + +TEST_F(TestReleaseFeed, installer_without_a_usable_digest_has_none) +{ + for (const auto* digest : { "", "md5:0123456789abcdef0123456789abcdef", "sha256:", "sha256:d02c96fe", "sha256:z02c96fe999b3b2bbab16cd745a0a94c269609a26269cc171764ebb48670a83e" }) + { + const auto release = ParseLatestRelease(Release("v1.1.0", Asset("example-tool-v1.1.0-linux-x86_64.deb", digest)), InstallerPlatform::linuxX64); + + ASSERT_TRUE(release.has_value()) << digest; + ASSERT_TRUE(release->installer.has_value()) << digest; + EXPECT_FALSE(release->installer->sha256.has_value()) << digest; + } +} + +TEST_F(TestReleaseFeed, sha256_digest_accepts_upper_case_hex) +{ + const auto digest = ParseSha256Digest("sha256:" + sha256Hex.toUpper()); + + ASSERT_TRUE(digest.has_value()); + EXPECT_EQ(QByteArray::fromHex(sha256Hex.toLatin1()), *digest); +} + +TEST_F(TestReleaseFeed, rejects_documents_that_are_not_a_release) +{ + EXPECT_FALSE(ParseLatestRelease("", InstallerPlatform::linuxX64).has_value()); + EXPECT_FALSE(ParseLatestRelease("[]", InstallerPlatform::linuxX64).has_value()); + EXPECT_FALSE(ParseLatestRelease(R"({ "message": "API rate limit exceeded" })", InstallerPlatform::linuxX64).has_value()); + EXPECT_FALSE(ParseLatestRelease(Release("dry-run-12", assets), InstallerPlatform::linuxX64).has_value()); +} + +TEST_F(TestReleaseFeed, newer_release_is_an_update) +{ + const auto evaluation = EvaluateLatestRelease(Release("v1.1.0", assets), ReleaseVersion{ 1, 0, 9 }, InstallerPlatform::linuxX64); + + EXPECT_EQ(UpdateStatus::updateAvailable, evaluation.status); + ASSERT_TRUE(evaluation.latest.has_value()); + EXPECT_EQ((ReleaseVersion{ 1, 1, 0 }), evaluation.latest->version); +} + +TEST_F(TestReleaseFeed, same_or_older_release_is_up_to_date) +{ + EXPECT_EQ(UpdateStatus::upToDate, EvaluateLatestRelease(Release("v1.1.0", assets), ReleaseVersion{ 1, 1, 0 }, InstallerPlatform::linuxX64).status); + EXPECT_EQ(UpdateStatus::upToDate, EvaluateLatestRelease(Release("v1.1.0", assets), ReleaseVersion{ 2, 0, 0 }, InstallerPlatform::linuxX64).status); +} + +TEST_F(TestReleaseFeed, unreadable_feed_is_invalid) +{ + const auto evaluation = EvaluateLatestRelease("not json", ReleaseVersion{ 1, 0, 0 }, InstallerPlatform::linuxX64); + + EXPECT_EQ(UpdateStatus::invalidResponse, evaluation.status); + EXPECT_FALSE(evaluation.latest.has_value()); +} + +TEST_F(TestReleaseFeed, keeps_every_asset_downloadable_over_https) +{ + const auto insecure = QString(R"({ "name": "example-data-v1.7.0.bin", "browser_download_url": "http://example.com/example-data-v1.7.0.bin" })"); + const auto unlinked = QString(R"({ "name": "example-notes-v1.7.0.txt" })"); + const auto release = ParseLatestRelease(Release("v1.7.0", assets + "," + Asset("example-data-v1.7.0.bin") + "," + insecure + "," + unlinked), InstallerPlatform::linuxX64); + + ASSERT_TRUE(release.has_value()); + ASSERT_EQ(5u, release->assets.size()); + EXPECT_EQ("example-data-v1.7.0.bin", release->assets.back().fileName); + EXPECT_EQ(4096, release->assets.back().size); + EXPECT_TRUE(release->assets.back().sha256.has_value()); +} diff --git a/ui/backend/qt/update/test/TestReleaseVersion.cpp b/ui/backend/qt/update/test/TestReleaseVersion.cpp new file mode 100644 index 0000000..5c73cba --- /dev/null +++ b/ui/backend/qt/update/test/TestReleaseVersion.cpp @@ -0,0 +1,66 @@ +#include "ui/backend/qt/update/ReleaseVersion.hpp" +#include "gtest/gtest.h" + +namespace +{ + using ui::backend::qt::update::ReleaseVersion; + + class TestReleaseVersion + : public testing::Test + {}; +} + +TEST_F(TestReleaseVersion, parses_release_please_tag) +{ + const auto version = ReleaseVersion::Parse("v1.2.3"); + + ASSERT_TRUE(version.has_value()); + EXPECT_EQ(1u, version->major); + EXPECT_EQ(2u, version->minor); + EXPECT_EQ(3u, version->patch); +} + +TEST_F(TestReleaseVersion, parses_project_version_without_prefix) +{ + EXPECT_EQ((ReleaseVersion{ 10, 0, 42 }), ReleaseVersion::Parse("10.0.42")); +} + +TEST_F(TestReleaseVersion, rejects_malformed_versions) +{ + for (const auto* text : { "", "v", "1", "1.2", "1.2.", "1..3", "1.2.3.4", "1.2.3-rc.1", "1.2.3+build", "01.2.3", "-1.2.3", "dry-run-17", "v 1.2.3" }) + EXPECT_FALSE(ReleaseVersion::Parse(text).has_value()) << text; +} + +TEST_F(TestReleaseVersion, orders_by_major_then_minor_then_patch) +{ + EXPECT_LT((ReleaseVersion{ 1, 9, 9 }), (ReleaseVersion{ 2, 0, 0 })); + EXPECT_LT((ReleaseVersion{ 1, 2, 9 }), (ReleaseVersion{ 1, 10, 0 })); + EXPECT_LT((ReleaseVersion{ 1, 2, 3 }), (ReleaseVersion{ 1, 2, 4 })); + EXPECT_EQ((ReleaseVersion{ 1, 2, 3 }), (ReleaseVersion{ 1, 2, 3 })); +} + +TEST_F(TestReleaseVersion, compares_each_component_in_both_directions) +{ + const ReleaseVersion base{ 1, 2, 3 }; + + for (const auto& higher : { ReleaseVersion{ 2, 0, 0 }, ReleaseVersion{ 1, 3, 0 }, ReleaseVersion{ 1, 2, 4 } }) + { + EXPECT_TRUE(base < higher); + EXPECT_TRUE(higher > base); + EXPECT_TRUE(base <= higher); + EXPECT_TRUE(higher >= base); + EXPECT_FALSE(base == higher); + EXPECT_TRUE(base != higher); + EXPECT_FALSE(higher < base); + } + + EXPECT_TRUE(base <= base); + EXPECT_TRUE(base >= base); + EXPECT_FALSE(base < base); + EXPECT_FALSE(base != base); +} + +TEST_F(TestReleaseVersion, formats_without_prefix) +{ + EXPECT_EQ("3.14.159", (ReleaseVersion{ 3, 14, 159 }).ToString()); +} diff --git a/ui/backend/qt/update/test/TestUpdateChecker.cpp b/ui/backend/qt/update/test/TestUpdateChecker.cpp new file mode 100644 index 0000000..a421320 --- /dev/null +++ b/ui/backend/qt/update/test/TestUpdateChecker.cpp @@ -0,0 +1,130 @@ +#include "ui/backend/qt/update/UpdateChecker.hpp" +#include "gtest/gtest.h" +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace ui::backend::qt::update; + + class TestUpdateChecker + : public testing::Test + { + public: + static void SetUpTestSuite() + { + static int argc{ 1 }; + static char name[]{ "support_test" }; + static char* argv[]{ name, nullptr }; + + if (QCoreApplication::instance() == nullptr) + application = std::make_unique(argc, argv); + } + + static void TearDownTestSuite() + { + application.reset(); + } + + QUrl Feed(const QByteArray& content) + { + const auto path = QDir{ temporary.path() }.filePath("latest.json"); + QFile file{ path }; + EXPECT_TRUE(file.open(QIODevice::WriteOnly)); + file.write(content); + return QUrl::fromLocalFile(path); + } + + static QByteArray Release(const QString& tag) + { + return QString(R"({ "tag_name": "%1", "html_url": "https://github.com/example/project/releases/tag/%1", "assets": [] })").arg(tag).toUtf8(); + } + + void Check(const QUrl& feed, int checks = 1) + { + UpdateChecker checker{ ReleaseVersion{ 1, 0, 0 }, feed, "example-tool/1.0.0" }; + QEventLoop loop; + QObject::connect(&checker, &UpdateChecker::UpdateAvailable, &loop, [this, &loop](const ReleaseInfo& release) + { + ++emitted; + available = release; + loop.quit(); + }); + QObject::connect(&checker, &UpdateChecker::UpToDate, &loop, [this, &loop](const ReleaseInfo& release) + { + ++emitted; + upToDate = release; + loop.quit(); + }); + QObject::connect(&checker, &UpdateChecker::CheckFailed, &loop, [this, &loop](const QString& reason) + { + ++emitted; + failure = reason; + loop.quit(); + }); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + + for (int index = 0; index < checks; ++index) + checker.Check(); + EXPECT_TRUE(checker.IsChecking()); + + loop.exec(); + QCoreApplication::processEvents(); + EXPECT_FALSE(checker.IsChecking()); + } + + static inline std::unique_ptr application; + QTemporaryDir temporary; + int emitted{ 0 }; + std::optional available; + std::optional upToDate; + std::optional failure; + }; +} + +TEST_F(TestUpdateChecker, announces_newer_release) +{ + Check(Feed(Release("v1.4.0"))); + + ASSERT_TRUE(available.has_value()); + EXPECT_EQ((ReleaseVersion{ 1, 4, 0 }), available->version); + EXPECT_FALSE(upToDate.has_value()); + EXPECT_FALSE(failure.has_value()); +} + +TEST_F(TestUpdateChecker, reports_up_to_date_for_current_release) +{ + Check(Feed(Release("v1.0.0"))); + + ASSERT_TRUE(upToDate.has_value()); + EXPECT_FALSE(available.has_value()); +} + +TEST_F(TestUpdateChecker, reports_failure_for_unreachable_feed) +{ + Check(QUrl::fromLocalFile(QDir{ temporary.path() }.filePath("missing.json"))); + + ASSERT_TRUE(failure.has_value()); + EXPECT_FALSE(failure->isEmpty()); +} + +TEST_F(TestUpdateChecker, reports_failure_for_malformed_feed) +{ + Check(Feed(R"({ "message": "Not Found" })")); + + ASSERT_TRUE(failure.has_value()); + EXPECT_EQ("the release feed did not contain a valid release", *failure); +} + +TEST_F(TestUpdateChecker, ignores_check_while_one_is_pending) +{ + Check(Feed(Release("v2.0.0")), 3); + QCoreApplication::processEvents(); + + EXPECT_EQ(1, emitted); +} diff --git a/ui/backend/qt/update/test/TestUpdateDownloader.cpp b/ui/backend/qt/update/test/TestUpdateDownloader.cpp new file mode 100644 index 0000000..251ebe0 --- /dev/null +++ b/ui/backend/qt/update/test/TestUpdateDownloader.cpp @@ -0,0 +1,292 @@ +#include "ui/backend/qt/update/UpdateDownloader.hpp" +#include "gtest/gtest.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace ui::backend::qt::update; + + class TestUpdateDownloader + : public testing::Test + { + public: + static void SetUpTestSuite() + { + static int argc{ 1 }; + static char name[]{ "support_test" }; + static char* argv[]{ name, nullptr }; + + if (QCoreApplication::instance() == nullptr) + application = std::make_unique(argc, argv); + } + + static void TearDownTestSuite() + { + application.reset(); + } + + InstallerAsset Asset(const QByteArray& content, const QString& fileName = "example-tool-v9.9.9-linux-x86_64.deb") + { + const auto path = QDir{ source.path() }.filePath("published.bin"); + QFile file{ path }; + EXPECT_TRUE(file.open(QIODevice::WriteOnly)); + file.write(content); + return InstallerAsset{ fileName, QUrl::fromLocalFile(path), content.size(), QCryptographicHash::hash(content, QCryptographicHash::Sha256) }; + } + + void Download(const InstallerAsset& asset) + { + QEventLoop loop; + QObject::connect(&downloader, &UpdateDownloader::Progress, &loop, [this](qint64 received, qint64 total) + { + lastReceived = received; + lastTotal = total; + }); + QObject::connect(&downloader, &UpdateDownloader::Downloaded, &loop, [this, &loop](const QString& path) + { + downloaded = path; + loop.quit(); + }); + QObject::connect(&downloader, &UpdateDownloader::Failed, &loop, [this, &loop](const QString& reason) + { + failure = reason; + loop.quit(); + }); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + + downloader.Start(asset, target.path()); + loop.exec(); + QCoreApplication::processEvents(); + } + + QStringList TargetFiles() const + { + return QDir{ target.path() }.entryList(QDir::Files); + } + + static QByteArray Read(const QString& path) + { + QFile file{ path }; + return file.open(QIODevice::ReadOnly) ? file.readAll() : QByteArray{}; + } + + static inline std::unique_ptr application; + QTemporaryDir source; + QTemporaryDir target; + UpdateDownloader downloader{ "example-tool/1.0.0" }; + std::optional downloaded; + std::optional failure; + qint64 lastReceived{ -1 }; + qint64 lastTotal{ -1 }; + const QByteArray payload{ QByteArray{ "installer payload " }.repeated(512) }; + }; +} + +TEST_F(TestUpdateDownloader, downloads_and_verifies_the_installer) +{ + Download(Asset(payload)); + + ASSERT_TRUE(downloaded.has_value()) << failure.value_or("").toStdString(); + EXPECT_EQ(QDir{ target.path() }.filePath("example-tool-v9.9.9-linux-x86_64.deb"), *downloaded); + EXPECT_EQ(payload, Read(*downloaded)); + EXPECT_EQ(QStringList{ "example-tool-v9.9.9-linux-x86_64.deb" }, TargetFiles()); + EXPECT_EQ(payload.size(), lastReceived); + EXPECT_EQ(payload.size(), lastTotal); + EXPECT_FALSE(downloader.IsDownloading()); +} + +TEST_F(TestUpdateDownloader, deletes_a_download_that_does_not_match_the_checksum) +{ + auto asset = Asset(payload); + asset.sha256 = QCryptographicHash::hash("something else", QCryptographicHash::Sha256); + + Download(asset); + + ASSERT_TRUE(failure.has_value()); + EXPECT_EQ("the download does not match the checksum published with the release", *failure); + EXPECT_FALSE(downloaded.has_value()); + EXPECT_TRUE(TargetFiles().isEmpty()); +} + +TEST_F(TestUpdateDownloader, deletes_a_download_of_unexpected_size) +{ + auto asset = Asset(payload); + asset.size = payload.size() + 1; + + Download(asset); + + ASSERT_TRUE(failure.has_value()); + EXPECT_TRUE(failure->contains("bytes")) << failure->toStdString(); + EXPECT_TRUE(TargetFiles().isEmpty()); +} + +TEST_F(TestUpdateDownloader, refuses_an_installer_without_a_published_checksum) +{ + auto asset = Asset(payload); + asset.sha256.reset(); + + Download(asset); + + ASSERT_TRUE(failure.has_value()); + EXPECT_TRUE(failure->contains("no checksum")) << failure->toStdString(); + EXPECT_TRUE(TargetFiles().isEmpty()); +} + +TEST_F(TestUpdateDownloader, refuses_an_installer_name_with_a_path) +{ + Download(Asset(payload, "../example-tool-v9.9.9-linux-x86_64.deb")); + + ASSERT_TRUE(failure.has_value()); + EXPECT_TRUE(failure->contains("not a plain file name")) << failure->toStdString(); + EXPECT_TRUE(TargetFiles().isEmpty()); +} + +TEST_F(TestUpdateDownloader, reports_an_unreachable_installer) +{ + auto asset = Asset(payload); + asset.url = QUrl::fromLocalFile(QDir{ source.path() }.filePath("missing.bin")); + + Download(asset); + + ASSERT_TRUE(failure.has_value()); + EXPECT_FALSE(failure->isEmpty()); + EXPECT_TRUE(TargetFiles().isEmpty()); +} + +TEST_F(TestUpdateDownloader, replaces_an_earlier_download_of_the_same_installer) +{ + QFile stale{ QDir{ target.path() }.filePath("example-tool-v9.9.9-linux-x86_64.deb") }; + ASSERT_TRUE(stale.open(QIODevice::WriteOnly)); + stale.write("stale"); + stale.close(); + + Download(Asset(payload)); + + ASSERT_TRUE(downloaded.has_value()) << failure.value_or("").toStdString(); + EXPECT_EQ(payload, Read(*downloaded)); +} + +TEST_F(TestUpdateDownloader, cancel_discards_the_partial_download_silently) +{ + bool signalled{ false }; + QObject::connect(&downloader, &UpdateDownloader::Downloaded, [&signalled](const QString&) + { + signalled = true; + }); + QObject::connect(&downloader, &UpdateDownloader::Failed, [&signalled](const QString&) + { + signalled = true; + }); + + downloader.Start(Asset(payload), target.path()); + EXPECT_TRUE(downloader.IsDownloading()); + downloader.Cancel(); + + QEventLoop loop; + QTimer::singleShot(200, &loop, &QEventLoop::quit); + loop.exec(); + + EXPECT_FALSE(signalled); + EXPECT_FALSE(downloader.IsDownloading()); + EXPECT_TRUE(TargetFiles().isEmpty()); +} + +TEST_F(TestUpdateDownloader, refuses_an_empty_or_windows_style_installer_name) +{ + for (const auto* name : { "", "bin\\setup.exe" }) + { + failure.reset(); + + Download(Asset(payload, name)); + + ASSERT_TRUE(failure.has_value()) << name; + EXPECT_TRUE(failure->contains("not a plain file name")) << failure->toStdString(); + } + EXPECT_TRUE(TargetFiles().isEmpty()); +} + +TEST_F(TestUpdateDownloader, accepts_a_release_that_lists_no_size) +{ + auto asset = Asset(payload); + asset.size = 0; + + Download(asset); + + ASSERT_TRUE(downloaded.has_value()) << failure.value_or("").toStdString(); + EXPECT_EQ(payload, Read(*downloaded)); +} + +TEST_F(TestUpdateDownloader, reports_a_download_folder_that_cannot_be_created) +{ + QFile blocker{ QDir{ target.path() }.filePath("not-a-folder") }; + ASSERT_TRUE(blocker.open(QIODevice::WriteOnly)); + blocker.close(); + const auto directory = QDir{ target.path() }.filePath("not-a-folder/downloads"); + + QEventLoop loop; + QObject::connect(&downloader, &UpdateDownloader::Failed, &loop, [this, &loop](const QString& reason) + { + failure = reason; + loop.quit(); + }); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + downloader.Start(Asset(payload), directory); + loop.exec(); + + ASSERT_TRUE(failure.has_value()); + EXPECT_TRUE(failure->startsWith("cannot create the download folder")) << failure->toStdString(); + EXPECT_FALSE(downloader.IsDownloading()); +} + +TEST_F(TestUpdateDownloader, reports_a_partial_file_that_cannot_be_written) +{ + ASSERT_TRUE(QDir{ target.path() }.mkpath("example-tool-v9.9.9-linux-x86_64.deb.part")); + + Download(Asset(payload)); + + ASSERT_TRUE(failure.has_value()); + EXPECT_TRUE(failure->startsWith("cannot write")) << failure->toStdString(); + EXPECT_FALSE(downloaded.has_value()); + EXPECT_FALSE(downloader.IsDownloading()); +} + +TEST_F(TestUpdateDownloader, reports_a_download_that_cannot_replace_the_target) +{ + ASSERT_TRUE(QDir{ target.path() }.mkpath("example-tool-v9.9.9-linux-x86_64.deb/occupied")); + + Download(Asset(payload)); + + ASSERT_TRUE(failure.has_value()); + EXPECT_TRUE(failure->startsWith("cannot move the download")) << failure->toStdString(); + EXPECT_FALSE(QFile::exists(QDir{ target.path() }.filePath("example-tool-v9.9.9-linux-x86_64.deb.part"))); +} + +TEST_F(TestUpdateDownloader, ignores_a_second_start_while_downloading) +{ + const auto asset = Asset(payload); + auto other = asset; + other.fileName = "other.deb"; + + downloader.Start(asset, target.path()); + downloader.Start(other, target.path()); + Download(asset); + + ASSERT_TRUE(downloaded.has_value()) << failure.value_or("").toStdString(); + + EXPECT_FALSE(TargetFiles().contains("other.deb")); +} + +TEST_F(TestUpdateDownloader, cancel_without_a_download_does_nothing) +{ + downloader.Cancel(); + + EXPECT_FALSE(downloader.IsDownloading()); + EXPECT_TRUE(TargetFiles().isEmpty()); +} diff --git a/ui/backend/qt/update/test/TestUpdateInstallation.cpp b/ui/backend/qt/update/test/TestUpdateInstallation.cpp new file mode 100644 index 0000000..46242ce --- /dev/null +++ b/ui/backend/qt/update/test/TestUpdateInstallation.cpp @@ -0,0 +1,169 @@ +#include "ui/backend/qt/update/UpdateInstallation.hpp" +#include "gtest/gtest.h" +#include +#include +#include +#include + +namespace +{ + using namespace ui::backend::qt::update; + + class TestUpdateInstallation + : public testing::Test + { + public: + static QString DecodedScript(const InstallCommand& command) + { + const auto index = command.arguments.indexOf("-EncodedCommand"); + if (index < 0 || index + 1 >= command.arguments.size()) + return {}; + + const auto bytes = QByteArray::fromBase64(command.arguments.at(index + 1).toLatin1()); + return QString::fromUtf16(reinterpret_cast(bytes.constData()), bytes.size() / 2); + } + + QString WindowsLayout(bool withUninstaller) + { + EXPECT_TRUE(QDir{ installation.path() }.mkpath("bin")); + if (withUninstaller) + { + QFile uninstaller{ QDir{ installation.path() }.filePath("Uninstall.exe") }; + EXPECT_TRUE(uninstaller.open(QIODevice::WriteOnly)); + } + return QDir{ installation.path() }.filePath("bin/example-tool.exe"); + } + + QString FakeExecutable(const QString& name) + { + const auto path = QDir{ tools.path() }.filePath(name); + QFile file{ path }; + EXPECT_TRUE(file.open(QIODevice::WriteOnly)); + file.write("#!/bin/sh\n"); + file.close(); + EXPECT_TRUE(file.setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner)); + return path; + } + + void UseOnlyFakeTools() + { + qputenv("PATH", QFile::encodeName(tools.path())); + } + + void TearDown() override + { + qputenv("PATH", originalPath); + } + + QTemporaryDir installation; + QTemporaryDir tools; + const QByteArray originalPath{ qgetenv("PATH") }; + }; +} + +TEST_F(TestUpdateInstallation, windows_installation_with_an_uninstaller_is_a_package) +{ + EXPECT_EQ(InstallationKind::package, DetectInstallation(InstallerPlatform::windowsX64, WindowsLayout(true))); +} + +TEST_F(TestUpdateInstallation, windows_installation_without_an_uninstaller_is_portable) +{ + EXPECT_EQ(InstallationKind::portable, DetectInstallation(InstallerPlatform::windowsX64, WindowsLayout(false))); +} + +TEST_F(TestUpdateInstallation, linux_installation_under_usr_is_a_package) +{ + EXPECT_EQ(InstallationKind::package, DetectInstallation(InstallerPlatform::linuxX64, "/usr/bin/example-tool")); + EXPECT_EQ(InstallationKind::portable, DetectInstallation(InstallerPlatform::linuxX64, "/home/user/tools/example-tool")); + EXPECT_EQ(InstallationKind::portable, DetectInstallation(InstallerPlatform::linuxX64, "/usr/../home/user/example-tool")); +} + +TEST_F(TestUpdateInstallation, unsupported_platform_is_portable) +{ + EXPECT_EQ(InstallationKind::portable, DetectInstallation(InstallerPlatform::unsupported, "/usr/bin/example-tool")); +} + +TEST_F(TestUpdateInstallation, windows_install_directory_is_the_parent_of_bin) +{ + EXPECT_EQ(QDir::cleanPath(installation.path()), WindowsInstallDirectory(WindowsLayout(true))); +} + +TEST_F(TestUpdateInstallation, windows_command_starts_the_installer_elevated_after_the_tool_exits) +{ + const auto command = WindowsUpdateCommand("C:\\Temp\\setup.exe", "C:\\Program Files\\Example Tool", 4242, "C:\\Program Files\\Example Tool\\bin\\example-tool.exe"); + const auto script = DecodedScript(command); + + EXPECT_EQ("powershell.exe", command.program); + EXPECT_TRUE(command.exitsBeforeInstalling); + EXPECT_TRUE(command.arguments.contains("-NoProfile")); + EXPECT_TRUE(script.startsWith("Wait-Process -Id 4242 ")) << script.toStdString(); + EXPECT_TRUE(script.contains("Start-Process -FilePath 'C:\\Temp\\setup.exe' -ArgumentList '/S /RELAUNCH /D=C:\\Program Files\\Example Tool' -Verb RunAs")) << script.toStdString(); +} + +TEST_F(TestUpdateInstallation, windows_command_restarts_the_old_version_when_elevation_is_declined) +{ + const auto script = DecodedScript(WindowsUpdateCommand("C:\\Temp\\setup.exe", "C:\\Apps\\CAN", 1, "C:\\Apps\\CAN\\bin\\example-tool.exe")); + + EXPECT_TRUE(script.contains("catch { Start-Process -FilePath 'C:\\Apps\\CAN\\bin\\example-tool.exe' }")) << script.toStdString(); +} + +TEST_F(TestUpdateInstallation, windows_command_escapes_quotes_in_paths) +{ + const auto script = DecodedScript(WindowsUpdateCommand("C:\\Users\\O'Brien\\setup.exe", "C:\\Apps\\CAN", 1, "C:\\Apps\\CAN\\bin\\example-tool.exe")); + + EXPECT_TRUE(script.contains("'C:\\Users\\O''Brien\\setup.exe'")) << script.toStdString(); +} + +TEST_F(TestUpdateInstallation, linux_command_installs_the_package_through_elevation) +{ + const auto command = LinuxUpdateCommand("/usr/bin/pkexec", "/usr/bin/apt-get", "/tmp/updates/example-tool-v9.9.9-linux-x86_64.deb"); + + EXPECT_EQ("/usr/bin/pkexec", command.program); + EXPECT_EQ((QStringList{ "/usr/bin/apt-get", "install", "-y", "/tmp/updates/example-tool-v9.9.9-linux-x86_64.deb" }), command.arguments); + EXPECT_FALSE(command.exitsBeforeInstalling); +} + +TEST_F(TestUpdateInstallation, portable_installation_has_no_update_command) +{ + EXPECT_FALSE(DefaultUpdateCommand(InstallerPlatform::linuxX64, "/tmp/x.deb", "/home/user/example-tool", 1).has_value()); + EXPECT_FALSE(DefaultUpdateCommand(InstallerPlatform::windowsX64, "C:\\Temp\\setup.exe", WindowsLayout(false), 1).has_value()); +} + +TEST_F(TestUpdateInstallation, windows_package_updates_its_own_installation_folder) +{ + const auto application = WindowsLayout(true); + const auto command = DefaultUpdateCommand(InstallerPlatform::windowsX64, "C:\\Temp\\setup.exe", application, 7); + + ASSERT_TRUE(command.has_value()); + EXPECT_TRUE(DecodedScript(*command).contains("/D=" + QDir::toNativeSeparators(QDir::cleanPath(installation.path())) + "'")); +} + +TEST_F(TestUpdateInstallation, linux_package_installs_through_pkexec_and_apt_get) +{ + const auto pkexec = FakeExecutable("pkexec"); + const auto aptGet = FakeExecutable("apt-get"); + UseOnlyFakeTools(); + + const auto command = DefaultUpdateCommand(InstallerPlatform::linuxX64, "/tmp/example-tool-v9.9.9-linux-x86_64.deb", "/usr/bin/example-tool", 1); + + ASSERT_TRUE(command.has_value()); + EXPECT_EQ(pkexec, command->program); + EXPECT_EQ((QStringList{ aptGet, "install", "-y", "/tmp/example-tool-v9.9.9-linux-x86_64.deb" }), command->arguments); + EXPECT_FALSE(command->exitsBeforeInstalling); +} + +TEST_F(TestUpdateInstallation, linux_package_without_pkexec_has_no_update_command) +{ + FakeExecutable("apt-get"); + UseOnlyFakeTools(); + + EXPECT_FALSE(DefaultUpdateCommand(InstallerPlatform::linuxX64, "/tmp/x.deb", "/usr/bin/example-tool", 1).has_value()); +} + +TEST_F(TestUpdateInstallation, linux_package_without_apt_get_has_no_update_command) +{ + FakeExecutable("pkexec"); + UseOnlyFakeTools(); + + EXPECT_FALSE(DefaultUpdateCommand(InstallerPlatform::linuxX64, "/tmp/x.deb", "/usr/bin/example-tool", 1).has_value()); +} diff --git a/ui/backend/qt/update/test/TestUpdateInstaller.cpp b/ui/backend/qt/update/test/TestUpdateInstaller.cpp new file mode 100644 index 0000000..cc4f434 --- /dev/null +++ b/ui/backend/qt/update/test/TestUpdateInstaller.cpp @@ -0,0 +1,162 @@ +#include "ui/backend/qt/update/UpdateInstaller.hpp" +#include "gtest/gtest.h" +#include +#include +#include +#include +#include + +namespace +{ + using namespace ui::backend::qt::update; + + class TestUpdateInstaller + : public testing::Test + { + public: + static void SetUpTestSuite() + { + static int argc{ 1 }; + static char name[]{ "support_test" }; + static char* argv[]{ name, nullptr }; + + if (QCoreApplication::instance() == nullptr) + application = std::make_unique(argc, argv); + } + + static void TearDownTestSuite() + { + application.reset(); + } + + TestUpdateInstaller() + { + QObject::connect(&installer, &UpdateInstaller::Installed, [this]() + { + ++installed; + }); + QObject::connect(&installer, &UpdateInstaller::HandedOver, [this]() + { + ++handedOver; + }); + QObject::connect(&installer, &UpdateInstaller::Failed, [this](const QString& reason) + { + failure = reason; + }); + } + + static InstallCommand Shell(const QString& script, bool exitsBeforeInstalling = false) + { + return InstallCommand{ "sh", { "-c", script }, exitsBeforeInstalling }; + } + + bool Finished() const + { + return installed > 0 || failure.has_value(); + } + + bool WaitUntilFinished(int timeoutMs = 5000) + { + QDeadlineTimer deadline{ timeoutMs }; + while (!Finished() && !deadline.hasExpired()) + QCoreApplication::processEvents(QEventLoop::AllEvents, 20); + QCoreApplication::processEvents(); + return Finished(); + } + + static inline std::unique_ptr application; + UpdateInstaller installer; + int installed{ 0 }; + int handedOver{ 0 }; + std::optional failure; + }; +} + +TEST_F(TestUpdateInstaller, reports_a_successful_installation) +{ + installer.Install(Shell("exit 0")); + + ASSERT_TRUE(WaitUntilFinished()); + EXPECT_EQ(1, installed); + EXPECT_FALSE(failure.has_value()); + EXPECT_FALSE(installer.IsInstalling()); +} + +TEST_F(TestUpdateInstaller, reports_a_dismissed_password_prompt) +{ + installer.Install(Shell("exit 126")); + + ASSERT_TRUE(WaitUntilFinished()); + EXPECT_EQ("the password prompt was dismissed", failure.value_or("")); + EXPECT_EQ(0, installed); +} + +TEST_F(TestUpdateInstaller, reports_an_account_that_may_not_install) +{ + installer.Install(Shell("exit 127")); + + ASSERT_TRUE(WaitUntilFinished()); + EXPECT_EQ("this account may not install software", failure.value_or("")); +} + +TEST_F(TestUpdateInstaller, reports_the_last_line_of_output_when_installation_fails) +{ + installer.Install(Shell("echo 'Reading package lists'; echo 'E: broken package'; exit 3")); + + ASSERT_TRUE(WaitUntilFinished()); + EXPECT_EQ("the installation failed (exit code 3): E: broken package", failure.value_or("")); +} + +TEST_F(TestUpdateInstaller, reports_the_exit_code_alone_when_the_installer_is_silent) +{ + installer.Install(Shell("exit 3")); + + ASSERT_TRUE(WaitUntilFinished()); + EXPECT_EQ("the installation failed (exit code 3)", failure.value_or("")); +} + +TEST_F(TestUpdateInstaller, reports_an_installer_that_crashes) +{ + installer.Install(Shell("kill -SEGV $$")); + + ASSERT_TRUE(WaitUntilFinished()); + EXPECT_EQ("sh stopped unexpectedly", failure.value_or("")); +} + +TEST_F(TestUpdateInstaller, reports_an_installer_that_cannot_start) +{ + installer.Install(InstallCommand{ "/nonexistent/example-installer", {}, false }); + + ASSERT_TRUE(WaitUntilFinished()); + ASSERT_TRUE(failure.has_value()); + EXPECT_TRUE(failure->startsWith("could not start /nonexistent/example-installer")) << failure->toStdString(); +} + +TEST_F(TestUpdateInstaller, hands_over_to_an_installer_that_runs_after_exit) +{ + installer.Install(Shell("exit 0", true)); + + EXPECT_EQ(1, handedOver); + EXPECT_FALSE(failure.has_value()); + EXPECT_FALSE(installer.IsInstalling()); +} + +TEST_F(TestUpdateInstaller, reports_a_detached_installer_that_cannot_start) +{ + installer.Install(InstallCommand{ "/nonexistent/example-installer", {}, true }); + + EXPECT_EQ(0, handedOver); + EXPECT_EQ("could not start /nonexistent/example-installer", failure.value_or("")); +} + +TEST_F(TestUpdateInstaller, ignores_a_second_installation_while_one_is_running) +{ + installer.Install(Shell("sleep 0.3; exit 0")); + ASSERT_TRUE(installer.IsInstalling()); + + installer.Install(Shell("exit 126")); + + ASSERT_TRUE(WaitUntilFinished()); + EXPECT_EQ(1, installed); + EXPECT_FALSE(failure.has_value()); +} diff --git a/ui/backend/qt/update/test/TestUpdateSession.cpp b/ui/backend/qt/update/test/TestUpdateSession.cpp new file mode 100644 index 0000000..63f0651 --- /dev/null +++ b/ui/backend/qt/update/test/TestUpdateSession.cpp @@ -0,0 +1,393 @@ +#include "ui/backend/qt/update/UpdateSession.hpp" +#include "gtest/gtest.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace ui::backend::qt::update; + + class TestUpdateSession + : public testing::Test + { + public: + static void SetUpTestSuite() + { + static int argc{ 1 }; + static char name[]{ "support_test" }; + static char* argv[]{ name, nullptr }; + + if (QCoreApplication::instance() == nullptr) + application = std::make_unique(argc, argv); + } + + static void TearDownTestSuite() + { + application.reset(); + } + + TestUpdateSession() + { + const auto path = QDir{ source.path() }.filePath("published.bin"); + QFile file{ path }; + EXPECT_TRUE(file.open(QIODevice::WriteOnly)); + file.write(payload); + + release.version = ReleaseVersion{ 9, 9, 9 }; + release.tag = "v9.9.9"; + release.pageUrl = QUrl{ "https://github.com/example/project/releases/tag/v9.9.9" }; + release.installer = InstallerAsset{ "example-tool-v9.9.9-linux-x86_64.deb", QUrl::fromLocalFile(path), payload.size(), QCryptographicHash::hash(payload, QCryptographicHash::Sha256) }; + } + + std::unique_ptr Session(std::optional command) + { + auto session = std::make_unique(downloads.path(), "example-tool/1.0.0", [this, command](const QString& installerPath) + { + requestedPaths.append(installerPath); + return command; + }); + QObject::connect(session.get(), &UpdateSession::Relaunch, [this]() + { + ++relaunches; + }); + QObject::connect(session.get(), &UpdateSession::RestartRequested, [this]() + { + ++restarts; + }); + return session; + } + + static InstallCommand Shell(const QString& script, bool exitsBeforeInstalling = false) + { + return InstallCommand{ "sh", { "-c", script }, exitsBeforeInstalling }; + } + + static bool WaitFor(const std::function& condition, int timeoutMs = 5000) + { + QDeadlineTimer deadline{ timeoutMs }; + while (!condition() && !deadline.hasExpired()) + QCoreApplication::processEvents(QEventLoop::AllEvents, 20); + return condition(); + } + + QString Downloaded() const + { + return QDir{ downloads.path() }.filePath("example-tool-v9.9.9-linux-x86_64.deb"); + } + + static inline std::unique_ptr application; + QTemporaryDir source; + QTemporaryDir downloads; + const QByteArray payload{ QByteArray{ "package " }.repeated(1024) }; + ReleaseInfo release; + QStringList requestedPaths; + int relaunches{ 0 }; + int restarts{ 0 }; + }; +} + +TEST_F(TestUpdateSession, offers_automatic_install_when_checksum_and_command_exist) +{ + auto session = Session(Shell("exit 0")); + session->Offer(release); + + EXPECT_EQ(UpdatePhase::available, session->State().phase); + EXPECT_TRUE(session->State().automaticInstall); + ASSERT_TRUE(session->State().release.has_value()); + EXPECT_EQ(release.version, session->State().release->version); +} + +TEST_F(TestUpdateSession, offers_only_a_download_without_a_checksum) +{ + release.installer->sha256.reset(); + auto session = Session(Shell("exit 0")); + session->Offer(release); + session->Install(); + + EXPECT_FALSE(session->State().automaticInstall); + EXPECT_EQ(UpdatePhase::available, session->State().phase); +} + +TEST_F(TestUpdateSession, offers_only_a_download_when_the_installation_cannot_update_itself) +{ + auto session = Session(std::nullopt); + session->Offer(release); + + EXPECT_FALSE(session->State().automaticInstall); +} + +TEST_F(TestUpdateSession, installs_the_verified_download_and_asks_for_a_relaunch) +{ + auto session = Session(Shell("exit 0")); + session->Offer(release); + session->Install(); + + EXPECT_EQ(UpdatePhase::downloading, session->State().phase); + ASSERT_TRUE(WaitFor([this]() + { + return relaunches > 0; + })); + EXPECT_EQ(UpdatePhase::installing, session->State().phase); + EXPECT_EQ(Downloaded(), requestedPaths.last()); + EXPECT_TRUE(QFile::exists(Downloaded())); + EXPECT_EQ(0, restarts); +} + +TEST_F(TestUpdateSession, hands_over_and_asks_for_a_restart_when_the_installer_runs_after_exit) +{ + auto session = Session(Shell("exit 0", true)); + session->Offer(release); + session->Install(); + + ASSERT_TRUE(WaitFor([this]() + { + return restarts > 0; + })); + EXPECT_EQ(UpdatePhase::installing, session->State().phase); + EXPECT_EQ(0, relaunches); +} + +TEST_F(TestUpdateSession, waits_for_the_bus_to_be_disconnected_before_installing) +{ + auto session = Session(Shell("exit 0")); + session->SetBlocked(true); + session->Offer(release); + session->Install(); + + ASSERT_TRUE(WaitFor([&session]() + { + return session->State().phase == UpdatePhase::ready; + })); + session->Install(); + EXPECT_EQ(UpdatePhase::ready, session->State().phase); + EXPECT_TRUE(session->State().blocked); + + session->SetBlocked(false); + session->Install(); + ASSERT_TRUE(WaitFor([this]() + { + return relaunches > 0; + })); +} + +TEST_F(TestUpdateSession, reports_a_dismissed_password_prompt) +{ + auto session = Session(Shell("exit 126")); + session->Offer(release); + session->Install(); + + ASSERT_TRUE(WaitFor([&session]() + { + return session->State().phase == UpdatePhase::failed; + })); + EXPECT_EQ("the password prompt was dismissed", session->State().failure); + EXPECT_EQ(0, relaunches); +} + +TEST_F(TestUpdateSession, reports_installer_output_on_failure) +{ + auto session = Session(Shell("echo 'dpkg: dependency problems' >&2; exit 100")); + session->Offer(release); + session->Install(); + + ASSERT_TRUE(WaitFor([&session]() + { + return session->State().phase == UpdatePhase::failed; + })); + EXPECT_EQ("the installation failed (exit code 100): dpkg: dependency problems", session->State().failure); +} + +TEST_F(TestUpdateSession, never_installs_a_download_that_fails_verification) +{ + release.installer->sha256 = QCryptographicHash::hash("tampered", QCryptographicHash::Sha256); + auto session = Session(Shell("exit 0")); + session->Offer(release); + session->Install(); + + ASSERT_TRUE(WaitFor([&session]() + { + return session->State().phase == UpdatePhase::failed; + })); + EXPECT_EQ("the download does not match the checksum published with the release", session->State().failure); + EXPECT_FALSE(QFile::exists(Downloaded())); + + session->Install(); + EXPECT_EQ(UpdatePhase::downloading, session->State().phase); + ASSERT_TRUE(WaitFor([&session]() + { + return session->State().phase == UpdatePhase::failed; + })); + EXPECT_EQ(0, relaunches); +} + +TEST_F(TestUpdateSession, cancel_returns_to_the_offer) +{ + auto session = Session(Shell("exit 0")); + session->Offer(release); + session->Install(); + session->Cancel(); + + EXPECT_EQ(UpdatePhase::available, session->State().phase); + EXPECT_FALSE(WaitFor([this]() + { + return relaunches > 0; + }, + 300)); + EXPECT_FALSE(QFile::exists(Downloaded())); +} + +TEST_F(TestUpdateSession, keeps_the_download_in_progress_when_a_newer_release_is_found) +{ + auto session = Session(Shell("exit 0")); + session->Offer(release); + session->SetBlocked(true); + session->Install(); + + auto newer = release; + newer.version = ReleaseVersion{ 10, 0, 0 }; + session->Offer(newer); + + ASSERT_TRUE(session->State().release.has_value()); + EXPECT_EQ(release.version, session->State().release->version); +} + +TEST_F(TestUpdateSession, dismiss_hides_the_offer) +{ + auto session = Session(Shell("exit 0")); + session->Offer(release); + session->Dismiss(); + + EXPECT_EQ(UpdatePhase::idle, session->State().phase); +} + +TEST_F(TestUpdateSession, offers_only_the_release_page_without_an_installer) +{ + release.installer.reset(); + auto session = Session(Shell("exit 0")); + session->Offer(release); + session->Install(); + + EXPECT_FALSE(session->State().automaticInstall); + EXPECT_EQ(UpdatePhase::available, session->State().phase); + EXPECT_TRUE(requestedPaths.isEmpty()); +} + +TEST_F(TestUpdateSession, install_without_an_offer_does_nothing) +{ + auto session = Session(Shell("exit 0")); + session->Install(); + session->Cancel(); + + EXPECT_EQ(UpdatePhase::idle, session->State().phase); +} + +TEST_F(TestUpdateSession, install_while_downloading_does_not_restart_the_download) +{ + auto session = Session(Shell("exit 0")); + session->SetBlocked(true); + session->Offer(release); + session->Install(); + session->Install(); + + EXPECT_EQ(UpdatePhase::downloading, session->State().phase); + ASSERT_TRUE(WaitFor([&session]() + { + return session->State().phase == UpdatePhase::ready; + })); +} + +TEST_F(TestUpdateSession, fails_when_the_installation_can_no_longer_update_itself) +{ + int calls{ 0 }; + UpdateSession session{ downloads.path(), "example-tool/1.0.0", [&calls](const QString&) -> std::optional + { + if (++calls == 1) + return Shell("exit 0"); + return std::nullopt; + } }; + session.Offer(release); + session.Install(); + + ASSERT_TRUE(WaitFor([&session]() + { + return session.State().phase == UpdatePhase::failed; + })); + EXPECT_EQ("this installation cannot be updated automatically", session.State().failure); +} + +TEST_F(TestUpdateSession, dismiss_during_download_cancels_it) +{ + auto session = Session(Shell("exit 0")); + session->Offer(release); + session->Install(); + session->Dismiss(); + + EXPECT_EQ(UpdatePhase::idle, session->State().phase); + EXPECT_FALSE(WaitFor([this]() + { + return relaunches > 0; + }, + 300)); + EXPECT_EQ(UpdatePhase::idle, session->State().phase); + EXPECT_FALSE(QFile::exists(Downloaded())); +} + +TEST_F(TestUpdateSession, dismiss_is_ignored_while_installing) +{ + auto session = Session(Shell("sleep 0.3; exit 0")); + session->Offer(release); + session->Install(); + ASSERT_TRUE(WaitFor([&session]() + { + return session->State().phase == UpdatePhase::installing; + })); + + session->Dismiss(); + session->Cancel(); + + EXPECT_EQ(UpdatePhase::installing, session->State().phase); + EXPECT_TRUE(WaitFor([this]() + { + return relaunches > 0; + })); +} + +TEST_F(TestUpdateSession, cancel_while_ready_returns_to_the_offer) +{ + auto session = Session(Shell("exit 0")); + session->SetBlocked(true); + session->Offer(release); + session->Install(); + ASSERT_TRUE(WaitFor([&session]() + { + return session->State().phase == UpdatePhase::ready; + })); + + session->Cancel(); + + EXPECT_EQ(UpdatePhase::available, session->State().phase); +} + +TEST_F(TestUpdateSession, reports_bus_changes_only_once) +{ + auto session = Session(Shell("exit 0")); + int changes{ 0 }; + QObject::connect(session.get(), &UpdateSession::StateChanged, [&changes](const UpdateState&) + { + ++changes; + }); + + session->SetBlocked(true); + session->SetBlocked(true); + session->SetBlocked(false); + session->SetBlocked(false); + + EXPECT_EQ(2, changes); + EXPECT_FALSE(session->State().blocked); +}