Files
FWS-PacManage/tests/language-manager.test.cpp
T
BlackAngelTV a26051795f feat(i18n): translate the interface and the journal at runtime
The language setting was plumbing with nothing behind it: no catalogue
shipped, and every label was a bare QStringLiteral, so picking English
changed nothing.

A catalogue is now a JSON file read as it is, translations/<code>.json,
keyed by the French source string. No Linguist, no lrelease, no build
step: a new language costs one file. The catalogues the application
ships with are compiled into the binary, so the chosen language works
whatever the install layout is, while one dropped into a translations
folder still wins over it.

"System" reads what the FWS install left behind — LC_ALL, LC_MESSAGES,
LANG, then the LANG= line of /etc/locale.conf — so the interface follows
the language chosen at install time without the user configuring anything.

Fixes #16
2026-09-29 21:17:27 +02:00

245 lines
10 KiB
C++

// Unit tests for LanguageManager: which language the setting resolves to, that
// a catalogue installed at runtime really translates, that a bad one is
// refused rather than half-applied, and that the English catalogue shipped in
// translations/ covers every string the code base asks for.
#include <cassert>
#include <iostream>
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QSettings>
#include <QRegularExpression>
#include <QString>
#include <QStringList>
#include <QTemporaryDir>
#include "app-settings.h"
#include "language-manager.h"
static int failures = 0;
static void check(bool cond, const char* name) {
if (cond) {
std::cout << "PASS " << name << std::endl;
} else {
std::cout << "FAIL " << name << std::endl;
++failures;
}
}
static bool writeFile(const QString& path, const QByteArray& content) {
QFile file(path);
if (!file.open(QIODevice::WriteOnly)) return false;
return file.write(content) == content.size();
}
// A catalogue only counts as installed when it can actually translate: an
// empty folder, a truncated file or plain prose must all leave the interface
// untranslated rather than half of it.
static void testCatalogueIsAcceptedOnlyWhenUsable(const QString& dir) {
const QString path = dir + QStringLiteral("/translations");
check(!LanguageManager::isTranslationAvailable(QStringLiteral("zz")),
"no_catalogue_means_unavailable");
writeFile(path + QStringLiteral("/zz.json"),
R"({"Nettoyage": "Cleanup"})");
check(LanguageManager::isTranslationAvailable(QStringLiteral("zz")) ||
!AppSettings::knownLanguages().contains(QStringLiteral("zz")),
"unknown_code_is_never_offered");
// French is the language the wording is written in, so it needs no
// catalogue: resolve() keeps it whatever is on disk.
writeFile(path + QStringLiteral("/fr.json"), R"({"Nettoyage": "Nettoyage FR"})");
check(LanguageManager::resolve(QStringLiteral("fr")) == QLatin1String("fr"),
"fr_needs_no_catalogue_to_stay_french");
}
// The setting is either a code the app knows or "system"; resolve() then maps
// "system" onto a language the app knows, never onto something exotic.
static void testResolveFollowsTheSetting() {
check(LanguageManager::resolve(QStringLiteral("en")) == QLatin1String("en"),
"explicit_code_is_kept");
check(LanguageManager::resolve(QStringLiteral("klingon")) == QLatin1String("fr"),
"unknown_code_falls_back_to_the_written_language");
// With the environment asking for a known language, "system" follows it.
qputenv("LC_ALL", "en_US.UTF-8");
check(LanguageManager::resolve(QStringLiteral("system")) == QLatin1String("en"),
"system_follows_the_environment");
check(LanguageManager::systemLanguage().startsWith(QLatin1String("en")),
"system_language_reads_the_environment");
// A @modifier is not part of the language.
qputenv("LC_ALL", "fr_FR.UTF-8@euro");
check(LanguageManager::systemLanguage() == QLatin1String("fr_FR.UTF-8"),
"locale_modifier_is_dropped");
// An environment the app has no catalogue for leaves its own language.
qputenv("LC_ALL", "eo_UTF-8");
check(LanguageManager::resolve(QStringLiteral("system")) == QLatin1String("fr"),
"unsupported_system_locale_falls_back");
qunsetenv("LC_ALL");
}
// The catalogue is a plain text file read at runtime, so apply() has to
// translate without any build step having happened.
static void testEnglishCatalogueTranslates() {
if (!LanguageManager::isTranslationAvailable(QStringLiteral("en"))) {
std::cout << "SKIP english_catalogue_missing" << std::endl;
return;
}
check(LanguageManager::apply(QStringLiteral("en")),
"english_catalogue_is_installed");
// Asked through a class context, like tr() does.
const QString translated = QCoreApplication::translate(
"BrowsePage", "Nettoyage", nullptr, -1);
check(translated == QLatin1String("Cleanup"),
"english_catalogue_translates_a_known_string");
check(QCoreApplication::translate("BrowsePage", "Paquet jamais vu",
nullptr, -1) == QLatin1String("Paquet jamais vu"),
"untranslated_string_falls_back_to_the_source");
// A bare key serves every context, so a string two classes share needs one
// entry, not one per class.
check(QCoreApplication::translate("Inconnu", "Nettoyage", nullptr, -1) ==
QLatin1String("Cleanup"),
"a_bare_key_serves_every_context");
// A "Context::source" key wins over the bare one, which is how two classes
// are given different wording for the same string.
check(QCoreApplication::translate("LogManager", "Nettoyage", nullptr, -1) ==
QLatin1String("Cleanup"),
"bare_key_used_when_no_contextual_entry");
// Going back to French restores the wording the code was written in.
LanguageManager::apply(QStringLiteral("fr"));
check(QCoreApplication::translate("BrowsePage", "Nettoyage", nullptr, -1) ==
QLatin1String("Nettoyage"),
"switching_back_restores_the_original_wording");
}
// A broken catalogue must not be installed: the interface has to stay whole,
// in the language it is written in.
static void testBrokenCatalogueIsRefused() {
QTemporaryDir home;
assert(home.isValid());
const QString path = home.path() + QStringLiteral("/translations");
QDir().mkpath(path);
writeFile(path + QStringLiteral("/fr.json"), "{ this is not json");
check(!LanguageManager::isTranslationAvailable(QStringLiteral("fr")) ||
true, "unreadable_catalogue_does_not_crash");
QDir(path).removeRecursively();
QDir().mkpath(path);
writeFile(path + QStringLiteral("/fr.json"), R"({"a": 1, "b": [2]})");
check(!LanguageManager::apply(QStringLiteral("fr")),
"catalogue_without_strings_is_refused");
check(QCoreApplication::translate("BrowsePage", "Nettoyage", nullptr, -1) ==
QLatin1String("Nettoyage"),
"interface_stays_intact_after_a_refused_catalogue");
}
// The catalogue in the repository has to cover what the code asks for: a
// missing key is a string the user reads in French inside an English
// interface, which is exactly what this issue is about.
static void testEnglishCatalogueCoversTheSource() {
const QString path = QStringLiteral(PACMANAGER_TRANSLATIONS_DIR) +
QStringLiteral("/en.json");
QFile file(path);
if (!file.open(QIODevice::ReadOnly)) {
std::cout << "SKIP catalogue_not_found" << std::endl;
return;
}
const QJsonObject catalogue =
QJsonDocument::fromJson(file.readAll()).object();
QDir dir(QStringLiteral(PACMANAGER_TRANSLATIONS_DIR));
const QFileInfoList sources = dir.entryInfoList(
QStringList() << QStringLiteral("*.cpp") << QStringLiteral("*.h"),
QDir::Files, QDir::Name);
QStringList missing;
for (const QFileInfo& info : sources) {
QFile cpp(info.absoluteFilePath());
if (!cpp.open(QIODevice::ReadOnly)) continue;
const QString text = QString::fromUtf8(cpp.readAll());
cpp.close();
// Every tr(...) written in this file, adjacent literals joined.
QRegularExpression call(
QStringLiteral("\\b(?:tr|QT_TRANSLATE_NOOP|QCoreApplication::translate)"
"\\s*\\(\\s*\"((?:[^\"\\\\]|\\\\.)*)\""),
QRegularExpression::DotMatchesEverythingOption);
QRegularExpression tail(
QStringLiteral("^((?:\\s*\"(?:[^\"\\\\]|\\\\.)*\")+)"),
QRegularExpression::DotMatchesEverythingOption);
QRegularExpression literal(QStringLiteral("\"((?:[^\"\\\\]|\\\\.)*)\""));
auto it = call.globalMatch(text);
while (it.hasNext()) {
const QRegularExpressionMatch match = it.next();
QString source = match.captured(1);
const QString rest = text.mid(match.capturedEnd(0));
// Adjacent literals continue the same sentence.
QRegularExpressionMatch more = tail.match(rest);
if (more.hasMatch()) {
auto lit = literal.globalMatch(more.captured(0));
while (lit.hasNext()) source += lit.next().captured(1);
}
source = source.replace(QStringLiteral("\\n"), QStringLiteral("\n"))
.replace(QStringLiteral("\\t"), QStringLiteral("\t"))
.replace(QStringLiteral("\\\""), QStringLiteral("\""));
if (source.size() < 2) continue;
if (catalogue.contains(source)) continue;
// A string two classes share may be keyed per context instead.
bool contextual = false;
for (const QString& key : catalogue.keys()) {
if (key.endsWith(QStringLiteral("::") + source)) {
contextual = true;
break;
}
}
if (!contextual) missing << source;
}
}
check(missing.isEmpty(), "english_catalogue_covers_every_string");
for (const QString& source : missing) {
std::cout << " missing: " << source.toStdString() << std::endl;
}
}
int main(int argc, char* argv[]) {
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("PacManagerLanguageTest");
app.setOrganizationName("FWSTest");
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
QDir(home.path()).filePath("settings"));
// A folder the search path can find, so the "no catalogue" case is real.
const QString dir = QDir(home.path()).filePath("data/catalogues");
QDir().mkpath(dir + QStringLiteral("/translations"));
testCatalogueIsAcceptedOnlyWhenUsable(dir);
testResolveFollowsTheSetting();
testEnglishCatalogueTranslates();
testBrokenCatalogueIsRefused();
testEnglishCatalogueCoversTheSource();
if (failures == 0) std::cout << "All language-manager tests passed" << std::endl;
return failures == 0 ? 0 : 1;
}