diff --git a/cmd/flag_completion.go b/cmd/flag_completion.go index afdef54..699e7f1 100644 --- a/cmd/flag_completion.go +++ b/cmd/flag_completion.go @@ -83,8 +83,11 @@ func registerFlagCompletion(c *cobra.Command, f *pflag.Flag) { } } +// netInterfaces lists the network interfaces; a variable so the tests can make it fail. +var netInterfaces = net.Interfaces + func completeInterfaces(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) { - ifaces, err := net.Interfaces() + ifaces, err := netInterfaces() if err != nil { return nil, cobra.ShellCompDirectiveNoFileComp } diff --git a/cmd/flag_completion_test.go b/cmd/flag_completion_test.go index 42d266b..5139308 100644 --- a/cmd/flag_completion_test.go +++ b/cmd/flag_completion_test.go @@ -3,7 +3,9 @@ package cmd import ( + "errors" "fmt" + "net" "regexp" "slices" "strings" @@ -110,3 +112,35 @@ func TestEveryValueFlagCompletes(t *testing.T) { } walk(rootCmd) } + +func TestCompleteInterfaceFlag(t *testing.T) { + ifaces, err := net.Interfaces() + if err != nil { + t.Fatalf("net.Interfaces: %v", err) + } + want := make([]string, 0, len(ifaces)) + for _, i := range ifaces { + want = append(want, i.Name) + } + got, directive := complete(t, "discover", "--interface", "") + if !slices.Equal(got, want) { + t.Fatalf("--interface candidates %v, want %v", got, want) + } + if want := fmt.Sprintf(":%d", cobra.ShellCompDirectiveNoFileComp); directive != want { + t.Fatalf("--interface directive %q, want %q", directive, want) + } +} + +func TestCompleteInterfacesError(t *testing.T) { + saved := netInterfaces + t.Cleanup(func() { netInterfaces = saved }) + netInterfaces = func() ([]net.Interface, error) { return nil, errors.New("no interfaces") } + + got, directive := completeInterfaces(nil, nil, "") + if got != nil { + t.Fatalf("candidates %v on error, want none", got) + } + if directive != cobra.ShellCompDirectiveNoFileComp { + t.Fatalf("directive %v on error, want %v", directive, cobra.ShellCompDirectiveNoFileComp) + } +}