#include #include #include #include #include #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 content_hash; std::optional title; std::optional> authors; std::optional author; std::optional cover_image_url; std::optional> chunks; std::optional> binaries; // Failed field std::optional 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 &parsed_authors, const QString &formatted_authors, const std::optional &resolved_cover_id, const QVector &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{}; 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 &parsed_authors, const QString &formatted_authors, const std::optional &resolved_cover_id, const QVector &binary_resources, const QVector &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 &parsed_authors, const QString &formatted_authors, const std::optional &resolved_cover_id, const QVector &binary_resources, const QVector &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}; book.chunks = QVector{fallbackChunk}; book.binaries = binary_resources; return true; } }; static bool createZipArchive(const QString &zipPath, const QHash &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, 500, 2}; ContentChunkValue c2{QStringLiteral("sec1"), 5, 500, 2}; ContentChunkValue cDiffHref{QStringLiteral("sec2"), 5, 500, 2}; ContentChunkValue cDiffBlocks{QStringLiteral("sec1"), 6, 500, 2}; ContentChunkValue cDiffChars{QStringLiteral("sec1"), 5, 501, 2}; ContentChunkValue cDiffContainers{QStringLiteral("sec1"), 5, 500, 3}; QVERIFY(c1 == c2); QVERIFY(!(c1 != c2)); QVERIFY(c1 != cDiffHref); QVERIFY(c1 != cDiffBlocks); 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.char_count, 0); QCOMPARE(c.unnested_containers, 0); c.section_href = QStringLiteral("body/s0"); c.blocks_count = 3; c.char_count = 250; c.unnested_containers = 1; QCOMPARE(c.section_href, QStringLiteral("body/s0")); QCOMPARE(c.blocks_count, 3); 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("

Paragraph in EPUB spine

")); QDomElement root1 = doc1.documentElement(); QDomDocument doc2; doc2.setContent(QStringLiteral("

Paragraph in EPUB spine

")); 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 chunks1 = HtmlBlockParser::parseChunks( root1, sectionHref, targetChars, {}, &sheet, scheme, sourcePath); QVector 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().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{}; book.author = QStringLiteral("Leo Tolstoy"); book.cover_image_url = QStringLiteral("image://fb2/cover.jpg"); book.chunks = QVector{}; book.binaries = QVector{}; 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, 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, 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}; // 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.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( "\n" "\n" " \n" " p.custom { text-align: right; }\n" " \n" " \n" " \n" " The Master and Margarita\n" " \n" " Mikhail\n" " Bulgakov\n" " \n" " \n" " \n" " \n" " \n" "

A classic satirical fantasy novel.

\n" "
\n" "
\n" "
\n" " \n" " <p>Part One</p>\n" "
\n" " <p>Chapter 1: Never Talk to Strangers</p>\n" " \n" "

...who then are you?

\n" " Goethe, Faust\n" "
\n" " At the Patriarch's Ponds\n" "

At the hour of the hot spring sunset two citizens appeared.

\n" " \n" " \n" " \n" " And the moon was rising\n" " Over Moscow city\n" " \n" " \n" "

He spoke with great conviction and doubt.

\n" "
\n" " \n" " \n" " /9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wgALCAABAAEBAREA/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxA=\n" " \n" "
\n" ); { QFile f(sampleFb2Path); QVERIFY(f.open(QIODevice::WriteOnly)); f.write(xmlContent.toUtf8()); } Fb2Reader reader([] { return std::make_unique(); }, 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 = "\n" "\n" " \n" " \n" " Zipped Book\n" " \n" " \n" " \n" "
\n" "

Content inside zip.

\n" "
\n" " \n" "
\n"; QVERIFY(createZipArchive(fbzPath, {{QStringLiteral("book.fb2"), xml}})); Fb2Reader reader([] { return std::make_unique(); }, 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(); }, 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 = "\n" "\n" " \n" " \n" " \xCF\xF0\xE8\xE2\xE5\xF2\n" " \n" " \n" " \n" "
\n" "

\xCF\xF0\xE8\xE2\xE5\xF2 \xEC\xE8\xF0

\n" "
\n" " \n" "
\n"; { QFile f(path); QVERIFY(f.open(QIODevice::WriteOnly)); f.write(bytes); } Fb2Reader reader([] { return std::make_unique(); }, 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 = "\n" "\n" " \n" " Test Book\n" " \n" " \n" "
\n" " \n" " <p>CHAPTER ONE</p>\n" " \n" "

First paragraph of the chapter with enough text to test layout.

\n" "

Second consecutive paragraph immediately following the first.

\n" " \n" "

Third paragraph following an empty line scene transition.

\n" "
\n" " \n" "
\n"; { QFile f(path); QVERIFY(f.open(QIODevice::WriteOnly)); f.write(bytes); } Fb2Reader fb2Reader([] { return std::make_unique(); }, 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 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

vs EPUB

const QString fb2Html = QStringLiteral( "
" "

CHAPTER ONE

" "

First paragraph of the chapter with enough text to test layout.

" "

Second consecutive paragraph immediately following the first.

" "
" ); 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( "
" "

CHAPTER ONE

" "
First paragraph of the chapter with enough text to test layout.
" "
Second consecutive paragraph immediately following the first.
" "
" ); 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"