package linkwatch import ( "encoding/binary" "testing" "golang.org/x/sys/unix" ) // msg is a netlink message of a type, with a payload of n bytes. func msg(typ uint16, n int) []byte { b := make([]byte, unix.NLMSG_HDRLEN+n) binary.NativeEndian.PutUint32(b[0:4], uint32(len(b))) binary.NativeEndian.PutUint16(b[4:6], typ) return b } func TestLinks(t *testing.T) { for _, c := range []struct { name string b []byte want bool }{ {"a new link", msg(unix.RTM_NEWLINK, 16), true}, {"a link going", msg(unix.RTM_DELLINK, 16), true}, {"an address", msg(unix.RTM_NEWADDR, 16), false}, {"a link after an address (padded)", append(msg(unix.RTM_NEWADDR, 13), append(make([]byte, 3), msg(unix.RTM_NEWLINK, 8)...)...), true}, {"truncated", msg(unix.RTM_NEWLINK, 16)[:10], false}, {"a length beyond the datagram", msg(unix.RTM_NEWLINK, 16)[:unix.NLMSG_HDRLEN+4], false}, {"empty", nil, false}, } { if got := links(c.b); got != c.want { t.Errorf("%s: %v", c.name, got) } } }