Просмотр исходного кода

fix handling of varargs in Errorf()

Fixes https://github.com/jcmturner/gokrb5/issues/162

Re-use Add() function that does what we need; pass varargs as a...

Also remove special-casing of empty varargs to aid readability, and
add a test.
Bryan Boreham 8 лет назад
Родитель
Сommit
c00b90f331
2 измененных файлов с 25 добавлено и 9 удалено
  1. 2 9
      krberror/error.go
  2. 23 0
      krberror/error_test.go

+ 2 - 9
krberror/error.go

@@ -45,17 +45,10 @@ func NewKrberror(et, s string) Krberror {
 // Errorf appends to or creates a new Krberror.
 func Errorf(err error, et, format string, a ...interface{}) Krberror {
 	if e, ok := err.(Krberror); ok {
-		if len(a) > 0 {
-			e.EText = append([]string{fmt.Sprintf("%s: "+format, et, a)}, e.EText...)
-			return e
-		}
-		e.EText = append([]string{fmt.Sprintf("%s: "+format, et)}, e.EText...)
+		e.Add(et, fmt.Sprintf(format, a...))
 		return e
 	}
-	if len(a) > 0 {
-		return NewErrorf(et, format+": %s", a, err)
-	}
-	return NewErrorf(et, format+": %s", err)
+	return NewErrorf(et, format+": %s", append(a, err)...)
 }
 
 // NewErrorf creates a new Krberror from a formatted string.

+ 23 - 0
krberror/error_test.go

@@ -0,0 +1,23 @@
+package krberror
+
+import (
+	"fmt"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestErrorf(t *testing.T) {
+	err := fmt.Errorf("an error")
+	var a Krberror
+	a = Errorf(err, "cause", "some text")
+	assert.Equal(t, "[Root cause: cause] cause: some text: an error", a.Error())
+	a = Errorf(err, "cause", "arg1=%d arg2=%s", 123, "arg")
+	assert.Equal(t, "[Root cause: cause] cause: arg1=123 arg2=arg: an error", a.Error())
+
+	err = NewErrorf("another error", "some text")
+	a = Errorf(err, "cause", "some text")
+	assert.Equal(t, "[Root cause: another error] cause: some text < another error: some text", a.Error())
+	a = Errorf(err, "cause", "arg1=%d arg2=%s", 123, "arg")
+	assert.Equal(t, "[Root cause: another error] cause: arg1=123 arg2=arg < another error: some text", a.Error())
+}