certificates/api/log/log_test.go

80 lines
2.2 KiB
Go
Raw Permalink Normal View History

package log
import (
2022-11-17 22:54:58 +00:00
"net/http"
"net/http/httptest"
"testing"
"unsafe"
pkgerrors "github.com/pkg/errors"
2022-11-17 14:00:01 +00:00
"github.com/stretchr/testify/assert"
"github.com/smallstep/certificates/logging"
)
2022-11-17 22:54:58 +00:00
type stackTracedError struct{}
func (stackTracedError) Error() string {
return "a stacktraced error"
}
func (stackTracedError) StackTrace() pkgerrors.StackTrace {
f := struct{}{}
return pkgerrors.StackTrace{ // fake stacktrace
pkgerrors.Frame(unsafe.Pointer(&f)),
pkgerrors.Frame(unsafe.Pointer(&f)),
}
}
func TestError(t *testing.T) {
2022-11-17 22:54:58 +00:00
tests := []struct {
name string
2022-11-17 14:00:01 +00:00
error
2022-11-17 22:54:58 +00:00
rw http.ResponseWriter
isFieldCarrier bool
2022-11-17 14:00:01 +00:00
stepDebug bool
expectStackTrace bool
}{
2022-11-17 22:54:58 +00:00
{"noLogger", nil, nil, false, false, false},
{"noError", nil, logging.NewResponseLogger(httptest.NewRecorder()), true, false, false},
{"noErrorDebug", nil, logging.NewResponseLogger(httptest.NewRecorder()), true, true, false},
{"anError", assert.AnError, logging.NewResponseLogger(httptest.NewRecorder()), true, false, false},
{"anErrorDebug", assert.AnError, logging.NewResponseLogger(httptest.NewRecorder()), true, true, false},
{"stackTracedError", new(stackTracedError), logging.NewResponseLogger(httptest.NewRecorder()), true, true, true},
{"stackTracedErrorDebug", new(stackTracedError), logging.NewResponseLogger(httptest.NewRecorder()), true, true, true},
}
2022-11-17 22:54:58 +00:00
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.stepDebug {
2022-11-17 14:00:01 +00:00
t.Setenv("STEPDEBUG", "1")
} else {
t.Setenv("STEPDEBUG", "0")
}
2022-11-17 22:54:58 +00:00
Error(tt.rw, tt.error)
2022-11-17 14:00:01 +00:00
2022-11-17 22:54:58 +00:00
// return early if test case doesn't use logger
if !tt.isFieldCarrier {
return
}
2022-11-17 14:00:01 +00:00
2022-11-17 22:54:58 +00:00
fields := tt.rw.(logging.ResponseLogger).Fields()
// expect the error field to be (not) set and to be the same error that was fed to Error
if tt.error == nil {
2022-11-17 14:00:01 +00:00
assert.Nil(t, fields["error"])
} else {
2022-11-17 22:54:58 +00:00
assert.Same(t, tt.error, fields["error"])
2022-11-17 14:00:01 +00:00
}
2022-11-17 22:54:58 +00:00
// check if stack-trace is set when expected
if _, hasStackTrace := fields["stack-trace"]; tt.expectStackTrace && !hasStackTrace {
t.Error(`ResponseLogger["stack-trace"] not set`)
} else if !tt.expectStackTrace && hasStackTrace {
t.Error(`ResponseLogger["stack-trace"] was set`)
}
})
}
}