SPB Git

Repository Public

ToolCrossCheckTests.swift 25.6 KB 405 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Tests/DocFormatsTests/ToolCrossCheckTests.swift3// Description: Cross-checks against independent tools: pandoc parses what we export (and we import what pandoc writes),4//              textutil converts our RTF and HTML to text. Every test is skipped cleanly when its tool is not installed.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Testing9import Foundation10import DocModel11import DocContainer12@testable import DocFormats1314/// A flattened view of a pandoc JSON AST: block and inline constructor names in document order, and the text.15struct PandocAST {16    var blocks: [String] = []          // top-level block types, headers as "Header1"…17    var inlines: Set<String> = []18    var words: [String] = []19    var links: [String] = []20    var math: [String] = []21    var citations: [String] = []22    var code: [String] = []23    var notes = 024    var listDepth = 025    /// "Plain" blocks: the content of tight list items and of table cells.26    var plains = 027    var images = 02829    init?(json: Data) {30        guard let root = try? JSONSerialization.jsonObject(with: json) as? [String: Any], let top = root["blocks"] as? [[String: Any]] else { return nil }31        for block in top {32            let type = block["t"] as? String ?? "?"33            if type == "Header", let content = block["c"] as? [Any], let level = content.first as? Int { blocks.append("Header\(level)") } else { blocks.append(type) }34        }35        walk(top, depth: 0)36    }3738    private mutating func walk(_ node: Any, depth: Int) {39        if let array = node as? [Any] { for item in array { walk(item, depth: depth) }; return }40        guard let object = node as? [String: Any] else { return }41        guard let type = object["t"] as? String else { for value in object.values { walk(value, depth: depth) }; return }42        let content = object["c"]43        switch type {44        case "Str": if let s = content as? String { words.append(contentsOf: Tool.words(s)) }45        case "Code":46            inlines.insert(type)47            if let parts = content as? [Any], let s = parts.last as? String { code.append(s); words.append(contentsOf: Tool.words(s)) }48        case "CodeBlock":49            if let parts = content as? [Any], let s = parts.last as? String { code.append(s); words.append(contentsOf: Tool.words(s)) }50        case "Math":51            inlines.insert(type)52            if let parts = content as? [Any], let kind = (parts.first as? [String: Any])?["t"] as? String, let s = parts.last as? String { math.append("\(kind):\(s)") }53        case "Link":54            inlines.insert(type)55            if let parts = content as? [Any], parts.count == 3, let target = parts[2] as? [Any], let url = target.first as? String { links.append(url) }56            if let parts = content as? [Any], parts.count == 3 { walk(parts[1], depth: depth) }57        case "Image":58            inlines.insert(type); images += 159            if let parts = content as? [Any], parts.count == 3 { walk(parts[1], depth: depth) }60        case "Cite":61            inlines.insert(type)62            if let parts = content as? [Any], let items = parts.first as? [[String: Any]] { citations.append(contentsOf: items.compactMap { $0["citationId"] as? String }) }63        case "Note":64            inlines.insert(type); notes += 165            if let content { walk(content, depth: depth) }66        case "BulletList", "OrderedList":67            listDepth = max(listDepth, depth + 1)68            if let content { walk(content, depth: depth + 1) }69        case "Plain":70            plains += 171            if let content { walk(content, depth: depth) }72        case "RawInline", "RawBlock": inlines.insert(type)73        default:74            if ["Strong", "Emph", "Strikeout", "Underline", "Subscript", "Superscript", "SoftBreak", "LineBreak", "Span", "Quoted"].contains(type) { inlines.insert(type) }75            if let content { walk(content, depth: depth) }76        }77    }78}7980@Suite struct PandocCrossCheckTests {81    static let available = Tool.available(Tool.pandoc)8283    /// A document limited to what Markdown and HTML both express, with known text.84    static func sample() -> DocumentModel {85        var doc = DocumentModel(meta: DocumentMetadata(title: "Cross check", author: "Ada Lovelace", language: "en"))86        doc.lists = [.bullets(id: "b"), .numbered(id: "n")]87        doc.lists[1].levels[0].start = 388        func item(_ text: String, _ list: String, _ level: Int = 0) -> Block { .paragraph(Paragraph(style: StyleID.listParagraph, runs: [Run(text)], list: ListItem(listID: list, level: level))) }89        let note = Note(id: "n1", kind: .footnote, paragraphs: [Paragraph("Footnote body text.", style: StyleID.footnoteText)])90        doc.notes = [note.id: note]91        var table = Table(strings: [["Name", "Value"], ["alpha", "1"], ["beta gamma", "2"]], width: 300)92        table.rows[0].cells = table.rows[0].cells.map { cell in var c = cell; c.paragraphs[0].runs = c.paragraphs[0].runs.map { Run($0.text) }; return c }93        doc.body = [94            .paragraph(Paragraph("First heading", style: StyleID.heading(1))),95            .paragraph(Paragraph(runs: [Run("Plain text with "), Run("bold words", props: CharProps(bold: true)), Run(", "), Run("italic words", props: CharProps(italic: true)), Run(", "),96                                        Run("struck", props: CharProps(strikethrough: true)), Run(", "), Run("inline code", charStyle: StyleID.inlineCode), Run(" and a "),97                                        Run("link", props: CharProps(link: "https://example.org/path?x=1"), charStyle: StyleID.hyperlink), Run(". Symbols: * _ [ ] # < > & $ ~ ^ | \\ survive"),98                                        Run(inline: .note(NoteRef(kind: .footnote, id: note.id))), Run(". Equation "), Run(inline: .equation(Equation(latex: "a^2 + b^2 = c^2"))), Run(" inline.")])),99            .paragraph(Paragraph("Second level", style: StyleID.heading(2))),100            item("first bullet", "b"), item("nested bullet", "b", 1), item("deeper bullet", "b", 2), item("second bullet", "b"),101            item("third", "n"), item("fourth", "n"),102            .paragraph(Paragraph("A quoted paragraph.", style: StyleID.quote)),103            .paragraph(Paragraph("func main() {\u{2028}    print(\"<hi> & bye\")\u{2028}}", style: StyleID.code)),104            .table(table),105            .paragraph(Paragraph(runs: [Run(inline: .equation(Equation(latex: "\\sum_{i=1}^{n} i = \\frac{n(n+1)}{2}", display: true)))])),106            .paragraph(ModelIdiom.rule()),107            .paragraph(Paragraph("Ünïcödé: 中文 العربية עברית 👩‍👩‍👧‍👦 e\u{301}.")),108            .paragraph(Paragraph("Line one\u{2028}line two after a break.")),109        ]110        return doc111    }112113    static let expectedWords: [String] = {114        let doc = sample()115        var words: [String] = []116        for block in doc.body {117            switch block {118            case .paragraph(let p): words += Tool.words(p.visibleText.replacingOccurrences(of: "\u{2028}", with: " "))119            case .table(let t): for row in t.rows { for cell in row.cells { words += Tool.words(cell.plainText) } }120            default: break121            }122            if case .paragraph(let p) = block, p.runs.contains(where: { if case .note? = $0.inline { return true } else { return false } }) {123                // pandoc inlines the note content at its reference.124            }125        }126        return words127    }()128129    private func pandoc(_ arguments: [String], _ input: Data) throws -> Data {130        let result = try #require(Tool.run(Tool.pandoc, arguments, input: input))131        #expect(result.status == 0)132        return result.output133    }134135    @Test(.enabled(if: available, "pandoc is not installed")) func pandocParsesOurMarkdownAsWeMeantIt() throws {136        let doc = PandocCrossCheckTests.sample()137        let markdown = MarkdownExporter.export(doc).data138        let ast = try #require(PandocAST(json: try pandoc(["-f", "markdown", "-t", "json"], markdown)))139        #expect(ast.blocks == ["Header1", "Para", "Header2", "BulletList", "OrderedList", "BlockQuote", "CodeBlock", "Table", "Para", "HorizontalRule", "Para", "Para"])140        #expect(ast.listDepth == 3)141        #expect(ast.inlines.isSuperset(of: ["Strong", "Emph", "Strikeout", "Code", "Link", "Math", "Note", "LineBreak"]))142        #expect(!ast.inlines.contains("RawInline") && !ast.inlines.contains("RawBlock") && !ast.inlines.contains("Cite"))      // nothing we escaped was read as markup143        #expect(ast.links == ["https://example.org/path?x=1"])144        #expect(ast.math == ["InlineMath:a^2 + b^2 = c^2", "DisplayMath:\n\\sum_{i=1}^{n} i = \\frac{n(n+1)}{2}\n"])145        #expect(ast.code == ["inline code", "func main() {\n    print(\"<hi> & bye\")\n}"])146        #expect(ast.notes == 1)147        #expect(ast.plains == 6 + 6)                       // six list items and six table cells148        // Same words in the same order (the note text sits where pandoc inlines it: at its reference).149        var expected = PandocCrossCheckTests.expectedWords150        let anchor = try #require(expected.firstIndex(of: "survive"))151        expected.insert(contentsOf: ["footnote", "body", "text"], at: anchor + 1)152        // The inline equation is a Math node for pandoc, not words; our visibleText leaves it out as well.153        #expect(ast.words == expected)154        // Metadata from the front matter.155        let meta = try #require((try JSONSerialization.jsonObject(with: try pandoc(["-f", "markdown", "-t", "json"], markdown)) as? [String: Any])?["meta"] as? [String: Any])156        #expect(meta["title"] != nil && meta["author"] != nil)157    }158159    @Test(.enabled(if: available, "pandoc is not installed")) func gfmParsersAgreeOnTheCommonSubset() throws {160        // Without the pandoc-only constructs (math, citations), a GitHub-flavoured parser sees the same structure and text.161        var doc = PandocCrossCheckTests.sample()162        doc.body.remove(at: 12)                                      // the display equation163        if case .paragraph(var p) = doc.body[1] { p.runs.removeAll { if case .equation? = $0.inline { return true } else { return false } }; doc.body[1] = .paragraph(p) }164        let markdown = MarkdownExporter.export(doc).data165        let ast = try #require(PandocAST(json: try pandoc(["-f", "gfm", "-t", "json"], markdown)))166        #expect(ast.blocks.filter { $0 != "RawBlock" } == ["Header1", "Para", "Header2", "BulletList", "OrderedList", "BlockQuote", "CodeBlock", "Table", "HorizontalRule", "Para", "Para"])167        #expect(ast.inlines.isSuperset(of: ["Strong", "Emph", "Strikeout", "Code", "Link", "Note"]))168        #expect(ast.links == ["https://example.org/path?x=1"])169        #expect(ast.plains == 6 + 6 && ast.listDepth == 3)170        let text = String(decoding: try pandoc(["-f", "gfm", "-t", "plain", "--wrap=none"], markdown), as: UTF8.self)171        for expected in ["Symbols: * _ [ ] # < > & $ ~ ^ | \\ survive", "Ünïcödé: 中文 العربية עברית 👩‍👩‍👧‍👦 e\u{301}.", "print(\"<hi> & bye\")", "beta gamma"] {172            #expect(text.contains(expected), "\(expected) not found in pandoc's reading")173        }174    }175176    @Test(.enabled(if: available, "pandoc is not installed")) func pandocParsesOurHTMLAsWeMeantIt() throws {177        let doc = PandocCrossCheckTests.sample()178        let html = HTMLExporter.export(doc).data179        let ast = try #require(PandocAST(json: try pandoc(["-f", "html", "-t", "json"], html)))180        #expect(ast.blocks.filter { $0 != "Div" } == ["Header1", "Para", "Header2", "BulletList", "OrderedList", "BlockQuote", "CodeBlock", "Table", "Para", "HorizontalRule", "Para", "Para"]181                || ast.blocks.prefix(8) == ["Header1", "Para", "Header2", "BulletList", "OrderedList", "BlockQuote", "CodeBlock", "Table"])182        #expect(ast.listDepth == 3 && ast.plains == 6 + 6)183        #expect(ast.inlines.isSuperset(of: ["Strong", "Emph", "Strikeout", "Code", "Link", "LineBreak"]))184        #expect(ast.links.contains("https://example.org/path?x=1"))185        #expect(ast.code == ["inline code", "func main() {\n    print(\"<hi> & bye\")\n}"])186        // Every word of the document is in pandoc's reading, in order (pandoc also reads the footnote section and equation sources).187        var cursor = ast.words.startIndex188        for word in PandocCrossCheckTests.expectedWords {189            guard let found = ast.words[cursor...].firstIndex(of: word) else { Issue.record("word \(word) missing or out of order in pandoc's reading of our HTML"); return }190            cursor = found + 1191        }192        let plain = String(decoding: try pandoc(["-f", "html", "-t", "plain", "--wrap=none"], html), as: UTF8.self)193        #expect(plain.contains("Symbols: * _ [ ] # < > & $ ~ ^ | \\ survive"))194        #expect(plain.contains("Ünïcödé: 中文 العربية עברית 👩‍👩‍👧‍👦 e\u{301}."))195        #expect(plain.contains("Footnote body text."))196    }197198    static let pandocSource = """199    ---200    title: Pandoc sample201    author: Grace Hopper202    lang: fr203    ---204205    # Introduction {#intro}206207    A paragraph with **strong**, *emphasis*, ~~deleted~~, `code`, a [link](https://pandoc.org "title"),208    H~2~O, x^2^, a footnote[^n] and math $E = mc^2$.209210    ## Lists211212    1. one213    2. two214        - nested *bullet*215        - another216    3. three217218    > A block quote219    > over two lines.220221    ```python222    def f(x):223        return x < 1 & True224    ```225226    | Left | Right |227    |:-----|------:|228    | a    | 1     |229    | b\\|c | 2     |230231    $$\\int_0^1 x\\,dx$$232233    ---234235    Last paragraph, see [Introduction](#intro).236237    [^n]: The note text.238    """239240    static let expectedFromPandocSource = [241        "Heading1: <bm intro>Introduction",242        "Normal: A paragraph with {b:strong}, {i:emphasis}, {s:deleted}, {c:code}, a [link](https://pandoc.org), H{_:2}O, x{^:2}, a footnote<footnote FootnoteText: The note text.> and math <eq E = mc^2>.",243        "Heading2: Lists",244        "ListParagraph L0(1.): one", "ListParagraph L0(2.): two", "ListParagraph L1(◦): nested {i:bullet}", "ListParagraph L1(◦): another", "ListParagraph L0(3.): three",245        "Quote: A block quote over two lines.",246        "Code: def f(x):⏎    return x < 1 & True",247        "TABLE 2 cols", "  H TableText: Left | TableText: Right", "  R TableText: a | TableText: 1", "  R TableText: b|c | TableText: 2",248        "Normal: <EQ \\int_0^1 x\\,dx>",249        "RULE",250        "Normal: Last paragraph, see [Introduction](#intro).",251    ]252253    @Test func ourReadingOfThePandocSource() {254        // The reference for the two tests below, checked on its own so a failure there points at pandoc's output, not at the source.255        let result = MarkdownImporter.importDocument(PandocCrossCheckTests.pandocSource)256        #expect(Describe.blocks(result.document) == PandocCrossCheckTests.expectedFromPandocSource)257        #expect(result.document.meta.title == "Pandoc sample" && result.document.meta.author == "Grace Hopper" && result.document.meta.language == "fr")258    }259260    @Test(.enabled(if: available, "pandoc is not installed"), arguments: ["markdown", "gfm", "commonmark_x", "markdown_strict+pipe_tables+footnotes+tex_math_dollars+strikeout+subscript+superscript+fenced_code_blocks+header_attributes"])261    func weImportMarkdownWrittenByPandoc(flavour: String) throws {262        let written = try pandoc(["-f", "markdown", "-t", flavour, "--wrap=none"], Data(PandocCrossCheckTests.pandocSource.utf8))263        let result = MarkdownImporter.importDocument(String(decoding: written, as: UTF8.self))264        let got = Describe.blocks(result.document)265        var want = PandocCrossCheckTests.expectedFromPandocSource266        if flavour == "gfm" {267            // GFM has no heading attributes and no sub/superscript syntax: pandoc writes <sub>/<sup> HTML (which we read) and drops the id.268            // Its math is written in GitHub's ```math / $`…`$ forms, which stay code for us.269            // The link still says #intro while GitHub would name the heading "introduction": pandoc's loss, visible as a heading without anchor.270            want[0] = "Heading1: Introduction"271            let drop = { (lines: [String]) in lines.filter { !$0.contains("mc^2") && !$0.contains("int_0") } }272            #expect(drop(got) == drop(want), "pandoc -t gfm:\n\(String(decoding: written, as: UTF8.self))")273            #expect(got.contains { $0.contains("E = mc^2") } && got.contains { $0.contains("\\int_0^1 x\\,dx") })274            return275        }276        if flavour.hasPrefix("markdown_strict") {277            // Without automatic identifiers pandoc writes an explicit {#id} on every heading; we keep explicit anchors.278            want[2] = "Heading2: <bm lists>Lists"279        }280        #expect(got == want, "pandoc -t \(flavour):\n\(String(decoding: written, as: UTF8.self))")281    }282283    @Test(.enabled(if: available, "pandoc is not installed")) func weImportHTMLWrittenByPandoc() throws {284        let source = Data(PandocCrossCheckTests.pandocSource.utf8)285        for mathOption in [["--mathjax"], ["--mathml"], []] {286            let written = try pandoc(["-f", "markdown", "-t", "html", "-s", "--wrap=none"] + mathOption, source)287            let html = String(decoding: written, as: UTF8.self)288            let result = HTMLImporter.importDocument(html)289            var want = PandocCrossCheckTests.expectedFromPandocSource290            // pandoc -s adds a title block (title and author) before the body.291            want.insert(contentsOf: ["Title: Pandoc sample", "Normal: Grace Hopper"], at: 0)292            if mathOption.isEmpty {293                // pandoc's default HTML writer renders simple formulas as HTML (<em>, <sup>): the LaTeX source is not in the file,294                // so the formulas come back as text and the importer reports it.295                want[3] = want[3].replacingOccurrences(of: "<eq E = mc^2>", with: "E = mc2")296                want[16] = "Normal: ∫01x dx"297                #expect(result.warnings.contains { $0.feature == "Equations" && $0.severity == .approximated })298            }299            // pandoc renders \, as a thin space: compare with every kind of space folded to U+0020.300            let got = Describe.blocks(result.document).map { String($0.map { $0.isWhitespace ? " " : $0 }) }301            #expect(got == want, "pandoc html \(mathOption):\n\(html.suffix(2500))")302            #expect(result.document.meta.title == "Pandoc sample" && result.document.meta.author == "Grace Hopper" && result.document.meta.language == "fr")303            #expect(result.document.notes.count == 1)304            let table = try #require(result.document.body.compactMap(\.table).first)305            #expect(table.rows[0].isHeader && table.rows[1].cells[1].paragraphs[0].props.alignment == .right)306            // The only things not carried over are pandoc's own style sheet and (for the default writer) nothing else.307            #expect(result.warnings.allSatisfy { $0.feature == "Style sheets" || $0.feature == "Equations" || $0.feature == "Active content" }, "\(result.warnings)")308            if mathOption == ["--mathml"] { #expect(result.warnings.map(\.feature) == ["Style sheets"]) }309        }310    }311312    @Test(.enabled(if: available, "pandoc is not installed")) func roundTripThroughPandocKeepsOurStructure() throws {313        // our model → our Markdown → pandoc (normalises it) → our importer: the same structure as importing our own output.314        let ours = MarkdownExporter.export(PandocCrossCheckTests.sample()).data315        let direct = Describe.blocks(MarkdownImporter.importDocument(String(decoding: ours, as: UTF8.self)).document)316        let normalised = try pandoc(["-f", "markdown", "-t", "markdown", "--wrap=none"], ours)317        let viaPandoc = Describe.blocks(MarkdownImporter.importDocument(String(decoding: normalised, as: UTF8.self)).document)318        #expect(viaPandoc == direct, "pandoc rewrote our Markdown as:\n\(String(decoding: normalised, as: UTF8.self))")319    }320}321322@Suite struct TextutilCrossCheckTests {323    static let available = Tool.available(Tool.textutil)324325    private func textutil(_ arguments: [String], file name: String, _ data: Data) throws -> String {326        let url = try Tool.temporaryFile(name, data)327        defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }328        let result = try #require(Tool.run(Tool.textutil, arguments + ["-stdout", url.path]))329        #expect(result.status == 0)330        return String(decoding: result.output, as: UTF8.self)331    }332333    private func sample() -> DocumentModel {334        var doc = DocumentModel(meta: DocumentMetadata(title: "Textutil check"))335        doc.lists = [.numbered(id: "n")]336        doc.assets = ["p": Asset(id: "p", mimeType: "image/png", data: Fixture.png())]337        doc.body = [338            .paragraph(Paragraph("A Heading", style: StyleID.heading(1))),339            .paragraph(Paragraph(runs: [Run("Plain, "), Run("bold", props: CharProps(bold: true)), Run(", "), Run("italic", props: CharProps(italic: true)), Run(" and a "),340                                        Run("link", props: CharProps(link: "https://example.org")), Run(". Ünïcödé « ok » — 中文 العربية 😀.")])),341            .paragraph(Paragraph(style: StyleID.listParagraph, runs: [Run("first item")], list: ListItem(listID: "n"))),342            .paragraph(Paragraph(style: StyleID.listParagraph, runs: [Run("second item")], list: ListItem(listID: "n"))),343            .table(Table(strings: [["H1", "H2"], ["c1", "c2"]], width: 200)),344            .paragraph(Paragraph(runs: [Run("Before image "), Run(inline: .image(ImageObject(asset: "p", width: 20, height: 15, altText: "pic"))), Run(" after image.")])),345            .paragraph(Paragraph("Braces {x} and backslash \\ and a tab\there.")),346        ]347        return doc348    }349350    @Test(.enabled(if: available, "textutil is not installed")) func textutilReadsOurRTF() throws {351        let text = try textutil(["-convert", "txt"], file: "ours.rtf", RTFExporter.export(sample()).data)352        let lines = text.components(separatedBy: "\n")353        #expect(lines.contains("A Heading"))354        #expect(lines.contains("Plain, bold, italic and a link. Ünïcödé « ok » — 中文 العربية 😀."))355        // List items (with or without their marker, depending on the system version); table cells one per line.356        #expect(lines.contains { $0.hasSuffix("first item") } && lines.contains { $0.hasSuffix("second item") })357        for cell in ["H1", "H2", "c1", "c2"] { #expect(lines.contains(cell)) }358        #expect(lines.contains { $0.hasPrefix("Before image ") && $0.hasSuffix(" after image.") })       // the picture does not disturb the text around it359        #expect(lines.contains("Braces {x} and backslash \\ and a tab\there."))360        // Its metadata reader sees the title we wrote.361        let info = try #require(Tool.run(Tool.textutil, ["-info", try Tool.temporaryFile("info.rtf", RTFExporter.export(sample()).data).path]))362        #expect(String(decoding: info.output, as: UTF8.self).contains("Textutil check"))363    }364365    @Test(.enabled(if: available, "textutil is not installed")) func textutilReadsOurHTML() throws {366        let text = try textutil(["-convert", "txt"], file: "ours.html", HTMLExporter.export(sample()).data)367        #expect(Tool.words(text).filter { !["1", "2"].contains($0) } == Tool.words("A Heading Plain, bold, italic and a link. Ünïcödé « ok » — 中文 العربية 😀. first item second item H1 H2 c1 c2 Before image after image. Braces {x} and backslash \\ and a tab here."))368        #expect(text.contains("Ünïcödé « ok » — 中文 العربية 😀."))369    }370371    @Test(.enabled(if: available, "textutil is not installed")) func weReadWhatTextutilWrites() throws {372        // textutil as an independent producer: it converts our HTML to RTF and our RTF to HTML; we import both.373        let doc = sample()374        let rtfURL = try Tool.temporaryFile("from-html.html", HTMLExporter.export(doc).data)375        let rtf = try #require(Tool.run(Tool.textutil, ["-convert", "rtf", "-stdout", rtfURL.path]))376        #expect(rtf.status == 0)377        let fromRTF = try RTFImporter.read(rtf.output).document378        let rtfText = Describe.texts(fromRTF).joined(separator: "\n")379        for expected in ["A Heading", "Plain, bold, italic and a link. Ünïcödé « ok » — 中文 العربية 😀.", "first item", "second item", "c2", "Braces {x} and backslash \\ and a tab\there."] {380            #expect(rtfText.contains(expected), "\(expected) missing from textutil's RTF as we read it")381        }382        var bold = false, link: String?383        DocumentModel.forEachParagraph(in: fromRTF.body) { p, _ in384            for run in p.runs where run.text == "bold" { bold = run.props.bold == true }385            for run in p.runs where run.text == "link" { link = run.props.link }386        }387        #expect(bold && link?.hasPrefix("https://example.org") == true)388        #expect(fromRTF.body.contains { $0.table != nil })389        #expect(fromRTF.body.compactMap { $0.paragraph?.list }.count == 2)390391        let htmlURL = try Tool.temporaryFile("from-rtf.rtf", RTFExporter.export(doc).data)392        let html = try #require(Tool.run(Tool.textutil, ["-convert", "html", "-stdout", htmlURL.path]))393        #expect(html.status == 0)394        let fromHTML = HTMLImporter.importDocument(String(decoding: html.output, as: UTF8.self))395        let htmlText = Describe.texts(fromHTML.document).joined(separator: "\n")396        for expected in ["A Heading", "Plain, bold, italic and a link. Ünïcödé « ok » — 中文 العربية 😀.", "first item", "second item", "c2", "Braces {x} and backslash \\ and a tab"] {397            #expect(htmlText.contains(expected), "\(expected) missing from textutil's HTML as we read it")398        }399        #expect(fromHTML.document.meta.title == "Textutil check")400        #expect(fromHTML.document.body.contains { $0.table != nil })401        // Cocoa's HTML carries its formatting in a <style> block, which we do not read: the importer says so.402        #expect(fromHTML.warnings.contains { $0.feature == "Style sheets" })403    }404}405
Files main
Menu

Theme