Skip to content

Commit 3b61818

Browse files
committed
fix(audit): resolve race condition in audit middleware test
1 parent 1f4916a commit 3b61818

1 file changed

Lines changed: 25 additions & 3 deletions

File tree

pkg/middleware/audit_test.go

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"net/http"
66
"net/http/httptest"
7+
"sync"
78
"testing"
89
"time"
910

@@ -13,22 +14,42 @@ import (
1314
)
1415

1516
type mockAuditLogger struct {
17+
mu sync.Mutex
1618
entries []*audit.AuditLogEntry
1719
}
1820

1921
func (m *mockAuditLogger) Log(ctx context.Context, entry *audit.AuditLogEntry) error {
22+
m.mu.Lock()
23+
defer m.mu.Unlock()
2024
m.entries = append(m.entries, entry)
2125
return nil
2226
}
2327

2428
func (m *mockAuditLogger) Query(ctx context.Context, filter audit.AuditLogFilter) ([]*audit.AuditLogEntry, error) {
29+
m.mu.Lock()
30+
defer m.mu.Unlock()
2531
return m.entries, nil
2632
}
2733

2834
func (m *mockAuditLogger) Close() error {
2935
return nil
3036
}
3137

38+
func (m *mockAuditLogger) getEntriesCount() int {
39+
m.mu.Lock()
40+
defer m.mu.Unlock()
41+
return len(m.entries)
42+
}
43+
44+
func (m *mockAuditLogger) getEntry(index int) *audit.AuditLogEntry {
45+
m.mu.Lock()
46+
defer m.mu.Unlock()
47+
if index < len(m.entries) {
48+
return m.entries[index]
49+
}
50+
return nil
51+
}
52+
3253
func TestAuditMiddleware(t *testing.T) {
3354
t.Run("audits API request", func(t *testing.T) {
3455
mockLogger := &mockAuditLogger{}
@@ -47,10 +68,10 @@ func TestAuditMiddleware(t *testing.T) {
4768

4869
// Wait for async audit logging to complete
4970
assert.Eventually(t, func() bool {
50-
return len(mockLogger.entries) == 1
71+
return mockLogger.getEntriesCount() == 1
5172
}, 100*time.Millisecond, 10*time.Millisecond, "audit entry should be logged")
5273

53-
entry := mockLogger.entries[0]
74+
entry := mockLogger.getEntry(0)
5475
assert.Equal(t, audit.EventAPIRequest, entry.EventType)
5576
assert.Equal(t, audit.CategoryWorkflow, entry.EventCategory)
5677
assert.Equal(t, audit.ResultSuccess, entry.Result)
@@ -71,7 +92,8 @@ func TestAuditMiddleware(t *testing.T) {
7192
handler.ServeHTTP(w, req)
7293

7394
assert.Equal(t, 200, w.Code)
74-
assert.Len(t, mockLogger.entries, 0) // No audit entry
95+
time.Sleep(50 * time.Millisecond) // Wait for async processing
96+
assert.Equal(t, 0, mockLogger.getEntriesCount()) // No audit entry
7597
})
7698

7799
t.Run("categorizes paths correctly", func(t *testing.T) {

0 commit comments

Comments
 (0)