diff --git a/ping_test.go b/ping_test.go index 7b775c8..0a36dc7 100644 --- a/ping_test.go +++ b/ping_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "fmt" "net" "runtime" "runtime/debug" @@ -474,13 +475,45 @@ func TestStatisticsZeroDivision(t *testing.T) { } } +func testSetInterfaceNameChooseInterface(t *testing.T) (string, string) { + ifaces, err := net.Interfaces() + AssertNoError(t, err) + + for _, i := range ifaces { + name := i.Name + // fix: this is a hack to choose any interface that is not `lo` to a permission issue in CircleCI + if name == "lo" { + continue + } + // find the local address to ping + addrs, err := i.Addrs() + AssertNoError(t, err) + + for _, a := range addrs { + switch v := a.(type) { + case *net.IPAddr: + return name, v.IP.String() + case *net.IPNet: + return name, v.IP.String() + } + } + } + + // we fail the test if no interface is available + AssertNoError(t, fmt.Errorf("no interface is available for testing")) + return "", "" +} + func TestSetInterfaceName(t *testing.T) { - pinger := New("localhost") + // we can ping `localhost`, refering to the address in the interface + interfaceName, localAddress := testSetInterfaceNameChooseInterface(t) + + pinger := New(localAddress) pinger.Count = 1 pinger.Timeout = time.Second // Set loopback interface - pinger.InterfaceDevice = "lo" + pinger.InterfaceDevice = interfaceName err := pinger.Run() if runtime.GOOS == "linux" { AssertNoError(t, err)