logrus/hooks/test/test_test.go

86 lines
1.8 KiB
Go
Raw Normal View History

2015-05-13 15:14:34 +03:00
package test
import (
2018-07-20 14:16:19 +03:00
"math/rand"
"sync"
2015-05-13 15:14:34 +03:00
"testing"
2018-07-20 14:16:19 +03:00
"time"
2015-05-13 15:14:34 +03:00
2017-05-19 15:00:16 +03:00
"github.com/sirupsen/logrus"
2015-05-13 15:14:34 +03:00
"github.com/stretchr/testify/assert"
)
func TestAllHooks(t *testing.T) {
assert := assert.New(t)
logger, hook := NewNullLogger()
2015-10-09 17:07:14 +03:00
assert.Nil(hook.LastEntry())
assert.Equal(0, len(hook.Entries))
2015-05-13 15:14:34 +03:00
logger.Error("Hello error")
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
assert.Equal("Hello error", hook.LastEntry().Message)
assert.Equal(1, len(hook.Entries))
logger.Warn("Hello warning")
assert.Equal(logrus.WarnLevel, hook.LastEntry().Level)
assert.Equal("Hello warning", hook.LastEntry().Message)
assert.Equal(2, len(hook.Entries))
hook.Reset()
2015-10-09 17:07:14 +03:00
assert.Nil(hook.LastEntry())
2015-05-13 15:14:34 +03:00
assert.Equal(0, len(hook.Entries))
hook = NewGlobal()
logrus.Error("Hello error")
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
assert.Equal("Hello error", hook.LastEntry().Message)
assert.Equal(1, len(hook.Entries))
}
func TestLoggingWithHooksRace(t *testing.T) {
2018-07-20 14:16:19 +03:00
rand.Seed(time.Now().Unix())
unlocker := rand.Int() % 100
assert := assert.New(t)
logger, hook := NewNullLogger()
2018-07-20 14:16:19 +03:00
var wgOne, wgAll sync.WaitGroup
wgOne.Add(1)
wgAll.Add(100)
for i := 0; i < 100; i++ {
2018-07-20 14:16:19 +03:00
go func(i int) {
logger.Info("info")
2018-07-20 14:16:19 +03:00
wgAll.Done()
if i == unlocker {
wgOne.Done()
}
}(i)
}
2018-07-20 14:16:19 +03:00
wgOne.Wait()
assert.Equal(logrus.InfoLevel, hook.LastEntry().Level)
assert.Equal("info", hook.LastEntry().Message)
2018-07-20 14:16:19 +03:00
wgAll.Wait()
entries := hook.AllEntries()
assert.Equal(100, len(entries))
2015-05-13 15:14:34 +03:00
}
func TestFatalWithAlternateExit(t *testing.T) {
assert := assert.New(t)
logger, hook := NewNullLogger()
logger.ExitFunc = func(code int) {}
logger.Fatal("something went very wrong")
assert.Equal(logrus.FatalLevel, hook.LastEntry().Level)
assert.Equal("something went very wrong", hook.LastEntry().Message)
assert.Equal(1, len(hook.Entries))
}