terminal_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. package terminal
  5. import (
  6. "io"
  7. "testing"
  8. )
  9. type MockTerminal struct {
  10. toSend []byte
  11. bytesPerRead int
  12. received []byte
  13. }
  14. func (c *MockTerminal) Read(data []byte) (n int, err error) {
  15. n = len(data)
  16. if n == 0 {
  17. return
  18. }
  19. if n > len(c.toSend) {
  20. n = len(c.toSend)
  21. }
  22. if n == 0 {
  23. return 0, io.EOF
  24. }
  25. if c.bytesPerRead > 0 && n > c.bytesPerRead {
  26. n = c.bytesPerRead
  27. }
  28. copy(data, c.toSend[:n])
  29. c.toSend = c.toSend[n:]
  30. return
  31. }
  32. func (c *MockTerminal) Write(data []byte) (n int, err error) {
  33. c.received = append(c.received, data...)
  34. return len(data), nil
  35. }
  36. func TestClose(t *testing.T) {
  37. c := &MockTerminal{}
  38. ss := NewTerminal(c, "> ")
  39. line, err := ss.ReadLine()
  40. if line != "" {
  41. t.Errorf("Expected empty line but got: %s", line)
  42. }
  43. if err != io.EOF {
  44. t.Errorf("Error should have been EOF but got: %s", err)
  45. }
  46. }
  47. var keyPressTests = []struct {
  48. in string
  49. line string
  50. err error
  51. }{
  52. {
  53. "",
  54. "",
  55. io.EOF,
  56. },
  57. {
  58. "\r",
  59. "",
  60. nil,
  61. },
  62. {
  63. "foo\r",
  64. "foo",
  65. nil,
  66. },
  67. {
  68. "a\x1b[Cb\r", // right
  69. "ab",
  70. nil,
  71. },
  72. {
  73. "a\x1b[Db\r", // left
  74. "ba",
  75. nil,
  76. },
  77. {
  78. "a\177b\r", // backspace
  79. "b",
  80. nil,
  81. },
  82. }
  83. func TestKeyPresses(t *testing.T) {
  84. for i, test := range keyPressTests {
  85. for j := 0; j < len(test.in); j++ {
  86. c := &MockTerminal{
  87. toSend: []byte(test.in),
  88. bytesPerRead: j,
  89. }
  90. ss := NewTerminal(c, "> ")
  91. line, err := ss.ReadLine()
  92. if line != test.line {
  93. t.Errorf("Line resulting from test %d (%d bytes per read) was '%s', expected '%s'", i, j, line, test.line)
  94. break
  95. }
  96. if err != test.err {
  97. t.Errorf("Error resulting from test %d (%d bytes per read) was '%v', expected '%v'", i, j, err, test.err)
  98. break
  99. }
  100. }
  101. }
  102. }