Debian Codegraph @

terminal_test.go

raw
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package term
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "io"
12 "os"
13 "runtime"
14 "testing"
15 )
16
17 type MockTerminal struct {
18 toSend []byte
19 bytesPerRead int
20 received []byte
21 }
22
23 func (c *MockTerminal) Read(data []byte) (n int, err error) {
24 n = len(data)
25 if n == 0 {
26 return
27 }
28 if n > len(c.toSend) {
29 n = len(c.toSend)
30 }
31 if n == 0 {
32 return 0, io.EOF
33 }
34 if c.bytesPerRead > 0 && n > c.bytesPerRead {
35 n = c.bytesPerRead
36 }
37 copy(data, c.toSend[:n])
38 c.toSend = c.toSend[n:]
39 return
40 }
41
42 func (c *MockTerminal) Write(data []byte) (n int, err error) {
43 c.received = append(c.received, data...)
44 return len(data), nil
45 }
46
47 func TestClose(t *testing.T) {
48 c := &MockTerminal{}
49 ss := NewTerminal(c, "> ")
50 line, err := ss.ReadLine()
51 if line != "" {
52 t.Errorf("Expected empty line but got: %s", line)
53 }
54 if err != io.EOF {
55 t.Errorf("Error should have been EOF but got: %s", err)
56 }
57 }
58
59 var keyPressTests = []struct {
60 in string
61 line string
62 err error
63 throwAwayLines int
64 }{
65 {
66 err: io.EOF,
67 },
68 {
69 in: "\r",
70 line: "",
71 },
72 {
73 in: "foo\r",
74 line: "foo",
75 },
76 {
77 in: "a\x1b[Cb\r", // right
78 line: "ab",
79 },
80 {
81 in: "a\x1b[Db\r", // left
82 line: "ba",
83 },
84 {
85 in: "a\006b\r", // ^F
86 line: "ab",
87 },
88 {
89 in: "a\002b\r", // ^B
90 line: "ba",
91 },
92 {
93 in: "a\177b\r", // backspace
94 line: "b",
95 },
96 {
97 in: "\x1b[A\r", // up
98 },
99 {
100 in: "\x1b[B\r", // down
101 },
102 {
103 in: "\016\r", // ^P
104 },
105 {
106 in: "\014\r", // ^N
107 },
108 {
109 in: "line\x1b[A\x1b[B\r", // up then down
110 line: "line",
111 },
112 {
113 in: "line1\rline2\x1b[A\r", // recall previous line.
114 line: "line1",
115 throwAwayLines: 1,
116 },
117 {
118 // recall two previous lines and append.
119 in: "line1\rline2\rline3\x1b[A\x1b[Axxx\r",
120 line: "line1xxx",
121 throwAwayLines: 2,
122 },
123 {
124 // Ctrl-A to move to beginning of line followed by ^K to kill
125 // line.
126 in: "a b \001\013\r",
127 line: "",
128 },
129 {
130 // Ctrl-A to move to beginning of line, Ctrl-E to move to end,
131 // finally ^K to kill nothing.
132 in: "a b \001\005\013\r",
133 line: "a b ",
134 },
135 {
136 in: "\027\r",
137 line: "",
138 },
139 {
140 in: "a\027\r",
141 line: "",
142 },
143 {
144 in: "a \027\r",
145 line: "",
146 },
147 {
148 in: "a b\027\r",
149 line: "a ",
150 },
151 {
152 in: "a b \027\r",
153 line: "a ",
154 },
155 {
156 in: "one two thr\x1b[D\027\r",
157 line: "one two r",
158 },
159 {
160 in: "\013\r",
161 line: "",
162 },
163 {
164 in: "a\013\r",
165 line: "a",
166 },
167 {
168 in: "ab\x1b[D\013\r",
169 line: "a",
170 },
171 {
172 in: "Ξεσκεπάζω\r",
173 line: "Ξεσκεπάζω",
174 },
175 {
176 in: "£\r\x1b[A\177\r", // non-ASCII char, enter, up, backspace.
177 line: "",
178 throwAwayLines: 1,
179 },
180 {
181 in: "£\r££\x1b[A\x1b[B\177\r", // non-ASCII char, enter, 2x non-ASCII, up, down, backspace, enter.
182 line: "£",
183 throwAwayLines: 1,
184 },
185 {
186 // Ctrl-D at the end of the line should be ignored.
187 in: "a\004\r",
188 line: "a",
189 },
190 {
191 // a, b, left, Ctrl-D should erase the b.
192 in: "ab\x1b[D\004\r",
193 line: "a",
194 },
195 {
196 // a, b, c, d, left, left, ^U should erase to the beginning of
197 // the line.
198 in: "abcd\x1b[D\x1b[D\025\r",
199 line: "cd",
200 },
201 {
202 // Bracketed paste mode: control sequences should be returned
203 // verbatim in paste mode.
204 in: "abc\x1b[200~de\177f\x1b[201~\177\r",
205 line: "abcde\177",
206 },
207 {
208 // Enter in bracketed paste mode should still work.
209 in: "abc\x1b[200~d\refg\x1b[201~h\r",
210 line: "efgh",
211 throwAwayLines: 1,
212 },
213 {
214 // Newline in bracketed paste mode should still work.
215 in: "abc\x1b[200~d\nefg\x1b[201~h\r",
216 line: "efgh",
217 throwAwayLines: 1,
218 },
219 {
220 // Lines consisting entirely of pasted data should be indicated as such.
221 in: "\x1b[200~a\r",
222 line: "a",
223 err: ErrPasteIndicator,
224 },
225 {
226 // Lines consisting entirely of pasted data should be indicated as such (\n paste).
227 in: "\x1b[200~a\n",
228 line: "a",
229 err: ErrPasteIndicator,
230 },
231 {
232 // Ctrl-C terminates readline
233 in: "\003",
234 err: io.EOF,
235 },
236 {
237 // Ctrl-C at the end of line also terminates readline
238 in: "a\003\r",
239 err: io.EOF,
240 },
241 {
242 // Delete at EOL: nothing
243 in: "abc\x1b[3~\r",
244 line: "abc",
245 },
246 {
247 // Delete in empty string: nothing
248 in: "\x1b[3~\r",
249 line: "",
250 },
251 {
252 // Move left, delete: delete 'c'
253 in: "abc\x1b[D\x1b[3~\r",
254 line: "ab",
255 },
256 {
257 // Home, delete: delete 'a'
258 in: "abc\x1b[H\x1b[3~\r",
259 line: "bc",
260 },
261 {
262 // Home, delete twice: delete 'a' and 'b'
263 in: "abc\x1b[H\x1b[3~\x1b[3~\r",
264 line: "c",
265 },
266 {
267 // Ctrl-T at end of line: transpose last two chars
268 in: "abc\x14\r",
269 line: "acb",
270 },
271 {
272 // Ctrl-T at end then type: cursor stays at end
273 in: "abc\x14N\r",
274 line: "acbN",
275 },
276 {
277 // Ctrl-T in middle: transpose chars before cursor, move cursor forward
278 in: "abc\x1b[D\x14\r",
279 line: "acb",
280 },
281 {
282 // Ctrl-T in middle then type: cursor moved past swapped char
283 in: "abcd\x1b[D\x1b[D\x14N\r",
284 line: "acbNd",
285 },
286 {
287 // Ctrl-T at pos 1 then type: cursor moves to pos 2
288 in: "abc\x1b[H\x1b[C\x14N\r",
289 line: "baNc",
290 },
291 {
292 // Ctrl-T with one char: do nothing
293 in: "a\x14\r",
294 line: "a",
295 },
296 {
297 // Ctrl-T with one char then type: cursor unchanged
298 in: "a\x14N\r",
299 line: "aN",
300 },
301 {
302 // Ctrl-T at beginning: do nothing
303 in: "ab\x1b[H\x14\r",
304 line: "ab",
305 },
306 {
307 // Ctrl-T at beginning then type: cursor unchanged, inserts at start
308 in: "ab\x1b[H\x14N\r",
309 line: "Nab",
310 },
311 {
312 // Ctrl-T on empty line: do nothing
313 in: "\x14\r",
314 line: "",
315 },
316 {
317 // Multiple Ctrl-T at end: keeps swapping last two
318 in: "abc\x14\x14\r",
319 line: "abc",
320 },
321 {
322 // Multiple Ctrl-T in middle: progresses through line
323 in: "abcd\x1b[D\x1b[D\x1b[D\x14\x14\x14\r",
324 line: "bcda",
325 },
326 }
327
328 func TestKeyPresses(t *testing.T) {
329 for i, test := range keyPressTests {
330 for j := 1; j < len(test.in); j++ {
331 c := &MockTerminal{
332 toSend: []byte(test.in),
333 bytesPerRead: j,
334 }
335 ss := NewTerminal(c, "> ")
336 for k := 0; k < test.throwAwayLines; k++ {
337 _, err := ss.ReadLine()
338 if err != nil {
339 t.Errorf("Throwaway line %d from test %d resulted in error: %s", k, i, err)
340 }
341 }
342 line, err := ss.ReadLine()
343 if line != test.line {
344 t.Errorf("Line resulting from test %d (%d bytes per read) was '%s', expected '%s'", i, j, line, test.line)
345 break
346 }
347 if err != test.err {
348 t.Errorf("Error resulting from test %d (%d bytes per read) was '%v', expected '%v'", i, j, err, test.err)
349 break
350 }
351 }
352 }
353 }
354
355 var renderTests = []struct {
356 in string
357 received string
358 err error
359 }{
360 {
361 // Cursor move after keyHome (left 4) then enter (right 4, newline)
362 in: "abcd\x1b[H\r",
363 received: "> abcd\x1b[4D\x1b[4C\r\n",
364 },
365 {
366 // Write, home, prepend, enter. Prepends rewrites the line.
367 in: "cdef\x1b[Hab\r",
368 received: "> cdef" + // Initial input
369 "\x1b[4Da" + // Move cursor back, insert first char
370 "cdef" + // Copy over original string
371 "\x1b[4Dbcdef" + // Repeat for second char with copy
372 "\x1b[4D" + // Put cursor back in position to insert again
373 "\x1b[4C\r\n", // Put cursor at the end of the line and newline.
374 },
375 }
376
377 func TestRender(t *testing.T) {
378 for i, test := range renderTests {
379 for j := 1; j < len(test.in); j++ {
380 c := &MockTerminal{
381 toSend: []byte(test.in),
382 bytesPerRead: j,
383 }
384 ss := NewTerminal(c, "> ")
385 _, err := ss.ReadLine()
386 if err != test.err {
387 t.Errorf("Error resulting from test %d (%d bytes per read) was '%v', expected '%v'", i, j, err, test.err)
388 break
389 }
390 if test.received != string(c.received) {
391 t.Errorf("Results rendered from test %d (%d bytes per read) was '%s', expected '%s'", i, j, c.received, test.received)
392 break
393 }
394 }
395 }
396 }
397
398 func TestCRLF(t *testing.T) {
399 c := &MockTerminal{
400 toSend: []byte("line1\rline2\r\nline3\n"),
401 // bytesPerRead 0 in this test means read all at once
402 // CR+LF need to be in same read for ReadLine to not produce an extra empty line
403 // which is what terminals do for reasonably small paste. if way many lines are pasted
404 // and going over say 1k-16k buffer, readline current implementation will possibly generate 1
405 // extra empty line, if the CR is in chunk1 and LF in chunk2 (and that's fine).
406 }
407
408 ss := NewTerminal(c, "> ")
409 for i := range 3 {
410 line, err := ss.ReadLine()
411 if err != nil {
412 t.Fatalf("failed to read line %d: %v", i+1, err)
413 }
414 expected := fmt.Sprintf("line%d", i+1)
415 if line != expected {
416 t.Fatalf("expected '%s', got '%s'", expected, line)
417 }
418 }
419 line, err := ss.ReadLine()
420 if !errors.Is(err, io.EOF) {
421 t.Fatalf("expected EOF after 3 lines, got '%s' with error %v", line, err)
422 }
423 if line != "" {
424 t.Fatalf("expected empty line after EOF, got '%s'", line)
425 }
426 }
427
428 func TestPasswordNotSaved(t *testing.T) {
429 c := &MockTerminal{
430 toSend: []byte("password\r\x1b[A\r"),
431 bytesPerRead: 1,
432 }
433 ss := NewTerminal(c, "> ")
434 pw, _ := ss.ReadPassword("> ")
435 if pw != "password" {
436 t.Fatalf("failed to read password, got %s", pw)
437 }
438 line, _ := ss.ReadLine()
439 if len(line) > 0 {
440 t.Fatalf("password was saved in history")
441 }
442 }
443
444 var setSizeTests = []struct {
445 width, height int
446 }{
447 {40, 13},
448 {80, 24},
449 {132, 43},
450 }
451
452 func TestTerminalSetSize(t *testing.T) {
453 for _, setSize := range setSizeTests {
454 c := &MockTerminal{
455 toSend: []byte("password\r\x1b[A\r"),
456 bytesPerRead: 1,
457 }
458 ss := NewTerminal(c, "> ")
459 ss.SetSize(setSize.width, setSize.height)
460 pw, _ := ss.ReadPassword("Password: ")
461 if pw != "password" {
462 t.Fatalf("failed to read password, got %s", pw)
463 }
464 if string(c.received) != "Password: \r\n" {
465 t.Errorf("failed to set the temporary prompt expected %q, got %q", "Password: ", c.received)
466 }
467 }
468 }
469
470 func TestReadPasswordLineEnd(t *testing.T) {
471 type testType struct {
472 input string
473 want string
474 }
475 tests := []testType{
476 {"\r\n", ""},
477 {"test\r\n", "test"},
478 {"test\r", "test"},
479 {"test\n", "test"},
480 {"testtesttesttes\n", "testtesttesttes"},
481 {"testtesttesttes\r\n", "testtesttesttes"},
482 {"testtesttesttesttest\n", "testtesttesttesttest"},
483 {"testtesttesttesttest\r\n", "testtesttesttesttest"},
484 {"\btest", "test"},
485 {"t\best", "est"},
486 {"te\bst", "tst"},
487 {"test\b", "tes"},
488 {"test\b\r\n", "tes"},
489 {"test\b\n", "tes"},
490 {"test\b\r", "tes"},
491 }
492 eol := "\n"
493 if runtime.GOOS == "windows" {
494 eol = "\r"
495 }
496 tests = append(tests, testType{eol, ""})
497 for _, test := range tests {
498 buf := new(bytes.Buffer)
499 if _, err := buf.WriteString(test.input); err != nil {
500 t.Fatal(err)
501 }
502
503 have, err := readPasswordLine(buf)
504 if err != nil {
505 t.Errorf("readPasswordLine(%q) failed: %v", test.input, err)
506 continue
507 }
508 if string(have) != test.want {
509 t.Errorf("readPasswordLine(%q) returns %q, but %q is expected", test.input, string(have), test.want)
510 continue
511 }
512
513 if _, err = buf.WriteString(test.input); err != nil {
514 t.Fatal(err)
515 }
516 have, err = readPasswordLine(buf)
517 if err != nil {
518 t.Errorf("readPasswordLine(%q) failed: %v", test.input, err)
519 continue
520 }
521 if string(have) != test.want {
522 t.Errorf("readPasswordLine(%q) returns %q, but %q is expected", test.input, string(have), test.want)
523 continue
524 }
525 }
526 }
527
528 func MockAutoCompleteCallback(line string, pos int, key rune) (newLine string, newPos int, ok bool) {
529 return "not-good", pos, true
530 }
531
532 func TestReadPasswordDisabledAutoCompleteCallback(t *testing.T) {
533 input := "testgood\ranother line\r"
534 expectedPassword := "testgood"
535 terminal := NewTerminal(
536 &MockTerminal{
537 toSend: []byte(input),
538 bytesPerRead: 1,
539 },
540 "prompt")
541 terminal.AutoCompleteCallback = MockAutoCompleteCallback
542 password, err := terminal.ReadPassword("Password: ")
543 if err != nil {
544 t.Fatalf("failed to read password: %v", err)
545 }
546 if password != expectedPassword {
547 t.Fatalf("failed to read password, got %q", password)
548 }
549 if terminal.AutoCompleteCallback == nil {
550 t.Fatalf("AutoCompleteCallback should not be nil after ReadPassword")
551 }
552 }
553
554 func TestMakeRawState(t *testing.T) {
555 fd := int(os.Stdout.Fd())
556 if !IsTerminal(fd) {
557 t.Skip("stdout is not a terminal; skipping test")
558 }
559
560 st, err := GetState(fd)
561 if err != nil {
562 t.Fatalf("failed to get terminal state from GetState: %s", err)
563 }
564
565 if runtime.GOOS == "ios" {
566 t.Skip("MakeRaw not allowed on iOS; skipping test")
567 }
568
569 defer Restore(fd, st)
570 raw, err := MakeRaw(fd)
571 if err != nil {
572 t.Fatalf("failed to get terminal state from MakeRaw: %s", err)
573 }
574
575 if *st != *raw {
576 t.Errorf("states do not match; was %v, expected %v", raw, st)
577 }
578 }
579
580 func TestOutputNewlines(t *testing.T) {
581 // \n should be changed to \r\n in terminal output.
582 buf := new(bytes.Buffer)
583 term := NewTerminal(buf, ">")
584
585 term.Write([]byte("1\n2\n"))
586 output := buf.String()
587 const expected = "1\r\n2\r\n"
588
589 if output != expected {
590 t.Errorf("incorrect output: was %q, expected %q", output, expected)
591 }
592 }