Files
FWS-PacManage/tests/app-settings.test.cpp
BlackAngelTV f4aa661b54 fix(logging): keep Qt's platform chatter out of the journal
Opening a dialog under Wayland made Qt write a burst of qt.qpa
warnings into the application journal — the text-input focus one,
repeated at every prompt — where the user can do nothing with them:
they describe the display server, not the application. Those
categories stay on stderr from now on, next to everything else, while
what the application logs (its own categories, and a bare qCWarning)
keeps going to the journal.
2026-10-09 19:22:19 +02:00

345 lines
14 KiB
C++

#include "app-settings.h"
#include "log-manager.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QLoggingCategory>
#include <QObject>
#include <QSettings>
#include <QString>
#include <QTemporaryDir>
#include <cassert>
#include <iostream>
// The preferences model, on its own and without a display: what a preference
// reads back, what it signals, and the two decisions that are pure functions
// (how long a block lasts, when it is in force).
namespace {
// Counts one signal so a test can assert it fired exactly once per real change.
// QSignalSpy would need Qt Test, which this target deliberately does not link.
//
// It is a QObject used as the connection's context: the settings object is a
// singleton that outlives every test, so without that the counter would be
// dangling by the time the *next* test changed a value.
class SignalCounter : public QObject {
public:
explicit SignalCounter(AppSettings* prefs) {
QObject::connect(prefs, &AppSettings::logDirectoryChanged, this,
[this](const QString&) { ++m_count; });
QObject::connect(prefs, &AppSettings::logMaxBytesChanged, this,
[this](qint64) { ++m_count; });
QObject::connect(prefs, &AppSettings::dragDropEnabledChanged, this,
[this](bool) { ++m_count; });
QObject::connect(prefs, &AppSettings::languageChanged, this,
[this](const QString&) { ++m_count; });
QObject::connect(prefs, &AppSettings::autoUpdateCheckEnabledChanged, this,
[this](bool) { ++m_count; });
QObject::connect(prefs, &AppSettings::updateBlockChanged, this,
[this] { ++m_count; });
}
int count() const { return m_count; }
private:
int m_count = 0;
};
// Every test starts from a known settings file: the model is a singleton, so
// what one test writes would otherwise leak into the next.
void resetSettings() {
QSettings().clear();
}
void testLogDirectoryDefaultsAndSanitizes() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
// No preference saved: the journal goes to the user's own config tree.
assert(prefs.logDirectory() == AppSettings::defaultLogDirectory());
assert(!prefs.logDirectory().isEmpty());
// A home-relative path is what a user types; nothing else in the app would
// expand it for them.
assert(AppSettings::sanitizeLogDirectory(QStringLiteral("~/journaux")) ==
QDir::homePath() + QStringLiteral("/journaux"));
assert(AppSettings::sanitizeLogDirectory(QStringLiteral("~")) ==
QDir::homePath());
// An empty or blank directory is refused rather than leaving the app with
// nowhere to log.
assert(AppSettings::sanitizeLogDirectory(QString()).isEmpty() == false);
assert(AppSettings::sanitizeLogDirectory(QStringLiteral(" ")) ==
AppSettings::defaultLogDirectory());
SignalCounter counter(&prefs);
const QString wanted = QDir::homePath() + QStringLiteral("/journaux-pacmgr");
prefs.setLogDirectory(wanted);
assert(prefs.logDirectory() == wanted);
assert(counter.count() == 1);
// Setting the same value again says nothing new.
prefs.setLogDirectory(wanted);
assert(counter.count() == 1);
// Back to the default the key is dropped, not pinned: a later change of
// XDG_CONFIG_HOME must follow the user.
prefs.setLogDirectory(AppSettings::defaultLogDirectory());
assert(prefs.logDirectory() == AppSettings::defaultLogDirectory());
assert(!QSettings().contains(QStringLiteral("settings/logDirectory")));
}
void testLogSizeCap() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
// No cap until the user picks one.
assert(prefs.logMaxBytes() == 0);
// A cap that would rotate on every line is raised to the floor rather than
// honoured; a negative cap means "no cap".
assert(AppSettings::sanitizeLogMaxBytes(-1) == 0);
assert(AppSettings::sanitizeLogMaxBytes(0) == 0);
assert(AppSettings::sanitizeLogMaxBytes(1024) == 64 * 1024);
assert(AppSettings::sanitizeLogMaxBytes(5LL * 1024 * 1024) == 5LL * 1024 * 1024);
SignalCounter counter(&prefs);
prefs.setLogMaxBytes(5LL * 1024 * 1024);
assert(prefs.logMaxBytes() == 5LL * 1024 * 1024);
assert(counter.count() == 1);
// The value stored is the one that will be read back, not what was asked for.
prefs.setLogMaxBytes(10);
assert(prefs.logMaxBytes() == 64 * 1024);
}
void testDragDropIsOnByDefault() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
// Dropping a .flatpakref on the window is the quickest way to install one:
// turning it off has to be a deliberate act.
assert(prefs.dragDropEnabled());
SignalCounter counter(&prefs);
prefs.setDragDropEnabled(false);
assert(!prefs.dragDropEnabled());
assert(counter.count() == 1);
prefs.setDragDropEnabled(false);
assert(counter.count() == 1);
prefs.setDragDropEnabled(true);
assert(prefs.dragDropEnabled());
}
void testLanguage() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
// No preference: follow the desktop, which the model records as "system".
assert(prefs.language() == QStringLiteral("system"));
// An unknown code must not be stored: the interface would then be in a
// language nothing can translate. An empty one is not unknown, it is unset.
assert(AppSettings::sanitizeLanguage(QString()).isEmpty() == false);
assert(AppSettings::sanitizeLanguage(QString()) == QStringLiteral("system"));
assert(AppSettings::sanitizeLanguage(QStringLiteral("klingon")) == QStringLiteral("fr"));
assert(AppSettings::sanitizeLanguage(QStringLiteral("EN")) == QStringLiteral("en"));
assert(AppSettings::sanitizeLanguage(QStringLiteral("system")) == QStringLiteral("system"));
SignalCounter counter(&prefs);
prefs.setLanguage(QStringLiteral("en"));
assert(prefs.language() == QStringLiteral("en"));
assert(counter.count() == 1);
prefs.setLanguage(QStringLiteral("en"));
assert(counter.count() == 1);
assert(AppSettings::knownLanguages().contains(QStringLiteral("fr")));
assert(AppSettings::knownLanguages().contains(QStringLiteral("en")));
}
void testUpdateBlockPolicyIsPure() {
const QDateTime now(QDate(2026, 9, 28), QTime(12, 0));
// Hours add up; "until cancelled" has no end and says so with an invalid date.
assert(AppSettings::blockTarget(now, 1) == now.addSecs(3600));
assert(AppSettings::blockTarget(now, 24 * 7) == now.addSecs(7 * 24 * 3600));
assert(!AppSettings::blockTarget(now, 0).isValid());
assert(!AppSettings::blockTarget(now, -5).isValid());
// Not blocked, blocked for a while, blocked for ever.
assert(!AppSettings::isBlocked(now, false, QDateTime()));
assert(AppSettings::isBlocked(now, false, now.addSecs(3600)));
assert(!AppSettings::isBlocked(now, false, now.addSecs(-1)));
assert(AppSettings::isBlocked(now, true, QDateTime()));
// The instant the block ends, it is over: a snooze that outlived itself
// must not keep the user from ever checking again.
assert(!AppSettings::isBlocked(now.addSecs(3600), false, now.addSecs(3600)));
// What it means, for the screen: nothing when no block is in force.
assert(AppSettings::blockDescription(false, QDateTime(), now).isEmpty());
assert(!AppSettings::blockDescription(true, QDateTime(), now).isEmpty());
assert(!AppSettings::blockDescription(false, now.addSecs(3600), now).isEmpty());
assert(!AppSettings::blockDescription(false, now.addSecs(180), now).isEmpty());
assert(AppSettings::blockDescription(false, now.addSecs(-1), now).isEmpty());
}
void testUpdateBlockIsPersistedAndCleared() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
assert(!prefs.autoUpdateCheckEnabled() == false); // checked once a day by default
assert(!prefs.updatesBlocked());
SignalCounter counter(&prefs);
prefs.blockUpdatesFor(1);
assert(prefs.updatesBlocked());
assert(!prefs.updatesBlockedIndefinitely());
assert(prefs.updateBlockedUntil().isValid());
assert(counter.count() == 1);
// The block survives being read back: a new process sees the same block.
AppSettings fresh;
assert(fresh.updatesBlocked());
assert(fresh.updateBlockedUntil() == prefs.updateBlockedUntil());
// "Until cancelled" keeps no deadline and still blocks.
prefs.blockUpdatesFor(0);
assert(prefs.updatesBlocked());
assert(prefs.updatesBlockedIndefinitely());
assert(!prefs.updateBlockedUntil().isValid());
prefs.unblockUpdates();
assert(!prefs.updatesBlocked());
assert(!prefs.updatesBlockedIndefinitely());
assert(!prefs.updateBlockedUntil().isValid());
}
void testAutomaticCheckCanBeTurnedOff() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
SignalCounter counter(&prefs);
prefs.setAutoUpdateCheckEnabled(false);
assert(!prefs.autoUpdateCheckEnabled());
assert(counter.count() == 1);
// Turning it back on is not blocked by a block still in force: the two
// settings are independent.
prefs.setAutoUpdateCheckEnabled(true);
assert(prefs.autoUpdateCheckEnabled());
assert(counter.count() == 2);
}
// The journal is the one thing the preferences change on disk, so it is
// exercised for real: it must land in the chosen directory, carry the previous
// one along, and rotate once the cap is reached.
void testJournalMovesAndRotates() {
resetSettings();
AppSettings& prefs = AppSettings::instance();
LogManager& journal = LogManager::instance();
// Cleared before the directory is chosen: a leftover from a previous run
// would be carried over by the move and read as this run's.
const QString first = QDir::homePath() + QStringLiteral("/journal-a");
QFile::remove(first + QStringLiteral("/operations.log"));
prefs.setLogDirectory(first);
journal.logEvent(QStringLiteral("test"), QStringLiteral("premier"));
assert(QFile::exists(first + QStringLiteral("/operations.log")));
assert(journal.filePath() == first + QStringLiteral("/operations.log"));
// Switching directory carries the journal along: the user did not ask to
// lose the record of what the app did.
const QString second = QDir::homePath() + QStringLiteral("/journal-b");
QFile::remove(second + QStringLiteral("/operations.log"));
prefs.setLogDirectory(second);
assert(QFile::exists(second + QStringLiteral("/operations.log")));
assert(!QFile::exists(first + QStringLiteral("/operations.log")));
assert(journal.readFile().contains(QStringLiteral("premier")));
// The cap is a real ceiling, and the journal that came before is kept.
prefs.setLogMaxBytes(64 * 1024);
for (int i = 0; i < 2000; ++i) {
journal.logEvent(QStringLiteral("test"),
QStringLiteral("ligne de remplissage numéro %1").arg(i));
}
assert(QFile::exists(second + QStringLiteral("/operations.log.1")));
assert(journal.currentSizeBytes() <= 64 * 1024);
// Back to no cap, and the log goes on growing.
prefs.setLogMaxBytes(0);
const qint64 before = journal.currentSizeBytes();
journal.logEvent(QStringLiteral("test"), QStringLiteral("dernière"));
assert(journal.currentSizeBytes() > before);
}
// Qt's platform plugins narrate the display server, not the application: the
// Wayland text-input warning, for one, repeats for every dialog the user opens,
// and a journal full of it is unreadable. Those categories stay on stderr; what
// the application logs — its own categories, and the "default" one a bare
// qCWarning carries — still lands in the journal.
void testPlatformChatterStaysOutOfTheJournal() {
// The decision itself first, so the test says which side a category is on
// even when nothing is written.
assert(LogManager::journalsQtCategory(QStringLiteral("default")));
assert(LogManager::journalsQtCategory(QStringLiteral("pacmgr.update")));
assert(LogManager::journalsQtCategory(QStringLiteral("qt.sql")));
assert(!LogManager::journalsQtCategory(QStringLiteral("qt.qpa.wayland.textinput")));
assert(!LogManager::journalsQtCategory(QStringLiteral("qt.qpa.xcb")));
resetSettings();
AppSettings& prefs = AppSettings::instance();
const QString dir = QDir::homePath() + QStringLiteral("/journal-c");
QFile::remove(dir + QStringLiteral("/operations.log"));
prefs.setLogDirectory(dir);
prefs.setLogMaxBytes(0);
LogManager::installQtMessageHandler();
LogManager& journal = LogManager::instance();
// An event the application writes, then the warning Qt's Wayland plugin
// repeats: the first must be in the journal, the second must not.
journal.logEvent(QStringLiteral("ui"), QStringLiteral("mot de passe fourni"));
qCWarning(QLoggingCategory("qt.qpa.wayland.textinput"))
<< "Trying to disable 0x1 but 0x2 is focused";
qCWarning(QLoggingCategory("pacmgr.update")) << "une alerte de l'application";
const QString content = journal.readFile();
assert(content.contains(QStringLiteral("mot de passe fourni")));
assert(content.contains(QStringLiteral("une alerte de l'application")));
assert(!content.contains(QStringLiteral("Trying to disable")));
}
} // namespace
int main(int argc, char* argv[]) {
// The model reads and writes QSettings, so the whole run has to happen
// against a throwaway configuration.
QTemporaryDir home;
assert(home.isValid());
qputenv("HOME", home.path().toLocal8Bit());
qputenv("XDG_CONFIG_HOME", QDir(home.path()).filePath("config").toLocal8Bit());
qputenv("XDG_DATA_HOME", QDir(home.path()).filePath("data").toLocal8Bit());
QCoreApplication app(argc, argv);
app.setApplicationName("PacManagerSettingsTest");
app.setOrganizationName("FWSTest");
// The model is a singleton: one format, one place, decided before the first
// QSettings is built.
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
QDir(home.path()).filePath("settings"));
testLogDirectoryDefaultsAndSanitizes();
testLogSizeCap();
testDragDropIsOnByDefault();
testLanguage();
testUpdateBlockPolicyIsPure();
testUpdateBlockIsPersistedAndCleared();
testAutomaticCheckCanBeTurnedOff();
testJournalMovesAndRotates();
testPlatformChatterStaysOutOfTheJournal();
std::cout << "app-settings: all tests passed" << std::endl;
return 0;
}