Tests/OrgCoreTests/LintOracleTests.swift

b50ce164c2ff8b87dcc4256e1b3c97994dc431f8
orgstar/Tests/OrgCoreTests/LintOracleTests.swift

86 lines · 4678 bytes

 1import Foundation
 2import Testing
 3@testable import OrgCore
 4
 5/// orgstar's checkers against `org-lint` in Emacs, on the same files: the same lines for every
 6/// checker both have.
 7struct LintOracleTests {
 8    static let enabled = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && EmacsOracle.isAvailable
 9
10    static let script = #"""
11    ;;; -*- lexical-binding: t -*-
12    (require 'org)
13    (require 'org-lint)
14    (require 'json)
15    (setq org-todo-keywords '((sequence "TODO" "DONE"))
16          org-id-locations-file (make-temp-file "orgstar-id-locations"))
17    (let ((results nil))
18      (dolist (file (split-string (getenv "ORACLE_FILES") "\n" t))
19        (with-current-buffer (find-file-noselect file)
20          (org-mode)
21          (let ((lines nil))
22            (dolist (r (org-lint))
23              (let ((v (cadr r)))
24                (push (format "%s %s" (aref v 0) (org-lint-checker-name (aref v 3))) lines)))
25            (push (vconcat (nreverse lines)) results))
26          (kill-buffer)))
27      (let ((coding-system-for-write 'utf-8-unix))
28        (with-temp-file (getenv "ORACLE_OUTPUT")
29          (insert (json-encode (vconcat (nreverse results)))))))
30    """#
31
32    /// `org-lint`'s reports for each file, as "LINE CHECKER".
33    static func orgLint(_ files: [URL]) throws -> [[String]] {
34        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-lint-\(UUID().uuidString)")
35        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
36        defer { try? FileManager.default.removeItem(at: folder) }
37        let scriptURL = folder.appendingPathComponent("lint.el"), output = folder.appendingPathComponent("out.json")
38        try script.write(to: scriptURL, atomically: true, encoding: .utf8)
39        let log = try EmacsOracle.run(["-Q", "--batch", "-l", scriptURL.path],
40                                      environment: ["ORACLE_FILES": files.map(\.path).joined(separator: "\n"), "ORACLE_OUTPUT": output.path, "TZ": "UTC"])
41        guard let data = try? Data(contentsOf: output) else { throw EmacsOracle.EvaluateError(log: log) }
42        return try JSONDecoder().decode([[String]].self, from: data)
43    }
44
45    /// The checkers both have. Not invalid-id-link: `org-id-find-id-file` falls back to the
46    /// file being linted for an ID it doesn't know, so what org-lint reports depends on org-id's
47    /// saved locations; `idLinksResolveThroughTheIndex` covers orgstar's.
48    static let shared: Set<String> = Set(LintChecker.allCases.filter { $0.isOrgLint && $0 != .invalidIDLink }.map(\.rawValue))
49
50    static func ours(_ url: URL) throws -> [String] {
51        let text = try String(contentsOf: url, encoding: .utf8)
52        return OrgLint.lint(text, tree: OrgParser.parse(text), path: url.path).map { "\($0.line) \($0.checker.rawValue)" }
53    }
54
55    /// Both sides' reports for the checkers both have, sorted.
56    static func compare(_ files: [URL]) throws {
57        let theirs = try orgLint(files)
58        for (file, reports) in zip(files, theirs) {
59            let expected = reports.filter { shared.contains(String($0.split(separator: " ")[1])) }.sorted()
60            let actual = try ours(file).filter { shared.contains(String($0.split(separator: " ")[1])) }.sorted()
61            #expect(actual == expected, "\(file.lastPathComponent)")
62        }
63    }
64
65    static func folder(_ files: [String: String]) throws -> URL {
66        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-lint-\(UUID().uuidString)").resolvingSymlinksInPath()
67        for (name, text) in files {
68            let url = folder.appendingPathComponent(name)
69            try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
70            try text.write(to: url, atomically: true, encoding: .utf8)
71        }
72        return folder
73    }
74
75    @Test(.enabled(if: enabled)) func corpusMatchesOrgLint() throws {
76        let folder = try Self.folder(LintTests.corpus.merging(["exists.org": "* Here\n", "data/ab/cdef/photo.png": ""]) { $1 })
77        defer { try? FileManager.default.removeItem(at: folder) }
78        try Self.compare(LintTests.corpus.keys.sorted().map { folder.appendingPathComponent($0) })
79    }
80
81    @Test(.enabled(if: enabled)) func conformanceFilesMatchOrgLint() throws {
82        let folder = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Conformance")
83        let files = try FileManager.default.contentsOfDirectory(atPath: folder.path).filter { $0.hasSuffix(".org") }.sorted()
84        try Self.compare(files.map { folder.appendingPathComponent($0) })
85    }
86}
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