1186 lines
48 KiB
C++
1186 lines
48 KiB
C++
#include <QtTest>
|
|
#include <QTemporaryDir>
|
|
#include <QFile>
|
|
#include <QDomDocument>
|
|
#include <minizip/zip.h>
|
|
|
|
#include "backend/formats/Fb2Reader.h"
|
|
#include "backend/formats/EpubReader.h"
|
|
#include "backend/formats/sources/ZipByteSource.h"
|
|
#include "backend/formats/Fb2Types.h"
|
|
#include "backend/formats/sources/Fb2ByteSource.h"
|
|
#include "backend/formats/ImageUrl.h"
|
|
#include "backend/reading/layout/CssParser.h"
|
|
#include "backend/reading/layout/HtmlBlockParser.h"
|
|
#include "backend/reading/layout/ChunkLayoutEngine.h"
|
|
|
|
// Spec Entities and Surface
|
|
struct ReaderClient {
|
|
QString name;
|
|
bool operator==(const ReaderClient &o) const { return name == o.name; }
|
|
};
|
|
|
|
struct Fb2BookEntity {
|
|
ReaderClient client;
|
|
QString file_path;
|
|
QString extension_kind; // "fb2", "fbz", "fb2.zip"
|
|
Fb2ContainerKind container_kind = Fb2ContainerKind::plain_xml;
|
|
HistoryFormatLabel format_label = HistoryFormatLabel::FB2;
|
|
Fb2LoadStatus status = Fb2LoadStatus::idle;
|
|
|
|
// Loaded fields
|
|
std::optional<QString> content_hash;
|
|
std::optional<QString> title;
|
|
std::optional<QVector<AuthorName>> authors;
|
|
std::optional<QString> author;
|
|
std::optional<QString> cover_image_url;
|
|
std::optional<QVector<ContentChunkValue>> chunks;
|
|
std::optional<QVector<BinaryResource>> binaries;
|
|
|
|
// Failed field
|
|
std::optional<QString> error_message;
|
|
|
|
HistoryFormatLabel expected_format_label() const
|
|
{
|
|
if (extension_kind == QLatin1String("fbz"))
|
|
return HistoryFormatLabel::FBZ;
|
|
return HistoryFormatLabel::FB2;
|
|
}
|
|
};
|
|
|
|
class Fb2FormatReaderSurface {
|
|
public:
|
|
ReaderClient client;
|
|
Fb2BookEntity book;
|
|
|
|
bool is_actor_accessible(const ReaderClient &actor) const
|
|
{
|
|
return actor.name == client.name;
|
|
}
|
|
|
|
bool can_provide_OpenFb2Requested() const
|
|
{
|
|
return book.status == Fb2LoadStatus::idle;
|
|
}
|
|
|
|
bool can_provide_LoadFb2MetadataRequested() const
|
|
{
|
|
return book.status == Fb2LoadStatus::idle;
|
|
}
|
|
|
|
bool can_provide_InspectZipArchive() const
|
|
{
|
|
return (book.status == Fb2LoadStatus::loading_metadata || book.status == Fb2LoadStatus::loading_full)
|
|
&& book.container_kind == Fb2ContainerKind::zip_archive;
|
|
}
|
|
|
|
bool can_provide_Fb2XmlParsed() const
|
|
{
|
|
return book.status == Fb2LoadStatus::loading_metadata || book.status == Fb2LoadStatus::loading_full;
|
|
}
|
|
|
|
bool can_provide_Fb2MetadataExtracted() const
|
|
{
|
|
return book.status == Fb2LoadStatus::loading_metadata;
|
|
}
|
|
|
|
bool can_provide_Fb2DocumentParsed() const
|
|
{
|
|
return book.status == Fb2LoadStatus::loading_full;
|
|
}
|
|
|
|
// Rules
|
|
bool startOpenFb2Book(const ReaderClient &actor)
|
|
{
|
|
if (actor.name != client.name || book.status != Fb2LoadStatus::idle)
|
|
return false;
|
|
book.status = Fb2LoadStatus::loading_full;
|
|
return true;
|
|
}
|
|
|
|
bool startLoadFb2Metadata(const ReaderClient &actor)
|
|
{
|
|
if (actor.name != client.name || book.status != Fb2LoadStatus::idle)
|
|
return false;
|
|
book.status = Fb2LoadStatus::loading_metadata;
|
|
return true;
|
|
}
|
|
|
|
bool resolveZipContainerEntry(const ReaderClient &actor, const QStringList &archive_entries)
|
|
{
|
|
if (actor.name != client.name)
|
|
return false;
|
|
if (book.status != Fb2LoadStatus::loading_metadata && book.status != Fb2LoadStatus::loading_full)
|
|
return false;
|
|
if (book.container_kind != Fb2ContainerKind::zip_archive)
|
|
return false;
|
|
if (!archive_entries.isEmpty())
|
|
return false;
|
|
|
|
book.status = Fb2LoadStatus::failed;
|
|
book.error_message = QStringLiteral("Archive contains no readable FB2 entry");
|
|
return true;
|
|
}
|
|
|
|
bool failOnInvalidOrMalformedXml(const ReaderClient &actor, bool is_well_formed_xml, const QString &root_tag_name)
|
|
{
|
|
if (actor.name != client.name)
|
|
return false;
|
|
if (book.status != Fb2LoadStatus::loading_metadata && book.status != Fb2LoadStatus::loading_full)
|
|
return false;
|
|
if (is_well_formed_xml && root_tag_name == QLatin1String("FictionBook"))
|
|
return false;
|
|
|
|
book.status = Fb2LoadStatus::failed;
|
|
book.error_message = QStringLiteral("Invalid or malformed FictionBook XML");
|
|
return true;
|
|
}
|
|
|
|
bool completeMetadataLoad(const ReaderClient &actor,
|
|
const QString &hash_md5,
|
|
const QString &raw_book_title,
|
|
const QString &filename_stem,
|
|
const QVector<AuthorName> &parsed_authors,
|
|
const QString &formatted_authors,
|
|
const std::optional<QString> &resolved_cover_id,
|
|
const QVector<BinaryResource> &binary_resources)
|
|
{
|
|
if (actor.name != client.name || book.status != Fb2LoadStatus::loading_metadata)
|
|
return false;
|
|
|
|
book.status = Fb2LoadStatus::loaded;
|
|
book.content_hash = hash_md5;
|
|
book.title = !raw_book_title.isEmpty() ? raw_book_title : filename_stem;
|
|
book.authors = parsed_authors;
|
|
book.author = formatted_authors;
|
|
if (resolved_cover_id.has_value()) {
|
|
book.cover_image_url = ImageUrl::build(QStringLiteral("fb2"), resolved_cover_id.value(), book.file_path);
|
|
} else {
|
|
book.cover_image_url = std::nullopt;
|
|
}
|
|
book.chunks = QVector<ContentChunkValue>{};
|
|
book.binaries = binary_resources;
|
|
return true;
|
|
}
|
|
|
|
bool completeFullOpenWithSections(const ReaderClient &actor,
|
|
const QString &hash_md5,
|
|
const QString &raw_book_title,
|
|
const QString &filename_stem,
|
|
const QVector<AuthorName> &parsed_authors,
|
|
const QString &formatted_authors,
|
|
const std::optional<QString> &resolved_cover_id,
|
|
const QVector<BinaryResource> &binary_resources,
|
|
const QVector<ContentChunkValue> &extracted_chunks)
|
|
{
|
|
if (actor.name != client.name || book.status != Fb2LoadStatus::loading_full || extracted_chunks.isEmpty())
|
|
return false;
|
|
|
|
book.status = Fb2LoadStatus::loaded;
|
|
book.content_hash = hash_md5;
|
|
book.title = !raw_book_title.isEmpty() ? raw_book_title : filename_stem;
|
|
book.authors = parsed_authors;
|
|
book.author = formatted_authors;
|
|
if (resolved_cover_id.has_value()) {
|
|
book.cover_image_url = ImageUrl::build(QStringLiteral("fb2"), resolved_cover_id.value(), book.file_path);
|
|
} else {
|
|
book.cover_image_url = std::nullopt;
|
|
}
|
|
book.chunks = extracted_chunks;
|
|
book.binaries = binary_resources;
|
|
return true;
|
|
}
|
|
|
|
bool completeFullOpenWithEmptyBodyFallback(const ReaderClient &actor,
|
|
const QString &hash_md5,
|
|
const QString &raw_book_title,
|
|
const QString &filename_stem,
|
|
const QVector<AuthorName> &parsed_authors,
|
|
const QString &formatted_authors,
|
|
const std::optional<QString> &resolved_cover_id,
|
|
const QVector<BinaryResource> &binary_resources,
|
|
const QVector<ContentChunkValue> &extracted_chunks)
|
|
{
|
|
if (actor.name != client.name || book.status != Fb2LoadStatus::loading_full || !extracted_chunks.isEmpty())
|
|
return false;
|
|
|
|
book.status = Fb2LoadStatus::loaded;
|
|
book.content_hash = hash_md5;
|
|
book.title = !raw_book_title.isEmpty() ? raw_book_title : filename_stem;
|
|
book.authors = parsed_authors;
|
|
book.author = formatted_authors;
|
|
if (resolved_cover_id.has_value()) {
|
|
book.cover_image_url = ImageUrl::build(QStringLiteral("fb2"), resolved_cover_id.value(), book.file_path);
|
|
} else {
|
|
book.cover_image_url = std::nullopt;
|
|
}
|
|
ContentChunkValue fallbackChunk{book.file_path, 1, 0, 0, 0};
|
|
book.chunks = QVector<ContentChunkValue>{fallbackChunk};
|
|
book.binaries = binary_resources;
|
|
return true;
|
|
}
|
|
};
|
|
|
|
static bool createZipArchive(const QString &zipPath, const QHash<QString, QByteArray> &entries)
|
|
{
|
|
zipFile zf = zipOpen64(zipPath.toUtf8().constData(), APPEND_STATUS_CREATE);
|
|
if (!zf) return false;
|
|
|
|
for (auto it = entries.constBegin(); it != entries.constEnd(); ++it) {
|
|
zip_fileinfo zi{};
|
|
int err = zipOpenNewFileInZip(zf, it.key().toUtf8().constData(), &zi, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, Z_DEFAULT_COMPRESSION);
|
|
if (err != ZIP_OK) {
|
|
zipClose(zf, nullptr);
|
|
return false;
|
|
}
|
|
err = zipWriteInFileInZip(zf, it.value().constData(), it.value().size());
|
|
zipCloseFileInZip(zf);
|
|
if (err < 0) {
|
|
zipClose(zf, nullptr);
|
|
return false;
|
|
}
|
|
}
|
|
zipClose(zf, nullptr);
|
|
return true;
|
|
}
|
|
|
|
class Fb2ReaderTest : public QObject {
|
|
Q_OBJECT
|
|
|
|
private slots:
|
|
// Obligation 1: value-equality.AuthorName
|
|
void testValueEqualityAuthorName()
|
|
{
|
|
AuthorName a1{QStringLiteral("Leo"), QStringLiteral("N."), QStringLiteral("Tolstoy"), std::nullopt};
|
|
AuthorName a2{QStringLiteral("Leo"), QStringLiteral("N."), QStringLiteral("Tolstoy"), std::nullopt};
|
|
AuthorName aDiffFirst{QStringLiteral("Alex"), QStringLiteral("N."), QStringLiteral("Tolstoy"), std::nullopt};
|
|
AuthorName aDiffNick{QStringLiteral("Leo"), QStringLiteral("N."), QStringLiteral("Tolstoy"), QStringLiteral("LN")};
|
|
|
|
QVERIFY(a1 == a2);
|
|
QVERIFY(!(a1 != a2));
|
|
QVERIFY(a1 != aDiffFirst);
|
|
QVERIFY(a1 != aDiffNick);
|
|
}
|
|
|
|
// Obligation 2: entity-fields.AuthorName
|
|
void testEntityFieldsAuthorName()
|
|
{
|
|
AuthorName a;
|
|
QVERIFY(!a.first_name.has_value());
|
|
QVERIFY(!a.middle_name.has_value());
|
|
QVERIFY(!a.last_name.has_value());
|
|
QVERIFY(!a.nickname.has_value());
|
|
QVERIFY(!a.has_structured_name());
|
|
|
|
a.first_name = QStringLiteral("Fyodor");
|
|
a.middle_name = QStringLiteral("Mikhailovich");
|
|
a.last_name = QStringLiteral("Dostoevsky");
|
|
a.nickname = QStringLiteral("FD");
|
|
|
|
QCOMPARE(a.first_name.value(), QStringLiteral("Fyodor"));
|
|
QCOMPARE(a.middle_name.value(), QStringLiteral("Mikhailovich"));
|
|
QCOMPARE(a.last_name.value(), QStringLiteral("Dostoevsky"));
|
|
QCOMPARE(a.nickname.value(), QStringLiteral("FD"));
|
|
QVERIFY(a.has_structured_name());
|
|
|
|
AuthorName nickOnly{std::nullopt, std::nullopt, std::nullopt, QStringLiteral("Strugatsky")};
|
|
QVERIFY(!nickOnly.has_structured_name());
|
|
QCOMPARE(nickOnly.format(), QStringLiteral("Strugatsky"));
|
|
}
|
|
|
|
// Obligation 3: value-equality.BinaryResource
|
|
void testValueEqualityBinaryResource()
|
|
{
|
|
BinaryResource b1{QStringLiteral("cover.jpg"), QStringLiteral("image/jpeg"), QByteArray("bytes123")};
|
|
BinaryResource b2{QStringLiteral("cover.jpg"), QStringLiteral("image/jpeg"), QByteArray("bytes123")};
|
|
BinaryResource bDiffId{QStringLiteral("pic.png"), QStringLiteral("image/jpeg"), QByteArray("bytes123")};
|
|
BinaryResource bDiffType{QStringLiteral("cover.jpg"), QStringLiteral("image/png"), QByteArray("bytes123")};
|
|
BinaryResource bDiffData{QStringLiteral("cover.jpg"), QStringLiteral("image/jpeg"), QByteArray("other")};
|
|
|
|
QVERIFY(b1 == b2);
|
|
QVERIFY(!(b1 != b2));
|
|
QVERIFY(b1 != bDiffId);
|
|
QVERIFY(b1 != bDiffType);
|
|
QVERIFY(b1 != bDiffData);
|
|
}
|
|
|
|
// Obligation 4: entity-fields.BinaryResource
|
|
void testEntityFieldsBinaryResource()
|
|
{
|
|
BinaryResource b;
|
|
QVERIFY(b.id.isEmpty());
|
|
QVERIFY(!b.content_type.has_value());
|
|
QVERIFY(b.decoded_bytes.isEmpty());
|
|
|
|
b.id = QStringLiteral("img1");
|
|
b.content_type = QStringLiteral("image/png");
|
|
b.decoded_bytes = QByteArray("pngdata");
|
|
|
|
QCOMPARE(b.id, QStringLiteral("img1"));
|
|
QCOMPARE(b.content_type.value(), QStringLiteral("image/png"));
|
|
QCOMPARE(b.decoded_bytes, QByteArray("pngdata"));
|
|
}
|
|
|
|
// Obligation 5: value-equality.ContentChunkValue
|
|
void testValueEqualityContentChunkValue()
|
|
{
|
|
ContentChunkValue c1{QStringLiteral("sec1"), 5, 100, 500, 2};
|
|
ContentChunkValue c2{QStringLiteral("sec1"), 5, 100, 500, 2};
|
|
ContentChunkValue cDiffHref{QStringLiteral("sec2"), 5, 100, 500, 2};
|
|
ContentChunkValue cDiffBlocks{QStringLiteral("sec1"), 6, 100, 500, 2};
|
|
ContentChunkValue cDiffWords{QStringLiteral("sec1"), 5, 101, 500, 2};
|
|
ContentChunkValue cDiffChars{QStringLiteral("sec1"), 5, 100, 501, 2};
|
|
ContentChunkValue cDiffContainers{QStringLiteral("sec1"), 5, 100, 500, 3};
|
|
|
|
QVERIFY(c1 == c2);
|
|
QVERIFY(!(c1 != c2));
|
|
QVERIFY(c1 != cDiffHref);
|
|
QVERIFY(c1 != cDiffBlocks);
|
|
QVERIFY(c1 != cDiffWords);
|
|
QVERIFY(c1 != cDiffChars);
|
|
QVERIFY(c1 != cDiffContainers);
|
|
}
|
|
|
|
// Obligation 6: entity-fields.ContentChunkValue
|
|
void testEntityFieldsContentChunkValue()
|
|
{
|
|
ContentChunkValue c;
|
|
QVERIFY(c.section_href.isEmpty());
|
|
QCOMPARE(c.blocks_count, 0);
|
|
QCOMPARE(c.word_count, 0);
|
|
QCOMPARE(c.char_count, 0);
|
|
QCOMPARE(c.unnested_containers, 0);
|
|
|
|
c.section_href = QStringLiteral("body/s0");
|
|
c.blocks_count = 3;
|
|
c.word_count = 50;
|
|
c.char_count = 250;
|
|
c.unnested_containers = 1;
|
|
|
|
QCOMPARE(c.section_href, QStringLiteral("body/s0"));
|
|
QCOMPARE(c.blocks_count, 3);
|
|
QCOMPARE(c.word_count, 50);
|
|
QCOMPARE(c.char_count, 250);
|
|
QCOMPARE(c.unnested_containers, 1);
|
|
}
|
|
|
|
// Obligation 7: contract-signature.SharedDomChunkPipeline.cascade_and_chunk
|
|
void testContractSignatureSharedDomChunkPipeline()
|
|
{
|
|
// Verify parseChunks deterministic chunking invariant
|
|
QDomDocument doc1;
|
|
doc1.setContent(QStringLiteral("<div><p class=\"lead\">Paragraph in EPUB spine</p></div>"));
|
|
QDomElement root1 = doc1.documentElement();
|
|
|
|
QDomDocument doc2;
|
|
doc2.setContent(QStringLiteral("<div><p class=\"lead\">Paragraph in EPUB spine</p></div>"));
|
|
QDomElement root2 = doc2.documentElement();
|
|
|
|
QStringList stylesheets = {QStringLiteral("p.lead { font-weight: bold; text-align: center; }")};
|
|
const QString scheme = QStringLiteral("fb2");
|
|
const QString sourcePath = QStringLiteral("/books/test.fb2");
|
|
const QString sectionHref = QStringLiteral("sec1");
|
|
const int targetChars = 512;
|
|
|
|
Css::StyleSheet sheet = Css::StyleSheet::parse(stylesheets.first());
|
|
QVector<ContentChunk> chunks1 = HtmlBlockParser::parseChunks(
|
|
root1, sectionHref, targetChars, {}, &sheet, scheme, sourcePath);
|
|
QVector<ContentChunk> chunks2 = HtmlBlockParser::parseChunks(
|
|
root2, sectionHref, targetChars, {}, &sheet, scheme, sourcePath);
|
|
|
|
QCOMPARE(chunks1.size(), chunks2.size());
|
|
QVERIFY(!chunks1.isEmpty());
|
|
QCOMPARE(chunks1.first().sectionHref, chunks2.first().sectionHref);
|
|
QCOMPARE(chunks1.first().wordCount, chunks2.first().wordCount);
|
|
QCOMPARE(chunks1.first().charCount, chunks2.first().charCount);
|
|
QCOMPARE(chunks1.first().blocks.size(), chunks2.first().blocks.size());
|
|
|
|
ContentChunkValue cv1 = ContentChunkValue::fromChunk(chunks1.first());
|
|
ContentChunkValue cv2 = ContentChunkValue::fromChunk(chunks2.first());
|
|
QCOMPARE(cv1, cv2);
|
|
}
|
|
|
|
// Obligation 8: enum-comparable.Fb2ContainerKind
|
|
void testEnumComparableFb2ContainerKind()
|
|
{
|
|
Fb2ContainerKind k1 = Fb2ContainerKind::plain_xml;
|
|
Fb2ContainerKind k2 = Fb2ContainerKind::zip_archive;
|
|
QVERIFY(k1 != k2);
|
|
QVERIFY(k1 == Fb2ContainerKind::plain_xml);
|
|
}
|
|
|
|
// Obligation 9: enum-comparable.Fb2LoadStatus
|
|
void testEnumComparableFb2LoadStatus()
|
|
{
|
|
Fb2LoadStatus s1 = Fb2LoadStatus::idle;
|
|
Fb2LoadStatus s2 = Fb2LoadStatus::loading_metadata;
|
|
Fb2LoadStatus s3 = Fb2LoadStatus::loading_full;
|
|
Fb2LoadStatus s4 = Fb2LoadStatus::loaded;
|
|
Fb2LoadStatus s5 = Fb2LoadStatus::failed;
|
|
|
|
QVERIFY(s1 != s2 && s2 != s3 && s3 != s4 && s4 != s5);
|
|
QVERIFY(s1 == Fb2LoadStatus::idle);
|
|
}
|
|
|
|
// Obligation 10: enum-comparable.HistoryFormatLabel
|
|
void testEnumComparableHistoryFormatLabel()
|
|
{
|
|
HistoryFormatLabel l1 = HistoryFormatLabel::FB2;
|
|
HistoryFormatLabel l2 = HistoryFormatLabel::FBZ;
|
|
QVERIFY(l1 != l2);
|
|
QVERIFY(l1 == HistoryFormatLabel::FB2);
|
|
}
|
|
|
|
// Obligation 11: entity-fields.ReaderClient
|
|
void testEntityFieldsReaderClient()
|
|
{
|
|
ReaderClient client;
|
|
QVERIFY(client.name.isEmpty());
|
|
client.name = QStringLiteral("AsteriaReader");
|
|
QCOMPARE(client.name, QStringLiteral("AsteriaReader"));
|
|
}
|
|
|
|
// Obligations 12-19: when-presence.Fb2Book.*
|
|
void testWhenPresenceFields()
|
|
{
|
|
Fb2BookEntity book;
|
|
book.status = Fb2LoadStatus::idle;
|
|
|
|
// When idle, loaded & failed fields are absent
|
|
QVERIFY(!book.content_hash.has_value());
|
|
QVERIFY(!book.title.has_value());
|
|
QVERIFY(!book.authors.has_value());
|
|
QVERIFY(!book.author.has_value());
|
|
QVERIFY(!book.cover_image_url.has_value());
|
|
QVERIFY(!book.chunks.has_value());
|
|
QVERIFY(!book.binaries.has_value());
|
|
QVERIFY(!book.error_message.has_value());
|
|
|
|
// When loaded, loaded fields are present, error_message is absent
|
|
book.status = Fb2LoadStatus::loaded;
|
|
book.content_hash = QStringLiteral("hash123");
|
|
book.title = QStringLiteral("War and Peace");
|
|
book.authors = QVector<AuthorName>{};
|
|
book.author = QStringLiteral("Leo Tolstoy");
|
|
book.cover_image_url = QStringLiteral("image://fb2/cover.jpg");
|
|
book.chunks = QVector<ContentChunkValue>{};
|
|
book.binaries = QVector<BinaryResource>{};
|
|
|
|
QVERIFY(book.content_hash.has_value());
|
|
QVERIFY(book.title.has_value());
|
|
QVERIFY(book.authors.has_value());
|
|
QVERIFY(book.author.has_value());
|
|
QVERIFY(book.cover_image_url.has_value());
|
|
QVERIFY(book.chunks.has_value());
|
|
QVERIFY(book.binaries.has_value());
|
|
QVERIFY(!book.error_message.has_value());
|
|
|
|
// When failed, error_message is present, loaded fields absent
|
|
Fb2BookEntity failedBook;
|
|
failedBook.status = Fb2LoadStatus::failed;
|
|
failedBook.error_message = QStringLiteral("Error loading book");
|
|
|
|
QVERIFY(failedBook.error_message.has_value());
|
|
QVERIFY(!failedBook.content_hash.has_value());
|
|
QVERIFY(!failedBook.title.has_value());
|
|
QVERIFY(!failedBook.chunks.has_value());
|
|
}
|
|
|
|
// Obligations 20-25: transition-edge.Fb2Book.*
|
|
void testTransitionEdges()
|
|
{
|
|
ReaderClient client{QStringLiteral("Client1")};
|
|
|
|
// Edge 1: idle -> loading_metadata
|
|
{
|
|
Fb2FormatReaderSurface s;
|
|
s.client = client;
|
|
s.book.client = client;
|
|
s.book.status = Fb2LoadStatus::idle;
|
|
QVERIFY(s.startLoadFb2Metadata(client));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::loading_metadata);
|
|
|
|
// Edge 3: loading_metadata -> loaded
|
|
QVERIFY(s.completeMetadataLoad(client, "hash", "Title", "stem", {}, "Author", std::nullopt, {}));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::loaded);
|
|
}
|
|
|
|
// Edge 4: loading_metadata -> failed
|
|
{
|
|
Fb2FormatReaderSurface s;
|
|
s.client = client;
|
|
s.book.client = client;
|
|
s.book.status = Fb2LoadStatus::loading_metadata;
|
|
QVERIFY(s.failOnInvalidOrMalformedXml(client, false, QStringLiteral("corrupt")));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::failed);
|
|
}
|
|
|
|
// Edge 2: idle -> loading_full
|
|
{
|
|
Fb2FormatReaderSurface s;
|
|
s.client = client;
|
|
s.book.client = client;
|
|
s.book.status = Fb2LoadStatus::idle;
|
|
QVERIFY(s.startOpenFb2Book(client));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::loading_full);
|
|
|
|
// Edge 5: loading_full -> loaded
|
|
ContentChunkValue chunk{"sec1", 1, 10, 50, 0};
|
|
QVERIFY(s.completeFullOpenWithSections(client, "hash", "Title", "stem", {}, "Author", std::nullopt, {}, {chunk}));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::loaded);
|
|
}
|
|
|
|
// Edge 6: loading_full -> failed
|
|
{
|
|
Fb2FormatReaderSurface s;
|
|
s.client = client;
|
|
s.book.client = client;
|
|
s.book.status = Fb2LoadStatus::loading_full;
|
|
s.book.container_kind = Fb2ContainerKind::zip_archive;
|
|
QVERIFY(s.resolveZipContainerEntry(client, {}));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::failed);
|
|
}
|
|
}
|
|
|
|
// Obligations 26-27: transition-rejected.Fb2Book.status & transition-terminal
|
|
void testTransitionRejectedAndTerminal()
|
|
{
|
|
ReaderClient client{QStringLiteral("Client1")};
|
|
Fb2FormatReaderSurface s;
|
|
s.client = client;
|
|
s.book.client = client;
|
|
|
|
// Terminal state 'loaded' has no outbound transitions
|
|
s.book.status = Fb2LoadStatus::loaded;
|
|
QVERIFY(!s.startOpenFb2Book(client));
|
|
QVERIFY(!s.startLoadFb2Metadata(client));
|
|
QVERIFY(!s.can_provide_OpenFb2Requested());
|
|
QVERIFY(!s.can_provide_LoadFb2MetadataRequested());
|
|
|
|
// Terminal state 'failed' has no outbound transitions
|
|
s.book.status = Fb2LoadStatus::failed;
|
|
QVERIFY(!s.startOpenFb2Book(client));
|
|
QVERIFY(!s.startLoadFb2Metadata(client));
|
|
QVERIFY(!s.can_provide_OpenFb2Requested());
|
|
QVERIFY(!s.can_provide_LoadFb2MetadataRequested());
|
|
|
|
// Undeclared transition: loading_metadata directly to loading_full is rejected
|
|
s.book.status = Fb2LoadStatus::loading_metadata;
|
|
QVERIFY(!s.startOpenFb2Book(client));
|
|
}
|
|
|
|
// Obligation 28 & 29: entity-fields.Fb2Book & entity-optional.Fb2Book.cover_image_url
|
|
void testEntityFieldsFb2Book()
|
|
{
|
|
ReaderClient client{QStringLiteral("TestApp")};
|
|
Fb2BookEntity b;
|
|
b.client = client;
|
|
b.file_path = QStringLiteral("/path/to/doc.fb2");
|
|
b.extension_kind = QStringLiteral("fb2");
|
|
b.container_kind = Fb2ContainerKind::plain_xml;
|
|
b.format_label = HistoryFormatLabel::FB2;
|
|
b.status = Fb2LoadStatus::idle;
|
|
|
|
QCOMPARE(b.client.name, QStringLiteral("TestApp"));
|
|
QCOMPARE(b.file_path, QStringLiteral("/path/to/doc.fb2"));
|
|
QCOMPARE(b.extension_kind, QStringLiteral("fb2"));
|
|
QCOMPARE(b.container_kind, Fb2ContainerKind::plain_xml);
|
|
QCOMPARE(b.format_label, HistoryFormatLabel::FB2);
|
|
QCOMPARE(b.status, Fb2LoadStatus::idle);
|
|
|
|
// Optional cover_image_url
|
|
QVERIFY(!b.cover_image_url.has_value());
|
|
b.cover_image_url = QStringLiteral("image://fb2/cov.png?src=/path/to/doc.fb2");
|
|
QVERIFY(b.cover_image_url.has_value());
|
|
b.cover_image_url = std::nullopt;
|
|
QVERIFY(!b.cover_image_url.has_value());
|
|
}
|
|
|
|
// Obligations 30-31: config-default.target_chunk_chars & max_heading_depth
|
|
void testConfigDefaults()
|
|
{
|
|
const int target_chunk_chars = 512;
|
|
const int max_heading_depth = 6;
|
|
QCOMPARE(target_chunk_chars, 512);
|
|
QCOMPARE(max_heading_depth, 6);
|
|
}
|
|
|
|
// Obligations 32-34: rule-success/failure.StartOpenFb2Book
|
|
void testRuleStartOpenFb2Book()
|
|
{
|
|
ReaderClient c1{QStringLiteral("User")};
|
|
ReaderClient c2{QStringLiteral("Other")};
|
|
Fb2FormatReaderSurface s;
|
|
s.client = c1;
|
|
s.book.client = c1;
|
|
s.book.status = Fb2LoadStatus::idle;
|
|
|
|
// Failure 1: actor != client
|
|
QVERIFY(!s.startOpenFb2Book(c2));
|
|
|
|
// Failure 2: status != idle
|
|
s.book.status = Fb2LoadStatus::loading_full;
|
|
QVERIFY(!s.startOpenFb2Book(c1));
|
|
|
|
// Success
|
|
s.book.status = Fb2LoadStatus::idle;
|
|
QVERIFY(s.startOpenFb2Book(c1));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::loading_full);
|
|
}
|
|
|
|
// Obligations 35-37: rule-success/failure.StartLoadFb2Metadata
|
|
void testRuleStartLoadFb2Metadata()
|
|
{
|
|
ReaderClient c1{QStringLiteral("User")};
|
|
ReaderClient c2{QStringLiteral("Other")};
|
|
Fb2FormatReaderSurface s;
|
|
s.client = c1;
|
|
s.book.client = c1;
|
|
s.book.status = Fb2LoadStatus::idle;
|
|
|
|
// Failure 1: actor != client
|
|
QVERIFY(!s.startLoadFb2Metadata(c2));
|
|
|
|
// Failure 2: status != idle
|
|
s.book.status = Fb2LoadStatus::loaded;
|
|
QVERIFY(!s.startLoadFb2Metadata(c1));
|
|
|
|
// Success
|
|
s.book.status = Fb2LoadStatus::idle;
|
|
QVERIFY(s.startLoadFb2Metadata(c1));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::loading_metadata);
|
|
}
|
|
|
|
// Obligations 38-42: rule-success/failure.ResolveZipContainerEntry
|
|
void testRuleResolveZipContainerEntry()
|
|
{
|
|
ReaderClient c1{QStringLiteral("User")};
|
|
ReaderClient c2{QStringLiteral("Other")};
|
|
Fb2FormatReaderSurface s;
|
|
s.client = c1;
|
|
s.book.client = c1;
|
|
s.book.status = Fb2LoadStatus::loading_full;
|
|
s.book.container_kind = Fb2ContainerKind::zip_archive;
|
|
|
|
// Failure 1: actor != client
|
|
QVERIFY(!s.resolveZipContainerEntry(c2, {}));
|
|
|
|
// Failure 2: status not in {loading_metadata, loading_full}
|
|
s.book.status = Fb2LoadStatus::idle;
|
|
QVERIFY(!s.resolveZipContainerEntry(c1, {}));
|
|
s.book.status = Fb2LoadStatus::loading_full;
|
|
|
|
// Failure 3: container_kind != zip_archive
|
|
s.book.container_kind = Fb2ContainerKind::plain_xml;
|
|
QVERIFY(!s.resolveZipContainerEntry(c1, {}));
|
|
s.book.container_kind = Fb2ContainerKind::zip_archive;
|
|
|
|
// Failure 4: archive_entries.count != 0 (entries present)
|
|
QVERIFY(!s.resolveZipContainerEntry(c1, {QStringLiteral("book.fb2")}));
|
|
|
|
// Success: archive_entries is empty -> fails with specified error
|
|
QVERIFY(s.resolveZipContainerEntry(c1, {}));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::failed);
|
|
QCOMPARE(s.book.error_message.value(), QStringLiteral("Archive contains no readable FB2 entry"));
|
|
}
|
|
|
|
// Obligations 43-46: rule-success/failure.FailOnInvalidOrMalformedXml
|
|
void testRuleFailOnInvalidOrMalformedXml()
|
|
{
|
|
ReaderClient c1{QStringLiteral("User")};
|
|
ReaderClient c2{QStringLiteral("Other")};
|
|
Fb2FormatReaderSurface s;
|
|
s.client = c1;
|
|
s.book.client = c1;
|
|
s.book.status = Fb2LoadStatus::loading_full;
|
|
|
|
// Failure 1: actor != client
|
|
QVERIFY(!s.failOnInvalidOrMalformedXml(c2, false, ""));
|
|
|
|
// Failure 2: status not in {loading_metadata, loading_full}
|
|
s.book.status = Fb2LoadStatus::idle;
|
|
QVERIFY(!s.failOnInvalidOrMalformedXml(c1, false, ""));
|
|
s.book.status = Fb2LoadStatus::loading_full;
|
|
|
|
// Failure 3: well formed and root is FictionBook -> rule does not fire
|
|
QVERIFY(!s.failOnInvalidOrMalformedXml(c1, true, QStringLiteral("FictionBook")));
|
|
|
|
// Success 1: malformed XML
|
|
QVERIFY(s.failOnInvalidOrMalformedXml(c1, false, ""));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::failed);
|
|
QCOMPARE(s.book.error_message.value(), QStringLiteral("Invalid or malformed FictionBook XML"));
|
|
|
|
// Success 2: well formed but root is not FictionBook
|
|
s.book.status = Fb2LoadStatus::loading_full;
|
|
QVERIFY(s.failOnInvalidOrMalformedXml(c1, true, QStringLiteral("html")));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::failed);
|
|
QCOMPARE(s.book.error_message.value(), QStringLiteral("Invalid or malformed FictionBook XML"));
|
|
}
|
|
|
|
// Obligations 47-49: rule-success/failure.CompleteMetadataLoad
|
|
void testRuleCompleteMetadataLoad()
|
|
{
|
|
ReaderClient c1{QStringLiteral("User")};
|
|
ReaderClient c2{QStringLiteral("Other")};
|
|
Fb2FormatReaderSurface s;
|
|
s.client = c1;
|
|
s.book.client = c1;
|
|
s.book.file_path = QStringLiteral("/books/novel.fb2");
|
|
s.book.status = Fb2LoadStatus::loading_metadata;
|
|
|
|
// Failure 1: actor != client
|
|
QVERIFY(!s.completeMetadataLoad(c2, "hash", "Title", "novel", {}, "", std::nullopt, {}));
|
|
|
|
// Failure 2: status != loading_metadata
|
|
s.book.status = Fb2LoadStatus::idle;
|
|
QVERIFY(!s.completeMetadataLoad(c1, "hash", "Title", "novel", {}, "", std::nullopt, {}));
|
|
|
|
// Success
|
|
s.book.status = Fb2LoadStatus::loading_metadata;
|
|
QVERIFY(s.completeMetadataLoad(c1, "hash123", "", "novel", {}, "A. Author", QStringLiteral("cover.jpg"), {}));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::loaded);
|
|
QCOMPARE(s.book.title.value(), QStringLiteral("novel")); // title fallback to filename stem
|
|
QVERIFY(s.book.chunks.value().isEmpty()); // chunks empty on metadata load
|
|
QCOMPARE(s.book.cover_image_url.value(), QStringLiteral("image://fb2/cover.jpg?src=%2Fbooks%2Fnovel.fb2"));
|
|
}
|
|
|
|
// Obligations 50-53: rule-success/failure.CompleteFullOpenWithSections
|
|
void testRuleCompleteFullOpenWithSections()
|
|
{
|
|
ReaderClient c1{QStringLiteral("User")};
|
|
ReaderClient c2{QStringLiteral("Other")};
|
|
Fb2FormatReaderSurface s;
|
|
s.client = c1;
|
|
s.book.client = c1;
|
|
s.book.file_path = QStringLiteral("/books/novel.fb2");
|
|
s.book.status = Fb2LoadStatus::loading_full;
|
|
|
|
ContentChunkValue chunk{"sec1", 2, 20, 100, 0};
|
|
|
|
// Failure 1: actor != client
|
|
QVERIFY(!s.completeFullOpenWithSections(c2, "hash", "Title", "stem", {}, "", std::nullopt, {}, {chunk}));
|
|
|
|
// Failure 2: status != loading_full
|
|
s.book.status = Fb2LoadStatus::loading_metadata;
|
|
QVERIFY(!s.completeFullOpenWithSections(c1, "hash", "Title", "stem", {}, "", std::nullopt, {}, {chunk}));
|
|
s.book.status = Fb2LoadStatus::loading_full;
|
|
|
|
// Failure 3: extracted_chunks.count == 0
|
|
QVERIFY(!s.completeFullOpenWithSections(c1, "hash", "Title", "stem", {}, "", std::nullopt, {}, {}));
|
|
|
|
// Success
|
|
QVERIFY(s.completeFullOpenWithSections(c1, "hash999", "My Novel", "novel", {}, "Author", QStringLiteral("cov.png"), {}, {chunk}));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::loaded);
|
|
QCOMPARE(s.book.title.value(), QStringLiteral("My Novel"));
|
|
QCOMPARE(s.book.chunks.value().size(), 1);
|
|
}
|
|
|
|
// Obligations 54-57: rule-success/failure.CompleteFullOpenWithEmptyBodyFallback
|
|
void testRuleCompleteFullOpenWithEmptyBodyFallback()
|
|
{
|
|
ReaderClient c1{QStringLiteral("User")};
|
|
ReaderClient c2{QStringLiteral("Other")};
|
|
Fb2FormatReaderSurface s;
|
|
s.client = c1;
|
|
s.book.client = c1;
|
|
s.book.file_path = QStringLiteral("/books/empty.fb2");
|
|
s.book.status = Fb2LoadStatus::loading_full;
|
|
|
|
ContentChunkValue chunk{"sec1", 1, 0, 0, 0};
|
|
|
|
// Failure 1: actor != client
|
|
QVERIFY(!s.completeFullOpenWithEmptyBodyFallback(c2, "hash", "", "empty", {}, "", std::nullopt, {}, {}));
|
|
|
|
// Failure 2: status != loading_full
|
|
s.book.status = Fb2LoadStatus::idle;
|
|
QVERIFY(!s.completeFullOpenWithEmptyBodyFallback(c1, "hash", "", "empty", {}, "", std::nullopt, {}, {}));
|
|
s.book.status = Fb2LoadStatus::loading_full;
|
|
|
|
// Failure 3: extracted_chunks.count != 0 (rule only fires on empty chunks)
|
|
QVERIFY(!s.completeFullOpenWithEmptyBodyFallback(c1, "hash", "", "empty", {}, "", std::nullopt, {}, {chunk}));
|
|
|
|
// Success
|
|
QVERIFY(s.completeFullOpenWithEmptyBodyFallback(c1, "hash000", "", "empty", {}, "", std::nullopt, {}, {}));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::loaded);
|
|
QCOMPARE(s.book.chunks.value().size(), 1);
|
|
ContentChunkValue fallback = s.book.chunks.value().first();
|
|
QCOMPARE(fallback.section_href, QStringLiteral("/books/empty.fb2"));
|
|
QCOMPARE(fallback.blocks_count, 1);
|
|
QCOMPARE(fallback.word_count, 0);
|
|
QCOMPARE(fallback.char_count, 0);
|
|
}
|
|
|
|
// Obligation 58: invariant.LoadedBookHasNonEmptyTitle
|
|
void testInvariantLoadedBookHasNonEmptyTitle()
|
|
{
|
|
ReaderClient c{QStringLiteral("User")};
|
|
Fb2FormatReaderSurface s;
|
|
s.client = c;
|
|
s.book.client = c;
|
|
s.book.status = Fb2LoadStatus::loading_metadata;
|
|
|
|
// If raw_book_title is empty, title falls back to filename_stem ("fallback_title")
|
|
s.completeMetadataLoad(c, "hash", "", "fallback_title", {}, "", std::nullopt, {});
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::loaded);
|
|
QVERIFY(!s.book.title.value().isEmpty());
|
|
}
|
|
|
|
// Obligation 59: invariant.FormatLabelMatchesExtension
|
|
void testInvariantFormatLabelMatchesExtension()
|
|
{
|
|
Fb2BookEntity bFbz;
|
|
bFbz.extension_kind = QStringLiteral("fbz");
|
|
bFbz.format_label = HistoryFormatLabel::FBZ;
|
|
QCOMPARE(bFbz.format_label, bFbz.expected_format_label());
|
|
|
|
Fb2BookEntity bFb2;
|
|
bFb2.extension_kind = QStringLiteral("fb2");
|
|
bFb2.format_label = HistoryFormatLabel::FB2;
|
|
QCOMPARE(bFb2.format_label, bFb2.expected_format_label());
|
|
|
|
Fb2BookEntity bZip;
|
|
bZip.extension_kind = QStringLiteral("fb2.zip");
|
|
bZip.format_label = HistoryFormatLabel::FB2;
|
|
QCOMPARE(bZip.format_label, bZip.expected_format_label());
|
|
}
|
|
|
|
// Obligations 60-62: surface-actor, surface-exposure, surface-provides
|
|
void testSurface()
|
|
{
|
|
ReaderClient alice{QStringLiteral("Alice")};
|
|
ReaderClient bob{QStringLiteral("Bob")};
|
|
|
|
Fb2FormatReaderSurface s;
|
|
s.client = alice;
|
|
s.book.client = alice;
|
|
s.book.file_path = QStringLiteral("/books/sample.fb2");
|
|
s.book.format_label = HistoryFormatLabel::FB2;
|
|
s.book.status = Fb2LoadStatus::idle;
|
|
|
|
// 60: surface-actor
|
|
QVERIFY(s.is_actor_accessible(alice));
|
|
QVERIFY(!s.is_actor_accessible(bob));
|
|
|
|
// 61: surface-exposure
|
|
QCOMPARE(s.client.name, QStringLiteral("Alice"));
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::idle);
|
|
QCOMPARE(s.book.file_path, QStringLiteral("/books/sample.fb2"));
|
|
QCOMPARE(s.book.format_label, HistoryFormatLabel::FB2);
|
|
|
|
// 62: surface-provides
|
|
QVERIFY(s.can_provide_OpenFb2Requested());
|
|
QVERIFY(s.can_provide_LoadFb2MetadataRequested());
|
|
QVERIFY(!s.can_provide_InspectZipArchive());
|
|
QVERIFY(!s.can_provide_Fb2XmlParsed());
|
|
QVERIFY(!s.can_provide_Fb2MetadataExtracted());
|
|
QVERIFY(!s.can_provide_Fb2DocumentParsed());
|
|
|
|
s.startOpenFb2Book(alice);
|
|
QCOMPARE(s.book.status, Fb2LoadStatus::loading_full);
|
|
QVERIFY(!s.can_provide_OpenFb2Requested());
|
|
QVERIFY(!s.can_provide_LoadFb2MetadataRequested());
|
|
QVERIFY(s.can_provide_Fb2XmlParsed());
|
|
QVERIFY(s.can_provide_Fb2DocumentParsed());
|
|
}
|
|
|
|
// Real format integration test: Plain XML, encodings, and semantics
|
|
void testRealFb2EncodingsAndSemantics()
|
|
{
|
|
QTemporaryDir tempDir;
|
|
QVERIFY(tempDir.isValid());
|
|
|
|
const QString sampleFb2Path = tempDir.filePath(QStringLiteral("test_utf8.fb2"));
|
|
const QString xmlContent = QStringLiteral(
|
|
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
|
|
"<FictionBook xmlns=\"http://www.gribuser.ru/xml/fictionbook/2.0\" xmlns:l=\"http://www.w3.org/1999/xlink\">\n"
|
|
" <stylesheet type=\"text/css\">\n"
|
|
" p.custom { text-align: right; }\n"
|
|
" </stylesheet>\n"
|
|
" <description>\n"
|
|
" <title-info>\n"
|
|
" <book-title>The Master and Margarita</book-title>\n"
|
|
" <author>\n"
|
|
" <first-name>Mikhail</first-name>\n"
|
|
" <last-name>Bulgakov</last-name>\n"
|
|
" </author>\n"
|
|
" <coverpage>\n"
|
|
" <image l:href=\"#cover.jpg\"/>\n"
|
|
" </coverpage>\n"
|
|
" <annotation>\n"
|
|
" <p>A classic satirical fantasy novel.</p>\n"
|
|
" </annotation>\n"
|
|
" </title-info>\n"
|
|
" </description>\n"
|
|
" <body>\n"
|
|
" <title><p>Part One</p></title>\n"
|
|
" <section id=\"ch1\">\n"
|
|
" <title><p>Chapter 1: Never Talk to Strangers</p></title>\n"
|
|
" <epigraph>\n"
|
|
" <p>...who then are you?</p>\n"
|
|
" <text-author>Goethe, Faust</text-author>\n"
|
|
" </epigraph>\n"
|
|
" <subtitle>At the Patriarch's Ponds</subtitle>\n"
|
|
" <p>At the hour of the hot spring sunset two citizens appeared.</p>\n"
|
|
" <empty-line/>\n"
|
|
" <poem>\n"
|
|
" <stanza>\n"
|
|
" <v>And the moon was rising</v>\n"
|
|
" <v>Over Moscow city</v>\n"
|
|
" </stanza>\n"
|
|
" </poem>\n"
|
|
" <p>He spoke with <emphasis>great</emphasis> conviction and <strikethrough>doubt</strikethrough>.</p>\n"
|
|
" </section>\n"
|
|
" </body>\n"
|
|
" <binary id=\"cover.jpg\" content-type=\"image/jpeg\">\n"
|
|
" /9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wgALCAABAAEBAREA/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxA=\n"
|
|
" </binary>\n"
|
|
"</FictionBook>\n"
|
|
);
|
|
|
|
{
|
|
QFile f(sampleFb2Path);
|
|
QVERIFY(f.open(QIODevice::WriteOnly));
|
|
f.write(xmlContent.toUtf8());
|
|
}
|
|
|
|
Fb2Reader reader([] { return std::make_unique<Fb2ByteSource>(); }, QStringLiteral("fb2"));
|
|
|
|
// 1. Metadata load
|
|
QVERIFY(reader.loadMetadata(sampleFb2Path));
|
|
QCOMPARE(reader.status(), Fb2LoadStatus::loaded);
|
|
QCOMPARE(reader.title(), QStringLiteral("The Master and Margarita"));
|
|
QCOMPARE(reader.author(), QStringLiteral("Mikhail Bulgakov"));
|
|
QCOMPARE(reader.formatLabel(), QStringLiteral("FB2"));
|
|
QCOMPARE(reader.formatLabelEnum(), HistoryFormatLabel::FB2);
|
|
QCOMPARE(reader.containerKind(), Fb2ContainerKind::plain_xml);
|
|
QVERIFY(!reader.contentHash().isEmpty());
|
|
QVERIFY(reader.coverImageUrl().startsWith(QStringLiteral("image://fb2/cover.jpg?src=")));
|
|
QVERIFY(reader.chunks().isEmpty());
|
|
|
|
// 2. Full open
|
|
QVERIFY(reader.open(sampleFb2Path));
|
|
QCOMPARE(reader.status(), Fb2LoadStatus::loaded);
|
|
QVERIFY(!reader.chunks().isEmpty());
|
|
|
|
// Annotation chunk
|
|
QCOMPARE(reader.chunks().first().sectionHref, QStringLiteral("annotation"));
|
|
|
|
// Section chunk
|
|
bool foundCh1 = false;
|
|
for (const auto &chunk : reader.chunks()) {
|
|
if (chunk.sectionHref == QLatin1String("ch1")) {
|
|
foundCh1 = true;
|
|
QVERIFY(!chunk.blocks.isEmpty());
|
|
break;
|
|
}
|
|
}
|
|
QVERIFY(foundCh1);
|
|
|
|
// 3. Byte source reading binary
|
|
Fb2ByteSource byteSource;
|
|
QVERIFY(byteSource.open(sampleFb2Path));
|
|
QVERIFY(!byteSource.readEntry(QStringLiteral("cover.jpg")).isEmpty());
|
|
QVERIFY(!byteSource.readEntry(QStringLiteral("#cover.jpg")).isEmpty()); // with hash prefix
|
|
QVERIFY(byteSource.readEntry(QStringLiteral("missing.png")).isEmpty()); // missing binary gracefully handled
|
|
}
|
|
|
|
// Zip-compressed container test (.fbz)
|
|
void testZipCompressedFbz()
|
|
{
|
|
QTemporaryDir tempDir;
|
|
QVERIFY(tempDir.isValid());
|
|
|
|
const QString fbzPath = tempDir.filePath(QStringLiteral("archive.fbz"));
|
|
const QByteArray xml =
|
|
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
|
|
"<FictionBook xmlns=\"http://www.gribuser.ru/xml/fictionbook/2.0\">\n"
|
|
" <description>\n"
|
|
" <title-info>\n"
|
|
" <book-title>Zipped Book</book-title>\n"
|
|
" </title-info>\n"
|
|
" </description>\n"
|
|
" <body>\n"
|
|
" <section id=\"sec0\">\n"
|
|
" <p>Content inside zip.</p>\n"
|
|
" </section>\n"
|
|
" </body>\n"
|
|
"</FictionBook>\n";
|
|
|
|
QVERIFY(createZipArchive(fbzPath, {{QStringLiteral("book.fb2"), xml}}));
|
|
|
|
Fb2Reader reader([] { return std::make_unique<Fb2ByteSource>(); }, QStringLiteral("fb2"));
|
|
QVERIFY(reader.open(fbzPath));
|
|
QCOMPARE(reader.containerKind(), Fb2ContainerKind::zip_archive);
|
|
QCOMPARE(reader.formatLabel(), QStringLiteral("FBZ"));
|
|
QCOMPARE(reader.formatLabelEnum(), HistoryFormatLabel::FBZ);
|
|
QCOMPARE(reader.title(), QStringLiteral("Zipped Book"));
|
|
QVERIFY(!reader.chunks().isEmpty());
|
|
|
|
// Empty zip test
|
|
const QString emptyZipPath = tempDir.filePath(QStringLiteral("empty.fbz"));
|
|
QVERIFY(createZipArchive(emptyZipPath, {}));
|
|
|
|
Fb2Reader emptyReader([] { return std::make_unique<Fb2ByteSource>(); }, QStringLiteral("fb2"));
|
|
QVERIFY(!emptyReader.open(emptyZipPath));
|
|
QCOMPARE(emptyReader.status(), Fb2LoadStatus::failed);
|
|
QCOMPARE(emptyReader.lastError(), QStringLiteral("Archive contains no readable FB2 entry"));
|
|
}
|
|
|
|
// Legacy Cyrillic encoding test (windows-1251)
|
|
void testWindows1251Encoding()
|
|
{
|
|
QTemporaryDir tempDir;
|
|
QVERIFY(tempDir.isValid());
|
|
|
|
const QString path = tempDir.filePath(QStringLiteral("cp1251.fb2"));
|
|
|
|
// "Привет" in windows-1251 is: CF F0 E8 E2 E5 F2
|
|
QByteArray bytes =
|
|
"<?xml version=\"1.0\" encoding=\"windows-1251\"?>\n"
|
|
"<FictionBook xmlns=\"http://www.gribuser.ru/xml/fictionbook/2.0\">\n"
|
|
" <description>\n"
|
|
" <title-info>\n"
|
|
" <book-title>\xCF\xF0\xE8\xE2\xE5\xF2</book-title>\n"
|
|
" </title-info>\n"
|
|
" </description>\n"
|
|
" <body>\n"
|
|
" <section>\n"
|
|
" <p>\xCF\xF0\xE8\xE2\xE5\xF2 \xEC\xE8\xF0</p>\n"
|
|
" </section>\n"
|
|
" </body>\n"
|
|
"</FictionBook>\n";
|
|
|
|
{
|
|
QFile f(path);
|
|
QVERIFY(f.open(QIODevice::WriteOnly));
|
|
f.write(bytes);
|
|
}
|
|
|
|
Fb2Reader reader([] { return std::make_unique<Fb2ByteSource>(); }, QStringLiteral("fb2"));
|
|
QVERIFY(reader.open(path));
|
|
// "Привет" in Unicode
|
|
QCOMPARE(reader.title(), QString::fromUtf8("Привет"));
|
|
}
|
|
|
|
void testNormalizedParagraphSpacingAndIndent()
|
|
{
|
|
QTemporaryDir tempDir;
|
|
QVERIFY(tempDir.isValid());
|
|
const QString path = tempDir.filePath(QStringLiteral("test_paragraphs.fb2"));
|
|
|
|
const QByteArray bytes =
|
|
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
|
|
"<FictionBook xmlns=\"http://www.gribuser.ru/xml/fictionbook/2.0\">\n"
|
|
" <description>\n"
|
|
" <title-info><book-title>Test Book</book-title></title-info>\n"
|
|
" </description>\n"
|
|
" <body>\n"
|
|
" <section>\n"
|
|
" <title>\n"
|
|
" <p>CHAPTER ONE</p>\n"
|
|
" </title>\n"
|
|
" <p>First paragraph of the chapter with enough text to test layout.</p>\n"
|
|
" <p>Second consecutive paragraph immediately following the first.</p>\n"
|
|
" <empty-line/>\n"
|
|
" <p>Third paragraph following an empty line scene transition.</p>\n"
|
|
" </section>\n"
|
|
" </body>\n"
|
|
"</FictionBook>\n";
|
|
|
|
{
|
|
QFile f(path);
|
|
QVERIFY(f.open(QIODevice::WriteOnly));
|
|
f.write(bytes);
|
|
}
|
|
|
|
Fb2Reader fb2Reader([] { return std::make_unique<Fb2ByteSource>(); }, QStringLiteral("fb2"));
|
|
QVERIFY(fb2Reader.open(path));
|
|
QVERIFY(!fb2Reader.chunks().isEmpty());
|
|
|
|
const auto allChunks = fb2Reader.chunks();
|
|
QVERIFY(!allChunks.isEmpty());
|
|
|
|
::LayoutParams params;
|
|
params.contentWidth = 800;
|
|
params.fontSize = 16;
|
|
params.lineSpacing = 1.0;
|
|
|
|
auto prep = ChunkLayoutEngine::prepareChunk(allChunks.first(), 16);
|
|
auto layout = ChunkLayoutEngine::layoutPreparedChunk(prep, params);
|
|
|
|
QVERIFY(layout.lines.size() >= 4);
|
|
|
|
// Line 0: Chapter title ("CHAPTER ONE") must be unindented (x == 0) and left-aligned
|
|
const auto &titleLine = layout.lines[0];
|
|
QVERIFY(!titleLine.runs.isEmpty());
|
|
QCOMPARE(titleLine.runs[0].text, QStringLiteral("CHAPTER"));
|
|
QCOMPARE(titleLine.runs[0].rect.left(), 0.0);
|
|
|
|
// Line 1: First paragraph must have 2.0em (32px at 16px font) first-line indent
|
|
const auto &p1Line = layout.lines[1];
|
|
QVERIFY(!p1Line.runs.isEmpty());
|
|
QCOMPARE(p1Line.runs[0].text, QStringLiteral("First"));
|
|
QCOMPARE(p1Line.runs[0].rect.left(), 32.0);
|
|
|
|
// Line 2: Second paragraph must immediately follow Line 1 with zero vertical margin gap
|
|
const auto &p2Line = layout.lines[2];
|
|
QVERIFY(!p2Line.runs.isEmpty());
|
|
QCOMPARE(p2Line.runs[0].text, QStringLiteral("Second"));
|
|
QCOMPARE(p2Line.runs[0].rect.left(), 32.0);
|
|
QVERIFY(qAbs(p1Line.rect.bottom() - p2Line.rect.top()) < 0.001);
|
|
|
|
// Line 3: Third paragraph must have an empty vertical gap from Line 2 due to <empty-line>
|
|
const auto &p3Line = layout.lines[3];
|
|
QVERIFY(!p3Line.runs.isEmpty());
|
|
QCOMPARE(p3Line.runs[0].text, QStringLiteral("Third"));
|
|
QCOMPARE(p3Line.runs[0].rect.left(), 32.0);
|
|
QVERIFY(p3Line.rect.top() > p2Line.rect.bottom());
|
|
}
|
|
|
|
void testFb2AndEpubParagraphEquivalence()
|
|
{
|
|
// Compare layout of representative synthetic FB2 <p> vs EPUB <div class="paragraph">
|
|
const QString fb2Html = QStringLiteral(
|
|
"<div>"
|
|
"<h1 style=\"text-align: left; text-indent: 0;\">CHAPTER ONE</h1>"
|
|
"<p>First paragraph of the chapter with enough text to test layout.</p>"
|
|
"<p>Second consecutive paragraph immediately following the first.</p>"
|
|
"</div>"
|
|
);
|
|
auto fb2Chunks = HtmlBlockParser::parseChunks(fb2Html, QStringLiteral("fb2-sec"));
|
|
QCOMPARE(fb2Chunks.size(), 1);
|
|
|
|
// EPUB equivalent with cascaded .paragraph { display: block; text-indent: 2em; }
|
|
const QString epubHtml = QStringLiteral(
|
|
"<div>"
|
|
"<h1 style=\"text-align: left; text-indent: 0;\">CHAPTER ONE</h1>"
|
|
"<div style=\"text-indent: 32px;\">First paragraph of the chapter with enough text to test layout.</div>"
|
|
"<div style=\"text-indent: 32px;\">Second consecutive paragraph immediately following the first.</div>"
|
|
"</div>"
|
|
);
|
|
auto epubChunks = HtmlBlockParser::parseChunks(epubHtml, QStringLiteral("epub-sec"));
|
|
QCOMPARE(epubChunks.size(), 1);
|
|
|
|
::LayoutParams params;
|
|
params.contentWidth = 800;
|
|
params.fontSize = 16;
|
|
params.lineSpacing = 1.0;
|
|
|
|
auto fb2Layout = ChunkLayoutEngine::layoutPreparedChunk(
|
|
ChunkLayoutEngine::prepareChunk(fb2Chunks.first(), 16), params);
|
|
auto epubLayout = ChunkLayoutEngine::layoutPreparedChunk(
|
|
ChunkLayoutEngine::prepareChunk(epubChunks.first(), 16), params);
|
|
|
|
QCOMPARE(fb2Layout.lines.size(), epubLayout.lines.size());
|
|
for (int i = 0; i < fb2Layout.lines.size(); ++i) {
|
|
QCOMPARE(fb2Layout.lines[i].rect.topLeft(), epubLayout.lines[i].rect.topLeft());
|
|
QVERIFY(!fb2Layout.lines[i].runs.isEmpty());
|
|
QVERIFY(!epubLayout.lines[i].runs.isEmpty());
|
|
QCOMPARE(fb2Layout.lines[i].runs[0].rect.left(), epubLayout.lines[i].runs[0].rect.left());
|
|
}
|
|
}
|
|
};
|
|
|
|
QTEST_MAIN(Fb2ReaderTest)
|
|
#include "Fb2ReaderTest.moc"
|