| 1 | package ui |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | |
| 11 | func TestBoxWidth(t *testing.T) { |
| 12 | for width, want := range map[int]int{40: 40, 20: 30, 200: 72} { |
| 13 | var b bytes.Buffer |
| 14 | u := &UI{Stderr: &b, Width: width} |
| 15 | u.Box("Title", strings.Repeat("word ", 40)) |
| 16 | for _, l := range strings.Split(strings.TrimSuffix(b.String(), "\n"), "\n") { |
| 17 | if len(l) > want { |
| 18 | t.Errorf("width %d: line of %d: %q", width, len(l), l) |
| 19 | } |
| 20 | } |
| 21 | if last := strings.Split(strings.TrimSuffix(b.String(), "\n"), "\n"); len(last[len(last)-1]) != want { |
| 22 | t.Errorf("width %d: bottom rule %q", width, last[len(last)-1]) |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | func TestWindow(t *testing.T) { |
| 31 | var out, log bytes.Buffer |
| 32 | w := &Window{out: &out, log: &log, tty: true, width: 20, height: 3} |
| 33 | var in strings.Builder |
| 34 | for i := 1; i <= 5; i++ { |
| 35 | fmt.Fprintf(&in, "line %d\n", i) |
| 36 | } |
| 37 | in.WriteString(`time="2026-10-04T10:00:00Z" level=info msg="Downloading the image"` + "\n") |
| 38 | in.WriteString("10%\r50%\r100%\n") |
| 39 | in.WriteString(strings.Repeat("x", 40) + "\n") |
| 40 | in.WriteString("\x1b[31mred\x1b[0m\tend") |
| 41 | w.Write([]byte(in.String())) |
| 42 | if strings.Join(w.lines, "|") != "Downloading the ima|100%|"+strings.Repeat("x", 19) { |
| 43 | t.Errorf("window: %q", w.lines) |
| 44 | } |
| 45 | if log.String() != in.String() { |
| 46 | t.Errorf("log: %q", log.String()) |
| 47 | } |
| 48 | w.Close() |
| 49 | if !strings.HasSuffix(out.String(), "\033[3A\r\033[J") || w.drawn != 0 { |
| 50 | t.Errorf("not cleared: %q", out.String()[max(len(out.String())-20, 0):]) |
| 51 | } |
| 52 | if strings.Join(w.lines, "|") != "100%|"+strings.Repeat("x", 19)+"|red end" { |
| 53 | t.Errorf("last line: %q", w.lines) |
| 54 | } |
| 55 | |
| 56 | out.Reset() |
| 57 | w = &Window{out: &out, log: &log, width: 20, height: 3} |
| 58 | w.Write([]byte("a\nb\n")) |
| 59 | w.Close() |
| 60 | if out.String() != "a\nb\n" { |
| 61 | t.Errorf("no terminal: %q", out.String()) |
| 62 | } |
| 63 | } |