SPB Git

Repository Public

ImportHandAuthoredTests.swift 20.4 KB 304 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Tests/DocDOCXTests/ImportHandAuthoredTests.swift3// Description: Import fidelity on hand-authored OOXML: tracked changes, comments, fields, drawings, tables, sections,4//              styles, numbering, notes, links and equations. Assertions are on the resulting model and on the warnings.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Testing10import DocModel11import DocContainer12@testable import DocDOCX1314@Suite("DOCX import — hand-authored packages")15struct ImportHandAuthoredTests {16    func date(_ s: String) -> Date { ISO8601DateFormatter().date(from: s)! }17    func has(_ r: ImportResult, _ feature: String, _ severity: FormatWarning.Severity? = nil) -> Bool {18        r.warnings.contains { $0.feature == feature && (severity == nil || $0.severity == severity) }19    }2021    @Test func trackedInsertionsDeletionsAndFormatChanges() throws {22        let r = try DocxImporter.importDocument(try Hand.trackedChanges())23        let doc = r.document24        #expect(doc.settings.trackChanges)25        let p = doc.bodyParagraphs[0]26        #expect(p.runs.map(\.text) == ["Keep ", "added", "removed", "bolded"])27        #expect(p.runs[0].revision == nil)28        #expect(p.runs[1].revision?.kind == .insertion)29        #expect(p.runs[1].revision?.author == "Alice")30        #expect(p.runs[1].revision?.date == date("2026-01-02T03:04:05Z"))31        #expect(p.runs[2].revision?.kind == .deletion)32        #expect(p.runs[2].revision?.author == "Bob")33        #expect(p.runs[2].revision?.date == date("2026-02-03T04:05:06Z"))34        #expect(p.runs[3].props.bold == true)35        let fr = try #require(p.runs[3].formatRevision)36        #expect(fr.author == "Carol" && fr.date == date("2026-03-04T05:06:07Z"))37        #expect(fr.previous == CharProps(italic: true))38        #expect(p.visibleText == "Keep addedbolded")39        #expect(p.plainText == "Keep addedremovedbolded")40        #expect(doc.bodyParagraphs[1].markRevision?.kind == .insertion)41        #expect(doc.bodyParagraphs[1].markRevision?.author == "Alice")42        #expect(doc.bodyParagraphs[2].markRevision?.kind == .deletion)43        #expect(doc.bodyParagraphs[2].markRevision?.author == "Bob")44        // Two runs inside one w:ins share one revision; a tracked move is a deletion.45        let q = doc.bodyParagraphs[3]46        #expect(q.runs.count == 3)47        #expect(q.runs[0].revision == q.runs[1].revision && q.runs[0].revision?.author == "Dana")48        #expect(q.runs[2].revision?.kind == .deletion && q.runs[2].revision?.author == "Eve")49        #expect(has(r, "Tracked moves", .approximated))50        #expect(doc.bodyParagraphs.allSatisfy { $0.hasTrackedChanges })51    }5253    @Test func commentRangesRepliesAndResolvedFlag() throws {54        let r = try DocxImporter.importDocument(try Hand.comments())55        let doc = r.document56        #expect(doc.comments.count == 3)57        let top = doc.comments[0], multi = doc.comments[1], point = doc.comments[2]58        #expect(top.author == "Alice Martin" && top.text == "Top comment" && !top.resolved)59        #expect(top.date == date("2026-06-01T10:00:00Z"))60        #expect(top.replies.count == 1)61        #expect(top.replies[0].author == "Bob" && top.replies[0].text == "Reply text" && top.replies[0].date == date("2026-06-01T11:00:00Z"))62        #expect(multi.author == "Carol" && multi.text == "First line\nSecond line" && multi.resolved && multi.replies.isEmpty)63        #expect(point.text == "No range")64        let p = doc.bodyParagraphs65        #expect(p[0].runs.map(\.text) == ["Before ", "commented", " after"])66        #expect(p[0].runs.map(\.comments) == [[], [top.id], []])67        #expect(p[1].runs.map(\.comments) == [[], [multi.id]])68        #expect(p[2].runs.map(\.comments) == [[multi.id], []])69        // A comment that covers no text is anchored on the run before its reference.70        #expect(p[3].runs.last?.comments == [point.id])71        #expect(!has(r, "Comments"))72    }7374    @Test func fieldsBecomeModelFields() throws {75        let r = try DocxImporter.importDocument(try Hand.fields())76        let doc = r.document77        let p = doc.bodyParagraphs78        #expect(p[1].runs.compactMap(\.inline) == [.field(.pageNumber), .field(.pageCount), .field(.date(format: "EEEE, d MMMM yyyy"))])79        #expect(p[1].visibleText == "Page  of  on ")           // cached results are not left as text80        #expect(p[2].runs.compactMap(\.inline) == [.field(.title), .field(.author)])81        #expect(p[3].style == StyleID.caption)82        #expect(p[3].runs.compactMap(\.inline) == [.bookmark("_Ref200"), .field(.sequence("Figure"))])83        #expect(p[3].visibleText == "Figure : The first figure")84        let refs: [CrossRef] = p[5].runs.compactMap { if case .crossRef(let c)? = $0.inline { return c } else { return nil } }85        // What the bookmark covers decides the display: label and number, number only, whole heading; PAGEREF is a page reference.86        #expect(refs == [CrossRef(target: "_Ref200", display: .labelAndNumber), CrossRef(target: "_Ref300", display: .number),87                         CrossRef(target: "_Ref100", display: .text), CrossRef(target: "_Ref100", display: .page)])88        let numbering = Numbering(doc)89        #expect(numbering.crossRefText(refs[0], pageOf: { _ in nil }) == "Figure 1")90        #expect(numbering.crossRefText(refs[1], pageOf: { _ in nil }) == "2")91        #expect(numbering.crossRefText(refs[2], pageOf: { _ in nil }) == "Results")92        #expect(numbering.crossRefText(refs[3], pageOf: { _ in "7" }) == "7")93        // HYPERLINK fields keep their result and carry the link.94        #expect(p[6].runs.first { $0.text == "the site" }?.props.link == "https://example.org/a b")95        #expect(p[6].runs.first { $0.text == "the results" }?.props.link == "#_Ref100")96        #expect(p[6].visibleText == "Go to the site or the results.")97        // Unknown fields and broken references keep their displayed text and are reported.98        #expect(p[7].visibleText == "Dear «FirstName», ref Error! Reference source not found.")99        #expect(has(r, "Fields", .approximated))100        #expect(has(r, "Cross-references", .approximated))101        // The TOC field with its stale multi-paragraph result is one block.102        let tocIndex = try #require(doc.body.firstIndex { if case .toc = $0 { return true } else { return false } })103        if case .toc(let toc) = doc.body[tocIndex] { #expect(toc.kind == .contents && toc.maxLevel == 2 && toc.title == nil) }104        #expect(doc.body[tocIndex + 1].paragraph?.visibleText == "After the contents.")105        #expect(!doc.bodyLines.contains { $0.contains("Stale entry") || $0.contains("Results 1") })106    }107108    @Test func drawingsPicturesShapesAndUnsupportedObjects() throws {109        let r = try DocxImporter.importDocument(try Hand.drawings())110        let doc = r.document111        let images: [ImageObject] = doc.inlines.compactMap { if case .image(let i) = $0 { return i } else { return nil } }112        // Anchored, inline and the OLE preview; the linked and the escaping pictures are dropped.113        #expect(images.count == 3)114        #expect(doc.assets.count == 1)115        #expect(doc.assets.values.first?.data == Pkg.png)116        let anchored = images[0]117        #expect(anchored.placement == .floating(wrap: .topAndBottom, align: .left, xOffset: 20, yOffset: 10))118        #expect(anchored.altText == "Anchored alt text")119        #expect(anchored.width == 100 && anchored.height == 50)120        #expect(anchored.crop == Insets(top: 0.2, left: 0.1, bottom: 0, right: 0.05))121        #expect(anchored.rotation == 90)122        #expect(images[1].placement == .inline && images[1].altText == "Inline alt" && images[1].width == 50)123        #expect(has(r, "Linked pictures", .dropped))124        #expect(has(r, "Unsafe relationship", .dropped))125        // Text box: text kept after the host paragraph, the VML fallback copy is not imported twice.126        let lines = doc.bodyLines127        let host = try #require(lines.firstIndex(of: "Host paragraph"))128        #expect(Array(lines[(host + 1)...(host + 2)]) == ["Text box first", "Text box second"])129        #expect(!lines.contains("FALLBACK COPY"))130        #expect(has(r, "Text boxes", .approximated))131        // A preset shape with a one-line label is a ShapeObject.132        let shapes: [ShapeObject] = doc.inlines.compactMap { if case .shape(let s) = $0 { return s } else { return nil } }133        #expect(shapes.count == 1)134        #expect(shapes.first?.kind == .ellipse && shapes.first?.text == "Label" && shapes.first?.altText == "An ellipse")135        #expect(shapes.first?.fill == RGBA(hex: 0xFFCC00) && shapes.first?.stroke == RGBA(hex: 0x112233) && shapes.first?.strokeWidth == 2)136        #expect(shapes.first?.width == 100 && shapes.first?.height == 50)137        #expect(has(r, "Charts", .dropped))138        #expect(has(r, "SmartArt", .dropped))139        #expect(has(r, "Embedded objects", .dropped))140        #expect(doc.preservedParts.keys.allSatisfy { !$0.contains("embeddings") })141        // Unknown run content: reported by name, text kept.142        #expect(r.warnings.contains { $0.feature == "Unsupported content" && $0.detail.contains("w:fancyNewThing") })143        #expect(lines.contains("Unknown: inner text"))144    }145146    @Test func tableGridMergesBordersShading() throws {147        let r = try DocxImporter.importDocument(try Hand.tables())148        let t = try #require(r.document.tables.first)149        #expect(t.columnWidths == [100, 150, 50])150        #expect(t.alignment == .center)151        #expect(t.rows.count == 4)152        #expect(t.rows[0].isHeader && t.rows[0].minHeight == 20)153        #expect(t.rows[0].cells.map(\.colSpan) == [2, 1])154        #expect(t.rows[0].cells[0].shading == RGBA(hex: 0xDDEEFF))155        #expect(t.rows[0].cells[1].vAlign == .bottom)156        #expect(t.rows[1].cells[0].vMerge == .restart && t.rows[1].cells[0].vAlign == .center)157        #expect(t.rows[2].cells[0].vMerge == .continue)158        #expect(t.rows[1].cells[1].borderBottom == BorderLine(width: 1.5, color: RGBA(hex: 0x00FF00), style: .double))159        #expect(t.style.outerBorder == BorderLine(width: 1, color: RGBA(hex: 0xFF0000)))160        #expect(t.style.innerHorizontal == BorderLine(width: 0.5, color: .black, style: .dotted))161        #expect(t.style.innerVertical == nil)162        #expect(t.style.cellPadding.left == 5 && t.style.cellPadding.right == 5)163        // Nested table: flattened into the cell's paragraphs, reported.164        #expect(t.rows[3].cells[1].paragraphs.map(\.visibleText) == ["Outer cell", "Nested one", "Nested two", ""])165        #expect(has(r, "Nested tables", .approximated))166        #expect(r.document.bodyLines.last == "After table")167    }168169    @Test func sectionPropertiesMoveFromLastParagraphToBreak() throws {170        let r = try DocxImporter.importDocument(try Hand.sections())171        let doc = r.document172        // Section 1 is described by the sectPr found in ITS last paragraph.173        let s1 = doc.pageSetup174        #expect(s1.paper == .letter && !s1.landscape)175        #expect(s1.margins == Insets(top: 72, left: 90, bottom: 72, right: 54))176        #expect(s1.headerDistance == 36 && s1.footerDistance == 30)177        #expect(s1.differentFirstPage && s1.differentOddEven)178        #expect(s1.header.default.map(\.visibleText) == ["First section header"])179        #expect(s1.header.first.map(\.visibleText) == ["Title page header"])180        #expect(s1.footer.default.first?.runs.compactMap(\.inline) == [.field(.pageNumber)])181        #expect(s1.footer.even.map(\.visibleText) == ["Even footer"])182        #expect(s1.watermark == nil)183184        let kinds = doc.body.map { b -> String in185            switch b {186            case .paragraph(let p): return "P:" + p.visibleText187            case .sectionBreak(let s): return "S:" + s.kind.rawValue188            case .pageBreak(let b): return "B:" + b.kind.rawValue189            default: return "?"190            }191        }192        #expect(kinds == ["P:Section one, paragraph one", "P:Section one, last paragraph", "S:continuous", "P:Section two text", "B:page", "P:After page break",193                          "P:Before column break", "B:column", "P:After column break", "P:", "S:oddPage", "P:Section three inherits headers"])194        // (The empty paragraph is the one that carries the second sectPr in the file: after a paragraph it is content, a blank line before the break.)195        let breaks: [SectionBreak] = doc.body.compactMap { if case .sectionBreak(let s) = $0 { return s } else { return nil } }196        // The first break starts section 2, whose properties (and start type) come from the SECOND sectPr.197        let s2 = breaks[0].setup198        #expect(s2.landscape && s2.paper == .letter && s2.columns == 2 && s2.columnGap == 18 && s2.columnRule)199        #expect(s2.pageNumberStart == 5 && s2.pageNumberFormat == .lowerRoman)200        #expect(s2.margins == Insets(all: 36))201        #expect(s2.header.default.map(\.visibleText) == ["Second section header"])202        #expect(s2.watermark == "CONFIDENTIAL")203        #expect(s2.footer.default.first?.runs.compactMap(\.inline) == [.field(.pageNumber)])     // inherited from section 1204        #expect(!s2.differentFirstPage)205        // The last section comes from the body-level sectPr and inherits the headers of section 2.206        let s3 = breaks[1].setup207        #expect(s3.paper == .a4 && !s3.landscape && s3.columns == 1)208        #expect(s3.header.default.map(\.visibleText) == ["Second section header"])209        #expect(s3.border == PageBorder(line: BorderLine(width: 1.5, color: RGBA(hex: 0x0000FF)), inset: 24))210        #expect(has(r, "Page breaks inside paragraphs", .approximated))211        #expect(doc.sectionSetups.count == 3)212    }213214    @Test func stylesNumberingNotesLinksAndDirectFormatting() throws {215        let r = try DocxImporter.importDocument(try Hand.stylesAndLists())216        let doc = r.document217        // Document defaults, theme fonts resolved from the (preserved) theme part.218        #expect(doc.styles.defaultChar.fontFamily == "Charter")219        #expect(doc.styles.defaultChar.fontSize == 11)220        #expect(doc.styles.defaultChar.language == "fr-CA")221        #expect(doc.styles.defaultPara.spaceAfter == 8)222        #expect(doc.preservedParts["word/theme/theme1.xml"] != nil)223        // A localised heading id maps to the Word built-in id through its name.224        let h1 = try #require(doc.styles.style(StyleID.heading(1)))225        #expect(doc.styles.style("Titre1") == nil)226        #expect(h1.basedOn == StyleID.normal && h1.next == StyleID.normal)227        #expect(h1.char == CharProps(fontFamily: "Avenir Next", fontSize: 16, bold: true, color: RGBA(hex: 0x2F5496)))228        #expect(h1.para.keepWithNext == true && h1.para.spaceBefore == 12 && h1.para.outlineLevel == 1)229        #expect(h1.numbered)230        let h2 = try #require(doc.styles.style(StyleID.heading(2)))231        #expect(h2.basedOn == StyleID.heading(1) && h2.numbered && h2.char.fontSize == 13)232        #expect(doc.styles.style(StyleID.emphasis)?.kind == .character)233        #expect(doc.styles.style("Code")?.char == CharProps(fontFamily: "Menlo", fontSize: 9.5))234        #expect(doc.bodyParagraphs[0].style == StyleID.heading(1))235        let numbering = Numbering(doc)236        #expect(numbering.headingNumbers[doc.bodyParagraphs[0].id] == "1")237        #expect(numbering.headingNumbers[doc.bodyParagraphs[1].id] == "1.1")238        // Lists: start values, level patterns, symbol-font bullet, numbering through a style, start override. The heading numbering is not a list.239        #expect(doc.lists.count == 3)240        let items = doc.bodyParagraphs.filter { $0.list != nil }241        #expect(items.map { numbering.listLabels[$0.id] ?? "" } == ["3.", "4.", "a)", "4.a.I", "5.", "•", "•", "10."])242        #expect(items.map(\.visibleText) == ["Three", "Four", "Sub a", "Deep", "Five", "Bullet", "Styled bullet", "Ten"])243        #expect(doc.list(items[0].list!.listID)?.levels[1].indent == 72)244        #expect(doc.list(items[0].list!.listID)?.levels[1].hanging == 18)245        // Character styles, notes.246        let p = try #require(doc.firstParagraph(containing: "accent"))247        #expect(p.runs.first { $0.text == "accent" }?.charStyle == StyleID.emphasis)248        #expect(p.runs.first { $0.text == "code" }?.charStyle == "Code")249        let notes: [NoteRef] = p.runs.compactMap { if case .note(let n)? = $0.inline { return n } else { return nil } }250        #expect(notes.map(\.kind) == [.footnote, .endnote])251        // The superscript Word puts on the reference mark is not kept as direct formatting.252        #expect(p.runs.first { $0.inline == .note(notes[0]) }?.props == CharProps.none)253        let fn = try #require(doc.notes[notes[0].id])254        #expect(fn.paragraphs.map(\.visibleText) == ["Footnote body with a link"])255        #expect(fn.paragraphs[0].runs.first { $0.text == "a link" }?.props.link == "https://example.org/note")256        #expect(doc.notes[notes[1].id]?.paragraphs.map(\.visibleText) == ["Endnote body", "Endnote second paragraph"])257        // Links and bookmarks.258        let links = try #require(doc.firstParagraph(containing: "External"))259        #expect(links.runs.first { $0.text == "External" }?.props.link == "https://example.org/ext?a=1&b=2")260        #expect(links.runs.first { $0.text == "Internal" }?.props.link == "#target")261        #expect(links.runs.contains { $0.inline == .bookmark("target") })262        // Direct paragraph and run formatting.263        let f = try #require(doc.firstParagraph(containing: "Formatted"))264        #expect(f.props == ParaProps(alignment: .justified, indentLeft: 36, indentRight: 18, firstLineIndent: -18, spaceBefore: 6, spaceAfter: 12, lineSpacing: .exact(18),265                                     keepWithNext: true, keepLinesTogether: true, pageBreakBefore: true, widowControl: false,266                                     tabs: [TabStop(position: 450, kind: .right, leader: .dots), TabStop(position: 200, kind: .decimal)], hyphenate: false,267                                     shading: RGBA(hex: 0xEEEEEE), borderTop: BorderLine(width: 1, color: RGBA(hex: 0xFF0000)),268                                     borderLeft: BorderLine(width: 2, color: RGBA(hex: 0x00FF00), style: .dashed), rightToLeft: true))269        #expect(f.runs[0].props == CharProps(fontFamily: "Courier New", fontSize: 13.5, bold: true, italic: false, underline: true, strikethrough: true,270                                             color: RGBA(hex: 0x123456), highlight: RGBA(hex: 0x00FFFF), vertical: .subscript, baselineShift: 3, tracking: 1,271                                             kerning: false, smallCaps: false, allCaps: true, language: "de-DE"))272        #expect(f.runs[1].text == "\ttab\u{2028}line\u{2011}\u{AD}•")273        #expect(has(r, "Symbol characters", .approximated))274        // Core properties.275        #expect(doc.meta.title == "Titre du document" && doc.meta.author == "Auteure" && doc.meta.subject == "Sujet")276        #expect(doc.meta.keywords == ["alpha", "beta", "gamma"])277        #expect(doc.meta.language == "fr-CA")278        #expect(doc.meta.created == date("2026-01-15T08:30:00Z") && doc.meta.modified == date("2026-02-20T09:45:00Z"))279    }280281    @Test func wordStyleEquationsAndUnknownMathAreNeverDropped() throws {282        let r = try DocxImporter.importDocument(try Hand.equations())283        let eqs: [Equation] = r.document.inlines.compactMap { if case .equation(let e) = $0 { return e } else { return nil } }284        #expect(eqs.count == 3)285        #expect(eqs[0] == Equation(latex: "a=\\frac{1}{2}", display: false))286        #expect(eqs[1] == Equation(latex: "\\sum_{k=1}^{n}k^{2}", display: true))287        // The unknown construct is reported and its content survives inside the LaTeX.288        #expect(eqs[2].latex.contains("x") && eqs[2].latex.contains("kept"))289        #expect(r.warnings.contains { $0.feature == "Equations" && $0.severity == .approximated && $0.detail.contains("mysteryElement") })290    }291292    @Test func strictNamespacesAndUnusualPrefixesAreRead() throws {293        // The same document with the ISO "strict" namespace bound to another prefix.294        let strict = "http://purl.oclc.org/ooxml/wordprocessingml/main"295        let xml = Pkg.head + "<x:document xmlns:x=\"\(strict)\"><x:body><x:p><x:pPr><x:jc x:val=\"center\"/></x:pPr><x:r><x:rPr><x:b/></x:rPr><x:t>Strict text</x:t></x:r></x:p><x:sectPr><x:pgSz x:w=\"595.3pt\" x:h=\"841.9pt\"/></x:sectPr></x:body></x:document>"296        let data = try Pkg.make(body: "", parts: ["word/document.xml": xml])297        let doc = try DocxImporter.importDocument(data).document298        #expect(doc.bodyLines == ["Strict text"])299        #expect(doc.bodyParagraphs[0].props.alignment == .center)300        #expect(doc.bodyParagraphs[0].runs[0].props.bold == true)301        #expect(doc.pageSetup.paper == .a4)302    }303}304
Files main
Menu

Theme