Some refactor

This commit is contained in:
Agel committed 2026-04-08 14:01:03 +02:00
1 parent 7ecb7f4f4f
commit 9280c838b2
37 files changed
+1599 -981

No files matched your search

+87 -402
View File
@@ -1,437 +1,122 @@
#include <QtTest>
#include <QSignalSpy>
#include <QDir>
#include <QSettings>
#include <QTemporaryFile>
#include "backend/AppState.h"
#include "backend/LibraryModel.h"
class AppStateTest : public QObject {
Q_OBJECT
private slots:
void initTestCase()
void freshSettingsWriteVersion()
{
QCoreApplication::setOrganizationName(QStringLiteral("AsteriaTest"));
QCoreApplication::setApplicationName(QStringLiteral("AppStateTest"));
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-test-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState state(s);
QCOMPARE(s.value(QStringLiteral("version")).toInt(), AppState::SETTINGS_VERSION);
}
void cleanup()
void staleVersionClearsSettings()
{
QSettings().clear();
}
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-stale-XXXXXX.ini"));
f.open(); f.close();
void saveAndRestoreLastFilePath()
{
{
AppState state;
state.setLastFilePath(QStringLiteral("/books/test.epub"));
state.save();
QSettings s(f.fileName(), QSettings::IniFormat);
s.setValue(QStringLiteral("version"), 0);
s.setValue(QStringLiteral("someOldKey"), QStringLiteral("data"));
}
AppState state2;
state2.restore();
QCOMPARE(state2.lastFilePath(), QStringLiteral("/books/test.epub"));
QSettings s2(f.fileName(), QSettings::IniFormat);
AppState state(s2);
QVERIFY(!s2.contains(QStringLiteral("someOldKey")));
QCOMPARE(s2.value(QStringLiteral("version")).toInt(), AppState::SETTINGS_VERSION);
}
void saveAndRestoreMargins()
void saveAndLoadSection()
{
{
AppState state;
state.setHorizontalMargin(64);
state.setVerticalMargin(24);
state.save();
}
AppState state2;
state2.restore();
QCOMPARE(state2.horizontalMargin(), 64);
QCOMPARE(state2.verticalMargin(), 24);
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-sec-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState state(s);
QVariantMap data;
data[QStringLiteral("foo")] = 42;
data[QStringLiteral("bar")] = QStringLiteral("hello");
state.saveSection(QStringLiteral("test"), data);
const QVariantMap loaded = state.loadSection(QStringLiteral("test"));
QCOMPARE(loaded.value(QStringLiteral("foo")).toInt(), 42);
QCOMPARE(loaded.value(QStringLiteral("bar")).toString(), QStringLiteral("hello"));
}
void saveAndRestoreFontSize()
void saveSectionOverwritesPrevious()
{
{
AppState state;
state.setFontSize(22);
state.save();
}
AppState state2;
state2.restore();
QCOMPARE(state2.fontSize(), 22);
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-over-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState state(s);
state.saveSection(QStringLiteral("g"), {{QStringLiteral("old"), 1}});
state.saveSection(QStringLiteral("g"), {{QStringLiteral("new"), 2}});
const QVariantMap loaded = state.loadSection(QStringLiteral("g"));
QVERIFY(!loaded.contains(QStringLiteral("old")));
QCOMPARE(loaded.value(QStringLiteral("new")).toInt(), 2);
}
void saveAndRestoreLineSpacing()
void saveAndLoadArray()
{
{
AppState state;
state.setLineSpacing(2.0);
state.save();
}
AppState state2;
state2.restore();
QCOMPARE(state2.lineSpacing(), 2.0);
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-arr-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState state(s);
QList<QVariantMap> items;
items.append({{QStringLiteral("filePath"), QStringLiteral("/a/b.epub")},
{QStringLiteral("progress"), 0.5}});
items.append({{QStringLiteral("filePath"), QStringLiteral("/c/d.txt")},
{QStringLiteral("progress"), 0.0}});
state.saveArray(QStringLiteral("library"), items);
const auto loaded = state.loadArray(QStringLiteral("library"));
QCOMPARE(loaded.size(), 2);
QCOMPARE(loaded[0].value(QStringLiteral("filePath")).toString(), QStringLiteral("/a/b.epub"));
QCOMPARE(loaded[0].value(QStringLiteral("progress")).toDouble(), 0.5);
QCOMPARE(loaded[1].value(QStringLiteral("filePath")).toString(), QStringLiteral("/c/d.txt"));
}
void saveAndRestoreWindowGeometry()
void emptyArrayReturnsEmptyList()
{
{
AppState state;
state.setWindowWidth(1280);
state.setWindowHeight(800);
state.setWindowX(100);
state.setWindowY(50);
state.save();
}
AppState state2;
state2.restore();
QCOMPARE(state2.windowWidth(), 1280);
QCOMPARE(state2.windowHeight(), 800);
QCOMPARE(state2.windowX(), 100);
QCOMPARE(state2.windowY(), 50);
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-earr-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState state(s);
QCOMPARE(state.loadArray(QStringLiteral("nonexistent")).size(), 0);
}
void restoreWithNoSavedData()
void nestedSectionKey()
{
AppState state;
state.restore();
QVERIFY(state.lastFilePath().isEmpty());
QCOMPARE(state.horizontalMargin(), 32);
QCOMPARE(state.verticalMargin(), 8);
QCOMPARE(state.fontSize(), 16);
QCOMPARE(state.lineSpacing(), 1.6);
QCOMPARE(state.windowWidth(), 1024);
QCOMPARE(state.windowHeight(), 768);
QCOMPARE(state.windowX(), -1);
QCOMPARE(state.windowY(), -1);
}
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/asteria-nest-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState state(s);
void settersEmitSignals()
{
AppState state;
QSignalSpy spyFilePath(&state, &AppState::lastFilePathChanged);
QSignalSpy spyHMargin(&state, &AppState::horizontalMarginChanged);
QSignalSpy spyVMargin(&state, &AppState::verticalMarginChanged);
QSignalSpy spyFontSize(&state, &AppState::fontSizeChanged);
QSignalSpy spyLineSpacing(&state, &AppState::lineSpacingChanged);
QSignalSpy spyWidth(&state, &AppState::windowWidthChanged);
QSignalSpy spyHeight(&state, &AppState::windowHeightChanged);
QSignalSpy spyX(&state, &AppState::windowXChanged);
QSignalSpy spyY(&state, &AppState::windowYChanged);
const QString nestedSection = QStringLiteral("saved-progress/abc123");
state.saveSection(nestedSection, {{QStringLiteral("chunkIndex"), 5}});
state.setLastFilePath(QStringLiteral("/foo.txt"));
state.setHorizontalMargin(64);
state.setVerticalMargin(24);
state.setFontSize(20);
state.setLineSpacing(2.0);
state.setWindowWidth(800);
state.setWindowHeight(600);
state.setWindowX(200);
state.setWindowY(150);
QCOMPARE(spyFilePath.count(), 1);
QCOMPARE(spyHMargin.count(), 1);
QCOMPARE(spyVMargin.count(), 1);
QCOMPARE(spyFontSize.count(), 1);
QCOMPARE(spyLineSpacing.count(), 1);
QCOMPARE(spyWidth.count(), 1);
QCOMPARE(spyHeight.count(), 1);
QCOMPARE(spyX.count(), 1);
QCOMPARE(spyY.count(), 1);
}
void saveAndLoadBookPosition()
{
AppState state;
state.saveBookPosition(QStringLiteral("/books/a.epub"), 5, 120);
QVariantMap pos = state.loadBookPosition(QStringLiteral("/books/a.epub"));
QCOMPARE(pos[QStringLiteral("chunkIndex")].toInt(), 5);
QCOMPARE(pos[QStringLiteral("intraChunkOffset")].toInt(), 120);
}
void loadBookPositionForUnknownBook()
{
AppState state;
QVariantMap pos = state.loadBookPosition(QStringLiteral("/books/unknown.epub"));
QCOMPARE(pos[QStringLiteral("chunkIndex")].toInt(), 0);
QCOMPARE(pos[QStringLiteral("intraChunkOffset")].toInt(), 0);
}
void saveBookPositionForMultipleBooks()
{
AppState state;
state.saveBookPosition(QStringLiteral("/books/a.epub"), 10, 50);
state.saveBookPosition(QStringLiteral("/books/b.epub"), 20, 200);
QVariantMap posA = state.loadBookPosition(QStringLiteral("/books/a.epub"));
QVariantMap posB = state.loadBookPosition(QStringLiteral("/books/b.epub"));
QCOMPARE(posA[QStringLiteral("chunkIndex")].toInt(), 10);
QCOMPARE(posA[QStringLiteral("intraChunkOffset")].toInt(), 50);
QCOMPARE(posB[QStringLiteral("chunkIndex")].toInt(), 20);
QCOMPARE(posB[QStringLiteral("intraChunkOffset")].toInt(), 200);
}
void saveBookPositionOverwritesPrevious()
{
AppState state;
state.saveBookPosition(QStringLiteral("/books/a.epub"), 10, 50);
state.saveBookPosition(QStringLiteral("/books/a.epub"), 15, 88);
QVariantMap pos = state.loadBookPosition(QStringLiteral("/books/a.epub"));
QCOMPARE(pos[QStringLiteral("chunkIndex")].toInt(), 15);
QCOMPARE(pos[QStringLiteral("intraChunkOffset")].toInt(), 88);
}
void restoreEmitsSingleSignal()
{
AppState state;
QSignalSpy spyRestored(&state, &AppState::stateRestored);
QSignalSpy spyFilePath(&state, &AppState::lastFilePathChanged);
QSignalSpy spyHMargin(&state, &AppState::horizontalMarginChanged);
QSignalSpy spyVMargin(&state, &AppState::verticalMarginChanged);
QSignalSpy spyFontSize(&state, &AppState::fontSizeChanged);
QSignalSpy spyLineSpacing(&state, &AppState::lineSpacingChanged);
QSignalSpy spyWidth(&state, &AppState::windowWidthChanged);
QSignalSpy spyHeight(&state, &AppState::windowHeightChanged);
QSignalSpy spyX(&state, &AppState::windowXChanged);
QSignalSpy spyY(&state, &AppState::windowYChanged);
QSignalSpy spyTheme(&state, &AppState::themeNameChanged);
state.restore();
QCOMPARE(spyRestored.count(), 1);
QCOMPARE(spyFilePath.count(), 0);
QCOMPARE(spyHMargin.count(), 0);
QCOMPARE(spyVMargin.count(), 0);
QCOMPARE(spyFontSize.count(), 0);
QCOMPARE(spyLineSpacing.count(), 0);
QCOMPARE(spyWidth.count(), 0);
QCOMPARE(spyHeight.count(), 0);
QCOMPARE(spyX.count(), 0);
QCOMPARE(spyY.count(), 0);
QCOMPARE(spyTheme.count(), 0);
}
void saveAndRestoreThemeName()
{
{
AppState state;
state.setThemeName(QStringLiteral("light"));
state.save();
}
AppState state2;
state2.restore();
QCOMPARE(state2.themeName(), QStringLiteral("light"));
}
void themeNameDefaultsToDark()
{
AppState state;
QCOMPARE(state.themeName(), QStringLiteral("dark"));
}
void themeNameSetterEmitsSignal()
{
AppState state;
QSignalSpy spy(&state, &AppState::themeNameChanged);
state.setThemeName(QStringLiteral("light"));
QCOMPARE(spy.count(), 1);
}
void themeNameSetterDoesNotEmitForSameValue()
{
AppState state;
QSignalSpy spy(&state, &AppState::themeNameChanged);
state.setThemeName(QStringLiteral("dark")); // Same as default
QCOMPARE(spy.count(), 0);
}
// Library tests
void saveAndRestoreLastPage()
{
{
AppState state;
state.setLastPage(QStringLiteral("library"));
state.save();
}
AppState state2;
state2.restore();
QCOMPARE(state2.lastPage(), QStringLiteral("library"));
}
void lastPageDefaultsToStarter()
{
AppState state;
QCOMPARE(state.lastPage(), QStringLiteral("starter"));
}
void libraryBooksInitiallyEmpty()
{
AppState state;
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QVERIFY(model->rowCount() == 0);
}
void addLibraryBookAddsEntry()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.0);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
// Get data from the model
QModelIndex index = model->index(0);
QString filePath = model->data(index, LibraryModel::FilePathRole).toString();
double progress = model->data(index, LibraryModel::ProgressRole).toDouble();
QCOMPARE(filePath, QStringLiteral("/books/a.epub"));
QCOMPARE(progress, 0.0);
// Title and author are now loaded asynchronously from file metadata
// QString title = model->data(index, 2).toString(); // TitleRole = 2
// QString author = model->data(index, 3).toString(); // AuthorRole = 3
// QCOMPARE(title, QStringLiteral("Title A"));
// QCOMPARE(author, QStringLiteral("Author A"));
}
void addLibraryBookPersistsThroughSaveRestore()
{
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.5);
state.save();
}
AppState state2;
state2.restore();
auto* model = qobject_cast<QAbstractListModel*>(state2.libraryModel());
QCOMPARE(model->rowCount(), 1);
QModelIndex index = model->index(0);
QString filePath = model->data(index, LibraryModel::FilePathRole).toString();
double progress = model->data(index, LibraryModel::ProgressRole).toDouble();
QCOMPARE(filePath, QStringLiteral("/books/a.epub"));
// Title is now loaded asynchronously from file metadata
// QString title = model->data(index, 2).toString(); // TitleRole = 2
// QCOMPARE(title, QStringLiteral("Title A"));
QCOMPARE(progress, 0.5);
}
void addLibraryBookUpdatesMetadata()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.3);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.3);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
QModelIndex index = model->index(0);
// Title and author are now loaded asynchronously from file metadata
// QString title = model->data(index, 2).toString(); // TitleRole = 2
// QString author = model->data(index, 3).toString(); // AuthorRole = 3
// QCOMPARE(title, QStringLiteral("New Title"));
// QCOMPARE(author, QStringLiteral("New Author"));
}
void addLibraryBookOverwritesProgress()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.6);
// Lower value should overwrite (always update, no max logic)
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.2);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
QModelIndex index = model->index(0);
double progress = model->data(index, LibraryModel::ProgressRole).toDouble();
QCOMPARE(progress, 0.2);
}
void addLibraryBookSentinelPreservesProgress()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.5);
// -1.0 sentinel: update metadata but don't touch progress
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), -1.0);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
QModelIndex index = model->index(0);
double progress = model->data(index, LibraryModel::ProgressRole).toDouble();
QCOMPARE(progress, 0.5);
// Title is now loaded asynchronously from file metadata
// QString title = model->data(index, 2).toString(); // TitleRole = 2
// QCOMPARE(title, QStringLiteral("New Title"));
}
void addNewLibraryBookWithSentinelStartsAtZero()
{
AppState state;
// New book added with sentinel should start at 0%
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), -1.0);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
QModelIndex index = model->index(0);
double progress = model->data(index, LibraryModel::ProgressRole).toDouble();
QCOMPARE(progress, 0.0);
}
void removeLibraryBookRemovesEntry()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.5);
state.addOrUpdateLibraryBook(QStringLiteral("/books/b.epub"), 0.3);
state.removeLibraryBook(QStringLiteral("/books/a.epub"));
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
QModelIndex index = model->index(0);
QString filePath = model->data(index, LibraryModel::FilePathRole).toString();
QCOMPARE(filePath, QStringLiteral("/books/b.epub"));
}
void removeNonexistentLibraryBookIsNoop()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.5);
state.removeLibraryBook(QStringLiteral("/books/nonexistent.epub"));
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
}
void libraryBooksChangedSignalOnAdd()
{
AppState state;
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QSignalSpy spy(model, &QAbstractListModel::rowsInserted);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.0);
QCOMPARE(spy.count(), 1);
}
void libraryBooksChangedSignalOnRemove()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.0);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QSignalSpy spy(model, &QAbstractListModel::rowsRemoved);
state.removeLibraryBook(QStringLiteral("/books/a.epub"));
QCOMPARE(spy.count(), 1);
}
void multipleLibraryBooksAreStoredInOrder()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.1);
state.addOrUpdateLibraryBook(QStringLiteral("/books/b.epub"), 0.2);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 2);
// Most recently added/updated comes first
QModelIndex index0 = model->index(0);
QModelIndex index1 = model->index(1);
QString filePath0 = model->data(index0, LibraryModel::FilePathRole).toString();
QString filePath1 = model->data(index1, LibraryModel::FilePathRole).toString();
QCOMPARE(filePath0, QStringLiteral("/books/b.epub"));
QCOMPARE(filePath1, QStringLiteral("/books/a.epub"));
const QVariantMap loaded = state.loadSection(nestedSection);
QCOMPARE(loaded.value(QStringLiteral("chunkIndex")).toInt(), 5);
}
};
+51 -27
View File
@@ -1,7 +1,12 @@
#include <QtTest>
#include <QDir>
#include <QSettings>
#include <QSignalSpy>
#include <QTemporaryFile>
#include "backend/AppState.h"
#include "backend/ReadingModel.h"
#include "backend/FormatReader.h"
#include "backend/state/BookPositionStore.h"
// A fake reader that has 3 chapters, 2 chunks each → 6 total chunks
class FakeReader : public FormatReader {
@@ -25,6 +30,7 @@ public:
QString author() override { return QStringLiteral("Fake Author"); }
QString filePath() override { return QStringLiteral("/fake/path.txt"); }
QString coverImagePath() override { return {}; }
QByteArray contentHash() override { return QByteArray("fakehash"); }
bool loadMetadata(const QString &) override { return true; }
};
@@ -39,16 +45,34 @@ public:
QString author() override { return {}; }
QString filePath() override { return QStringLiteral("/fake/single.txt"); }
QString coverImagePath() override { return {}; }
QByteArray contentHash() override { return QByteArray("singlehash"); }
bool loadMetadata(const QString &) override { return true; }
};
class ReadingModelTest : public QObject {
Q_OBJECT
private:
struct Ctx {
QTemporaryFile f;
QSettings *s = nullptr;
AppState *appState = nullptr;
BookPositionStore *store = nullptr;
Ctx() {
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/rm-test-XXXXXX.ini"));
f.open(); f.close();
s = new QSettings(f.fileName(), QSettings::IniFormat);
appState = new AppState(*s);
store = new BookPositionStore(*appState);
}
~Ctx() { delete store; delete appState; delete s; }
};
private slots:
void initialState()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
QCOMPARE(model.totalChapters(), 0);
QCOMPARE(model.progress(), 0.0);
QVERIFY(model.chapterTitle().isEmpty());
@@ -57,7 +81,7 @@ private slots:
void setReaderLoadsAllChapters()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
@@ -70,7 +94,7 @@ private slots:
void chunkContentAcrossChapters()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
@@ -93,7 +117,7 @@ private slots:
void dataInvalidForOutOfRange()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
@@ -103,7 +127,7 @@ private slots:
void currentChapterDerivedFromScroll()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
@@ -126,7 +150,7 @@ private slots:
void chapterChangedSignalOnScroll()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
@@ -147,7 +171,7 @@ private slots:
void goToChapterEmitsScrollSignal()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
@@ -164,7 +188,7 @@ private slots:
void goToChapterOutOfRangeNoSignal()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
@@ -176,7 +200,7 @@ private slots:
void nextChapterEmitsScrollSignal()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
@@ -189,7 +213,7 @@ private slots:
void nextChapterAtEndNoSignal()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
model.setScrollInfo(4, 0.0); // chapter 2
@@ -201,7 +225,7 @@ private slots:
void previousChapterEmitsScrollSignal()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
model.setScrollInfo(4, 0.0); // chapter 2
@@ -214,7 +238,7 @@ private slots:
void previousChapterAtStartNoSignal()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
@@ -225,7 +249,7 @@ private slots:
void setReaderNull()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
model.setReader(nullptr);
@@ -238,7 +262,7 @@ private slots:
void roleNamesContainsContent()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
QHash<int, QByteArray> roles = model.roleNames();
QVERIFY(roles.contains(ReadingModel::ContentRole));
QCOMPARE(roles.value(ReadingModel::ContentRole), QByteArray("content"));
@@ -246,14 +270,14 @@ private slots:
void initialPageState()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
QCOMPARE(model.currentPage(), 0);
QCOMPARE(model.totalPages(), 0);
}
void setScrollInfoUpdatesCurrentPage()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
@@ -270,7 +294,7 @@ private slots:
void hasChaptersFalseForSingleChapter()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
SingleChapterReader reader;
model.setReader(&reader);
@@ -279,7 +303,7 @@ private slots:
void hasChaptersTrueForMultipleChapters()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
model.setReader(&reader);
@@ -288,7 +312,7 @@ private slots:
void hasChaptersFalseInitially()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
QVERIFY(!model.hasChapters());
}
@@ -297,7 +321,7 @@ private slots:
void coverImagePrependedToChunks()
{
FakeReader reader;
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
model.setCoverImageUrl("image://epub/OEBPS/cover.jpg");
model.setReader(&reader);
@@ -313,7 +337,7 @@ private slots:
void coverImageNotAddedWhenUrlEmpty()
{
FakeReader reader;
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
model.setReader(&reader);
model.setCoverImageUrl("");
@@ -324,7 +348,7 @@ private slots:
void chapterNavigationSkipsCoverImage()
{
FakeReader reader;
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
model.setCoverImageUrl("image://epub/OEBPS/cover.jpg");
model.setReader(&reader);
@@ -343,7 +367,7 @@ private slots:
void coverImageSetAfterReaderReloadsChunks()
{
FakeReader reader;
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
model.setReader(&reader);
QCOMPARE(model.rowCount(QModelIndex()), 6); // no cover yet
@@ -363,7 +387,7 @@ private slots:
void clearCoverImageUrlRemovesCover()
{
FakeReader reader;
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
model.setCoverImageUrl(QStringLiteral("image://epub/OEBPS/cover.jpg"));
model.setReader(&reader);
QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6
@@ -378,7 +402,7 @@ private slots:
void roleNamesHasNewRoles()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
auto roles = model.roleNames();
QVERIFY(roles.contains(ReadingModel::PixelHeightRole));
QVERIFY(roles.contains(ReadingModel::ChapterRole));
@@ -388,13 +412,13 @@ private slots:
void totalPixelHeightInitiallyZero()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
QCOMPARE(model.totalPixelHeight(), 0.0);
}
void totalPixelHeightResetOnReaderSet()
{
ReadingModel model;
Ctx ctx; ReadingModel model(*ctx.store);
FakeReader reader;
QSignalSpy spy(&model, &ReadingModel::totalPixelHeightChanged);
+221
View File
@@ -0,0 +1,221 @@
#include <QtTest>
#include <QDir>
#include <QSettings>
#include <QSignalSpy>
#include <QTemporaryFile>
#include "backend/AppState.h"
#include "backend/IFileDialogService.h"
#include "backend/state/BookPositionStore.h"
#include "backend/book/Book.h"
// Minimal fake dialog service — never opens a dialog; used to satisfy the Book constructor.
class FakeDialogService : public IFileDialogService {
Q_OBJECT
public:
explicit FakeDialogService(QObject *parent = nullptr) : IFileDialogService(parent) {}
void open() override { /* no-op */ }
void triggerFile(const QString &path) { emit fileSelected(path); }
};
class BookTest : public QObject {
Q_OBJECT
private:
static QString epubFixture()
{
#ifdef FIXTURES_DIR
return QStringLiteral(FIXTURES_DIR) + QStringLiteral("/sample.epub");
#else
return QString();
#endif
}
static QString txtFixture()
{
#ifdef FIXTURES_DIR
return QStringLiteral(FIXTURES_DIR) + QStringLiteral("/sample.txt");
#else
return QString();
#endif
}
struct Ctx {
QTemporaryFile f;
QSettings *s = nullptr;
AppState *appState = nullptr;
BookPositionStore *store = nullptr;
FakeDialogService *dialog = nullptr;
Book *book = nullptr;
Ctx() {
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/book-test-XXXXXX.ini"));
f.open(); f.close();
s = new QSettings(f.fileName(), QSettings::IniFormat);
appState = new AppState(*s);
store = new BookPositionStore(*appState);
dialog = new FakeDialogService;
book = new Book(*dialog, *store);
}
~Ctx() {
delete book;
delete dialog;
delete store;
delete appState;
delete s;
}
};
private slots:
void initialState()
{
Ctx ctx;
QVERIFY(!ctx.book->hasBook());
QVERIFY(!ctx.book->loading());
QCOMPARE(ctx.book->title(), QString());
QCOMPARE(ctx.book->author(), QString());
QCOMPARE(ctx.book->filePath(), QString());
QCOMPARE(ctx.book->coverImageUrl(),QString());
QCOMPARE(ctx.book->errorMessage(), QString());
QVERIFY(ctx.book->toc().isEmpty());
}
void openValidTxtFile()
{
const QString path = txtFixture();
if (path.isEmpty() || !QFileInfo::exists(path))
QSKIP("No TXT fixture");
Ctx ctx;
QSignalSpy bookChanged(ctx.book, &Book::bookChanged);
QSignalSpy loading(ctx.book, &Book::loadingChanged);
ctx.book->openFromPath(path);
// loading should have become true
QVERIFY(loading.count() > 0 || ctx.book->loading());
// Wait for the async open to complete
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
QVERIFY(!ctx.book->loading());
QCOMPARE(ctx.book->filePath(), path);
QVERIFY(!ctx.book->title().isEmpty());
QVERIFY(bookChanged.count() > 0);
}
void openInvalidPath()
{
Ctx ctx;
QSignalSpy errorSpy(ctx.book, &Book::errorMessageChanged);
ctx.book->openFromPath(QStringLiteral("/nonexistent/file.txt"));
QTRY_VERIFY_WITH_TIMEOUT(!ctx.book->errorMessage().isEmpty(), 5000);
QVERIFY(!ctx.book->hasBook());
QVERIFY(!ctx.book->loading());
}
void clearError()
{
Ctx ctx;
ctx.book->openFromPath(QStringLiteral("/nonexistent/file.txt"));
QTRY_VERIFY_WITH_TIMEOUT(!ctx.book->errorMessage().isEmpty(), 5000);
QSignalSpy errorSpy(ctx.book, &Book::errorMessageChanged);
ctx.book->clearError();
QCOMPARE(ctx.book->errorMessage(), QString());
QCOMPARE(errorSpy.count(), 1);
}
void closeBook()
{
const QString path = txtFixture();
if (path.isEmpty() || !QFileInfo::exists(path))
QSKIP("No TXT fixture");
Ctx ctx;
ctx.book->openFromPath(path);
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
QSignalSpy bookChanged(ctx.book, &Book::bookChanged);
ctx.book->close();
QVERIFY(!ctx.book->hasBook());
QCOMPARE(bookChanged.count(), 1);
}
void willOpenNewBookFiredBeforeSwap()
{
const QString path = txtFixture();
if (path.isEmpty() || !QFileInfo::exists(path))
QSKIP("No TXT fixture");
Ctx ctx;
ctx.book->openFromPath(path);
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
QSignalSpy willOpen(ctx.book, &Book::willOpenNewBook);
ctx.book->openFromPath(path); // second open triggers willOpenNewBook
QCOMPARE(willOpen.count(), 1);
}
void openFromUrl()
{
const QString path = txtFixture();
if (path.isEmpty() || !QFileInfo::exists(path))
QSKIP("No TXT fixture");
Ctx ctx;
ctx.book->openFromUrl(QUrl::fromLocalFile(path));
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
QCOMPARE(ctx.book->filePath(), path);
}
void browseAndOpenDelegatesToDialog()
{
Ctx ctx;
QSignalSpy loading(ctx.book, &Book::loadingChanged);
const QString path = txtFixture();
if (path.isEmpty() || !QFileInfo::exists(path))
QSKIP("No TXT fixture");
// Simulate the dialog emitting fileSelected
ctx.book->browseAndOpen(); // calls dialog.open() which in FakeDialogService is a no-op
ctx.dialog->triggerFile(path);
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
}
void saveCurrentPositionUsesHash()
{
const QString path = txtFixture();
if (path.isEmpty() || !QFileInfo::exists(path))
QSKIP("No TXT fixture");
Ctx ctx;
ctx.book->openFromPath(path);
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
ctx.book->saveCurrentPosition(3, 17);
const QByteArray hash = ctx.book->reader()->contentHash();
QVERIFY(!hash.isEmpty());
const BookPosition pos = ctx.store->load(hash);
QCOMPARE(pos.chunkIndex, 3);
QCOMPARE(pos.intraOffset, 17);
}
void contentWidthSignal()
{
Ctx ctx;
QSignalSpy spy(ctx.book, &Book::contentWidthChanged);
ctx.book->setContentWidth(800);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.first().first().toInt(), 800);
ctx.book->setContentWidth(800); // no-op
QCOMPARE(spy.count(), 1);
}
};
QTEST_MAIN(BookTest)
#include "BookTest.moc"
+98
View File
@@ -0,0 +1,98 @@
#include <QtTest>
#include <QByteArray>
#include <QDir>
#include <QSettings>
#include <QTemporaryFile>
#include "backend/AppState.h"
#include "backend/state/BookPositionStore.h"
class BookPositionStoreTest : public QObject {
Q_OBJECT
private slots:
void defaultPositionForUnknownHash()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/bps-def-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
BookPositionStore store(appState);
const BookPosition pos = store.load(QByteArray("nonexistent"));
QCOMPARE(pos.chunkIndex, 0);
QCOMPARE(pos.intraOffset, 0);
}
void saveAndLoad()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/bps-sr-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
BookPositionStore store(appState);
const QByteArray hash = QByteArray("abc123deadbeef");
store.save(hash, 7, 42);
const BookPosition pos = store.load(hash);
QCOMPARE(pos.chunkIndex, 7);
QCOMPARE(pos.intraOffset, 42);
}
void separateHashesStoredIndependently()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/bps-sep-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
BookPositionStore store(appState);
store.save(QByteArray("hash1"), 1, 10);
store.save(QByteArray("hash2"), 2, 20);
QCOMPARE(store.load(QByteArray("hash1")).chunkIndex, 1);
QCOMPARE(store.load(QByteArray("hash2")).chunkIndex, 2);
QCOMPARE(store.load(QByteArray("hash1")).intraOffset, 10);
QCOMPARE(store.load(QByteArray("hash2")).intraOffset, 20);
}
void overwriteExistingPosition()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/bps-ow-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
BookPositionStore store(appState);
const QByteArray hash = QByteArray("overwrite-hash");
store.save(hash, 3, 30);
store.save(hash, 5, 55);
const BookPosition pos = store.load(hash);
QCOMPARE(pos.chunkIndex, 5);
QCOMPARE(pos.intraOffset, 55);
}
void emptyHashIgnored()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/bps-empty-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
BookPositionStore store(appState);
// Neither save nor load should crash with an empty hash
store.save(QByteArray(), 1, 1);
const BookPosition pos = store.load(QByteArray());
QCOMPARE(pos.chunkIndex, 0);
QCOMPARE(pos.intraOffset, 0);
}
};
QTEST_MAIN(BookPositionStoreTest)
#include "BookPositionStoreTest.moc"
+81
View File
@@ -0,0 +1,81 @@
#include <QtTest>
#include <QDir>
#include <QFile>
#include <QSettings>
#include <QTemporaryFile>
#include "backend/AppState.h"
#include "backend/state/ReadingPreferences.h"
class ReadingPreferencesTest : public QObject {
Q_OBJECT
private slots:
void defaultsWhenEmpty()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/rp-def-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
ReadingPreferences prefs(appState);
QCOMPARE(prefs.fontSize(), 16);
QCOMPARE(prefs.lineSpacing(), 1.6);
QCOMPARE(prefs.horizontalMargin(), 32);
QCOMPARE(prefs.verticalMargin(), 8);
}
void saveAndRestore()
{
QString fileName;
{
QTemporaryFile tmp;
tmp.setFileTemplate(QDir::tempPath() + QStringLiteral("/rp-sr-XXXXXX.ini"));
tmp.setAutoRemove(false);
QVERIFY(tmp.open());
fileName = tmp.fileName();
}
{
QSettings s(fileName, QSettings::IniFormat);
AppState appState(s);
ReadingPreferences prefs(appState);
prefs.setFontSize(20);
prefs.setLineSpacing(2.0);
prefs.setHorizontalMargin(48);
prefs.setVerticalMargin(16);
prefs.save();
}
QSettings s2(fileName, QSettings::IniFormat);
AppState appState2(s2);
ReadingPreferences prefs2(appState2);
QCOMPARE(prefs2.fontSize(), 20);
QCOMPARE(prefs2.lineSpacing(), 2.0);
QCOMPARE(prefs2.horizontalMargin(), 48);
QCOMPARE(prefs2.verticalMargin(), 16);
QFile::remove(fileName);
}
void fontSizeSignal()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/rp-sig-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
ReadingPreferences prefs(appState);
QSignalSpy spy(&prefs, &ReadingPreferences::fontSizeChanged);
prefs.setFontSize(18);
QCOMPARE(spy.count(), 1);
prefs.setFontSize(18); // no-op
QCOMPARE(spy.count(), 1);
}
};
QTEST_MAIN(ReadingPreferencesTest)
#include "ReadingPreferencesTest.moc"
+109
View File
@@ -0,0 +1,109 @@
#include <QtTest>
#include <QDir>
#include <QFile>
#include <QSettings>
#include <QTemporaryFile>
#include "backend/AppState.h"
#include "backend/state/UiState.h"
class UiStateTest : public QObject {
Q_OBJECT
private slots:
void defaultsWhenEmpty()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/ui-def-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
UiState ui(appState);
QCOMPARE(ui.themeName(), QStringLiteral("dark"));
QCOMPARE(ui.lastPage(), QStringLiteral("starter"));
QCOMPARE(ui.sidebarOpen(), false);
QCOMPARE(ui.lastFilePath(), QString());
QCOMPARE(ui.windowWidth(), 1024);
QCOMPARE(ui.windowHeight(), 768);
QCOMPARE(ui.windowX(), -1);
QCOMPARE(ui.windowY(), -1);
}
void saveAndRestore()
{
QString fileName;
{
QTemporaryFile tmp;
tmp.setFileTemplate(QDir::tempPath() + QStringLiteral("/ui-sr-XXXXXX.ini"));
tmp.setAutoRemove(false);
QVERIFY(tmp.open());
fileName = tmp.fileName();
}
{
QSettings s(fileName, QSettings::IniFormat);
AppState appState(s);
UiState ui(appState);
ui.setThemeName(QStringLiteral("light"));
ui.setLastPage(QStringLiteral("settings"));
ui.setSidebarOpen(true);
ui.setLastFilePath(QStringLiteral("/some/file.epub"));
ui.setWindowWidth(1280);
ui.setWindowHeight(800);
ui.setWindowX(100);
ui.setWindowY(50);
ui.save();
}
QSettings s2(fileName, QSettings::IniFormat);
AppState appState2(s2);
UiState ui2(appState2);
QCOMPARE(ui2.themeName(), QStringLiteral("light"));
QCOMPARE(ui2.lastPage(), QStringLiteral("settings"));
QCOMPARE(ui2.sidebarOpen(), true);
QCOMPARE(ui2.lastFilePath(), QStringLiteral("/some/file.epub"));
QCOMPARE(ui2.windowWidth(), 1280);
QCOMPARE(ui2.windowHeight(), 800);
QCOMPARE(ui2.windowX(), 100);
QCOMPARE(ui2.windowY(), 50);
QFile::remove(fileName);
}
void lastFilePathSignal()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/ui-sig-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
UiState ui(appState);
QSignalSpy spy(&ui, &UiState::lastFilePathChanged);
ui.setLastFilePath(QStringLiteral("/a/b"));
QCOMPARE(spy.count(), 1);
ui.setLastFilePath(QStringLiteral("/a/b")); // no-op
QCOMPARE(spy.count(), 1);
}
void windowWidthSignal()
{
QTemporaryFile f;
f.setFileTemplate(QDir::tempPath() + QStringLiteral("/ui-sig-w-XXXXXX.ini"));
f.open(); f.close();
QSettings s(f.fileName(), QSettings::IniFormat);
AppState appState(s);
UiState ui(appState);
QSignalSpy spy(&ui, &UiState::windowWidthChanged);
ui.setWindowWidth(999);
QCOMPARE(spy.count(), 1);
ui.setWindowWidth(999); // no-op
QCOMPARE(spy.count(), 1);
}
};
QTEST_MAIN(UiStateTest)
#include "UiStateTest.moc"