package auth import ( "errors" "testing" "time" ) func TestPingHostUsesICMPWhenAvailable(t *testing.T) { originalPing := runICMPPing originalDial := dialTCP t.Cleanup(func() { runICMPPing = originalPing dialTCP = originalDial }) runICMPPing = func(hostIP string) error { if hostIP != "10.0.0.1" { t.Fatalf("host = %q", hostIP) } return nil } dialTCP = func(address string, timeout time.Duration) error { t.Fatal("tcp should not be used when icmp succeeds") return nil } result := PingHost("10.0.0.1") if !result.OK { t.Fatalf("expected ok, got %#v", result) } if result.Method != PingMethodICMP { t.Fatalf("method = %q", result.Method) } } func TestPingHostFallsBackToTCPWhenICMPFails(t *testing.T) { originalPing := runICMPPing originalDial := dialTCP t.Cleanup(func() { runICMPPing = originalPing dialTCP = originalDial }) runICMPPing = func(hostIP string) error { return errors.New("ping unavailable: executable file not found") } dialTCP = func(address string, timeout time.Duration) error { if address != "10.0.0.2:22" { t.Fatalf("address = %q", address) } return nil } result := PingHost("10.0.0.2") if !result.OK { t.Fatalf("expected ok, got %#v", result) } if result.Method != PingMethodTCP { t.Fatalf("method = %q", result.Method) } } func TestPingHostFailsWhenBothFail(t *testing.T) { originalPing := runICMPPing originalDial := dialTCP t.Cleanup(func() { runICMPPing = originalPing dialTCP = originalDial }) runICMPPing = func(hostIP string) error { return errors.New("100% packet loss") } dialTCP = func(address string, timeout time.Duration) error { return errors.New("connection refused") } result := PingHost("10.0.0.3") if result.OK { t.Fatal("expected failure") } if result.Error == nil { t.Fatal("expected error") } if result.Method != PingMethodTCP { t.Fatalf("method = %q", result.Method) } } func TestPingHostRequiresHostIP(t *testing.T) { result := PingHost(" ") if result.OK || result.Error == nil { t.Fatalf("expected failure, got %#v", result) } }