mirror of
https://github.com/spf13/cobra
synced 2025-04-27 17:17:20 +00:00
Merge 2b6e651ee4
into 283e32d889
This commit is contained in:
commit
9ede36eb73
2 changed files with 44 additions and 4 deletions
6
cobra.go
6
cobra.go
|
@ -20,7 +20,6 @@ package cobra
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
|
||||||
"reflect"
|
"reflect"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
@ -229,11 +228,10 @@ func stringInSlice(a string, list []string) bool {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing.
|
// CheckErr prints the msg with the prefix 'panic:' and exits with code != 0. If the msg is nil, it does nothing.
|
||||||
func CheckErr(msg interface{}) {
|
func CheckErr(msg interface{}) {
|
||||||
if msg != nil {
|
if msg != nil {
|
||||||
fmt.Fprintln(os.Stderr, "Error:", msg)
|
panic(msg)
|
||||||
os.Exit(1)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -15,6 +15,7 @@
|
||||||
package cobra
|
package cobra
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"testing"
|
"testing"
|
||||||
"text/template"
|
"text/template"
|
||||||
)
|
)
|
||||||
|
@ -40,3 +41,44 @@ func TestAddTemplateFunctions(t *testing.T) {
|
||||||
t.Errorf("Expected UsageString: %v\nGot: %v", expected, got)
|
t.Errorf("Expected UsageString: %v\nGot: %v", expected, got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCheckErr(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
msg interface{}
|
||||||
|
panic bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "no error",
|
||||||
|
msg: nil,
|
||||||
|
panic: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "panic string",
|
||||||
|
msg: "test",
|
||||||
|
panic: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "panic error",
|
||||||
|
msg: errors.New("test error"),
|
||||||
|
panic: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
defer func() {
|
||||||
|
r := recover()
|
||||||
|
if r != nil {
|
||||||
|
if !tt.panic {
|
||||||
|
t.Error("Didn't expect panic")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if tt.panic {
|
||||||
|
t.Error("Expected to panic")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
CheckErr(tt.msg)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue