forked from ajankovic/smpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
smpp_test.go
130 lines (120 loc) · 2.54 KB
/
smpp_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
package smpp_test
import (
"bytes"
"context"
"io"
"log"
"net"
"testing"
"time"
"github.com/ajankovic/smpp"
"github.com/ajankovic/smpp/pdu"
)
type mockServer struct {
Addr string
Respond func(c net.Conn, in pdu.PDU, i int) []byte
}
func startServer(server *mockServer, n int) {
l, err := net.Listen("tcp", server.Addr)
if err != nil {
log.Fatal(err)
}
defer l.Close()
tcpConn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
defer tcpConn.Close()
for i := 0; i < n; i++ {
server.Serve(tcpConn, i)
}
}
func (this *mockServer) Serve(c net.Conn, i int) {
d := pdu.NewDecoder(c)
_, p, err := d.Decode()
if err != nil {
if err != io.EOF {
log.Fatalf("serve decode %v %d", err, i)
}
return
}
if p == nil {
log.Fatal("decode returned nil")
}
res := this.Respond(c, p, i)
if res == nil {
return
}
if _, err := c.Write(res); err != nil {
log.Fatalf("connection write %v", err)
}
}
func newBindingServer() *mockServer {
b := &bytes.Buffer{}
e := pdu.NewEncoder(b, nil)
return &mockServer{
Addr: "localhost:2222",
Respond: func(c net.Conn, in pdu.PDU, i int) []byte {
var res pdu.PDU
switch in.CommandID() {
case pdu.BindTransceiverID:
res = &pdu.BindTRxResp{
SystemID: "testing",
Options: pdu.NewOptions().SetScInterfaceVersion(0x34),
}
case pdu.UnbindID:
res = &pdu.UnbindResp{}
}
b.Reset()
if _, err := e.Encode(res); err != nil {
panic("Can't encode pdu")
}
return b.Bytes()
},
}
}
func TestBindingUnbinding(t *testing.T) {
finished := make(chan struct{})
server := newBindingServer()
go func() {
startServer(server, 2)
finished <- struct{}{}
}()
time.Sleep(time.Millisecond * 10)
conf := smpp.BindConf{
Addr: "localhost:2222",
}
sess, err := smpp.BindTRx(smpp.SessionConf{}, conf)
if err != nil {
t.Errorf("bind error %s", err)
}
if sess.SystemID() != "testing" {
t.Errorf("Invalid SystemID after bind %s", sess.SystemID())
}
err = smpp.Unbind(context.Background(), sess)
if err != nil {
t.Errorf("unbind error %s", err)
}
select {
case <-sess.NotifyClosed():
case <-time.After(100 * time.Millisecond):
t.Error("session close timeout")
}
select {
case <-finished:
case <-time.After(100 * time.Millisecond):
t.Errorf("mock server didn't close")
}
}
func TestBindToDeadEnd(t *testing.T) {
conf := smpp.BindConf{
Addr: "localhost:8484",
}
sess, err := smpp.BindTRx(smpp.SessionConf{}, conf)
if err == nil {
t.Errorf("expected error bot got nil")
}
if sess != nil {
t.Errorf("expected session to be nil got %s", sess)
}
}