github.com/ladydascalie/elvish@v0.0.0-20170703214355-2964dd3ece7f/edit/tty/reader_test.go (about) 1 package tty 2 3 import ( 4 "os" 5 "testing" 6 "time" 7 8 "github.com/elves/elvish/edit/ui" 9 ) 10 11 // timeout is the longest time the tests wait between writing something on 12 // the writer and reading it from the reader before declaring that the 13 // reader has a bug. 14 const timeoutInterval = 100 * time.Millisecond 15 16 func timeout() <-chan time.Time { 17 return time.After(timeoutInterval) 18 } 19 20 var ( 21 writer *os.File 22 reader *Reader 23 ) 24 25 func TestMain(m *testing.M) { 26 r, w, err := os.Pipe() 27 if err != nil { 28 panic("os.Pipe returned error, something is seriously wrong") 29 } 30 defer r.Close() 31 defer w.Close() 32 writer = w 33 reader = NewReader(r) 34 go reader.Run() 35 defer reader.Quit() 36 37 os.Exit(m.Run()) 38 } 39 40 var keyTests = []struct { 41 input string 42 want ReadUnit 43 }{ 44 // Simple graphical key. 45 {"x", Key{'x', 0}}, 46 {"X", Key{'X', 0}}, 47 {" ", Key{' ', 0}}, 48 49 // Ctrl key. 50 {"\001", Key{'A', ui.Ctrl}}, 51 {"\033", Key{'[', ui.Ctrl}}, 52 53 // Ctrl-ish keys, but not thought as Ctrl keys by our reader. 54 {"\n", Key{'\n', 0}}, 55 {"\t", Key{'\t', 0}}, 56 {"\x7f", Key{'\x7f', 0}}, // backspace 57 58 // Alt plus simple graphical key. 59 {"\033a", Key{'a', ui.Alt}}, 60 {"\033[", Key{'[', ui.Alt}}, 61 62 // G3-style key. 63 {"\033OA", Key{ui.Up, 0}}, 64 {"\033OH", Key{ui.Home, 0}}, 65 66 // CSI-sequence key identified by the ending rune. 67 {"\033[A", Key{ui.Up, 0}}, 68 {"\033[H", Key{ui.Home, 0}}, 69 // Test for all possible modifier 70 {"\033[1;2A", Key{ui.Up, ui.Shift}}, 71 72 // CSI-sequence key with one argument, always ending in '~'. 73 {"\033[1~", Key{ui.Home, 0}}, 74 {"\033[11~", Key{ui.F1, 0}}, 75 76 // CSI-sequence key with three arguments and ending in '~'. The first 77 // argument is always 27, the second identifies the modifier and the last 78 // identifies the key. 79 {"\033[27;4;63~", Key{';', ui.Shift | ui.Alt}}, 80 } 81 82 func TestKey(t *testing.T) { 83 for _, test := range keyTests { 84 writer.WriteString(test.input) 85 select { 86 case k := <-reader.UnitChan(): 87 if k != test.want { 88 t.Errorf("Reader reads key %v, want %v", k, test.want) 89 } 90 case <-timeout(): 91 t.Errorf("Reader fails to convert literal key") 92 } 93 } 94 }