Skip to content

Commit

Permalink
util/logutil: migrate to testify (#26322) (#28137)
Browse files Browse the repository at this point in the history
  • Loading branch information
ti-srebot authored Sep 17, 2021
1 parent 6b0c1a3 commit 51b88fe
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 71 deletions.
27 changes: 11 additions & 16 deletions util/logutil/hex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,48 +17,43 @@ import (
"bytes"
"encoding/hex"
"reflect"
"testing"

. "github.com/pingcap/check"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/stretchr/testify/require"

"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/util/logutil"
)

var _ = Suite(&testHexSuite{})

type testHexSuite struct{}

func (s *testHexSuite) SetUpSuite(c *C) {}

func (s *testHexSuite) SetUpTest(c *C) {}

func (s *testHexSuite) TestHex(c *C) {
func TestHex(t *testing.T) {
var region metapb.Region
region.Id = 6662
region.StartKey = []byte{'t', 200, '\\', 000, 000, 000, '\\', 000, 000, 000, 37, '-', 000, 000, 000, 000, 000, 000, 000, 37}
region.EndKey = []byte("3asg3asd")

c.Assert(logutil.Hex(&region).String(), Equals, "{Id:6662 StartKey:74c85c0000005c000000252d0000000000000025 EndKey:3361736733617364 RegionEpoch:<nil> Peers:[] EncryptionMeta:<nil>}")
expected := "{Id:6662 StartKey:74c85c0000005c000000252d0000000000000025 EndKey:3361736733617364 RegionEpoch:<nil> Peers:[] EncryptionMeta:<nil>}"
require.Equal(t, expected, logutil.Hex(&region).String())
}

func (s *testHexSuite) TestPrettyPrint(c *C) {
func TestPrettyPrint(t *testing.T) {
var buf bytes.Buffer

byteSlice := []byte("asd2fsdafs中文3af")
logutil.PrettyPrint(&buf, reflect.ValueOf(byteSlice))
c.Assert(buf.String(), Equals, "61736432667364616673e4b8ade69687336166")
c.Assert(buf.String(), Equals, hex.EncodeToString(byteSlice))
require.Equal(t, "61736432667364616673e4b8ade69687336166", buf.String())
require.Equal(t, hex.EncodeToString(byteSlice), buf.String())
buf.Reset()

// Go reflect can't distinguish uint8 from byte!
intSlice := []uint8{1, 2, 3, uint8('a'), uint8('b'), uint8('c'), uint8('\'')}
logutil.PrettyPrint(&buf, reflect.ValueOf(intSlice))
c.Assert(buf.String(), Equals, "01020361626327")
require.Equal(t, "01020361626327", buf.String())
buf.Reset()

var ran kv.KeyRange
ran.StartKey = kv.Key("_txxey23_i263")
ran.EndKey = nil
logutil.PrettyPrint(&buf, reflect.ValueOf(ran))
c.Assert(buf.String(), Equals, "{StartKey:5f747878657932335f69323633 EndKey:}")
require.Equal(t, "{StartKey:5f747878657932335f69323633 EndKey:}", buf.String())
}
85 changes: 30 additions & 55 deletions util/logutil/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,82 +15,57 @@ package logutil

import (
"bufio"
"bytes"
"context"
"io"
"os"
"runtime"
"strings"
"testing"

. "github.com/pingcap/check"
"github.com/pingcap/log"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)

const (
// zapLogPatern is used to match the zap log format, such as the following log:
// [2019/02/13 15:56:05.385 +08:00] [INFO] [log_test.go:167] ["info message"] [conn=conn1] ["str key"=val] ["int key"=123]
zapLogWithConnIDPattern = `\[\d\d\d\d/\d\d/\d\d \d\d:\d\d:\d\d.\d\d\d\ (\+|-)\d\d:\d\d\] \[(FATAL|ERROR|WARN|INFO|DEBUG)\] \[([\w_%!$@.,+~-]+|\\.)+:\d+\] \[.*\] \[conn=.*\] (\[.*=.*\]).*\n`
// [2019/02/13 15:56:05.385 +08:00] [INFO] [log_test.go:167] ["info message"] [ctxKey=ctxKey1] ["str key"=val] ["int key"=123]
zapLogWithKeyValPattern = `\[\d\d\d\d/\d\d/\d\d \d\d:\d\d:\d\d.\d\d\d\ (\+|-)\d\d:\d\d\] \[(FATAL|ERROR|WARN|INFO|DEBUG)\] \[([\w_%!$@.,+~-]+|\\.)+:\d+\] \[.*\] \[ctxKey=.*\] (\[.*=.*\]).*\n`
)

var PrettyPrint = prettyPrint

func Test(t *testing.T) {
TestingT(t)
}

var _ = Suite(&testLogSuite{})

type testLogSuite struct {
buf *bytes.Buffer
}

func (s *testLogSuite) SetUpSuite(_ *C) {
s.buf = &bytes.Buffer{}
}

func (s *testLogSuite) SetUpTest(_ *C) {
s.buf = &bytes.Buffer{}
}

func (s *testLogSuite) TestZapLoggerWithKeys(c *C) {
func TestZapLoggerWithKeys(t *testing.T) {
if runtime.GOOS == "windows" {
// Skip this test on windows for two reason:
// 1. The pattern match fails somehow. It seems windows treat \n as slash and character n.
// 2. Remove file doesn't work as long as the log instance hold the file.
c.Skip("skip on windows")
t.Skip("skip on windows")
}

fileCfg := FileLogConfig{log.FileLogConfig{Filename: "zap_log", MaxSize: 4096}}
conf := NewLogConfig("info", DefaultLogFormat, "", fileCfg, false)
err := InitZapLogger(conf)
c.Assert(err, IsNil)
require.NoError(t, err)
connID := uint64(123)
ctx := WithConnID(context.Background(), connID)
s.testZapLogger(ctx, c, fileCfg.Filename, zapLogWithConnIDPattern)
os.Remove(fileCfg.Filename)
testZapLogger(ctx, t, fileCfg.Filename, zapLogWithConnIDPattern)
err = os.Remove(fileCfg.Filename)
require.NoError(t, err)

err = InitZapLogger(conf)
c.Assert(err, IsNil)
require.NoError(t, err)
key := "ctxKey"
val := "ctxValue"
ctx1 := WithKeyValue(context.Background(), key, val)
s.testZapLogger(ctx1, c, fileCfg.Filename, zapLogWithKeyValPattern)
os.Remove(fileCfg.Filename)
testZapLogger(ctx1, t, fileCfg.Filename, zapLogWithKeyValPattern)
err = os.Remove(fileCfg.Filename)
require.NoError(t, err)
}

func (s *testLogSuite) testZapLogger(ctx context.Context, c *C, fileName, pattern string) {
func testZapLogger(ctx context.Context, t *testing.T, fileName, pattern string) {
Logger(ctx).Debug("debug msg", zap.String("test with key", "true"))
Logger(ctx).Info("info msg", zap.String("test with key", "true"))
Logger(ctx).Warn("warn msg", zap.String("test with key", "true"))
Logger(ctx).Error("error msg", zap.String("test with key", "true"))

f, err := os.Open(fileName)
c.Assert(err, IsNil)
defer f.Close()
require.NoError(t, err)
defer func() {
err = f.Close()
require.NoError(t, err)
}()

r := bufio.NewReader(f)
for {
Expand All @@ -99,26 +74,26 @@ func (s *testLogSuite) testZapLogger(ctx context.Context, c *C, fileName, patter
if err != nil {
break
}
c.Assert(str, Matches, pattern)
c.Assert(strings.Contains(str, "stack"), IsFalse)
c.Assert(strings.Contains(str, "errorVerbose"), IsFalse)
require.Regexp(t, pattern, str)
require.NotContains(t, str, "stack")
require.NotContains(t, str, "errorVerbose")
}
c.Assert(err, Equals, io.EOF)
require.Equal(t, io.EOF, err)
}

func (s *testLogSuite) TestSetLevel(c *C) {
func TestSetLevel(t *testing.T) {
conf := NewLogConfig("info", DefaultLogFormat, "", EmptyFileLogConfig, false)
err := InitZapLogger(conf)
c.Assert(err, IsNil)
require.NoError(t, err)
require.Equal(t, zap.InfoLevel, log.GetLevel())

c.Assert(log.GetLevel(), Equals, zap.InfoLevel)
err = SetLevel("warn")
c.Assert(err, IsNil)
c.Assert(log.GetLevel(), Equals, zap.WarnLevel)
require.NoError(t, err)
require.Equal(t, zap.WarnLevel, log.GetLevel())
err = SetLevel("Error")
c.Assert(err, IsNil)
c.Assert(log.GetLevel(), Equals, zap.ErrorLevel)
require.NoError(t, err)
require.Equal(t, zap.ErrorLevel, log.GetLevel())
err = SetLevel("DEBUG")
c.Assert(err, IsNil)
c.Assert(log.GetLevel(), Equals, zap.DebugLevel)
require.NoError(t, err)
require.Equal(t, zap.DebugLevel, log.GetLevel())
}
41 changes: 41 additions & 0 deletions util/logutil/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package logutil

import (
"testing"

"github.com/pingcap/tidb/util/testbridge"
"go.uber.org/goleak"
)

const (
// zapLogPatern is used to match the zap log format, such as the following log:
// [2019/02/13 15:56:05.385 +08:00] [INFO] [log_test.go:167] ["info message"] [conn=conn1] ["str key"=val] ["int key"=123]
zapLogWithConnIDPattern = `\[\d\d\d\d/\d\d/\d\d \d\d:\d\d:\d\d.\d\d\d\ (\+|-)\d\d:\d\d\] \[(FATAL|ERROR|WARN|INFO|DEBUG)\] \[([\w_%!$@.,+~-]+|\\.)+:\d+\] \[.*\] \[conn=.*\] (\[.*=.*\]).*\n`
// [2019/02/13 15:56:05.385 +08:00] [INFO] [log_test.go:167] ["info message"] [ctxKey=ctxKey1] ["str key"=val] ["int key"=123]
zapLogWithKeyValPattern = `\[\d\d\d\d/\d\d/\d\d \d\d:\d\d:\d\d.\d\d\d\ (\+|-)\d\d:\d\d\] \[(FATAL|ERROR|WARN|INFO|DEBUG)\] \[([\w_%!$@.,+~-]+|\\.)+:\d+\] \[.*\] \[ctxKey=.*\] (\[.*=.*\]).*\n`
)

var (
PrettyPrint = prettyPrint
)

func TestMain(m *testing.M) {
testbridge.WorkaroundGoCheckFlags()
opts := []goleak.Option{
goleak.IgnoreTopFunction("gopkg.in/natefinch/lumberjack%2ev2.(*Logger).millRun"),
}
goleak.VerifyTestMain(m, opts...)
}

0 comments on commit 51b88fe

Please sign in to comment.