Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion cmd/flag_completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
34 changes: 34 additions & 0 deletions cmd/flag_completion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
package cmd

import (
"errors"
"fmt"
"net"
"regexp"
"slices"
"strings"
Expand Down Expand Up @@ -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)
}
}
Loading