51 lines
2.2 KiB
Swift
51 lines
2.2 KiB
Swift
import PlakCore
|
|
import Testing
|
|
|
|
@Suite struct CodeHighlighterTests {
|
|
/// The tokens of `body` as (kind, text) pairs.
|
|
private func pieces(_ body: String, _ kind: FenceKind) -> [(CodeTokenKind, String)] {
|
|
let units = Array(body.utf16)
|
|
return CodeHighlighter.tokens(body, kind: kind).map { token in
|
|
(token.kind, String(decoding: units[token.range], as: UTF16.self))
|
|
}
|
|
}
|
|
|
|
private func expect(_ body: String, _ kind: FenceKind, _ expected: [(CodeTokenKind, String)]) {
|
|
let found = pieces(body, kind)
|
|
#expect(found.map(\.0) == expected.map(\.0), "\(found)")
|
|
#expect(found.map(\.1) == expected.map(\.1), "\(found)")
|
|
}
|
|
|
|
@Test("PHP: tags, comments, variables, strings, numbers, keywords and a heredoc")
|
|
func php() {
|
|
let body = "<?php\n// note\n$total = \"a\\\"b\" . 12; # end\n/* block */ function f() { return <<<EOT\n hi $x\n EOT; }"
|
|
expect(body, .php, [
|
|
(.tag, "<?php"), (.comment, "// note"), (.variable, "$total"), (.string, "\"a\\\"b\""), (.number, "12"),
|
|
(.comment, "# end"), (.comment, "/* block */"), (.keyword, "function"), (.keyword, "return"),
|
|
(.string, "<<<EOT\n hi $x\n EOT"),
|
|
])
|
|
}
|
|
|
|
@Test("JSON: keys apart from string values, numbers and literals")
|
|
func json() {
|
|
expect(#"{"key": "value", "n": -1.5e3, "ok": true, "none": null}"#, .json, [
|
|
(.attribute, "\"key\""), (.string, "\"value\""), (.attribute, "\"n\""), (.number, "-1.5e3"),
|
|
(.attribute, "\"ok\""), (.keyword, "true"), (.attribute, "\"none\""), (.keyword, "null"),
|
|
])
|
|
}
|
|
|
|
@Test("XML: tags, attribute names and values, comments and CDATA")
|
|
func xml() {
|
|
expect(#"<!-- c --><a b='1' c:d="2"><![CDATA[x < y]]></a>"#, .xml, [
|
|
(.comment, "<!-- c -->"), (.tag, "<a"), (.attribute, "b"), (.string, "'1'"), (.attribute, "c:d"),
|
|
(.string, "\"2\""), (.tag, ">"), (.string, "<![CDATA[x < y]]>"), (.tag, "</a"), (.tag, ">"),
|
|
])
|
|
}
|
|
|
|
@Test("ranges count UTF-16 units, so text before a token can hold any character")
|
|
func utf16() {
|
|
let tokens = CodeHighlighter.tokens("{\"é😀\": 1}", kind: .json)
|
|
#expect(tokens.map(\.range) == [1..<6, 8..<9])
|
|
}
|
|
}
|