package capture import ( "errors" "runtime" "strings" "testing" ) // TestListInterfaces verifies that net.Interfaces() returns at least one interface. // The loopback interface (lo on Linux, lo0 on macOS) always exists. func TestListInterfaces(t *testing.T) { ifaces, err := ListInterfaces() if err != nil { t.Fatalf("ListInterfaces() error: %v", err) } if len(ifaces) == 0 { t.Fatal("ListInterfaces() returned 0 interfaces; expected at least 1 (loopback)") } t.Logf("Found %d interfaces", len(ifaces)) } // TestListInterfacesFormat verifies that each returned interface has a non-empty Name. func TestListInterfacesFormat(t *testing.T) { ifaces, err := ListInterfaces() if err != nil { t.Fatalf("ListInterfaces() error: %v", err) } for i, iface := range ifaces { if iface.Name == "" { t.Errorf("Interface[%d] has empty Name", i) } } } // TestIsPermissionError checks positive cases for isPermissionError. func TestIsPermissionError(t *testing.T) { positives := []string{ "permission denied", "Permission Denied", "PERMISSION DENIED", "operation not permitted", "Operation Not Permitted", "pcap_create: foo", "pcap_create: operation not permitted", } for _, msg := range positives { err := errors.New(msg) if !isPermissionError(err) { t.Errorf("isPermissionError(%q) = false; want true", msg) } } } // TestIsPermissionErrorNegative checks that non-permission errors are not flagged. func TestIsPermissionErrorNegative(t *testing.T) { negatives := []string{ "interface not found", "no such device", "network is unreachable", "device busy", } for _, msg := range negatives { err := errors.New(msg) if isPermissionError(err) { t.Errorf("isPermissionError(%q) = true; want false", msg) } } } // TestPermissionErrorMsg verifies the platform-specific error message. func TestPermissionErrorMsg(t *testing.T) { iface := "eth0" err := permissionErrorMsg(iface) if err == nil { t.Fatal("permissionErrorMsg() returned nil; want an error") } msg := err.Error() // All platforms should mention sudo and the interface name. if !strings.Contains(msg, "sudo") { t.Errorf("permissionErrorMsg(%q) message missing 'sudo': %s", iface, msg) } if !strings.Contains(msg, iface) { t.Errorf("permissionErrorMsg(%q) message missing interface name: %s", iface, msg) } // Linux-specific: must mention setcap. if runtime.GOOS == "linux" { if !strings.Contains(msg, "setcap cap_net_raw+ep") { t.Errorf("permissionErrorMsg on linux missing 'setcap cap_net_raw+ep': %s", msg) } } }