Tests/OrgCoreTests/ExportTests.swift

9abba9cfc504b344b7d267978a97f1c925a1d5dd
orgstar/Tests/OrgCoreTests/ExportTests.swift history · blame · raw

223 lines · 8050 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5/// The org-conformance skeleton reduction (SKELETON.md): element opens and closes and text
  6/// runs, without `div`/`span` and attributes other than `href` and `src`.
  7enum Skeleton {
  8    static let ignored: Set<String> = ["div", "span"]
  9    static let void: Set<String> = ["br", "hr", "img", "input", "meta", "link", "col", "area", "base", "source", "wbr"]
 10
 11    static func decode(_ s: String) -> String {
 12        var out = ""
 13        var i = s.startIndex
 14        while i < s.endIndex {
 15            if s[i] == "&", let semicolon = s[i...].prefix(13).firstIndex(of: ";") {
 16                let name = String(s[s.index(after: i)..<semicolon])
 17                var replacement: String?
 18                switch name {
 19                case "amp": replacement = "&"
 20                case "lt": replacement = "<"
 21                case "gt": replacement = ">"
 22                case "quot": replacement = "\""
 23                case "apos": replacement = "'"
 24                case "nbsp": replacement = " "
 25                default:
 26                    if name.hasPrefix("#x") || name.hasPrefix("#X"), let v = UInt32(name.dropFirst(2), radix: 16), let u = Unicode.Scalar(v) {
 27                        replacement = String(Character(u))
 28                    } else if name.hasPrefix("#"), let v = UInt32(name.dropFirst()), let u = Unicode.Scalar(v) {
 29                        replacement = String(Character(u))
 30                    }
 31                }
 32                if let replacement {
 33                    out += replacement == "\u{a0}" ? " " : replacement
 34                    i = s.index(after: semicolon)
 35                    continue
 36                }
 37            }
 38            out.append(s[i] == "\u{a0}" ? " " : s[i])
 39            i = s.index(after: i)
 40        }
 41        return out
 42    }
 43
 44    static func reduce(_ html: String) -> String {
 45        var lines: [String] = []
 46        var text = ""
 47        func flush() {
 48            let collapsed = decode(text).split(whereSeparator: \.isWhitespace).joined(separator: " ")
 49            if !collapsed.isEmpty {
 50                lines.append("\"" + collapsed.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"")
 51            }
 52            text = ""
 53        }
 54        var i = html.startIndex
 55        while i < html.endIndex {
 56            if html[i] == "<" {
 57                if html[i...].hasPrefix("<!--") {
 58                    let end = html[i...].range(of: "-->")?.upperBound ?? html.endIndex
 59                    i = end
 60                    continue
 61                }
 62                guard let close = html[i...].firstIndex(of: ">") else { text.append(html[i]); i = html.index(after: i); continue }
 63                let tag = String(html[html.index(after: i)..<close])
 64                i = html.index(after: close)
 65                if tag.hasPrefix("!") { continue }
 66                let closing = tag.hasPrefix("/")
 67                var body = closing ? String(tag.dropFirst()) : tag
 68                if body.hasSuffix("/") { body.removeLast() }
 69                let name = String(body.prefix { !$0.isWhitespace }).lowercased()
 70                if ignored.contains(name) { continue }
 71                if closing {
 72                    if void.contains(name) { continue }
 73                    flush()
 74                    lines.append("</\(name)>")
 75                    continue
 76                }
 77                flush()
 78                var attributes = ""
 79                for attribute in ["href", "src"] {
 80                    if let m = body.firstMatch(of: try! Regex("\\s\(attribute)=\"([^\"]*)\"")) {
 81                        attributes += " \(attribute)=\"\(decode(String(m.output[1].substring!)))\""
 82                    }
 83                }
 84                lines.append("<\(name)\(attributes)>")
 85            } else {
 86                text.append(html[i])
 87                i = html.index(after: i)
 88            }
 89        }
 90        flush()
 91        return lines.joined(separator: "\n") + "\n"
 92    }
 93}
 94
 95struct ExportTests {
 96    static let folder = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Conformance")
 97
 98    @Test(arguments: ["minimal", "core", "elements", "headings", "listblocks", "lists", "table", "blocks", "timestamps", "footnote", "images", "tblfm"])
 99    func conformance(_ name: String) throws {
100        let org = try String(contentsOf: Self.folder.appendingPathComponent("\(name).org"), encoding: .utf8)
101        let expected = try String(contentsOf: Self.folder.appendingPathComponent("\(name).skeleton"), encoding: .utf8)
102        let html = HTMLExport.body(org)
103        let ours = Skeleton.reduce(html)
104        #expect(ours == expected, "\(name)\n--- ours\n\(ours)\n--- html\n\(html)")
105    }
106
107    @Test func page() {
108        let page = HTMLExport.page("#+TITLE: Notes & Things\n#+AUTHOR: Me\n\nHello.\n", fallbackTitle: "x")
109        #expect(page.contains("<title>Notes &amp; Things</title>"))
110        #expect(page.contains("<h1 class=\"title\">Notes &amp; Things</h1>"))
111        #expect(page.contains("<p class=\"byline\">Me</p>"))
112        #expect(page.contains("<p>Hello.</p>"))
113    }
114}
115
116struct MarkdownExportTests {
117    @Test func document() {
118        let org = """
119        #+TITLE: Notes
120
121        Intro with *bold*, /italic/, =code=, a [[https://example.com][link]] and a note.[fn:1]
122
123        * TODO Plans :work:
124        - [ ] first
125        - [X] second
126          1. nested
127        - term :: definition
128
129        | a | b |
130        |---+---|
131        | 1 | 2 |
132
133        #+begin_src swift
134        let x = 1
135        #+end_src
136
137        #+begin_quote
138        Quoted.
139        #+end_quote
140
141        [fn:1] The note.
142        """
143        let expected = """
144        # Notes
145
146        Intro with **bold**, *italic*, `code`, a [link](https://example.com) and a note.[^1]
147
148        ## TODO Plans `work`
149
150        - [ ] first
151        - [x] second
152          1. nested
153        - **term**: definition
154
155        | a | b |
156        |---|---|
157        | 1 | 2 |
158
159        ```swift
160        let x = 1
161        ```
162
163        > Quoted.
164
165        [^1]: The note.
166
167        """
168        let ours = MarkdownExport.document(org)
169        #expect(ours == expected)
170    }
171}
172
173struct ExportCorpusTests {
174    /// `ORGSTAR_ORACLE_CORPUS=<folder>`: every file exports to HTML and Markdown.
175    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil))
176    func exportsEveryFile() throws {
177        let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"]!)
178        let files = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil)!
179            .compactMap { $0 as? URL }.filter { $0.pathExtension == "org" }
180        var slowest = (0.0, "")
181        for file in files {
182            guard let text = try? String(contentsOf: file, encoding: .utf8) else { continue }
183            let start = Date()
184            let html = HTMLExport.page(text, fallbackTitle: file.lastPathComponent)
185            let markdown = MarkdownExport.document(text)
186            let elapsed = Date().timeIntervalSince(start)
187            if elapsed > slowest.0 { slowest = (elapsed, file.lastPathComponent) }
188            #expect(html.contains("</html>") && !markdown.isEmpty, "\(file.path)")
189        }
190        print("exported \(files.count) files; slowest \(slowest.1) in \(String(format: "%.2f", slowest.0)) s")
191    }
192}
193
194struct ExportResultsTests {
195    @Test func resultsFollowExports() {
196        let org = """
197        #+begin_src sh
198        echo a
199        #+end_src
200
201        #+RESULTS:
202        : a
203
204        #+begin_src sh :exports both
205        echo b
206        #+end_src
207
208        #+RESULTS:
209        : b
210
211        #+begin_src sh :exports results
212        echo c
213        #+end_src
214
215        #+RESULTS:
216        : c
217        """
218        let html = HTMLExport.body(org)
219        #expect(html.contains("echo a") && !html.contains(">a</pre>"))
220        #expect(html.contains("echo b") && html.contains(">b</pre>"))
221        #expect(!html.contains("echo c") && html.contains(">c</pre>"))
222    }
223}