| 1 |
package ansi |
| 2 |
|
| 3 |
import ( |
| 4 |
"testing" |
| 5 |
) |
| 6 |
|
| 7 |
var cases = []struct { |
| 8 |
name string |
| 9 |
input string |
| 10 |
stripped string |
| 11 |
width int |
| 12 |
wcwidth int |
| 13 |
}{ |
| 14 |
{"empty", "", "", 0, 0}, |
| 15 |
{"ascii", "hello", "hello", 5, 5}, |
| 16 |
{"emoji", "👋", "👋", 2, 2}, |
| 17 |
{"wideemoji", "🫧", "🫧", 2, 2}, |
| 18 |
{"combining", "a\u0300", "à", 1, 1}, |
| 19 |
{"control", "\x1b[31mhello\x1b[0m", "hello", 5, 5}, |
| 20 |
{"csi8", "\x9b38;5;1mhello\x9bm", "hello", 5, 5}, |
| 21 |
{"osc", "\x9d2;charmbracelet: ~/Source/bubbletea\x9c", "", 0, 0}, |
| 22 |
{"controlemoji", "\x1b[31m👋\x1b[0m", "👋", 2, 2}, |
| 23 |
{"oscwideemoji", "\x1b]2;title👨👩👦\x07", "", 0, 0}, |
| 24 |
{"oscwideemoji", "\x1b[31m👨👩👦\x1b[m", "👨\u200d👩\u200d👦", 2, 2}, |
| 25 |
{"multiemojicsi", "👨👩👦\x9b38;5;1mhello\x9bm", "👨👩👦hello", 7, 7}, |
| 26 |
{"osc8eastasianlink", "\x9d8;id=1;https://example.com/\x9c打豆豆\x9d8;id=1;\x07", "打豆豆", 6, 6}, |
| 27 |
{"dcsarabic", "\x1bP?123$pسلام\x1b\\اهلا", "اهلا", 4, 4}, |
| 28 |
{"newline", "hello\nworld", "hello\nworld", 10, 10}, |
| 29 |
{"tab", "hello\tworld", "hello\tworld", 10, 10}, |
| 30 |
{"controlnewline", "\x1b[31mhello\x1b[0m\nworld", "hello\nworld", 10, 10}, |
| 31 |
{"style", "\x1B[38;2;249;38;114mfoo", "foo", 3, 3}, |
| 32 |
{"unicode", "\x1b[35m“box”\x1b[0m", "“box”", 5, 5}, |
| 33 |
{"just_unicode", "Claire’s Boutique", "Claire’s Boutique", 17, 17}, |
| 34 |
{"unclosed_ansi", "Hey, \x1b[7m\n猴", "Hey, \n猴", 7, 7}, |
| 35 |
{"double_asian_runes", " 你\x1b[8m好.", " 你好.", 6, 6}, |
| 36 |
{"flag", "🇸🇦", "🇸🇦", 2, 1}, |
| 37 |
} |
| 38 |
|
| 39 |
func TestStrip(t *testing.T) { |
| 40 |
for i, c := range cases { |
| 41 |
t.Run(c.name, func(t *testing.T) { |
| 42 |
if res := Strip(c.input); res != c.stripped { |
| 43 |
t.Errorf("test case %d (%s) failed:\nexpected %q, got %q", i, c.name, c.stripped, res) |
| 44 |
} |
| 45 |
}) |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
func TestStringWidth(t *testing.T) { |
| 50 |
for i, c := range cases { |
| 51 |
t.Run(c.name, func(t *testing.T) { |
| 52 |
if width := StringWidth(c.input); width != c.width { |
| 53 |
t.Errorf("test case %d failed: expected %d, got %d", i+1, c.width, width) |
| 54 |
} |
| 55 |
}) |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
func TestWcStringWidth(t *testing.T) { |
| 60 |
for i, c := range cases { |
| 61 |
t.Run(c.name, func(t *testing.T) { |
| 62 |
if width := StringWidthWc(c.input); width != c.wcwidth { |
| 63 |
t.Errorf("test case %d failed: expected %d, got %d", i+1, c.wcwidth, width) |
| 64 |
} |
| 65 |
}) |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
func BenchmarkStringWidth(b *testing.B) { |
| 70 |
b.RunParallel(func(pb *testing.PB) { |
| 71 |
b.ReportAllocs() |
| 72 |
b.ResetTimer() |
| 73 |
for pb.Next() { |
| 74 |
StringWidth("foo") |
| 75 |
} |
| 76 |
}) |
| 77 |
} |