github.com/vishvananda/netlink@v1.3.0/nl/route_linux_test.go (about)

     1  package nl
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/rand"
     6  	"encoding/binary"
     7  	"testing"
     8  
     9  	"golang.org/x/sys/unix"
    10  )
    11  
    12  func (msg *RtMsg) write(b []byte) {
    13  	native := NativeEndian()
    14  	b[0] = msg.Family
    15  	b[1] = msg.Dst_len
    16  	b[2] = msg.Src_len
    17  	b[3] = msg.Tos
    18  	b[4] = msg.Table
    19  	b[5] = msg.Protocol
    20  	b[6] = msg.Scope
    21  	b[7] = msg.Type
    22  	native.PutUint32(b[8:12], msg.Flags)
    23  }
    24  
    25  func (msg *RtMsg) serializeSafe() []byte {
    26  	len := unix.SizeofRtMsg
    27  	b := make([]byte, len)
    28  	msg.write(b)
    29  	return b
    30  }
    31  
    32  func deserializeRtMsgSafe(b []byte) *RtMsg {
    33  	var msg = RtMsg{}
    34  	binary.Read(bytes.NewReader(b[0:unix.SizeofRtMsg]), NativeEndian(), &msg)
    35  	return &msg
    36  }
    37  
    38  func TestRtMsgDeserializeSerialize(t *testing.T) {
    39  	var orig = make([]byte, unix.SizeofRtMsg)
    40  	rand.Read(orig)
    41  	safemsg := deserializeRtMsgSafe(orig)
    42  	msg := DeserializeRtMsg(orig)
    43  	testDeserializeSerialize(t, orig, safemsg, msg)
    44  }
    45  
    46  func TestDeserializeRtNexthop(t *testing.T) {
    47  	buf := make([]byte, unix.SizeofRtNexthop+64)
    48  	native := NativeEndian()
    49  	native.PutUint16(buf[0:2], unix.SizeofRtNexthop)
    50  	buf[2] = 17
    51  	buf[3] = 1
    52  	native.PutUint32(buf[4:8], 1234)
    53  
    54  	msg := DeserializeRtNexthop(buf)
    55  	safemsg := &RtNexthop{
    56  		unix.RtNexthop{
    57  			Len:     unix.SizeofRtNexthop,
    58  			Flags:   17,
    59  			Hops:    1,
    60  			Ifindex: 1234,
    61  		},
    62  		nil,
    63  	}
    64  	if msg.Len() != safemsg.Len() || msg.Flags != safemsg.Flags || msg.Hops != safemsg.Hops || msg.Ifindex != safemsg.Ifindex {
    65  		t.Fatal("Deserialization failed.\nIn:", buf, "\nOut:", msg, "\n", msg.Serialize(), "\nExpected:", safemsg, "\n", safemsg.Serialize())
    66  	}
    67  }