-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_test.go
795 lines (674 loc) · 18.2 KB
/
client_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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
package mp
import (
"bytes"
"io"
"sync"
"sync/atomic"
"testing"
)
// -----------------------------------------------------------------------------
// Utilities for testing
// -----------------------------------------------------------------------------
type callbackTranslator struct {
ReadCallback func() (*Message, error)
WriteCallback func(*Message) error
}
func (c *callbackTranslator) ReadMessage() (*Message, error) {
return c.ReadCallback()
}
func (c *callbackTranslator) WriteMessage(m *Message) error {
return c.WriteCallback(m)
}
type channelTranslator struct {
incoming, outgoing chan *Message
closed chan struct{}
isClosed uint32
}
func newChannelTranslator() *channelTranslator {
// Incoming can't be buffered because race -- take the following
// code:
// ct := newChannelTranslator()
// go readFromCTIncoming(ct)
// ct.incoming <- nil
// ct.Close()
//
// ...If ct.incoming doesn't block before nil is passed off, then
// it's unspecified whether or not the nil will ever be received.
// (In my implementation of Go [v1.3], nil is never received).
return &channelTranslator{
incoming: make(chan *Message),
outgoing: make(chan *Message),
closed: make(chan struct{}),
}
}
func (c *channelTranslator) Close() error {
if atomic.CompareAndSwapUint32(&c.isClosed, 0, 1) {
close(c.closed)
}
return nil
}
func (c *channelTranslator) ReadMessage() (*Message, error) {
select {
case m := <-c.incoming:
return m, nil
case <-c.closed:
return nil, io.EOF
}
// compat with Go 1.0
panic(unreachableCode)
}
func (c *channelTranslator) WriteMessage(m *Message) error {
select {
case c.outgoing <- m:
return nil
case <-c.closed:
return io.EOF
}
// compat with Go 1.0
panic(unreachableCode)
}
// Because all Client reads/writes go through the MessageTranslator we give it,
// most of the time we don't even need a ReadWriteCloser.
type nopRWC struct{}
func (*nopRWC) Read([]byte) (n int, err error) {
return 0, io.EOF
}
func (*nopRWC) Write([]byte) (n int, err error) {
return 0, io.EOF
}
func (*nopRWC) Close() error {
return nil
}
type callbackConnectionHandler struct {
Callback func(string, func() Connection)
}
func (h *callbackConnectionHandler) IncomingConnection(s string, c func() Connection) {
h.Callback(s, c)
}
func singletonTranslator(t MessageTranslator) TranslatorMaker {
return func(io.Reader, io.Writer) MessageTranslator {
return t
}
}
// -----------------------------------------------------------------------------
// clientConnection testing
// -----------------------------------------------------------------------------
var _ Connection = (*clientConnection)(nil)
func TestClientConnectionWritesMessageDirectlyToClient(t *testing.T) {
msg := []byte("Hello, World!")
numWriteCalls := 0
ct := callbackTranslator{
ReadCallback: func() (*Message, error) {
t.Error("Read function was called.")
return nil, io.EOF
},
WriteCallback: func(m *Message) error {
numWriteCalls++
if &m.Data[0] != &msg[0] {
t.Error("Didn't get expected message by reference.")
}
return nil
},
}
client := NewClient("test-client", &nopRWC{}, singletonTranslator(&ct), nil)
conn := newClientConnection("other-client", "connID", client)
n, err := conn.Write(msg)
if err != nil {
t.Error("Write failed:", err)
} else if n != len(msg) {
t.Error("Write reported", n, "<", len(msg), "bytes written")
}
err = conn.WriteMessage(msg)
if err != nil {
t.Error("WriteMessage failed:", err)
}
if numWriteCalls != 2 {
t.Error("Expected 2 write calls, got", numWriteCalls)
}
}
// No, I'm not kidding.
func TestClientConnectionOtherClientWorks(t *testing.T) {
conn := newClientConnection("foo", "id", nil)
if conn.OtherClient() != "foo" {
t.Error("How did it return", conn.OtherClient())
}
}
func TestClientConnectionIgnoresNilMessagesInRead(t *testing.T) {
conn := newClientConnection("other-client", "connID", nil)
msg1 := []byte("Hello")
msg2 := []byte("World!")
syncChan := make(chan struct{})
go func() {
msg := &Message{Data: msg1}
conn.putNewMessage(msg)
// We need the writes to not be smashed into one read, so we synchronize
// with the test here.
<-syncChan
msg.Data = []byte{}
conn.putNewMessage(msg)
msg.Data = msg2
conn.putNewMessage(msg)
}()
buf := make([]byte, 32)
n, err := conn.Read(buf)
if err != nil {
t.Error("Read error:", err)
} else if n != len(msg1) {
t.Error("Reported buffer length of", n)
} else if !bytes.Equal(buf[:n], msg1) {
t.Error("Got bytes:", string(buf[:n]))
}
close(syncChan)
n, err = conn.Read(buf)
if err != nil {
t.Error("Read error:", err)
} else if n != len(msg2) {
t.Error("Reported buffer length of", n)
} else if !bytes.Equal(buf[:n], msg2) {
t.Error("Got bytes:", string(msg2))
}
}
func TestClientConnectionSpreadsBigMessagesAcrossManyReads(t *testing.T) {
conn := newClientConnection("other-client", "connID", nil)
// "Big messages"
msg1 := []byte("Hello")
go func() {
msg := &Message{Data: msg1}
conn.putNewMessage(msg)
conn.Close()
}()
buf := make([]byte, 0, len(msg1))
var readBuf [2]byte
nReads := 0
for {
n, err := conn.Read(readBuf[:])
buf = append(buf, readBuf[:n]...)
nReads++
if err == io.EOF {
break
} else if err != nil {
t.Fatal("Error reading:", err)
}
}
expNReads := len(msg1)/2 + len(msg1)%2
if nReads != expNReads {
t.Error("Expected", expNReads, "reads but got", nReads)
}
if !bytes.Equal(msg1, buf) {
t.Error("Buffer wasn't expected:", buf)
}
}
func TestClientConnectionReturnsOneMessagePerReadMessage(t *testing.T) {
conn := newClientConnection("other-client", "connID", nil)
msg1 := []byte("Hello")
msg2 := []byte{}
msg3 := []byte("World!")
go func() {
msg := &Message{Data: msg1}
conn.putNewMessage(msg)
msg.Data = msg2
conn.putNewMessage(msg)
msg.Data = msg3
conn.putNewMessage(msg)
conn.Close()
}()
msgs := [...][]byte{msg1, msg2, msg3}
for i, m := range msgs {
rmsg, err := conn.ReadMessage()
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(rmsg, m) {
t.Errorf("%d message (%s) != expected (%s)", i, string(rmsg), string(m))
}
}
}
func mockBoundClientConnection() (*channelTranslator, *clientConnection) {
ct := newChannelTranslator()
client := NewClient("client-connection-client", &nopRWC{}, singletonTranslator(ct), nil)
conn := newClientConnection("client-connection", "test-id", client)
return ct, conn
}
func TestClientConnectionHandlesWriteMessageFailureGracefully(t *testing.T) {
ct, conn := mockBoundClientConnection()
ct.Close()
err := conn.WriteMessage([]byte("Hi!"))
if err != io.EOF {
t.Error("Expected EOF, got", err)
}
_, err = conn.Write([]byte("Hi!"))
if err != io.EOF {
t.Error("Expected EOF, got", err)
}
}
func TestClientConnectionHandlesReadMessageFailureGracefully(t *testing.T) {
conn := newClientConnection("client-connection", "test-id", nil)
conn.Close()
_, err := conn.ReadMessage()
if err != io.EOF {
t.Error("Expected EOF, got", err)
}
var bs [1]byte
_, err = conn.Read(bs[:])
if err != io.EOF {
t.Error("Expected EOF, got", err)
}
}
func TestClientConnectionReadReportsProperAmount(t *testing.T) {
const InputBufferLen = 3
conn := newClientConnection("client-connection", "test-id", nil)
defer conn.Close()
// Conveniently InputBufferLen+1 and InputBufferLen*2, respectively
messages := [...]string{"Hi!!", "Hello!"}
for _, message := range messages {
msg := &Message{Data: []byte(message)}
go conn.putNewMessage(msg)
var inBuf [InputBufferLen]byte
n, err := conn.Read(inBuf[:])
if err != nil {
t.Fatal(err)
}
if n != len(inBuf) {
t.Error("Got less bytes than expected.")
} else if exp := msg.Data[:n]; !bytes.Equal(inBuf[:], exp) {
t.Error("Data wasn't what eas expected. Got", inBuf, "-- expected", exp)
}
remData := msg.Data[n:]
n, err = conn.Read(inBuf[:])
if err != nil {
t.Fatal(err)
}
if n != len(remData) {
t.Errorf("Got %d bytes, expected %d.", n, len(remData))
} else if got := inBuf[:n]; !bytes.Equal(remData, got) {
t.Errorf("Got bytes %v, expected %v", got, remData)
}
}
}
// -----------------------------------------------------------------------------
// Client
// -----------------------------------------------------------------------------
func TestClientSubmitsUnalteredUsernameAndPassword(t *testing.T) {
const clientName = "test-client"
clientPass := []byte("test-password")
readCalled := false
writeCalled := false
ct := callbackTranslator{
ReadCallback: func() (*Message, error) {
readCalled = true
msg := &Message{Meta: MetaAuthOk}
return msg, nil
},
WriteCallback: func(m *Message) error {
writeCalled = true
if m.Meta != MetaAuth {
t.Error("Auth message type wasn't MetaAuth")
}
if m.OtherClient != clientName {
t.Error("Didn't submit proper client name. Submitted:", m.OtherClient)
}
if !bytes.Equal(m.Data, clientPass) {
t.Error("Didn't submit requested password. Submitted:", string(m.Data))
}
return nil
},
}
client := NewClient(clientName, &nopRWC{}, singletonTranslator(&ct), nil)
err := client.Authenticate(clientPass)
if err != nil {
t.Error("Got error authenticating:", err)
}
if !readCalled || !writeCalled {
t.Error("Authenticate didn't call read/write")
}
}
func makeAuthedClient(
t *testing.T,
handler NewConnectionHandler,
) (*Client, *channelTranslator, *sync.WaitGroup, func()) {
wg := new(sync.WaitGroup)
ct := newChannelTranslator()
client := NewClient("client-name", &nopRWC{}, singletonTranslator(ct), handler)
client.authed = true
wg.Add(1)
go func() {
defer wg.Done()
err := client.Run()
if err != io.EOF {
t.Error("Client died with", err)
}
}()
return client, ct, wg, func() {
ct.Close()
client.Close()
wg.Wait()
}
}
func TestClientSendsSynAckOnNewConnectionRequest(t *testing.T) {
const (
otherClient = "other-client"
proto = "proto1"
)
client, ct, _, shutdown := makeAuthedClient(t, nil)
defer shutdown()
// Main test routine routes messages, so we leave making the connection to
// other goroutines
connectionMade := make(chan struct{})
go func() {
_, err := client.MakeConnection(otherClient, proto)
if err != nil {
t.Fatal(err)
}
close(connectionMade)
}()
msg := <-ct.outgoing
if msg.Meta != MetaConnSyn {
t.Error("Expected Syn meta type in message, got", msg.Meta)
}
if mData := string(msg.Data); mData != proto {
t.Error("Unexpected message data:", mData)
}
if msg.OtherClient != otherClient {
t.Error("Other client was unexpectedly", msg.OtherClient)
}
msg.Meta = MetaConnAck
ct.incoming <- msg
<-connectionMade
}
func TestClientSendsNoSuchConnectionOnAckOrRegularMessage(t *testing.T) {
_, ct, _, shutdown := makeAuthedClient(t, nil)
defer shutdown()
msg := &Message{
Meta: MetaConnAck,
ConnectionID: "does-not-exist",
OtherClient: "no-client",
Data: []byte("Noproto"),
}
ct.incoming <- msg
resp := <-ct.outgoing
if resp.Meta != MetaNoSuchConnection {
t.Error("Expected meta to be MetaNoSuchConnection, was", resp.Meta)
}
msg.Meta = MetaNone
ct.incoming <- msg
resp = <-ct.outgoing
if resp.Meta != MetaNoSuchConnection {
t.Error("Expected meta to be MetaNoSuchConnection, was", resp.Meta)
}
}
func TestClientSendsWatWhenSentAuthMessage(t *testing.T) {
_, ct, _, shutdown := makeAuthedClient(t, nil)
defer shutdown()
msg := &Message{
ConnectionID: "does-not-exist",
OtherClient: "no-client",
Data: []byte("Noproto"),
}
metas := [...]MetaType{MetaAuth, MetaAuthOk, MetaAuthFailure}
for _, m := range metas {
msg.Meta = m
ct.incoming <- msg
resp := <-ct.outgoing
if resp.Meta != MetaWAT {
t.Error("Expected WAT response to", m, "got", resp.Meta)
}
}
}
func TestClientObeysSynHandlerDecisions(t *testing.T) {
const (
clientName = "test-client"
inputProto = "input-proto"
)
ch := &callbackConnectionHandler{
Callback: func(proto string, accept func() Connection) {
if proto == inputProto {
accept()
}
},
}
_, ct, _, shutdown := makeAuthedClient(t, ch)
defer shutdown()
msg := &Message{
Meta: MetaConnSyn,
ConnectionID: "test-connid",
OtherClient: "other",
Data: []byte(inputProto),
}
ct.incoming <- msg
ack := <-ct.outgoing
if ack.Meta != MetaConnAck {
t.Error("Meta is wrong:", ack.Meta)
}
// ack == msg, so we need to reset meta.
msg.Meta = MetaConnSyn
msg.Data = append([]byte(inputProto), '!')
ct.incoming <- msg
ack = <-ct.outgoing
if ack.Meta != MetaUnknownProto {
t.Error("Meta is wrong:", ack.Meta)
}
}
func TestClientSendsCloseNotificationOnConnectionClose(t *testing.T) {
clientConnChan := make(chan Connection, 1)
ch := &callbackConnectionHandler{
Callback: func(_ string, accept func() Connection) {
clientConnChan <- accept()
},
}
_, ct, _, shutdown := makeAuthedClient(t, ch)
defer shutdown()
msg := &Message{
Meta: MetaConnSyn,
ConnectionID: "test-connid",
OtherClient: "other",
Data: []byte("test-proto"),
}
ct.incoming <- msg
ack := <-ct.outgoing
if ack.Meta != MetaConnAck {
t.Error("Meta is wrong:", ack.Meta)
}
clientConn := <-clientConnChan
go clientConn.Close()
out := <-ct.outgoing
if out.Meta != MetaConnClosed {
t.Error("Meta is wrong:", ack.Meta)
}
}
func TestClientAckIsAlwaysSentBeforeFirstMessage(t *testing.T) {
respText := []byte("Bye!")
ch := &callbackConnectionHandler{
Callback: func(_ string, accept func() Connection) {
conn := accept()
conn.WriteMessage(respText)
conn.Close()
},
}
_, ct, _, shutdown := makeAuthedClient(t, ch)
defer shutdown()
msg := &Message{
Meta: MetaConnSyn,
ConnectionID: "test-connid",
OtherClient: "other",
Data: []byte("test-proto"),
}
ct.incoming <- msg
ack := <-ct.outgoing
if ack.Meta != MetaConnAck {
t.Error("Meta is wrong:", ack.Meta)
}
resp := <-ct.outgoing
if resp.Meta != MetaNone {
t.Error("Meta is wrong:", resp.Meta)
} else if !bytes.Equal(respText, resp.Data) {
t.Error("Response text is wrong:", resp.Data)
}
closed := <-ct.outgoing
if closed.Meta != MetaConnClosed {
t.Error("Meta is wrong:", closed.Meta)
}
}
func TestClientClosesConnectionIfOtherSideClosed(t *testing.T) {
const otherClient = "test-other-client"
client, ct, wg, shutdown := makeAuthedClient(t, nil)
defer shutdown()
wg.Add(1)
// "Main" goroutine. I'm just juggling messages and things in the
// test after this runs
go func() {
defer wg.Done()
conn, err := client.MakeConnection(otherClient, "test-proto")
if err != nil {
t.Fatal("Error making connection:", err)
}
_, err = conn.ReadMessage()
if err != io.EOF {
t.Error(err)
}
}()
syn := <-ct.outgoing
connID := syn.ConnectionID
syn.Meta = MetaConnAck
ct.incoming <- syn
closedMsg := &Message{
Meta: MetaConnClosed,
ConnectionID: connID,
OtherClient: otherClient,
}
ct.incoming <- closedMsg
}
func TestClientClosesConnectionIfOtherClientClosed(t *testing.T) {
const (
clientName = "test-client"
otherClient = "other-client"
)
client, ct, wg, shutdown := makeAuthedClient(t, nil)
defer shutdown()
wg.Add(2)
// "Main" goroutine 1 -- half-establishes a connection
go func() {
defer wg.Done()
_, err := client.MakeConnection(otherClient, "half-open")
if err == nil {
t.Fatal("No error making a connection")
}
}()
// "Main" goroutine 2 -- fully establishes a connection
go func() {
defer wg.Done()
conn, err := client.MakeConnection(otherClient, "full-open")
if err != nil {
t.Fatal("Error making connection:", err)
}
_, err = conn.ReadMessage()
if err != io.EOF {
t.Error(err)
}
}()
for i := 0; i < 2; i++ {
syn := <-ct.outgoing
if string(syn.Data) != "full-open" {
continue
}
syn.Meta = MetaConnAck
ct.incoming <- syn
}
closedMsg := &Message{
Meta: MetaClientClosed,
OtherClient: otherClient,
}
ct.incoming <- closedMsg
}
func TestClientAuthFailsGracefullyOnCommunicationErrors(t *testing.T) {
var wg sync.WaitGroup
wg.Add(3)
// Reauth
client0, _, _, shutdown := makeAuthedClient(t, nil)
err := client0.Authenticate([]byte("Nope.jpg"))
if err.Error() != errStringMultipleAuths {
t.Error("Expected multiple auths error, got", err)
}
shutdown()
// Close before send
ct1 := newChannelTranslator()
client1 := NewClient("client-name", &nopRWC{}, singletonTranslator(ct1), nil)
ct1.Close()
go func() {
defer wg.Done()
err := client1.Authenticate(nil)
if err != io.EOF {
t.Error("Expected io.EOF from Authenticate, but got", err)
}
}()
// Close before recv
ct2 := newChannelTranslator()
client2 := NewClient("client-name", &nopRWC{}, singletonTranslator(ct2), nil)
go func() {
defer wg.Done()
err := client2.Authenticate(nil)
if err != io.EOF {
t.Error("Expected io.EOF from Authenticate, but got", err)
}
}()
<-ct2.outgoing
ct2.Close()
// Send back not-MetaAuthOk
const ErrorText = "Oh noes!"
ct3 := newChannelTranslator()
client3 := NewClient("client-name", &nopRWC{}, singletonTranslator(ct3), nil)
go func() {
defer wg.Done()
err := client3.Authenticate(nil)
if err.Error() != ErrorText {
t.Error("Expected", ErrorText, "from Authenticate, but got", err)
}
}()
in := <-ct3.outgoing
in.Meta = MetaAuthFailure
in.Data = []byte(ErrorText)
ct3.incoming <- in
wg.Wait()
}
func TestClientCloseClosesAllConnections(t *testing.T) {
client, ct, _, shutdown := makeAuthedClient(t, nil)
defer shutdown()
var conn Connection
connMade := make(chan struct{})
go func() {
defer close(connMade)
var err error
conn, err = client.MakeConnection("test-other-client", "test-proto")
if err != nil {
t.Fatal("Expected connection to be made, but got", err)
}
}()
syn := <-ct.outgoing
syn.Meta = MetaConnAck
ct.incoming <- syn
<-connMade
client.Close()
_, err := conn.ReadMessage()
if err != io.EOF {
t.Error("Expected EOF, but got", err)
}
}
func TestClientMakeConnectionFailsGracefullyOnWriteFailure(t *testing.T) {
client, ct, wg, shutdown := makeAuthedClient(t, nil)
defer shutdown()
wg.Add(1)
go func() {
defer wg.Done()
_, err := client.MakeConnection("test-other-client", "test-proto")
if err != io.EOF {
t.Fatal("Expected io.EOF, got", err)
}
}()
ct.Close()
}
func TestClientComplainsIfRunWithoutAuthenticating(t *testing.T) {
client := NewClient("basically-nil", nil, singletonTranslator(nil), nil)
err := client.Run()
if err.Error() != errStringNotYetAuthed {
t.Error("Expected not yet authed error message, got", err)
}
}