代码拉取完成,页面将自动刷新
package queuetest
import (
"bufio"
"flag"
"fmt"
"os"
"sync"
"testing"
"github.com/elastic/beats/libbeat/logp"
)
var debug bool
var printLog bool
type TestLogger struct {
t *testing.T
}
func init() {
flag.BoolVar(&debug, "debug", false, "enable test debug log")
flag.BoolVar(&printLog, "debug-print", false, "print test log messages right away")
}
type testLogWriter struct {
t *testing.T
}
func (w *testLogWriter) Write(p []byte) (int, error) {
w.t.Log(string(p))
return len(p), nil
}
func withLogOutput(fn func(*testing.T)) func(*testing.T) {
return func(t *testing.T) {
stderr := os.Stderr
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
defer r.Close()
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
t.Log(line)
if printLog {
stderr.WriteString(line)
stderr.WriteString("\n")
}
}
}()
os.Stderr = w
defer func() {
os.Stderr = stderr
w.Close()
wg.Wait()
}()
level := logp.LOG_INFO
if debug {
level = logp.LOG_DEBUG
}
logp.LogInit(level, "", false, true, []string{"*"})
fn(t)
}
}
// NewTestLogger creates a new logger interface,
// logging via t.Log/t.Logf. If `-debug` is given on command
// line, debug logs will be included.
// Run tests with `-debug-print`, to print log output to console right away.
// This guarantees logs are still written if the test logs are not printed due
// to a panic in the test itself.
//
// Capturing log output using the TestLogger, will make the
// log output correctly display with test test being run.
func NewTestLogger(t *testing.T) *TestLogger {
return &TestLogger{t}
}
func (l *TestLogger) Debug(vs ...interface{}) {
if debug {
l.t.Log(vs...)
print(vs)
}
}
func (l *TestLogger) Info(vs ...interface{}) {
l.t.Log(vs...)
print(vs)
}
func (l *TestLogger) Err(vs ...interface{}) {
l.t.Error(vs...)
print(vs)
}
func (l *TestLogger) Debugf(format string, v ...interface{}) {
if debug {
l.t.Logf(format, v...)
printf(format, v)
}
}
func (l *TestLogger) Infof(format string, v ...interface{}) {
l.t.Logf(format, v...)
printf(format, v)
}
func (l *TestLogger) Errf(format string, v ...interface{}) {
l.t.Errorf(format, v...)
printf(format, v)
}
func print(vs []interface{}) {
if printLog {
fmt.Println(vs...)
}
}
func printf(format string, vs []interface{}) {
if printLog {
fmt.Printf(format, vs...)
if format[len(format)-1] != '\n' {
fmt.Println("")
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。