Debian Codegraph @

fuzz_test.go

raw symbols SCIP
1 package displaywidth
2
3 import (
4 "bytes"
5 "strings"
6 "testing"
7 "unicode/utf8"
8
9 "github.com/clipperhouse/displaywidth/testdata"
10 )
11
12 // FuzzBytesAndString fuzzes the Bytes function with valid and invalid UTF-8.
13 func FuzzBytesAndString(f *testing.F) {
14 if testing.Short() {
15 f.Skip("skipping fuzz test in short mode")
16 }
17
18 // Seed with multi-lingual text (paragraph-sized chunks)
19 file, err := testdata.Sample()
20 if err != nil {
21 f.Fatal(err)
22 }
23 chunks := bytes.Split(file, []byte("\n"))
24 for _, chunk := range chunks {
25 f.Add(chunk)
26 }
27
28 // Seed with invalid UTF-8
29 invalid, err := testdata.InvalidUTF8()
30 if err != nil {
31 f.Fatal(err)
32 }
33 chunks = bytes.Split(invalid, []byte("\n"))
34 for _, chunk := range chunks {
35 f.Add(chunk)
36 }
37
38 // Seed with test cases
39 testCases, err := testdata.TestCases()
40 if err != nil {
41 f.Fatal(err)
42 }
43 chunks = bytes.Split(testCases, []byte("\n"))
44 for _, chunk := range chunks {
45 f.Add(chunk)
46 }
47
48 // Seed with random bytes
49 for i := 0; i < 10; i++ {
50 b, err := testdata.RandomBytes()
51 if err != nil {
52 f.Fatal(err)
53 }
54 f.Add(b)
55 }
56
57 // Seed with edge cases
58 f.Add([]byte("")) // empty
59 f.Add([]byte("a")) // single ASCII
60 f.Add([]byte("\x00")) // null byte
61 f.Add([]byte("\t\n\r")) // whitespace
62 f.Add([]byte("🌍")) // emoji
63 f.Add([]byte("\u0301")) // combining mark
64 f.Add([]byte{0xff, 0xfe, 0xfd}) // invalid UTF-8
65
66 f.Fuzz(func(t *testing.T, text []byte) {
67 // Test with default options
68 wb := Bytes(text)
69
70 // Invariant: width should never be negative
71 if wb < 0 {
72 t.Errorf("Bytes() returned negative width for %q: %d", text, wb)
73 }
74
75 // Invariant: empty input should always return 0
76 if len(text) == 0 && wb != 0 {
77 t.Errorf("Bytes() returned non-zero width %d for empty input", wb)
78 }
79
80 // Invariant: for valid UTF-8, width should never exceed input length
81 // (each byte is at most 1 column wide, some are 0, some multi-byte chars are 2)
82 if utf8.Valid(text) {
83 runeCount := utf8.RuneCount(text)
84 if wb > len(text) {
85 t.Errorf("Bytes() width %d exceeds byte length %d for valid UTF-8: %q", wb, len(text), text)
86 }
87
88 // Also shouldn't exceed rune count * 2 (max width per rune is 2)
89 if wb > runeCount*2 {
90 t.Errorf("Bytes() width %d exceeds rune count * 2 (%d) for %q", wb, runeCount*2, text)
91 }
92
93 // Consistency check: String() and Bytes() should agree on valid UTF-8
94 ws := String(string(text))
95 if wb != ws {
96 t.Errorf("Bytes() returned %d but String() returned %d for %q", wb, ws, text)
97 }
98 }
99
100 // Test with different options combinations
101 options := []Options{
102 {EastAsianWidth: false},
103 {EastAsianWidth: true},
104 {ControlSequences: true},
105 {ControlSequences8Bit: true},
106 {ControlSequences: true, ControlSequences8Bit: true},
107 {EastAsianWidth: true, ControlSequences: true},
108 {EastAsianWidth: true, ControlSequences8Bit: true},
109 }
110
111 for _, option := range options {
112 wb := option.Bytes(text)
113
114 // Same invariants apply
115 if wb < 0 {
116 t.Errorf("Bytes() with options %+v returned negative width for %q: %d", option, text, wb)
117 }
118
119 if len(text) == 0 && wb != 0 {
120 t.Errorf("Bytes() with options %+v returned non-zero width %d for empty input", option, wb)
121 }
122
123 ws := option.String(string(text))
124 if wb != ws {
125 t.Errorf("Bytes() returned %d but String() returned %d with options %+v for %q", wb, ws, option, text)
126 }
127 }
128 })
129 }
130
131 // FuzzRune fuzzes the Rune function.
132 func FuzzRune(f *testing.F) {
133 if testing.Short() {
134 f.Skip("skipping fuzz test in short mode")
135 }
136
137 // Seed with interesting runes
138 seeds := []rune{
139 0, // null
140 ' ', // space
141 'A', // ASCII
142 '\t', // tab
143 '\n', // newline
144 '\u0000', // null
145 '\u0301', // combining acute accent
146 '\u00A0', // non-breaking space
147 '\u2028', // line separator
148 '\u2029', // paragraph separator
149 '\uFEFF', // zero-width no-break space
150 '\uFFFD', // replacement character
151 '\uFFFE', // noncharacter
152 '\uFFFF', // noncharacter
153 'δΈ–', // CJK
154 'η•Œ', // CJK
155 '🌍', // emoji
156 'πŸ‘¨', // emoji
157 0xD800, // surrogate (invalid)
158 0xDFFF, // surrogate (invalid)
159 0x10FFFF, // max valid rune
160 }
161
162 for _, r := range seeds {
163 f.Add(r)
164 }
165
166 f.Fuzz(func(t *testing.T, r rune) {
167 // Test with default options
168 wr := Rune(r)
169
170 // Invariant: width should never be negative
171 if wr < 0 {
172 t.Errorf("Rune() returned negative width for %U (%c): %d", r, r, wr)
173 }
174
175 // Invariant: width should be 0, 1, or 2
176 if wr > 2 {
177 t.Errorf("Rune() returned invalid width for %U (%c): %d (expected 0, 1, or 2)", r, r, wr)
178 }
179
180 // Consistency check: compare with Bytes/String for valid runes
181 if utf8.ValidRune(r) {
182 var buf [4]byte
183 n := utf8.EncodeRune(buf[:], r)
184
185 wb := Bytes(buf[:n])
186 if wr != wb {
187 t.Errorf("Rune() returned %d but Bytes() returned %d for %U (%c)", wr, wb, r, r)
188 }
189
190 ws := String(string(r))
191 if wr != ws {
192 t.Errorf("Rune() returned %d but String() returned %d for %U (%c)", wr, ws, r, r)
193 }
194 }
195
196 // Test with different options (Rune is per-rune, ControlSequences
197 // doesn't affect single runes, but we include it for completeness)
198 options := []Options{
199 {EastAsianWidth: false},
200 {EastAsianWidth: true},
201 {ControlSequences: true},
202 {EastAsianWidth: true, ControlSequences: true},
203 }
204
205 for _, option := range options {
206 wr := option.Rune(r)
207
208 // Same invariants apply
209 if wr < 0 || wr > 2 {
210 t.Errorf("Rune() with options %+v returned invalid width for %U (%c): %d", option, r, r, wr)
211 }
212
213 // Consistency check with Bytes/String for valid runes
214 if utf8.ValidRune(r) {
215 var buf [4]byte
216 n := utf8.EncodeRune(buf[:], r)
217
218 wb := option.Bytes(buf[:n])
219 if wr != wb {
220 t.Errorf("Rune() returned %d but Bytes() returned %d with options %+v for %U (%c)", wr, wb, option, r, r)
221 }
222
223 ws := option.String(string(r))
224 if wr != ws {
225 t.Errorf("Rune() returned %d but String() returned %d with options %+v for %U (%c)", wr, ws, option, r, r)
226 }
227 }
228 }
229 })
230 }
231
232 func FuzzTruncateStringAndBytes(f *testing.F) {
233 if testing.Short() {
234 f.Skip("skipping fuzz test in short mode")
235 }
236
237 // Seed with multi-lingual text (paragraph-sized chunks)
238 file, err := testdata.Sample()
239 if err != nil {
240 f.Fatal(err)
241 }
242 fs := string(file)
243 chunks := strings.Split(fs, "\n")
244 for _, chunk := range chunks {
245 f.Add(chunk)
246 }
247
248 // Seed with invalid UTF-8
249 invalid, err := testdata.InvalidUTF8()
250 if err != nil {
251 f.Fatal(err)
252 }
253 fs = string(invalid)
254 chunks = strings.Split(fs, "\n")
255 for _, chunk := range chunks {
256 f.Add(chunk)
257 }
258
259 // Seed with test cases
260 testCases, err := testdata.TestCases()
261 if err != nil {
262 f.Fatal(err)
263 }
264 fs = string(testCases)
265 chunks = strings.Split(fs, "\n")
266 for _, chunk := range chunks {
267 f.Add(chunk)
268 }
269
270 // Seed with random bytes
271 for i := 0; i < 10; i++ {
272 b, err := testdata.RandomBytes()
273 if err != nil {
274 f.Fatal(err)
275 }
276 f.Add(string(b))
277 }
278
279 // Seed with edge cases
280 f.Add("") // empty
281 f.Add("a") // single ASCII
282 f.Add("\t\n\r") // whitespace
283 f.Add("🌍") // emoji
284 f.Add("\u0301") // combining mark
285 f.Add("\xff\xfe\xfd") // invalid UTF-8
286
287 f.Fuzz(func(t *testing.T, text string) {
288 // Exercise truncation to discover panics and infinite loops.
289 // Width invariant testing is in proper unit tests.
290 options := []Options{
291 {},
292 {EastAsianWidth: true},
293 {ControlSequences: true},
294 {ControlSequences8Bit: true},
295 {ControlSequences: true, ControlSequences8Bit: true},
296 {EastAsianWidth: true, ControlSequences: true},
297 {EastAsianWidth: true, ControlSequences8Bit: true},
298 }
299
300 for _, option := range options {
301 ts := option.TruncateString(text, 10, "...")
302 tb := option.TruncateBytes([]byte(text), 10, []byte("..."))
303
304 // Invariant: String and Bytes paths must agree
305 if !bytes.Equal(tb, []byte(ts)) {
306 t.Errorf("TruncateBytes() != TruncateString() with %+v for %q: %q != %q", option, text, tb, ts)
307 }
308 }
309 })
310 }
311
312 // FuzzControlSequences fuzzes strings containing ANSI/ECMA-48 escape sequences
313 // across all option combinations (EastAsianWidth x ControlSequences).
314 func FuzzControlSequences(f *testing.F) {
315 if testing.Short() {
316 f.Skip("skipping fuzz test in short mode")
317 }
318
319 // Seed with ANSI escape sequences
320 f.Add([]byte("\x1b[31m")) // SGR red
321 f.Add([]byte("\x1b[0m")) // SGR reset
322 f.Add([]byte("\x1b[1m")) // SGR bold
323 f.Add([]byte("\x1b[38;5;196m")) // SGR 256-color
324 f.Add([]byte("\x1b[38;2;255;0;0m")) // SGR truecolor
325 f.Add([]byte("\x1b[A")) // cursor up
326 f.Add([]byte("\x1b[10;20H")) // cursor position
327 f.Add([]byte("\x1b[2J")) // erase in display
328 f.Add([]byte("\x1b[31mhello\x1b[0m")) // red text
329 f.Add([]byte("\x1b[1m\x1b[31mhi\x1b[0m")) // nested SGR
330 f.Add([]byte("hello\x1b[31mworld\x1b[0m")) // ANSI mid-string
331 f.Add([]byte("\x1b[31mδΈ­ζ–‡\x1b[0m")) // colored CJK
332 f.Add([]byte("\x1b[31mπŸ˜€\x1b[0m")) // colored emoji
333 f.Add([]byte("\x1b[31mπŸ‡ΊπŸ‡Έ\x1b[0m")) // colored flag
334 f.Add([]byte("a\x1b[31mb\x1b[32mc\x1b[33md\x1b[0m")) // multiple colors
335 f.Add([]byte("\x1b[31m\x1b[42m\x1b[1mbold on red\x1b[0m")) // stacked SGR
336 f.Add([]byte("\r\n")) // CR+LF
337 f.Add([]byte("hello\r\nworld")) // text with CRLF
338 f.Add([]byte("\x1b")) // bare ESC
339 f.Add([]byte("\x1b[")) // incomplete sequence
340 f.Add([]byte("\x1b[31")) // incomplete SGR
341 f.Add([]byte("")) // empty
342 f.Add([]byte("hello")) // plain ASCII
343 f.Add([]byte("δΈ­ζ–‡")) // plain CJK
344 f.Add([]byte("πŸ˜€")) // plain emoji
345
346 // Seed with 8-bit C1 escape sequences
347 f.Add([]byte("\x9B31m")) // C1 CSI red
348 f.Add([]byte("\x9B0m")) // C1 CSI reset
349 f.Add([]byte("\x9B1m")) // C1 CSI bold
350 f.Add([]byte("\x9B31mhello\x9B0m")) // C1 CSI red text
351 f.Add([]byte("\x9B1m\x9B31mhi\x9B0m")) // C1 nested SGR
352 f.Add([]byte("hello\x9B31mworld\x9B0m")) // C1 mid-string
353 f.Add([]byte("\x9B31mδΈ­ζ–‡\x9B0m")) // C1 colored CJK
354 f.Add([]byte("\x9B31mπŸ˜€\x9B0m")) // C1 colored emoji
355 f.Add([]byte("\x9D0;Title\x9C")) // C1 OSC with C1 ST
356 f.Add([]byte("\x9D0;Title\x07")) // C1 OSC with BEL
357 f.Add([]byte("\x90qpayload\x9C")) // C1 DCS with C1 ST
358 f.Add([]byte("\x84")) // standalone C1
359 f.Add([]byte("\x1b[31mhello\x9B0m")) // mixed 7-bit and 8-bit
360
361 // Seed with multi-lingual text
362 file, err := testdata.Sample()
363 if err != nil {
364 f.Fatal(err)
365 }
366 chunks := bytes.Split(file, []byte("\n"))
367 for _, chunk := range chunks {
368 f.Add(chunk)
369 }
370
371 options := []Options{
372 {},
373 {EastAsianWidth: true},
374 {ControlSequences: true},
375 {ControlSequences8Bit: true},
376 {ControlSequences: true, ControlSequences8Bit: true},
377 {EastAsianWidth: true, ControlSequences: true},
378 {EastAsianWidth: true, ControlSequences8Bit: true},
379 {EastAsianWidth: true, ControlSequences: true, ControlSequences8Bit: true},
380 }
381
382 f.Fuzz(func(t *testing.T, text []byte) {
383 for _, opt := range options {
384 wb := opt.Bytes(text)
385 ws := opt.String(string(text))
386
387 // Invariant: width is never negative
388 if wb < 0 {
389 t.Errorf("Bytes() with %+v returned negative width %d for %q", opt, wb, text)
390 }
391
392 // Invariant: String and Bytes agree
393 if wb != ws {
394 t.Errorf("Bytes()=%d != String()=%d with %+v for %q", wb, ws, opt, text)
395 }
396
397 // Invariant: empty input is always 0
398 if len(text) == 0 && wb != 0 {
399 t.Errorf("non-zero width %d for empty input with %+v", wb, opt)
400 }
401
402 // Invariant: sum of grapheme widths equals total width
403 bg := opt.BytesGraphemes(text)
404 bgSum := 0
405 for bg.Next() {
406 gw := bg.Width()
407 if gw < 0 {
408 t.Errorf("grapheme Width() < 0 with %+v for %q", opt, text)
409 }
410 bgSum += gw
411 }
412 if bgSum != wb {
413 t.Errorf("sum of grapheme widths %d != Bytes() %d with %+v for %q", bgSum, wb, opt, text)
414 }
415
416 // Same for StringGraphemes
417 sg := opt.StringGraphemes(string(text))
418 sgSum := 0
419 for sg.Next() {
420 gw := sg.Width()
421 if gw < 0 {
422 t.Errorf("grapheme Width() < 0 with %+v for %q", opt, text)
423 }
424 sgSum += gw
425 }
426 if sgSum != ws {
427 t.Errorf("sum of StringGraphemes widths %d != String() %d with %+v for %q", sgSum, ws, opt, text)
428 }
429
430 // Exercise truncation to discover panics and infinite loops.
431 // Width invariant testing is in proper unit tests.
432 tail := "..."
433 for _, maxWidth := range []int{0, 1, 3, 5, 10, 20} {
434 ts := opt.TruncateString(string(text), maxWidth, tail)
435 tb := opt.TruncateBytes(text, maxWidth, []byte(tail))
436
437 // Invariant: String and Bytes paths must agree
438 if !bytes.Equal(tb, []byte(ts)) {
439 t.Errorf("TruncateBytes() != TruncateString() with %+v for %q: %q != %q",
440 opt, text, tb, ts)
441 }
442 }
443 }
444 })
445 }