...

Source file src/github.com/sirupsen/logrus/hooks/test/test_test.go

Documentation: github.com/sirupsen/logrus/hooks/test

     1  package test
     2  
     3  import (
     4  	"math/rand"
     5  	"sync"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/sirupsen/logrus"
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  func TestAllHooks(t *testing.T) {
    14  	assert := assert.New(t)
    15  
    16  	logger, hook := NewNullLogger()
    17  	assert.Nil(hook.LastEntry())
    18  	assert.Equal(0, len(hook.Entries))
    19  
    20  	logger.Error("Hello error")
    21  	assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
    22  	assert.Equal("Hello error", hook.LastEntry().Message)
    23  	assert.Equal(1, len(hook.Entries))
    24  
    25  	logger.Warn("Hello warning")
    26  	assert.Equal(logrus.WarnLevel, hook.LastEntry().Level)
    27  	assert.Equal("Hello warning", hook.LastEntry().Message)
    28  	assert.Equal(2, len(hook.Entries))
    29  
    30  	hook.Reset()
    31  	assert.Nil(hook.LastEntry())
    32  	assert.Equal(0, len(hook.Entries))
    33  
    34  	hook = NewGlobal()
    35  
    36  	logrus.Error("Hello error")
    37  	assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
    38  	assert.Equal("Hello error", hook.LastEntry().Message)
    39  	assert.Equal(1, len(hook.Entries))
    40  }
    41  
    42  func TestLoggingWithHooksRace(t *testing.T) {
    43  
    44  	rand.Seed(time.Now().Unix())
    45  	unlocker := rand.Int() % 100
    46  
    47  	assert := assert.New(t)
    48  	logger, hook := NewNullLogger()
    49  
    50  	var wgOne, wgAll sync.WaitGroup
    51  	wgOne.Add(1)
    52  	wgAll.Add(100)
    53  
    54  	for i := 0; i < 100; i++ {
    55  		go func(i int) {
    56  			logger.Info("info")
    57  			wgAll.Done()
    58  			if i == unlocker {
    59  				wgOne.Done()
    60  			}
    61  		}(i)
    62  	}
    63  
    64  	wgOne.Wait()
    65  
    66  	assert.Equal(logrus.InfoLevel, hook.LastEntry().Level)
    67  	assert.Equal("info", hook.LastEntry().Message)
    68  
    69  	wgAll.Wait()
    70  
    71  	entries := hook.AllEntries()
    72  	assert.Equal(100, len(entries))
    73  }
    74  
    75  func TestFatalWithAlternateExit(t *testing.T) {
    76  	assert := assert.New(t)
    77  
    78  	logger, hook := NewNullLogger()
    79  	logger.ExitFunc = func(code int) {}
    80  
    81  	logger.Fatal("something went very wrong")
    82  	assert.Equal(logrus.FatalLevel, hook.LastEntry().Level)
    83  	assert.Equal("something went very wrong", hook.LastEntry().Message)
    84  	assert.Equal(1, len(hook.Entries))
    85  }
    86  

View as plain text