From 3733b06f1b62db2e40c5b9c7e809d2ff041dc22a Mon Sep 17 00:00:00 2001 From: kevin Date: Fri, 9 Oct 2020 14:15:27 +0800 Subject: [PATCH] fix data race in tests --- core/logx/logs_test.go | 18 ++++++++++++++++-- core/logx/tracelogger_test.go | 10 +++++----- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/core/logx/logs_test.go b/core/logx/logs_test.go index 69e1ae80..f5a37e23 100644 --- a/core/logx/logs_test.go +++ b/core/logx/logs_test.go @@ -9,6 +9,7 @@ import ( "os" "runtime" "strings" + "sync" "sync/atomic" "testing" "time" @@ -22,10 +23,13 @@ var ( ) type mockWriter struct { + lock sync.Mutex builder strings.Builder } func (mw *mockWriter) Write(data []byte) (int, error) { + mw.lock.Lock() + defer mw.lock.Unlock() return mw.builder.Write(data) } @@ -33,12 +37,22 @@ func (mw *mockWriter) Close() error { return nil } +func (mw *mockWriter) Contains(text string) bool { + mw.lock.Lock() + defer mw.lock.Unlock() + return strings.Contains(mw.builder.String(), text) +} + func (mw *mockWriter) Reset() { + mw.lock.Lock() + defer mw.lock.Unlock() mw.builder.Reset() } -func (mw *mockWriter) Contains(text string) bool { - return strings.Contains(mw.builder.String(), text) +func (mw *mockWriter) String() string { + mw.lock.Lock() + defer mw.lock.Unlock() + return mw.builder.String() } func TestFileLineFileMode(t *testing.T) { diff --git a/core/logx/tracelogger_test.go b/core/logx/tracelogger_test.go index 2c2640f9..9985cc66 100644 --- a/core/logx/tracelogger_test.go +++ b/core/logx/tracelogger_test.go @@ -19,7 +19,7 @@ const ( var mock tracespec.Trace = new(mockTrace) func TestTraceLog(t *testing.T) { - var buf strings.Builder + var buf mockWriter ctx := context.WithValue(context.Background(), tracespec.TracingKey, mock) WithContext(ctx).(*traceLogger).write(&buf, levelInfo, testlog) assert.True(t, strings.Contains(buf.String(), mockTraceId)) @@ -27,7 +27,7 @@ func TestTraceLog(t *testing.T) { } func TestTraceError(t *testing.T) { - var buf strings.Builder + var buf mockWriter ctx := context.WithValue(context.Background(), tracespec.TracingKey, mock) l := WithContext(ctx).(*traceLogger) SetLevel(InfoLevel) @@ -42,7 +42,7 @@ func TestTraceError(t *testing.T) { } func TestTraceInfo(t *testing.T) { - var buf strings.Builder + var buf mockWriter ctx := context.WithValue(context.Background(), tracespec.TracingKey, mock) l := WithContext(ctx).(*traceLogger) SetLevel(InfoLevel) @@ -57,7 +57,7 @@ func TestTraceInfo(t *testing.T) { } func TestTraceSlow(t *testing.T) { - var buf strings.Builder + var buf mockWriter ctx := context.WithValue(context.Background(), tracespec.TracingKey, mock) l := WithContext(ctx).(*traceLogger) SetLevel(InfoLevel) @@ -72,7 +72,7 @@ func TestTraceSlow(t *testing.T) { } func TestTraceWithoutContext(t *testing.T) { - var buf strings.Builder + var buf mockWriter l := WithContext(context.Background()).(*traceLogger) SetLevel(InfoLevel) infoLog = newLogWriter(log.New(&buf, "", flags))