@@ -11,6 +11,8 @@ import (
11
11
"net"
12
12
"os"
13
13
"runtime"
14
+ "sync"
15
+ "sync/atomic"
14
16
"testing"
15
17
"time"
16
18
@@ -237,4 +239,45 @@ func TestServerHeartbeatStartedEvent(t *testing.T) {
237
239
}
238
240
assert .Equal (t , expectedEvents , actualEvents )
239
241
})
242
+
243
+ mt := mtest .New (t )
244
+
245
+ mt .Run ("polling must await frequency" , func (mt * mtest.T ) {
246
+ var heartbeatStartedCount atomic.Int64
247
+
248
+ servers := map [string ]bool {}
249
+ serversMu := sync.RWMutex {} // Guard the servers set
250
+
251
+ serverMonitor := & event.ServerMonitor {
252
+ ServerHeartbeatStarted : func (* event.ServerHeartbeatStartedEvent ) {
253
+ heartbeatStartedCount .Add (1 )
254
+ },
255
+ TopologyDescriptionChanged : func (evt * event.TopologyDescriptionChangedEvent ) {
256
+ serversMu .Lock ()
257
+ defer serversMu .Unlock ()
258
+
259
+ for _ , srv := range evt .NewDescription .Servers {
260
+ servers [srv .Addr .String ()] = true
261
+ }
262
+ },
263
+ }
264
+
265
+ // Create a client with heartbeatFrequency=100ms,
266
+ // serverMonitoringMode=poll. Use SDAM to record the number of times the
267
+ // a heartbeat is started and the number of servers discovered.
268
+ mt .ResetClient (options .Client ().
269
+ SetServerMonitor (serverMonitor ).
270
+ SetServerMonitoringMode (options .ServerMonitoringModePoll ))
271
+
272
+ // Per specifications, minHeartbeatFrequencyMS=500ms. So, within the first
273
+ // 500ms the heartbeatStartedCount should be LEQ to the number of discovered
274
+ // servers.
275
+ time .Sleep (500 * time .Millisecond )
276
+
277
+ serversMu .Lock ()
278
+ serverCount := int64 (len (servers ))
279
+ serversMu .Unlock ()
280
+
281
+ assert .LessOrEqual (mt , heartbeatStartedCount .Load (), serverCount )
282
+ })
240
283
}
0 commit comments