Recover possible panic in EncodeMsg and improve debug logs
[govpp.git] / codec / msg_codec_test.go
1 package codec
2
3 import (
4         "bytes"
5         "testing"
6
7         "git.fd.io/govpp.git/api"
8 )
9
10 type MyMsg struct {
11         Index uint16
12         Label []byte `struc:"[16]byte"`
13         Port  uint16
14 }
15
16 func (*MyMsg) GetMessageName() string {
17         return "my_msg"
18 }
19 func (*MyMsg) GetCrcString() string {
20         return "xxxxx"
21 }
22 func (*MyMsg) GetMessageType() api.MessageType {
23         return api.OtherMessage
24 }
25
26 func TestEncode(t *testing.T) {
27         tests := []struct {
28                 name    string
29                 msg     api.Message
30                 msgID   uint16
31                 expData []byte
32         }{
33                 {name: "basic",
34                         msg:     &MyMsg{Index: 1, Label: []byte("Abcdef"), Port: 1000},
35                         msgID:   100,
36                         expData: []byte{0x00, 0x64, 0x00, 0x01, 0x41, 0x62, 0x63, 0x64, 0x65, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE8},
37                 },
38         }
39         for _, test := range tests {
40                 t.Run(test.name, func(t *testing.T) {
41                         c := &MsgCodec{}
42
43                         data, err := c.EncodeMsg(test.msg, test.msgID)
44                         if err != nil {
45                                 t.Fatalf("expected nil error, got: %v", err)
46                         }
47                         if !bytes.Equal(data, test.expData) {
48                                 t.Fatalf("expected data: % 0X, got: % 0X", test.expData, data)
49                         }
50                 })
51         }
52 }
53
54 func TestEncodePanic(t *testing.T) {
55         c := &MsgCodec{}
56
57         msg := &MyMsg{Index: 1, Label: []byte("thisIsLongerThan16Bytes"), Port: 1000}
58
59         _, err := c.EncodeMsg(msg, 100)
60         if err == nil {
61                 t.Fatalf("expected non-nil error, got: %v", err)
62         }
63 }