-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserver_test.go
81 lines (66 loc) · 2.02 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
package opc
import (
"bytes"
"net"
"testing"
"time"
)
// This struct is used to mock out network connections
// So that we can test connection network operations accordingly
type MockConn struct {
payload []byte
}
// Read a single byte off of the payload into the passed in byte array.
func (m *MockConn) Read(b []byte) (n int, err error) {
b[0] = m.payload[0]
m.payload = m.payload[len(b):]
return len(b), nil
}
// Mocked out implementations of net.Conn.
func (m *MockConn) Write(b []byte) (n int, err error) { return len(b), nil }
func (m *MockConn) Close() error { return nil }
func (m *MockConn) LocalAddr() net.Addr { return nil }
func (m *MockConn) RemoteAddr() net.Addr { return nil }
func (m *MockConn) SetDeadline(t time.Time) error { return nil }
func (m *MockConn) SetReadDeadline(t time.Time) error { return nil }
func (m *MockConn) SetWriteDeadline(t time.Time) error { return nil }
// This struct is used to mock out a device implementation
// such that we can test server operations accordingly
type MockDevice struct {
channel uint8
}
func (md *MockDevice) Write(m *Message) error {
return nil
}
func (md *MockDevice) Channel() uint8 {
return 0
}
func TestRegisterDevice(t *testing.T) {
s := NewServer()
d := &MockDevice{channel: 1}
s.RegisterDevice(d)
if _, ok := s.devs[d.Channel()]; !ok {
t.Errorf("Expected Device to be registered")
}
}
func TestUnregisterDevice(t *testing.T) {
s := NewServer()
d := &MockDevice{channel: 1}
s.RegisterDevice(d)
s.UnregisterDevice(d)
if _, ok := s.devs[d.Channel()]; ok {
t.Errorf("Expected Device to be unregistered after registering it")
}
}
func TestReadOpc(t *testing.T) {
s := NewServer()
payload := []byte{255, 0, 0, 3, 1, 2, 3}
m := &MockConn{payload: payload}
msg, err := s.readOpc(m)
if err != nil {
t.Errorf("Encountered an error when reading a valid Message")
}
if bytes.Compare(msg.ByteArray(), payload) != 0 {
t.Errorf("Recieved a mismatched message when reading from a Mocked Connection")
}
}