~fnux/yggdrasil-go-coap

ref: e042d7baf5169b5c24e7261d57260a87506cb2db yggdrasil-go-coap/messagetcp_test.go -rw-r--r-- 1.5 KiB
e042d7ba — Jozef Kralik fix sending message when peerMaxMessageSize is not set 2 years ago
                                                                                
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
package coap

import (
	"bytes"
	"testing"
)

func TestTCPDecodeMessageSmallWithPayload(t *testing.T) {
	input := []byte{
		13 << 4, // len=13, tkl=0
		0x01,    // Extended Length
		0x01,    // Code
		0x30, 0x39, 0x21, 0x3,
		0x26, 0x77, 0x65, 0x65, 0x74, 0x61, 0x67,
		0xff,
		'h', 'i',
	}

	msg, err := Decode(bytes.NewReader(input))
	if err != nil {
		t.Fatalf("Error parsing message: %v", err)
	}

	if msg.Type() != Confirmable {
		t.Errorf("Expected message type confirmable, got %v", msg.Type())
	}
	if msg.Code() != GET {
		t.Errorf("Expected message code GET, got %v", msg.Code())
	}

	if !bytes.Equal(msg.Payload(), []byte("hi")) {
		t.Errorf("Incorrect payload: %q", msg.Payload())
	}

}

func TestMessageTCPToBytesLength(t *testing.T) {
	msgParams := MessageParams{
		Code:    COAPCode(02),
		Token:   []byte{0xab},
		Payload: []byte("hi"),
	}

	msg := NewTcpMessage(msgParams)
	msg.AddOption(MaxMessageSize, maxMessageSize)

	buf := &bytes.Buffer{}
	err := msg.MarshalBinary(buf)
	if err != nil {
		t.Fatalf("Error encoding request: %v", err)
	}

	bytesLength, err := msg.ToBytesLength()
	if err != nil {
		t.Fatalf("Error parsing request: %v", err)
	}

	lenTkl := 1
	lenCode := 1
	maxMessageSizeOptionLength := 3
	payloadMarker := []byte{0xff}

	expectedLength := lenTkl + lenCode + len(msgParams.Token) + maxMessageSizeOptionLength + len(payloadMarker) + len(msgParams.Payload)
	if expectedLength != bytesLength {
		t.Errorf("Expected Length  = %d, got %d", expectedLength, bytesLength)
	}
}