Skip to content

Commit

Permalink
testutils: add DupFD helper
Browse files Browse the repository at this point in the history
Add a cross-platform DupFD helper and use it from tests.

Signed-off-by: Lorenz Bauer <[email protected]>
  • Loading branch information
lmb committed Mar 3, 2025
1 parent 11a0bb3 commit 21f046d
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 14 deletions.
20 changes: 20 additions & 0 deletions internal/testutils/fd_other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//go:build !windows

package testutils

import (
"testing"

"github.com/go-quicktest/qt"

"github.com/cilium/ebpf/internal/unix"
)

func DupFD(tb testing.TB, fd int) int {
tb.Helper()

dup, err := unix.FcntlInt(uintptr(fd), unix.F_DUPFD_CLOEXEC, 1)
qt.Assert(tb, qt.IsNil(err))

return dup
}
17 changes: 17 additions & 0 deletions internal/testutils/fd_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package testutils

import (
"testing"

"github.com/cilium/ebpf/internal/efw"
"github.com/go-quicktest/qt"
)

func DupFD(tb testing.TB, fd int) int {
tb.Helper()

dup, err := efw.EbpfDuplicateFd(fd)
qt.Assert(tb, qt.IsNil(err))

return dup
}
4 changes: 2 additions & 2 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -804,7 +804,7 @@ func TestNewMapInMapFromFD(t *testing.T) {
nested := createMapInMap(t, ArrayOfMaps, Array)

// Do not copy this, use Clone instead.
another, err := NewMapFromFD(dupFD(t, nested.FD()))
another, err := NewMapFromFD(testutils.DupFD(t, nested.FD()))
if err != nil {
t.Fatal("Can't create a new nested map from an FD")
}
Expand Down Expand Up @@ -1388,7 +1388,7 @@ func TestMapFromFD(t *testing.T) {

// If you're thinking about copying this, don't. Use
// Clone() instead.
m2, err := NewMapFromFD(dupFD(t, m.FD()))
m2, err := NewMapFromFD(testutils.DupFD(t, m.FD()))
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
Expand Down
13 changes: 1 addition & 12 deletions prog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ func TestProgramFromFD(t *testing.T) {

// If you're thinking about copying this, don't. Use
// Clone() instead.
prog2, err := NewProgramFromFD(dupFD(t, prog.FD()))
prog2, err := NewProgramFromFD(testutils.DupFD(t, prog.FD()))
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
Expand Down Expand Up @@ -1087,14 +1087,3 @@ func ExampleProgramSpec_Tag() {
fmt.Println("The programs are identical, tag is", tag)
}
}

func dupFD(tb testing.TB, fd int) int {
tb.Helper()

dup, err := unix.FcntlInt(uintptr(fd), unix.F_DUPFD_CLOEXEC, 1)
if err != nil {
tb.Fatal("Can't dup fd:", err)
}

return dup
}

0 comments on commit 21f046d

Please sign in to comment.