Tests/OrgCoreTests/RoundTripTests.swift

397c9ad69a596cfff75844141c5e537217661eb3
orgstar/Tests/OrgCoreTests/RoundTripTests.swift history · blame · raw

81 lines · 3511 bytes

 1import Foundation
 2import Testing
 3@testable import OrgCore
 4
 5/// SplitMix64, so failures reproduce from the seed.
 6struct SeededGenerator: RandomNumberGenerator {
 7    var state: UInt64
 8    mutating func next() -> UInt64 {
 9        state &+= 0x9E37_79B9_7F4A_7C15
10        var z = state
11        z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
12        z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
13        return z ^ (z >> 31)
14    }
15}
16
17let fragments = [
18    "* ", "** TODO [#A] title :a:b:", "*** DONE", "#+TODO: NEXT | DONE", "#+begin_src sh", "#+end_src",
19    "#+BEGIN_QUOTE", "#+end_quote", "#+BEGIN: clocktable", "#+END:", ":PROPERTIES:", ":ID: x", ":END:",
20    ":LOGBOOK:", "CLOCK: [2026-10-04 Sun 10:00]", "SCHEDULED: <2026-10-04 Sun>", "- item", "  - nested",
21    "\t+ tab", "1. one", "| a | b |", "|---+---|", "#+TBLFM: $2=$1", "# comment", ": fixed", "-----",
22    "[fn:1] note", "#+NAME: x", "plain text", "é", "😀", "e\u{301}", " ", "\t", "\n", "\n", "\r\n", "\r", "",
23    "*bold*", "/it/ ", "=v=", "~c~", "_u_", "+s+", "*", "/", "=", "[[https://a.b][d *b*]]", "[[x]]", "[[", "]]",
24    "<2026-10-04 Sun 10:00 +1w -2d>", "[2026-10-04]--[2026-10-05]", "<", ">", "[fn:2]", "[fn::in [x]]", "[1/3]",
25    "[50%]", "<<t>>", "{{{m(a)}}}", "\\(x\\)", "a\\\\", "x^2", "^{y}", "src_sh{echo}", "https://e.com.",
26    "<https://e.com>", "| *a* | b |", "||", "- [X] done", "+ [ ] todo", "-",
27]
28
29func randomDocument(_ rng: inout SeededGenerator) -> String {
30    (0..<Int.random(in: 0...40, using: &rng)).map { _ in
31        fragments.randomElement(using: &rng)! + (Bool.random(using: &rng) ? "\n" : "")
32    }.joined()
33}
34
35func checkLengths(_ node: SyntaxNode) -> Bool {
36    let sum = node.green.children.reduce(0) { $0 + $1.length }
37    return sum == node.green.length && node.children.allSatisfy(checkLengths)
38}
39
40struct RoundTripTests {
41    @Test func fuzzedDocumentsRoundTrip() {
42        var rng = SeededGenerator(state: 20261004)
43        for n in 0..<2_000 {
44            let text = randomDocument(&rng)
45            let tree = OrgParser.parse(text)
46            #expect(tree.text == text, "document \(n)")
47            #expect(checkLengths(tree.root), "document \(n)")
48            _ = DocumentModel(tree: tree)
49        }
50    }
51
52    @Test(arguments: [
53        [0xEF, 0xBB, 0xBF] + Array("* a\r\n".utf8),
54        Array("* a\r\n- b\n\tc".utf8),
55        Array("* a".utf8),
56        Array("😀 e\u{301}\n".utf8),
57        [0x2A, 0x20, 0xFF, 0x0A] as [UInt8],
58    ])
59    func encodingFixturesRoundTrip(bytes: [UInt8]) {
60        let source = SourceText(bytes: bytes)
61        let tree = OrgParser.parse(source.text)
62        #expect(source.encode(tree.text) == bytes)
63    }
64
65    /// Private corpus: `ORGSTAR_CORPUS=/path/to/org swift test --filter corpus`.
66    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_CORPUS"] != nil))
67    func corpusRoundTrips() throws {
68        let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ORGSTAR_CORPUS"]!)
69        let files = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil)!
70            .compactMap { $0 as? URL }
71            .filter { ["org", "org_archive"].contains($0.pathExtension) }
72        #expect(!files.isEmpty)
73        for file in files {
74            let bytes = try [UInt8](Data(contentsOf: file))
75            let source = SourceText(bytes: bytes)
76            let tree = OrgParser.parse(source.text)
77            #expect(source.encode(tree.text) == bytes, "\(file.path)")
78            _ = DocumentModel(tree: tree)
79        }
80    }
81}