Merge branch 'feat/fwspacm-plugin-packages' into release-1.6.0

This commit is contained in:
BlackAngelTV committed 2026-09-28 22:08:56 +02:00
commit b6f51a76ff
29 files changed
+2107 -1047

No files matched your search

+615
View File
@@ -0,0 +1,615 @@
// Unit tests for PluginPackage: the .fwspacm format, and the bookkeeping that
// decides what an uninstall is allowed to delete.
//
// The archives are built here (both a stored and a deflated entry, so both
// compression methods are exercised), every file operation runs in a temporary
// directory, and the settings go to a temporary INI: no network, no real
// plugin, nothing of the user's is touched.
#include "plugin-package.h"
#include <QCryptographicHash>
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QSettings>
#include <QTemporaryDir>
#include <QTextStream>
#include <zlib.h>
#include <cassert>
namespace {
// --- Building archives -----------------------------------------------------
void writeU16(QByteArray* out, quint16 value) {
out->append(static_cast<char>(value & 0xff));
out->append(static_cast<char>((value >> 8) & 0xff));
}
void writeU32(QByteArray* out, quint32 value) {
out->append(static_cast<char>(value & 0xff));
out->append(static_cast<char>((value >> 8) & 0xff));
out->append(static_cast<char>((value >> 16) & 0xff));
out->append(static_cast<char>((value >> 24) & 0xff));
}
// A minimal ZIP writer, so the reader is tested against bytes rather than
// against a library that would agree with it by construction. `stored` writes
// the payload uncompressed (method 0), otherwise a deflate stream is required
// from the caller and written as-is (method 8).
class ZipBuilder {
public:
void addFile(const QString& name, const QByteArray& payload, bool stored) {
m_entries.append({name, payload, stored});
}
// Adds a directory entry, which a reader has to skip rather than treat as a
// file.
void addDirectory(const QString& name) {
m_entries.append({name, QByteArray(), true, true});
}
QByteArray build() const {
QByteArray out;
QList<int> offsets;
for (const auto& entry : m_entries) {
offsets.append(out.size());
const QByteArray name = entry.name.toUtf8();
const QByteArray payload =
entry.directory ? QByteArray() : entry.payload;
writeU32(&out, 0x04034b50);
writeU16(&out, 20); // version needed
writeU16(&out, 0); // flags
writeU16(&out, entry.directory ? 0 : (entry.stored ? 0 : 8));
writeU16(&out, 0); // mod time
writeU16(&out, 0); // mod date
writeU32(&out, 0); // crc (not verified on read)
writeU32(&out, static_cast<quint32>(payload.size()));
writeU32(&out, static_cast<quint32>(entry.rawSize()));
writeU16(&out, static_cast<quint16>(name.size()));
writeU16(&out, 0); // extra
out.append(name);
if (entry.stored || entry.directory) {
out.append(payload);
} else {
out.append(entry.deflated);
}
}
const int directoryOffset = out.size();
for (int i = 0; i < m_entries.size(); ++i) {
const auto& entry = m_entries[i];
const QByteArray name = entry.name.toUtf8();
const QByteArray payload = entry.directory ? QByteArray() : entry.payload;
const int compressedSize =
entry.directory ? 0
: (entry.stored ? payload.size() : entry.deflated.size());
writeU32(&out, 0x02014b50);
writeU16(&out, 20); // version made by
writeU16(&out, 20); // version needed
writeU16(&out, 0); // flags
writeU16(&out, entry.directory ? 0 : (entry.stored ? 0 : 8));
writeU16(&out, 0);
writeU16(&out, 0);
writeU32(&out, 0); // crc
writeU32(&out, static_cast<quint32>(compressedSize));
writeU32(&out, static_cast<quint32>(entry.directory ? 0 : payload.size()));
writeU16(&out, static_cast<quint16>(name.size()));
writeU16(&out, 0); // extra
writeU16(&out, 0); // comment
writeU16(&out, 0); // disk
writeU16(&out, 0); // internal attributes
writeU32(&out, 0); // external attributes
writeU32(&out, static_cast<quint32>(offsets[i]));
out.append(name);
}
const int directorySize = out.size() - directoryOffset;
writeU32(&out, 0x06054b50);
writeU16(&out, 0);
writeU16(&out, 0);
writeU16(&out, static_cast<quint16>(m_entries.size()));
writeU16(&out, static_cast<quint16>(m_entries.size()));
writeU32(&out, static_cast<quint32>(directorySize));
writeU32(&out, static_cast<quint32>(directoryOffset));
writeU16(&out, 0); // comment
return out;
}
// A deflate stream for a payload, produced by zlib the same way a real ZIP
// writer would. Raw deflate, not the zlib-wrapped stream compress2() emits:
// a ZIP entry has no zlib header and no trailing checksum, which is why the
// reader in zip-archive.cpp calls inflateInit2() with a negative window.
static QByteArray rawDeflate(const QByteArray& payload) {
z_stream stream{};
if (deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, 8,
Z_DEFAULT_STRATEGY) != Z_OK) {
return {};
}
stream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(payload.constData()));
stream.avail_in = static_cast<uInt>(payload.size());
QByteArray out;
char buffer[16384];
int status = Z_OK;
do {
stream.next_out = reinterpret_cast<Bytef*>(buffer);
stream.avail_out = sizeof(buffer);
status = deflate(&stream, Z_FINISH);
assert(status == Z_OK || status == Z_STREAM_END);
out.append(buffer, static_cast<int>(sizeof(buffer)) - static_cast<int>(stream.avail_out));
} while (status != Z_STREAM_END);
deflateEnd(&stream);
return out;
}
private:
struct Entry {
QString name;
QByteArray payload;
bool stored = true;
bool directory = false;
QByteArray deflated;
Entry() = default;
Entry(QString entryName, QByteArray entryPayload, bool isStored)
: name(std::move(entryName)),
payload(std::move(entryPayload)),
stored(isStored) {
if (!stored) deflated = rawDeflate(payload);
}
Entry(QString entryName, QByteArray, bool, bool isDirectory)
: name(std::move(entryName)), stored(true), directory(isDirectory) {}
int rawSize() const { return static_cast<int>(payload.size()); }
};
QList<Entry> m_entries;
};
QByteArray sha256Of(const QByteArray& payload) {
return QCryptographicHash::hash(payload, QCryptographicHash::Sha256).toHex();
}
// Writes an archive and closes it, so the file is complete on disk before any
// test reads it back.
QString writeArchive(const QString& path, const ZipBuilder& zip) {
QFile file(path);
assert(file.open(QIODevice::WriteOnly));
file.write(zip.build());
file.close();
return path;
}
// A package with a manifest and a library, written to `path`.
QString writePackage(const QString& path, const QByteArray& library,
const QByteArray& manifest, bool deflated = true) {
ZipBuilder zip;
zip.addFile(QStringLiteral("plugin.json"), manifest, false);
zip.addFile(QStringLiteral("libsample.so"), library, !deflated);
return writeArchive(path, zip);
}
QByteArray manifestJson(const QByteArray& library, bool withChecksum = true) {
QByteArray json = "{\"format\": 1, \"id\": \"sample\", \"name\": \"Sample\", "
"\"kind\": \"provider\", \"version\": \"1.0.0\", "
"\"library\": \"libsample.so\"";
if (withChecksum) {
json += ", \"sha256\": \"" + sha256Of(library) + "\"";
}
json += "}";
return json;
}
const QByteArray kLibrary = QByteArray("\x7f"
"ELF-fake-shared-library-payload");
// --- Tests -----------------------------------------------------------------
// A well-formed package is read whole: manifest fields, library bytes, and the
// name the library is written under.
static void testPackageIsRead() {
QTemporaryDir dir;
const QString path = writePackage(dir.path() + "/sample.fwspacm", kLibrary,
manifestJson(kLibrary));
QString error;
const PluginPackage::Contents contents = PluginPackage::read(path, &error);
assert(error.isEmpty());
assert(contents.manifest.id == QStringLiteral("sample"));
assert(contents.manifest.name == QStringLiteral("Sample"));
assert(contents.manifest.version == QStringLiteral("1.0.0"));
assert(contents.manifest.kind == QStringLiteral("provider"));
assert(contents.library == kLibrary);
assert(contents.libraryName == QStringLiteral("libsample.so"));
}
// A deflated entry and a stored one must give the same bytes back: the format
// allows both, and a plugin author picks whichever their zip tool defaults to.
static void testBothCompressionMethodsAreRead() {
QTemporaryDir dir;
QString error;
const PluginPackage::Contents deflated = PluginPackage::read(
writePackage(dir.path() + "/deflated.fwspacm", kLibrary, manifestJson(kLibrary), true),
&error);
assert(error.isEmpty());
assert(deflated.library == kLibrary);
const PluginPackage::Contents stored = PluginPackage::read(
writePackage(dir.path() + "/stored.fwspacm", kLibrary, manifestJson(kLibrary), false),
&error);
assert(error.isEmpty());
assert(stored.library == kLibrary);
}
// A library whose bytes do not match the announced checksum never reaches the
// plugin directory: that check is the only guarantee about *which* code runs.
static void testChecksumMismatchIsRefused() {
QTemporaryDir dir;
// The manifest announces the checksum of other bytes than the ones zipped.
const QByteArray other = QByteArray("some other library");
QByteArray manifest = "{\"format\": 1, \"id\": \"sample\", "
"\"library\": \"libsample.so\", \"sha256\": \"" +
sha256Of(other) + "\"}";
QString error;
const PluginPackage::Contents contents = PluginPackage::read(
writePackage(dir.path() + "/sample.fwspacm", kLibrary, manifest), &error);
assert(contents.library.isEmpty());
assert(error.contains(QStringLiteral("Somme de contrôle")));
}
// Without a checksum the package still installs: the manifest is free to omit
// it, and refusing would make the format unusable for a local build.
static void testChecksumIsOptional() {
QTemporaryDir dir;
QString error;
const PluginPackage::Contents contents = PluginPackage::read(
writePackage(dir.path() + "/sample.fwspacm", kLibrary, manifestJson(kLibrary, false)),
&error);
assert(error.isEmpty());
assert(contents.library == kLibrary);
}
// Every way a package can be unusable must be refused with a reason, and never
// half-installed.
static void testInvalidPackagesAreRefused() {
QTemporaryDir dir;
QString error;
// Not a ZIP at all.
const QString plain = dir.path() + "/plain.fwspacm";
{
QFile file(plain);
assert(file.open(QIODevice::WriteOnly));
file.write("this is not an archive");
file.close();
}
assert(PluginPackage::read(plain, &error).library.isEmpty());
assert(!error.isEmpty());
// A ZIP with no manifest: the library is right there, and it is still
// refused, because a package without a manifest says nothing about what it
// would install.
{
ZipBuilder zip;
zip.addFile(QStringLiteral("libsample.so"), kLibrary, true);
const QString path = writeArchive(dir.path() + "/nomanifest.fwspacm", zip);
assert(PluginPackage::read(path, &error).library.isEmpty());
assert(error.contains(QStringLiteral("plugin.json")));
}
// A manifest that is not JSON, and one that is JSON but not an object.
assert(PluginPackage::read(
writePackage(dir.path() + "/badjson.fwspacm", kLibrary, "{ not json"),
&error).library.isEmpty());
assert(!error.isEmpty());
assert(PluginPackage::read(
writePackage(dir.path() + "/array.fwspacm", kLibrary, "[]"), &error)
.library.isEmpty());
assert(!error.isEmpty());
// A manifest of another version: read as-is would mean reading a package as
// something it is not.
assert(PluginPackage::read(
writePackage(dir.path() + "/format2.fwspacm", kLibrary,
"{\"format\": 2, \"id\": \"sample\", "
"\"library\": \"libsample.so\"}"),
&error).library.isEmpty());
assert(error.contains(QStringLiteral("Format de paquet")));
// A manifest with no id.
assert(PluginPackage::read(
writePackage(dir.path() + "/noid.fwspacm", kLibrary,
"{\"format\": 1, \"library\": \"libsample.so\"}"),
&error).library.isEmpty());
assert(error.contains(QStringLiteral("id")));
// An id holding a slash would need quoting as a settings key.
assert(PluginPackage::read(
writePackage(dir.path() + "/badid.fwspacm", kLibrary,
"{\"format\": 1, \"id\": \"a/b\", "
"\"library\": \"libsample.so\"}"),
&error).library.isEmpty());
assert(error.contains(QStringLiteral("Identifiant refusé")));
// A manifest naming a library the archive does not contain.
assert(PluginPackage::read(
writePackage(dir.path() + "/nolib.fwspacm", kLibrary,
"{\"format\": 1, \"id\": \"sample\", "
"\"library\": \"libabsent.so\"}"),
&error).library.isEmpty());
assert(!error.isEmpty());
// A manifest naming a path instead of a file name: the package would be
// writing outside the directory it is installed into.
assert(PluginPackage::read(
writePackage(dir.path() + "/escape.fwspacm", kLibrary,
"{\"format\": 1, \"id\": \"sample\", "
"\"library\": \"../libsample.so\"}"),
&error).library.isEmpty());
assert(!error.isEmpty());
// An archive with no shared library at all. The manifest names none, so the
// reader has to find it by suffix and finds nothing.
{
ZipBuilder zip;
zip.addFile(QStringLiteral("plugin.json"),
"{\"format\": 1, \"id\": \"sample\", \"name\": \"Sample\"}", false);
zip.addFile(QStringLiteral("readme.txt"), "nothing to load", true);
const QString path = writeArchive(dir.path() + "/nolibrary.fwspacm", zip);
assert(PluginPackage::read(path, &error).library.isEmpty());
assert(error.contains(QStringLiteral("bibliothèque partagée")));
}
// An empty library is refused: writing a zero-byte file into the scanned
// directory would fail later, at load time, with a worse message.
assert(PluginPackage::read(
writePackage(dir.path() + "/emptylib.fwspacm", QByteArray(),
manifestJson(QByteArray(), false)),
&error).library.isEmpty());
assert(error.contains(QStringLiteral("vide")));
}
// With no "library" in the manifest, the archive's single shared library is
// the one to install; with several, the package has to say which, because
// picking one silently is how the wrong file gets installed.
static void testLibraryIsFoundBySuffix() {
ZipArchive archive;
QString error;
assert(archive.openData(
[] {
ZipBuilder zip;
zip.addFile(QStringLiteral("readme.txt"), "docs", true);
zip.addFile(QStringLiteral("libonly.so"), kLibrary, true);
return zip.build();
}(),
&error));
assert(error.isEmpty());
PluginPackage::Manifest manifest;
manifest.id = QStringLiteral("sample");
const QString found = PluginPackage::targetFileName(manifest, archive, &error);
assert(error.isEmpty());
assert(found == QStringLiteral("libonly.so"));
// Two candidates: refused rather than guessed.
ZipArchive ambiguous;
assert(ambiguous.openData(
[] {
ZipBuilder zip;
zip.addFile(QStringLiteral("libone.so"), kLibrary, true);
zip.addFile(QStringLiteral("libtwo.so"), kLibrary, true);
return zip.build();
}(),
&error));
assert(PluginPackage::targetFileName(manifest, ambiguous, &error).isEmpty());
assert(error.contains(QStringLiteral("library")));
// A directory entry is not a library, whatever it is called.
ZipArchive onlyDir;
assert(onlyDir.openData(
[] {
ZipBuilder zip;
zip.addDirectory(QStringLiteral("libdir.so/"));
return zip.build();
}(),
&error));
assert(PluginPackage::targetFileName(manifest, onlyDir, &error).isEmpty());
assert(!error.isEmpty());
}
// Entry names that would escape the directory they are written to.
static void testUnsafeEntryNamesAreRefused() {
assert(ZipArchive::isSafeEntryName(QStringLiteral("libsample.so")));
assert(ZipArchive::isSafeEntryName(QStringLiteral("subdir/libsample.so")));
assert(!ZipArchive::isSafeEntryName(QString()));
assert(!ZipArchive::isSafeEntryName(QStringLiteral("/etc/passwd")));
assert(!ZipArchive::isSafeEntryName(QStringLiteral("../escape.so")));
assert(!ZipArchive::isSafeEntryName(QStringLiteral("subdir/../../escape.so")));
assert(!ZipArchive::isSafeEntryName(QStringLiteral("\\windows\\system32")));
assert(!ZipArchive::isSafeEntryName(QStringLiteral("C:/windows")));
}
// Installing writes the library in the install directory and records it;
// removing takes back exactly that file, and refuses anything else.
static void testInstallAndRemove() {
QTemporaryDir dir;
PluginPackage packages;
const QString pluginsDir = dir.path() + "/plugins";
packages.setInstallDirectory(pluginsDir);
const QString path = writePackage(dir.path() + "/sample.fwspacm", kLibrary,
manifestJson(kLibrary));
QString id;
bool success = false;
QObject::connect(&packages, &PluginPackage::installFinished, &packages,
[&](const QString& installedId, bool ok, const QString&) {
id = installedId;
success = ok;
});
// Nothing installed yet: a removal must fail rather than delete anything.
// A separate flag, since removeFinished is the signal a removal reports on.
bool removed = true;
QObject::connect(&packages, &PluginPackage::removeFinished, &packages,
[&](const QString&, bool ok, const QString&) { removed = ok; });
packages.remove(QStringLiteral("sample"));
assert(!removed);
packages.install(path);
assert(success);
assert(id == QStringLiteral("sample"));
assert(packages.isInstalled(QStringLiteral("sample")));
const QString written = pluginsDir + "/libsample.so";
assert(packages.installedPath(QStringLiteral("sample")) == written);
QFile file(written);
assert(file.open(QIODevice::ReadOnly));
assert(file.readAll() == kLibrary);
file.close();
// The id shows up in the list the page renders.
assert(packages.installedIds() == QStringList{QStringLiteral("sample")});
success = false;
removed = false;
packages.remove(QStringLiteral("sample"));
assert(removed);
assert(!QFile::exists(written));
assert(!packages.isInstalled(QStringLiteral("sample")));
assert(packages.installedIds().isEmpty());
}
// A file the user copied in by hand is not the installer's to delete.
static void testUninstallOnlyRemovesWhatItInstalled() {
QTemporaryDir dir;
PluginPackage packages;
packages.setInstallDirectory(dir.path() + "/plugins");
assert(QDir().mkpath(dir.path() + "/plugins"));
// A library present in the directory, with no install recorded for it.
const QString handPlaced = dir.path() + "/plugins/libmanual.so";
QFile manual(handPlaced);
assert(manual.open(QIODevice::WriteOnly));
manual.write(kLibrary);
manual.close();
bool success = true;
QObject::connect(&packages, &PluginPackage::removeFinished, &packages,
[&](const QString&, bool ok, const QString&) { success = ok; });
packages.remove(QStringLiteral("manual"));
assert(!success);
assert(QFile::exists(handPlaced));
}
// A file deleted behind the installer's back is not installed any more, even
// though the setting still names it: the state follows the disk.
static void testMissingFileCountsAsNotInstalled() {
QTemporaryDir dir;
PluginPackage packages;
packages.setInstallDirectory(dir.path() + "/plugins");
QSettings settings;
settings.setValue("packages/installed/gone", dir.path() + "/plugins/libgone.so");
settings.sync();
assert(!packages.isInstalled(QStringLiteral("gone")));
assert(packages.installedPath(QStringLiteral("gone")).isEmpty());
// A recorded but missing library is not listed either, so the page never
// offers to remove something that is not there.
assert(!packages.installedIds().contains(QStringLiteral("gone")));
}
// Reinstalling a package overwrites the previous library, in place.
static void testReinstallOverwrites() {
QTemporaryDir dir;
PluginPackage packages;
packages.setInstallDirectory(dir.path() + "/plugins");
bool success = false;
QObject::connect(&packages, &PluginPackage::installFinished, &packages,
[&](const QString&, bool ok, const QString&) { success = ok; });
packages.install(writePackage(dir.path() + "/v1.fwspacm", kLibrary,
manifestJson(kLibrary)));
assert(success);
const QByteArray newer = kLibrary + "-v2";
packages.install(writePackage(dir.path() + "/v2.fwspacm", newer,
manifestJson(newer)));
assert(success);
QFile file(dir.path() + "/plugins/libsample.so");
assert(file.open(QIODevice::ReadOnly));
assert(file.readAll() == newer);
}
// A file that is not a package is refused before it is even opened.
static void testNonPackageIsRefused() {
assert(PluginPackage::isPackagePath(QStringLiteral("/tmp/sample.fwspacm")));
assert(PluginPackage::isPackagePath(QStringLiteral("/tmp/SAMPLE.FWSPACM")));
assert(!PluginPackage::isPackagePath(QStringLiteral("/tmp/sample.fwspacm.zip")));
assert(!PluginPackage::isPackagePath(QStringLiteral("/tmp/sample.so")));
assert(!PluginPackage::isPackagePath(QString()));
QTemporaryDir dir;
PluginPackage packages;
packages.setInstallDirectory(dir.path() + "/plugins");
bool success = true;
QString message;
QObject::connect(&packages, &PluginPackage::installFinished, &packages,
[&](const QString&, bool ok, const QString& detail) {
success = ok;
message = detail;
});
// Written under a .fwspacm name, so the extension is not what refuses it:
// the content is.
const QString path = writePackage(dir.path() + "/bogus.fwspacm", kLibrary,
QByteArray("{\"format\": 9, \"id\": \"x\"}"));
packages.install(path);
assert(!success);
assert(!message.isEmpty());
assert(!packages.installedIds().contains(QStringLiteral("x")));
}
} // namespace
int main(int argc, char* argv[]) {
QCoreApplication app(argc, argv);
app.setOrganizationName(QStringLiteral("PacManagerTests"));
app.setApplicationName(QStringLiteral("plugin-package-test"));
// Settings and the install directory go to a temporary INI, so the recorded
// installs of these tests never reach the user's real configuration.
QTemporaryDir settingsDir;
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, settingsDir.path());
testPackageIsRead();
testBothCompressionMethodsAreRead();
testChecksumMismatchIsRefused();
testChecksumIsOptional();
testInvalidPackagesAreRefused();
testLibraryIsFoundBySuffix();
testUnsafeEntryNamesAreRefused();
testInstallAndRemove();
testUninstallOnlyRemovesWhatItInstalled();
testMissingFileCountsAsNotInstalled();
testReinstallOverwrites();
testNonPackageIsRefused();
QTextStream(stdout) << "All plugin-package tests passed." << Qt::endl;
return 0;
}
-181
View File
@@ -1,181 +0,0 @@
// Unit tests for PluginShop: the catalogue format the shop accepts, and the
// bookkeeping that decides what an uninstall is allowed to delete. Parsing is
// pure logic and the file half runs against a temporary directory, so no network
// access and no real plugin is involved.
#include "plugin-shop.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QSettings>
#include <QString>
#include <QTemporaryDir>
#include <cassert>
#include <iostream>
// The full field set, in both kinds, with an entry relying on the URL for the
// file name.
static void testCatalogIsParsed() {
const QByteArray json = R"({
"catalog": 1,
"plugins": [
{
"id": "apt",
"name": "APT",
"kind": "provider",
"version": "1.0.0",
"author": "FWS",
"description": "Gestionnaire de paquets Debian",
"url": "https://example.org/plugins/libapt-provider.so",
"sha256": "ABCDEF0123",
"file": "libapt-provider.so"
},
{
"id": "gnome-tweaks",
"name": "GNOME Tweaks",
"kind": "addon",
"url": "https://example.org/plugins/libgnome-tweaks.so"
}
]
})";
QString error;
const std::vector<PluginShop::CatalogEntry> entries = PluginShop::parseCatalog(json, &error);
assert(error.isEmpty());
assert(entries.size() == 2);
assert(entries[0].id == "apt");
assert(entries[0].kind == "provider");
assert(entries[0].fileName == "libapt-provider.so");
// Checksums are compared case-insensitively, so they are stored lowercased.
assert(entries[0].sha256 == "abcdef0123");
assert(entries[1].id == "gnome-tweaks");
assert(entries[1].kind == "addon");
// No "file": the name is taken from the URL when the plugin is installed.
assert(entries[1].fileName.isEmpty());
assert(entries[1].sha256.isEmpty());
}
// A document that is not a catalogue must be refused as a whole, so the shop
// never shows half a catalogue.
static void testInvalidDocumentsAreRejected() {
QString error;
assert(PluginShop::parseCatalog("{ not json", &error).empty());
assert(!error.isEmpty());
error.clear();
assert(PluginShop::parseCatalog("[]", &error).empty());
assert(!error.isEmpty());
error.clear();
assert(PluginShop::parseCatalog("{\"catalog\": 1}", &error).empty());
assert(!error.isEmpty());
}
// Entries that cannot be installed are skipped one by one: one broken line in
// the catalogue does not hide the plugins that are fine.
static void testIncompleteEntriesAreSkipped() {
const QByteArray json = R"({
"plugins": [
{"id": "no-name", "url": "https://example.org/a.so"},
{"id": "no-url", "name": "Sans URL"},
{"name": "Sans identifiant", "url": "https://example.org/c.so"},
"not an object",
{"id": "ok", "name": "Complet", "url": "https://example.org/d.so",
"kind": "autre chose"}
]
})";
QString error;
const std::vector<PluginShop::CatalogEntry> entries = PluginShop::parseCatalog(json, &error);
assert(error.isEmpty());
assert(entries.size() == 1);
assert(entries[0].id == "ok");
// An unknown kind is dropped rather than guessed: the loaded library
// declares the real one.
assert(entries[0].kind.isEmpty());
}
// The shop only removes what it installed itself.
static void testUninstallOnlyRemovesWhatItInstalled() {
QTemporaryDir dir;
PluginShop shop;
shop.setInstallDirectory(dir.path() + "/plugins");
bool finished = false;
bool success = true;
QObject::connect(&shop, &PluginShop::removeFinished, &shop,
[&](const QString&, bool ok, const QString&) {
finished = true;
success = ok;
});
// Unknown entry: a removal must fail instead of deleting anything.
assert(!shop.isInstalled("apt"));
shop.remove("apt");
assert(finished && !success);
// A plugin the shop installed: recorded path plus a file on disk. The key
// is the one the shop writes (documented in doc/plugin-shop.md).
const QString pluginsDir = dir.path() + "/plugins";
assert(QDir().mkpath(pluginsDir));
const QString path = pluginsDir + "/libapt-provider.so";
QFile file(path);
assert(file.open(QIODevice::WriteOnly));
file.write("not a real shared library");
file.close();
QSettings settings;
settings.setValue("shop/installed/apt", path);
settings.sync();
assert(shop.isInstalled("apt"));
assert(shop.installedPath("apt") == path);
success = false;
shop.remove("apt");
assert(finished && success);
assert(!QFile::exists(path));
assert(!shop.isInstalled("apt"));
}
// A file deleted by hand is not installed any more, even when the shop still
// remembers it: the state follows the disk.
static void testMissingFileCountsAsNotInstalled() {
QTemporaryDir dir;
PluginShop shop;
shop.setInstallDirectory(dir.path() + "/plugins");
QSettings settings;
settings.setValue("shop/installed/gone", dir.path() + "/plugins/libgone.so");
settings.sync();
assert(!shop.isInstalled("gone"));
assert(shop.installedPath("gone").isEmpty());
}
int main(int argc, char** argv) {
// The tests must not read or write the user's PacManager settings: an INI
// file of their own, in a temporary directory, stands in for them.
QTemporaryDir settingsDir;
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, settingsDir.path());
QCoreApplication app(argc, argv);
app.setOrganizationName("PacManagerTests");
app.setApplicationName("plugin-shop-test");
testCatalogIsParsed();
testInvalidDocumentsAreRejected();
testIncompleteEntriesAreSkipped();
testUninstallOnlyRemovesWhatItInstalled();
testMissingFileCountsAsNotInstalled();
std::cout << "All plugin-shop tests passed." << std::endl;
return 0;
}