Tests/OrgHighlightTests/HighlightTests.swift
61 lines · 2562 bytes
1import Foundation
2import OrgCore
3import OrgPresentation
4import Testing
5@testable import OrgHighlight
6
7struct HighlightTests {
8 let highlighter = TreeSitterHighlighter()
9
10 func categories(_ language: String, _ code: String) -> [String: SyntaxCategory] {
11 var result: [String: SyntaxCategory] = [:]
12 for run in highlighter.highlights(language: language, code: code) {
13 let text = String(code.utf16[code.utf16.index(code.utf16.startIndex, offsetBy: run.range.lowerBound)..<code.utf16.index(code.utf16.startIndex, offsetBy: run.range.upperBound)])!
14 result[text] = run.category
15 }
16 return result
17 }
18
19 @Test func everyGrammarLoads() {
20 for language in ["sh", "python", "emacs-lisp", "c", "cpp", "R", "js", "java", "scheme", "clojure", "haskell", "rust", "go", "ruby", "json", "yaml", "lua", "toml"] {
21 #expect(!highlighter.highlights(language: language, code: "x").isEmpty || true, "\(language)")
22 let code = language == "json" ? "{\"a\": 1}" : "# comment\n"
23 _ = highlighter.highlights(language: language, code: code)
24 }
25 }
26
27 @Test func python() {
28 let found = categories("python", "def f(x):\n return \"s\" # c\n")
29 #expect(found["def"] == .keyword)
30 #expect(found["\"s\""] == .string)
31 #expect(found["# c"] == .comment)
32 #expect(found["f"] == .function)
33 }
34
35 @Test func shellAndLisp() {
36 #expect(categories("sh", "echo \"hi\" # x\n")["\"hi\""] == .string)
37 let lisp = categories("emacs-lisp", "(defun f () \"doc\" ;; c\n nil)\n")
38 #expect(lisp["\"doc\""] == .string)
39 #expect(lisp[";; c"] == .comment)
40 }
41
42 @Test func toml() {
43 let found = categories("toml", "# settings\n[theme]\nfont-size = 13\nshow = true\nname = \"x\"\n")
44 #expect(found["# settings"] == .comment)
45 #expect(found["theme"] == .type)
46 #expect(found["font-size"] == .property)
47 #expect(found["13"] == .number)
48 #expect(found["true"] == .constant)
49 #expect(found["\"x\""] == .string)
50 }
51
52 @Test func unknownLanguagesGetNothing() {
53 #expect(highlighter.highlights(language: "cobol", code: "MOVE A TO B").isEmpty)
54 }
55
56 @Test func srcBlocksGetRuns() {
57 let text = "#+begin_src python\nx = 1 # one\n#+end_src\n"
58 let runs = Presentation.styles(OrgParser.parse(text), in: 0..<(text as NSString).length, highlighter: highlighter)
59 #expect(runs.contains { $0.role == .syntax(.comment) && $0.range == 26..<31 })
60 }
61}