fix: add mutex to mockLogger in errorbus tests to prevent race conditions
The mockLogger's errors slice was being accessed concurrently from multiple goroutines (the error bus consumer and the test goroutine), causing race conditions when running tests with the race detector. Added sync.Mutex to protect the errors slice and proper locking when accessing it in test assertions.
This commit is contained in:
@@ -3,6 +3,7 @@ package errorbus
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -61,7 +62,10 @@ func TestChannelBus_Publish(t *testing.T) {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
// Verify error was logged
|
||||
if len(mockLogger.errors) == 0 {
|
||||
mockLogger.mu.Lock()
|
||||
errorCount := len(mockLogger.errors)
|
||||
mockLogger.mu.Unlock()
|
||||
if errorCount == 0 {
|
||||
t.Error("Expected error to be logged")
|
||||
}
|
||||
|
||||
@@ -84,7 +88,10 @@ func TestChannelBus_Publish_NilError(t *testing.T) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
// Verify nil error was not logged
|
||||
if len(mockLogger.errors) > 0 {
|
||||
mockLogger.mu.Lock()
|
||||
errorCount := len(mockLogger.errors)
|
||||
mockLogger.mu.Unlock()
|
||||
if errorCount > 0 {
|
||||
t.Error("Expected nil error to be ignored")
|
||||
}
|
||||
|
||||
@@ -107,7 +114,10 @@ func TestChannelBus_Publish_WithContext(t *testing.T) {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
// Verify error was logged with context
|
||||
if len(mockLogger.errors) == 0 {
|
||||
mockLogger.mu.Lock()
|
||||
errorCount := len(mockLogger.errors)
|
||||
mockLogger.mu.Unlock()
|
||||
if errorCount == 0 {
|
||||
t.Error("Expected error to be logged")
|
||||
}
|
||||
|
||||
@@ -181,12 +191,15 @@ func TestChannelBus_ChannelFull(t *testing.T) {
|
||||
// mockLogger implements logger.Logger for testing.
|
||||
type mockLogger struct {
|
||||
errors []string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (m *mockLogger) Debug(msg string, fields ...logger.Field) {}
|
||||
func (m *mockLogger) Info(msg string, fields ...logger.Field) {}
|
||||
func (m *mockLogger) Warn(msg string, fields ...logger.Field) {}
|
||||
func (m *mockLogger) Error(msg string, fields ...logger.Field) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.errors = append(m.errors, msg)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user