2022-03-22 12:31:18 +00:00
|
|
|
package log
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http/httptest"
|
2022-11-17 14:00:01 +00:00
|
|
|
"strconv"
|
2022-03-22 12:31:18 +00:00
|
|
|
"testing"
|
2022-11-17 11:29:54 +00:00
|
|
|
"unsafe"
|
|
|
|
|
|
|
|
pkgerrors "github.com/pkg/errors"
|
2022-11-17 14:00:01 +00:00
|
|
|
"github.com/stretchr/testify/assert"
|
2022-03-22 12:31:18 +00:00
|
|
|
|
|
|
|
"github.com/smallstep/certificates/logging"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestError(t *testing.T) {
|
2022-11-17 14:00:01 +00:00
|
|
|
cases := []struct {
|
|
|
|
error
|
|
|
|
stepDebug bool
|
|
|
|
expectStackTrace bool
|
2022-03-22 12:31:18 +00:00
|
|
|
}{
|
2022-11-17 14:00:01 +00:00
|
|
|
0: {nil, false, false},
|
|
|
|
1: {nil, true, false},
|
|
|
|
2: {assert.AnError, false, false},
|
|
|
|
3: {assert.AnError, true, false},
|
|
|
|
4: {new(stackTracedError), false, false},
|
|
|
|
5: {new(stackTracedError), true, true},
|
2022-03-22 12:31:18 +00:00
|
|
|
}
|
|
|
|
|
2022-11-17 14:00:01 +00:00
|
|
|
for caseIndex := range cases {
|
|
|
|
kase := cases[caseIndex]
|
|
|
|
|
|
|
|
t.Run(strconv.Itoa(caseIndex), func(t *testing.T) {
|
|
|
|
if kase.stepDebug {
|
|
|
|
t.Setenv("STEPDEBUG", "1")
|
|
|
|
} else {
|
|
|
|
t.Setenv("STEPDEBUG", "0")
|
|
|
|
}
|
|
|
|
|
|
|
|
rw := logging.NewResponseLogger(httptest.NewRecorder())
|
|
|
|
Error(rw, kase.error)
|
|
|
|
|
|
|
|
fields := rw.Fields()
|
|
|
|
|
|
|
|
// expect the error field to be set and to be the same error that was fed to Error
|
|
|
|
if kase.error == nil {
|
|
|
|
assert.Nil(t, fields["error"])
|
|
|
|
} else {
|
|
|
|
assert.Same(t, kase.error, fields["error"])
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, hasStackTrace := fields["stack-trace"]; kase.expectStackTrace && !hasStackTrace {
|
|
|
|
t.Error("stack-trace was not set")
|
|
|
|
} else if !kase.expectStackTrace && hasStackTrace {
|
|
|
|
t.Error("stack-trace was set")
|
2022-11-17 11:29:54 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-17 14:00:01 +00:00
|
|
|
type stackTracedError struct{}
|
2022-11-17 11:29:54 +00:00
|
|
|
|
2022-11-17 14:00:01 +00:00
|
|
|
func (stackTracedError) Error() string {
|
2022-11-17 11:29:54 +00:00
|
|
|
return "a stacktraced error"
|
|
|
|
}
|
|
|
|
|
2022-11-17 14:00:01 +00:00
|
|
|
func (stackTracedError) StackTrace() pkgerrors.StackTrace {
|
2022-11-17 11:29:54 +00:00
|
|
|
f := struct{}{}
|
|
|
|
return pkgerrors.StackTrace{ // fake stacktrace
|
|
|
|
pkgerrors.Frame(unsafe.Pointer(&f)),
|
|
|
|
pkgerrors.Frame(unsafe.Pointer(&f)),
|
|
|
|
}
|
|
|
|
}
|