|
| 1 | +package keepalive |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/hex" |
| 5 | + "github.com/cloudstruct/go-ouroboros-network/protocol" |
| 6 | + "github.com/cloudstruct/go-ouroboros-network/utils" |
| 7 | + "reflect" |
| 8 | + "testing" |
| 9 | +) |
| 10 | + |
| 11 | +type testDefinition struct { |
| 12 | + CborHex string |
| 13 | + Message protocol.Message |
| 14 | + MessageType uint |
| 15 | +} |
| 16 | + |
| 17 | +var tests = []testDefinition{ |
| 18 | + { |
| 19 | + CborHex: "8200193039", |
| 20 | + Message: NewMsgKeepAlive(12345), |
| 21 | + MessageType: MESSAGE_TYPE_KEEP_ALIVE, |
| 22 | + }, |
| 23 | + { |
| 24 | + CborHex: "8201193039", |
| 25 | + Message: NewMsgKeepAliveResponse(12345), |
| 26 | + MessageType: MESSAGE_TYPE_KEEP_ALIVE_RESPONSE, |
| 27 | + }, |
| 28 | + { |
| 29 | + CborHex: "8102", |
| 30 | + Message: NewMsgDone(), |
| 31 | + MessageType: MESSAGE_TYPE_DONE, |
| 32 | + }, |
| 33 | +} |
| 34 | + |
| 35 | +func TestDecode(t *testing.T) { |
| 36 | + for _, test := range tests { |
| 37 | + cborData, err := hex.DecodeString(test.CborHex) |
| 38 | + if err != nil { |
| 39 | + t.Fatalf("failed to decode CBOR hex: %s", err) |
| 40 | + } |
| 41 | + msg, err := NewMsgFromCbor(test.MessageType, cborData) |
| 42 | + if err != nil { |
| 43 | + t.Fatalf("failed to decode CBOR: %s", err) |
| 44 | + } |
| 45 | + // Set the raw CBOR so the comparison should succeed |
| 46 | + test.Message.SetCbor(cborData) |
| 47 | + if !reflect.DeepEqual(msg, test.Message) { |
| 48 | + t.Fatalf("CBOR did not decode to expected message object\n got: %#v\n wanted: %#v", msg, test.Message) |
| 49 | + } |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +func TestEncode(t *testing.T) { |
| 54 | + for _, test := range tests { |
| 55 | + cborData, err := utils.CborEncode(test.Message) |
| 56 | + if err != nil { |
| 57 | + t.Fatalf("failed to encode message to CBOR: %s", err) |
| 58 | + } |
| 59 | + cborHex := hex.EncodeToString(cborData) |
| 60 | + if cborHex != test.CborHex { |
| 61 | + t.Fatalf("message did not encode to expected CBOR\n got: %s\n wanted: %s", cborHex, test.CborHex) |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments