-
Notifications
You must be signed in to change notification settings - Fork 16
/
server_test.go
117 lines (88 loc) · 1.75 KB
/
server_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
/*
* DudelDu
*
* Copyright 2016 Matthias Ladkau. All rights reserved.
*
* This Source Code Form is subject to the terms of the MIT
* License, If a copy of the MIT License was not distributed with this
* file, You can obtain one at https://opensource.org/licenses/MIT.
*/
package dudeldu
import (
"bytes"
"fmt"
"io"
"net"
"sync"
"testing"
)
var testport = "localhost:9090"
type TestDebugLogger struct {
DebugOutput bool
LogPrint func(v ...interface{})
}
func (ds *TestDebugLogger) IsDebugOutputEnabled() bool {
return ds.DebugOutput
}
func (ds *TestDebugLogger) PrintDebug(v ...interface{}) {
if ds.DebugOutput {
ds.LogPrint(v...)
}
}
func TestServer(t *testing.T) {
// Collect the print output
var out bytes.Buffer
debugLogger := &TestDebugLogger{true, func(v ...interface{}) {
out.WriteString(fmt.Sprint(v...))
out.WriteString("\n")
}}
dds := NewServer(func(c net.Conn, err net.Error) {
if err != nil {
t.Error(err)
return
}
c.Write([]byte("Hello"))
c.Close()
})
dds.DebugOutput = debugLogger.DebugOutput
dds.LogPrint = debugLogger.LogPrint
var wg sync.WaitGroup
wg.Add(1)
err := dds.Run(":abc", &wg)
if err == nil {
t.Error("Unexpected error return:", err)
return
}
wg.Add(1)
go func() {
err := dds.Run(testport, &wg)
if err != nil {
t.Error(err)
return
}
}()
wg.Wait()
// Server is now running
ret, err := readSocket()
if err != nil {
t.Error(err)
return
}
if ret != "Hello" {
t.Error("Unexpected server response:", ret)
return
}
wg.Add(1)
dds.Shutdown()
wg.Wait()
}
func readSocket() (string, error) {
conn, err := net.Dial("tcp", testport)
if err != nil {
return "", err
}
defer conn.Close()
var buf bytes.Buffer
io.Copy(&buf, conn)
return buf.String(), nil
}