-
Notifications
You must be signed in to change notification settings - Fork 301
/
interactive_tester.go
354 lines (297 loc) · 8.06 KB
/
interactive_tester.go
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package rty
import (
"encoding/gob"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"runtime/debug"
"strings"
"testing"
"github.com/pkg/errors"
"github.com/rivo/tview"
"github.com/stretchr/testify/assert"
"github.com/gdamore/tcell"
)
const testDataDir = "testdata"
// Whitelist characters allowed in a name, because they will be used to create
// filenames.
//
// Forbid filenames with colons because they mess up the Windows git client :(
var validNameRegexp = regexp.MustCompile("^[a-zA-Z0-9 .,_-]+$")
type InteractiveTester struct {
usedNames map[string]bool
dummyScreen tcell.SimulationScreen
interactiveScreen tcell.Screen
rty RTY
t ErrorReporter
}
type ErrorReporter interface {
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
Helper()
}
func NewInteractiveTester(t ErrorReporter, screen tcell.Screen) InteractiveTester {
dummyScreen := tcell.NewSimulationScreen("")
err := dummyScreen.Init()
assert.NoError(t, err)
return InteractiveTester{
usedNames: make(map[string]bool),
dummyScreen: dummyScreen,
interactiveScreen: screen,
rty: NewRTY(dummyScreen, t),
t: t,
}
}
func (i *InteractiveTester) T() ErrorReporter {
return i.t
}
func (i *InteractiveTester) Run(name string, width int, height int, c Component) {
i.t.Helper()
err := i.runCaptureError(name, width, height, c)
if err != nil {
i.t.Errorf("error rendering %s: %v", name, err)
}
i.dummyScreen.Clear()
}
func (i *InteractiveTester) render(width int, height int, c Component) Canvas {
actual := newScreenCanvas(i.dummyScreen, i.t)
i.dummyScreen.SetSize(width, height)
defer func() {
if e := recover(); e != nil {
i.t.Fatalf("panic rendering: %v %s", e, debug.Stack())
}
}()
i.rty.Render(c)
return actual
}
// Returns an error if rendering failed.
// If any other failure is encountered, fails via `i.t`'s `testing.T` and returns `nil`.
func (i *InteractiveTester) runCaptureError(name string, width int, height int, c Component) error {
i.t.Helper()
_, ok := i.usedNames[name]
if ok {
i.t.Fatalf("test name '%s' was already used", name)
}
if !validNameRegexp.MatchString(name) {
i.t.Fatalf("test name has invalid characters: %s", name)
}
actual := i.render(width, height, c)
expected := i.loadGoldenFile(name)
eq := canvasesEqual(actual, expected)
if !eq {
updated, err := i.displayAndMaybeWrite(name, actual, expected)
if err == nil {
if !updated {
err = errors.New("actual rendering didn't match expected")
}
}
if err != nil {
i.t.Errorf("%s: %v", name, err)
}
}
return nil
}
// Default windows terminal fonts typically don't include
// these characters, so we make substitutions.
var equivalentChars = [][]rune{
{'▼', '↓'},
{'▶', '→'},
{'✖', '×'},
{tview.BoxDrawingsLightDownAndRight, '⠋'},
}
func canvasesEqual(actual, expected Canvas) bool {
actualWidth, actualHeight := actual.Size()
expectedWidth, expectedHeight := expected.Size()
if actualWidth != expectedWidth || actualHeight != expectedHeight {
return false
}
for x := 0; x < actualWidth; x++ {
for y := 0; y < actualHeight; y++ {
actualCh, _, actualStyle, _ := actual.GetContent(x, y)
expectedCh, _, expectedStyle, _ := expected.GetContent(x, y)
isEqualCh := actualCh == expectedCh
if !isEqualCh {
for _, pair := range equivalentChars {
if expectedCh == pair[0] {
expectedCh = pair[1]
}
if actualCh == pair[0] {
actualCh = pair[1]
}
}
isEqualCh = actualCh == expectedCh
}
if !isEqualCh || actualStyle != expectedStyle {
return false
}
}
}
return true
}
func (i *InteractiveTester) renderDiff(screen tcell.Screen, name string, actual, expected Canvas, highlightDiff bool) error {
screen.Clear()
actualWidth, actualHeight := actual.Size()
expectedWidth, expectedHeight := expected.Size()
curHeight := 0
printForTest(screen, curHeight, "y: accept, n: reject, d: diff, q: quit")
curHeight++
printForTest(screen, curHeight, fmt.Sprintf("test: %s", name))
curHeight++
printForTest(screen, curHeight, "actual:")
curHeight++
for y := 0; y < actualHeight; y++ {
for x := 0; x < actualWidth; x++ {
ch, _, style, _ := actual.GetContent(x, y)
if highlightDiff {
expectedCh, _, expectedStyle, _ := expected.GetContent(x, y)
if ch != expectedCh || style != expectedStyle {
style = style.Reverse(true)
}
}
screen.SetContent(x, curHeight, ch, nil, style)
}
curHeight++
}
curHeight++
printForTest(screen, curHeight, "expected:")
curHeight++
for y := 0; y < expectedHeight; y++ {
for x := 0; x < expectedWidth; x++ {
ch, _, style, _ := expected.GetContent(x, y)
if highlightDiff {
actualCh, _, actualStyle, _ := actual.GetContent(x, y)
if ch != actualCh || style != actualStyle {
style = style.Reverse(true)
}
}
screen.SetContent(x, curHeight, ch, nil, style)
}
curHeight++
}
screen.Show()
return nil
}
func (i *InteractiveTester) displayAndMaybeWrite(name string, actual, expected Canvas) (updated bool, err error) {
screen := i.interactiveScreen
if screen == nil {
return false, nil
}
highlightDiff := false
for {
err := i.renderDiff(screen, name, actual, expected, highlightDiff)
if err != nil {
return false, err
}
ev := screen.PollEvent()
if ev, ok := ev.(*tcell.EventKey); ok {
switch ev.Rune() {
case 'y':
return true, i.writeGoldenFile(name, actual)
case 'n':
return false, errors.New("user indicated expected output was not as desired")
case 'd':
highlightDiff = !highlightDiff
case 'q':
fmt.Println("User exited by pressing 'q'")
screen.Fini()
os.Exit(1)
}
}
}
}
func printForTest(screen tcell.Screen, y int, text string) {
for x, ch := range text {
screen.SetContent(x, y, ch, nil, tcell.StyleDefault)
}
}
type caseData struct {
Width int
Height int
Cells []caseCell
}
type caseCell struct {
Ch rune
Style tcell.Style
}
func (i *InteractiveTester) filename(name string) string {
return filepath.Join(testDataDir, strings.ReplaceAll(name, "/", "_")+".gob")
}
func (i *InteractiveTester) loadGoldenFile(name string) Canvas {
fi, err := os.Open(i.filename(name))
if err != nil {
return newTempCanvas(1, 1, tcell.StyleDefault, i.t)
}
defer func() {
err := fi.Close()
if err != nil {
log.Printf("error closing file %s\n", fi.Name())
}
}()
dec := gob.NewDecoder(fi)
var d caseData
err = dec.Decode(&d)
if err != nil {
return newTempCanvas(1, 1, tcell.StyleDefault, i.t)
}
c := newTempCanvas(d.Width, d.Height, tcell.StyleDefault, i.t)
for i, cell := range d.Cells {
x := i % d.Width
y := i / d.Width
c.SetContent(x, y, cell.Ch, nil, cell.Style)
}
return c
}
func (i *InteractiveTester) writeGoldenFile(name string, actual Canvas) error {
_, err := os.Stat(testDataDir)
if os.IsNotExist(err) {
err := os.Mkdir(testDataDir, os.FileMode(0755))
if err != nil {
return err
}
} else if err != nil {
return err
}
fi, err := os.Create(i.filename(name))
if err != nil {
return err
}
width, height := actual.Size()
d := caseData{
Width: width,
Height: height,
}
// iterative over y first so we write by rows
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
ch, _, style, _ := actual.GetContent(x, y)
d.Cells = append(d.Cells, caseCell{Ch: ch, Style: style})
}
}
enc := gob.NewEncoder(fi)
return enc.Encode(d)
}
// unfortunately, tcell misbehaves if we try to make a new Screen for every test
// this function is intended for use from a `TestMain`, so that we can have a global Screen across all tests in the package
func InitScreenAndRun(m *testing.M, screen *tcell.Screen) {
if s := os.Getenv("RTY_INTERACTIVE"); s != "" {
var err error
*screen, err = tcell.NewTerminfoScreen()
if err != nil {
log.Fatal(err)
}
err = (*screen).Init()
if err != nil {
log.Fatal(err)
}
}
r := m.Run()
if *screen != nil {
(*screen).Fini()
}
if r != 0 && *screen == nil {
log.Printf("To update golden files, run with env variable RTY_INTERACTIVE=1 and hit y/n on each case to overwrite (or not)")
}
os.Exit(r)
}