Tests/OrgCoreTests/HeadingCommandTests.swift

5d313b882d074ec238c7165acee91a0ae5e4a41a
orgstar/Tests/OrgCoreTests/HeadingCommandTests.swift

143 lines · 7489 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct HeadingCommandTests {
  6    @Test func todoCycle() {
  7        let cycle = TodoCycle()
  8        #expect(runCommand(cycle, "* a\n", caret: 2).text == "* TODO a\n")
  9        #expect(runCommand(cycle, "* TODO a\n", caret: 2).text == "* DONE a\n")
 10        #expect(runCommand(cycle, "* DONE a\n", caret: 2).text == "* a\n")
 11        #expect(runCommand(cycle, "* TODO\n", caret: 2).text == "* DONE \n")
 12        #expect(runCommand(cycle, "#+TODO: A B | C\n* B x\n", caret: 18).text == "#+TODO: A B | C\n* C x\n")
 13        #expect(runCommand(cycle, "text\n", caret: 1).failure != nil)
 14    }
 15
 16    @Test func caretMovesToTheTitleWhenBeforeIt() {
 17        #expect(runCommand(TodoCycle(), "* a\n", caret: 2).caret == 7)
 18        #expect(runCommand(TodoCycle(), "* TODO abc\nbody\n", caret: 13).caret == 13)
 19    }
 20
 21    @Test func priorities() {
 22        #expect(runCommand(PriorityUp(), "* a\n", caret: 2).text == "* [#B] a\n")
 23        #expect(runCommand(PriorityUp(), "* [#A] a\n", caret: 2).text == "* a\n")
 24        #expect(runCommand(PriorityDown(), "* TODO a\n", caret: 2).text == "* TODO [#B] a\n")
 25        #expect(runCommand(PriorityDown(), "* [#C] a\n", caret: 2).text == "* a\n")
 26    }
 27
 28    @Test func promoteAndDemote() {
 29        #expect(runCommand(DemoteHeading(), "* a\nbody\n", caret: 2).text == "** a\nbody\n")
 30        #expect(runCommand(PromoteHeading(), "** a\n", caret: 3).text == "* a\n")
 31        #expect(runCommand(PromoteHeading(), "* a\n", caret: 0).failure != nil)
 32        #expect(runCommand(DemoteHeading(), "* a\nbody\n", caret: 6).failure != nil)
 33    }
 34
 35    @Test func tagsAlignToColumn77() {
 36        let result = runCommand(PriorityUp(), "* TODO a :t:\n", caret: 2).text
 37        #expect(result == "* TODO [#B] a" + String(repeating: " ", count: 77 - 13 - 3) + ":t:\n")
 38    }
 39}
 40
 41/// Every heading variant, every caret position, every heading command, against Emacs.
 42/// Fails when Emacs is missing unless `ORGSTAR_SKIP_ORACLE` is set.
 43struct HeadingOracleTests {
 44    static let variants = [
 45        "* a\nbody\n", "* TODO a\n", "* DONE a\n", "** [#B] two words :tag:\n", "* TODO [#A] x :a:b:\nbody\n",
 46        "* \n", "* TODO\n", "*** title with 日本 :t:\n", "* a😀 b\n", "* a  :t:\n", "text\n* a\n", "*  a\n",
 47        "* TODO  a\n", "* a\r\n",
 48        "#+TODO: NEXT WAIT | DONE CANCELED\n* WAIT a :t:\n",
 49        "* " + String(repeating: "long ", count: 16) + "title :t:\n",
 50        "* TODO\ttab\n",
 51    ]
 52
 53    /// Commands, their Emacs forms, and whether they only act on heading lines.
 54    static let commands: [(command: any OrgCommand, form: String, headingLineOnly: Bool)] = [
 55        (TodoCycle(), "(org-todo)", false),
 56        (PriorityUp(), "(org-priority-up)", true),
 57        (PriorityDown(), "(org-priority-down)", true),
 58        (PromoteHeading(), "(org-do-promote)", true),
 59        (DemoteHeading(), "(org-do-demote)", true),
 60    ]
 61
 62    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 63    func headingCommandsMatchEmacs() throws {
 64        try compareWithEmacs(Self.variants.map { ($0, EmacsOracle.positions($0)) }, Self.commands)
 65    }
 66
 67    /// Real headings: `ORGSTAR_ORACLE_CORPUS=<folder>` runs every command on up to 400 heading
 68    /// lines from the folder's files, with the caret at the line start, the title start and
 69    /// the line end.
 70    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil))
 71    func headingCommandsMatchEmacsOnACorpus() throws {
 72        let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"]!)
 73        var samples: [(String, [Int])] = []
 74        let files = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil)!
 75            .compactMap { $0 as? URL }.filter { $0.pathExtension == "org" }.sorted { $0.path < $1.path }
 76        for file in files where samples.count < 400 {
 77            guard let text = try? String(contentsOf: file, encoding: .utf8) else { continue }
 78            var settings = ""
 79            for line in text.components(separatedBy: "\n") where line.uppercased().hasPrefix("#+TODO:") || line.uppercased().hasPrefix("#+SEQ_TODO:") {
 80                settings += line + "\n"
 81            }
 82            for line in text.components(separatedBy: "\n") where line.hasPrefix("*") && samples.count < 400 {
 83                let sample = settings + line + "\n"
 84                guard let heading = entryHeading(at: (sample as NSString).length - 1, in: OrgParser.parse(sample)) else { continue }
 85                let parts = HeadingLine(heading)
 86                samples.append((sample, [parts.start, parts.titleStart, parts.contentEnd]))
 87            }
 88        }
 89        try compareWithEmacs(samples, Self.commands)
 90    }
 91}
 92
 93/// Runs every command at every caret of every input here and in Emacs, and records each
 94/// difference in text, caret or failure.
 95func compareWithEmacs(_ inputs: [(text: String, carets: [Int])], _ commands: [(command: any OrgCommand, form: String, headingLineOnly: Bool)]) throws {
 96    try #require(EmacsOracle.isAvailable, "Emacs is required for the oracle tests; set ORGSTAR_SKIP_ORACLE to skip")
 97    var cases: [EmacsOracle.Case] = []
 98    var ours: [(label: String, text: String, caret: Int, failed: Bool)] = []
 99    for (text, carets) in inputs {
100        for offset in carets {
101            let onHeadingLine = headingOnLine(at: offset, in: OrgParser.parse(text)) != nil
102            for (command, form, headingLineOnly) in commands where onHeadingLine || !headingLineOnly {
103                cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(offset, in: text), form: form))
104                let result = runCommand(command, text, caret: offset)
105                ours.append(("\(command.id) at \(offset) in \(text.debugDescription)", result.text, result.caret, result.failure != nil))
106            }
107        }
108    }
109    let theirs = try EmacsOracle.run(cases)
110    var mismatches = 0
111    for (mine, emacs) in zip(ours, theirs) {
112        let emacsFailed = !emacs.error.isEmpty
113        let emacsCaret = EmacsOracle.offset(emacs.point, in: emacs.text)
114        let same = mine.failed == emacsFailed && (emacsFailed || (mine.text == emacs.text && mine.caret == emacsCaret))
115        if !same {
116            mismatches += 1
117            if mismatches <= 15 {
118                let (a, b) = excerpts(mine.text, emacs.text)
119                Issue.record("""
120                    \(mine.label.prefix(100))
121                      ours:  \(mine.failed ? "failed" : "\(a.debugDescription) @\(mine.caret)")
122                      emacs: \(emacsFailed ? "failed: \(emacs.error)" : "\(b.debugDescription) @\(emacsCaret)")
123                    """)
124            }
125        }
126    }
127    #expect(mismatches == 0, "\(mismatches) of \(ours.count) cases differ from Emacs")
128}
129
130/// The parts of two texts around their first difference.
131func excerpts(_ a: String, _ b: String) -> (String, String) {
132    let x = Array(a.utf16), y = Array(b.utf16)
133    var prefix = 0
134    while prefix < min(x.count, y.count), x[prefix] == y[prefix] { prefix += 1 }
135    var suffix = 0
136    while suffix < min(x.count, y.count) - prefix, x[x.count - 1 - suffix] == y[y.count - 1 - suffix] { suffix += 1 }
137    let start = max(0, prefix - 40)
138    func cut(_ s: [UInt16]) -> String {
139        let end = min(s.count, s.count - suffix + 40)
140        return "…" + String(decoding: s[start..<max(start, end)], as: UTF16.self) + "…"
141    }
142    return (cut(x), cut(y))
143}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form