Files
netlink/chain_test.go
Vishvananda Abrams 1e35ba25dc test: Improve test reliability with proper cleanup and isolation
Refactors test setup and teardown logic to use `t.Cleanup` instead
of `defer`. This ensures that cleanup functions are correctly scoped
to each subtest's lifecycle, improving test isolation and reliability.

The `setUpNetlinkTest` helper function is also improved to correctly
save and restore the original network namespace, ensuring that tests
do not leak state.

To support this, a `Close()` method that returns an error is added to
the `Handle` struct, allowing for proper cleanup of underlying netlink
sockets. The test helpers are updated to use this new method,
preventing resource leaks between tests.

Additionally, a bug in the `netns` tests is fixed where a large
namespace ID could overflow a 32-bit integer, causing spurious
failures on some systems.
2025-08-27 09:24:17 -07:00

77 lines
1.5 KiB
Go

//go:build linux
// +build linux
package netlink
import (
"testing"
)
func TestChainAddDel(t *testing.T) {
t.Cleanup(setUpNetlinkTest(t))
if err := LinkAdd(&Ifb{LinkAttrs{Name: "foo"}}); err != nil {
t.Fatal(err)
}
if err := LinkAdd(&Ifb{LinkAttrs{Name: "bar"}}); err != nil {
t.Fatal(err)
}
link, err := LinkByName("foo")
if err != nil {
t.Fatal(err)
}
if err := LinkSetUp(link); err != nil {
t.Fatal(err)
}
qdisc := &Ingress{
QdiscAttrs: QdiscAttrs{
LinkIndex: link.Attrs().Index,
Handle: MakeHandle(0xffff, 0),
Parent: HANDLE_INGRESS,
},
}
if err := QdiscAdd(qdisc); err != nil {
t.Fatal(err)
}
qdiscs, err := SafeQdiscList(link)
if err != nil {
t.Fatal(err)
}
if len(qdiscs) != 1 {
t.Fatal("Failed to add qdisc")
}
_, ok := qdiscs[0].(*Ingress)
if !ok {
t.Fatal("Qdisc is the wrong type")
}
chainVal := new(uint32)
*chainVal = 20
chain := NewChain(HANDLE_INGRESS, *chainVal)
err = ChainAdd(link, chain)
if err != nil {
t.Fatal(err)
}
chains, err := ChainList(link, HANDLE_INGRESS)
if err != nil {
t.Fatal(err)
}
if len(chains) != 1 {
t.Fatal("Failed to add chain")
}
if chains[0].Chain != *chainVal {
t.Fatal("Incorrect chain added")
}
if chains[0].Parent != HANDLE_INGRESS {
t.Fatal("Incorrect chain parent")
}
if err := ChainDel(link, chain); err != nil {
t.Fatal(err)
}
chains, err = ChainList(link, HANDLE_INGRESS)
if err != nil {
t.Fatal(err)
}
if len(chains) != 0 {
t.Fatal("Failed to remove chain")
}
}