File indexing completed on 2024-04-14 03:43:51

0001 #ifndef TESTHELPERS_H
0002 #define TESTHELPERS_H
0003 
0004 #include "config-kstars.h"
0005 
0006 #include <QObject>
0007 #include <QTest>
0008 #include <QStandardPaths>
0009 
0010 #include "kstars.h"
0011 #include "kspaths.h"
0012 
0013 /** @brief Helper to clean application user folders when in test mode.
0014  *
0015  * It verifies that App(Data|Config|Cache)Location folders can be removed, that KSPaths::writableLocation
0016  * will not recreate them by itself and that those folders can be recreated manually.
0017  *
0018  * @param recreate is a boolean that requires the helper to recreate the application user folders after removal.
0019  */
0020 #define KTEST_CLEAN_TEST(recreate) do { \
0021     if (!QStandardPaths::isTestModeEnabled()) \
0022         qFatal("Helper KTEST_CLEAN_TEST only works in test mode."); \
0023     QList<QStandardPaths::StandardLocation> const locs = { \
0024         QStandardPaths::AppLocalDataLocation, \
0025         QStandardPaths::AppConfigLocation, \
0026         QStandardPaths::CacheLocation }; \
0027     for (auto loc: locs) { \
0028         QString const path = KSPaths::writableLocation(loc); \
0029         if (!QDir(path).removeRecursively()) \
0030             qFatal("Local application location '%s' must be removable.", qPrintable(path)); \
0031         if (QDir(KSPaths::writableLocation(loc)).exists()) \
0032             qFatal("Local application location '%s' must not exist after having been removed.", qPrintable(path)); \
0033         if (recreate) \
0034             if (!QDir(path).mkpath(".")) \
0035                 qFatal("Local application location '%s' must be recreatable.", qPrintable(path)); \
0036         }} while(false)
0037 
0038 #define KTEST_CLEAN_RCFILE() do { \
0039     if (!QStandardPaths::isTestModeEnabled()) \
0040         qFatal("Helper KTEST_CLEAN_RCFILE only works in test mode."); \
0041     QString const rcfilepath = KSPaths::locate(QStandardPaths::GenericConfigLocation, qAppName() + "rc"); \
0042     if (!rcfilepath.isEmpty() && QFileInfo(rcfilepath).exists()) { \
0043         if (!QFile(rcfilepath).remove()) \
0044             qFatal("Local application location RC file must be removable."); \
0045     }} while(false)
0046 
0047 /** @brief Helper to begin a test.
0048  *
0049  * For now, this puts the application paths in test mode, and removes and recreates
0050  * the three application user folders.
0051  */
0052 #define KTEST_BEGIN() do { \
0053     QStandardPaths::setTestModeEnabled(true); \
0054     KTEST_CLEAN_TEST(true); \
0055     KTEST_CLEAN_RCFILE(); } while(false)
0056 
0057 /** @brief Helper to end a test.
0058  *
0059  * For now, this removes the three application user folders.
0060  */
0061 #define KTEST_END() do { \
0062     KTEST_CLEAN_RCFILE(); \
0063     KTEST_CLEAN_TEST(false); } while(false)
0064 
0065 #endif // TESTHELPERS_H