Skip to content

Commit

Permalink
Merge pull request #1990 from dearchap/add_test_cov_2
Browse files Browse the repository at this point in the history
Add more tests for map
  • Loading branch information
dearchap authored Oct 24, 2024
2 parents 4770e1d + fb6aad2 commit 1540997
Show file tree
Hide file tree
Showing 10 changed files with 159 additions and 37 deletions.
28 changes: 28 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3990,6 +3990,34 @@ func TestCommandInvalidName(t *testing.T) {
assert.Equal(t, []string(nil), cmd.StringSlice("foo"))
}

func TestCommandCategories(t *testing.T) {
var cc commandCategories = []*commandCategory{
{
name: "foo",
commands: []*Command{},
},
{
name: "bar",
commands: []*Command{},
},
{
name: "goo",
commands: nil,
},
}

sort.Sort(&cc)

var prev *commandCategory
for _, c := range cc {
if prev != nil {
assert.LessOrEqual(t, prev.name, c.name)
}
prev = c
assert.Equal(t, []*Command(nil), c.VisibleCommands())
}
}

func TestJSONExportCommand(t *testing.T) {
cmd := buildExtendedTestCommand()
cmd.Arguments = []Argument{
Expand Down
39 changes: 38 additions & 1 deletion completion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cli

import (
"bytes"
"fmt"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -98,11 +99,47 @@ func TestCompletionSubcommand(t *testing.T) {
)
}

type mockWriter struct {
err error
}

func (mw *mockWriter) Write(p []byte) (int, error) {
if mw.err != nil {
return 0, mw.err
}
return len(p), nil
}

func TestCompletionInvalidShell(t *testing.T) {
cmd := &Command{
EnableShellCompletion: true,
}

err := cmd.Run(buildTestContext(t), []string{"foo", completionCommandName, "junky-sheell"})
unknownShellName := "junky-sheell"
err := cmd.Run(buildTestContext(t), []string{"foo", completionCommandName, unknownShellName})
assert.ErrorContains(t, err, "unknown shell junky-sheell")

enableError := true
shellCompletions[unknownShellName] = func(c *Command) (string, error) {
if enableError {
return "", fmt.Errorf("cant do completion")
}
return "something", nil
}
defer func() {
delete(shellCompletions, unknownShellName)
}()

err = cmd.Run(buildTestContext(t), []string{"foo", completionCommandName, unknownShellName})
assert.ErrorContains(t, err, "cant do completion")

// now disable shell completion error
enableError = false
c := cmd.Command(completionCommandName)
assert.NotNil(t, c)
c.Writer = &mockWriter{
err: fmt.Errorf("writer error"),
}
err = cmd.Run(buildTestContext(t), []string{"foo", completionCommandName, unknownShellName})
assert.ErrorContains(t, err, "writer error")
}
4 changes: 0 additions & 4 deletions fish.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,6 @@ func (cmd *Command) writeFishCompletionTemplate(w io.Writer) error {
func (cmd *Command) prepareFishCommands(commands []*Command, allCommands *[]string, previousCommands []string) []string {
completions := []string{}
for _, command := range commands {
if command.Hidden {
continue
}

var completion strings.Builder
completion.WriteString(fmt.Sprintf(
"complete -r -c %s -n '%s' -a '%s'",
Expand Down
24 changes: 20 additions & 4 deletions fish_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,33 @@ package cli
import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestFishCompletion(t *testing.T) {
// Given
cmd := buildExtendedTestCommand()
cmd.Flags = append(cmd.Flags, &StringFlag{
Name: "logfile",
TakesFile: true,
})
cmd.Flags = append(cmd.Flags,
&StringFlag{
Name: "logfile",
TakesFile: true,
},
&StringSliceFlag{
Name: "foofile",
TakesFile: true,
})

oldTemplate := FishCompletionTemplate
defer func() { FishCompletionTemplate = oldTemplate }()
FishCompletionTemplate = "{{something"

// test error case
_, err1 := cmd.ToFishCompletion()
assert.Error(t, err1)

// reset the template
FishCompletionTemplate = oldTemplate
// When
res, err := cmd.ToFishCompletion()

Expand Down
10 changes: 2 additions & 8 deletions flag_bool.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,17 +71,11 @@ func (b *boolValue) Set(s string) error {
func (b *boolValue) Get() interface{} { return *b.destination }

func (b *boolValue) String() string {
if b.destination != nil {
return strconv.FormatBool(*b.destination)
}
return strconv.FormatBool(false)
return strconv.FormatBool(*b.destination)
}

func (b *boolValue) IsBoolFlag() bool { return true }

func (b *boolValue) Count() int {
if b.count != nil {
return *b.count
}
return 0
return *b.count
}
13 changes: 3 additions & 10 deletions flag_bool_with_inverse.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,7 @@ func (parent *BoolWithInverseFlag) RunAction(ctx context.Context, cmd *Command)
}

if *parent.negDest {
err := cmd.Set(parent.positiveFlag.Name, "false")
if err != nil {
return err
}
_ = cmd.Set(parent.positiveFlag.Name, "false")
}

if parent.BoolFlag.Action != nil {
Expand Down Expand Up @@ -116,16 +113,12 @@ func (parent *BoolWithInverseFlag) initialize() {
}

func (parent *BoolWithInverseFlag) inverseName() string {
if parent.InversePrefix == "" {
parent.InversePrefix = DefaultInverseBoolPrefix
}

return parent.InversePrefix + parent.BoolFlag.Name
return parent.inversePrefix() + parent.BoolFlag.Name
}

func (parent *BoolWithInverseFlag) inversePrefix() string {
if parent.InversePrefix == "" {
return DefaultInverseBoolPrefix
parent.InversePrefix = DefaultInverseBoolPrefix
}

return parent.InversePrefix
Expand Down
21 changes: 16 additions & 5 deletions flag_bool_with_inverse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,18 @@ func TestBoolWithInverseEnvVars(t *testing.T) {
"NO-ENV": "true",
},
},
{
err: fmt.Errorf("could not parse \"true_env\" as bool value from environment variable \"ENV\" for flag env: parse error"),
envVars: map[string]string{
"ENV": "true_env",
},
},
{
err: fmt.Errorf("could not parse \"false_env\" as bool value from environment variable \"NO-ENV\" for flag no-env: parse error"),
envVars: map[string]string{
"NO-ENV": "false_env",
},
},
}

err := runBoolWithInverseFlagTests(t, flagMethod, testCases)
Expand Down Expand Up @@ -391,11 +403,10 @@ func TestBoolWithInverseString(t *testing.T) {
expected: "--[nope-]env\t",
},
{
testName: "empty inverse prefix",
flagName: "env",
required: true,
inversePrefix: "",
expected: "--[no-]env\t",
testName: "empty inverse prefix",
flagName: "env",
required: true,
expected: "--[no-]env\t",
},
}

Expand Down
6 changes: 1 addition & 5 deletions flag_map_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,7 @@ func (i *MapBase[T, C, VC]) Set(value string) error {
if err := i.value.Set(value); err != nil {
return err
}
tmp, ok := i.value.Get().(T)
if !ok {
return fmt.Errorf("unable to cast %v", i.value)
}
(*i.dict)[key] = tmp
(*i.dict)[key] = i.value.Get().(T)
}

return nil
Expand Down
50 changes: 50 additions & 0 deletions flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"os"
"reflect"
"regexp"
"runtime"
"sort"
"strings"
"testing"
Expand Down Expand Up @@ -3077,3 +3078,52 @@ func TestFlagsByName(t *testing.T) {
prev = f
}
}

func TestNonStringMap(t *testing.T) {
type (
floatMap = MapBase[float64, NoConfig, floatValue]
)

p := map[string]float64{}

var fv floatValue

f := &floatMap{
value: &fv,
}

assert.Equal(t, map[string]float64{}, f.Value())
f.dict = &p
assert.Equal(t, map[string]float64{}, f.Value())
assert.Equal(t, "map[string]float64{}", f.String())

assert.ErrorContains(t, f.Set("invalid=value"), "ParseFloat")
}

func TestUnqouteUsage(t *testing.T) {
tests := []struct {
str string
expStr string
expUsage string
}{
{"foo", "", "foo"},
{"foo something", "", "foo something"},
{"foo `bar 11`", "bar 11", "foo bar 11"},
{"foo `bar 11` sobar", "bar 11", "foo bar 11 sobar"},
{"foo `bar 11", "", "foo `bar 11"},
}

for i, test := range tests {
t.Run(fmt.Sprintf("unquote %d", i), func(t *testing.T) {
str, usage := unquoteUsage(test.str)
assert.Equal(t, test.expStr, str)
assert.Equal(t, test.expUsage, usage)
})
}
}

func TestEnvHintWindows(t *testing.T) {
if runtime.GOOS == "windows" && os.Getenv("PSHOME") == "" {
assert.Equal(t, "something [%foo%, %bar%, %ss%]", withEnvHint([]string{"foo", "bar", "ss"}, "something"))
}
}
1 change: 1 addition & 0 deletions testdata/expected-fish-full.fish
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ complete -c greet -n '__fish_greet_no_subcommand' -l socket -s s -r -d 'some \'u
complete -c greet -n '__fish_greet_no_subcommand' -f -l flag -s fl -s f -r
complete -c greet -n '__fish_greet_no_subcommand' -f -l another-flag -s b -d 'another usage text'
complete -c greet -n '__fish_greet_no_subcommand' -l logfile -r
complete -c greet -n '__fish_greet_no_subcommand' -l foofile -r
complete -c greet -n '__fish_greet_no_subcommand' -f -l help -s h -d 'show help'
complete -c greet -n '__fish_greet_no_subcommand' -f -l version -s v -d 'print the version'
complete -c greet -n '__fish_seen_subcommand_from config c' -f -l help -s h -d 'show help'
Expand Down

0 comments on commit 1540997

Please sign in to comment.