Skip to content

Commit

Permalink
Add tests for flag completion in Go
Browse files Browse the repository at this point in the history
Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
  • Loading branch information
marckhouzam committed Feb 28, 2020
1 parent 93b505d commit 63c08bd
Showing 1 changed file with 85 additions and 0 deletions.
85 changes: 85 additions & 0 deletions custom_completions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,3 +262,88 @@ func TestNoValidArgsFuncInScript(t *testing.T) {

checkOmit(t, output, "has_completion_function=1")
}

func TestFlagCompletionInGo(t *testing.T) {
rootCmd := &Command{
Use: "root",
Run: emptyRun,
}
rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")
rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) {
completions := []string{}
for _, comp := range []string{"1", "2", "10"} {
if strings.HasPrefix(comp, toComplete) {
completions = append(completions, comp)
}
}
return completions, BashCompDirectiveDefault
})
rootCmd.Flags().String("filename", "", "Enter a filename")
rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective) {
completions := []string{}
for _, comp := range []string{"file.yaml", "myfile.json", "file.xml"} {
if strings.HasPrefix(comp, toComplete) {
completions = append(completions, comp)
}
}
return completions, BashCompDirectiveNoSpace | BashCompDirectiveNoFileComp
})

// Test completing an empty string
output, err := executeCommand(rootCmd, CompRequestCmd, "--introot", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

expected := `1
2
10
:0
`
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}

// Check completing with a prefix
output, err = executeCommand(rootCmd, CompRequestCmd, "--introot", "1")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

expected = `1
10
:0
`
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}

// Test completing an empty string
output, err = executeCommand(rootCmd, CompRequestCmd, "--filename", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

expected = `file.yaml
myfile.json
file.xml
:6
`
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}

// Check completing with a prefix
output, err = executeCommand(rootCmd, CompRequestCmd, "--filename", "f")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

expected = `file.yaml
file.xml
:6
`
if output != expected {
t.Errorf("expected: %q, got: %q", expected, output)
}
}

0 comments on commit 63c08bd

Please sign in to comment.