Restore in-scope files missing from the merge and scope-aware CMakeLists

The merge from story/release-validation-scope only carried files that
existed at the common base or on that branch. In-scope files added on
story/release-2-cleanup after the base (per-module unit-test dirs, the
Release 2 driver and rpmbuild script) were missing, breaking
ADD_SUBDIRECTORY(unit-test) references.

- Restore the 33 missing in-scope files from story/release-2-cleanup.
- Lts/Common/CMakeLists.txt and LtsUtilsGui/CMakeLists.txt: take the
  story/release-2-cleanup versions (the validation versions still
  reference out-of-scope subdirectories: httq, LtsRestClient,
  LtsWebSocket, ConnectDialog, StyleManager).
This commit is contained in:
berrux-dev committed 2026-11-16 19:04:24 +01:00
1 parent cfe15c72c4
commit 262fd226f9
35 files changed
+6856 -16

No files matched your search

@@ -0,0 +1,25 @@
#
# Unit tests for the NGLLogger module.
# One test executable per module, each registered with ctest.
#
if (NOT BUILD_TESTING)
return()
endif()
# --- NGLLogger: bootstrap + logger lookup (Log4Qt-independent; works in
# --- the Log4Qt-less (stub) build).
# --- MurmurHash2 has no export macro and the tree builds with hidden
# --- visibility, so its symbols are not exported from libNGLLogger - the
# --- module source is compiled directly into the test (same pattern as the
# --- LogView test in TetraIF/unit-test).
if (TARGET NGLLogger)
ADD_EXECUTABLE(ngllogger_unit_test
ngllogger_unit_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../MurmurHash2.cpp)
TARGET_LINK_LIBRARIES(ngllogger_unit_test
NGLLogger
Qt6::Core
Qt6::Test
)
ADD_TEST(NAME ngllogger_unit_test COMMAND $<TARGET_FILE:ngllogger_unit_test>)
endif()
@@ -0,0 +1,163 @@
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <NGLLogger/NGLLogger.h>
#include <NGLLogger/MurmurHash2.h>
#include <QtTest/QTest>
#include <QtTest/QTestEventLoop>
class ngllogger_unit_test : public QObject
{
Q_OBJECT
private slots:
void initTestCase()
{
// Create the root logger once for the whole test process.
// Works in both the Log4Qt build and the Log4Qt-less (stub) build.
NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx.props", false);
}
void A_LoggerHierarchyHelperSameNameReturnsSameInstance()
{
#ifndef HAVE_LOG4QT
// The instance cache (m_loggermap) is only populated in Log4Qt builds
// (NGLLogger constructor); the stub build creates a fresh logger per call.
QSKIP("requires the Log4Qt build (instance caching is a Log4Qt feature)");
#else
auto &a = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui");
auto &b = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui");
QCOMPARE(&a, &b); // same instance for same name
#endif
}
void B_LoggerHierarchyHelperDifferentNamesReturnDifferentInstances()
{
auto &a = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui.AES");
auto &b = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui.Dataview");
QVERIFY(&a != &b); // different instances for different names
}
void C_LoggerNameRoundTrip()
{
auto &a = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui");
QCOMPARE(a.getLoggerName(), std::string("Gui"));
auto &b = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui.AES");
QCOMPARE(b.getLoggerName(), std::string("Gui.AES"));
}
void D_StdStringAndCharOverloadsReturnSameInstance()
{
#ifndef HAVE_LOG4QT
QSKIP("requires the Log4Qt build (instance caching is a Log4Qt feature)");
#else
auto &a = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui");
auto &b = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(std::string("Gui"));
QCOMPARE(&a, &b);
auto &c = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui.AES");
auto &d = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(std::string("Gui.AES"));
QCOMPARE(&c, &d);
#endif
}
void E_NoSpaceFlag()
{
auto &a = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui");
QVERIFY(a.noSpace()); // default true
a.setNoSpace(false);
QVERIFY(!a.noSpace());
a.setNoSpace(true);
QVERIFY(a.noSpace());
}
void F_LogLevelEnumOrdering()
{
QVERIFY(NGL::LogLevel::Trace < NGL::LogLevel::Debug);
QVERIFY(NGL::LogLevel::Debug < NGL::LogLevel::Info);
QVERIFY(NGL::LogLevel::Info < NGL::LogLevel::Warning);
QVERIFY(NGL::LogLevel::Warning < NGL::LogLevel::Error);
QVERIFY(NGL::LogLevel::Error < NGL::LogLevel::Fatal);
}
void G_PerLevelHelpersAgreeWithGeneric()
{
auto &a = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui");
QCOMPARE(a.isTraceEnabled(), a.isLevelEnabled(NGL::LogLevel::Trace));
QCOMPARE(a.isDebugEnabled(), a.isLevelEnabled(NGL::LogLevel::Debug));
QCOMPARE(a.isInfoEnabled(), a.isLevelEnabled(NGL::LogLevel::Info));
QCOMPARE(a.isWarningEnabled(), a.isLevelEnabled(NGL::LogLevel::Warning));
QCOMPARE(a.isErrorEnabled(), a.isLevelEnabled(NGL::LogLevel::Error));
QCOMPARE(a.isFatalEnabled(), a.isLevelEnabled(NGL::LogLevel::Fatal));
}
void H_LevelEnabledIsUpwardClosed()
{
// For any two levels lo < hi: if lo enabled then hi enabled; if hi disabled then lo
// disabled. This holds regardless of the actual enabled level.
const auto levels = {
NGL::LogLevel::Trace, NGL::LogLevel::Debug, NGL::LogLevel::Info,
NGL::LogLevel::Warning, NGL::LogLevel::Error, NGL::LogLevel::Fatal
};
auto &a = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Gui");
for (auto lo : levels)
for (auto hi : levels)
{
if (lo < hi)
{
if (a.isLevelEnabled(lo))
QVERIFY(a.isLevelEnabled(hi));
if (!a.isLevelEnabled(hi))
QVERIFY(!a.isLevelEnabled(lo));
}
}
}
void I_BootstrapCreateAndGet()
{
auto &a = NGL::NGLLoggerBootstrap::getNGLRootLogger();
auto &b = NGL::NGLLoggerBootstrap::getNGLRootLogger();
QCOMPARE(&a, &b); // get returns the created root logger
// create with ignore-already-created returns the existing root logger
auto &c = NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx.props", true);
QCOMPARE(&a, &c);
}
void J_AlreadyCreatedError()
{
// Re-creating without ignore-already-created throws AlreadyCreatedError (root was
// created in initTestCase)
bool threw = false;
try
{
NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx.props", false);
}
catch (const NGL::NGLLogger::AlreadyCreatedError &e)
{
Q_UNUSED(e);
threw = true;
}
QVERIFY(threw);
}
void K_NotCreatedError()
{
// Not tested here: requires a fresh process without prior bootstrap, and initTestCase
// already created the root logger
QSKIP("requires fresh process without prior bootstrap");
}
void L_MurmurHash2Determinism()
{
QCOMPARE(NGL::MurmurHash2("", 0, 0), 0u); // empty, seed 0
QCOMPARE(NGL::MurmurHash2("hello", 5, 0), NGL::MurmurHash2("hello", 5, 0));
}
void M_MurmurHash2Distinctness()
{
QVERIFY(NGL::MurmurHash2("hello", 5, 0) != NGL::MurmurHash2("hello", 5, 1)); //
// different seed
QVERIFY(NGL::MurmurHash2("abc", 3, 0) != NGL::MurmurHash2("abd", 3, 0)); //
// different input
}
};
QTEST_MAIN(ngllogger_unit_test)
#include "ngllogger_unit_test.moc"
@@ -0,0 +1,18 @@
#
# Unit tests for the WMS_Interface module.
# One test executable per module, each registered with ctest.
#
if (NOT BUILD_TESTING)
return()
endif()
# --- WMS_Interface: JSON/QVariantMap serialization roundtrips
if (TARGET wms_json_ds)
ADD_EXECUTABLE(wms_json_ds_unit_test wms_json_ds_unit_test.cpp)
TARGET_LINK_LIBRARIES(wms_json_ds_unit_test
wms_json_ds
Qt6::Core
Qt6::Test
)
ADD_TEST(NAME wms_json_ds_unit_test COMMAND $<TARGET_FILE:wms_json_ds_unit_test>)
endif()
@@ -0,0 +1,598 @@
//
// Unit tests for the wms_json_ds module (Z/src/WMS_Interface): offline
// JSON / QVariantMap serialization and deserialization of the WMS<->ECC
// data structures (equipment types, exercises, player info, registration,
// unregister, equipment requirements) plus the JSON key helpers.
//
#include <WMS_Interface/IWMS2ECC.h>
#include <WMS_Interface/json_keys.h>
#include <WMS_Interface/wms_ecc_equipRequirements.h>
#include <WMS_Interface/wms_ecc_equipmenttypes.h>
#include <WMS_Interface/wms_ecc_exercises.h>
#include <WMS_Interface/wms_ecc_playerInfo.h>
#include <WMS_Interface/wms_ecc_registration.h>
#include <WMS_Interface/wms_ecc_unregister.h>
#include <QtCore/QByteArray>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtTest/QTest>
class wms_json_ds_unit_test : public QObject
{
Q_OBJECT
private slots:
void jsonKeysSanity();
void int2PlayerAssignState();
void equipmentTypeJsonRoundtrip();
void equipmentTypesJsonAllRoundtrip();
void equipmentTypesVariantAllRoundtrip();
void exerciseJsonRoundtrip();
void exercisesJsonAllRoundtrip();
void exerciseVariantRoundtrip();
void exercisesVariantAllRoundtrip();
void playerInfoJsonRoundtrip();
void playerInfosJsonAllRoundtrip();
void playerInfoVariantRoundtrip();
void playerInfosVariantAllRoundtrip();
void registrationJsonFullRoundtrip();
void registrationJsonOptionalFields();
void registrationVariantRoundtrip();
void unregisterJsonRoundtrip();
void unregisterVariantRoundtrip();
void equipRequirementsJsonRoundtrip();
void equipRequirementsVariantRoundtrip();
};
void wms_json_ds_unit_test::jsonKeysSanity()
{
// json_keys.h: inline key-name helpers used by the WMS<->ECC JSON protocol
QCOMPARE(WebSocketInterface::JsonKeys::EXERCISE_ID(), QStringLiteral("exerciseId"));
QCOMPARE(WebSocketInterface::JsonKeys::DATA_MODIFICATION(), QStringLiteral("dataModification"));
QCOMPARE(WebSocketInterface::JsonKeys::PARTICIPANT_ID(), QStringLiteral("participantId"));
QCOMPARE(WebSocketInterface::JsonKeys::REGISTRATION_RETURN_VALUE(), QStringLiteral("registrationReturnValue"));
QCOMPARE(WebSocketInterface::JsonKeys::EQUIPMENT_TYPES_REQUEST(), QStringLiteral("equipmentTypesRequest"));
QCOMPARE(WebSocketInterface::JsonKeys::EQUIPMENT_TYPES_REPLY(), QStringLiteral("equipmentTypesReply"));
QCOMPARE(WebSocketInterface::JsonKeys::EXERCISES_REQUEST(), QStringLiteral("exercisesRequest"));
QCOMPARE(WebSocketInterface::JsonKeys::EXERCISES_REPLY(), QStringLiteral("exercisesReply"));
QCOMPARE(WebSocketInterface::JsonKeys::PARTICIPANTS_REQUEST(), QStringLiteral("participantsRequest"));
QCOMPARE(WebSocketInterface::JsonKeys::PARTICIPANTS_REPLY(), QStringLiteral("participantsReply"));
QCOMPARE(WebSocketInterface::JsonKeys::PARTICIPANT_REGISTER_IN_EXCON_REQUEST(), QStringLiteral("participantRegisterInEXCONRequest"));
QCOMPARE(WebSocketInterface::JsonKeys::PARTICIPANT_REGISTER_IN_EXCON_REPLY(), QStringLiteral("participantRegisterInEXCONReply"));
}
void wms_json_ds_unit_test::int2PlayerAssignState()
{
// IWMS2ECC::int2PlayerAssignState passes through all defined values.
// (Invalid values hit Q_ASSERT(false) in the implementation, so they are
// deliberately not exercised here.)
QCOMPARE(IWMS2ECC::int2PlayerAssignState(-2), IWMS2ECC::UNDEFINED);
QCOMPARE(IWMS2ECC::int2PlayerAssignState(-1), IWMS2ECC::NOT_ASSIGNED);
QCOMPARE(IWMS2ECC::int2PlayerAssignState(0), IWMS2ECC::ASSIGNED);
QCOMPARE(IWMS2ECC::int2PlayerAssignState(1), IWMS2ECC::HANDOUT_EXCON);
QCOMPARE(IWMS2ECC::int2PlayerAssignState(2), IWMS2ECC::HANDOUT_WMS);
QCOMPARE(IWMS2ECC::int2PlayerAssignState(3), IWMS2ECC::HANDOUT_EXCON_OVERRULED_WMS);
}
void wms_json_ds_unit_test::equipmentTypeJsonRoundtrip()
{
IWMS2ECC::EquipmentType et;
et.name = QStringLiteral("Panzergreaner");
et.id = 1001;
et.specialType = 7;
et.minEquipNo = 10;
et.maxEquipNo = 99;
et.taVulnerabilityModelId = 5;
et.taPlayerTypeId = 6;
et.deletedInWMS = true;
const QJsonObject obj = EquipmentTypes::toJson(et);
QCOMPARE(obj[QLatin1String("id")].toInt(), 1001);
QCOMPARE(obj[QLatin1String("taVulnerabilityModelId")].toInt(), 5);
const IWMS2ECC::EquipmentType back = EquipmentTypes::fromJson(obj);
QCOMPARE(back.id, et.id);
QCOMPARE(back.name, et.name);
QCOMPARE(back.minEquipNo, et.minEquipNo);
QCOMPARE(back.maxEquipNo, et.maxEquipNo);
QCOMPARE(back.specialType, et.specialType);
QCOMPARE(back.taVulnerabilityModelId, et.taVulnerabilityModelId);
QCOMPARE(back.taPlayerTypeId, et.taPlayerTypeId);
QCOMPARE(back.deletedInWMS, et.deletedInWMS);
}
void wms_json_ds_unit_test::equipmentTypesJsonAllRoundtrip()
{
IWMS2ECC::equipTypeMap map;
IWMS2ECC::EquipmentType a;
a.name = QStringLiteral("typeA");
a.id = 1001;
a.minEquipNo = 1;
a.maxEquipNo = 20;
IWMS2ECC::EquipmentType b;
b.name = QStringLiteral("typeB");
b.id = 1002;
b.minEquipNo = 21;
b.maxEquipNo = 40;
b.deletedInWMS = true;
map.insert(a.id, a);
map.insert(b.id, b);
EquipmentTypes src;
src.setEquipmentTypes(map);
src.setOk(true);
// Full wire-format roundtrip: serialize to a JSON string and parse it back.
const QByteArray wire = QJsonDocument(src.toJsonAll()).toJson(QJsonDocument::Compact);
QJsonParseError perr;
const QJsonDocument doc = QJsonDocument::fromJson(wire, &perr);
QCOMPARE(perr.error, QJsonParseError::NoError);
QCOMPARE(static_cast<int>(doc[QLatin1String("etMap")].toArray().size()), 2);
const EquipmentTypes back = EquipmentTypes::fromJsonAll(doc.object());
QVERIFY(back.getOk());
QCOMPARE(static_cast<int>(back.getEquipmentTypes().size()), 2);
QCOMPARE(back.getEquipmentTypes().value(1001).name, a.name);
QCOMPARE(back.getEquipmentTypes().value(1002).name, b.name);
QCOMPARE(back.getEquipmentTypes().value(1002).deletedInWMS, true);
QCOMPARE(back.getEquipmentTypes().value(1001).minEquipNo, 1);
QCOMPARE(back.getEquipmentTypes().value(1002).maxEquipNo, 40);
}
void wms_json_ds_unit_test::equipmentTypesVariantAllRoundtrip()
{
IWMS2ECC::equipTypeMap map;
IWMS2ECC::EquipmentType a;
a.name = QStringLiteral("typeA");
a.id = 2001;
a.specialType = 3;
a.minEquipNo = 5;
a.maxEquipNo = 15;
map.insert(a.id, a);
EquipmentTypes src;
src.setEquipmentTypes(map);
src.setOk(true);
const QVariantMap v = src.toVariantMapAll();
QCOMPARE(v[QLatin1String("ok")].toBool(), true);
QVERIFY(v.contains(QLatin1String("etMap")));
const EquipmentTypes back = EquipmentTypes::fromVariantMapAll(v);
QVERIFY(back.getOk());
QCOMPARE(static_cast<int>(back.getEquipmentTypes().size()), 1);
QCOMPARE(back.getEquipmentTypes().value(2001).name, a.name);
QCOMPARE(back.getEquipmentTypes().value(2001).specialType, 3);
QCOMPARE(back.getEquipmentTypes().value(2001).minEquipNo, 5);
QCOMPARE(back.getEquipmentTypes().value(2001).maxEquipNo, 15);
// NOTE: the single-object QVariant conversion (toVariantMap) does not carry
// taVulnerabilityModelId / taPlayerTypeId, so the map conversion loses them;
// the JSON conversion above does preserve both.
}
void wms_json_ds_unit_test::exerciseJsonRoundtrip()
{
IWMS2ECC::Exercise ex;
ex.id = 42;
ex.actExercise = 1;
ex.start = 1700000000;
ex.end = 1700003600;
ex.name = QStringLiteral("Wintermanöver");
ex.stateAsString = QStringLiteral("running");
EXCON::Exercises src;
src.setExercise(ex);
src.setOk(true);
const QJsonObject obj = src.toJson(ex);
QCOMPARE(obj[QLatin1String("id")].toInt(), 42);
QCOMPARE(obj[QLatin1String("state")].toString(), ex.stateAsString);
const IWMS2ECC::Exercise back = EXCON::Exercises::fromJson(obj);
QCOMPARE(back.id, ex.id);
QCOMPARE(back.actExercise, ex.actExercise);
QCOMPARE(back.start, ex.start);
QCOMPARE(back.end, ex.end);
QCOMPARE(back.name, ex.name);
QCOMPARE(back.stateAsString, ex.stateAsString);
}
void wms_json_ds_unit_test::exercisesJsonAllRoundtrip()
{
IWMS2ECC::exerciseMap map;
IWMS2ECC::Exercise a;
a.id = 1;
a.name = QStringLiteral("ExA");
a.start = 1000;
a.end = 2000;
IWMS2ECC::Exercise b;
b.id = 2;
b.name = QStringLiteral("ExB");
b.actExercise = 1;
b.start = 3000;
b.end = 4000;
b.stateAsString = QStringLiteral("stopped");
map.insert(a.id, a);
map.insert(b.id, b);
EXCON::Exercises src;
src.setExercises(map);
src.setOk(true);
const QByteArray wire = QJsonDocument(src.toJsonAll()).toJson(QJsonDocument::Compact);
QJsonParseError perr;
const QJsonDocument doc = QJsonDocument::fromJson(wire, &perr);
QCOMPARE(perr.error, QJsonParseError::NoError);
QCOMPARE(static_cast<int>(doc[QLatin1String("exMap")].toArray().size()), 2);
const EXCON::Exercises back = EXCON::Exercises::fromJsonAll(doc.object());
QVERIFY(back.getOk());
QCOMPARE(static_cast<int>(back.getExercises().size()), 2);
QCOMPARE(back.getExercises().value(1).name, a.name);
QCOMPARE(back.getExercises().value(2).name, b.name);
QCOMPARE(back.getExercises().value(2).actExercise, 1);
QCOMPARE(back.getExercises().value(2).stateAsString, b.stateAsString);
QCOMPARE(back.getExercises().value(1).start, 1000);
QCOMPARE(back.getExercises().value(2).end, 4000);
}
void wms_json_ds_unit_test::exerciseVariantRoundtrip()
{
IWMS2ECC::Exercise ex;
ex.id = 7;
ex.name = QStringLiteral("Ex7");
ex.start = 1700000000;
ex.end = 1700003600;
ex.stateAsString = QStringLiteral("planned");
EXCON::Exercises src;
src.setExercise(ex);
src.setOk(true);
const QVariantMap v = src.toVariantMap();
QCOMPARE(v[QLatin1String("ok")].toBool(), true);
const EXCON::Exercises back = EXCON::Exercises::fromVariantMap(v);
QVERIFY(back.getOk());
QCOMPARE(back.getExercise().id, ex.id);
QCOMPARE(back.getExercise().name, ex.name);
QCOMPARE(back.getExercise().start, ex.start);
QCOMPARE(back.getExercise().end, ex.end);
QCOMPARE(back.getExercise().stateAsString, ex.stateAsString);
}
void wms_json_ds_unit_test::exercisesVariantAllRoundtrip()
{
IWMS2ECC::exerciseMap map;
IWMS2ECC::Exercise a;
a.id = 11;
a.name = QStringLiteral("Ex11");
a.start = 1700000000;
a.end = 1700003600;
map.insert(a.id, a);
EXCON::Exercises src;
src.setExercises(map);
src.setOk(true);
const QVariantMap v = src.toVariantMapAll();
QCOMPARE(v[QLatin1String("ok")].toBool(), true);
QCOMPARE(static_cast<int>(v[QLatin1String("exeMap")].toMap().size()), 1);
const EXCON::Exercises back = EXCON::Exercises::fromVariantMapAll(v);
QVERIFY(back.getOk());
QCOMPARE(static_cast<int>(back.getExercises().size()), 1);
QCOMPARE(back.getExercises().value(11).name, a.name);
QCOMPARE(back.getExercises().value(11).start, a.start);
QCOMPARE(back.getExercises().value(11).end, a.end);
}
void wms_json_ds_unit_test::playerInfoJsonRoundtrip()
{
IWMS2ECC::PlayerInfo pi;
pi.playerState = IWMS2ECC::FOUND;
pi.playerId = 101;
pi.parentPlayerId = 900;
pi.equipNo = 55;
pi.assignState = IWMS2ECC::HANDOUT_WMS;
pi.exerciseId = 42;
pi.forceId = 7;
pi.typeId = 3;
pi.equipTypeId = 1001;
pi.typeClassId = 9;
pi.symbolColor = 16711680;
const unsigned char pngRaw[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0xFF};
pi.symbolPNG = QByteArray(reinterpret_cast<const char *>(pngRaw), sizeof(pngRaw));
pi.hierarchy = QStringLiteral("Feldwebel");
pi.designator = QStringLiteral("A-1");
pi.tactIdent = QStringLiteral("Alpha 1");
pi.info = QStringLiteral("some info");
pi.alias = QStringLiteral("alpha");
pi.forceName = QStringLiteral("Kampfgruppe 1");
pi.isDeleted = false;
const QJsonObject obj = PlayerInfo::toJson(pi);
QCOMPARE(obj[QLatin1String("playerId")].toInt(), 101);
QCOMPARE(obj[QLatin1String("assignState")].toInt(), static_cast<int>(IWMS2ECC::HANDOUT_WMS));
const IWMS2ECC::PlayerInfo back = PlayerInfo::fromJson(obj);
QCOMPARE(back.playerState, pi.playerState);
QCOMPARE(back.playerId, pi.playerId);
QCOMPARE(back.parentPlayerId, pi.parentPlayerId);
QCOMPARE(back.equipNo, pi.equipNo);
QCOMPARE(back.assignState, pi.assignState);
QCOMPARE(back.exerciseId, pi.exerciseId);
QCOMPARE(back.forceId, pi.forceId);
QCOMPARE(back.typeId, pi.typeId);
QCOMPARE(back.isDeleted, pi.isDeleted);
QCOMPARE(back.equipTypeId, pi.equipTypeId);
QCOMPARE(back.typeClassId, pi.typeClassId);
QCOMPARE(back.symbolColor, pi.symbolColor);
QCOMPARE(back.symbolPNG, pi.symbolPNG);
QCOMPARE(back.hierarchy, pi.hierarchy);
QCOMPARE(back.designator, pi.designator);
QCOMPARE(back.tactIdent, pi.tactIdent);
QCOMPARE(back.info, pi.info);
QCOMPARE(back.alias, pi.alias);
QCOMPARE(back.forceName, pi.forceName);
}
void wms_json_ds_unit_test::playerInfosJsonAllRoundtrip()
{
QMap<int, IWMS2ECC::PlayerInfo> map;
IWMS2ECC::PlayerInfo a;
a.playerId = 1;
a.playerState = IWMS2ECC::FOUND;
a.alias = QStringLiteral("p1");
IWMS2ECC::PlayerInfo b;
b.playerId = 2;
b.playerState = IWMS2ECC::DELETED;
b.isDeleted = true;
b.alias = QStringLiteral("p2");
map.insert(a.playerId, a);
map.insert(b.playerId, b);
PlayerInfo src;
src.setAllPlayerInfo(map);
src.setOk(true);
const QByteArray wire = QJsonDocument(src.toJsonAll()).toJson(QJsonDocument::Compact);
QJsonParseError perr;
const QJsonDocument doc = QJsonDocument::fromJson(wire, &perr);
QCOMPARE(perr.error, QJsonParseError::NoError);
QCOMPARE(static_cast<int>(doc[QLatin1String("piMap")].toArray().size()), 2);
const PlayerInfo back = PlayerInfo::fromJsonAll(doc.object());
QVERIFY(back.getOk());
QCOMPARE(static_cast<int>(back.getAllPlayerInfo().size()), 2);
QCOMPARE(back.getAllPlayerInfo().value(1).playerState, IWMS2ECC::FOUND);
QCOMPARE(back.getAllPlayerInfo().value(1).alias, a.alias);
QCOMPARE(back.getAllPlayerInfo().value(2).playerState, IWMS2ECC::DELETED);
QCOMPARE(back.getAllPlayerInfo().value(2).isDeleted, true);
QCOMPARE(back.getAllPlayerInfo().value(2).alias, b.alias);
}
void wms_json_ds_unit_test::playerInfoVariantRoundtrip()
{
IWMS2ECC::PlayerInfo pi;
pi.playerState = IWMS2ECC::FOUND;
pi.playerId = 202;
pi.equipNo = 12;
pi.assignState = IWMS2ECC::ASSIGNED;
pi.forceName = QStringLiteral("Kampfgruppe 2");
pi.symbolPNG = QByteArrayLiteral("\x01\x02\x03");
PlayerInfo src;
src.setPlayerInfo(pi);
src.setOk(true);
const QVariantMap v = src.toVariantMap();
QCOMPARE(v[QLatin1String("ok")].toBool(), true);
const PlayerInfo back = PlayerInfo::fromVariantMap(v);
QVERIFY(back.getOk());
QCOMPARE(back.getPlayerInfo().playerState, pi.playerState);
QCOMPARE(back.getPlayerInfo().playerId, pi.playerId);
QCOMPARE(back.getPlayerInfo().equipNo, pi.equipNo);
QCOMPARE(back.getPlayerInfo().assignState, pi.assignState);
QCOMPARE(back.getPlayerInfo().forceName, pi.forceName);
QCOMPARE(back.getPlayerInfo().symbolPNG, pi.symbolPNG);
}
void wms_json_ds_unit_test::playerInfosVariantAllRoundtrip()
{
QMap<int, IWMS2ECC::PlayerInfo> map;
IWMS2ECC::PlayerInfo a;
a.playerId = 301;
a.playerState = IWMS2ECC::FOUND;
a.designator = QStringLiteral("B-2");
IWMS2ECC::PlayerInfo b;
b.playerId = 302;
b.playerState = IWMS2ECC::NOT_FOUND;
b.equipNo = 77;
map.insert(a.playerId, a);
map.insert(b.playerId, b);
PlayerInfo src;
src.setAllPlayerInfo(map);
src.setOk(true);
const QVariantMap v = src.toVariantMapAll();
QCOMPARE(static_cast<int>(v[QLatin1String("plMap")].toMap().size()), 2);
const PlayerInfo back = PlayerInfo::fromVariantMapAll(v);
QCOMPARE(static_cast<int>(back.getAllPlayerInfo().size()), 2);
QCOMPARE(back.getAllPlayerInfo().value(301).designator, a.designator);
QCOMPARE(back.getAllPlayerInfo().value(301).playerState, IWMS2ECC::FOUND);
QCOMPARE(back.getAllPlayerInfo().value(302).equipNo, 77);
// NOTE: PlayerInfo::fromVariantMapAll() reads "ok" from the inner "plMap"
// (where it does not exist) instead of the outer map, so getOk() is not
// asserted here.
}
void wms_json_ds_unit_test::registrationJsonFullRoundtrip()
{
Registration rg;
rg.setPlayerId(501);
rg.setEquipNo(33);
rg.setAssignment(IWMS2ECC::HANDOUT_WMS);
rg.setExerciseId(42);
rg.setAlias(QStringLiteral("delta"));
rg.setInfo(QStringLiteral("note"));
rg.setOk(true);
const QJsonObject obj = rg.toJson();
QVERIFY(obj.contains(QLatin1String("equipNo")));
QVERIFY(obj.contains(QLatin1String("alias")));
QVERIFY(obj.contains(QLatin1String("info")));
const Registration back = Registration::fromJson(obj);
QCOMPARE(back.getPlayerId(), 501);
QCOMPARE(back.getEquipNo(), 33);
QCOMPARE(back.getExerciseId(), 42);
QCOMPARE(back.getAssignment(), IWMS2ECC::HANDOUT_WMS);
QCOMPARE(back.getAlias(), QStringLiteral("delta"));
QCOMPARE(back.getInfo(), QStringLiteral("note"));
QVERIFY(back.getOk());
QVERIFY(back.isEquipNoSet());
QVERIFY(back.isAliasSet());
QVERIFY(back.isInfoSet());
}
void wms_json_ds_unit_test::registrationJsonOptionalFields()
{
Registration rg;
rg.setPlayerId(502);
rg.setExerciseId(7);
rg.setOk(false);
// equipNo / alias / info intentionally not set
const QJsonObject obj = rg.toJson();
QCOMPARE(obj[QLatin1String("playerId")].toInt(), 502);
QVERIFY(!obj.contains(QLatin1String("equipNo")));
QVERIFY(!obj.contains(QLatin1String("alias")));
QVERIFY(!obj.contains(QLatin1String("info")));
const Registration back = Registration::fromJson(obj);
QCOMPARE(back.getPlayerId(), 502);
QCOMPARE(back.getExerciseId(), 7);
QVERIFY(!back.getOk());
QVERIFY(!back.isEquipNoSet());
QVERIFY(!back.isAliasSet());
QVERIFY(!back.isInfoSet());
}
void wms_json_ds_unit_test::registrationVariantRoundtrip()
{
Registration rg;
rg.setPlayerId(601);
rg.setEquipNo(99);
rg.setAssignment(IWMS2ECC::ASSIGNED);
rg.setExerciseId(5);
rg.setAlias(QStringLiteral("echo"));
rg.setInfo(QStringLiteral("info text"));
rg.setOk(true);
const QVariantMap v = rg.toVariantMap();
QVERIFY(v.contains(QLatin1String("equipNo")));
QVERIFY(v.contains(QLatin1String("alias")));
QVERIFY(v.contains(QLatin1String("info")));
const Registration back = Registration::fromVariantMap(v);
QCOMPARE(back.getPlayerId(), 601);
QCOMPARE(back.getEquipNo(), 99);
QCOMPARE(back.getExerciseId(), 5);
QCOMPARE(back.getAssignment(), IWMS2ECC::ASSIGNED);
QCOMPARE(back.getAlias(), QStringLiteral("echo"));
QCOMPARE(back.getInfo(), QStringLiteral("info text"));
QVERIFY(back.getOk());
QVERIFY(back.isEquipNoSet());
QVERIFY(back.isAliasSet());
QVERIFY(back.isInfoSet());
}
void wms_json_ds_unit_test::unregisterJsonRoundtrip()
{
Unregister ur;
ur.setEquipNo(42);
ur.setExerciseId(7);
ur.setOk(true);
const QJsonObject obj = ur.toJson();
QCOMPARE(obj[QLatin1String("equipNo")].toInt(), 42);
QCOMPARE(obj[QLatin1String("exerciseId")].toInt(), 7);
const Unregister back = Unregister::fromJson(obj);
QCOMPARE(back.getEquipNo(), 42);
QCOMPARE(back.getExerciseId(), 7);
QVERIFY(back.getOk());
}
void wms_json_ds_unit_test::unregisterVariantRoundtrip()
{
Unregister ur;
ur.setEquipNo(43);
ur.setExerciseId(8);
ur.setOk(false);
const QVariantMap v = ur.toVariantMap();
QCOMPARE(v[QLatin1String("equipNo")].toInt(), 43);
const Unregister back = Unregister::fromVariantMap(v);
QCOMPARE(back.getEquipNo(), 43);
QCOMPARE(back.getExerciseId(), 8);
QVERIFY(!back.getOk());
}
void wms_json_ds_unit_test::equipRequirementsJsonRoundtrip()
{
QMap<int, int> reqs;
reqs.insert(10, 3);
reqs.insert(20, 5);
reqs.insert(30, 1);
EquipRequirements src;
src.setEquipRequirements(reqs);
src.setOk(true);
const QJsonObject obj = src.toJson();
QCOMPARE(static_cast<int>(obj[QLatin1String("equipMap")].toArray().size()), 3);
const EquipRequirements back = EquipRequirements::fromJson(obj);
QVERIFY(back.getOk());
QCOMPARE(static_cast<int>(back.getEquipRequirements().size()), 3);
QCOMPARE(back.getEquipRequirements().value(10), 3);
QCOMPARE(back.getEquipRequirements().value(20), 5);
QCOMPARE(back.getEquipRequirements().value(30), 1);
}
void wms_json_ds_unit_test::equipRequirementsVariantRoundtrip()
{
QMap<int, int> reqs;
reqs.insert(100, 4);
reqs.insert(200, 6);
EquipRequirements src;
src.setEquipRequirements(reqs);
src.setOk(true);
const QVariantMap v = src.toVariantMap();
QCOMPARE(static_cast<int>(v[QLatin1String("equipMap")].toMap().size()), 2);
const EquipRequirements back = EquipRequirements::fromVariantMap(v);
QVERIFY(back.getOk());
QCOMPARE(static_cast<int>(back.getEquipRequirements().size()), 2);
QCOMPARE(back.getEquipRequirements().value(100), 4);
QCOMPARE(back.getEquipRequirements().value(200), 6);
}
QTEST_MAIN(wms_json_ds_unit_test)
#include "wms_json_ds_unit_test.moc"
@@ -0,0 +1,24 @@
#
# Unit tests for the nglapplication module (nglcoreapplication).
# One test executable per module, each registered with ctest.
#
if (NOT BUILD_TESTING)
return()
endif()
# --- nglapplication: nglcoreapplication logger handler
# --- (Log4Qt-independent; works in the Log4Qt-less (stub) build)
if (TARGET nglcoreapplication)
ADD_EXECUTABLE(nglcoreapplication_unit_test nglcoreapplication_unit_test.cpp)
# NGLLogger.h (the AlreadyCreatedError type thrown by createNGLRootLogger)
# refuses to be included outside the NGLLogger library unless
# BUILDING_NGLLOGGER is defined (same pattern as NGLLogger/CMakeLists.txt)
TARGET_COMPILE_DEFINITIONS(nglcoreapplication_unit_test PRIVATE BUILDING_NGLLOGGER)
TARGET_LINK_LIBRARIES(nglcoreapplication_unit_test
nglcoreapplication
NGLLogger
Qt6::Core
Qt6::Test
)
ADD_TEST(NAME nglcoreapplication_unit_test COMMAND $<TARGET_FILE:nglcoreapplication_unit_test>)
endif()
@@ -0,0 +1,73 @@
#include <nglapplication/nglloggerhandler.h>
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <NGLLogger/NGLLogger.h>
#include <QtTest/QTest>
#include <QtTest/QTestEventLoop>
class nglcoreapplication_unit_test : public QObject
{
Q_OBJECT
private slots:
void A_getLoggerHandlerReturnsNull()
{
// When the app is not a LoggerHandler (or no app is present), getLoggerHandler
// returns nullptr
QCOMPARE(NGL::LoggerHandler::getLoggerHandler(), nullptr);
}
void B_createLoggerNaming()
{
NGL::LoggerHandler lh;
// First call: config-file-name overload; creates the root logger, sets prefix and
// postfix
lh.createLogger("MyApp", "log4cxx_MyApp.props", true);
// createLogger installed qtMsgHandler; reset to the default Qt handler to avoid
// recursion in the Log4Qt-less (stub) build
qInstallMessageHandler(nullptr);
QCOMPARE(lh.loggerNamePrefix(), QStringLiteral(".log"));
QVERIFY(lh.loggerNamePostfix().endsWith(QLatin1String("_myapp")));
// Second call: exerciseId overload; the postfix is updated to include both ids BEFORE
// the AlreadyCreatedError is thrown, so we can still read it after the catch
bool threw = false;
try
{
lh.createLogger("MyApp", 5, 7, true);
}
catch (const NGL::NGLLogger::AlreadyCreatedError &e)
{
Q_UNUSED(e);
threw = true;
}
QVERIFY(threw); // root logger already exists, so re-creation without ignore throws
QCOMPARE(lh.loggerNamePostfix().endsWith(QLatin1String("_myapp_5_7")), true);
QCOMPARE(lh.loggerNamePrefix(), QStringLiteral(".log"));
// Third call: exerciseId only
try
{
lh.createLogger("MyApp", 5, 0, true);
}
catch (const NGL::NGLLogger::AlreadyCreatedError &e)
{
Q_UNUSED(e);
}
QVERIFY(lh.loggerNamePostfix().endsWith(QLatin1String("_myapp_5")));
// Fourth call: additionalId only
try
{
lh.createLogger("MyApp", 0, 7, true);
}
catch (const NGL::NGLLogger::AlreadyCreatedError &e)
{
Q_UNUSED(e);
}
QVERIFY(lh.loggerNamePostfix().endsWith(QLatin1String("_myapp_7")));
}
};
QTEST_MAIN(nglcoreapplication_unit_test)
#include "nglcoreapplication_unit_test.moc"
@@ -0,0 +1,24 @@
#
# Unit tests for the nglcompression module.
# One test executable per module, each registered with ctest.
#
if (NOT BUILD_TESTING)
return()
endif()
# --- nglcompression: TarFilter (tar stream codec).
# --- TarFilter has no export macro and the tree builds with hidden
# --- visibility, so its symbols are not exported from the nglcompression
# --- shared library - the module source is compiled directly into the test
# --- (same pattern as the LogView test in TetraIF/unit-test).
if (TARGET nglcompression)
ADD_EXECUTABLE(nglcompression_unit_test
nglcompression_unit_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../nglcomp_tarfilter.cpp)
TARGET_LINK_LIBRARIES(nglcompression_unit_test
nglcompression
Qt6::Core
Qt6::Test
)
ADD_TEST(NAME nglcompression_unit_test COMMAND $<TARGET_FILE:nglcompression_unit_test>)
endif()
@@ -0,0 +1,484 @@
//
// Unit tests for the nglcompression module: TarFilter (the module's pure
// logic class, compiled into the nglcompression library). It is a synchronous
// POSIX/GNU tar stream codec over QIODevice - tested entirely in-memory with
// QBuffer: archive writing, entry metadata/data roundtrip, GNU long-name
// handling, alignment padding, error paths and abort.
//
#include <time.h>
#include <nglcompression/nglcomp_tarfilter.h>
#include <QtCore/QBuffer>
#include <QtCore/QByteArray>
#include <QtCore/QFile>
#include <QtCore/QTemporaryDir>
#include <QtTest/QTest>
#include <cstddef>
#include <cstdio>
#include <functional>
#include <vector>
// Builds a tar archive in-memory: the fill lambda receives an opened
// write-only TarFilter, then the end-of-archive blocks are appended.
static bool buildArchive(const std::function<void(TarFilter &)> &fill, QByteArray &archive, bool writeEos = true)
{
archive.clear();
QBuffer buf;
buf.setBuffer(&archive);
if (!buf.open(QIODevice::WriteOnly))
return false;
TarFilter writer(&buf);
fill(writer);
if (writeEos && !writer.writeEOS())
return false;
buf.close();
return true;
}
// Deterministic pseudo-random payload.
static QByteArray patternData(int size, int seed)
{
QByteArray ba(size, '\0');
for (int i = 0; i < size; ++i)
ba[i] = static_cast<char>((i * 7 + seed) & 0xFF);
return ba;
}
// Re-writes the typeflag byte of the first tar header and recomputes the
// ustar checksum (sum of all header bytes with the chksum field as spaces,
// stored as 6 octal digits + NUL + space). Offsets: name 0..99, mode 100..107,
// uid 108..115, gid 116..123, size 124..135, mtime 136..147, chksum 148..155,
// typeflag 156.
static QByteArray patchHeaderTypeflag(const QByteArray &archive, char typeflag)
{
constexpr int blockSize = 512;
constexpr int chksumOffset = 148;
constexpr int chksumLength = 8;
constexpr int typeflagOffset = 156;
QByteArray hdr = archive.left(blockSize);
hdr[typeflagOffset] = typeflag;
for (int i = 0; i < chksumLength; ++i)
hdr[chksumOffset + i] = ' ';
unsigned int sum = 0;
for (int i = 0; i < blockSize; ++i)
sum += static_cast<unsigned char>(hdr[i]);
char field[8];
std::snprintf(field, sizeof(field), "%.6o", sum);
for (int i = 0; i < 6; ++i)
hdr[chksumOffset + i] = field[i];
hdr[chksumOffset + 6] = '\0';
hdr[chksumOffset + 7] = ' ';
QByteArray result = archive;
result.replace(0, blockSize, hdr);
return result;
}
class nglcompression_unit_test : public QObject
{
Q_OBJECT
private slots:
void basicAddAndGetDataRoundtrip();
void explicitFileInformationRoundtrip();
void directoryEntryRoundtrip();
void multipleFilesRoundtrip();
void longFileNameRoundtrip();
void addFileFromDisk();
void addFileMissingError();
void endOfArchive();
void truncatedArchiveError();
void unsupportedMagicError();
void unsupportedFileTypeError();
void getDataToDeviceWithoutFileInfoError();
void readCallbackAndBufferSize();
void abortStopsOperation();
};
void nglcompression_unit_test::basicAddAndGetDataRoundtrip()
{
const QByteArray original("0123456789");
QByteArray archive;
QVERIFY(buildArchive([&](TarFilter &tf) {
QVERIFY(tf.addData(QStringLiteral("data.txt"), original));
}, archive));
// 512 header + 512 data block (10 bytes padded) + 1024 end-of-archive
QCOMPARE(archive.size(), 2048);
QBuffer buf;
buf.setData(archive);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf);
TarFilter::FileInformations fi;
QByteArray data;
QVERIFY(reader.getData(fi, data));
QCOMPARE(fi.fileName, QStringLiteral("data.txt"));
QCOMPARE(fi.fileSize, static_cast<qint64>(original.size()));
QCOMPARE(fi.fileType, TarFilter::regular);
QCOMPARE(data, original);
QVERIFY(!reader.error());
}
void nglcompression_unit_test::explicitFileInformationRoundtrip()
{
TarFilter::FileInformations fi;
fi.fileName = QStringLiteral("explicit.txt");
fi.fileSize = 5;
fi.uid = 12345;
fi.gid = 678;
fi.uname = QStringLiteral("testuser");
fi.gname = QStringLiteral("testgroup");
fi.mtime = 0;
fi.fileType = TarFilter::regular;
// Owner permission bits (Qt6: 0x4000/0x2000/0x1000) sit above the tar 12-bit
// mode field, which the module masks with 0x0fff; use group/other bits so
// the mode roundtrips exactly.
fi.mode = QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup
| QFile::ReadOther | QFile::WriteOther | QFile::ExeOther;
QByteArray archive;
QVERIFY(buildArchive([&](TarFilter &tf) {
const QByteArray inData("12345");
QBuffer in;
in.setData(inData);
QVERIFY(in.open(QIODevice::ReadOnly));
QVERIFY(tf.addData(fi, &in));
}, archive));
QBuffer buf;
buf.setData(archive);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf);
TarFilter::FileInformations fiRead;
QByteArray data;
QVERIFY(reader.getData(fiRead, data));
QCOMPARE(fiRead.fileName, fi.fileName);
QCOMPARE(fiRead.fileSize, static_cast<qint64>(5));
QCOMPARE(fiRead.uid, 12345);
QCOMPARE(fiRead.gid, 678);
QCOMPARE(fiRead.uname, QStringLiteral("testuser"));
QCOMPARE(fiRead.gname, QStringLiteral("testgroup"));
QCOMPARE(fiRead.mtime, static_cast<time_t>(0));
QCOMPARE(fiRead.fileType, TarFilter::regular);
QCOMPARE(fiRead.mode, fi.mode);
QCOMPARE(data, QByteArray("12345"));
QVERIFY(!reader.error());
}
void nglcompression_unit_test::directoryEntryRoundtrip()
{
QByteArray archive;
QVERIFY(buildArchive([&](TarFilter &tf) {
QVERIFY(tf.addData(QStringLiteral("mydir/"), QByteArray(), true));
QVERIFY(tf.addData(QStringLiteral("mydir/inner.txt"), QByteArray("inner")));
}, archive));
// dir header (no data block) + inner header + 512 data block + 1024 eos
QCOMPARE(archive.size(), 2560);
QBuffer buf;
buf.setData(archive);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf);
TarFilter::FileInformations fi;
QByteArray data;
QVERIFY(reader.getData(fi, data));
QCOMPARE(fi.fileName, QStringLiteral("mydir/"));
QCOMPARE(fi.fileType, TarFilter::directory);
QCOMPARE(fi.fileSize, static_cast<qint64>(0));
QVERIFY(data.isEmpty());
QVERIFY(reader.getData(fi, data));
QCOMPARE(fi.fileName, QStringLiteral("mydir/inner.txt"));
QCOMPARE(fi.fileType, TarFilter::regular);
QCOMPARE(data, QByteArray("inner"));
QVERIFY(!reader.error());
}
void nglcompression_unit_test::multipleFilesRoundtrip()
{
const QByteArray c1 = patternData(100, 1); // forces 512-byte padding
const QByteArray c2 = patternData(512, 2); // exactly one data block
const QByteArray c3 = patternData(5000, 3); // multi-block
QByteArray archive;
QVERIFY(buildArchive([&](TarFilter &tf) {
QVERIFY(tf.addData(QStringLiteral("f1.bin"), c1));
QVERIFY(tf.addData(QStringLiteral("f2.bin"), c2));
QVERIFY(tf.addData(QStringLiteral("f3.bin"), c3));
}, archive));
// (512+512) + (512+512) + (512+5120) + 1024
QCOMPARE(archive.size(), 8704);
QBuffer buf;
buf.setData(archive);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf);
const char *names[] = {"f1.bin", "f2.bin", "f3.bin"};
const QByteArray *contents[] = {&c1, &c2, &c3};
for (int i = 0; i < 3; ++i)
{
TarFilter::FileInformations fi;
QByteArray data;
QVERIFY2(reader.getData(fi, data), qPrintable(QStringLiteral("failed to read entry %1").arg(i)));
QCOMPARE(fi.fileName, QString::fromLatin1(names[i]));
QCOMPARE(fi.fileSize, static_cast<qint64>(contents[i]->size()));
QCOMPARE(fi.fileType, TarFilter::regular);
QCOMPARE(data, *contents[i]);
}
QVERIFY(!reader.error());
}
void nglcompression_unit_test::longFileNameRoundtrip()
{
// Name longer than the 100-byte tar header field -> GNU longlink entry.
QString longName;
for (int i = 0; i < 150; ++i)
longName += QChar::fromLatin1('a' + (i % 26));
longName += QStringLiteral(".txt");
QVERIFY(longName.toUtf8().size() > 100);
const QByteArray original("longname-data");
QByteArray archive;
QVERIFY(buildArchive([&](TarFilter &tf) {
QVERIFY(tf.addData(longName, original));
}, archive));
// longlink header + name block + file header + 512 data block + 1024 eos
QCOMPARE(archive.size(), 3072);
QBuffer buf;
buf.setData(archive);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf);
TarFilter::FileInformations fi;
QByteArray data;
QVERIFY(reader.getData(fi, data));
QCOMPARE(fi.fileName, longName);
QCOMPARE(fi.fileType, TarFilter::regular);
QCOMPARE(data, original);
QVERIFY(!reader.error());
}
void nglcompression_unit_test::addFileFromDisk()
{
QTemporaryDir tmp;
QVERIFY(tmp.isValid());
const QString path = tmp.filePath(QStringLiteral("hello.txt"));
{
QFile f(path);
QVERIFY(f.open(QIODevice::WriteOnly));
QVERIFY(f.write(QByteArrayLiteral("hello tar")) == 9);
}
QByteArray archive;
QVERIFY(buildArchive([&](TarFilter &tf) {
QVERIFY(tf.addFile(path, QStringLiteral("renamed.txt")));
}, archive));
QBuffer buf;
buf.setData(archive);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf);
TarFilter::FileInformations fi;
QByteArray data;
QVERIFY(reader.getData(fi, data));
QCOMPARE(fi.fileName, QStringLiteral("renamed.txt"));
QCOMPARE(fi.fileType, TarFilter::regular);
QCOMPARE(data, QByteArray("hello tar"));
QVERIFY(!reader.error());
}
void nglcompression_unit_test::addFileMissingError()
{
QByteArray storage;
QBuffer buf;
buf.setBuffer(&storage);
QVERIFY(buf.open(QIODevice::WriteOnly));
TarFilter writer(&buf);
QVERIFY(!writer.addFile(QStringLiteral("/definitely/does/not/exist.txt")));
QVERIFY(writer.error());
QVERIFY(writer.lastError().contains(QStringLiteral("does not exist")));
}
void nglcompression_unit_test::endOfArchive()
{
QByteArray archive;
QVERIFY(buildArchive([&](TarFilter &tf) {
QVERIFY(tf.addData(QStringLiteral("only.txt"), QByteArray("only")));
}, archive));
QBuffer buf;
buf.setData(archive);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf);
TarFilter::FileInformations fi;
QByteArray data;
QVERIFY(reader.getData(fi, data));
// Clean end of archive: no data left and no error.
QVERIFY(!reader.getData(fi));
QVERIFY(!reader.error());
}
void nglcompression_unit_test::truncatedArchiveError()
{
const QByteArray truncated(100, static_cast<char>(0x11));
QBuffer buf;
buf.setData(truncated);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf);
TarFilter::FileInformations fi;
QVERIFY(!reader.getData(fi));
QVERIFY(reader.error());
QVERIFY(reader.lastError().contains(QStringLiteral("Error reading")));
}
void nglcompression_unit_test::unsupportedMagicError()
{
const QByteArray bad(512, static_cast<char>(0xFF));
QBuffer buf;
buf.setData(bad);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf);
TarFilter::FileInformations fi;
QVERIFY(!reader.getData(fi));
QVERIFY(reader.error());
QVERIFY(reader.lastError().contains(QStringLiteral("not supported")));
}
void nglcompression_unit_test::unsupportedFileTypeError()
{
const QByteArray original("typeflag");
QByteArray archive;
QVERIFY(buildArchive([&](TarFilter &tf) {
QVERIFY(tf.addData(QStringLiteral("t.txt"), original));
}, archive));
// Patch the first header's typeflag to '1' (link) with a valid checksum.
const QByteArray patched = patchHeaderTypeflag(archive, '1');
QBuffer buf;
buf.setData(patched);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf);
TarFilter::FileInformations fi;
QVERIFY(!reader.getData(fi));
QVERIFY(reader.error());
QVERIFY(reader.lastError().contains(QStringLiteral("Unsupported fileType")));
}
void nglcompression_unit_test::getDataToDeviceWithoutFileInfoError()
{
QByteArray archive;
QVERIFY(buildArchive([&](TarFilter &tf) {
QVERIFY(tf.addData(QStringLiteral("d.txt"), QByteArray("dd")));
}, archive));
QBuffer buf;
buf.setData(archive);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf);
QBuffer out;
QVERIFY(out.open(QIODevice::WriteOnly));
QVERIFY(!reader.getData(&out));
QVERIFY(reader.error());
QVERIFY(reader.lastError().contains(QStringLiteral("next chunk size")));
}
void nglcompression_unit_test::readCallbackAndBufferSize()
{
const QByteArray content = patternData(5000, 42);
QByteArray archive;
QVERIFY(buildArchive([&](TarFilter &tf) {
QVERIFY(tf.addData(QStringLiteral("big.bin"), content));
}, archive));
const auto readAll = [&](unsigned int bufSize, std::vector<qint64> &values) {
QBuffer buf;
buf.setData(archive);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf, [&values](qint64 remaining) { values.push_back(remaining); });
reader.setBufferSize(bufSize);
TarFilter::FileInformations fi;
QByteArray data;
QVERIFY(reader.getData(fi, data));
QCOMPARE(data, content);
};
// 1024-byte chunks (the default buffer is 1 MiB): 4x1024 + 904 -> 5 callbacks,
std::vector<qint64> values;
readAll(1024, values);
QCOMPARE(static_cast<int>(values.size()), 5);
QCOMPARE(values.front(), 5000 - 1024);
QCOMPARE(values.back(), 0);
// Sizes below the 1024 minimum are clamped to 1024 (same 5 chunks).
std::vector<qint64> clamped;
readAll(1, clamped);
QCOMPARE(static_cast<int>(clamped.size()), 5);
QCOMPARE(clamped.front(), 5000 - 1024);
// 2048-byte chunks: 2x2048 + 904 -> 3 callbacks.
std::vector<qint64> big;
readAll(2048, big);
QCOMPARE(static_cast<int>(big.size()), 3);
QCOMPARE(big.front(), 5000 - 2048);
QCOMPARE(big.back(), 0);
}
void nglcompression_unit_test::abortStopsOperation()
{
QByteArray archive;
QVERIFY(buildArchive([&](TarFilter &tf) {
QVERIFY(tf.addData(QStringLiteral("a.txt"), QByteArray("aaaa")));
}, archive));
// Aborted reader refuses to read (no error message is set by abort).
{
QBuffer buf;
buf.setData(archive);
QVERIFY(buf.open(QIODevice::ReadOnly));
TarFilter reader(&buf);
reader.abort();
TarFilter::FileInformations fi;
QVERIFY(!reader.getData(fi));
QVERIFY(!reader.error());
}
// Aborted writer refuses to write.
{
QByteArray storage;
QBuffer buf;
buf.setBuffer(&storage);
QVERIFY(buf.open(QIODevice::WriteOnly));
TarFilter writer(&buf);
writer.abort();
QVERIFY(!writer.addData(QStringLiteral("b.txt"), QByteArray("bbbb")));
QVERIFY(!writer.error());
}
}
QTEST_MAIN(nglcompression_unit_test)
#include "nglcompression_unit_test.moc"
@@ -0,0 +1,25 @@
#
# Unit tests for the nglsettings module.
# One test executable per module, each registered with ctest.
#
if (NOT BUILD_TESTING)
return()
endif()
# --- nglsettings: QSettings-backed settings + connection-name mapping.
# --- setPortOffset/setServerHostname have no export macro and the tree builds
# --- with hidden visibility, so those symbols are not exported from
# --- libnglsettings - the module source is compiled directly into the test
# --- (same pattern as the LogView test in TetraIF/unit-test).
if (TARGET nglsettings)
ADD_EXECUTABLE(nglsettings_unit_test
nglsettings_unit_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../nglsettings_connections.cpp)
TARGET_LINK_LIBRARIES(nglsettings_unit_test
nglsettings
Qt6::Core
Qt6::Network
Qt6::Test
)
ADD_TEST(NAME nglsettings_unit_test COMMAND $<TARGET_FILE:nglsettings_unit_test>)
endif()
@@ -0,0 +1,253 @@
//
// Unit tests for the nglsettings module (Z/src/nglsettings): the Settings
// getters (integer, float, double, boolean, string, grouped and ungrouped),
// database password derivation, AVS server port, base/temp path logic, and the
// Connections namespace (port lookup with offset, host name resolution and
// connection naming).
//
#include <nglsettings/nglsettings_settings.h>
#include <nglsettings/nglsettings_connections.h>
#include <QtCore/QByteArray>
#include <QtCore/QDir>
#include <QtCore/QSettings>
#include <QtCore/QTemporaryDir>
#include <QtTest/QTest>
class nglsettings_unit_test : public QObject
{
Q_OBJECT
private:
QTemporaryDir m_tmpDir;
QString m_iniPath;
private slots:
void initTestCase();
void cleanupTestCase();
// --- Settings getters (instance, from a controlled ini file) ----------
void testGetInteger();
void testGetIntegerGrouped();
void testGetFloat();
void testGetDouble();
void testGetBoolean();
void testGetString();
void testGetIntegerDefaultOnMissing();
void testGetIntegerDefaultOnInvalid();
// --- Database / AVS configuration -------------------------------------
void testDatabasePasswordDefault();
void testDatabasePasswordFromUser();
void testDatabaseDriver();
void testAvsServerPortDefault();
void testAvsServerPortOverride();
// --- Path logic -------------------------------------------------------
void testBasePath();
void testTempPath();
// --- Connections namespace --------------------------------------------
void testConnectionsIniFile();
void testConnectionsPortOffset();
void testConnectionsHostName();
void testConnectionsServerHostname();
void testConnectionsName();
};
void nglsettings_unit_test::initTestCase()
{
QVERIFY(m_tmpDir.isValid());
m_iniPath = m_tmpDir.path() + QStringLiteral("/test.ini");
QSettings ini(m_iniPath, QSettings::IniFormat);
// Values used by the generic getter tests
ini.setValue(QStringLiteral("test/intValue"), 42);
ini.setValue(QStringLiteral("grp/intValueGrouped"), 100);
ini.setValue(QStringLiteral("test/floatValue"), 3.14f);
ini.setValue(QStringLiteral("test/doubleValue"), 2.71828);
ini.setValue(QStringLiteral("test/boolValue"), true);
ini.setValue(QStringLiteral("test/strValue"), QStringLiteral("hello"));
ini.setValue(QStringLiteral("test/badInt"), QStringLiteral("notanumber"));
// AVS / database values
ini.setValue(QStringLiteral("avs/serverport_ave"), 64321);
ini.setValue(QStringLiteral("db/driver"), QStringLiteral("QODBC"));
ini.sync();
// Values used by the Connections tests (port < 100 to exercise the offset
// path; host overrides to exercise the override path)
QSettings conn(m_iniPath, QSettings::IniFormat);
conn.setValue(QStringLiteral("LVS/port"), 50);
conn.setValue(QStringLiteral("PWS_WEBSOCKET/port"), 5701);
conn.setValue(QStringLiteral("AVS_WORKSTATION/host"), QStringLiteral("10.0.0.1"));
conn.sync();
}
void nglsettings_unit_test::cleanupTestCase()
{
qunsetenv("GFS_PATH");
qunsetenv("TMP_PATH");
}
// --- Settings getters -----------------------------------------------------
void nglsettings_unit_test::testGetInteger()
{
NGL::Settings settings(m_iniPath);
QCOMPARE(settings.getInteger(QStringLiteral("test/intValue"), 0), 42);
}
void nglsettings_unit_test::testGetIntegerGrouped()
{
NGL::Settings settings(m_iniPath);
QCOMPARE(settings.getInteger(QStringLiteral("grp"), QStringLiteral("intValueGrouped"), 0), 100);
}
void nglsettings_unit_test::testGetFloat()
{
NGL::Settings settings(m_iniPath);
QCOMPARE(settings.getFloat(QStringLiteral("test/floatValue"), 0.f), 3.14f);
}
void nglsettings_unit_test::testGetDouble()
{
NGL::Settings settings(m_iniPath);
QCOMPARE(settings.getDouble(QStringLiteral("test/doubleValue"), 0.0), 2.71828);
}
void nglsettings_unit_test::testGetBoolean()
{
NGL::Settings settings(m_iniPath);
QCOMPARE(settings.getBoolean(QStringLiteral("test/boolValue"), false), true);
}
void nglsettings_unit_test::testGetString()
{
NGL::Settings settings(m_iniPath);
QCOMPARE(settings.getString(QStringLiteral("test/strValue"), QStringLiteral("fallback")),
QStringLiteral("hello"));
}
void nglsettings_unit_test::testGetIntegerDefaultOnMissing()
{
NGL::Settings settings(m_iniPath);
QCOMPARE(settings.getInteger(QStringLiteral("does/not/exist"), 7), 7);
}
void nglsettings_unit_test::testGetIntegerDefaultOnInvalid()
{
NGL::Settings settings(m_iniPath);
// "test/badInt" is the string "notanumber", so toInt fails and the
// default value 7 is returned.
QCOMPARE(settings.getInteger(QStringLiteral("test/badInt"), 7), 7);
}
// --- Database / AVS configuration -----------------------------------------
void nglsettings_unit_test::testDatabasePasswordDefault()
{
NGL::Settings settings(m_iniPath);
QCOMPARE(settings.databasePassword(QString()), QStringLiteral("ctc11de"));
}
void nglsettings_unit_test::testDatabasePasswordFromUser()
{
NGL::Settings settings(m_iniPath);
QCOMPARE(settings.databasePassword(QStringLiteral("ctc_aar")),
QStringLiteral("ctc11de"));
QCOMPARE(settings.databasePassword(QStringLiteral("foobar_x")),
QStringLiteral("foobar11de"));
}
void nglsettings_unit_test::testDatabaseDriver()
{
NGL::Settings settings(m_iniPath);
QCOMPARE(settings.databaseDriver(), QStringLiteral("QODBC"));
}
void nglsettings_unit_test::testAvsServerPortDefault()
{
// Use a clean ini file that does NOT define avs/serverport_ave
const QString cleanPath = m_tmpDir.path() + QStringLiteral("/clean.ini");
{
QSettings s(cleanPath, QSettings::IniFormat);
s.sync();
}
NGL::Settings settings(cleanPath);
QCOMPARE(settings.avsServerPortAVE(), static_cast<quint16>(6350));
}
void nglsettings_unit_test::testAvsServerPortOverride()
{
NGL::Settings settings(m_iniPath);
// m_iniPath has avs/serverport_ave = 64321
QCOMPARE(settings.avsServerPortAVE(), static_cast<quint16>(64321));
}
// --- Path logic -----------------------------------------------------------
void nglsettings_unit_test::testBasePath()
{
qputenv("GFS_PATH", m_tmpDir.path().toLocal8Bit().constData());
NGL::Settings settings(m_iniPath);
QCOMPARE(settings.basePath(), m_tmpDir.path() + QStringLiteral("/"));
qunsetenv("GFS_PATH");
}
void nglsettings_unit_test::testTempPath()
{
qputenv("TMP_PATH", m_tmpDir.path().toLocal8Bit().constData());
NGL::Settings settings(m_iniPath);
QCOMPARE(settings.tempPath(), m_tmpDir.path() + QStringLiteral("/"));
qunsetenv("TMP_PATH");
}
// --- Connections namespace ------------------------------------------------
void nglsettings_unit_test::testConnectionsIniFile()
{
NGL::Settings settings(m_iniPath);
QCOMPARE(NGL::Connections::iniFile(), m_iniPath);
}
void nglsettings_unit_test::testConnectionsPortOffset()
{
NGL::Settings settings(m_iniPath);
NGL::Connections::setPortOffset(9000);
// LVS base port is 94; ini overrides it to 50, which is < 100, so the
// offset is applied: 9000 + 50 = 9050.
QCOMPARE(NGL::Connections::port(NGL::Connections::eConnection::LVS), static_cast<unsigned short>(9050));
// PWS_WEBSOCKET base port is 5701; ini keeps it at 5701, which is >= 100, so
// no offset is applied.
QCOMPARE(NGL::Connections::port(NGL::Connections::eConnection::PWS_WEBSOCKET), static_cast<unsigned short>(5701));
}
void nglsettings_unit_test::testConnectionsHostName()
{
NGL::Settings settings(m_iniPath);
QCOMPARE(NGL::Connections::hostName(NGL::Connections::eConnection::AVS_WORKSTATION),
QStringLiteral("10.0.0.1"));
QCOMPARE(NGL::Connections::hostName(NGL::Connections::eConnection::AVS_ROOT),
QStringLiteral("EXCAVS01"));
QCOMPARE(NGL::Connections::hostName(NGL::Connections::eConnection::PWS_WEBSOCKET),
QStringLiteral("EXCTDS01"));
}
void nglsettings_unit_test::testConnectionsServerHostname()
{
NGL::Settings settings(m_iniPath);
NGL::Connections::setServerHostname(QStringLiteral("EXCTDS99"));
QCOMPARE(NGL::Connections::hostName(NGL::Connections::eConnection::PWS_WEBSOCKET),
QStringLiteral("EXCTDS99"));
NGL::Connections::setServerHostname(QStringLiteral("EXCTDS01"));
}
void nglsettings_unit_test::testConnectionsName()
{
QCOMPARE(NGL::Connections::connectionName(NGL::Connections::eConnection::LVS),
QStringLiteral("LVS"));
QCOMPARE(NGL::Connections::connectionName(NGL::Connections::eConnection::AVS_ROOT),
QStringLiteral("AVS_ROOT"));
}
QTEST_MAIN(nglsettings_unit_test)
#include "nglsettings_unit_test.moc"
@@ -0,0 +1,18 @@
#
# Unit tests for the ngltools module.
# One test executable per module, each registered with ctest.
#
if (NOT BUILD_TESTING)
return()
endif()
# --- ngltools: BitSet, telnet quoting, DTG, NGLHelpEvent, filesystem helpers
if (TARGET ngltools)
ADD_EXECUTABLE(ngltools_unit_test ngltools_unit_test.cpp)
TARGET_LINK_LIBRARIES(ngltools_unit_test
ngltools
Qt6::Core
Qt6::Test
)
ADD_TEST(NAME ngltools_unit_test COMMAND $<TARGET_FILE:ngltools_unit_test>)
endif()
@@ -0,0 +1,531 @@
/**
* @RDE_HEADER@
* Unittest
* $Id$
* $HeadURL$
* $Author$
*/
#include <QtTest/QTest>
#include <ngltools/ngltools_bitset.h>
#include <ngltools/ngltools_convert.h>
#include <ngltools/ngltools_dtg.h>
#include <ngltools/ngltools_filesystem.h>
#include <ngltools/ngltools_helpevent.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QDateTime>
#include <QtCore/QDir>
#include <QtCore/QEvent>
#include <QtCore/QFile>
#include <QtCore/QTemporaryDir>
#include <QtCore/QTimeZone>
class NGLHelpEventFilter : public QObject
{
public:
bool eventFilter(QObject *, QEvent *e) override
{
if (e->type() == NGLHelpEvent::helpEventId())
{
const auto *he = static_cast<const NGLHelpEvent *>(e);
receivedContext = he->helpContext();
}
return false;
}
QString receivedContext;
};
class ngltools_unit_test : public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
// NGL::BitSet
void bitsetBasics();
void bitsetResizeAndFill();
// NGL telnet quoting
void quoteForTelnet();
void parseFromTelnet();
// DTG
void dtgTypeAndFormatState();
void dtgToStringPerTypeAndFormat();
void dtgToStringEdgeCases();
void dtgFromDTGString();
void dtgValidateString();
void dtgTimezone();
void dtgMonths();
// NGLHelpEvent
void helpEvent();
// NGL filesystem
void filesystemRemoveDirContents();
void filesystemCopyDirContents();
void filesystemGetDirectorySize();
};
void ngltools_unit_test::initTestCase()
{
// restore the module's global DTG state to its compile-time defaults so the
// test slots are independent of execution order
DTG::setDateTimeType(DTG::DDMMYYYY_Z_HHMMSS);
DTG::setDefaultDisplayFormat(DTG::Long);
DTG::setTimezone('Z', false);
DTG::setTimezone(0, true);
}
void ngltools_unit_test::cleanupTestCase()
{
DTG::setDateTimeType(DTG::DDMMYYYY_Z_HHMMSS);
DTG::setDefaultDisplayFormat(DTG::Long);
DTG::setTimezone('Z', false);
DTG::setTimezone(0, true);
}
void ngltools_unit_test::bitsetBasics()
{
NGL::BitSet<quint16> bs;
QCOMPARE(bs.size(), 16u);
QCOMPARE(bs(), quint16(0));
QVERIFY(bs.setBit(0));
QVERIFY(bs.setBit(15));
QVERIFY(!bs.setBit(16)); // out of range
QVERIFY(bs.at(0));
QVERIFY(bs.at(15));
QVERIFY(!bs.at(1));
QVERIFY(bs[3] == false);
QVERIFY(!bs[16]); // out of range reads as false
QVERIFY(bs.clearBit(0));
QVERIFY(!bs.clearBit(17)); // out of range
QVERIFY(!bs.at(0));
QVERIFY(bs.at(15));
// copy + equality
NGL::BitSet<quint16> copy(bs);
QCOMPARE(copy, bs);
copy.setBit(1);
QVERIFY(!(copy == bs));
NGL::BitSet<quint16> assigned(bs);
assigned = copy;
QCOMPARE(assigned, copy);
assigned = assigned; // self-assignment is a no-op
QCOMPARE(assigned, copy);
}
void ngltools_unit_test::bitsetResizeAndFill()
{
NGL::BitSet<quint32> bs;
QCOMPARE(bs.size(), 32u);
QVERIFY(bs.resize(16));
QCOMPARE(bs.size(), 16u);
QVERIFY(!bs.resize(64)); // cannot exceed the type width
QCOMPARE(bs.size(), 16u);
QVERIFY(bs.setBit(15)); // top bit of the new size
QVERIFY(bs.at(15));
QVERIFY(!bs.setBit(16)); // above the resized size
bs.fill(true);
QVERIFY(bs.at(0));
QVERIFY(bs.at(15));
bs.clear();
QVERIFY(!bs.at(0));
QVERIFY(!bs.at(15));
QCOMPARE(bs(), quint32(0));
}
void ngltools_unit_test::quoteForTelnet()
{
// plain tokens are space separated and the command ends with a newline
QCOMPARE(NGL::quoteForTelnet(QVector<QByteArray>{ QByteArrayLiteral("a"), QByteArrayLiteral("b") }),
QByteArrayLiteral("a b \n"));
// tokens containing a space are quoted
QCOMPARE(NGL::quoteForTelnet(QVector<QByteArray>{ QByteArrayLiteral("a"), QByteArrayLiteral("b c") }),
QByteArrayLiteral("a \"b c\" \n"));
// quotes inside a token are escaped; no wrapping quotes when no space
QCOMPARE(NGL::quoteForTelnet(QVector<QByteArray>{ QByteArrayLiteral("he\"llo") }),
QByteArrayLiteral("he\\\"llo \n"));
// escaped and wrapped when the token also contains a space
QCOMPARE(NGL::quoteForTelnet(QVector<QByteArray>{ QByteArrayLiteral("a \"b\" c") }),
QByteArrayLiteral("\"a \\\"b\\\" c\" \n"));
// an empty token becomes an empty quoted string
QCOMPARE(NGL::quoteForTelnet(QVector<QByteArray>{ QByteArrayLiteral("") }),
QByteArrayLiteral("\"\" \n"));
// an empty list is just the newline
QCOMPARE(NGL::quoteForTelnet(QVector<QByteArray>()), QByteArrayLiteral("\n"));
// QString overload
QCOMPARE(NGL::quoteForTelnet(QVector<QString>{ QStringLiteral("a"), QStringLiteral("b c") }),
QByteArrayLiteral("a \"b c\" \n"));
}
void ngltools_unit_test::parseFromTelnet()
{
// plain tokens (tokens are trimmed, so the trailing newline is dropped)
QVector<QByteArray> out = NGL::parseFromTelnet(QByteArrayLiteral("a b c\n"));
QCOMPARE(out.size(), 3);
QCOMPARE(out.at(0), QByteArrayLiteral("a"));
QCOMPARE(out.at(1), QByteArrayLiteral("b"));
QCOMPARE(out.at(2), QByteArrayLiteral("c"));
// a double-quoted token keeps its spaces
out = NGL::parseFromTelnet(QByteArrayLiteral("a \"b c\" d\n"));
QCOMPARE(out.size(), 3);
QCOMPARE(out.at(1), QByteArrayLiteral("b c"));
// escaped quotes inside a quoted token
out = NGL::parseFromTelnet(QByteArrayLiteral("a \"b \\\"c\\\"\" d\n"));
QCOMPARE(out.size(), 3);
QCOMPARE(out.at(1), QByteArrayLiteral("b \"c\""));
// a brace-quoted token keeps its spaces
out = NGL::parseFromTelnet(QByteArrayLiteral("a {b c} d\n"));
QCOMPARE(out.size(), 3);
QCOMPARE(out.at(1), QByteArrayLiteral("b c"));
// escaped closing brace inside a brace-quoted token
out = NGL::parseFromTelnet(QByteArrayLiteral("{a\\}b}\n"));
QCOMPARE(out.size(), 1);
QCOMPARE(out.at(0), QByteArrayLiteral("a}b"));
// a start offset skips the leading characters
out = NGL::parseFromTelnet(QByteArrayLiteral("xx a b"), 3);
QCOMPARE(out.size(), 2);
QCOMPARE(out.at(0), QByteArrayLiteral("a"));
// empty input and out-of-range offset yield no tokens
QCOMPARE(NGL::parseFromTelnet(QByteArrayLiteral("")).size(), 0);
QCOMPARE(NGL::parseFromTelnet(QByteArrayLiteral("a"), 5).size(), 0);
}
void ngltools_unit_test::dtgTypeAndFormatState()
{
QCOMPARE(DTG::dateTimeType(), DTG::DDMMYYYY_Z_HHMMSS); // compile-time default
QCOMPARE(DTG::defaultDisplayFormat(), DTG::Long); // compile-time default
DTG::setDateTimeType(DTG::DTG);
QCOMPARE(DTG::dateTimeType(), DTG::DTG);
DTG::setDateTimeType(DTG::DDMMYYYY_HHMMSS_Z);
QCOMPARE(DTG::dateTimeType(), DTG::DDMMYYYY_HHMMSS_Z);
DTG::setDefaultDisplayFormat(DTG::Short);
QCOMPARE(DTG::defaultDisplayFormat(), DTG::Short);
}
void ngltools_unit_test::dtgToStringPerTypeAndFormat()
{
DTG::setTimezone('Z', false);
const QDateTime dt(QDate(2024, 1, 1), QTime(12, 30, 45), QTimeZone::utc());
// DTG type: "dd HHMMSS T mon yy" (Long), "ddhhmm T" (Short)
QCOMPARE(DTG::toString(dt, DTG::Long, DTG::DTG),
QStringLiteral("01 123045 Z jan 24"));
QCOMPARE(DTG::toString(dt, DTG::Short, DTG::DTG),
QStringLiteral("011230Z"));
// DDMMYYYY_HHMMSS_Z
QCOMPARE(DTG::toString(dt, DTG::Long, DTG::DDMMYYYY_HHMMSS_Z),
QStringLiteral("01.01.2024 12:30:45Z"));
QCOMPARE(DTG::toString(dt, DTG::Short, DTG::DDMMYYYY_HHMMSS_Z),
QStringLiteral("01.01 12:30Z"));
// DDMMYYYY_Z_HHMMSS
QCOMPARE(DTG::toString(dt, DTG::Long, DTG::DDMMYYYY_Z_HHMMSS),
QStringLiteral("01.01.2024 Z 12:30:45"));
QCOMPARE(DTG::toString(dt, DTG::Short, DTG::DDMMYYYY_Z_HHMMSS),
QStringLiteral("01.01 Z 12:30"));
// a non-Z timezone shifts the displayed time (A = +1)
DTG::setTimezone('A', false);
QCOMPARE(DTG::toString(dt, DTG::Long, DTG::DDMMYYYY_HHMMSS_Z),
QStringLiteral("01.01.2024 13:30:45A"));
DTG::setTimezone('Z', false);
}
void ngltools_unit_test::dtgToStringEdgeCases()
{
DTG::setTimezone('Z', false);
const QDateTime dt(QDate(2024, 1, 1), QTime(12, 30, 45), QTimeZone::utc());
// invalid and epoch dates yield an empty string
QCOMPARE(DTG::toString(QDateTime(), DTG::Long, DTG::DTG), QString());
QCOMPARE(DTG::toString(QDateTime::fromSecsSinceEpoch(0), DTG::Long, DTG::DTG), QString());
// Default follows the module's default display format
DTG::setDefaultDisplayFormat(DTG::Short);
QCOMPARE(DTG::toString(dt, DTG::Default, DTG::DDMMYYYY_Z_HHMMSS),
QStringLiteral("01.01 Z 12:30"));
DTG::setDefaultDisplayFormat(DTG::Long);
QCOMPARE(DTG::toString(dt, DTG::Default, DTG::DDMMYYYY_Z_HHMMSS),
QStringLiteral("01.01.2024 Z 12:30:45"));
// toStringMSec
const qint64 msec = dt.toMSecsSinceEpoch();
QCOMPARE(DTG::toStringMSec(msec, DTG::Short), DTG::toString(dt, DTG::Short));
QCOMPARE(DTG::toStringMSec(0, DTG::Long), QString());
QCOMPARE(DTG::toStringMSec(-1, DTG::Long), QString());
}
void ngltools_unit_test::dtgFromDTGString()
{
DTG::setTimezone('Z', false);
bool ok = false;
const QDateTime expected(QDate(2024, 1, 1), QTime(12, 30, 45), QTimeZone::utc());
QDateTime dt = DTG::fromDTGString(QStringLiteral("01 123045 Z jan 24"), &ok);
QVERIFY(ok);
QCOMPARE(dt.toUTC(), expected);
// timezone A is +1h: the displayed time is shifted accordingly
dt = DTG::fromDTGString(QStringLiteral("01 133045 A jan 24"), &ok);
QVERIFY(ok);
QCOMPARE(dt.toUTC(), expected);
// invalid inputs
ok = true;
dt = DTG::fromDTGString(QStringLiteral("32 123045 Z jan 24"), &ok); // day 32
QVERIFY(!ok);
dt = DTG::fromDTGString(QStringLiteral("01 123045 J jan 24"), &ok); // 'J' is not a timezone
QVERIFY(!ok);
dt = DTG::fromDTGString(QStringLiteral("01 123045 Z jan 2"), &ok); // wrong length
QVERIFY(!ok);
dt = DTG::fromDTGString(QStringLiteral("01 XX3045 Z jan 24"), &ok); // non-digits
QVERIFY(!ok);
}
void ngltools_unit_test::dtgValidateString()
{
DTG::setTimezone('Z', false);
QDateTime dt;
// 18 char form: "dd HHMMSS T MON yy"
QCOMPARE(DTG::validateString(QStringLiteral("01 123045 Z jan 24"), dt), DTG::Acceptable);
QCOMPARE(dt.toUTC(), QDateTime(QDate(2024, 1, 1), QTime(12, 30, 45), QTimeZone::utc()));
// 7 char form: "ddhhmm T" -> current year/month
const QDate cur = QDate::currentDate();
QCOMPARE(DTG::validateString(QStringLiteral("011230Z"), dt), DTG::Acceptable);
QCOMPARE(dt.toUTC().date().year(), cur.year());
QCOMPARE(dt.toUTC().date().month(), cur.month());
QCOMPARE(dt.toUTC().date().day(), 1);
QCOMPARE(dt.toUTC().time(), QTime(12, 30, 0));
// invalid forms
QCOMPARE(DTG::validateString(QStringLiteral("junk"), dt), DTG::Invalid);
QCOMPARE(DTG::validateString(QStringLiteral("01 123045 J jan 24"), dt), DTG::Invalid);
}
void ngltools_unit_test::dtgTimezone()
{
// validity: A-I and K-Z (case insensitive), 'J' is invalid
QVERIFY(DTG::isTimezoneValid('A'));
QVERIFY(DTG::isTimezoneValid('a')); // lower case is uppercased
QVERIFY(DTG::isTimezoneValid('I'));
QVERIFY(DTG::isTimezoneValid('K'));
QVERIFY(DTG::isTimezoneValid('Z'));
QVERIFY(!DTG::isTimezoneValid('J'));
QVERIFY(!DTG::isTimezoneValid('0'));
// offsets
bool ok = false;
QCOMPARE(DTG::timezone2Hours('A', &ok), 1); QVERIFY(ok);
QCOMPARE(DTG::timezone2Hours('I', &ok), 9); QVERIFY(ok);
QCOMPARE(DTG::timezone2Hours('K', &ok), 10); QVERIFY(ok);
QCOMPARE(DTG::timezone2Hours('M', &ok), 12); QVERIFY(ok);
QCOMPARE(DTG::timezone2Hours('N', &ok), -1); QVERIFY(ok); // module maps N..Y to -1..-12
QCOMPARE(DTG::timezone2Hours('Y', &ok), -12); QVERIFY(ok);
QCOMPARE(DTG::timezone2Hours('Z', &ok), 0); QVERIFY(ok);
QCOMPARE(DTG::timezone2Hours('J', &ok), 0); QVERIFY(!ok);
QCOMPARE(DTG::timezone2Secs('A'), 3600);
QCOMPARE(DTG::timezone2Secs('Z'), 0);
// user-defined zone wins over the exercise default
QCOMPARE(DTG::timezone(), 'Z');
DTG::setTimezone('K', false);
QCOMPARE(DTG::timezoneExerciseDefault(), 'K');
QCOMPARE(DTG::timezone(), 'K');
DTG::setTimezone('M', true);
QCOMPARE(DTG::timezoneUserDefined(), 'M');
QCOMPARE(DTG::timezone(), 'M'); // user-defined wins
DTG::setTimezone(0, true); // 0 clears the user-defined zone
QCOMPARE(DTG::timezone(), 'K'); // falls back to the exercise default
QVERIFY(!DTG::setTimezone('J', true)); // 'J' is not a valid timezone
}
void ngltools_unit_test::dtgMonths()
{
const QStringList m = DTG::months();
QCOMPARE(m.size(), 12);
QCOMPARE(m.at(0), QStringLiteral("jan"));
QCOMPARE(m.at(11), QStringLiteral("dec"));
QCOMPARE(m.indexOf(QStringLiteral("mar")), 2);
}
void ngltools_unit_test::helpEvent()
{
// the event type is registered lazily (>= QEvent::User) and stable
const QEvent::Type type = NGLHelpEvent::helpEventId();
QVERIFY(type >= QEvent::User);
QCOMPARE(NGLHelpEvent::helpEventId(), type);
// sendHelpEvent dispatches to qApp; an event filter on qApp observes it
NGLHelpEventFilter filter;
qApp->installEventFilter(&filter);
NGLHelpEvent::sendHelpEvent(QStringLiteral("ctx-42"));
qApp->removeEventFilter(&filter);
QCOMPARE(filter.receivedContext, QStringLiteral("ctx-42"));
}
void ngltools_unit_test::filesystemRemoveDirContents()
{
// The temporary dir is created under the working directory (which is never
// empty) instead of the default /tmp: removeDirContentsRecursively(base, true)
// ends with QDir::rmpath, which also removes the empty parent directories
// ("the opposite of mkpath") — a base directly under an empty /tmp would
// cascade up and remove /tmp itself, breaking any later QTemporaryDir.
QTemporaryDir tmp(QDir::current().absolutePath() + QStringLiteral("/ngl_ut_XXXXXX"));
QVERIFY(tmp.isValid());
const QString base = tmp.path();
QDir().mkpath(base + QStringLiteral("/sub/nested"));
{
QFile f1(base + QStringLiteral("/file1.txt"));
QVERIFY(f1.open(QIODevice::WriteOnly));
f1.write(QByteArrayLiteral("12345"));
}
{
QFile f2(base + QStringLiteral("/sub/file2.txt"));
QVERIFY(f2.open(QIODevice::WriteOnly));
f2.write(QByteArrayLiteral("67890"));
}
{
QFile f3(base + QStringLiteral("/sub/nested/file3.txt"));
QVERIFY(f3.open(QIODevice::WriteOnly));
f3.write(QByteArrayLiteral("abcde"));
}
// removing the contents keeps the base directory
QVERIFY(NGL::removeDirContentsRecursively(base));
QVERIFY(QDir(base).exists());
QCOMPARE(QDir(base).entryList(QDir::NoDotAndDotDot | QDir::AllEntries).size(), 0);
// a non-existent directory fails
QVERIFY(!NGL::removeDirContentsRecursively(base + QStringLiteral("/nowhere")));
// recreate and remove including the base directory
QDir().mkpath(base + QStringLiteral("/sub"));
{
QFile f1(base + QStringLiteral("/file1.txt"));
QVERIFY(f1.open(QIODevice::WriteOnly));
f1.write(QByteArrayLiteral("x"));
}
QVERIFY(NGL::removeDirContentsRecursively(base, true));
QVERIFY(!QDir(base).exists());
}
void ngltools_unit_test::filesystemCopyDirContents()
{
// The temporary dir is created under the working directory (which is never
// empty) instead of the default /tmp: removeDirContentsRecursively(base, true)
// ends with QDir::rmpath, which also removes the empty parent directories
// ("the opposite of mkpath") — a base directly under an empty /tmp would
// cascade up and remove /tmp itself, breaking any later QTemporaryDir.
QTemporaryDir tmp(QDir::current().absolutePath() + QStringLiteral("/ngl_ut_XXXXXX"));
QVERIFY(tmp.isValid());
const QString src = tmp.path() + QStringLiteral("/src");
const QString dst = tmp.path() + QStringLiteral("/dst");
QDir().mkpath(src + QStringLiteral("/nested"));
{
QFile f1(src + QStringLiteral("/file1.txt"));
QVERIFY(f1.open(QIODevice::WriteOnly));
f1.write(QByteArrayLiteral("content1"));
}
{
QFile f2(src + QStringLiteral("/nested/file2.txt"));
QVERIFY(f2.open(QIODevice::WriteOnly));
f2.write(QByteArrayLiteral("content2"));
}
// the destination is created automatically
QVERIFY(NGL::copyDirContentsToDir(src, dst));
{
QFile f1(dst + QStringLiteral("/file1.txt"));
QVERIFY(f1.exists());
QVERIFY(f1.open(QIODevice::ReadOnly));
QCOMPARE(f1.readAll(), QByteArrayLiteral("content1"));
}
{
QFile f2(dst + QStringLiteral("/nested/file2.txt"));
QVERIFY(f2.exists());
QVERIFY(f2.open(QIODevice::ReadOnly));
QCOMPARE(f2.readAll(), QByteArrayLiteral("content2"));
}
// copying again overwrites existing files
{
QFile f1(src + QStringLiteral("/file1.txt"));
QVERIFY(f1.open(QIODevice::WriteOnly));
f1.write(QByteArrayLiteral("updated"));
}
QVERIFY(NGL::copyDirContentsToDir(src, dst));
{
QFile f1(dst + QStringLiteral("/file1.txt"));
QVERIFY(f1.open(QIODevice::ReadOnly));
QCOMPARE(f1.readAll(), QByteArrayLiteral("updated"));
}
}
void ngltools_unit_test::filesystemGetDirectorySize()
{
// The temporary dir is created under the working directory (which is never
// empty) instead of the default /tmp: removeDirContentsRecursively(base, true)
// ends with QDir::rmpath, which also removes the empty parent directories
// ("the opposite of mkpath") — a base directly under an empty /tmp would
// cascade up and remove /tmp itself, breaking any later QTemporaryDir.
QTemporaryDir tmp(QDir::current().absolutePath() + QStringLiteral("/ngl_ut_XXXXXX"));
QVERIFY(tmp.isValid());
const QString base = tmp.path();
// an empty directory: only its own (inode) size
const qint64 emptySize = NGL::getDirectorySize(base);
QCOMPARE(emptySize, QFileInfo(base).size());
// adding files and a subdirectory: the size grows by exactly their sizes
// plus the subdirectory's own inode size (the recursion visits every level)
QDir().mkpath(base + QStringLiteral("/sub"));
{
QFile f1(base + QStringLiteral("/file1.txt"));
QVERIFY(f1.open(QIODevice::WriteOnly));
QVERIFY(f1.write(QByteArray(100, 'a')) == 100);
}
{
QFile f2(base + QStringLiteral("/sub/file2.txt"));
QVERIFY(f2.open(QIODevice::WriteOnly));
QVERIFY(f2.write(QByteArray(50, 'b')) == 50);
}
const qint64 expect = QFileInfo(base).size() + 100
+ QFileInfo(base + QStringLiteral("/sub")).size() + 50;
QCOMPARE(NGL::getDirectorySize(base), expect);
}
QTEST_MAIN(ngltools_unit_test)
#include "ngltools_unit_test.moc"
@@ -0,0 +1,24 @@
#
# Unit tests for the ngltranslator module.
# One test executable per module, each registered with ctest.
#
if (NOT BUILD_TESTING)
return()
endif()
# --- ngltranslator: translation catalog, plural/disambiguation and locale.
# --- The Translator class (ngltranslator_p.h) has no export macro and the
# --- tree builds with hidden visibility, so its symbols are not exported
# --- from libngltranslator - the module source is compiled directly into the
# --- test (same pattern as the LogView test in TetraIF/unit-test).
if (TARGET ngltranslator)
ADD_EXECUTABLE(ngltranslator_unit_test
ngltranslator_unit_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../ngltranslator.cpp)
TARGET_LINK_LIBRARIES(ngltranslator_unit_test
ngltranslator
Qt6::Core
Qt6::Test
)
ADD_TEST(NAME ngltranslator_unit_test COMMAND $<TARGET_FILE:ngltranslator_unit_test>)
endif()
@@ -0,0 +1,310 @@
//
// Unit tests for the ngltranslator module (Z/src/ngltranslator): the Translator
// (QTranslator subclass) dynamic-translation catalog, JSON catalog parsing with
// md5 caching and compressed data, and locale handling via the public free
// functions.
//
// NOTE: a QCoreApplication is created in main() because the free functions in
// ngltranslator.cpp drive the global TranslationData instance, whose constructor
// calls QCoreApplication::installTranslator.
//
#include <ngltranslator/ngltranslator.h>
#include <ngltranslator/ngltranslator_p.h>
#include <QtCore/QByteArray>
#include <QtCore/QCoreApplication>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QVector>
#include <QtTest/QTest>
class ngltranslator_unit_test : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
// --- Translator instance: catalog + translate (pure logic) -------------
void testSetTranslationCatalogAndTranslate();
void testTranslateMissingContext();
void testTranslatePluralForm();
void testTranslateDisambiguation();
// --- Translator instance: JSON catalog parsing -------------------------
void testSetTranslationDataJsonValid();
void testSetTranslationDataJsonInvalid();
void testSetTranslationDataJsonMd5Cache();
void testSetTranslationDataJsonCompressed();
// --- Free functions: locale --------------------------------------------
void testTranslationLocaleInitial();
void testSetTranslationLocale();
void testSetTranslationLocaleShortCircuit();
};
void ngltranslator_unit_test::initTestCase()
{
// Nothing global to set up; each test uses a local NGL::Translator instance
// or the documented global-state behaviour of the free functions.
}
void ngltranslator_unit_test::cleanupTestCase()
{
}
// --- Translator instance: catalog + translate -----------------------------
void ngltranslator_unit_test::testSetTranslationCatalogAndTranslate()
{
NGL::Translator t;
NGL::TranslationCatalog catalog;
NGL::TranslationEntry e1;
e1.isoCode = "de_DE";
e1.context = "Main";
e1.key = "Hello";
e1.disambiguation = "";
e1.translation = QStringLiteral("Hallo");
catalog.append(e1);
NGL::TranslationEntry e2;
e2.isoCode = "de_DE";
e2.context = "Main";
e2.key = "Bye";
e2.disambiguation = "";
e2.translation = QStringLiteral("Tschüss");
catalog.append(e2);
NGL::TranslationEntry e3;
e3.isoCode = "fr_FR";
e3.context = "Main";
e3.key = "Bonjour";
e3.disambiguation = "";
e3.translation = QStringLiteral("Bon jour");
catalog.append(e3);
t.setTranslationCatalog(catalog);
t.isoCodeChanged("de_DE");
QCOMPARE(t.translate("Main", "Hello"), QStringLiteral("Hallo"));
QCOMPARE(t.translate("Main", "Bye"), QStringLiteral("Tschüss"));
// fr_FR entry is not in the de_DE lookup
QCOMPARE(t.translate("Main", "Bonjour"), QString());
}
void ngltranslator_unit_test::testTranslateMissingContext()
{
NGL::Translator t;
NGL::TranslationCatalog catalog;
NGL::TranslationEntry e;
e.isoCode = "de_DE";
e.context = "Main";
e.key = "Hello";
e.disambiguation = "";
e.translation = QStringLiteral("Hallo");
catalog.append(e);
t.setTranslationCatalog(catalog);
t.isoCodeChanged("de_DE");
QCOMPARE(t.translate("Nonexistent", "Hello"), QString());
}
void ngltranslator_unit_test::testTranslatePluralForm()
{
NGL::Translator t;
NGL::TranslationCatalog catalog;
NGL::TranslationEntry e;
e.isoCode = "de_DE";
e.context = "Main";
e.key = "Hello";
e.disambiguation = "";
e.translation = QStringLiteral("Hallo");
catalog.append(e);
t.setTranslationCatalog(catalog);
t.isoCodeChanged("de_DE");
// n != -1 means plural form, which the dynamic translator does not support
QCOMPARE(t.translate("Main", "Hello", nullptr, 2), QString());
QCOMPARE(t.translate("Main", "Hello", nullptr, -1), QStringLiteral("Hallo"));
}
void ngltranslator_unit_test::testTranslateDisambiguation()
{
NGL::Translator t;
NGL::TranslationCatalog catalog;
NGL::TranslationEntry e1;
e1.isoCode = "de_DE";
e1.context = "Main";
e1.key = "Item";
e1.disambiguation = "first";
e1.translation = QStringLiteral("Erstes");
catalog.append(e1);
NGL::TranslationEntry e2;
e2.isoCode = "de_DE";
e2.context = "Main";
e2.key = "Item";
e2.disambiguation = "second";
e2.translation = QStringLiteral("Zweites");
catalog.append(e2);
t.setTranslationCatalog(catalog);
t.isoCodeChanged("de_DE");
QCOMPARE(t.translate("Main", "Item", "first"), QStringLiteral("Erstes"));
QCOMPARE(t.translate("Main", "Item", "second"), QStringLiteral("Zweites"));
QCOMPARE(t.translate("Main", "Item", nullptr), QString());
}
// --- Translator instance: JSON catalog parsing ----------------------------
void ngltranslator_unit_test::testSetTranslationDataJsonValid()
{
NGL::Translator t;
QJsonObject entry1;
entry1[QLatin1String("isoCode")] = QLatin1String("de_DE");
entry1[QLatin1String("context")] = QLatin1String("Main");
entry1[QLatin1String("key")] = QLatin1String("Hello");
entry1[QLatin1String("disambiguation")] = QLatin1String("");
entry1[QLatin1String("translation")] = QLatin1String("Hallo");
QJsonObject entry2;
entry2[QLatin1String("isoCode")] = QLatin1String("de_DE");
entry2[QLatin1String("context")] = QLatin1String("Main");
entry2[QLatin1String("key")] = QLatin1String("Bye");
entry2[QLatin1String("disambiguation")] = QLatin1String("");
entry2[QLatin1String("translation")] = QStringLiteral("Tschüss");
QJsonArray arr;
arr.append(entry1);
arr.append(entry2);
QJsonObject root;
root[QLatin1String("translations")] = arr;
const QByteArray jsonData = QJsonDocument(root).toJson(QJsonDocument::Compact);
// Successful parse returns false (see ngltranslator.cpp); the catalog is
// populated regardless.
QCOMPARE(t.setTranslationDataJson(jsonData, "md5_1", false), false);
t.isoCodeChanged("de_DE");
QCOMPARE(t.translate("Main", "Hello"), QStringLiteral("Hallo"));
QCOMPARE(t.translate("Main", "Bye"), QStringLiteral("Tschüss"));
}
void ngltranslator_unit_test::testSetTranslationDataJsonInvalid()
{
NGL::Translator t;
// Case a: empty JSON data
QCOMPARE(t.setTranslationDataJson(QByteArray(), "md5_a", false), false);
// Case b: JSON without "translations" key
QJsonObject noKey;
noKey[QLatin1String("foo")] = QLatin1String("bar");
QCOMPARE(t.setTranslationDataJson(QJsonDocument(noKey).toJson(QJsonDocument::Compact),
"md5_b", false), false);
// Case c: "translations" is not an array
QJsonObject badType;
badType[QLatin1String("translations")] = QLatin1String("notanarray");
QCOMPARE(t.setTranslationDataJson(QJsonDocument(badType).toJson(QJsonDocument::Compact),
"md5_c", false), false);
// Catalog remains empty in all invalid cases
t.isoCodeChanged("de_DE");
QCOMPARE(t.translate("Main", "Hello"), QString());
}
void ngltranslator_unit_test::testSetTranslationDataJsonMd5Cache()
{
NGL::Translator t;
QJsonObject entry;
entry[QLatin1String("isoCode")] = QLatin1String("de_DE");
entry[QLatin1String("context")] = QLatin1String("Main");
entry[QLatin1String("key")] = QLatin1String("Hello");
entry[QLatin1String("disambiguation")] = QLatin1String("");
entry[QLatin1String("translation")] = QLatin1String("Hallo");
QJsonArray arr;
arr.append(entry);
QJsonObject root;
root[QLatin1String("translations")] = arr;
const QByteArray jsonData = QJsonDocument(root).toJson(QJsonDocument::Compact);
// First call: new md5, successful parse, returns false
QCOMPARE(t.setTranslationDataJson(jsonData, "md5_X", false), false);
// Second call: same md5, cache hit, returns true
QCOMPARE(t.setTranslationDataJson(jsonData, "md5_X", false), true);
// Third call: different md5, re-parses, returns false
QCOMPARE(t.setTranslationDataJson(jsonData, "md5_Y", false), false);
}
void ngltranslator_unit_test::testSetTranslationDataJsonCompressed()
{
NGL::Translator t;
QJsonObject entry;
entry[QLatin1String("isoCode")] = QLatin1String("de_DE");
entry[QLatin1String("context")] = QLatin1String("Main");
entry[QLatin1String("key")] = QLatin1String("Hello");
entry[QLatin1String("disambiguation")] = QLatin1String("");
entry[QLatin1String("translation")] = QLatin1String("Hallo");
QJsonArray arr;
arr.append(entry);
QJsonObject root;
root[QLatin1String("translations")] = arr;
const QByteArray raw = QJsonDocument(root).toJson(QJsonDocument::Compact);
const QByteArray compressed = qCompress(raw, 9);
QCOMPARE(t.setTranslationDataJson(compressed, "md5_Z", true), false);
t.isoCodeChanged("de_DE");
QCOMPARE(t.translate("Main", "Hello"), QStringLiteral("Hallo"));
}
// --- Free functions: locale ------------------------------------------------
void ngltranslator_unit_test::testTranslationLocaleInitial()
{
// At the start of the process the global locale is empty
QCOMPARE(NGL::translationLocale(), QByteArray());
}
void ngltranslator_unit_test::testSetTranslationLocale()
{
// No .qm translation files exist in the test environment, so ltsTranslator
// stays empty and the function returns false. But the locale is recorded.
const bool ret = NGL::setTranslationLocale("de_DE");
Q_UNUSED(ret);
QCOMPARE(NGL::translationLocale(), QByteArray("de_DE"));
}
void ngltranslator_unit_test::testSetTranslationLocaleShortCircuit()
{
// First call sets the locale (may return false if no .qm files found)
NGL::setTranslationLocale("de_DE", QStringLiteral("tds"));
// Second call with the same isoCode and prefix short-circuits and returns true
QCOMPARE(NGL::setTranslationLocale("de_DE", QStringLiteral("tds")), true);
// Different prefix does not short-circuit
QCOMPARE(NGL::setTranslationLocale("de_DE", QStringLiteral("other")), false);
QCOMPARE(NGL::translationLocale(), QByteArray("de_DE"));
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
ngltranslator_unit_test tc;
return QTest::qExec(&tc, argc, argv);
}
#include "ngltranslator_unit_test.moc"