Tests/OrgCoreTests/HeadingCommandTests.swift
150 lines · 7945 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 "* P [1/2]\n** TODO a\n** DONE b\n",
52 "* P [50%] :t:\n** TODO a\n*** TODO deep\n** b\n",
53 ]
54
55 /// Commands, their Emacs forms, and whether they only act on heading lines.
56 static let commands: [(command: any OrgCommand, form: String, headingLineOnly: Bool)] = [
57 (TodoCycle(), "(org-todo)", false),
58 (PriorityUp(), "(org-priority-up)", true),
59 (PriorityDown(), "(org-priority-down)", true),
60 (PromoteHeading(), "(org-do-promote)", true),
61 (DemoteHeading(), "(org-do-demote)", true),
62 ]
63
64 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
65 func headingCommandsMatchEmacs() throws {
66 try compareWithEmacs(Self.variants.map { ($0, EmacsOracle.positions($0)) }, Self.commands)
67 }
68
69 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
70 func headingCommandsMatchEmacsWithDoomOptions() throws {
71 try compareWithEmacs(Self.variants.map { ($0, EmacsOracle.positions($0)) }, Self.commands, options: doomOptions)
72 }
73
74 /// Real headings: `ORGSTAR_ORACLE_CORPUS=<folder>` runs every command on up to 400 heading
75 /// lines from the folder's files, with the caret at the line start, the title start and
76 /// the line end.
77 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil))
78 func headingCommandsMatchEmacsOnACorpus() throws {
79 let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"]!)
80 var samples: [(String, [Int])] = []
81 let files = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil)!
82 .compactMap { $0 as? URL }.filter { $0.pathExtension == "org" }.sorted { $0.path < $1.path }
83 for file in files where samples.count < 400 {
84 guard let text = try? String(contentsOf: file, encoding: .utf8) else { continue }
85 var settings = ""
86 for line in text.components(separatedBy: "\n") where line.uppercased().hasPrefix("#+TODO:") || line.uppercased().hasPrefix("#+SEQ_TODO:") {
87 settings += line + "\n"
88 }
89 for line in text.components(separatedBy: "\n") where line.hasPrefix("*") && samples.count < 400 {
90 let sample = settings + line + "\n"
91 guard let heading = entryHeading(at: (sample as NSString).length - 1, in: OrgParser.parse(sample)) else { continue }
92 let parts = HeadingLine(heading)
93 samples.append((sample, [parts.start, parts.titleStart, parts.contentEnd]))
94 }
95 }
96 try compareWithEmacs(samples, Self.commands)
97 }
98}
99
100/// Runs every command at every caret of every input here and in Emacs, and records each
101/// difference in text, caret or failure.
102func compareWithEmacs(_ inputs: [(text: String, carets: [Int])], _ commands: [(command: any OrgCommand, form: String, headingLineOnly: Bool)], options: EditingOptions = .org) throws {
103 try #require(EmacsOracle.isAvailable, "Emacs is required for the oracle tests; set ORGSTAR_SKIP_ORACLE to skip")
104 var cases: [EmacsOracle.Case] = []
105 var ours: [(label: String, text: String, caret: Int, failed: Bool)] = []
106 for (text, carets) in inputs {
107 for offset in carets {
108 let onHeadingLine = headingOnLine(at: offset, in: OrgParser.parse(text)) != nil
109 for (command, form, headingLineOnly) in commands where onHeadingLine || !headingLineOnly {
110 cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(offset, in: text), form: withOptions(options, form)))
111 let result = runCommand(command, text, caret: offset, options: options)
112 ours.append(("\(command.id) at \(offset) in \(text.debugDescription)", result.text, result.caret, result.failure != nil))
113 }
114 }
115 }
116 let theirs = try EmacsOracle.run(cases)
117 var mismatches = 0
118 for (mine, emacs) in zip(ours, theirs) {
119 let emacsFailed = !emacs.error.isEmpty
120 let emacsCaret = EmacsOracle.offset(emacs.point, in: emacs.text)
121 let same = mine.failed == emacsFailed && (emacsFailed || (mine.text == emacs.text && mine.caret == emacsCaret))
122 if !same {
123 mismatches += 1
124 if mismatches <= 15 {
125 let (a, b) = excerpts(mine.text, emacs.text)
126 Issue.record("""
127 \(mine.label.prefix(100))
128 ours: \(mine.failed ? "failed" : "\(a.debugDescription) @\(mine.caret)")
129 emacs: \(emacsFailed ? "failed: \(emacs.error)" : "\(b.debugDescription) @\(emacsCaret)")
130 """)
131 }
132 }
133 }
134 #expect(mismatches == 0, "\(mismatches) of \(ours.count) cases differ from Emacs")
135}
136
137/// The parts of two texts around their first difference.
138func excerpts(_ a: String, _ b: String) -> (String, String) {
139 let x = Array(a.utf16), y = Array(b.utf16)
140 var prefix = 0
141 while prefix < min(x.count, y.count), x[prefix] == y[prefix] { prefix += 1 }
142 var suffix = 0
143 while suffix < min(x.count, y.count) - prefix, x[x.count - 1 - suffix] == y[y.count - 1 - suffix] { suffix += 1 }
144 let start = max(0, prefix - 40)
145 func cut(_ s: [UInt16]) -> String {
146 let end = min(s.count, s.count - suffix + 40)
147 return "…" + String(decoding: s[start..<max(start, end)], as: UTF16.self) + "…"
148 }
149 return (cut(x), cut(y))
150}