Skip to content

Commit 44562eb

Browse files
authored
fix race condition in heartbeat unittest (#534)
1 parent f0b4ecd commit 44562eb

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

internal/topology/node_test.go

+9
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"errors"
66
"net/url"
7+
"sync"
78
"testing"
89
"time"
910

@@ -16,13 +17,16 @@ var _ heartbeat.HeartBeat = &mockHeartbeat{}
1617
type mockHeartbeat struct {
1718
interval time.Duration
1819
err error
20+
mu sync.Mutex
1921
}
2022

2123
func (hb *mockHeartbeat) Interval() time.Duration {
2224
return hb.interval
2325
}
2426

2527
func (hb *mockHeartbeat) IsHealthy(ctx context.Context, addr string) error {
28+
hb.mu.Lock()
29+
defer hb.mu.Unlock()
2630
return hb.err
2731
}
2832

@@ -54,6 +58,7 @@ func TestStartHeartbeat(t *testing.T) {
5458
hb := &mockHeartbeat{
5559
interval: 10 * time.Millisecond,
5660
err: nil,
61+
mu: sync.Mutex{},
5762
}
5863

5964
done := make(chan struct{})
@@ -69,14 +74,18 @@ func TestStartHeartbeat(t *testing.T) {
6974
}, time.Second, 100*time.Millisecond)
7075

7176
// change heartbeat to error, node eventually becomes inactive.
77+
hb.mu.Lock()
7278
hb.err = errors.New("failed connection")
79+
hb.mu.Unlock()
7380

7481
assert.Eventually(t, func() bool {
7582
return !node.IsActive()
7683
}, time.Second, 100*time.Millisecond)
7784

7885
// If error is removed node becomes active again.
86+
hb.mu.Lock()
7987
hb.err = nil
88+
hb.mu.Unlock()
8089

8190
assert.Eventually(t, func() bool {
8291
return node.IsActive()

0 commit comments

Comments
 (0)