From 3950cdc37c294ce06f873228ac96ad30b3876a2f Mon Sep 17 00:00:00 2001 From: Hugo Hromic Date: Thu, 27 Jun 2024 00:02:41 +0100 Subject: [PATCH] Fix crash on errors in package-level `MustParse` --- parse.go | 5 ++++- parse_test.go | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/parse.go b/parse.go index 251b005..0d92df9 100644 --- a/parse.go +++ b/parse.go @@ -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 diff --git a/parse_test.go b/parse_test.go index fe055fe..07af7ed 100644 --- a/parse_test.go +++ b/parse_test.go @@ -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"`