Debian Codegraph @

src/ansi_test.go

raw
1 package fzf
2
3 import (
4 "math/rand"
5 "regexp"
6 "strings"
7 "testing"
8 "unicode/utf8"
9
10 "github.com/junegunn/fzf/src/tui"
11 )
12
13 // The following regular expression will include not all but most of the
14 // frequently used ANSI sequences. This regex is used as a reference for
15 // testing nextAnsiEscapeSequence().
16 //
17 // References:
18 // - https://github.com/gnachman/iTerm2
19 // - https://web.archive.org/web/20090204053813/http://ascii-table.com/ansi-escape-sequences.php
20 // (archived from http://ascii-table.com/ansi-escape-sequences.php)
21 // - https://web.archive.org/web/20090227051140/http://ascii-table.com/ansi-escape-sequences-vt-100.php
22 // (archived from http://ascii-table.com/ansi-escape-sequences-vt-100.php)
23 // - http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x405.html
24 // - https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
25 var ansiRegexReference = regexp.MustCompile("(?:\x1b[\\[()][0-9;:]*[a-zA-Z@]|\x1b][0-9][;:][[:print:]]+(?:\x1b\\\\|\x07)|\x1b.|[\x0e\x0f]|.\x08|\n)")
26
27 func testParserReference(t testing.TB, str string) {
28 t.Helper()
29
30 toSlice := func(start, end int) []int {
31 if start == -1 {
32 return nil
33 }
34 return []int{start, end}
35 }
36
37 s := str
38 for i := 0; ; i++ {
39 got := toSlice(nextAnsiEscapeSequence(s))
40 exp := ansiRegexReference.FindStringIndex(s)
41
42 equal := len(got) == len(exp)
43 if equal {
44 for i := range got {
45 if got[i] != exp[i] {
46 equal = false
47 break
48 }
49 }
50 }
51 if !equal {
52 var exps, gots []rune
53 if len(got) == 2 {
54 gots = []rune(s[got[0]:got[1]])
55 }
56 if len(exp) == 2 {
57 exps = []rune(s[exp[0]:exp[1]])
58 }
59 t.Errorf("%d: %q: got: %v (%q) want: %v (%q)", i, s, got, gots, exp, exps)
60 return
61 }
62 if len(exp) == 0 {
63 return
64 }
65 s = s[exp[1]:]
66 }
67 }
68
69 func TestNextAnsiEscapeSequence(t *testing.T) {
70 testStrs := []string{
71 "\x1b[0mhello world",
72 "\x1b[1mhello world",
73 "椙\x1b[1m椙",
74 "椙\x1b[1椙m椙",
75 "\x1b[1mhello \x1b[mw\x1b7o\x1b8r\x1b(Bl\x1b[2@d",
76 "\x1b[1mhello \x1b[Kworld",
77 "hello \x1b[34;45;1mworld",
78 "hello \x1b[34;45;1mwor\x1b[34;45;1mld",
79 "hello \x1b[34;45;1mwor\x1b[0mld",
80 "hello \x1b[34;48;5;233;1mwo\x1b[38;5;161mr\x1b[0ml\x1b[38;5;161md",
81 "hello \x1b[38;5;38;48;5;48;1mwor\x1b[38;5;48;48;5;38ml\x1b[0md",
82 "hello \x1b[32;1mworld",
83 "hello world",
84 "hello \x1b[0;38;5;200;48;5;100mworld",
85 "\x1b椙",
86 "椙\x08",
87 "\n\x08",
88 "X\x08",
89 "",
90 "\x1b]4;3;rgb:aa/bb/cc\x07 ",
91 "\x1b]4;3;rgb:aa/bb/cc\x1b\\ ",
92 ansiBenchmarkString,
93 }
94
95 for _, s := range testStrs {
96 testParserReference(t, s)
97 }
98 }
99
100 func TestNextAnsiEscapeSequence_Fuzz_Modified(t *testing.T) {
101 t.Parallel()
102 if testing.Short() {
103 t.Skip("short test")
104 }
105
106 testStrs := []string{
107 "\x1b[0mhello world",
108 "\x1b[1mhello world",
109 "椙\x1b[1m椙",
110 "椙\x1b[1椙m椙",
111 "\x1b[1mhello \x1b[mw\x1b7o\x1b8r\x1b(Bl\x1b[2@d",
112 "\x1b[1mhello \x1b[Kworld",
113 "hello \x1b[34;45;1mworld",
114 "hello \x1b[34;45;1mwor\x1b[34;45;1mld",
115 "hello \x1b[34;45;1mwor\x1b[0mld",
116 "hello \x1b[34;48;5;233;1mwo\x1b[38;5;161mr\x1b[0ml\x1b[38;5;161md",
117 "hello \x1b[38;5;38;48;5;48;1mwor\x1b[38;5;48;48;5;38ml\x1b[0md",
118 "hello \x1b[32;1mworld",
119 "hello world",
120 "hello \x1b[0;38;5;200;48;5;100mworld",
121 ansiBenchmarkString,
122 }
123
124 replacementBytes := [...]rune{'\x0e', '\x0f', '\x1b', '\x08'}
125
126 modifyString := func(s string, rr *rand.Rand) string {
127 n := rr.Intn(len(s))
128 b := []rune(s)
129 for ; n >= 0 && len(b) != 0; n-- {
130 i := rr.Intn(len(b))
131 switch x := rr.Intn(4); x {
132 case 0:
133 b = append(b[:i], b[i+1:]...)
134 case 1:
135 j := rr.Intn(len(replacementBytes) - 1)
136 b[i] = replacementBytes[j]
137 case 2:
138 x := rune(rr.Intn(utf8.MaxRune))
139 for !utf8.ValidRune(x) {
140 x = rune(rr.Intn(utf8.MaxRune))
141 }
142 b[i] = x
143 case 3:
144 b[i] = rune(rr.Intn(utf8.MaxRune)) // potentially invalid
145 default:
146 t.Fatalf("unsupported value: %d", x)
147 }
148 }
149 return string(b)
150 }
151
152 rr := rand.New(rand.NewSource(1))
153 for _, s := range testStrs {
154 for i := 1_000; i >= 0; i-- {
155 testParserReference(t, modifyString(s, rr))
156 }
157 }
158 }
159
160 func TestNextAnsiEscapeSequence_Fuzz_Random(t *testing.T) {
161 t.Parallel()
162
163 if testing.Short() {
164 t.Skip("short test")
165 }
166
167 randomString := func(rr *rand.Rand) string {
168 numChars := rand.Intn(50)
169 codePoints := make([]rune, numChars)
170 for i := range codePoints {
171 var r rune
172 for range 1000 {
173 r = rune(rr.Intn(utf8.MaxRune))
174 // Allow 10% of runes to be invalid
175 if utf8.ValidRune(r) || rr.Float64() < 0.10 {
176 break
177 }
178 }
179 codePoints[i] = r
180 }
181 return string(codePoints)
182 }
183
184 rr := rand.New(rand.NewSource(1))
185 for range 100_000 {
186 testParserReference(t, randomString(rr))
187 }
188 }
189
190 func TestExtractColor(t *testing.T) {
191 assert := func(offset ansiOffset, b int32, e int32, fg tui.Color, bg tui.Color, bold bool) {
192 var attr tui.Attr
193 if bold {
194 attr = tui.Bold
195 }
196 if offset.offset[0] != b || offset.offset[1] != e ||
197 offset.color.fg != fg || offset.color.bg != bg || offset.color.attr != attr {
198 t.Error(offset, b, e, fg, bg, attr)
199 }
200 }
201
202 src := "hello world"
203 var state *ansiState
204 clean := "\x1b[0m"
205 check := func(assertion func(ansiOffsets *[]ansiOffset, state *ansiState)) {
206 output, ansiOffsets, newState := extractColor(src, state, nil)
207 state = newState
208 if output != "hello world" {
209 t.Errorf("Invalid output: %s %v", output, []rune(output))
210 }
211 t.Log(src, ansiOffsets, clean)
212 assertion(ansiOffsets, state)
213 }
214
215 check(func(offsets *[]ansiOffset, state *ansiState) {
216 if offsets != nil {
217 t.Fail()
218 }
219 })
220
221 state = nil
222 src = "\x1b[0mhello world"
223 check(func(offsets *[]ansiOffset, state *ansiState) {
224 if offsets != nil {
225 t.Fail()
226 }
227 })
228
229 state = nil
230 src = "\x1b[1mhello world"
231 check(func(offsets *[]ansiOffset, state *ansiState) {
232 if len(*offsets) != 1 {
233 t.Fail()
234 }
235 assert((*offsets)[0], 0, 11, -1, -1, true)
236 })
237
238 state = nil
239 src = "\x1b[1mhello \x1b[mw\x1b7o\x1b8r\x1b(Bl\x1b[2@d"
240 check(func(offsets *[]ansiOffset, state *ansiState) {
241 if len(*offsets) != 1 {
242 t.Fail()
243 }
244 assert((*offsets)[0], 0, 6, -1, -1, true)
245 })
246
247 state = nil
248 src = "\x1b[1mhello \x1b[Kworld"
249 check(func(offsets *[]ansiOffset, state *ansiState) {
250 if len(*offsets) != 1 {
251 t.Fail()
252 }
253 assert((*offsets)[0], 0, 11, -1, -1, true)
254 })
255
256 state = nil
257 src = "hello \x1b[34;45;1mworld"
258 check(func(offsets *[]ansiOffset, state *ansiState) {
259 if len(*offsets) != 1 {
260 t.Fail()
261 }
262 assert((*offsets)[0], 6, 11, 4, 5, true)
263 })
264
265 state = nil
266 src = "hello \x1b[34;45;1mwor\x1b[34;45;1mld"
267 check(func(offsets *[]ansiOffset, state *ansiState) {
268 if len(*offsets) != 1 {
269 t.Fail()
270 }
271 assert((*offsets)[0], 6, 11, 4, 5, true)
272 })
273
274 state = nil
275 src = "hello \x1b[34;45;1mwor\x1b[0mld"
276 check(func(offsets *[]ansiOffset, state *ansiState) {
277 if len(*offsets) != 1 {
278 t.Fail()
279 }
280 assert((*offsets)[0], 6, 9, 4, 5, true)
281 })
282
283 state = nil
284 src = "hello \x1b[34;48;5;233;1mwo\x1b[38;5;161mr\x1b[0ml\x1b[38;5;161md"
285 check(func(offsets *[]ansiOffset, state *ansiState) {
286 if len(*offsets) != 3 {
287 t.Fail()
288 }
289 assert((*offsets)[0], 6, 8, 4, 233, true)
290 assert((*offsets)[1], 8, 9, 161, 233, true)
291 assert((*offsets)[2], 10, 11, 161, -1, false)
292 })
293
294 // {38,48};5;{38,48}
295 state = nil
296 src = "hello \x1b[38;5;38;48;5;48;1mwor\x1b[38;5;48;48;5;38ml\x1b[0md"
297 check(func(offsets *[]ansiOffset, state *ansiState) {
298 if len(*offsets) != 2 {
299 t.Fail()
300 }
301 assert((*offsets)[0], 6, 9, 38, 48, true)
302 assert((*offsets)[1], 9, 10, 48, 38, true)
303 })
304
305 src = "hello \x1b[32;1mworld"
306 check(func(offsets *[]ansiOffset, state *ansiState) {
307 if len(*offsets) != 1 {
308 t.Fail()
309 }
310 if state.fg != 2 || state.bg != -1 || state.attr == 0 {
311 t.Fail()
312 }
313 assert((*offsets)[0], 6, 11, 2, -1, true)
314 })
315
316 src = "hello world"
317 check(func(offsets *[]ansiOffset, state *ansiState) {
318 if len(*offsets) != 1 {
319 t.Fail()
320 }
321 if state.fg != 2 || state.bg != -1 || state.attr == 0 {
322 t.Fail()
323 }
324 assert((*offsets)[0], 0, 11, 2, -1, true)
325 })
326
327 src = "hello \x1b[0;38;5;200;48;5;100mworld"
328 check(func(offsets *[]ansiOffset, state *ansiState) {
329 if len(*offsets) != 2 {
330 t.Fail()
331 }
332 if state.fg != 200 || state.bg != 100 || state.attr > 0 {
333 t.Fail()
334 }
335 assert((*offsets)[0], 0, 6, 2, -1, true)
336 assert((*offsets)[1], 6, 11, 200, 100, false)
337 })
338
339 state = nil
340 var color24 tui.Color = (1 << 24) + (180 << 16) + (190 << 8) + 254
341 src = "\x1b[1mhello \x1b[22;1;38:2:180:190:254mworld"
342 check(func(offsets *[]ansiOffset, state *ansiState) {
343 if len(*offsets) != 2 {
344 t.Fail()
345 }
346 if state.fg != color24 || state.attr != 1 {
347 t.Fail()
348 }
349 assert((*offsets)[0], 0, 6, -1, -1, true)
350 assert((*offsets)[1], 6, 11, color24, -1, true)
351 })
352
353 src = "\x1b]133;A\x1b\\hello \x1b]133;C\x1b\\world"
354 check(func(offsets *[]ansiOffset, state *ansiState) {
355 if len(*offsets) != 1 {
356 t.Fail()
357 }
358 assert((*offsets)[0], 0, 11, color24, -1, true)
359 })
360 }
361
362 func TestAnsiCodeStringConversion(t *testing.T) {
363 assert := func(code string, prevState *ansiState, expected string) {
364 state := interpretCode(code, prevState)
365 if expected != state.ToString() {
366 t.Errorf("expected: %s, actual: %s",
367 strings.ReplaceAll(expected, "\x1b[", "\\x1b["),
368 strings.ReplaceAll(state.ToString(), "\x1b[", "\\x1b["))
369 }
370 }
371 assert("\x1b[m", nil, "")
372 assert("\x1b[m", &ansiState{attr: tui.Blink, ul: -1, lbg: -1}, "")
373 assert("\x1b[0m", &ansiState{fg: 4, bg: 4, ul: -1, lbg: -1}, "")
374 assert("\x1b[;m", &ansiState{fg: 4, bg: 4, ul: -1, lbg: -1}, "")
375 assert("\x1b[;;m", &ansiState{fg: 4, bg: 4, ul: -1, lbg: -1}, "")
376
377 assert("\x1b[31m", nil, "\x1b[31;49m")
378 assert("\x1b[41m", nil, "\x1b[39;41m")
379
380 assert("\x1b[92m", nil, "\x1b[92;49m")
381 assert("\x1b[102m", nil, "\x1b[39;102m")
382
383 assert("\x1b[31m", &ansiState{fg: 4, bg: 4, ul: -1, lbg: -1}, "\x1b[31;44m")
384 assert("\x1b[1;2;31m", &ansiState{fg: 2, bg: -1, ul: -1, attr: tui.Reverse, lbg: -1}, "\x1b[1;2;7;31;49m")
385 assert("\x1b[38;5;100;48;5;200m", nil, "\x1b[38;5;100;48;5;200m")
386 assert("\x1b[38:5:100:48:5:200m", nil, "\x1b[38;5;100;48;5;200m")
387 assert("\x1b[48;5;100;38;5;200m", nil, "\x1b[38;5;200;48;5;100m")
388 assert("\x1b[48;5;100;38;2;10;20;30;1m", nil, "\x1b[1;38;2;10;20;30;48;5;100m")
389 assert("\x1b[48;5;100;38;2;10;20;30;7m",
390 &ansiState{attr: tui.Dim | tui.Italic, fg: 1, bg: 1, ul: -1},
391 "\x1b[2;3;7;38;2;10;20;30;48;5;100m")
392
393 // Underline styles
394 assert("\x1b[4:3m", nil, "\x1b[4:3;39;49m")
395 assert("\x1b[4:2m", nil, "\x1b[4:2;39;49m")
396 assert("\x1b[4:4m", nil, "\x1b[4:4;39;49m")
397 assert("\x1b[4:5m", nil, "\x1b[4:5;39;49m")
398 assert("\x1b[4:1m", nil, "\x1b[4;39;49m")
399
400 // Underline color (256-color)
401 assert("\x1b[4;58;5;100m", nil, "\x1b[4;39;49;58;5;100m")
402 // Underline color (24-bit)
403 assert("\x1b[4;58;2;255;0;128m", nil, "\x1b[4;39;49;58;2;255;0;128m")
404 // Curly underline + underline color
405 assert("\x1b[4:3;58;2;255;0;0m", nil, "\x1b[4:3;39;49;58;2;255;0;0m")
406 // SGR 59 resets underline color
407 assert("\x1b[59m", &ansiState{fg: 1, bg: -1, ul: 100, lbg: -1}, "\x1b[31;49m")
408 }
409
410 func TestParseAnsiCode(t *testing.T) {
411 tests := []struct {
412 In string
413 Exp string
414 N int
415 Sep byte
416 }{
417 {"123", "", 123, 0},
418 {"1a", "", -1, 0},
419 {"1a;12", "12", -1, ';'},
420 {"12;a", "a", 12, ';'},
421 {"-2", "", -1, 0},
422 // Colon sub-parameters: earliest separator wins (@shtse8)
423 {"4:3", "3", 4, ':'},
424 {"4:3;31", "3;31", 4, ':'},
425 {"38:2:255:0:0", "2:255:0:0", 38, ':'},
426 {"58:5:200", "5:200", 58, ':'},
427 // Semicolon before colon
428 {"4;38:2:0:0:0", "38:2:0:0:0", 4, ';'},
429 }
430 for _, x := range tests {
431 n, sep, s := parseAnsiCode(x.In)
432 if n != x.N || s != x.Exp || sep != x.Sep {
433 t.Fatalf("%q: got: (%d %q %q) want: (%d %q %q)", x.In, n, s, string(sep), x.N, x.Exp, string(x.Sep))
434 }
435 }
436 }
437
438 // Test cases adapted from @shtse8 (PR #4678)
439 func TestInterpretCodeUnderlineStyles(t *testing.T) {
440 // 4:0 = no underline
441 state := interpretCode("\x1b[4:0m", nil)
442 if state.attr&tui.Underline != 0 {
443 t.Error("4:0 should not set underline")
444 }
445
446 // 4:1 = single underline
447 state = interpretCode("\x1b[4:1m", nil)
448 if state.attr&tui.Underline == 0 {
449 t.Error("4:1 should set underline")
450 }
451
452 // 4:3 = curly underline
453 state = interpretCode("\x1b[4:3m", nil)
454 if state.attr&tui.Underline == 0 {
455 t.Error("4:3 should set underline")
456 }
457 if state.attr.UnderlineStyle() != tui.UlStyleCurly {
458 t.Error("4:3 should set curly underline style")
459 }
460
461 // 4:3 should NOT set italic (3 is a sub-param, not SGR 3)
462 if state.attr&tui.Italic != 0 {
463 t.Error("4:3 should not set italic")
464 }
465
466 // 4:2;31 = double underline + red fg
467 state = interpretCode("\x1b[4:2;31m", nil)
468 if state.attr&tui.Underline == 0 {
469 t.Error("4:2;31 should set underline")
470 }
471 if state.fg != 1 {
472 t.Errorf("4:2;31 should set fg to red (1), got %d", state.fg)
473 }
474 if state.attr&tui.Dim != 0 {
475 t.Error("4:2;31 should not set dim")
476 }
477
478 // Plain 4 still works
479 state = interpretCode("\x1b[4m", nil)
480 if state.attr&tui.Underline == 0 {
481 t.Error("4 should set underline")
482 }
483
484 // 4;2 (semicolon) = underline + dim
485 state = interpretCode("\x1b[4;2m", nil)
486 if state.attr&tui.Underline == 0 {
487 t.Error("4;2 should set underline")
488 }
489 if state.attr&tui.Dim == 0 {
490 t.Error("4;2 should set dim")
491 }
492 }
493
494 // Test cases adapted from @shtse8 (PR #4678)
495 func TestInterpretCodeUnderlineColor(t *testing.T) {
496 // 58:2:R:G:B should not affect fg or bg
497 state := interpretCode("\x1b[58:2:255:0:0m", nil)
498 if state.fg != -1 || state.bg != -1 {
499 t.Errorf("58:2:R:G:B should not affect fg/bg, got fg=%d bg=%d", state.fg, state.bg)
500 }
501
502 // 58:5:200 should not affect fg or bg
503 state = interpretCode("\x1b[58:5:200m", nil)
504 if state.fg != -1 || state.bg != -1 {
505 t.Errorf("58:5:N should not affect fg/bg, got fg=%d bg=%d", state.fg, state.bg)
506 }
507
508 // 58:2:R:G:B combined with 38:2:R:G:B should only set fg
509 state = interpretCode("\x1b[58:2:255:0:0;38:2:0:255:0m", nil)
510 expectedFg := tui.Color(1<<24 | 0<<16 | 255<<8 | 0)
511 if state.fg != expectedFg {
512 t.Errorf("expected fg=%d, got %d", expectedFg, state.fg)
513 }
514 if state.bg != -1 {
515 t.Errorf("bg should be -1, got %d", state.bg)
516 }
517 }
518
519 // kernel/bpf/preload/iterators/README
520 const ansiBenchmarkString = "\x1b[38;5;81m\x1b[01;31m\x1b[Kkernel/\x1b[0m\x1b[38:5:81mbpf/" +
521 "\x1b[0m\x1b[38:5:81mpreload/\x1b[0m\x1b[38;5;81miterators/" +
522 "\x1b[0m\x1b[38:5:149mMakefile\x1b[m\x1b[K\x1b[0m"
523
524 func BenchmarkNextAnsiEscapeSequence(b *testing.B) {
525 b.SetBytes(int64(len(ansiBenchmarkString)))
526 for i := 0; i < b.N; i++ {
527 s := ansiBenchmarkString
528 for {
529 _, o := nextAnsiEscapeSequence(s)
530 if o == -1 {
531 break
532 }
533 s = s[o:]
534 }
535 }
536 }
537
538 // Baseline test to compare the speed of nextAnsiEscapeSequence() to the
539 // previously used regex based implementation.
540 func BenchmarkNextAnsiEscapeSequence_Regex(b *testing.B) {
541 b.SetBytes(int64(len(ansiBenchmarkString)))
542 for i := 0; i < b.N; i++ {
543 s := ansiBenchmarkString
544 for {
545 a := ansiRegexReference.FindStringIndex(s)
546 if len(a) == 0 {
547 break
548 }
549 s = s[a[1]:]
550 }
551 }
552 }
553
554 func BenchmarkExtractColor(b *testing.B) {
555 b.SetBytes(int64(len(ansiBenchmarkString)))
556 for i := 0; i < b.N; i++ {
557 extractColor(ansiBenchmarkString, nil, nil)
558 }
559 }