This repository has been archived by the owner on Aug 1, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlayer_test.go
346 lines (315 loc) · 10.1 KB
/
layer_test.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
package rafthttp_test
import (
"bufio"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/CanonicalLtd/raft-http"
"github.com/hashicorp/raft"
)
// The Accept method receives connections from the conns channel.
func TestLayer_Accept(t *testing.T) {
handler, layer := newHandlerAndLayer(t)
server, client := net.Pipe()
go func() {
w := newResponseHijacker()
w.HijackConn = server
r := &http.Request{Method: "GET", Header: make(http.Header)}
r.Header.Set("Upgrade", "raft")
handler.ServeHTTP(w, r)
}()
reader := bufio.NewReader(client)
reader.ReadString('\n')
got, err := layer.Accept()
if err != nil {
t.Fatal(err)
}
if got != server {
t.Fatal("Accept() didn't receive the connection through the conns channel")
}
}
// The Accept method returns an error if the layer was closed.
func TestLayer_AcceptWhenClosed(t *testing.T) {
layer := newLayer(t)
layer.Close()
conn, err := layer.Accept()
if conn != nil {
t.Fatal("Expected nil connection")
}
if err != io.EOF {
t.Fatal("Expected EOF error")
}
}
// The Close method is a no-op.
func TestLayer_Close(t *testing.T) {
layer := newLayer(t)
if err := layer.Close(); err != nil {
t.Fatal(err)
}
}
// The Addr method return the local address.
func TestLayer_Addr(t *testing.T) {
listener, err := net.Listen("tcp", ":0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
addr := listener.Addr()
layer := newLayerWithAddr(t, addr)
if layer.Addr() != addr {
t.Fatal("Addr() did not return the configured address")
}
}
// If the given HTTP path is invalid, an error is returned.
func TestLayer_DialPathParseError(t *testing.T) {
layer := newLayerWithPath(t, "%:not\a/path")
want := "invalid URL path %:not\a/path"
defer func() {
if got := recover(); got != want {
t.Fatalf("Invalid path did not panic as expected: %s (should be %s)", got, want)
}
}()
layer.Dial(":0", time.Second)
}
// If the Dial function returns an error when trying to connect, it
// gets propagated.
func TestLayer_DialDialError(t *testing.T) {
dial := func(string, time.Duration) (net.Conn, error) {
return nil, fmt.Errorf("connection error")
}
layer := newLayerWithDial(t, dial)
conn, err := layer.Dial(":0", time.Second)
if conn != nil {
t.Fatal("expected nil conn")
}
if err == nil {
t.Fatal("expected error")
}
const want = "dialing failed: connection error"
got := err.Error()
if want != got {
t.Fatalf("expected error\n%q\ngot\n%q", want, got)
}
}
// If an error occurs while writing the HTTP request, it is returned.
func TestLayer_DialRequestWriteError(t *testing.T) {
dial := func(string, time.Duration) (net.Conn, error) {
conn, _ := net.Pipe()
conn.Close() // This will trigger a write error
return conn, nil
}
layer := newLayerWithDial(t, dial)
conn, err := layer.Dial(":0", time.Second)
if conn != nil {
t.Fatal("expected nil conn")
}
if err == nil {
t.Fatal("expected error")
}
const want = "sending HTTP request failed: io: read/write on closed pipe"
got := err.Error()
if want != got {
t.Fatalf("expected error error\n%q\ngot\n%q", want, got)
}
}
// If the response sent by the server has not code 101, an error is
// returned.
func TestLayer_DialResponseWrongStatusCode(t *testing.T) {
server, client := net.Pipe()
dial := func(string, time.Duration) (net.Conn, error) {
return client, nil
}
layer := newLayerWithDial(t, dial)
go func() {
// Read a line from the request data written by the
// layer via the client conn. This unblocks reading
// the response
buffer := bufio.NewReader(server)
_, _, err := buffer.ReadLine()
if err != nil {
t.Fatalf("Failed to read client request: %v", err)
}
// Send a malformed response to the client.
server.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
}()
conn, err := layer.Dial(":0", time.Second)
if conn != nil {
t.Fatal("Dial() returned a non-nil connection")
}
if err == nil {
t.Fatal("Dial() didn't return any error")
}
if err.Error() != "dialing fail: expected status code 101 got 200" {
t.Fatalf("Dial() returned unexpected error: %v", err)
}
}
// If an error occurs while reading the HTTP request, it is returned.
func TestLayer_DialResponseReadError(t *testing.T) {
server, client := net.Pipe()
dial := func(string, time.Duration) (net.Conn, error) {
return client, nil
}
layer := newLayerWithDial(t, dial)
go func() {
// Read a line from the request data written by the
// layer via the client conn. This unblocks reading
// the response
buffer := bufio.NewReader(server)
_, _, err := buffer.ReadLine()
if err != nil {
t.Fatalf("Failed to read client request: %v", err)
}
// Send a malformed response to the client.
server.Write([]byte("garbage\n"))
}()
conn, err := layer.Dial("127.0.0.1:0", time.Second)
if conn != nil {
t.Fatal("expected nil conn")
}
if err == nil {
t.Fatal("expected error")
}
const want = `failed to read response: malformed HTTP response "garbage"`
got := err.Error()
if want != got {
t.Fatalf("expected error\n%q\ngot\n%q", want, got)
}
}
// If the response sent by the server has not an Upgrade header set to
// "raft", an error is returned.
func TestLayer_DialResponseNoUpgradeHeader(t *testing.T) {
server, client := net.Pipe()
dial := func(string, time.Duration) (net.Conn, error) {
return client, nil
}
layer := newLayerWithDial(t, dial)
go func() {
// Read a line from the request data written by the
// layer via the client conn. This unblocks reading
// the response
buffer := bufio.NewReader(server)
_, _, err := buffer.ReadLine()
if err != nil {
t.Fatalf("Failed to read client request: %v", err)
}
// Send a malformed response to the client.
server.Write([]byte("HTTP/1.1 101 Switching Protocols\r\n\r\n"))
}()
conn, err := layer.Dial(":0", time.Second)
if conn != nil {
t.Fatal("Dial() returned a non-nil connection")
}
if err == nil {
t.Fatal("Dial() didn't return any error")
}
if err.Error() != "missing or unexpected Upgrade header in response" {
t.Fatalf("Dial() returned unexpected error: %v", err)
}
}
// If the HTTP request to join a cluster returns an unexpected status
// code, an error is returned.
func TestLayer_JoinErrorStatusCode(t *testing.T) {
// Setup a handler that always returns 404.
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
}))
defer server.Close()
addr := server.Listener.Addr()
layer := newLayerWithAddrAndDial(t, addr, rafthttp.NewDialTCP())
err := layer.Join("1", raftAddress(addr), time.Second)
if err == nil {
t.Fatal("Join call did not fail")
}
if err.Error() != fmt.Sprintf("server join failed: http code 404 '404 page not found'") {
t.Fatalf("Got unexpected error: %v", err)
}
}
// If there's a network failure while leaving, an error is returned.
func TestLayer_LeaveNetworkError(t *testing.T) {
addr := &net.TCPAddr{IP: []byte{0, 0, 0, 0}, Port: 0}
layer := newLayerWithAddrAndDial(t, addr, rafthttp.NewDialTCP())
err := layer.Leave("1", raftAddress(addr), time.Second)
if err == nil {
t.Fatal("Leave call did not fail")
}
}
// If there's a network failure while joining, an error is returned.
func TestLayer_JoinNetworkError(t *testing.T) {
addr := &net.TCPAddr{IP: []byte{0, 0, 0, 0}, Port: 0}
layer := newLayerWithAddrAndDial(t, addr, rafthttp.NewDialTCP())
err := layer.Join("1", raftAddress(addr), time.Second)
if err == nil {
t.Fatal("Join call did not fail")
}
}
// If the URL in the Location header of a redirect is not valid, an
// error is returned.
func TestLayer_JoinLocationParseError(t *testing.T) {
// Setup a handler that returns an invalid Location.
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, ":/%:not\a/url", http.StatusPermanentRedirect)
}))
defer server.Close()
addr := server.Listener.Addr()
layer := newLayerWithAddrAndDial(t, addr, rafthttp.NewDialTCP())
if err := layer.Join("1", raftAddress(addr), time.Second); err == nil {
t.Fatal("Join call did not fail")
}
}
func TestLayer_JoinRetryIfServiceUnavailable(t *testing.T) {
// Setup a handler that fails only the first time.
retried := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !retried {
http.Error(w, "leader unknown", http.StatusServiceUnavailable)
retried = true
}
}))
defer server.Close()
addr := server.Listener.Addr()
layer := newLayerWithAddrAndDial(t, addr, rafthttp.NewDialTCP())
if err := layer.Join("1", raftAddress(addr), time.Second); err != nil {
t.Fatalf("Join request failed although it was supposed to retry: %v", err)
}
}
// Create both a new Handler and a new Layer, with sane defaults.
func newHandlerAndLayer(t *testing.T) (*rafthttp.Handler, *rafthttp.Layer) {
handler := newHandler(t)
layer := rafthttp.NewLayerWithLogger("/", newAddr(), handler, nil, newLogger(t))
return handler, layer
}
// Create a new Layer, with sane defaults.
func newLayer(t *testing.T) *rafthttp.Layer {
return rafthttp.NewLayerWithLogger("/", newAddr(), newHandler(t), nil, newLogger(t))
}
// Create a new Layer, with the given address.
func newLayerWithAddr(t *testing.T, addr net.Addr) *rafthttp.Layer {
return rafthttp.NewLayerWithLogger("/", addr, newHandler(t), nil, newLogger(t))
}
// Create a new Layer, with the given path.
func newLayerWithPath(t *testing.T, path string) *rafthttp.Layer {
return rafthttp.NewLayerWithLogger(path, newAddr(), newHandler(t), nil, newLogger(t))
}
// Create a new Layer, with the given dial function.
func newLayerWithDial(t *testing.T, dial rafthttp.Dial) *rafthttp.Layer {
return rafthttp.NewLayerWithLogger("/", newAddr(), newHandler(t), dial, newLogger(t))
}
// Create a new Layer, with the given address and dial function.
func newLayerWithAddrAndDial(t *testing.T, addr net.Addr, dial rafthttp.Dial) *rafthttp.Layer {
return rafthttp.NewLayerWithLogger("/", addr, newHandler(t), dial, newLogger(t))
}
// Create a new test network address.
func newAddr() net.Addr {
return &net.TCPAddr{
IP: net.IPv4(127, 0, 0, 1),
Port: 1234,
}
}
// Covert a net.Addr to raft.ServerAddress
func raftAddress(addr net.Addr) raft.ServerAddress {
return raft.ServerAddress(addr.String())
}