| 1 | package ui |
| 2 | |
| 3 | import ( |
| 4 | "io" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | "unicode" |
| 10 | "unicode/utf8" |
| 11 | ) |
| 12 | |
| 13 | |
| 14 | |
| 15 | func checkPlain(t *testing.T, what, s string) { |
| 16 | t.Helper() |
| 17 | if !utf8.ValidString(s) { |
| 18 | t.Fatalf("%s: invalid UTF-8 (a raw C1 byte to some terminals): %q", what, s) |
| 19 | } |
| 20 | for _, r := range s { |
| 21 | if r != '\t' && unicode.IsControl(r) { |
| 22 | t.Fatalf("%s: control character %U in %q", what, r, s) |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | var guestSeeds = []string{ |
| 28 | "plain line", |
| 29 | "\x1b[31mred\x1b[0m", |
| 30 | "\x1b]0;title\x07", |
| 31 | "\u009b31m C1 CSI", |
| 32 | "\u009d0;title\u009c", |
| 33 | "bell\x07 bs\x08 del\x7f", |
| 34 | "\xff\x9b2J raw bytes", |
| 35 | `time="2026" level=info msg="Downloading \x1b[2J"`, |
| 36 | "progress 10%\rprogress 20%", |
| 37 | } |
| 38 | |
| 39 | func FuzzTail(f *testing.F) { |
| 40 | for _, s := range guestSeeds { |
| 41 | f.Add(s) |
| 42 | } |
| 43 | f.Fuzz(func(t *testing.T, s string) { |
| 44 | p := filepath.Join(t.TempDir(), "log") |
| 45 | if err := os.WriteFile(p, []byte(s), 0o644); err != nil { |
| 46 | t.Fatal(err) |
| 47 | } |
| 48 | for _, l := range strings.Split(strings.TrimSuffix(Tail(p, 20), "\n"), "\n") { |
| 49 | checkPlain(t, "Tail", l) |
| 50 | } |
| 51 | }) |
| 52 | } |
| 53 | |
| 54 | func FuzzWindowLine(f *testing.F) { |
| 55 | for _, s := range guestSeeds { |
| 56 | f.Add(s) |
| 57 | } |
| 58 | f.Fuzz(func(t *testing.T, s string) { |
| 59 | w := &Window{out: io.Discard, log: io.Discard, tty: true, width: 80, height: 10} |
| 60 | w.Write([]byte(s + "\n")) |
| 61 | w.Close() |
| 62 | for _, l := range w.lines { |
| 63 | checkPlain(t, "Window", l) |
| 64 | if strings.Contains(l, "\t") { |
| 65 | t.Fatalf("Window: a tab breaks the width: %q", l) |
| 66 | } |
| 67 | } |
| 68 | }) |
| 69 | } |