Skip to content

Commit b84e4b9

Browse files
committed
Improve locking
1 parent e8f286b commit b84e4b9

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

plugins/outputs/heartbeat/heartbeat_test.go

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1117,7 +1117,9 @@ func TestDetailedLogging(t *testing.T) {
11171117
expected := replacer.Replace(tt.expected)
11181118

11191119
// Create a test server to validate the data sent
1120-
var actual string
1120+
var receivedMessage string
1121+
var receivedMu sync.Mutex
1122+
var snapshot atomic.Bool
11211123
var done atomic.Bool
11221124
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
11231125
if r.Method != http.MethodPost {
@@ -1126,13 +1128,17 @@ func TestDetailedLogging(t *testing.T) {
11261128
}
11271129

11281130
// Decode the body
1129-
body, err := io.ReadAll(r.Body)
1130-
if err != nil {
1131-
t.Fail()
1132-
w.WriteHeader(http.StatusInternalServerError)
1131+
if snapshot.Swap(false) {
1132+
body, err := io.ReadAll(r.Body)
1133+
if err != nil {
1134+
t.Fail()
1135+
w.WriteHeader(http.StatusInternalServerError)
1136+
}
1137+
receivedMu.Lock()
1138+
receivedMessage = string(body)
1139+
receivedMu.Unlock()
1140+
done.Store(true)
11331141
}
1134-
actual = string(body)
1135-
done.Store(true)
11361142
w.WriteHeader(http.StatusOK)
11371143
}))
11381144
defer ts.Close()
@@ -1144,7 +1150,7 @@ func TestDetailedLogging(t *testing.T) {
11441150
plugin := &Heartbeat{
11451151
URL: u,
11461152
InstanceID: "telegraf",
1147-
Interval: config.Duration(time.Second),
1153+
Interval: config.Duration(100 * time.Millisecond),
11481154
Include: []string{"log-details"},
11491155
Logs: tt.logcfg,
11501156
Log: &testutil.Logger{},
@@ -1175,6 +1181,7 @@ func TestDetailedLogging(t *testing.T) {
11751181
}
11761182

11771183
// Start processing
1184+
snapshot.Store(true)
11781185
require.NoError(t, plugin.Connect())
11791186
defer plugin.Close()
11801187

@@ -1183,6 +1190,10 @@ func TestDetailedLogging(t *testing.T) {
11831190
require.Eventually(t, func() bool {
11841191
return done.Load()
11851192
}, 3*time.Second, 100*time.Millisecond)
1193+
1194+
receivedMu.Lock()
1195+
actual := receivedMessage
1196+
receivedMu.Unlock()
11861197
require.JSONEq(t, expected, actual, actual)
11871198
})
11881199
}

0 commit comments

Comments
 (0)