aboutsummaryrefslogtreecommitdiff
path: root/terminal_test.go
blob: b0686ed92b7deef5223f850ca0854db7fb79091f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main

import (
	"slices"
	"testing"
)

// This could be way more extensive, but we're not aiming for perfection.
var tests = []struct {
	push, want string
}{
	{
		// Escaping and UTF-8.
		"\x03\x1bž\bř",
		"^C^[ř\n",
	},
	{
		// Several kinds of sequences to be ignored.
		"\x1bc\x1b[?7l\x1b[2J\x1b[0;1mSeaBIOS\rTea",
		"TeaBIOS\n",
	},
	{
		// New origin and absolute positioning.
		"Line 1\n\x1bcWine B\nFine 3\x1b[1;6H2\x1b[HL\nL",
		"Line 1\nLine 2\nLine 3\n",
	},
	{
		// In-line positioning (without corner cases).
		"A\x1b[CB\x1b[2C?\x1b[DC\x1b[2D\b->",
		"A B->C\n",
	},
	{
		// Up and down.
		"\nB\x1bMA\v\vC" + "\x1b[4EG" + "\x1b[FF" + "\x1b[2FD" + "\x1b[EE",
		" A\nB\nC\nD\nE\nF\nG\n",
	},
	{
		// In-line erasing.
		"1234\b\b\x1b[K\n5678\b\b\x1b[0K\n" + "abcd\b\b\x1b[1K\nefgh\x1b[2K",
		"12\n56\n  cd\n\n",
	},
}

func TestTerminal(t *testing.T) {
	for _, test := range tests {
		tw := terminalWriter{}
		if _, err := tw.Write([]byte(test.push)); err != nil {
			t.Errorf("%#v: %s", test.push, err)
			continue
		}
		have := string(tw.Serialize(0))
		if have != test.want {
			t.Errorf("%#v: %#v; want %#v", test.push, have, test.want)
		}
	}
}

func TestTerminalExploded(t *testing.T) {
Loop:
	for _, test := range tests {
		tw := terminalWriter{}
		for _, b := range []byte(test.push) {
			if _, err := tw.Write([]byte{b}); err != nil {
				t.Errorf("%#v: %s", test.push, err)
				continue Loop
			}
		}
		have := string(tw.Serialize(0))
		if have != test.want {
			t.Errorf("%#v: %#v; want %#v", test.push, have, test.want)
		}
	}
}

func TestTerminalUpdateGroups(t *testing.T) {
	tw := terminalWriter{}
	collect := func() (have []int) {
		for _, line := range tw.lines {
			have = append(have, line.updateGroup)
		}
		return
	}

	// 0: A      0 0 0
	// 1: B X    1 1 1
	// 2: C Y 1  2 1 1
	// 3:   Z 2    3 2
	// 4:     3      4
	tw.Write([]byte("A\nB\nC\x1b[FX\nY\nZ"))
	have, want := collect(), []int{0, 1, 1, 3}
	if !slices.Equal(want, have) {
		t.Errorf("update groups: %+v; want: %+v", have, want)
	}

	tw.Write([]byte("\x1b[F1\n2\n3"))
	have, want = collect(), []int{0, 1, 1, 2, 4}
	if !slices.Equal(want, have) {
		t.Errorf("update groups: %+v; want: %+v", have, want)
	}
}