2017-08-10 13:35:58 +00:00
|
|
|
package log
|
|
|
|
|
|
|
|
import (
|
2017-08-24 08:50:16 +00:00
|
|
|
"bytes"
|
2017-09-01 18:44:50 +00:00
|
|
|
"io/ioutil"
|
2017-08-10 13:35:58 +00:00
|
|
|
"testing"
|
2017-08-24 08:50:16 +00:00
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/log"
|
2017-09-01 18:44:50 +00:00
|
|
|
"github.com/stretchr/testify/require"
|
2017-08-24 08:50:16 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
trace = "trace log message\n"
|
|
|
|
debug = "debug log message\n"
|
|
|
|
info = "info log message\n"
|
|
|
|
warn = "warning log message\n"
|
|
|
|
err = "error log message\n"
|
2017-08-10 13:35:58 +00:00
|
|
|
)
|
|
|
|
|
2017-08-24 08:50:16 +00:00
|
|
|
func TestLogLevels(t *testing.T) {
|
|
|
|
var tests = []struct {
|
|
|
|
lvl log.Lvl
|
|
|
|
out string
|
|
|
|
}{
|
|
|
|
{log.LvlTrace, trace + debug + info + warn + err},
|
|
|
|
{log.LvlDebug, debug + info + warn + err},
|
|
|
|
{log.LvlInfo, info + warn + err},
|
|
|
|
{log.LvlWarn, warn + err},
|
|
|
|
{log.LvlError, err},
|
|
|
|
}
|
|
|
|
|
|
|
|
var buf bytes.Buffer
|
2017-10-20 09:06:22 +00:00
|
|
|
// log-compatible handler that writes log in the buffer
|
2017-08-24 08:50:16 +00:00
|
|
|
handler := log.FuncHandler(func(r *log.Record) error {
|
|
|
|
_, err := buf.Write([]byte(r.Msg))
|
|
|
|
return err
|
|
|
|
})
|
|
|
|
for _, test := range tests {
|
|
|
|
buf.Reset()
|
|
|
|
|
|
|
|
setHandler(test.lvl, handler)
|
2017-08-10 13:35:58 +00:00
|
|
|
|
2017-08-24 08:50:16 +00:00
|
|
|
Trace(trace)
|
|
|
|
Debug(debug)
|
|
|
|
Info(info)
|
|
|
|
Warn(warn)
|
|
|
|
Error(err)
|
2017-08-10 13:35:58 +00:00
|
|
|
|
2017-09-01 18:44:50 +00:00
|
|
|
require.Equal(t, test.out, buf.String())
|
2017-08-24 08:50:16 +00:00
|
|
|
}
|
2017-08-10 13:35:58 +00:00
|
|
|
}
|
2017-09-01 18:44:50 +00:00
|
|
|
|
|
|
|
func TestLogFile(t *testing.T) {
|
|
|
|
file, err := ioutil.TempFile("", "statusim_log_test")
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
2017-10-20 09:06:22 +00:00
|
|
|
defer file.Close() //nolint: errcheck
|
2017-09-01 18:44:50 +00:00
|
|
|
|
|
|
|
// setup log
|
|
|
|
SetLevel("INFO")
|
2017-10-20 09:06:22 +00:00
|
|
|
err = SetLogFile(file.Name())
|
|
|
|
require.NoError(t, err)
|
2017-09-01 18:44:50 +00:00
|
|
|
|
|
|
|
// test log output to file
|
|
|
|
Info(info)
|
|
|
|
Debug(debug)
|
|
|
|
|
|
|
|
data, err := ioutil.ReadAll(file)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
got := string(data)
|
|
|
|
require.Contains(t, got, info)
|
|
|
|
require.NotContains(t, got, debug)
|
|
|
|
}
|