summaryrefslogtreecommitdiff
path: root/src/pkg/exp/ssh/server_shell_test.go
blob: 622cf7cfada59f2162394df72805de6097cb6027 (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
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
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ssh

import (
	"testing"
	"os"
)

type MockChannel struct {
	toSend       []byte
	bytesPerRead int
	received     []byte
}

func (c *MockChannel) Accept() os.Error {
	return nil
}

func (c *MockChannel) Reject(RejectionReason, string) os.Error {
	return nil
}

func (c *MockChannel) Read(data []byte) (n int, err os.Error) {
	n = len(data)
	if n == 0 {
		return
	}
	if n > len(c.toSend) {
		n = len(c.toSend)
	}
	if n == 0 {
		return 0, os.EOF
	}
	if c.bytesPerRead > 0 && n > c.bytesPerRead {
		n = c.bytesPerRead
	}
	copy(data, c.toSend[:n])
	c.toSend = c.toSend[n:]
	return
}

func (c *MockChannel) Write(data []byte) (n int, err os.Error) {
	c.received = append(c.received, data...)
	return len(data), nil
}

func (c *MockChannel) Close() os.Error {
	return nil
}

func (c *MockChannel) AckRequest(ok bool) os.Error {
	return nil
}

func (c *MockChannel) ChannelType() string {
	return ""
}

func (c *MockChannel) ExtraData() []byte {
	return nil
}

func TestClose(t *testing.T) {
	c := &MockChannel{}
	ss := NewServerShell(c, "> ")
	line, err := ss.ReadLine()
	if line != "" {
		t.Errorf("Expected empty line but got: %s", line)
	}
	if err != os.EOF {
		t.Errorf("Error should have been EOF but got: %s", err)
	}
}

var keyPressTests = []struct {
	in   string
	line string
	err  os.Error
}{
	{
		"",
		"",
		os.EOF,
	},
	{
		"\r",
		"",
		nil,
	},
	{
		"foo\r",
		"foo",
		nil,
	},
	{
		"a\x1b[Cb\r", // right
		"ab",
		nil,
	},
	{
		"a\x1b[Db\r", // left
		"ba",
		nil,
	},
	{
		"a\177b\r", // backspace
		"b",
		nil,
	},
}

func TestKeyPresses(t *testing.T) {
	for i, test := range keyPressTests {
		for j := 0; j < len(test.in); j++ {
			c := &MockChannel{
				toSend:       []byte(test.in),
				bytesPerRead: j,
			}
			ss := NewServerShell(c, "> ")
			line, err := ss.ReadLine()
			if line != test.line {
				t.Errorf("Line resulting from test %d (%d bytes per read) was '%s', expected '%s'", i, j, line, test.line)
				break
			}
			if err != test.err {
				t.Errorf("Error resulting from test %d (%d bytes per read) was '%v', expected '%v'", i, j, err, test.err)
				break
			}
		}
	}
}