Tests/OrgCoreTests/RoundTripTests.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Tests/OrgCoreTests/RoundTripTests.swift history · blame · raw

88 lines · 3973 bytes

9 symbols in this file
 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
17/// `ORGSTAR_SEED` when set, else `fallback`, so random tests repeat unless asked to vary.
18func testSeed(_ fallback: UInt64) -> UInt64 {
19    ProcessInfo.processInfo.environment["ORGSTAR_SEED"].flatMap { UInt64($0) } ?? fallback
20}
21
22let fragments = [
23    "* ", "** TODO [#A] title :a:b:", "*** DONE", "#+TODO: NEXT | DONE", "#+begin_src sh", "#+end_src",
24    "#+BEGIN_QUOTE", "#+end_quote", "#+BEGIN: clocktable", "#+END:", ":PROPERTIES:", ":ID: x", ":END:",
25    ":LOGBOOK:", "CLOCK: [2026-10-04 Sun 10:00]", "SCHEDULED: <2026-10-04 Sun>", "- item", "  - nested",
26    "\t+ tab", "1. one", "| a | b |", "|---+---|", "#+TBLFM: $2=$1", "# comment", ": fixed", "-----",
27    "[fn:1] note", "#+NAME: x", "plain text", "é", "😀", "e\u{301}", " ", "\t", "\n", "\n", "\r\n", "\r", "",
28    "*bold*", "/it/ ", "=v=", "~c~", "_u_", "+s+", "*", "/", "=", "[[https://a.b][d *b*]]", "[[x]]", "[[", "]]",
29    "<2026-10-04 Sun 10:00 +1w -2d>", "[2026-10-04]--[2026-10-05]", "<", ">", "[fn:2]", "[fn::in [x]]", "[1/3]",
30    "[50%]", "<<t>>", "{{{m(a)}}}", "\\(x\\)", "a\\\\", "x^2", "^{y}", "src_sh{echo}", "https://e.com.",
31    "<https://e.com>", "| *a* | b |", "||", "- [X] done", "+ [ ] todo", "-",
32    "[cite:@a; @b]", "[cite/t:see @k p. 2;]", "@@html:<b>@@", "call_f(x=1)[:results raw]", "%%(diary-float t 4 2)",
33    "+---+---+", "+-", "- term :: def", "1. [@3] three", "- [@2] [X] x :: y", " :: ", "@", "call_",
34]
35
36func randomDocument(_ rng: inout SeededGenerator) -> String {
37    (0..<Int.random(in: 0...40, using: &rng)).map { _ in
38        fragments.randomElement(using: &rng)! + (Bool.random(using: &rng) ? "\n" : "")
39    }.joined()
40}
41
42func checkLengths(_ node: SyntaxNode) -> Bool {
43    let sum = node.green.children.reduce(0) { $0 + $1.length }
44    return sum == node.green.length && node.children.allSatisfy(checkLengths)
45}
46
47struct RoundTripTests {
48    @Test func fuzzedDocumentsRoundTrip() {
49        var rng = SeededGenerator(state: 20261004)
50        for n in 0..<2_000 {
51            let text = randomDocument(&rng)
52            let tree = OrgParser.parse(text)
53            #expect(tree.root.text == text, "document \(n)")
54            #expect(checkLengths(tree.root), "document \(n)")
55            _ = DocumentModel(tree: tree)
56        }
57    }
58
59    @Test(arguments: [
60        [0xEF, 0xBB, 0xBF] + Array("* a\r\n".utf8),
61        Array("* a\r\n- b\n\tc".utf8),
62        Array("* a".utf8),
63        Array("😀 e\u{301}\n".utf8),
64        [0x2A, 0x20, 0xFF, 0x0A] as [UInt8],
65    ])
66    func encodingFixturesRoundTrip(bytes: [UInt8]) {
67        let source = SourceText(bytes: bytes)
68        let tree = OrgParser.parse(source.text)
69        #expect(source.encode(tree.root.text) == bytes)
70    }
71
72    /// Private corpus: `ORGSTAR_CORPUS=/path/to/org swift test --filter corpus`.
73    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_CORPUS"] != nil))
74    func corpusRoundTrips() throws {
75        let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ORGSTAR_CORPUS"]!)
76        let files = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil)!
77            .compactMap { $0 as? URL }
78            .filter { ["org", "org_archive"].contains($0.pathExtension) }
79        #expect(!files.isEmpty)
80        for file in files {
81            let bytes = try [UInt8](Data(contentsOf: file))
82            let source = SourceText(bytes: bytes)
83            let tree = OrgParser.parse(source.text)
84            #expect(source.encode(tree.root.text) == bytes, "\(file.path)")
85            _ = DocumentModel(tree: tree)
86        }
87    }
88}