github.com/zaquestion/lab@v0.25.1/internal/logger/logger_test.go (about) 1 package logger 2 3 import ( 4 "bytes" 5 "io" 6 "os" 7 "regexp" 8 "testing" 9 10 "github.com/stretchr/testify/require" 11 ) 12 13 func TestGetInstance(t *testing.T) { 14 firstInstance := GetInstance() 15 secondInstance := GetInstance() 16 require.Equal(t, firstInstance, secondInstance) 17 } 18 19 func TestLogLevel(t *testing.T) { 20 log := GetInstance() 21 // Check default log level 22 require.Equal(t, LogLevelInfo, log.LogLevel()) 23 24 // Set invalid log level 25 err := log.SetLogLevel(100) 26 require.Error(t, err) 27 require.EqualError(t, err, "invalid log level") 28 err = log.SetLogLevel(-1) 29 require.Error(t, err) 30 require.EqualError(t, err, "invalid log level") 31 32 // Set a different and valid log level 33 err = log.SetLogLevel(LogLevelDebug) 34 require.NoError(t, err) 35 require.Equal(t, LogLevelDebug, log.LogLevel()) 36 } 37 38 func Test_addFileLinePrefix(t *testing.T) { 39 msg := addFileLinePrefix("test") 40 regex := regexp.MustCompile("testing.go:[0-9]+: test") 41 require.Regexp(t, regex, msg) 42 } 43 44 func TestLogFunctions(t *testing.T) { 45 type logFunc func(string, ...interface{}) 46 type logFuncf func(string, ...interface{}) 47 type logFuncln func(...interface{}) 48 49 log := GetInstance() 50 log.SetLogLevel(LogLevelDebug) 51 52 tests := []struct { 53 name string 54 prefix string 55 fn logFunc 56 fnf logFuncf 57 fnln logFuncln 58 }{ 59 { 60 name: "error", 61 prefix: "ERROR:", 62 fn: log.Error, 63 fnf: log.Errorf, 64 fnln: log.Errorln, 65 }, 66 { 67 name: "warn", 68 prefix: "WARNING:", 69 fn: log.Warn, 70 fnf: log.Warnf, 71 fnln: log.Warnln, 72 }, 73 { 74 name: "info", 75 prefix: "", 76 fn: log.Info, 77 fnf: log.Infof, 78 fnln: log.Infoln, 79 }, 80 { 81 name: "debug", 82 prefix: "DEBUG:", 83 fn: log.Debug, 84 fnf: log.Debugf, 85 fnln: log.Debugln, 86 }, 87 } 88 89 for _, test := range tests { 90 t.Run(test.name, func(t *testing.T) { 91 // Redirect system stdout to our own so we can check log output 92 // to stdout 93 oldStderr := os.Stderr 94 r, w, err := os.Pipe() 95 if err != nil { 96 t.Errorf("failed to redirect stderr: %s", err) 97 } 98 os.Stderr = w 99 log.SetStdDest(w) 100 outChan := make(chan string) 101 102 test.fn("test") 103 test.fnf("test\n") 104 test.fnln("test") 105 106 go func() { 107 var buf bytes.Buffer 108 io.Copy(&buf, r) 109 outChan <- buf.String() 110 }() 111 112 w.Close() 113 os.Stderr = oldStderr 114 out := <-outChan 115 116 regex := regexp.MustCompile(test.prefix + " logger_test.go:[0-9]+: test") 117 require.Regexp(t, regex, out) 118 }) 119 } 120 121 }