Skip to content

Commit a672da2

Browse files
committed
fix: resolve race conditions in monitor tests
1 parent 3dd3172 commit a672da2

1 file changed

Lines changed: 13 additions & 10 deletions

File tree

tests/monitor_test.go

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"os"
66
"path/filepath"
7+
"sync/atomic"
78
"testing"
89
"time"
910

@@ -128,10 +129,10 @@ SELECT * FROM inventory WHERE id = 5
128129
func TestLogProcessor(t *testing.T) {
129130
processor := monitor.NewLogProcessor("mysql")
130131

131-
// Track processed queries
132-
processedCount := 0
132+
// Track processed queries (atomic to avoid race conditions)
133+
var processedCount int64
133134
processor.SetQueryHandler(func(pq *monitor.ProcessedQuery) {
134-
processedCount++
135+
atomic.AddInt64(&processedCount, 1)
135136
if pq.Query == "" {
136137
t.Error("Processed query should not be empty")
137138
}
@@ -167,8 +168,9 @@ func TestLogProcessor(t *testing.T) {
167168
time.Sleep(500 * time.Millisecond)
168169

169170
// Should have processed the queries (some may fail to parse due to incomplete SQL)
170-
if processedCount < 4 {
171-
t.Errorf("Expected at least 4 processed queries, got %d", processedCount)
171+
count := atomic.LoadInt64(&processedCount)
172+
if count < 4 {
173+
t.Errorf("Expected at least 4 processed queries, got %d", count)
172174
}
173175

174176
// Check statistics - total lines should include all processed queries
@@ -361,11 +363,11 @@ func TestQueryExtraction(t *testing.T) {
361363

362364
for _, tc := range testCases {
363365
t.Run(tc.name, func(t *testing.T) {
364-
// Process the line
365-
queryExtracted := false
366+
// Process the line (use atomic int32 for thread-safe access)
367+
var queryExtracted int32
366368
processor.SetQueryHandler(func(pq *monitor.ProcessedQuery) {
367369
if pq.Query != "" {
368-
queryExtracted = true
370+
atomic.StoreInt32(&queryExtracted, 1)
369371
}
370372
})
371373

@@ -378,9 +380,10 @@ func TestQueryExtraction(t *testing.T) {
378380
lines <- tc.logLine
379381
time.Sleep(100 * time.Millisecond)
380382

381-
if queryExtracted != tc.expected {
383+
extracted := atomic.LoadInt32(&queryExtracted) == 1
384+
if extracted != tc.expected {
382385
t.Errorf("Query extraction mismatch: expected %v, got %v for line: %s",
383-
tc.expected, queryExtracted, tc.logLine)
386+
tc.expected, extracted, tc.logLine)
384387
}
385388

386389
cancel()

0 commit comments

Comments
 (0)