SPB Git

Repository Public

TemplateLibraryTests.swift 47.1 KB 856 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Tests/DocTemplatesTests/TemplateLibraryTests.swift3// Description: Tests of the template library: catalogue, structural integrity of every template in both languages, promised features,4//              localisation and typography, context handling, genre-specific machinery.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Testing10import DocModel11@testable import DocTemplates1213// MARK: - Catalogue1415@Suite struct CatalogueTests {16    @Test func sixteenTemplatesBlankFirst() {17        #expect(TemplateLibrary.all.count == 16)18        #expect(TemplateLibrary.all.first?.id == "blank")19        #expect(TemplateLibrary.blank.id == "blank")20        #expect(Set(templateIDs).count == 16)21        let expected: Set<String> = ["blank", "business-letter", "academic-paper", "research-report", "thesis", "proposal", "financial-report", "legal-memorandum",22                                     "meeting-minutes", "resume", "cover-letter", "technical-manual", "book-manuscript", "project-report", "invoice", "newsletter"]23        #expect(Set(templateIDs) == expected)24    }2526    @Test func lookup() {27        for t in TemplateLibrary.all { #expect(TemplateLibrary.template(id: t.id)?.id == t.id) }28        #expect(TemplateLibrary.template(id: "nope") == nil)29        for c in TemplateCategory.allCases {30            #expect(!TemplateLibrary.templates(in: c).isEmpty)31            #expect(!c.name("en").isEmpty)32            #expect(c.name("fr") != c.name("en"))33        }34    }3536    @Test func descriptors() {37        for t in TemplateLibrary.all {38            #expect(!t.name("en").isEmpty && !t.name("fr").isEmpty)39            #expect(!t.summary("en").isEmpty && !t.summary("fr").isEmpty)40            #expect(t.summary("en") != t.summary("fr"))41            #expect(t.name("fr-CA") == t.name("fr"))42            #expect(!t.symbolName.isEmpty)43            #expect(Theme.named(t.themeName) != nil)44            #expect(!t.name("fr").contains("'") && !t.summary("fr").contains("'") && !t.summary("en").contains("'"))45            #expect(!t.summary("fr").contains(" ;") && !t.summary("fr").contains(" :"))46        }47        #expect(Set(TemplateLibrary.all.map { $0.name("en") }).count == 16)48        #expect(Set(TemplateLibrary.all.map { $0.name("fr") }).count == 16)49    }50}5152// MARK: - Structural integrity (every template × both languages)5354@Suite struct IntegrityTests {55    @Test(arguments: templateIDs, languages)56    func buildsWithContent(id: String, language: String) {57        let doc = make(id, language)58        #expect(!doc.body.isEmpty)59        #expect(doc.schemaVersion == DocumentModel.currentSchemaVersion)60        if id != "blank" {61            #expect(doc.bodyParagraphs.count >= 10)62            #expect(!doc.meta.title.isEmpty)63        }64        #expect(doc.styles.themeName == TemplateLibrary.template(id: id)!.themeName)65    }6667    @Test(arguments: templateIDs, languages)68    func stylesExist(id: String, language: String) {69        let doc = make(id, language)70        for p in doc.allParagraphs {71            #expect(doc.styles.style(p.style)?.kind == .paragraph, "missing paragraph style \(p.style)")72            for r in p.runs {73                if let cs = r.charStyle { #expect(doc.styles.style(cs)?.kind == .character, "missing character style \(cs)") }74            }75        }76        for s in doc.styles.styles {77            if let parent = s.basedOn { #expect(doc.styles.style(parent) != nil, "\(s.id) is based on missing \(parent)") }78            if let next = s.next { #expect(doc.styles.style(next) != nil, "\(s.id) is followed by missing \(next)") }79            #expect(!s.name.isEmpty)80        }81        #expect(Set(doc.styles.styles.map(\.id)).count == doc.styles.styles.count)82    }8384    @Test(arguments: templateIDs, languages)85    func noDirectCharacterFormatting(id: String, language: String) {86        let doc = make(id, language)87        for p in doc.allParagraphs { for r in p.runs { #expect(r.props == .none) } }88        // Direct paragraph formatting is reserved for one-offs.89        let direct = doc.bodyParagraphs.filter { !$0.props.isEmpty }.count90        #expect(direct * 5 <= max(5, doc.bodyParagraphs.count), "\(direct) of \(doc.bodyParagraphs.count) paragraphs carry direct formatting")91    }9293    @Test(arguments: templateIDs, languages)94    func listsExist(id: String, language: String) {95        let doc = make(id, language)96        #expect(Set(doc.lists.map(\.id)).count == doc.lists.count)97        for p in doc.allParagraphs {98            guard let item = p.list else { continue }99            let def = doc.list(item.listID)100            #expect(def != nil)101            #expect(item.level >= 0 && item.level < (def?.levels.count ?? 0))102        }103        let numbering = Numbering(doc)104        for p in doc.allParagraphs where p.list != nil { #expect(numbering.listLabels[p.id]?.isEmpty == false) }105        // No definition is left unused.106        let used = Set(doc.allParagraphs.compactMap { $0.list?.listID })107        #expect(used == Set(doc.lists.map(\.id)))108    }109110    @Test(arguments: templateIDs, languages)111    func crossReferencesResolve(id: String, language: String) {112        let doc = make(id, language)113        let numbering = Numbering(doc)114        for ref in doc.crossRefs {115            #expect(numbering.targetExists(ref.target))116            let text = numbering.crossRefText(ref, pageOf: { _ in "1" })117            #expect(!text.contains("?") && !text.isEmpty, "cross-reference renders as \(text)")118        }119    }120121    @Test(arguments: templateIDs, languages)122    func notesAndCitationsResolve(id: String, language: String) {123        let doc = make(id, language)124        let refs = doc.noteRefs125        #expect(Set(refs.map(\.id)) == Set(doc.notes.keys))126        #expect(refs.count == doc.notes.count)127        for ref in refs {128            #expect(doc.notes[ref.id]?.kind == ref.kind)129            #expect(doc.notes[ref.id]?.id == ref.id)130            #expect(doc.notes[ref.id]?.paragraphs.allSatisfy { !$0.visibleText.isEmpty && $0.style == StyleID.footnoteText } == true)131        }132        let keys = Set(doc.bibliography.map(\.key))133        #expect(keys.count == doc.bibliography.count)134        for c in doc.citations { for item in c.items { #expect(keys.contains(item.key)) } }135        // Placeholder entries only, all of them cited so the generated bibliography shows them.136        #expect(Set(doc.citations.flatMap { $0.items.map(\.key) }) == keys)137    }138139    @Test(arguments: templateIDs, languages)140    func headingsAreSound(id: String, language: String) {141        let doc = make(id, language)142        var previous = 0143        for h in doc.headings {144            let level = doc.outlineLevel(h)145            #expect(level <= previous + 1, "heading “\(h.visibleText)” jumps from level \(previous) to \(level)")146            #expect(!h.visibleText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)147            previous = level148        }149        if let first = doc.headings.first { #expect(doc.outlineLevel(first) == 1) }150        #expect(Numbering(doc).outline.count == doc.headings.count)151        // Nothing looks like a heading without being one: titles in tables, notes or headers have no outline level.152        for p in doc.tableParagraphs + doc.noteParagraphs + doc.headerFooterParagraphs { #expect(doc.outlineLevel(p) == 0) }153    }154155    @Test(arguments: templateIDs, languages)156    func identifiersAreUnique(id: String, language: String) {157        let ids = make(id, language).allIDs158        #expect(Set(ids).count == ids.count)159        #expect(!ids.contains(""))160    }161162    @Test(arguments: templateIDs, languages)163    func jsonRoundTrip(id: String, language: String) throws {164        let doc = make(id, language)165        let data = try JSONEncoder().encode(doc)166        let back = try JSONDecoder().decode(DocumentModel.self, from: data)167        #expect(back == doc)168    }169170    @Test(arguments: templateIDs, languages)171    func tablesAreWellFormed(id: String, language: String) {172        let doc = make(id, language)173        let headingStyles: Set<String> = ["TableHeading", "TableHeadingNumber"]174        for t in doc.tables {175            #expect(!t.rows.isEmpty)176            #expect(t.columnWidths.allSatisfy { $0 > 20 })177            #expect(t.totalWidth <= doc.sections.map(\.contentWidth).max()! + 0.5)178            for (i, row) in t.rows.enumerated() {179                #expect(row.cells.reduce(0) { $0 + $1.colSpan } == t.columnCount)180                for c in row.cells { #expect(!c.paragraphs.isEmpty) }181                let isHeading = row.cells.contains { headingStyles.contains($0.paragraphs[0].style) }182                #expect(row.isHeader == isHeading)183                #expect(row.isHeader == (i == 0), "every data table has exactly one header row, the first")184            }185        }186    }187188    @Test(arguments: templateIDs, languages)189    func captionsAndFiguresAreGenuine(id: String, language: String) {190        let doc = make(id, language)191        let numbering = Numbering(doc)192        for p in doc.bodyParagraphs {193            let sequences = p.runs.compactMap { r -> String? in if case .field(.sequence(let n))? = r.inline { return n } else { return nil } }194            if p.style == StyleID.caption {195                #expect(sequences.count == 1)196                #expect(["Figure", "Table"].contains(sequences.first ?? ""))197                #expect(numbering.captions[p.id]?.text.isEmpty == false)198            }199            for s in sequences where s == "Figure" || s == "Table" { #expect(p.style == StyleID.caption) }200        }201        // Every figure placeholder has alternative text and is followed by its caption.202        for (i, block) in doc.body.enumerated() {203            guard let p = block.paragraph, p.runs.contains(where: { if case .shape? = $0.inline { return true } else { return false } }) else { continue }204            let next = i + 1 < doc.body.count ? doc.body[i + 1].paragraph : nil205            #expect(next?.style == StyleID.caption)206            #expect(next.map { numbering.captions[$0.id]?.label } == "Figure")207        }208        for s in doc.shapes {209            #expect(s.altText.count > 20)210            #expect(s.width > 0 && s.height > 0)211        }212        // A table caption is immediately followed by its table.213        for (i, block) in doc.body.enumerated() {214            guard let p = block.paragraph, numbering.captions[p.id]?.label == "Table" else { continue }215            #expect(i + 1 < doc.body.count && doc.body[i + 1].table != nil)216        }217        #expect(!doc.allInlines.contains { if case .image = $0 { return true } else { return false } })218        #expect(doc.assets.isEmpty)219    }220221    @Test(arguments: templateIDs, languages)222    func contentDoesNotDependOnTheCall(id: String, language: String) {223        let a = make(id, language), b = make(id, language)224        #expect(a.fullText == b.fullText)225        #expect(a.styles == b.styles)226        if id != "blank" { #expect(Set(a.allIDs).isDisjoint(with: b.allIDs)) }227    }228}229230// MARK: - Promised features231232@Suite struct FeatureTests {233    @Test(arguments: templateIDs, languages)234    func promisesAreKept(id: String, language: String) {235        let template = TemplateLibrary.template(id: id)!236        let doc = make(id, language)237        let f = template.features238        let numbering = Numbering(doc)239240        let hasTOC = doc.tocBlocks.contains { $0.kind == .contents }241        #expect(f.contains(.tableOfContents) == hasTOC)242        if hasTOC { #expect(doc.headings.count >= 3) }243244        #expect(f.contains(.pageNumbers) == doc.headerFooterFields.contains(.pageNumber))245        // Page fields live in headers and footers only.246        #expect(!doc.bodyParagraphs.flatMap { $0.runs.compactMap(\.inline) }.contains(.field(.pageNumber)))247248        let numbered = doc.headings.filter { doc.styles.isNumberedHeading($0.style) }249        #expect(f.contains(.numberedHeadings) == !numbered.isEmpty)250        if f.contains(.numberedHeadings) {251            #expect(numbered.count >= 4)252            #expect(numbering.headingNumbers[numbered[0].id] == "1")253            #expect(numbering.headingNumbers.values.contains { $0.contains(".") })254        }255256        #expect(f.contains(.bibliography) == !doc.bibliographyBlocks.isEmpty)257        #expect(f.contains(.bibliography) == !doc.bibliography.isEmpty)258        #expect(f.contains(.bibliography) == !doc.citations.isEmpty)259260        #expect(f.contains(.multipleSections) == (doc.sections.count > 1))261        #expect(f.contains(.formulas) == !doc.formulaCells.isEmpty)262        #expect(f.contains(.captions) == !numbering.captions.values.filter { $0.label == "Figure" || $0.label == "Table" }.isEmpty)263        #expect(f.contains(.crossReferences) == !doc.crossRefs.isEmpty)264        #expect(f.contains(.footnotes) == !doc.notes.isEmpty)265266        let displayEquations = doc.allInlines.filter { if case .equation(let e) = $0 { return e.display } else { return false } }267        #expect(f.contains(.equations) == !displayEquations.isEmpty)268269        let mirrored = doc.sections.contains { $0.differentOddEven && !$0.header.even.isEmpty && !$0.header.default.isEmpty }270        #expect(f.contains(.mirroredPages) == mirrored)271        if mirrored { #expect(doc.headerFooterFields.contains(.headingText(level: 1))) }272273        let kinds = Set(doc.tocBlocks.map(\.kind))274        #expect(f.contains(.listsOfFiguresAndTables) == (kinds.contains(.figures) && kinds.contains(.tables)))275        if kinds.contains(.figures) { #expect(numbering.captions.values.contains { $0.label == "Figure" }) }276        if kinds.contains(.tables) { #expect(numbering.captions.values.contains { $0.label == "Table" }) }277278        #expect(f.contains(.columns) == doc.sections.contains { $0.columns >= 2 })279        #expect(f.contains(.landscapeSection) == doc.sections.contains { $0.landscape })280281        let roman = doc.pageSetup.pageNumberFormat == .lowerRoman282            && doc.sections.dropFirst().contains { $0.pageNumberFormat == .decimal && $0.pageNumberStart == 1 }283        #expect(f.contains(.romanFrontMatter) == roman)284    }285286    @Test func genresThatCallForNumberedHeadings() {287        for id in ["thesis", "technical-manual", "legal-memorandum", "research-report"] {288            #expect(TemplateLibrary.template(id: id)!.features.contains(.numberedHeadings))289        }290        for id in ["academic-paper", "research-report", "thesis"] {291            #expect(TemplateLibrary.template(id: id)!.features.contains(.bibliography))292        }293    }294295    @Test(arguments: templateIDs, languages)296    func headersAndFootersUseTheirStyles(id: String, language: String) {297        let doc = make(id, language)298        for s in doc.sections {299            for p in s.header.default + s.header.first + s.header.even { #expect(p.style == StyleID.header) }300            for p in s.footer.default + s.footer.first + s.footer.even { #expect(p.style == StyleID.footer) }301            // The right tab stop of the header sits on the right margin of its section.302            for p in s.header.default + s.footer.default {303                let tabs = doc.styles.paraProps(style: p.style, direct: p.props).tabs304                #expect(abs((tabs.last?.position ?? 0) - s.contentWidth) < 1)305                #expect(tabs.last?.kind == .right)306            }307        }308    }309}310311// MARK: - Context312313@Suite struct ContextTests {314    @Test(arguments: templateIDs, languages)315    func authorAndDateAreHonoured(id: String, language: String) {316        let ctx = sampleContext(language)317        let doc = make(id, language)318        #expect(doc.meta.author == ctx.author)319        #expect(doc.meta.created == ctx.date)320        #expect(doc.meta.modified == ctx.date)321        guard id != "blank" else { return }322        // The author shows through a real field, or as text.323        #expect(doc.allFields.contains(.author) || doc.fullText.contains(ctx.author))324        #expect(!doc.fullText.contains("[Your name]") && !doc.fullText.contains("[Votre nom]"))325        if id != "resume" {326            #expect(doc.fullText.contains(ctx.organization))327            #expect(!doc.fullText.contains("[Organization name]") && !doc.fullText.contains("[Nom de l’organisation]"))328        }329        let date = language == "fr" ? "14 mars 2025" : "March 14, 2025"330        switch id {331        case "resume": break332        case "thesis": #expect(doc.fullText.contains(language == "fr" ? "mars 2025" : "March 2025"))333        default: #expect(doc.fullText.contains(date), "the context date is not printed")334        }335    }336337    @Test(arguments: templateIDs, languages)338    func emptyContextShowsPrompts(id: String, language: String) {339        let doc = TemplateLibrary.template(id: id)!.make(TemplateContext(date: sampleDate, language: language))340        #expect(doc.meta.author.isEmpty)341        #expect(!doc.allFields.contains(.author), "an author field would print nothing")342        guard id != "blank" else { return }343        #expect(doc.fullText.contains(language == "fr" ? "[Votre nom]" : "[Your name]"))344        if id != "resume" && id != "book-manuscript" {345            #expect(doc.fullText.contains(language == "fr" ? "[Nom de l’organisation]" : "[Organization name]"))346        }347    }348349    @Test(arguments: templateIDs, [PaperSize.letter, .a4, .legal, .trade6x9])350    func paperIsHonoured(id: String, paper: PaperSize) {351        let doc = make(id, "en", paper: paper)352        for s in doc.sections {353            #expect(s.paper == paper)354            #expect(s.margins.left + s.margins.right < s.pageWidth / 2)355        }356        for t in doc.tables { #expect(t.totalWidth <= doc.sections.map(\.contentWidth).max()! + 0.5) }357        // Equation and right-aligned tab stops follow the text width.358        if let eq = doc.styles.style("Equation") { #expect(abs((eq.para.tabs?.last?.position ?? 0) - doc.sections.last!.contentWidth) < 1) }359    }360361    @Test func firstOfTheMonthInFrench() {362        var comps = DateComponents()363        comps.year = 2026; comps.month = 7; comps.day = 1; comps.hour = 12364        let date = Calendar(identifier: .gregorian).date(from: comps)!365        #expect(Loc(french: true).date(date) == "1er juillet 2026")366        #expect(Loc(french: false).date(date) == "July 1, 2026")367    }368369    @Test func languageTagsStartingWithFrSelectFrench() {370        #expect(TemplateContext(language: "fr-CA").isFrench)371        #expect(TemplateContext(language: "FR").isFrench)372        #expect(!TemplateContext(language: "en-CA").isFrench)373        #expect(!TemplateContext().isFrench)374    }375}376377// MARK: - Language and typography378379@Suite struct LanguageTests {380    static let englishWords: Set<String> = ["the", "and", "with", "your", "for", "of", "this", "that", "is", "are", "from", "by", "to", "you", "be", "should", "here", "each"]381    static let frenchWords: Set<String> = ["le", "la", "les", "des", "une", "du", "vous", "votre", "vos", "avec", "pour", "dans", "est", "et", "au", "qui", "sont", "ici", "chaque"]382383    @Test(arguments: templateIDs)384    func frenchDiffersFromEnglish(id: String) {385        let en = make(id, "en"), fr = make(id, "fr")386        #expect(en.meta.language == "en")387        #expect(fr.meta.language == "fr-CA")388        #expect(en.styles.defaultChar.language == "en")389        #expect(fr.styles.defaultChar.language == "fr-CA")390        guard id != "blank" else { return }391        #expect(en.fullText != fr.fullText)392        #expect(en.meta.title != fr.meta.title)393        // Same structure in both languages.394        #expect(en.body.count == fr.body.count || id == "invoice")395        #expect(en.headings.count == fr.headings.count)396        #expect(en.styles.styles.map(\.id) == fr.styles.styles.map(\.id))397    }398399    @Test(arguments: templateIDs)400    func noLeftoverEnglishInFrench(id: String) {401        let fr = make(id, "fr")402        for s in fr.visibleStrings {403            let leftovers = words(s).intersection(Self.englishWords)404            #expect(leftovers.isEmpty, "English words \(leftovers) in French text “\(s)”")405        }406        for label in ["Contents", "References", "Abstract", "Keywords", "Chapter", "Appendix", "Dear", "Sincerely", "Summary", "Invoice", "Subtotal", "Total due",407                      "Table of", "List of", "Subject", "Introduction to", "Heading", "Sidebar", "Signature Line", "Prepared", "Meeting"] {408            #expect(!fr.fullText.contains(label), "leftover English label “\(label)”")409        }410        for t in fr.tocBlocks { #expect(["Table des matières", "Liste des figures", "Liste des tableaux"].contains(t.title ?? "")) }411        for b in fr.bibliographyBlocks { #expect(b.title == "Références") }412    }413414    @Test(arguments: templateIDs)415    func noFrenchInEnglish(id: String) {416        let en = make(id, "en")417        for s in en.visibleStrings {418            let leftovers = words(s).intersection(Self.frenchWords)419            #expect(leftovers.isEmpty, "French words \(leftovers) in English text “\(s)”")420        }421        for t in en.tocBlocks { #expect(["Table of Contents", "List of Figures", "List of Tables"].contains(t.title ?? "")) }422        for b in en.bibliographyBlocks { #expect(b.title == "References") }423    }424425    @Test(arguments: templateIDs)426    func frenchTypography(id: String) {427        let fr = make(id, "fr")428        for s in fr.visibleStrings {429            let chars = Array(s)430            for (i, ch) in chars.enumerated() {431                if ";?!»%".contains(ch) || (ch == ":" && !(i + 1 < chars.count && chars[i + 1] == "/")) {432                    #expect(i > 0 && chars[i - 1] == nbspChar, "no no-break space before “\(ch)” in “\(s)”")433                }434                if ch == "$" { #expect(i > 0 && chars[i - 1] == nbspChar, "no no-break space before $ in “\(s)”") }435                if ch == "«" { #expect(i + 1 < chars.count && chars[i + 1] == nbspChar, "no no-break space after « in “\(s)”") }436            }437            #expect(!s.contains("'") && !s.contains("\""), "straight quote in “\(s)”")438            #expect(!s.contains("“") && !s.contains("”"), "English quotation marks in “\(s)”")439        }440    }441442    @Test(arguments: templateIDs)443    func englishTypography(id: String) {444        let en = make(id, "en")445        for s in en.visibleStrings {446            #expect(!s.contains("'") && !s.contains("\""), "straight quote in “\(s)”")447            #expect(!s.contains("«") && !s.contains("»"))448            #expect(!s.contains(" :") && !s.contains(" ;") && !s.contains(" ?") && !s.contains(" !"))449            #expect(!s.contains("\u{00A0}%") && !s.contains("\u{00A0}$"))450        }451    }452453    @Test func typographyHelpers() {454        #expect(Typography.french("Objet : l'été ; quoi ? oui ! « bien » 5 % 10 $") == "Objet\u{A0}: l’été\u{A0}; quoi\u{A0}? oui\u{A0}! «\u{A0}bien\u{A0}» 5\u{A0}% 10\u{A0}$")455        #expect(Typography.english("it's") == "it’s")456        let en = Loc(french: false), fr = Loc(french: true)457        #expect(en.number(1234567) == "1,234,567")458        #expect(fr.number(1234567) == "1\u{A0}234\u{A0}567")459        #expect(en.money(1905) == "$1,905.00")460        #expect(fr.money(1905) == "1\u{A0}905,00\u{A0}$")461        #expect(en.money(190.02375) == "$190.02")462        #expect(fr.money(0.5) == "0,50\u{A0}$")463        #expect(en.money(-17400, decimals: 0) == "-$17,400")464        #expect(en.percent(10.34) == "10.3%")465        #expect(fr.percent(10.34) == "10,3\u{A0}%")466        #expect(en.number(999.999, decimals: 2) == "1,000.00")467        #expect(en.number(12.05, decimals: 2) == "12.05")468    }469470    @Test func keyStrings() {471        func text(_ id: String, _ l: String) -> String { make(id, l).fullText }472        #expect(text("business-letter", "fr").contains("Objet\u{A0}:"))473        #expect(text("business-letter", "fr").contains("Madame, Monsieur,"))474        #expect(text("business-letter", "fr").contains("le 14 mars 2025"))475        #expect(text("business-letter", "en").contains("Subject:"))476        #expect(text("business-letter", "en").contains("Sincerely,"))477        #expect(text("academic-paper", "fr").contains("Mots-clés\u{A0}:"))478        #expect(text("academic-paper", "fr").contains("Résumé"))479        #expect(text("academic-paper", "en").contains("Keywords:"))480        #expect(text("invoice", "fr").contains("Facture") && text("invoice", "fr").contains("Total à payer") && text("invoice", "fr").contains("TVQ (9,975\u{A0}%)"))481        #expect(text("invoice", "en").contains("Invoice") && text("invoice", "en").contains("Total due"))482        #expect(text("legal-memorandum", "fr").contains("DESTINATAIRE\u{A0}:") && text("legal-memorandum", "fr").contains("OBJET\u{A0}:"))483        #expect(text("legal-memorandum", "en").contains("TO:") && text("legal-memorandum", "en").contains("RE:"))484        #expect(text("meeting-minutes", "fr").contains("Ordre du jour"))485        #expect(text("thesis", "fr").contains("Remerciements"))486        #expect(text("book-manuscript", "fr").contains("«\u{A0}comme ceci\u{A0}»"))487        #expect(text("book-manuscript", "en").contains("“like this.”"))488        #expect(text("newsletter", "fr").contains("À venir"))489        #expect(text("resume", "fr").contains("Expérience professionnelle"))490    }491}492493// MARK: - Genre-specific machinery494495@Suite struct GenreTests {496    /// The caption label of a French table caption is "Tableau", but its sequence stays "Table" so the list of tables finds it.497    @Test func frenchCaptionsKeepTheSequenceNames() {498        let doc = make("thesis", "fr")499        let n = Numbering(doc)500        let texts = n.captions.values.filter { $0.label == "Table" }.map(\.text)501        #expect(!texts.isEmpty)502        #expect(texts.allSatisfy { $0.hasPrefix("Tableau\u{A0}1\u{A0}– ") })503        #expect(n.captions.values.contains { $0.label == "Figure" && $0.text.hasPrefix("Figure\u{A0}1\u{A0}– ") })504        let en = Numbering(make("thesis", "en"))505        #expect(en.captions.values.contains { $0.label == "Table" && $0.text.hasPrefix("Table\u{A0}1. ") })506    }507508    @Test(arguments: ["academic-paper", "thesis"], languages)509    func scholarlyMachinery(id: String, language: String) throws {510        let doc = make(id, language)511        let n = Numbering(doc)512        // Abstract and keywords513        #expect(doc.bodyParagraphs.contains { $0.style == StyleID.abstract && $0.visibleText.count > 80 })514        #expect(doc.bodyParagraphs.contains { $0.style == "Keywords" && $0.runs.first?.charStyle == StyleID.strong })515        // Numbered display equation: tab, equation, tab, "(", sequence, ")" on centre and right tab stops516        let eq = try #require(doc.bodyParagraphs.first { $0.style == "Equation" })517        #expect(eq.runs.count == 5)518        #expect(eq.runs[0].text == "\t")519        if case .equation(let e)? = eq.runs[1].inline { #expect(e.display && !e.latex.isEmpty) } else { Issue.record("no equation") }520        #expect(eq.runs[2].text == "\t(")521        #expect(eq.runs[3].inline == .field(.sequence("Equation")))522        #expect(eq.runs[4].text == ")")523        let tabs = doc.styles.paraProps(style: eq.style, direct: eq.props).tabs524        #expect(tabs.map(\.kind) == [.center, .right])525        #expect(n.captions[eq.id]?.label == "Equation" && n.captions[eq.id]?.number == 1)526        // … and a cross-reference to it that reads "(1)"527        let eqRef = try #require(doc.crossRefs.first { $0.target == eq.id })528        #expect(n.crossRefText(eqRef, pageOf: { _ in nil }) == "(1)")529        // Figure placeholder with caption, referenced530        let figure = try #require(n.captions.first { $0.value.label == "Figure" })531        #expect(doc.crossRefs.contains { $0.target == figure.key })532        #expect(doc.shapes.count == 1 && doc.shapes[0].kind == .rectangle)533        // Three-rule table with caption, referenced534        let table = try #require(doc.tables.first { $0.style.name == "Academic" })535        #expect(table.rows[0].isHeader)536        #expect(table.rows[0].cells.allSatisfy { $0.borderTop != nil && $0.borderBottom != nil })537        #expect(table.rows.last!.cells.allSatisfy { $0.borderBottom != nil })538        #expect(table.rows.dropFirst().dropLast().allSatisfy { $0.cells.allSatisfy { $0.borderTop == nil && $0.borderBottom == nil } })539        #expect(table.style.innerVertical == nil && table.style.outerBorder == nil)540        let tableCaption = try #require(n.captions.first { $0.value.label == "Table" })541        #expect(doc.crossRefs.contains { $0.target == tableCaption.key })542        // Numeric columns are right-aligned through a style543        let numeric = table.rows[1].cells[1].paragraphs[0]544        #expect(doc.styles.paraProps(style: numeric.style, direct: numeric.props).alignment == .right)545        // Footnote, appendix, bibliography placeholders546        #expect(!doc.notes.isEmpty)547        #expect(doc.headings.contains { $0.style == "AppendixHeading" && !doc.styles.isNumberedHeading($0.style) })548        #expect(doc.bibliography.count == 2)549        for e in doc.bibliography {550            #expect(e.key.hasPrefix("placeholder"))551            #expect(e.title.hasPrefix("[") && e.title.hasSuffix("]"))552            #expect(e.authors.map(\.family) == [language == "fr" ? "Auteur" : "Author"])553            #expect(e.fields["DOI"] == nil && e.fields["URL"] == nil)554            #expect(e.fields.filter { $0.key != "title" }.values.allSatisfy { $0.hasPrefix("[") })555        }556        // The bibliography comes after the last citation557        let bibIndex = try #require(doc.body.firstIndex { if case .bibliography = $0 { return true } else { return false } })558        let lastCitation = doc.body.lastIndex { $0.paragraph?.runs.contains { if case .citation? = $0.inline { return true } else { return false } } ?? false }559        #expect((lastCitation ?? Int.max) < bibIndex)560    }561562    @Test(arguments: ["academic-paper", "research-report", "thesis"], languages)563    func placeholderBibliographyOnly(id: String, language: String) {564        let doc = make(id, language)565        #expect(doc.bibliography.allSatisfy { $0.key.hasPrefix("placeholder") && $0.title.hasPrefix("[") })566        #expect(doc.bibliography.allSatisfy { $0.authors.allSatisfy { ["Author", "Auteur"].contains($0.family) && $0.given.count == 2 } })567    }568569    @Test(arguments: languages)570    func thesisSections(language: String) throws {571        let doc = make("thesis", language)572        let n = Numbering(doc)573        #expect(doc.sections.count == 2)574        let front = doc.sections[0], main = doc.sections[1]575        #expect(front.pageNumberFormat == .lowerRoman && front.differentFirstPage && front.footer.first.isEmpty && front.header.isEmpty)576        #expect(main.pageNumberFormat == .decimal && main.pageNumberStart == 1 && main.differentOddEven && !main.differentFirstPage)577        guard case .sectionBreak(let br)? = doc.body.first(where: { if case .sectionBreak = $0 { return true } else { return false } }) else { Issue.record("no break"); return }578        #expect(br.kind == .oddPage)579        #expect(main.header.default.flatMap(\.runs).contains { $0.inline == .field(.headingText(level: 1)) })580        #expect(main.header.even.flatMap(\.runs).contains { $0.inline == .field(.title) })581        #expect(main.footer.default.flatMap(\.runs).contains { $0.inline == .field(.pageNumber) })582        #expect(main.footer.even.flatMap(\.runs).contains { $0.inline == .field(.pageNumber) })583        #expect(doc.tocBlocks.map(\.kind) == [.contents, .figures, .tables])584        // Generated lists sit in the front matter, chapters after the break.585        let breakIndex = try #require(doc.body.firstIndex { if case .sectionBreak = $0 { return true } else { return false } })586        #expect(doc.body[..<breakIndex].contains { if case .toc = $0 { return true } else { return false } })587        // Five numbered chapters, front matter and appendices unnumbered, chapter references read 2…5.588        let chapters = n.outline.filter { $0.level == 1 && $0.number != nil }589        #expect(chapters.map(\.number) == ["1", "2", "3", "4", "5"])590        #expect(chapters.allSatisfy { $0.blockIndex > breakIndex })591        #expect(n.outline.filter { $0.level == 1 && $0.number == nil }.count == 4)592        let chapterRefs = doc.crossRefs.filter { $0.display == .number }.map { n.crossRefText($0, pageOf: { _ in nil }) }593        #expect(chapterRefs.contains("2") && chapterRefs.contains("5"))594        #expect(doc.styles.style(StyleID.heading(1))?.para.pageBreakBefore == true)595        #expect(doc.pageSetup.margins.left > doc.pageSetup.margins.right)596    }597598    @Test(arguments: languages)599    func bookSections(language: String) throws {600        let doc = make("book-manuscript", language)601        let n = Numbering(doc)602        #expect(doc.sections.count == 2)603        #expect(doc.sections[0].pageNumberFormat == .lowerRoman && doc.sections[0].differentFirstPage)604        let main = doc.sections[1]605        #expect(main.pageNumberStart == 1 && main.pageNumberFormat == .decimal && main.differentOddEven)606        #expect(main.header.default.flatMap(\.runs).contains { $0.inline == .field(.headingText(level: 1)) })607        #expect(main.header.even.flatMap(\.runs).contains { $0.inline == .field(.author) })608        // Chapters number themselves with a sequence field and are real level-1 headings.609        let labels = doc.bodyParagraphs.filter { $0.style == "ChapterLabel" }610        #expect(labels.count == 2)611        #expect(labels.map { n.displayText(of: $0, document: doc) } == (language == "fr" ? ["Chapitre\u{A0}1", "Chapitre\u{A0}2"] : ["Chapter\u{A0}1", "Chapter\u{A0}2"]))612        #expect(doc.styles.paraProps(style: "ChapterLabel", direct: .none).pageBreakBefore)613        #expect(doc.headings.filter { $0.style == "ChapterTitle" }.count == 2)614        #expect(doc.styles.style("ChapterTitle")?.basedOn == StyleID.heading(1))615        #expect(doc.styles.paraProps(style: "FirstParagraph", direct: .none).dropCapLines == 3)616        #expect(doc.styles.paraProps(style: StyleID.normal, direct: .none).firstLineIndent > 0)617        // A drop cap needs a letter, not a bracket.618        for p in doc.bodyParagraphs where p.style == "FirstParagraph" { #expect(p.visibleText.first?.isLetter == true) }619    }620621    @Test(arguments: languages)622    func newsletterColumns(language: String) {623        let doc = make("newsletter", language)624        let breaks = doc.body.compactMap { b -> SectionBreak? in if case .sectionBreak(let s) = b { return s } else { return nil } }625        #expect(breaks.count == 2)626        #expect(breaks.allSatisfy { $0.kind == .continuous })627        #expect(breaks[0].setup.columns == 2 && breaks[0].setup.columnRule)628        #expect(breaks[1].setup.columns == 1)629        #expect(doc.pageSetup.columns == 1)630        // The figure fits its column.631        #expect(doc.shapes[0].width <= breaks[0].setup.columnWidth + 0.5)632        #expect(doc.bodyParagraphs.contains { $0.style == "Sidebar" } && doc.bodyParagraphs.contains { $0.style == "PullQuote" })633        #expect(doc.styles.paraProps(style: "Sidebar", direct: .none).shading != nil)634    }635636    @Test(arguments: languages)637    func financialReportTables(language: String) throws {638        let doc = make("financial-report", language)639        let french = language == "fr"640        #expect(doc.sections.map(\.landscape) == [false, true, false])641        #expect(doc.sections.allSatisfy { !$0.footer.default.isEmpty && !$0.header.default.isEmpty })642        // The wide table sits in the landscape section and uses its width.643        let breaks = doc.body.indices.filter { if case .sectionBreak = doc.body[$0] { return true } else { return false } }644        let wide = try #require(doc.body[breaks[0]..<breaks[1]].compactMap(\.table).first)645        #expect(wide.columnCount == 6)646        #expect(abs(wide.totalWidth - doc.sections[1].contentWidth) < 1)647        #expect(wide.totalWidth > doc.sections[0].contentWidth)648        #expect(doc.tables.count == 3)649        #expect(doc.formulaCells.count == 19)650        try checkFormulas(doc, french: french)651    }652653    @Test(arguments: ["financial-report", "invoice", "proposal", "project-report"], languages)654    func formulasMatchTheirText(id: String, language: String) throws {655        let doc = make(id, language)656        #expect(!doc.formulaCells.isEmpty)657        #expect(doc.formulaCells.contains { $0.formula == "=SUM(ABOVE)" })658        try checkFormulas(doc, french: language == "fr")659        // Numeric cells are right-aligned through their style; header rows are flagged.660        for t in doc.tables {661            #expect(t.rows[0].isHeader)662            for row in t.rows { for c in row.cells where c.formula != nil {663                let p = c.paragraphs[0]664                #expect(doc.styles.paraProps(style: p.style, direct: p.props).alignment == .right)665                #expect(p.props.isEmpty)666            } }667        }668    }669670    /// Recomputes every formula of the document from the cell texts and compares with the text of the formula cell.671    func checkFormulas(_ doc: DocumentModel, french: Bool) throws {672        for t in doc.tables {673            func value(_ r: Int, _ c: Int) -> Double? { parseNumber(t.rows[r].cells[c].plainText, french: french) }674            for (r, row) in t.rows.enumerated() {675                for (c, cell) in row.cells.enumerated() {676                    guard let formula = cell.formula else { continue }677                    let shown = try #require(value(r, c), "formula cell “\(cell.plainText)” is not a number")678                    var expected: Double679                    if formula == "=SUM(ABOVE)" {680                        expected = (0..<r).compactMap { t.rows[$0].isHeader ? nil : value($0, c) }.reduce(0, +)681                    } else if formula == "=SUM(LEFT)" {682                        expected = (0..<c).compactMap { value(r, $0) }.reduce(0, +)683                    } else {684                        expected = try #require(evaluate(String(formula.dropFirst()), in: t, french: french), "cannot evaluate \(formula)")685                    }686                    let decimals = cell.plainText.contains(french ? "," : ".") ? 2 : 0687                    if cell.plainText.contains("%") { expected = (expected * 10).rounded() / 10 }688                    let tolerance = cell.plainText.contains("%") ? 0.051 : (decimals == 2 ? 0.006 : 0.51)689                    #expect(abs(shown - expected) <= tolerance, "\(formula) shows \(cell.plainText), computed \(expected)")690                }691            }692        }693    }694695    /// A tiny evaluator for the cell-reference formulas the templates use: + − * / and parentheses over A1 references and numbers.696    func evaluate(_ expr: String, in t: Table, french: Bool) -> Double? {697        var tokens: [String] = []698        var cur = ""699        for ch in expr {700            if "+-*/()".contains(ch) { if !cur.isEmpty { tokens.append(cur); cur = "" }; tokens.append(String(ch)) } else { cur.append(ch) }701        }702        if !cur.isEmpty { tokens.append(cur) }703        var i = 0704        func atom() -> Double? {705            guard i < tokens.count else { return nil }706            let tok = tokens[i]; i += 1707            if tok == "(" { let v = sum(); i += 1; return v }708            if let d = Double(tok) { return d }709            guard let col = tok.unicodeScalars.first, col.value >= 65, col.value <= 90, let row = Int(tok.dropFirst()) else { return nil }710            let c = Int(col.value) - 65, r = row - 1711            guard r >= 0, r < t.rows.count, c < t.rows[r].cells.count else { return nil }712            return parseNumber(t.rows[r].cells[c].plainText, french: french)713        }714        func product() -> Double? {715            guard var v = atom() else { return nil }716            while i < tokens.count, tokens[i] == "*" || tokens[i] == "/" {717                let op = tokens[i]; i += 1718                guard let rhs = atom() else { return nil }719                v = op == "*" ? v * rhs : v / rhs720            }721            return v722        }723        func sum() -> Double? {724            guard var v = product() else { return nil }725            while i < tokens.count, tokens[i] == "+" || tokens[i] == "-" {726                let op = tokens[i]; i += 1727                guard let rhs = product() else { return nil }728                v = op == "+" ? v + rhs : v - rhs729            }730            return v731        }732        return sum()733    }734735    @Test(arguments: languages)736    func invoiceTotals(language: String) throws {737        let doc = make("invoice", language)738        let table = try #require(doc.tables.first)739        #expect(doc.tables.count == 1)740        let last = try #require(table.rows.last)741        #expect(last.cells[3].paragraphs[0].style == "InvoiceTotal")742        #expect(doc.styles.style("InvoiceTotal")?.basedOn == "TableTotalNumber")743        #expect(last.cells[3].plainText == (language == "fr" ? "2\u{A0}190,27\u{A0}$" : "$2,000.25"))744        #expect(table.rows.filter { $0.cells[3].formula?.contains("*C") == true }.count == 3)745        // Canadian French shows GST and QST.746        #expect(table.rows.count == (language == "fr" ? 8 : 7))747        #expect(doc.fullText.contains(language == "fr" ? "14 mars 2025" : "March 14, 2025"))748        #expect(doc.headerFooterFields.contains(.pageCount))749    }750751    @Test(arguments: languages)752    func legalMemorandum(language: String) throws {753        let doc = make("legal-memorandum", language)754        let n = Numbering(doc)755        // Header block: label, tab, value on a hanging indent756        let header = doc.bodyParagraphs.filter { $0.style == "MemoHeader" || $0.style == "MemoHeaderLast" }757        #expect(header.count == 5)758        for p in header {759            #expect(p.runs[0].charStyle == StyleID.strong && p.runs[1].text == "\t")760            let resolved = doc.styles.paraProps(style: p.style, direct: p.props)761            #expect(resolved.tabs.count == 1 && resolved.firstLineIndent < 0 && resolved.indentLeft == resolved.tabs[0].position)762        }763        #expect(header.last?.style == "MemoHeaderLast")764        #expect(doc.styles.paraProps(style: "MemoHeaderLast", direct: .none).borderBottom != nil)765        // Numbered headings 1 … 5 with 4.1 and 4.2766        #expect(n.outline.compactMap(\.number) == ["1", "2", "3", "4", "4.1", "4.2", "5"])767        // Numbered paragraphs from multilevel lists768        let items = doc.bodyParagraphs.filter { $0.list != nil }769        #expect(items.compactMap { n.listLabels[$0.id] } == ["1.", "2.", "1.", "1.1.", "2."])770        #expect(items.allSatisfy { $0.style == "NumberedParagraph" })771        // Confidentiality footer with page x of y, on every page772        #expect(!doc.pageSetup.differentFirstPage)773        let footer = try #require(doc.pageSetup.footer.default.first)774        #expect(footer.visibleText.contains(language == "fr" ? "Privilégié et confidentiel" : "Privileged and confidential"))775        #expect(footer.runs.contains { $0.inline == .field(.pageNumber) } && footer.runs.contains { $0.inline == .field(.pageCount) })776        // Section references render with their numbers777        let refs = doc.crossRefs.map { n.crossRefText($0, pageOf: { _ in nil }) }778        #expect(refs == (language == "fr" ? ["3", "4.1"] : ["Section 3", "Section 4.1"]))779        #expect(doc.notes.count == 1)780    }781782    @Test(arguments: languages)783    func lettersAndResume(language: String) {784        let letter = make("business-letter", language)785        #expect(letter.pageSetup.differentFirstPage && letter.pageSetup.header.first.isEmpty)786        #expect(letter.pageSetup.header.default.flatMap(\.runs).contains { $0.inline == .field(.pageNumber) })787        for style in ["Letterhead", "Recipient", "Subject", "Salutation", "Closing", "Signature"] {788            #expect(letter.bodyParagraphs.contains { $0.style == style }, "no \(style) paragraph")789            #expect(letter.styles.chain(style).first?.id == StyleID.normal)790        }791        #expect(letter.headings.isEmpty)792        #expect(letter.bodyParagraphs.contains { $0.style == "Signature" && $0.runs.contains { $0.inline == .field(.author) } })793794        let cover = make("cover-letter", language), resume = make("resume", language)795        #expect(cover.pageSetup.header.isEmpty && cover.pageSetup.footer.isEmpty)796        // The two application documents share their identity block.797        #expect(cover.styles.style("ApplicantName") == resume.styles.style("ApplicantName"))798        #expect(cover.styles.themeName == resume.styles.themeName)799        #expect(resume.headings.count == 5 && resume.headings.allSatisfy { resume.outlineLevel($0) == 1 })800        #expect(resume.bodyParagraphs.filter { $0.style == "EntryTitle" }.allSatisfy { $0.runs.contains { $0.text == "\t" } })801        #expect(resume.styles.paraProps(style: "EntryTitle", direct: .none).tabs.last?.kind == .right)802        #expect(resume.bodyParagraphs.filter { $0.list != nil }.count >= 6)803    }804805    @Test(arguments: languages)806    func manualMinutesAndReports(language: String) {807        let manual = make("technical-manual", language)808        let n = Numbering(manual)809        #expect(n.outline.filter { $0.level == 1 }.compactMap(\.number) == ["1", "2", "3", "4", "5"])810        #expect(n.headingNumbers.values.contains("3.2.1"))811        #expect(manual.bodyParagraphs.contains { $0.style == "Note" } && manual.bodyParagraphs.contains { $0.style == "Warning" })812        #expect(manual.bodyParagraphs.contains { $0.style == StyleID.code })813        #expect(manual.bodyParagraphs.contains { $0.list?.level == 1 })814        #expect(manual.tocBlocks.map(\.kind) == [.contents, .figures, .tables])815        #expect(manual.pageSetup.header.default.flatMap(\.runs).contains { $0.inline == .field(.headingText(level: 1)) })816817        let minutes = make("meeting-minutes", language)818        let mn = Numbering(minutes)819        let agenda = minutes.bodyParagraphs.filter { $0.list != nil }820        #expect(agenda.compactMap { mn.listLabels[$0.id] } == ["1.", "2.", "3.", "4.", "5.", "6."])821        #expect(minutes.tables.count == 1 && minutes.tables[0].rows[0].isHeader && minutes.tables[0].columnCount == 5)822        #expect(minutes.bodyParagraphs.filter { $0.style == "Decision" }.count == 2)823824        let project = make("project-report", language)825        #expect(project.tables.count == 3)826        #expect(project.pageSetup.header.default.flatMap(\.runs).contains { $0.inline == .field(.date(format: language == "fr" ? "d MMMM yyyy" : "MMMM d, yyyy")) })827        #expect(Numbering(project).captions.values.filter { $0.label == "Table" }.map(\.number).sorted() == [1, 2, 3])828829        let report = make("research-report", language)830        let rn = Numbering(report)831        #expect(rn.outline.filter { $0.level == 1 }.compactMap(\.number) == ["1", "2", "3", "4", "5"])832        #expect(report.pageSetup.differentFirstPage && report.pageSetup.header.first.isEmpty && report.pageSetup.footer.first.isEmpty)833        #expect(report.pageSetup.header.default.flatMap(\.runs).contains { $0.inline == .field(.title) })834835        let proposal = make("proposal", language)836        #expect(proposal.tables.count == 2)837        #expect(proposal.styles.paraProps(style: "SignatureLine", direct: .none).tabs.filter { $0.leader == .line }.count == 2)838    }839840    @Test func blankDocument() {841        let doc = TemplateLibrary.blank.make(sampleContext("fr", paper: .a4))842        #expect(doc.body.count == 1)843        #expect(doc.body[0].paragraph?.isEmpty == true)844        #expect(doc.body[0].paragraph?.style == StyleID.normal)845        // The standard sheet, untouched except for the header tab stops that follow the text width of the paper.846        let standard = StyleSheet.standard(theme: .orix)847        #expect(doc.styles.styles.map(\.id) == standard.styles.map(\.id))848        #expect(doc.styles.styles.filter { $0.id != StyleID.header } == standard.styles.filter { $0.id != StyleID.header })849        #expect(doc.styles.style(StyleID.header)?.para.tabs?.last?.position == doc.pageSetup.contentWidth)850        #expect(TemplateLibrary.blank.make(sampleContext("en")).styles.styles == standard.styles)851        #expect(doc.lists.isEmpty && doc.notes.isEmpty && doc.bibliography.isEmpty)852        #expect(doc.pageSetup.paper == .a4 && doc.pageSetup.header.isEmpty && doc.pageSetup.footer.isEmpty)853        #expect(doc.meta.language == "fr-CA")854    }855}856
Files main
Menu

Theme