Skip to content

Commit

Permalink
Fix crash on errors in package-level MustParse
Browse files Browse the repository at this point in the history
  • Loading branch information
hhromic committed Jun 26, 2024
1 parent dfca71d commit 3950cdc
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
5 changes: 4 additions & 1 deletion parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,12 @@ var ErrVersion = errors.New("version requested by user")
// for monkey patching in example code
var mustParseExit = os.Exit

// for monkey patching in test code
var mustParseOut io.Writer = os.Stdout

// MustParse processes command line arguments and exits upon failure
func MustParse(dest ...interface{}) *Parser {
return mustParse(Config{Exit: mustParseExit}, dest...)
return mustParse(Config{Exit: mustParseExit, Out: mustParseOut}, dest...)
}

// mustParse is a helper that facilitates testing
Expand Down
15 changes: 15 additions & 0 deletions parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,21 @@ func TestMustParse(t *testing.T) {
assert.NotNil(t, parser)
}

func TestMustParseError(t *testing.T) {
var args struct {
Foo []string `default:""`
}
var exitCode int
var stdout bytes.Buffer
mustParseExit = func(code int) { exitCode = code }
mustParseOut = &stdout
os.Args = []string{"example"}
parser := MustParse(&args)
assert.Nil(t, parser)
assert.Equal(t, -1, exitCode)
assert.Contains(t, stdout.String(), "default values are not supported for slice or map fields")
}

func TestEnvironmentVariable(t *testing.T) {
var args struct {
Foo string `arg:"env"`
Expand Down

0 comments on commit 3950cdc

Please sign in to comment.