Tests/OrgCoreTests/HeadingCommandTests.swift

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

125 lines · 6641 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 compare(Self.variants.map { ($0, EmacsOracle.positions($0)) })
 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 compare(samples)
 90    }
 91
 92    func compare(_ inputs: [(text: String, carets: [Int])]) throws {
 93        try #require(EmacsOracle.isAvailable, "Emacs is required for the oracle tests; set ORGSTAR_SKIP_ORACLE to skip")
 94        var cases: [EmacsOracle.Case] = []
 95        var ours: [(label: String, text: String, caret: Int, failed: Bool)] = []
 96        for (text, carets) in inputs {
 97            for offset in carets {
 98                let onHeadingLine = headingOnLine(at: offset, in: OrgParser.parse(text)) != nil
 99                for (command, form, headingLineOnly) in Self.commands where onHeadingLine || !headingLineOnly {
100                    cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(offset, in: text), form: form))
101                    let result = runCommand(command, text, caret: offset)
102                    ours.append(("\(command.id) at \(offset) in \(text.debugDescription)", result.text, result.caret, result.failure != nil))
103                }
104            }
105        }
106        let theirs = try EmacsOracle.run(cases)
107        var mismatches = 0
108        for (mine, emacs) in zip(ours, theirs) {
109            let emacsFailed = !emacs.error.isEmpty
110            let emacsCaret = EmacsOracle.offset(emacs.point, in: emacs.text)
111            let same = mine.failed == emacsFailed && (emacsFailed || (mine.text == emacs.text && mine.caret == emacsCaret))
112            if !same {
113                mismatches += 1
114                if mismatches <= 15 {
115                    Issue.record("""
116                        \(mine.label)
117                          ours:  \(mine.failed ? "failed" : "\(mine.text.debugDescription) @\(mine.caret)")
118                          emacs: \(emacsFailed ? "failed: \(emacs.error)" : "\(emacs.text.debugDescription) @\(emacsCaret)")
119                        """)
120                }
121            }
122        }
123        #expect(mismatches == 0, "\(mismatches) of \(ours.count) cases differ from Emacs")
124    }
125}