forked from flosse/go-modbus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pdu_test.go
91 lines (69 loc) · 1.95 KB
/
pdu_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
package modbus
import (
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func Test_Pdu(t *testing.T) {
Convey("Given a pdu struct", t, func() {
data := []byte{7, 8}
pdu := &Pdu{4, data}
Convey("When we pack it", func() {
bin, _ := pdu.pack()
Convey("the length of the binary array should be correct", func() {
So(len(bin), ShouldEqual, 3)
})
Convey("the function code should be checked", func() {
_, err := (&Pdu{0, data}).pack()
So(err, ShouldNotBeNil)
_, err = (&Pdu{1, data}).pack()
So(err, ShouldBeNil)
})
Convey("the function code should be encoded", func() {
So(bin[0], ShouldEqual, 4)
})
Convey("the data should be added", func() {
So(bin[2], ShouldEqual, 8)
})
Convey("the data field can be nil", func() {
b, err := (&Pdu{1, nil}).pack()
So(err, ShouldBeNil)
So(len(b), ShouldEqual, 1)
})
Convey("the data length has to be less than 252", func() {
_, err := (&Pdu{1, make([]byte, 253)}).pack()
So(err, ShouldNotBeNil)
_, err = (&Pdu{1, make([]byte, 252)}).pack()
So(err, ShouldBeNil)
})
})
})
Convey("Given a valid binary pdu", t, func() {
bin := []byte{3, 7, 8}
Convey("When we unpack it", func() {
pdu, err := unpackPdu(bin)
Convey("we should not get an error", func() {
So(err, ShouldBeNil)
})
Convey("the function code should be decoded", func() {
So(pdu.Function, ShouldEqual, 3)
})
Convey("the data field should be corret", func() {
So(len(pdu.Data), ShouldEqual, 2)
So(pdu.Data[0], ShouldEqual, 7)
})
Convey("the data field can be empty", func() {
pdu, _ := unpackPdu([]byte{1})
So(pdu.Data, ShouldHaveSameTypeAs, []byte{})
So(len(pdu.Data), ShouldEqual, 0)
})
})
})
Convey("Given an invalid binary pdu", t, func() {
Convey("When we unpack it", func() {
_, err := unpackPdu([]byte{})
Convey("we should get an error", func() {
So(err, ShouldNotBeNil)
})
})
})
}