Refactor and improve tests for RunnerTextFormatter

parent b9e53794
......@@ -6,6 +6,7 @@ import (
"sort"
"github.com/sirupsen/logrus"
"gitlab.com/gitlab-org/gitlab-runner/helpers"
)
......@@ -20,57 +21,85 @@ type RunnerTextFormatter struct {
}
func (f *RunnerTextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
var keys = make([]string, 0, len(entry.Data))
for k := range entry.Data {
keys = append(keys, k)
}
if !f.DisableSorting {
sort.Strings(keys)
}
b := bytes.Buffer{}
f.printColored(&b, entry, keys)
b := new(bytes.Buffer)
f.printColored(b, entry)
b.WriteByte('\n')
return b.Bytes(), nil
}
func (f *RunnerTextFormatter) printColored(b *bytes.Buffer, entry *logrus.Entry, keys []string) {
var levelColor, levelText string
switch entry.Level {
case logrus.DebugLevel:
levelColor = helpers.ANSI_BOLD_WHITE
case logrus.WarnLevel:
levelColor = helpers.ANSI_YELLOW
levelText = "WARNING: "
case logrus.ErrorLevel:
levelColor = helpers.ANSI_BOLD_RED
levelText = "ERROR: "
case logrus.FatalLevel:
levelColor = helpers.ANSI_BOLD_RED
levelText = "FATAL: "
case logrus.PanicLevel:
levelColor = helpers.ANSI_BOLD_RED
levelText = "PANIC: "
default:
func (f *RunnerTextFormatter) printColored(b *bytes.Buffer, entry *logrus.Entry) {
levelColor, resetColor, levelPrefix := f.getColorsAndPrefix(entry)
indentLength := 50 - len(levelPrefix)
fmt.Fprintf(b, "%s%s%-*s%s ", levelColor, levelPrefix, indentLength, entry.Message, resetColor)
for _, k := range f.prepareKeys(entry) {
v := entry.Data[k]
fmt.Fprintf(b, " %s%s%s=%v", levelColor, k, resetColor, v)
}
}
func (f *RunnerTextFormatter) getColorsAndPrefix(entry *logrus.Entry) (string, string, string) {
definitions := map[logrus.Level]struct {
color string
prefix string
}{
logrus.DebugLevel: {
color: helpers.ANSI_BOLD_WHITE,
},
logrus.WarnLevel: {
color: helpers.ANSI_YELLOW,
prefix: "WARNING: ",
},
logrus.ErrorLevel: {
color: helpers.ANSI_BOLD_RED,
prefix: "ERROR: ",
},
logrus.FatalLevel: {
color: helpers.ANSI_BOLD_RED,
prefix: "FATAL: ",
},
logrus.PanicLevel: {
color: helpers.ANSI_BOLD_RED,
prefix: "PANIC: ",
},
}
resetColor := helpers.ANSI_RESET
color := ""
prefix := ""
definition, ok := definitions[entry.Level]
if ok {
if definition.color != "" {
color = definition.color
}
if definition.prefix != "" {
prefix = definition.prefix
}
}
if f.DisableColors {
levelColor = ""
resetColor = ""
return "", "", prefix
}
indentLength := 50 - len(levelText)
return color, helpers.ANSI_RESET, prefix
}
fmt.Fprintf(b, "%s%s%-*s%s ", levelColor, levelText, indentLength, entry.Message, resetColor)
for _, k := range keys {
v := entry.Data[k]
fmt.Fprintf(b, " %s%s%s=%v", levelColor, k, resetColor, v)
func (f *RunnerTextFormatter) prepareKeys(entry *logrus.Entry) []string {
keys := make([]string, 0, len(entry.Data))
for k := range entry.Data {
keys = append(keys, k)
}
if !f.DisableSorting {
sort.Strings(keys)
}
return keys
}
func SetRunnerFormatter() {
logrus.SetFormatter(&RunnerTextFormatter{})
logrus.SetFormatter(new(RunnerTextFormatter))
}
package log
import (
"fmt"
"io/ioutil"
"testing"
"github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gitlab.com/gitlab-org/gitlab-runner/helpers"
)
func newNullLogger(formatter logrus.Formatter, level logrus.Level) *logrus.Logger {
logger := logrus.New()
logger.SetOutput(ioutil.Discard)
logger.SetFormatter(formatter)
logger.SetLevel(level)
return logger
}
type colorsAndPrefixesTestCase struct {
expectedPrefix string
expectedColorCode string
}
func TestRunnerTextFormatter_ColorsAndPrefixes(t *testing.T) {
logrus.RegisterExitHandler(func() {
panic("Fatal logged")
})
key := "key"
value := "value"
fields := logrus.Fields{
key: value,
}
tests := map[logrus.Level]colorsAndPrefixesTestCase{
logrus.PanicLevel: {
expectedPrefix: "PANIC: ",
expectedColorCode: helpers.ANSI_BOLD_RED,
},
// Fatal is skipped by purpose
//
// There is no way to disable or overwrite the `Exit(1)` called by logrus
// at the end of `Fatal` logger. We have our helpers.MakeFatalToPanic
// hook, but in this case it is unusable: hooks are fired before the formatting
// is done, and this is what we would like to test.
//
// We just need to assume, that if all other levels are working properly, then
// `Fatal` will also work. In the end, it's just another entry in the prefix/color
// choosing method.
logrus.ErrorLevel: {
expectedPrefix: "ERROR: ",
expectedColorCode: helpers.ANSI_BOLD_RED,
},
logrus.WarnLevel: {
expectedPrefix: "WARNING: ",
expectedColorCode: helpers.ANSI_YELLOW,
},
logrus.InfoLevel: {},
logrus.DebugLevel: {
expectedColorCode: helpers.ANSI_BOLD_WHITE,
},
}
for level, testCase := range tests {
for _, colored := range []bool{true, false} {
t.Run(fmt.Sprintf("%s-level colored-%v", level.String(), colored), func(t *testing.T) {
formatter := new(RunnerTextFormatter)
formatter.DisableColors = !colored
logger := newNullLogger(formatter, logrus.DebugLevel)
hook := test.NewLocal(logger)
defer testOutputColoringAndPrefix(t, key, value, testCase, colored, hook)
levels := map[logrus.Level]func(args ...interface{}){
logrus.PanicLevel: logger.WithFields(fields).Panic,
logrus.ErrorLevel: logger.WithFields(fields).Error,
logrus.WarnLevel: logger.WithFields(fields).Warning,
logrus.InfoLevel: logger.WithFields(fields).Info,
logrus.DebugLevel: logger.WithFields(fields).Debug,
}
levelLogger, ok := levels[level]
require.True(t, ok, "Unknown level %v used", level)
levelLogger("test message")
})
}
}
}
func testOutputColoringAndPrefix(t *testing.T, key string, value string, testCase colorsAndPrefixesTestCase, colored bool, hook *test.Hook) {
recover()
entry := hook.LastEntry()
require.NotNil(t, entry)
logrusOutput, err := entry.String()
require.NoError(t, err)
if testCase.expectedPrefix != "" {
assert.Contains(t, logrusOutput, testCase.expectedPrefix)
}
if colored {
if testCase.expectedColorCode != "" {
assert.Contains(t, logrusOutput, testCase.expectedColorCode, "Should contain color code")
}
assert.Contains(t, logrusOutput, helpers.ANSI_RESET, "Should contain reset color code")
assert.Contains(t, logrusOutput, fmt.Sprintf("%s%s%s=%s", testCase.expectedColorCode, key, helpers.ANSI_RESET, value), "Should color field key")
} else {
if testCase.expectedColorCode != "" {
assert.NotContains(t, logrusOutput, testCase.expectedColorCode, "Shouldn't contain color code")
}
assert.NotContains(t, logrusOutput, helpers.ANSI_RESET, "Shouldn't contain reset color code")
assert.Contains(t, logrusOutput, fmt.Sprintf("%s=%s", key, value), "Shouldn't color field key")
}
}
func TestRunnerTextFormatter_KeysSorting(t *testing.T) {
fields := logrus.Fields{
"aza": "v",
"zzz": "v",
"zaz": "v",
"aaa": "v",
}
formatter := new(RunnerTextFormatter)
formatter.DisableColors = true
formatter.DisableSorting = false
logger := newNullLogger(formatter, logrus.InfoLevel)
hook := test.NewLocal(logger)
for i := 0; i <= 2; i++ {
logger.WithFields(fields).Info("test message")
entry := hook.LastEntry()
require.NotNil(t, entry)
logrusOutput, err := entry.String()
require.NoError(t, err)
assert.Contains(t, logrusOutput, " aaa=v aza=v zaz=v zzz=v")
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment