[TASK] add test to log hook output

This commit is contained in:
Martin Geno 2017-06-14 23:52:38 +02:00
parent 5aff5e58fa
commit 8ca34866fd
No known key found for this signature in database
GPG Key ID: F0D39A37E925E941
3 changed files with 77 additions and 5 deletions

View File

@ -4,6 +4,7 @@ package output
import (
"fmt"
"io"
"os"
"time"
@ -16,6 +17,8 @@ var (
TimeFormat = "2006-01-02 15:04:05"
ShowTime = true
AboveLevel = log.InfoLevel
errOutput io.Writer = os.Stderr
output io.Writer = os.Stdout
)
// logger for output
@ -76,9 +79,9 @@ func (l *Logger) Hook(e *log.Entry) {
text := fmt.Sprintf(format, v...)
if e.Level > log.WarnLevel {
os.Stderr.WriteString(text)
errOutput.Write([]byte(text))
} else {
os.Stdout.WriteString(text)
output.Write([]byte(text))
}
}

View File

@ -1 +1,69 @@
package output
import (
"bytes"
"os"
"testing"
"github.com/genofire/logmania/log"
"github.com/stretchr/testify/assert"
)
func captureOutput(f func()) (string, string) {
var bufErrOutput bytes.Buffer
var bufOutput bytes.Buffer
errOutput = &bufErrOutput
output = &bufOutput
f()
errOutput = os.Stderr
output = os.Stdout
return bufOutput.String(), bufErrOutput.String()
}
// Warning: colors are not tested (it should be in the imported package)
func TestOutput(t *testing.T) {
assert := assert.New(t)
assert.True(true)
out, err := captureOutput(func() {
log.Info("test")
})
assert.Regexp("-.*\\[.{5}Info.{4}\\] test", out)
assert.Equal("", err)
ShowTime = false
out, err = captureOutput(func() {
log.Warn("test")
})
assert.Regexp("\\[.{5}Warn.{4}\\] test", out)
assert.NotRegexp("-.*\\[.{5}Warn.{4}\\] test", out)
assert.Equal("", err)
out, err = captureOutput(func() {
log.Error("test")
})
assert.Equal("", out)
assert.Regexp("\\[.{5}ERROR.{4}\\] test", err)
out, err = captureOutput(func() {
log.Debug("test")
})
assert.Equal("", out)
assert.Equal("", err)
AboveLevel = log.DebugLevel
out, err = captureOutput(func() {
log.New().AddField("a", 3).Debug("test")
})
assert.Regexp("\\[.{5}Debug.{4}\\] test .{8}(a=3)", out)
assert.Equal("", err)
log.RemoveLogger("output")
out, err = captureOutput(func() {
log.Info("test")
})
assert.Equal("", out)
assert.Equal("", err)
}

View File

@ -13,6 +13,7 @@ func AddLogger(name string, logger Logger) {
loggers[name] = logger
}
func RemoveLogger(name string) {
loggers[name].Close()
delete(loggers, name)
}