File size: 1,528 Bytes
f5375f2
 
b09157d
f5375f2
 
 
b09157d
f5375f2
 
 
 
 
b09157d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import test from "node:test";
import assert from "node:assert/strict";
import { highlightC, cTokens } from "../src/training/cSyntaxHighlight.js";

test("C highlighter colors tokens, escapes source and marks each selected identifier", () => {
  const html = highlightC('int total = 3; // total < 4', "total");
  assert.match(html, /token-type[^>]*>int/);
  assert.match(html, /token-number[^>]*>3/);
  assert.match(html, /token-comment/);
  assert.equal((html.match(/code-occurrence/g) || []).length, 2);
  assert.match(html, /&lt; 4/);
});

test('C tokens distinguish types, control flow, functions, constants and literals', () => {
  const tokens = cTokens('const int total = 0xFFu; if (total) printf("%d", EOF);');
  for (const [text, kind] of [['const', 'keyword'], ['int', 'type'], ['total', 'variable'], ['0xFFu', 'number'], ['if', 'control'], ['printf', 'function'], ['EOF', 'constant'], ['"%d"', 'string']]) {
    assert.equal(tokens.find(token => token.text === text)?.kind, kind);
  }
  assert.equal(cTokens('/* start\n int not_code;\n }').length, 1);
  assert.equal(cTokens('/* start\n int not_code;\n */ int real;')[0].kind, 'comment');
});

test('occurrence highlights match whole identifiers and cannot inject HTML', () => {
  const html = highlightC('int total; total++; int totals; // total\n"<script>total</script>"', 'total');
  assert.equal((html.match(/code-occurrence/g) || []).length, 4);
  assert.ok(!html.includes('<script>'));
  assert.ok(!highlightC('int a;', '<img>').includes('code-occurrence'));
});