forked from dustin/go-coap
-
Notifications
You must be signed in to change notification settings - Fork 3
/
server_test.go
96 lines (84 loc) · 2.15 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
package coap
import (
"net"
"testing"
)
func startUDPLisenter(t *testing.T) (*net.UDPConn, string) {
udpAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
if err != nil {
t.Fatal("Can't resolve UDP addr")
}
udpListener, err := net.ListenUDP("udp", udpAddr)
if err != nil {
t.Fatal("Can't listen on UDP")
}
coapServerAddr := udpListener.LocalAddr().String()
return udpListener, coapServerAddr
}
func dialAndSend(t *testing.T, addr string, req Message) Message {
c, err := Dial("udp", addr)
if err != nil {
t.Fatalf("Error dialing: %v", err)
}
m, err := c.Send(req)
if err != nil {
t.Fatalf("Error sending request: %v", err)
}
return m
}
func TestServeWithAckResponse(t *testing.T) {
req := &DgramMessage{
MessageBase{
typ: Confirmable,
code: POST,
messageID: 9876,
payload: []byte("Content sent by client"),
},
}
req.SetOption(ContentFormat, TextPlain)
req.SetPathString("/req/path")
res := &DgramMessage{
MessageBase{
typ: Acknowledgement,
code: Content,
messageID: req.MessageID(),
payload: []byte("Reply from CoAP server"),
},
}
res.SetOption(ContentFormat, TextPlain)
res.SetPath(req.Path())
handler := FuncHandler(func(l *net.UDPConn, a *net.UDPAddr, m Message) Message {
assertEqualMessages(t, req, m)
return res
})
udpListener, coapServerAddr := startUDPLisenter(t)
defer udpListener.Close()
go Serve(udpListener, handler)
m := dialAndSend(t, coapServerAddr, req)
if m == nil {
t.Fatalf("Didn't receive CoAP response")
}
assertEqualMessages(t, res, m)
}
func TestServeWithoutAckResponse(t *testing.T) {
req := &DgramMessage{
MessageBase{
typ: NonConfirmable,
code: POST,
messageID: 54321,
payload: []byte("Content sent by client"),
},
}
req.SetOption(ContentFormat, AppOctets)
handler := FuncHandler(func(l *net.UDPConn, a *net.UDPAddr, m Message) Message {
assertEqualMessages(t, req, m)
return nil
})
udpListener, coapServerAddr := startUDPLisenter(t)
defer udpListener.Close()
go Serve(udpListener, handler)
m := dialAndSend(t, coapServerAddr, req)
if m != nil {
t.Fatalf("Received response packet, but expected none")
}
}