Adding unit test for chain add (#29)

Signed-off-by: Serguei Bezverkhi <sbezverk@cisco.com>
This commit is contained in:
Serguei Bezverkhi 2019-06-26 10:53:43 -04:00 committed by Michael Stapelberg
parent 76dc827b18
commit d22d8d0641
1 changed files with 81 additions and 0 deletions

View File

@ -561,6 +561,87 @@ func TestAddCounter(t *testing.T) {
} }
} }
func TestAddChain(t *testing.T) {
tests := []struct {
name string
chain *nftables.Chain
want [][]byte
}{
{
name: "Base chain",
chain: &nftables.Chain{
Name: "base-chain",
Hooknum: nftables.ChainHookPrerouting,
Priority: 0,
Type: nftables.ChainTypeFilter,
},
want: [][]byte{
// batch begin
[]byte("\x00\x00\x00\x0a"),
// nft add table ip filter
[]byte("\x02\x00\x00\x00\x0b\x00\x01\x00\x66\x69\x6c\x74\x65\x72\x00\x00\x08\x00\x02\x00\x00\x00\x00\x00"),
// nft add chain ip filter base-chain { type filter hook prerouting priority 0 \; }
[]byte("\x02\x00\x00\x00\x0b\x00\x01\x00\x66\x69\x6c\x74\x65\x72\x00\x00\x0f\x00\x03\x00\x62\x61\x73\x65\x2d\x63\x68\x61\x69\x6e\x00\x00\x14\x00\x04\x80\x08\x00\x01\x00\x00\x00\x00\x00\x08\x00\x02\x00\x00\x00\x00\x00\x0b\x00\x07\x00\x66\x69\x6c\x74\x65\x72\x00\x00"),
// batch end
[]byte("\x00\x00\x00\x0a"),
},
},
{
name: "Regular chain",
chain: &nftables.Chain{
Name: "regular-chain",
},
want: [][]byte{
// batch begin
[]byte("\x00\x00\x00\x0a"),
// nft add table ip filter
[]byte("\x02\x00\x00\x00\x0b\x00\x01\x00\x66\x69\x6c\x74\x65\x72\x00\x00\x08\x00\x02\x00\x00\x00\x00\x00"),
// nft add chain ip filter regular-chain
[]byte("\x02\x00\x00\x00\x0b\x00\x01\x00\x66\x69\x6c\x74\x65\x72\x00\x00\x12\x00\x03\x00\x72\x65\x67\x75\x6c\x61\x72\x2d\x63\x68\x61\x69\x6e\x00\x00\x00"),
// batch end
[]byte("\x00\x00\x00\x0a"),
},
},
}
for _, tt := range tests {
c := &nftables.Conn{
TestDial: func(req []netlink.Message) ([]netlink.Message, error) {
for idx, msg := range req {
b, err := msg.MarshalBinary()
if err != nil {
t.Fatal(err)
}
if len(b) < 16 {
continue
}
b = b[16:]
if len(tt.want[idx]) == 0 {
t.Errorf("no want entry for message %d: %x", idx, b)
continue
}
got := b
if !bytes.Equal(got, tt.want[idx]) {
t.Errorf("message %d: %s", idx, linediff(nfdump(got), nfdump(tt.want[idx])))
}
}
return req, nil
},
}
filter := c.AddTable(&nftables.Table{
Family: nftables.TableFamilyIPv4,
Name: "filter",
})
tt.chain.Table = filter
c.AddChain(tt.chain)
if err := c.Flush(); err != nil {
t.Fatal(err)
}
}
}
func TestGetObjReset(t *testing.T) { func TestGetObjReset(t *testing.T) {
// The want byte sequences come from stracing nft(8), e.g.: // The want byte sequences come from stracing nft(8), e.g.:
// strace -f -v -x -s 2048 -eraw=sendto nft list chain ip filter forward // strace -f -v -x -s 2048 -eraw=sendto nft list chain ip filter forward